OSDN Git Service

Use _() macro consistently rather than gettext(). Add translation
[pg-rex/syncrep.git] / src / backend / utils / error / elog.c
1 /*-------------------------------------------------------------------------
2  *
3  * elog.c
4  *        error logging and reporting
5  *
6  * Some notes about recursion and errors during error processing:
7  *
8  * We need to be robust about recursive-error scenarios --- for example,
9  * if we run out of memory, it's important to be able to report that fact.
10  * There are a number of considerations that go into this.
11  *
12  * First, distinguish between re-entrant use and actual recursion.      It
13  * is possible for an error or warning message to be emitted while the
14  * parameters for an error message are being computed.  In this case
15  * errstart has been called for the outer message, and some field values
16  * may have already been saved, but we are not actually recursing.      We handle
17  * this by providing a (small) stack of ErrorData records.      The inner message
18  * can be computed and sent without disturbing the state of the outer message.
19  * (If the inner message is actually an error, this isn't very interesting
20  * because control won't come back to the outer message generator ... but
21  * if the inner message is only debug or log data, this is critical.)
22  *
23  * Second, actual recursion will occur if an error is reported by one of
24  * the elog.c routines or something they call.  By far the most probable
25  * scenario of this sort is "out of memory"; and it's also the nastiest
26  * to handle because we'd likely also run out of memory while trying to
27  * report this error!  Our escape hatch for this case is to reset the
28  * ErrorContext to empty before trying to process the inner error.  Since
29  * ErrorContext is guaranteed to have at least 8K of space in it (see mcxt.c),
30  * we should be able to process an "out of memory" message successfully.
31  * Since we lose the prior error state due to the reset, we won't be able
32  * to return to processing the original error, but we wouldn't have anyway.
33  * (NOTE: the escape hatch is not used for recursive situations where the
34  * inner message is of less than ERROR severity; in that case we just
35  * try to process it and return normally.  Usually this will work, but if
36  * it ends up in infinite recursion, we will PANIC due to error stack
37  * overflow.)
38  *
39  *
40  * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
41  * Portions Copyright (c) 1994, Regents of the University of California
42  *
43  *
44  * IDENTIFICATION
45  *        $PostgreSQL: pgsql/src/backend/utils/error/elog.c,v 1.156 2005/02/22 04:37:38 momjian Exp $
46  *
47  *-------------------------------------------------------------------------
48  */
49 #include "postgres.h"
50
51 #include <fcntl.h>
52 #include <time.h>
53 #include <unistd.h>
54 #include <signal.h>
55 #include <ctype.h>
56 #ifdef HAVE_SYSLOG
57 #include <syslog.h>
58 #endif
59
60 #include "libpq/libpq.h"
61 #include "libpq/pqformat.h"
62 #include "mb/pg_wchar.h"
63 #include "miscadmin.h"
64 #include "postmaster/postmaster.h"
65 #include "postmaster/syslogger.h"
66 #include "storage/ipc.h"
67 #include "tcop/tcopprot.h"
68 #include "utils/memutils.h"
69 #include "utils/guc.h"
70
71
72 /* Global variables */
73 ErrorContextCallback *error_context_stack = NULL;
74
75 sigjmp_buf *PG_exception_stack = NULL;
76
77 /* GUC parameters */
78 PGErrorVerbosity Log_error_verbosity = PGERROR_VERBOSE;
79 char       *Log_line_prefix = NULL;             /* format for extra log line info */
80 int                     Log_destination = LOG_DESTINATION_STDERR;
81
82 #ifdef HAVE_SYSLOG
83 char       *Syslog_facility;    /* openlog() parameters */
84 char       *Syslog_ident;
85
86 static void write_syslog(int level, const char *line);
87 #endif
88 #ifdef WIN32
89 static void write_eventlog(int level, const char *line);
90 #endif
91
92 /* We provide a small stack of ErrorData records for re-entrant cases */
93 #define ERRORDATA_STACK_SIZE  5
94
95 static ErrorData errordata[ERRORDATA_STACK_SIZE];
96
97 static int      errordata_stack_depth = -1; /* index of topmost active frame */
98
99 static int      recursion_depth = 0;    /* to detect actual recursion */
100
101
102 /* Macro for checking errordata_stack_depth is reasonable */
103 #define CHECK_STACK_DEPTH() \
104         do { \
105                 if (errordata_stack_depth < 0) \
106                 { \
107                         errordata_stack_depth = -1; \
108                         ereport(ERROR, (errmsg_internal("errstart was not called"))); \
109                 } \
110         } while (0)
111
112
113 static void log_line_prefix(StringInfo buf);
114 static void send_message_to_server_log(ErrorData *edata);
115 static void send_message_to_frontend(ErrorData *edata);
116 static char *expand_fmt_string(const char *fmt, ErrorData *edata);
117 static const char *useful_strerror(int errnum);
118 static const char *error_severity(int elevel);
119 static void append_with_tabs(StringInfo buf, const char *str);
120
121
122 /*
123  * errstart --- begin an error-reporting cycle
124  *
125  * Create a stack entry and store the given parameters in it.  Subsequently,
126  * errmsg() and perhaps other routines will be called to further populate
127  * the stack entry.  Finally, errfinish() will be called to actually process
128  * the error report.
129  *
130  * Returns TRUE in normal case.  Returns FALSE to short-circuit the error
131  * report (if it's a warning or lower and not to be reported anywhere).
132  */
133 bool
134 errstart(int elevel, const char *filename, int lineno,
135                  const char *funcname)
136 {
137         ErrorData  *edata;
138         bool            output_to_server = false;
139         bool            output_to_client = false;
140         int                     i;
141
142         /*
143          * Check some cases in which we want to promote an error into a more
144          * severe error.  None of this logic applies for non-error messages.
145          */
146         if (elevel >= ERROR)
147         {
148                 /*
149                  * If we are inside a critical section, all errors become PANIC
150                  * errors.      See miscadmin.h.
151                  */
152                 if (CritSectionCount > 0)
153                         elevel = PANIC;
154
155                 /*
156                  * Check reasons for treating ERROR as FATAL:
157                  *
158                  * 1. we have no handler to pass the error to (implies we are in the
159                  * postmaster or in backend startup).
160                  *
161                  * 2. ExitOnAnyError mode switch is set (initdb uses this).
162                  *
163                  * 3. the error occurred after proc_exit has begun to run.      (It's
164                  * proc_exit's responsibility to see that this doesn't turn into
165                  * infinite recursion!)
166                  */
167                 if (elevel == ERROR)
168                 {
169                         if (PG_exception_stack == NULL ||
170                                 ExitOnAnyError ||
171                                 proc_exit_inprogress)
172                                 elevel = FATAL;
173                 }
174
175                 /*
176                  * If the error level is ERROR or more, errfinish is not going to
177                  * return to caller; therefore, if there is any stacked error already
178                  * in progress it will be lost.  This is more or less okay, except we
179                  * do not want to have a FATAL or PANIC error downgraded because the
180                  * reporting process was interrupted by a lower-grade error.  So check
181                  * the stack and make sure we panic if panic is warranted.
182                  */
183                 for (i = 0; i <= errordata_stack_depth; i++)
184                         elevel = Max(elevel, errordata[i].elevel);
185         }
186
187         /*
188          * Now decide whether we need to process this report at all; if it's
189          * warning or less and not enabled for logging, just return FALSE
190          * without starting up any error logging machinery.
191          */
192
193         /* Determine whether message is enabled for server log output */
194         if (IsPostmasterEnvironment)
195         {
196                 /* Complicated because LOG is sorted out-of-order for this purpose */
197                 if (elevel == LOG || elevel == COMMERROR)
198                 {
199                         if (log_min_messages == LOG)
200                                 output_to_server = true;
201                         else if (log_min_messages < FATAL)
202                                 output_to_server = true;
203                 }
204                 else
205                 {
206                         /* elevel != LOG */
207                         if (log_min_messages == LOG)
208                         {
209                                 if (elevel >= FATAL)
210                                         output_to_server = true;
211                         }
212                         /* Neither is LOG */
213                         else if (elevel >= log_min_messages)
214                                 output_to_server = true;
215                 }
216         }
217         else
218         {
219                 /* In bootstrap/standalone case, do not sort LOG out-of-order */
220                 output_to_server = (elevel >= log_min_messages);
221         }
222
223         /* Determine whether message is enabled for client output */
224         if (whereToSendOutput == Remote && elevel != COMMERROR)
225         {
226                 /*
227                  * client_min_messages is honored only after we complete the
228                  * authentication handshake.  This is required both for security
229                  * reasons and because many clients can't handle NOTICE messages
230                  * during authentication.
231                  */
232                 if (ClientAuthInProgress)
233                         output_to_client = (elevel >= ERROR);
234                 else
235                         output_to_client = (elevel >= client_min_messages ||
236                                                                 elevel == INFO);
237         }
238
239         /* Skip processing effort if non-error message will not be output */
240         if (elevel < ERROR && !output_to_server && !output_to_client)
241                 return false;
242
243         /*
244          * Okay, crank up a stack entry to store the info in.
245          */
246
247         if (recursion_depth++ > 0 && elevel >= ERROR)
248         {
249                 /*
250                  * Ooops, error during error processing.  Clear ErrorContext as
251                  * discussed at top of file.  We will not return to the original
252                  * error's reporter or handler, so we don't need it.
253                  */
254                 MemoryContextReset(ErrorContext);
255
256                 /*
257                  * If we recurse more than once, the problem might be something
258                  * broken in a context traceback routine.  Abandon them too.
259                  */
260                 if (recursion_depth > 2)
261                         error_context_stack = NULL;
262         }
263         if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
264         {
265                 /*
266                  * Wups, stack not big enough.  We treat this as a PANIC condition
267                  * because it suggests an infinite loop of errors during error
268                  * recovery.
269                  */
270                 errordata_stack_depth = -1;             /* make room on stack */
271                 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
272         }
273
274         /* Initialize data for this error frame */
275         edata = &errordata[errordata_stack_depth];
276         MemSet(edata, 0, sizeof(ErrorData));
277         edata->elevel = elevel;
278         edata->output_to_server = output_to_server;
279         edata->output_to_client = output_to_client;
280         edata->filename = filename;
281         edata->lineno = lineno;
282         edata->funcname = funcname;
283         /* Select default errcode based on elevel */
284         if (elevel >= ERROR)
285                 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
286         else if (elevel == WARNING)
287                 edata->sqlerrcode = ERRCODE_WARNING;
288         else
289                 edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
290         /* errno is saved here so that error parameter eval can't change it */
291         edata->saved_errno = errno;
292
293         recursion_depth--;
294         return true;
295 }
296
297 /*
298  * errfinish --- end an error-reporting cycle
299  *
300  * Produce the appropriate error report(s) and pop the error stack.
301  *
302  * If elevel is ERROR or worse, control does not return to the caller.
303  * See elog.h for the error level definitions.
304  */
305 void
306 errfinish(int dummy,...)
307 {
308         ErrorData  *edata = &errordata[errordata_stack_depth];
309         int                     elevel = edata->elevel;
310         MemoryContext oldcontext;
311         ErrorContextCallback *econtext;
312
313         recursion_depth++;
314         CHECK_STACK_DEPTH();
315
316         /*
317          * Do processing in ErrorContext, which we hope has enough reserved
318          * space to report an error.
319          */
320         oldcontext = MemoryContextSwitchTo(ErrorContext);
321
322         /*
323          * Call any context callback functions.  Errors occurring in callback
324          * functions will be treated as recursive errors --- this ensures we
325          * will avoid infinite recursion (see errstart).
326          */
327         for (econtext = error_context_stack;
328                  econtext != NULL;
329                  econtext = econtext->previous)
330                 (*econtext->callback) (econtext->arg);
331
332         /*
333          * If ERROR (not more nor less) we pass it off to the current handler.
334          * Printing it and popping the stack is the responsibility of
335          * the handler.
336          */
337         if (elevel == ERROR)
338         {
339                 /*
340                  * We do some minimal cleanup before longjmp'ing so that handlers
341                  * can execute in a reasonably sane state.
342                  */
343
344                 /* This is just in case the error came while waiting for input */
345                 ImmediateInterruptOK = false;
346
347                 /*
348                  * Reset InterruptHoldoffCount in case we ereport'd from
349                  * inside an interrupt holdoff section.  (We assume here that
350                  * no handler will itself be inside a holdoff section.  If
351                  * necessary, such a handler could save and restore
352                  * InterruptHoldoffCount for itself, but this should make life
353                  * easier for most.)
354                  */
355                 InterruptHoldoffCount = 0;
356
357                 CritSectionCount = 0;           /* should be unnecessary, but... */
358
359                 /*
360                  * Note that we leave CurrentMemoryContext set to ErrorContext.
361                  * The handler should reset it to something else soon.
362                  */
363
364                 recursion_depth--;
365                 PG_RE_THROW();
366         }
367
368         /*
369          * If we are doing FATAL or PANIC, abort any old-style COPY OUT in
370          * progress, so that we can report the message before dying.  (Without
371          * this, pq_putmessage will refuse to send the message at all, which
372          * is what we want for NOTICE messages, but not for fatal exits.) This
373          * hack is necessary because of poor design of old-style copy
374          * protocol.  Note we must do this even if client is fool enough to
375          * have set client_min_messages above FATAL, so don't look at
376          * output_to_client.
377          */
378         if (elevel >= FATAL && whereToSendOutput == Remote)
379                 pq_endcopyout(true);
380
381         /* Emit the message to the right places */
382         EmitErrorReport();
383
384         /* Now free up subsidiary data attached to stack entry, and release it */
385         if (edata->message)
386                 pfree(edata->message);
387         if (edata->detail)
388                 pfree(edata->detail);
389         if (edata->hint)
390                 pfree(edata->hint);
391         if (edata->context)
392                 pfree(edata->context);
393         if (edata->internalquery)
394                 pfree(edata->internalquery);
395
396         errordata_stack_depth--;
397
398         /* Exit error-handling context */
399         MemoryContextSwitchTo(oldcontext);
400         recursion_depth--;
401
402         /*
403          * Perform error recovery action as specified by elevel.
404          */
405         if (elevel == FATAL)
406         {
407                 /*
408                  * For a FATAL error, we let proc_exit clean up and exit.
409                  */
410                 ImmediateInterruptOK = false;
411
412                 /*
413                  * If we just reported a startup failure, the client will
414                  * disconnect on receiving it, so don't send any more to the
415                  * client.
416                  */
417                 if (PG_exception_stack == NULL && whereToSendOutput == Remote)
418                         whereToSendOutput = None;
419
420                 /*
421                  * fflush here is just to improve the odds that we get to see the
422                  * error message, in case things are so hosed that proc_exit
423                  * crashes.  Any other code you might be tempted to add here
424                  * should probably be in an on_proc_exit callback instead.
425                  */
426                 fflush(stdout);
427                 fflush(stderr);
428
429                 /*
430                  * If proc_exit is already running, we exit with nonzero exit code
431                  * to indicate that something's pretty wrong.  We also want to
432                  * exit with nonzero exit code if not running under the postmaster
433                  * (for example, if we are being run from the initdb script, we'd
434                  * better return an error status).
435                  */
436                 proc_exit(proc_exit_inprogress || !IsUnderPostmaster);
437         }
438
439         if (elevel >= PANIC)
440         {
441                 /*
442                  * Serious crash time. Postmaster will observe nonzero process
443                  * exit status and kill the other backends too.
444                  *
445                  * XXX: what if we are *in* the postmaster?  abort() won't kill our
446                  * children...
447                  */
448                 ImmediateInterruptOK = false;
449                 fflush(stdout);
450                 fflush(stderr);
451                 abort();
452         }
453
454         /* We reach here if elevel <= WARNING. OK to return to caller. */
455 }
456
457
458 /*
459  * errcode --- add SQLSTATE error code to the current error
460  *
461  * The code is expected to be represented as per MAKE_SQLSTATE().
462  */
463 int
464 errcode(int sqlerrcode)
465 {
466         ErrorData  *edata = &errordata[errordata_stack_depth];
467
468         /* we don't bother incrementing recursion_depth */
469         CHECK_STACK_DEPTH();
470
471         edata->sqlerrcode = sqlerrcode;
472
473         return 0;                                       /* return value does not matter */
474 }
475
476
477 /*
478  * errcode_for_file_access --- add SQLSTATE error code to the current error
479  *
480  * The SQLSTATE code is chosen based on the saved errno value.  We assume
481  * that the failing operation was some type of disk file access.
482  *
483  * NOTE: the primary error message string should generally include %m
484  * when this is used.
485  */
486 int
487 errcode_for_file_access(void)
488 {
489         ErrorData  *edata = &errordata[errordata_stack_depth];
490
491         /* we don't bother incrementing recursion_depth */
492         CHECK_STACK_DEPTH();
493
494         switch (edata->saved_errno)
495         {
496                         /* Permission-denied failures */
497                 case EPERM:                             /* Not super-user */
498                 case EACCES:                    /* Permission denied */
499 #ifdef EROFS
500                 case EROFS:                             /* Read only file system */
501 #endif
502                         edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
503                         break;
504
505                         /* File not found */
506                 case ENOENT:                    /* No such file or directory */
507                         edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
508                         break;
509
510                         /* Duplicate file */
511                 case EEXIST:                    /* File exists */
512                         edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
513                         break;
514
515                         /* Wrong object type or state */
516                 case ENOTDIR:                   /* Not a directory */
517                 case EISDIR:                    /* Is a directory */
518 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
519                 case ENOTEMPTY: /* Directory not empty */
520 #endif
521                         edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
522                         break;
523
524                         /* Insufficient resources */
525                 case ENOSPC:                    /* No space left on device */
526                         edata->sqlerrcode = ERRCODE_DISK_FULL;
527                         break;
528
529                 case ENFILE:                    /* File table overflow */
530                 case EMFILE:                    /* Too many open files */
531                         edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
532                         break;
533
534                         /* Hardware failure */
535                 case EIO:                               /* I/O error */
536                         edata->sqlerrcode = ERRCODE_IO_ERROR;
537                         break;
538
539                         /* All else is classified as internal errors */
540                 default:
541                         edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
542                         break;
543         }
544
545         return 0;                                       /* return value does not matter */
546 }
547
548 /*
549  * errcode_for_socket_access --- add SQLSTATE error code to the current error
550  *
551  * The SQLSTATE code is chosen based on the saved errno value.  We assume
552  * that the failing operation was some type of socket access.
553  *
554  * NOTE: the primary error message string should generally include %m
555  * when this is used.
556  */
557 int
558 errcode_for_socket_access(void)
559 {
560         ErrorData  *edata = &errordata[errordata_stack_depth];
561
562         /* we don't bother incrementing recursion_depth */
563         CHECK_STACK_DEPTH();
564
565         switch (edata->saved_errno)
566         {
567                         /* Loss of connection */
568                 case EPIPE:
569 #ifdef ECONNRESET
570                 case ECONNRESET:
571 #endif
572                         edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
573                         break;
574
575                         /* All else is classified as internal errors */
576                 default:
577                         edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
578                         break;
579         }
580
581         return 0;                                       /* return value does not matter */
582 }
583
584
585 /*
586  * This macro handles expansion of a format string and associated parameters;
587  * it's common code for errmsg(), errdetail(), etc.  Must be called inside
588  * a routine that is declared like "const char *fmt, ..." and has an edata
589  * pointer set up.      The message is assigned to edata->targetfield, or
590  * appended to it if appendval is true.
591  *
592  * Note: we pstrdup the buffer rather than just transferring its storage
593  * to the edata field because the buffer might be considerably larger than
594  * really necessary.
595  */
596 #define EVALUATE_MESSAGE(targetfield, appendval)  \
597         { \
598                 char               *fmtbuf; \
599                 StringInfoData  buf; \
600                 /* Internationalize the error format string */ \
601                 fmt = _(fmt); \
602                 /* Expand %m in format string */ \
603                 fmtbuf = expand_fmt_string(fmt, edata); \
604                 initStringInfo(&buf); \
605                 if ((appendval) && edata->targetfield) \
606                         appendStringInfo(&buf, "%s\n", edata->targetfield); \
607                 /* Generate actual output --- have to use appendStringInfoVA */ \
608                 for (;;) \
609                 { \
610                         va_list         args; \
611                         bool            success; \
612                         va_start(args, fmt); \
613                         success = appendStringInfoVA(&buf, fmtbuf, args); \
614                         va_end(args); \
615                         if (success) \
616                                 break; \
617                         enlargeStringInfo(&buf, buf.maxlen); \
618                 } \
619                 /* Done with expanded fmt */ \
620                 pfree(fmtbuf); \
621                 /* Save the completed message into the stack item */ \
622                 if (edata->targetfield) \
623                         pfree(edata->targetfield); \
624                 edata->targetfield = pstrdup(buf.data); \
625                 pfree(buf.data); \
626         }
627
628
629 /*
630  * errmsg --- add a primary error message text to the current error
631  *
632  * In addition to the usual %-escapes recognized by printf, "%m" in
633  * fmt is replaced by the error message for the caller's value of errno.
634  *
635  * Note: no newline is needed at the end of the fmt string, since
636  * ereport will provide one for the output methods that need it.
637  */
638 int
639 errmsg(const char *fmt,...)
640 {
641         ErrorData  *edata = &errordata[errordata_stack_depth];
642         MemoryContext oldcontext;
643
644         recursion_depth++;
645         CHECK_STACK_DEPTH();
646         oldcontext = MemoryContextSwitchTo(ErrorContext);
647
648         EVALUATE_MESSAGE(message, false);
649
650         MemoryContextSwitchTo(oldcontext);
651         recursion_depth--;
652         return 0;                                       /* return value does not matter */
653 }
654
655
656 /*
657  * errmsg_internal --- add a primary error message text to the current error
658  *
659  * This is exactly like errmsg() except that strings passed to errmsg_internal
660  * are customarily left out of the internationalization message dictionary.
661  * This should be used for "can't happen" cases that are probably not worth
662  * spending translation effort on.
663  */
664 int
665 errmsg_internal(const char *fmt,...)
666 {
667         ErrorData  *edata = &errordata[errordata_stack_depth];
668         MemoryContext oldcontext;
669
670         recursion_depth++;
671         CHECK_STACK_DEPTH();
672         oldcontext = MemoryContextSwitchTo(ErrorContext);
673
674         EVALUATE_MESSAGE(message, false);
675
676         MemoryContextSwitchTo(oldcontext);
677         recursion_depth--;
678         return 0;                                       /* return value does not matter */
679 }
680
681
682 /*
683  * errdetail --- add a detail error message text to the current error
684  */
685 int
686 errdetail(const char *fmt,...)
687 {
688         ErrorData  *edata = &errordata[errordata_stack_depth];
689         MemoryContext oldcontext;
690
691         recursion_depth++;
692         CHECK_STACK_DEPTH();
693         oldcontext = MemoryContextSwitchTo(ErrorContext);
694
695         EVALUATE_MESSAGE(detail, false);
696
697         MemoryContextSwitchTo(oldcontext);
698         recursion_depth--;
699         return 0;                                       /* return value does not matter */
700 }
701
702
703 /*
704  * errhint --- add a hint error message text to the current error
705  */
706 int
707 errhint(const char *fmt,...)
708 {
709         ErrorData  *edata = &errordata[errordata_stack_depth];
710         MemoryContext oldcontext;
711
712         recursion_depth++;
713         CHECK_STACK_DEPTH();
714         oldcontext = MemoryContextSwitchTo(ErrorContext);
715
716         EVALUATE_MESSAGE(hint, false);
717
718         MemoryContextSwitchTo(oldcontext);
719         recursion_depth--;
720         return 0;                                       /* return value does not matter */
721 }
722
723
724 /*
725  * errcontext --- add a context error message text to the current error
726  *
727  * Unlike other cases, multiple calls are allowed to build up a stack of
728  * context information.  We assume earlier calls represent more-closely-nested
729  * states.
730  */
731 int
732 errcontext(const char *fmt,...)
733 {
734         ErrorData  *edata = &errordata[errordata_stack_depth];
735         MemoryContext oldcontext;
736
737         recursion_depth++;
738         CHECK_STACK_DEPTH();
739         oldcontext = MemoryContextSwitchTo(ErrorContext);
740
741         EVALUATE_MESSAGE(context, true);
742
743         MemoryContextSwitchTo(oldcontext);
744         recursion_depth--;
745         return 0;                                       /* return value does not matter */
746 }
747
748
749 /*
750  * errfunction --- add reporting function name to the current error
751  *
752  * This is used when backwards compatibility demands that the function
753  * name appear in messages sent to old-protocol clients.  Note that the
754  * passed string is expected to be a non-freeable constant string.
755  */
756 int
757 errfunction(const char *funcname)
758 {
759         ErrorData  *edata = &errordata[errordata_stack_depth];
760
761         /* we don't bother incrementing recursion_depth */
762         CHECK_STACK_DEPTH();
763
764         edata->funcname = funcname;
765         edata->show_funcname = true;
766
767         return 0;                                       /* return value does not matter */
768 }
769
770 /*
771  * errposition --- add cursor position to the current error
772  */
773 int
774 errposition(int cursorpos)
775 {
776         ErrorData  *edata = &errordata[errordata_stack_depth];
777
778         /* we don't bother incrementing recursion_depth */
779         CHECK_STACK_DEPTH();
780
781         edata->cursorpos = cursorpos;
782
783         return 0;                                       /* return value does not matter */
784 }
785
786 /*
787  * internalerrposition --- add internal cursor position to the current error
788  */
789 int
790 internalerrposition(int cursorpos)
791 {
792         ErrorData  *edata = &errordata[errordata_stack_depth];
793
794         /* we don't bother incrementing recursion_depth */
795         CHECK_STACK_DEPTH();
796
797         edata->internalpos = cursorpos;
798
799         return 0;                                       /* return value does not matter */
800 }
801
802 /*
803  * internalerrquery --- add internal query text to the current error
804  *
805  * Can also pass NULL to drop the internal query text entry.  This case
806  * is intended for use in error callback subroutines that are editorializing
807  * on the layout of the error report.
808  */
809 int
810 internalerrquery(const char *query)
811 {
812         ErrorData  *edata = &errordata[errordata_stack_depth];
813
814         /* we don't bother incrementing recursion_depth */
815         CHECK_STACK_DEPTH();
816
817         if (edata->internalquery)
818         {
819                 pfree(edata->internalquery);
820                 edata->internalquery = NULL;
821         }
822
823         if (query)
824                 edata->internalquery = MemoryContextStrdup(ErrorContext, query);
825
826         return 0;                                       /* return value does not matter */
827 }
828
829 /*
830  * geterrposition --- return the currently set error position (0 if none)
831  *
832  * This is only intended for use in error callback subroutines, since there
833  * is no other place outside elog.c where the concept is meaningful.
834  */
835 int
836 geterrposition(void)
837 {
838         ErrorData  *edata = &errordata[errordata_stack_depth];
839
840         /* we don't bother incrementing recursion_depth */
841         CHECK_STACK_DEPTH();
842
843         return edata->cursorpos;
844 }
845
846 /*
847  * getinternalerrposition --- same for internal error position
848  *
849  * This is only intended for use in error callback subroutines, since there
850  * is no other place outside elog.c where the concept is meaningful.
851  */
852 int
853 getinternalerrposition(void)
854 {
855         ErrorData  *edata = &errordata[errordata_stack_depth];
856
857         /* we don't bother incrementing recursion_depth */
858         CHECK_STACK_DEPTH();
859
860         return edata->internalpos;
861 }
862
863
864 /*
865  * elog_start --- startup for old-style API
866  *
867  * All that we do here is stash the hidden filename/lineno/funcname
868  * arguments into a stack entry.
869  *
870  * We need this to be separate from elog_finish because there's no other
871  * portable way to deal with inserting extra arguments into the elog call.
872  * (If macros with variable numbers of arguments were portable, it'd be
873  * easy, but they aren't.)
874  */
875 void
876 elog_start(const char *filename, int lineno, const char *funcname)
877 {
878         ErrorData  *edata;
879
880         if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
881         {
882                 /*
883                  * Wups, stack not big enough.  We treat this as a PANIC condition
884                  * because it suggests an infinite loop of errors during error
885                  * recovery.
886                  */
887                 errordata_stack_depth = -1;             /* make room on stack */
888                 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
889         }
890
891         edata = &errordata[errordata_stack_depth];
892         edata->filename = filename;
893         edata->lineno = lineno;
894         edata->funcname = funcname;
895         /* errno is saved now so that error parameter eval can't change it */
896         edata->saved_errno = errno;
897 }
898
899 /*
900  * elog_finish --- finish up for old-style API
901  */
902 void
903 elog_finish(int elevel, const char *fmt,...)
904 {
905         ErrorData  *edata = &errordata[errordata_stack_depth];
906         MemoryContext oldcontext;
907
908         CHECK_STACK_DEPTH();
909
910         /*
911          * Do errstart() to see if we actually want to report the message.
912          */
913         errordata_stack_depth--;
914         errno = edata->saved_errno;
915         if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname))
916                 return;                                 /* nothing to do */
917
918         /*
919          * Format error message just like errmsg().
920          */
921         recursion_depth++;
922         oldcontext = MemoryContextSwitchTo(ErrorContext);
923
924         EVALUATE_MESSAGE(message, false);
925
926         MemoryContextSwitchTo(oldcontext);
927         recursion_depth--;
928
929         /*
930          * And let errfinish() finish up.
931          */
932         errfinish(0);
933 }
934
935 /*
936  * Actual output of the top-of-stack error message
937  *
938  * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
939  * if the error is caught by somebody).  For all other severity levels this
940  * is called by errfinish.
941  */
942 void
943 EmitErrorReport(void)
944 {
945         ErrorData  *edata = &errordata[errordata_stack_depth];
946         MemoryContext oldcontext;
947
948         recursion_depth++;
949         CHECK_STACK_DEPTH();
950         oldcontext = MemoryContextSwitchTo(ErrorContext);
951
952         /* Send to server log, if enabled */
953         if (edata->output_to_server)
954                 send_message_to_server_log(edata);
955
956         /* Send to client, if enabled */
957         if (edata->output_to_client)
958                 send_message_to_frontend(edata);
959
960         MemoryContextSwitchTo(oldcontext);
961         recursion_depth--;
962 }
963
964 /*
965  * CopyErrorData --- obtain a copy of the topmost error stack entry
966  *
967  * This is only for use in error handler code.  The data is copied into the
968  * current memory context, so callers should always switch away from
969  * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
970  */
971 ErrorData *
972 CopyErrorData(void)
973 {
974         ErrorData  *edata = &errordata[errordata_stack_depth];
975         ErrorData  *newedata;
976
977         /*
978          * we don't increment recursion_depth because out-of-memory here does
979          * not indicate a problem within the error subsystem.
980          */
981         CHECK_STACK_DEPTH();
982
983         Assert(CurrentMemoryContext != ErrorContext);
984
985         /* Copy the struct itself */
986         newedata = (ErrorData *) palloc(sizeof(ErrorData));
987         memcpy(newedata, edata, sizeof(ErrorData));
988
989         /* Make copies of separately-allocated fields */
990         if (newedata->message)
991                 newedata->message = pstrdup(newedata->message);
992         if (newedata->detail)
993                 newedata->detail = pstrdup(newedata->detail);
994         if (newedata->hint)
995                 newedata->hint = pstrdup(newedata->hint);
996         if (newedata->context)
997                 newedata->context = pstrdup(newedata->context);
998         if (newedata->internalquery)
999                 newedata->internalquery = pstrdup(newedata->internalquery);
1000
1001         return newedata;
1002 }
1003
1004 /*
1005  * FreeErrorData --- free the structure returned by CopyErrorData.
1006  *
1007  * Error handlers should use this in preference to assuming they know all
1008  * the separately-allocated fields.
1009  */
1010 void
1011 FreeErrorData(ErrorData *edata)
1012 {
1013         if (edata->message)
1014                 pfree(edata->message);
1015         if (edata->detail)
1016                 pfree(edata->detail);
1017         if (edata->hint)
1018                 pfree(edata->hint);
1019         if (edata->context)
1020                 pfree(edata->context);
1021         if (edata->internalquery)
1022                 pfree(edata->internalquery);
1023         pfree(edata);
1024 }
1025
1026 /*
1027  * FlushErrorState --- flush the error state after error recovery
1028  *
1029  * This should be called by an error handler after it's done processing
1030  * the error; or as soon as it's done CopyErrorData, if it intends to
1031  * do stuff that is likely to provoke another error.  You are not "out" of
1032  * the error subsystem until you have done this.
1033  */
1034 void
1035 FlushErrorState(void)
1036 {
1037         /*
1038          * Reset stack to empty.  The only case where it would be more than
1039          * one deep is if we serviced an error that interrupted construction
1040          * of another message.  We assume control escaped out of that message
1041          * construction and won't ever go back.
1042          */
1043         errordata_stack_depth = -1;
1044         recursion_depth = 0;
1045         /* Delete all data in ErrorContext */
1046         MemoryContextResetAndDeleteChildren(ErrorContext);
1047 }
1048
1049 /*
1050  * ReThrowError --- re-throw a previously copied error
1051  *
1052  * A handler can do CopyErrorData/FlushErrorState to get out of the error
1053  * subsystem, then do some processing, and finally ReThrowError to re-throw
1054  * the original error.  This is slower than just PG_RE_THROW() but should
1055  * be used if the "some processing" is likely to incur another error.
1056  */
1057 void
1058 ReThrowError(ErrorData *edata)
1059 {
1060         ErrorData  *newedata;
1061
1062         Assert(edata->elevel == ERROR);
1063
1064         /* Push the data back into the error context */
1065         recursion_depth++;
1066         MemoryContextSwitchTo(ErrorContext);
1067
1068         if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1069         {
1070                 /*
1071                  * Wups, stack not big enough.  We treat this as a PANIC condition
1072                  * because it suggests an infinite loop of errors during error
1073                  * recovery.
1074                  */
1075                 errordata_stack_depth = -1;             /* make room on stack */
1076                 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1077         }
1078
1079         newedata = &errordata[errordata_stack_depth];
1080         memcpy(newedata, edata, sizeof(ErrorData));
1081
1082         /* Make copies of separately-allocated fields */
1083         if (newedata->message)
1084                 newedata->message = pstrdup(newedata->message);
1085         if (newedata->detail)
1086                 newedata->detail = pstrdup(newedata->detail);
1087         if (newedata->hint)
1088                 newedata->hint = pstrdup(newedata->hint);
1089         if (newedata->context)
1090                 newedata->context = pstrdup(newedata->context);
1091         if (newedata->internalquery)
1092                 newedata->internalquery = pstrdup(newedata->internalquery);
1093
1094         recursion_depth--;
1095         PG_RE_THROW();
1096 }
1097
1098 /*
1099  * Initialization of error output file
1100  */
1101 void
1102 DebugFileOpen(void)
1103 {
1104         int                     fd,
1105                                 istty;
1106
1107         if (OutputFileName[0])
1108         {
1109                 /*
1110                  * A debug-output file name was given.
1111                  *
1112                  * Make sure we can write the file, and find out if it's a tty.
1113                  */
1114                 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
1115                                            0666)) < 0)
1116                         ereport(FATAL,
1117                                         (errcode_for_file_access(),
1118                           errmsg("could not open file \"%s\": %m", OutputFileName)));
1119                 istty = isatty(fd);
1120                 close(fd);
1121
1122                 /*
1123                  * Redirect our stderr to the debug output file.
1124                  */
1125                 if (!freopen(OutputFileName, "a", stderr))
1126                         ereport(FATAL,
1127                                         (errcode_for_file_access(),
1128                                          errmsg("could not reopen file \"%s\" as stderr: %m",
1129                                                         OutputFileName)));
1130
1131                 /*
1132                  * If the file is a tty and we're running under the postmaster,
1133                  * try to send stdout there as well (if it isn't a tty then stderr
1134                  * will block out stdout, so we may as well let stdout go wherever
1135                  * it was going before).
1136                  */
1137                 if (istty && IsUnderPostmaster)
1138                         if (!freopen(OutputFileName, "a", stdout))
1139                                 ereport(FATAL,
1140                                                 (errcode_for_file_access(),
1141                                          errmsg("could not reopen file \"%s\" as stdout: %m",
1142                                                         OutputFileName)));
1143         }
1144 }
1145
1146
1147
1148 #ifdef HAVE_SYSLOG
1149
1150 #ifndef PG_SYSLOG_LIMIT
1151 #define PG_SYSLOG_LIMIT 128
1152 #endif
1153
1154 /*
1155  * Write a message line to syslog if the syslog option is set.
1156  *
1157  * Our problem here is that many syslog implementations don't handle
1158  * long messages in an acceptable manner. While this function doesn't
1159  * help that fact, it does work around by splitting up messages into
1160  * smaller pieces.
1161  */
1162 static void
1163 write_syslog(int level, const char *line)
1164 {
1165         static bool openlog_done = false;
1166         static unsigned long seq = 0;
1167         static int      syslog_fac = LOG_LOCAL0;
1168
1169         int                     len = strlen(line);
1170
1171         if (!openlog_done)
1172         {
1173                 if (pg_strcasecmp(Syslog_facility, "LOCAL0") == 0)
1174                         syslog_fac = LOG_LOCAL0;
1175                 if (pg_strcasecmp(Syslog_facility, "LOCAL1") == 0)
1176                         syslog_fac = LOG_LOCAL1;
1177                 if (pg_strcasecmp(Syslog_facility, "LOCAL2") == 0)
1178                         syslog_fac = LOG_LOCAL2;
1179                 if (pg_strcasecmp(Syslog_facility, "LOCAL3") == 0)
1180                         syslog_fac = LOG_LOCAL3;
1181                 if (pg_strcasecmp(Syslog_facility, "LOCAL4") == 0)
1182                         syslog_fac = LOG_LOCAL4;
1183                 if (pg_strcasecmp(Syslog_facility, "LOCAL5") == 0)
1184                         syslog_fac = LOG_LOCAL5;
1185                 if (pg_strcasecmp(Syslog_facility, "LOCAL6") == 0)
1186                         syslog_fac = LOG_LOCAL6;
1187                 if (pg_strcasecmp(Syslog_facility, "LOCAL7") == 0)
1188                         syslog_fac = LOG_LOCAL7;
1189                 openlog(Syslog_ident, LOG_PID | LOG_NDELAY | LOG_NOWAIT, syslog_fac);
1190                 openlog_done = true;
1191         }
1192
1193         /*
1194          * We add a sequence number to each log message to suppress "same"
1195          * messages.
1196          */
1197         seq++;
1198
1199         /* divide into multiple syslog() calls if message is too long */
1200         /* or if the message contains embedded NewLine(s) '\n' */
1201         if (len > PG_SYSLOG_LIMIT || strchr(line, '\n') != NULL)
1202         {
1203                 int                     chunk_nr = 0;
1204
1205                 while (len > 0)
1206                 {
1207                         char            buf[PG_SYSLOG_LIMIT + 1];
1208                         int                     buflen;
1209                         int                     i;
1210
1211                         /* if we start at a newline, move ahead one char */
1212                         if (line[0] == '\n')
1213                         {
1214                                 line++;
1215                                 len--;
1216                                 continue;
1217                         }
1218
1219                         strncpy(buf, line, PG_SYSLOG_LIMIT);
1220                         buf[PG_SYSLOG_LIMIT] = '\0';
1221                         if (strchr(buf, '\n') != NULL)
1222                                 *strchr(buf, '\n') = '\0';
1223
1224                         buflen = strlen(buf);
1225
1226                         /* trim to multibyte letter boundary */
1227                         buflen = pg_mbcliplen(buf, buflen, buflen);
1228                         if (buflen <= 0)
1229                                 return;
1230                         buf[buflen] = '\0';
1231
1232                         /* already word boundary? */
1233                         if (!isspace((unsigned char) line[buflen]) &&
1234                                 line[buflen] != '\0')
1235                         {
1236                                 /* try to divide at word boundary */
1237                                 i = buflen - 1;
1238                                 while (i > 0 && !isspace((unsigned char) buf[i]))
1239                                         i--;
1240
1241                                 if (i > 0)              /* else couldn't divide word boundary */
1242                                 {
1243                                         buflen = i;
1244                                         buf[i] = '\0';
1245                                 }
1246                         }
1247
1248                         chunk_nr++;
1249
1250                         syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1251                         line += buflen;
1252                         len -= buflen;
1253                 }
1254         }
1255         else
1256         {
1257                 /* message short enough */
1258                 syslog(level, "[%lu] %s", seq, line);
1259         }
1260 }
1261 #endif   /* HAVE_SYSLOG */
1262 #ifdef WIN32
1263 /*
1264  * Write a message line to the windows event log
1265  */
1266 static void
1267 write_eventlog(int level, const char *line)
1268 {
1269         static HANDLE evtHandle = INVALID_HANDLE_VALUE;
1270
1271         if (evtHandle == INVALID_HANDLE_VALUE)
1272         {
1273                 evtHandle = RegisterEventSource(NULL, "PostgreSQL");
1274                 if (evtHandle == NULL)
1275                 {
1276                         evtHandle = INVALID_HANDLE_VALUE;
1277                         return;
1278                 }
1279         }
1280
1281         ReportEvent(evtHandle,
1282                                 level,
1283                                 0,
1284                                 0,                              /* All events are Id 0 */
1285                                 NULL,
1286                                 1,
1287                                 0,
1288                                 &line,
1289                                 NULL);
1290 }
1291 #endif   /* WIN32 */
1292
1293 /*
1294  * Format tag info for log lines; append to the provided buffer.
1295  */
1296 static void
1297 log_line_prefix(StringInfo buf)
1298 {
1299         /* static counter for line numbers */
1300         static long log_line_number = 0;
1301
1302         /* has counter been reset in current process? */
1303         static int      log_my_pid = 0;
1304
1305         int                     format_len;
1306         int                     i;
1307
1308         /*
1309          * This is one of the few places where we'd rather not inherit a
1310          * static variable's value from the postmaster.  But since we will,
1311          * reset it when MyProcPid changes.
1312          */
1313         if (log_my_pid != MyProcPid)
1314         {
1315                 log_line_number = 0;
1316                 log_my_pid = MyProcPid;
1317         }
1318         log_line_number++;
1319
1320         if (Log_line_prefix == NULL)
1321                 return;                                 /* in case guc hasn't run yet */
1322
1323         format_len = strlen(Log_line_prefix);
1324
1325         for (i = 0; i < format_len; i++)
1326         {
1327                 if (Log_line_prefix[i] != '%')
1328                 {
1329                         /* literal char, just copy */
1330                         appendStringInfoChar(buf, Log_line_prefix[i]);
1331                         continue;
1332                 }
1333                 /* go to char after '%' */
1334                 i++;
1335                 if (i >= format_len)
1336                 {
1337                         /* format error - ignore it */
1338                         break;
1339                 }
1340
1341                 /* process the option */
1342                 switch (Log_line_prefix[i])
1343                 {
1344                         case 'u':
1345                                 if (MyProcPort)
1346                                 {
1347                                         const char *username = MyProcPort->user_name;
1348
1349                                         if (username == NULL || *username == '\0')
1350                                                 username = _("[unknown]");
1351                                         appendStringInfo(buf, "%s", username);
1352                                 }
1353                                 break;
1354                         case 'd':
1355                                 if (MyProcPort)
1356                                 {
1357                                         const char *dbname = MyProcPort->database_name;
1358
1359                                         if (dbname == NULL || *dbname == '\0')
1360                                                 dbname = _("[unknown]");
1361                                         appendStringInfo(buf, "%s", dbname);
1362                                 }
1363                                 break;
1364                         case 'c':
1365                                 if (MyProcPort)
1366                                 {
1367                                         appendStringInfo(buf, "%lx.%x",
1368                                                            (long) (MyProcPort->session_start.tv_sec),
1369                                                            MyProcPid);
1370                                 }
1371                                 break;
1372                         case 'p':
1373                                 appendStringInfo(buf, "%d", MyProcPid);
1374                                 break;
1375                         case 'l':
1376                                 appendStringInfo(buf, "%ld", log_line_number);
1377                                 break;
1378                         case 't':
1379                                 {
1380                                         /*
1381                                          * Note: for %t and %s we deliberately use the C
1382                                          * library's strftime/localtime, and not the
1383                                          * equivalent functions from src/timezone.      This
1384                                          * ensures that all backends will report log entries
1385                                          * in the same timezone, namely whatever C-library
1386                                          * setting they inherit from the postmaster.  If we
1387                                          * used src/timezone then local settings of the
1388                                          * TimeZone GUC variable would confuse the log.
1389                                          */
1390                                         time_t          stamp_time = time(NULL);
1391                                         char            strfbuf[128];
1392
1393                                         strftime(strfbuf, sizeof(strfbuf),
1394                                         /* Win32 timezone names are too long so don't print them. */
1395 #ifndef WIN32
1396                                                          "%Y-%m-%d %H:%M:%S %Z",
1397 #else
1398                                                          "%Y-%m-%d %H:%M:%S",
1399 #endif
1400                                                          localtime(&stamp_time));
1401                                         appendStringInfoString(buf, strfbuf);
1402                                 }
1403                                 break;
1404                         case 's':
1405                                 if (MyProcPort)
1406                                 {
1407                                         time_t          stamp_time = MyProcPort->session_start.tv_sec;
1408                                         char            strfbuf[128];
1409
1410                                         strftime(strfbuf, sizeof(strfbuf),
1411                                                          "%Y-%m-%d %H:%M:%S %Z",
1412                                                          localtime(&stamp_time));
1413                                         appendStringInfoString(buf, strfbuf);
1414                                 }
1415                                 break;
1416                         case 'i':
1417                                 if (MyProcPort)
1418                                         appendStringInfo(buf, "%s", MyProcPort->commandTag);
1419                                 break;
1420                         case 'r':
1421                                 if (MyProcPort)
1422                                 {
1423                                         appendStringInfo(buf, "%s", MyProcPort->remote_host);
1424                                         if (strlen(MyProcPort->remote_port) > 0)
1425                                                 appendStringInfo(buf, "(%s)",
1426                                                                                  MyProcPort->remote_port);
1427                                 }
1428                                 break;
1429                         case 'q':
1430                                 /* in postmaster and friends, stop if %q is seen */
1431                                 /* in a backend, just ignore */
1432                                 if (MyProcPort == NULL)
1433                                         i = format_len;
1434                                 break;
1435                         case 'x':
1436                                 if (MyProcPort)
1437                                 {
1438                                         if (IsTransactionState())
1439                                                 appendStringInfo(buf, "%u", GetTopTransactionId());
1440                                         else
1441                                                 appendStringInfo(buf, "%u", InvalidTransactionId);
1442                                 }
1443                                 break;
1444                         case '%':
1445                                 appendStringInfoChar(buf, '%');
1446                                 break;
1447                         default:
1448                                 /* format error - ignore it */
1449                                 break;
1450                 }
1451         }
1452 }
1453
1454
1455 /*
1456  * Write error report to server's log
1457  */
1458 static void
1459 send_message_to_server_log(ErrorData *edata)
1460 {
1461         StringInfoData buf;
1462
1463         initStringInfo(&buf);
1464
1465         log_line_prefix(&buf);
1466         appendStringInfo(&buf, "%s:  ", error_severity(edata->elevel));
1467
1468         if (Log_error_verbosity >= PGERROR_VERBOSE)
1469         {
1470                 /* unpack MAKE_SQLSTATE code */
1471                 char            tbuf[12];
1472                 int                     ssval;
1473                 int                     i;
1474
1475                 ssval = edata->sqlerrcode;
1476                 for (i = 0; i < 5; i++)
1477                 {
1478                         tbuf[i] = PGUNSIXBIT(ssval);
1479                         ssval >>= 6;
1480                 }
1481                 tbuf[i] = '\0';
1482                 appendStringInfo(&buf, "%s: ", tbuf);
1483         }
1484
1485         if (edata->message)
1486                 append_with_tabs(&buf, edata->message);
1487         else
1488                 append_with_tabs(&buf, _("missing error text"));
1489
1490         if (edata->cursorpos > 0)
1491                 appendStringInfo(&buf, _(" at character %d"),
1492                                                  edata->cursorpos);
1493         else if (edata->internalpos > 0)
1494                 appendStringInfo(&buf, _(" at character %d"),
1495                                                  edata->internalpos);
1496
1497         appendStringInfoChar(&buf, '\n');
1498
1499         if (Log_error_verbosity >= PGERROR_DEFAULT)
1500         {
1501                 if (edata->detail)
1502                 {
1503                         log_line_prefix(&buf);
1504                         appendStringInfoString(&buf, _("DETAIL:  "));
1505                         append_with_tabs(&buf, edata->detail);
1506                         appendStringInfoChar(&buf, '\n');
1507                 }
1508                 if (edata->hint)
1509                 {
1510                         log_line_prefix(&buf);
1511                         appendStringInfoString(&buf, _("HINT:  "));
1512                         append_with_tabs(&buf, edata->hint);
1513                         appendStringInfoChar(&buf, '\n');
1514                 }
1515                 if (edata->internalquery)
1516                 {
1517                         log_line_prefix(&buf);
1518                         appendStringInfoString(&buf, _("QUERY:  "));
1519                         append_with_tabs(&buf, edata->internalquery);
1520                         appendStringInfoChar(&buf, '\n');
1521                 }
1522                 if (edata->context)
1523                 {
1524                         log_line_prefix(&buf);
1525                         appendStringInfoString(&buf, _("CONTEXT:  "));
1526                         append_with_tabs(&buf, edata->context);
1527                         appendStringInfoChar(&buf, '\n');
1528                 }
1529                 if (Log_error_verbosity >= PGERROR_VERBOSE)
1530                 {
1531                         /* assume no newlines in funcname or filename... */
1532                         if (edata->funcname && edata->filename)
1533                         {
1534                                 log_line_prefix(&buf);
1535                                 appendStringInfo(&buf, _("LOCATION:  %s, %s:%d\n"),
1536                                                                  edata->funcname, edata->filename,
1537                                                                  edata->lineno);
1538                         }
1539                         else if (edata->filename)
1540                         {
1541                                 log_line_prefix(&buf);
1542                                 appendStringInfo(&buf, _("LOCATION:  %s:%d\n"),
1543                                                                  edata->filename, edata->lineno);
1544                         }
1545                 }
1546         }
1547
1548         /*
1549          * If the user wants the query that generated this error logged, do
1550          * it.
1551          */
1552         if (edata->elevel >= log_min_error_statement && debug_query_string != NULL)
1553         {
1554                 log_line_prefix(&buf);
1555                 appendStringInfoString(&buf, _("STATEMENT:  "));
1556                 append_with_tabs(&buf, debug_query_string);
1557                 appendStringInfoChar(&buf, '\n');
1558         }
1559
1560
1561 #ifdef HAVE_SYSLOG
1562         /* Write to syslog, if enabled */
1563         if (Log_destination & LOG_DESTINATION_SYSLOG)
1564         {
1565                 int                     syslog_level;
1566
1567                 switch (edata->elevel)
1568                 {
1569                         case DEBUG5:
1570                         case DEBUG4:
1571                         case DEBUG3:
1572                         case DEBUG2:
1573                         case DEBUG1:
1574                                 syslog_level = LOG_DEBUG;
1575                                 break;
1576                         case LOG:
1577                         case COMMERROR:
1578                         case INFO:
1579                                 syslog_level = LOG_INFO;
1580                                 break;
1581                         case NOTICE:
1582                         case WARNING:
1583                                 syslog_level = LOG_NOTICE;
1584                                 break;
1585                         case ERROR:
1586                                 syslog_level = LOG_WARNING;
1587                                 break;
1588                         case FATAL:
1589                                 syslog_level = LOG_ERR;
1590                                 break;
1591                         case PANIC:
1592                         default:
1593                                 syslog_level = LOG_CRIT;
1594                                 break;
1595                 }
1596
1597                 write_syslog(syslog_level, buf.data);
1598         }
1599 #endif   /* HAVE_SYSLOG */
1600 #ifdef WIN32
1601         if (Log_destination & LOG_DESTINATION_EVENTLOG)
1602         {
1603                 int                     eventlog_level;
1604
1605                 switch (edata->elevel)
1606                 {
1607                         case DEBUG5:
1608                         case DEBUG4:
1609                         case DEBUG3:
1610                         case DEBUG2:
1611                         case DEBUG1:
1612                         case LOG:
1613                         case COMMERROR:
1614                         case INFO:
1615                         case NOTICE:
1616                                 eventlog_level = EVENTLOG_INFORMATION_TYPE;
1617                                 break;
1618                         case WARNING:
1619                                 eventlog_level = EVENTLOG_WARNING_TYPE;
1620                                 break;
1621                         case ERROR:
1622                         case FATAL:
1623                         case PANIC:
1624                         default:
1625                                 eventlog_level = EVENTLOG_ERROR_TYPE;
1626                                 break;
1627                 }
1628                 write_eventlog(eventlog_level, buf.data);
1629         }
1630 #endif   /* WIN32 */
1631         /* Write to stderr, if enabled */
1632         if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == Debug)
1633                 fprintf(stderr, "%s", buf.data);
1634
1635         /* If in the syslogger process, try to write messages direct to file */
1636         if (am_syslogger)
1637                 write_syslogger_file(buf.data, buf.len);
1638
1639         pfree(buf.data);
1640 }
1641
1642
1643 /*
1644  * Write error report to client
1645  */
1646 static void
1647 send_message_to_frontend(ErrorData *edata)
1648 {
1649         StringInfoData msgbuf;
1650
1651         /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
1652         pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
1653
1654         if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
1655         {
1656                 /* New style with separate fields */
1657                 char            tbuf[12];
1658                 int                     ssval;
1659                 int                     i;
1660
1661                 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
1662                 pq_sendstring(&msgbuf, error_severity(edata->elevel));
1663
1664                 /* unpack MAKE_SQLSTATE code */
1665                 ssval = edata->sqlerrcode;
1666                 for (i = 0; i < 5; i++)
1667                 {
1668                         tbuf[i] = PGUNSIXBIT(ssval);
1669                         ssval >>= 6;
1670                 }
1671                 tbuf[i] = '\0';
1672
1673                 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
1674                 pq_sendstring(&msgbuf, tbuf);
1675
1676                 /* M field is required per protocol, so always send something */
1677                 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
1678                 if (edata->message)
1679                         pq_sendstring(&msgbuf, edata->message);
1680                 else
1681                         pq_sendstring(&msgbuf, _("missing error text"));
1682
1683                 if (edata->detail)
1684                 {
1685                         pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
1686                         pq_sendstring(&msgbuf, edata->detail);
1687                 }
1688
1689                 if (edata->hint)
1690                 {
1691                         pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
1692                         pq_sendstring(&msgbuf, edata->hint);
1693                 }
1694
1695                 if (edata->context)
1696                 {
1697                         pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
1698                         pq_sendstring(&msgbuf, edata->context);
1699                 }
1700
1701                 if (edata->cursorpos > 0)
1702                 {
1703                         snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
1704                         pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
1705                         pq_sendstring(&msgbuf, tbuf);
1706                 }
1707
1708                 if (edata->internalpos > 0)
1709                 {
1710                         snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
1711                         pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
1712                         pq_sendstring(&msgbuf, tbuf);
1713                 }
1714
1715                 if (edata->internalquery)
1716                 {
1717                         pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
1718                         pq_sendstring(&msgbuf, edata->internalquery);
1719                 }
1720
1721                 if (edata->filename)
1722                 {
1723                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
1724                         pq_sendstring(&msgbuf, edata->filename);
1725                 }
1726
1727                 if (edata->lineno > 0)
1728                 {
1729                         snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
1730                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
1731                         pq_sendstring(&msgbuf, tbuf);
1732                 }
1733
1734                 if (edata->funcname)
1735                 {
1736                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
1737                         pq_sendstring(&msgbuf, edata->funcname);
1738                 }
1739
1740                 pq_sendbyte(&msgbuf, '\0');             /* terminator */
1741         }
1742         else
1743         {
1744                 /* Old style --- gin up a backwards-compatible message */
1745                 StringInfoData buf;
1746
1747                 initStringInfo(&buf);
1748
1749                 appendStringInfo(&buf, "%s:  ", error_severity(edata->elevel));
1750
1751                 if (edata->show_funcname && edata->funcname)
1752                         appendStringInfo(&buf, "%s: ", edata->funcname);
1753
1754                 if (edata->message)
1755                         appendStringInfoString(&buf, edata->message);
1756                 else
1757                         appendStringInfoString(&buf, _("missing error text"));
1758
1759                 if (edata->cursorpos > 0)
1760                         appendStringInfo(&buf, _(" at character %d"),
1761                                                          edata->cursorpos);
1762                 else if (edata->internalpos > 0)
1763                         appendStringInfo(&buf, _(" at character %d"),
1764                                                          edata->internalpos);
1765
1766                 appendStringInfoChar(&buf, '\n');
1767
1768                 pq_sendstring(&msgbuf, buf.data);
1769
1770                 pfree(buf.data);
1771         }
1772
1773         pq_endmessage(&msgbuf);
1774
1775         /*
1776          * This flush is normally not necessary, since postgres.c will flush
1777          * out waiting data when control returns to the main loop. But it
1778          * seems best to leave it here, so that the client has some clue what
1779          * happened if the backend dies before getting back to the main loop
1780          * ... error/notice messages should not be a performance-critical path
1781          * anyway, so an extra flush won't hurt much ...
1782          */
1783         pq_flush();
1784 }
1785
1786
1787 /*
1788  * Support routines for formatting error messages.
1789  */
1790
1791
1792 /*
1793  * expand_fmt_string --- process special format codes in a format string
1794  *
1795  * We must replace %m with the appropriate strerror string, since vsnprintf
1796  * won't know what to do with it.
1797  *
1798  * The result is a palloc'd string.
1799  */
1800 static char *
1801 expand_fmt_string(const char *fmt, ErrorData *edata)
1802 {
1803         StringInfoData buf;
1804         const char *cp;
1805
1806         initStringInfo(&buf);
1807
1808         for (cp = fmt; *cp; cp++)
1809         {
1810                 if (cp[0] == '%' && cp[1] != '\0')
1811                 {
1812                         cp++;
1813                         if (*cp == 'm')
1814                         {
1815                                 /*
1816                                  * Replace %m by system error string.  If there are any
1817                                  * %'s in the string, we'd better double them so that
1818                                  * vsnprintf won't misinterpret.
1819                                  */
1820                                 const char *cp2;
1821
1822                                 cp2 = useful_strerror(edata->saved_errno);
1823                                 for (; *cp2; cp2++)
1824                                 {
1825                                         if (*cp2 == '%')
1826                                                 appendStringInfoCharMacro(&buf, '%');
1827                                         appendStringInfoCharMacro(&buf, *cp2);
1828                                 }
1829                         }
1830                         else
1831                         {
1832                                 /* copy % and next char --- this avoids trouble with %%m */
1833                                 appendStringInfoCharMacro(&buf, '%');
1834                                 appendStringInfoCharMacro(&buf, *cp);
1835                         }
1836                 }
1837                 else
1838                         appendStringInfoCharMacro(&buf, *cp);
1839         }
1840
1841         return buf.data;
1842 }
1843
1844
1845 /*
1846  * A slightly cleaned-up version of strerror()
1847  */
1848 static const char *
1849 useful_strerror(int errnum)
1850 {
1851         /* this buffer is only used if errno has a bogus value */
1852         static char errorstr_buf[48];
1853         const char *str;
1854
1855 #ifdef WIN32
1856         /* Winsock error code range, per WinError.h */
1857         if (errnum >= 10000 && errnum <= 11999)
1858                 return pgwin32_socket_strerror(errnum);
1859 #endif
1860         str = strerror(errnum);
1861
1862         /*
1863          * Some strerror()s return an empty string for out-of-range errno.
1864          * This is ANSI C spec compliant, but not exactly useful.
1865          */
1866         if (str == NULL || *str == '\0')
1867         {
1868                 /*
1869                  * translator: This string will be truncated at 47 characters
1870                  * expanded.
1871                  */
1872                 snprintf(errorstr_buf, sizeof(errorstr_buf),
1873                                  _("operating system error %d"), errnum);
1874                 str = errorstr_buf;
1875         }
1876
1877         return str;
1878 }
1879
1880
1881 /*
1882  * error_severity --- get localized string representing elevel
1883  */
1884 static const char *
1885 error_severity(int elevel)
1886 {
1887         const char *prefix;
1888
1889         switch (elevel)
1890         {
1891                 case DEBUG1:
1892                 case DEBUG2:
1893                 case DEBUG3:
1894                 case DEBUG4:
1895                 case DEBUG5:
1896                         prefix = _("DEBUG");
1897                         break;
1898                 case LOG:
1899                 case COMMERROR:
1900                         prefix = _("LOG");
1901                         break;
1902                 case INFO:
1903                         prefix = _("INFO");
1904                         break;
1905                 case NOTICE:
1906                         prefix = _("NOTICE");
1907                         break;
1908                 case WARNING:
1909                         prefix = _("WARNING");
1910                         break;
1911                 case ERROR:
1912                         prefix = _("ERROR");
1913                         break;
1914                 case FATAL:
1915                         prefix = _("FATAL");
1916                         break;
1917                 case PANIC:
1918                         prefix = _("PANIC");
1919                         break;
1920                 default:
1921                         prefix = "???";
1922                         break;
1923         }
1924
1925         return prefix;
1926 }
1927
1928
1929 /*
1930  *      append_with_tabs
1931  *
1932  *      Append the string to the StringInfo buffer, inserting a tab after any
1933  *      newline.
1934  */
1935 static void
1936 append_with_tabs(StringInfo buf, const char *str)
1937 {
1938         char            ch;
1939
1940         while ((ch = *str++) != '\0')
1941         {
1942                 appendStringInfoCharMacro(buf, ch);
1943                 if (ch == '\n')
1944                         appendStringInfoCharMacro(buf, '\t');
1945         }
1946 }
1947
1948
1949 /*
1950  * Write errors to stderr (or by equal means when stderr is
1951  * not available). Used before ereport/elog can be used
1952  * safely (memory context, GUC load etc)
1953  */
1954 void
1955 write_stderr(const char *fmt,...)
1956 {
1957         va_list         ap;
1958
1959         fmt = _(fmt);
1960
1961         va_start(ap, fmt);
1962 #ifndef WIN32
1963         /* On Unix, we just fprintf to stderr */
1964         vfprintf(stderr, fmt, ap);
1965 #else
1966
1967         /*
1968          * On Win32, we print to stderr if running on a console, or write to
1969          * eventlog if running as a service
1970          */
1971         if (pgwin32_is_service())       /* Running as a service */
1972         {
1973                 char            errbuf[2048];           /* Arbitrary size? */
1974
1975                 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
1976
1977                 write_eventlog(EVENTLOG_ERROR_TYPE, errbuf);
1978         }
1979         else
1980                 /* Not running as service, write to stderr */
1981                 vfprintf(stderr, fmt, ap);
1982 #endif
1983         va_end(ap);
1984 }