1 /*-------------------------------------------------------------------------
4 * error logging and reporting
6 * Some notes about recursion and errors during error processing:
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.
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.)
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
40 * Portions Copyright (c) 1996-2004, PostgreSQL Global Development Group
41 * Portions Copyright (c) 1994, Regents of the University of California
45 * $PostgreSQL: pgsql/src/backend/utils/error/elog.c,v 1.149 2004/09/05 02:01:41 tgl Exp $
47 *-------------------------------------------------------------------------
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"
72 /* Global variables */
73 ErrorContextCallback *error_context_stack = NULL;
75 sigjmp_buf *PG_exception_stack = NULL;
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;
83 char *Syslog_facility; /* openlog() parameters */
86 static void write_syslog(int level, const char *line);
89 static void write_eventlog(int level, const char *line);
92 /* We provide a small stack of ErrorData records for re-entrant cases */
93 #define ERRORDATA_STACK_SIZE 5
95 static ErrorData errordata[ERRORDATA_STACK_SIZE];
97 static int errordata_stack_depth = -1; /* index of topmost active frame */
99 static int recursion_depth = 0; /* to detect actual recursion */
102 /* Macro for checking errordata_stack_depth is reasonable */
103 #define CHECK_STACK_DEPTH() \
105 if (errordata_stack_depth < 0) \
107 errordata_stack_depth = -1; \
108 ereport(ERROR, (errmsg_internal("errstart was not called"))); \
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);
123 * errstart --- begin an error-reporting cycle
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
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).
134 errstart(int elevel, const char *filename, int lineno,
135 const char *funcname)
138 bool output_to_server = false;
139 bool output_to_client = false;
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.
149 * If we are inside a critical section, all errors become PANIC
150 * errors. See miscadmin.h.
152 if (CritSectionCount > 0)
156 * Check reasons for treating ERROR as FATAL:
158 * 1. we have no handler to pass the error to (implies we are in the
159 * postmaster or in backend startup).
161 * 2. ExitOnAnyError mode switch is set (initdb uses this).
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!)
169 if (PG_exception_stack == NULL ||
171 proc_exit_inprogress)
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.
183 for (i = 0; i <= errordata_stack_depth; i++)
184 elevel = Max(elevel, errordata[i].elevel);
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.
193 /* Determine whether message is enabled for server log output */
194 if (IsPostmasterEnvironment)
196 /* Complicated because LOG is sorted out-of-order for this purpose */
197 if (elevel == LOG || elevel == COMMERROR)
199 if (log_min_messages == LOG)
200 output_to_server = true;
201 else if (log_min_messages < FATAL)
202 output_to_server = true;
207 if (log_min_messages == LOG)
210 output_to_server = true;
213 else if (elevel >= log_min_messages)
214 output_to_server = true;
219 /* In bootstrap/standalone case, do not sort LOG out-of-order */
220 output_to_server = (elevel >= log_min_messages);
223 /* Determine whether message is enabled for client output */
224 if (whereToSendOutput == Remote && elevel != COMMERROR)
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.
232 if (ClientAuthInProgress)
233 output_to_client = (elevel >= ERROR);
235 output_to_client = (elevel >= client_min_messages ||
239 /* Skip processing effort if non-error message will not be output */
240 if (elevel < ERROR && !output_to_server && !output_to_client)
244 * Okay, crank up a stack entry to store the info in.
247 if (recursion_depth++ > 0 && elevel >= ERROR)
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.
254 MemoryContextReset(ErrorContext);
257 * If we recurse more than once, the problem might be something
258 * broken in a context traceback routine. Abandon them too.
260 if (recursion_depth > 2)
261 error_context_stack = NULL;
263 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
266 * Wups, stack not big enough. We treat this as a PANIC condition
267 * because it suggests an infinite loop of errors during error
270 errordata_stack_depth = -1; /* make room on stack */
271 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
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 */
285 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
286 else if (elevel == WARNING)
287 edata->sqlerrcode = ERRCODE_WARNING;
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;
298 * errfinish --- end an error-reporting cycle
300 * Produce the appropriate error report(s) and pop the error stack.
302 * If elevel is ERROR or worse, control does not return to the caller.
303 * See elog.h for the error level definitions.
306 errfinish(int dummy,...)
308 ErrorData *edata = &errordata[errordata_stack_depth];
309 int elevel = edata->elevel;
310 MemoryContext oldcontext;
311 ErrorContextCallback *econtext;
317 * Do processing in ErrorContext, which we hope has enough reserved
318 * space to report an error.
320 oldcontext = MemoryContextSwitchTo(ErrorContext);
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).
327 for (econtext = error_context_stack;
329 econtext = econtext->previous)
330 (*econtext->callback) (econtext->arg);
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
340 * We do some minimal cleanup before longjmp'ing so that handlers
341 * can execute in a reasonably sane state.
344 /* This is just in case the error came while waiting for input */
345 ImmediateInterruptOK = false;
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
355 InterruptHoldoffCount = 0;
357 CritSectionCount = 0; /* should be unnecessary, but... */
360 * Note that we leave CurrentMemoryContext set to ErrorContext.
361 * The handler should reset it to something else soon.
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
378 if (elevel >= FATAL && whereToSendOutput == Remote)
381 /* Emit the message to the right places */
384 /* Now free up subsidiary data attached to stack entry, and release it */
386 pfree(edata->message);
388 pfree(edata->detail);
392 pfree(edata->context);
393 if (edata->internalquery)
394 pfree(edata->internalquery);
396 errordata_stack_depth--;
398 /* Exit error-handling context */
399 MemoryContextSwitchTo(oldcontext);
403 * Perform error recovery action as specified by elevel.
408 * For a FATAL error, we let proc_exit clean up and exit.
410 ImmediateInterruptOK = false;
413 * If we just reported a startup failure, the client will
414 * disconnect on receiving it, so don't send any more to the
417 if (PG_exception_stack == NULL && whereToSendOutput == Remote)
418 whereToSendOutput = None;
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.
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).
436 proc_exit(proc_exit_inprogress || !IsUnderPostmaster);
442 * Serious crash time. Postmaster will observe nonzero process
443 * exit status and kill the other backends too.
445 * XXX: what if we are *in* the postmaster? abort() won't kill our
448 ImmediateInterruptOK = false;
454 /* We reach here if elevel <= WARNING. OK to return to caller. */
459 * errcode --- add SQLSTATE error code to the current error
461 * The code is expected to be represented as per MAKE_SQLSTATE().
464 errcode(int sqlerrcode)
466 ErrorData *edata = &errordata[errordata_stack_depth];
468 /* we don't bother incrementing recursion_depth */
471 edata->sqlerrcode = sqlerrcode;
473 return 0; /* return value does not matter */
478 * errcode_for_file_access --- add SQLSTATE error code to the current error
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.
483 * NOTE: the primary error message string should generally include %m
487 errcode_for_file_access(void)
489 ErrorData *edata = &errordata[errordata_stack_depth];
491 /* we don't bother incrementing recursion_depth */
494 switch (edata->saved_errno)
496 /* Permission-denied failures */
497 case EPERM: /* Not super-user */
498 case EACCES: /* Permission denied */
500 case EROFS: /* Read only file system */
502 edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
506 case ENOENT: /* No such file or directory */
507 edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
511 case EEXIST: /* File exists */
512 edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
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 */
521 edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
524 /* Insufficient resources */
525 case ENOSPC: /* No space left on device */
526 edata->sqlerrcode = ERRCODE_DISK_FULL;
529 case ENFILE: /* File table overflow */
530 case EMFILE: /* Too many open files */
531 edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
534 /* Hardware failure */
535 case EIO: /* I/O error */
536 edata->sqlerrcode = ERRCODE_IO_ERROR;
539 /* All else is classified as internal errors */
541 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
545 return 0; /* return value does not matter */
549 * errcode_for_socket_access --- add SQLSTATE error code to the current error
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.
554 * NOTE: the primary error message string should generally include %m
558 errcode_for_socket_access(void)
560 ErrorData *edata = &errordata[errordata_stack_depth];
562 /* we don't bother incrementing recursion_depth */
565 switch (edata->saved_errno)
567 /* Loss of connection */
572 edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
575 /* All else is classified as internal errors */
577 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
581 return 0; /* return value does not matter */
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.
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
596 #define EVALUATE_MESSAGE(targetfield, appendval) \
599 StringInfoData buf; \
600 /* Internationalize the error format string */ \
601 fmt = gettext(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 */ \
612 va_start(args, fmt); \
613 success = appendStringInfoVA(&buf, fmtbuf, args); \
617 enlargeStringInfo(&buf, buf.maxlen); \
619 /* Done with expanded fmt */ \
621 /* Save the completed message into the stack item */ \
622 if (edata->targetfield) \
623 pfree(edata->targetfield); \
624 edata->targetfield = pstrdup(buf.data); \
630 * errmsg --- add a primary error message text to the current error
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.
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.
639 errmsg(const char *fmt,...)
641 ErrorData *edata = &errordata[errordata_stack_depth];
642 MemoryContext oldcontext;
646 oldcontext = MemoryContextSwitchTo(ErrorContext);
648 EVALUATE_MESSAGE(message, false);
650 MemoryContextSwitchTo(oldcontext);
652 return 0; /* return value does not matter */
657 * errmsg_internal --- add a primary error message text to the current error
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.
665 errmsg_internal(const char *fmt,...)
667 ErrorData *edata = &errordata[errordata_stack_depth];
668 MemoryContext oldcontext;
672 oldcontext = MemoryContextSwitchTo(ErrorContext);
674 EVALUATE_MESSAGE(message, false);
676 MemoryContextSwitchTo(oldcontext);
678 return 0; /* return value does not matter */
683 * errdetail --- add a detail error message text to the current error
686 errdetail(const char *fmt,...)
688 ErrorData *edata = &errordata[errordata_stack_depth];
689 MemoryContext oldcontext;
693 oldcontext = MemoryContextSwitchTo(ErrorContext);
695 EVALUATE_MESSAGE(detail, false);
697 MemoryContextSwitchTo(oldcontext);
699 return 0; /* return value does not matter */
704 * errhint --- add a hint error message text to the current error
707 errhint(const char *fmt,...)
709 ErrorData *edata = &errordata[errordata_stack_depth];
710 MemoryContext oldcontext;
714 oldcontext = MemoryContextSwitchTo(ErrorContext);
716 EVALUATE_MESSAGE(hint, false);
718 MemoryContextSwitchTo(oldcontext);
720 return 0; /* return value does not matter */
725 * errcontext --- add a context error message text to the current error
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
732 errcontext(const char *fmt,...)
734 ErrorData *edata = &errordata[errordata_stack_depth];
735 MemoryContext oldcontext;
739 oldcontext = MemoryContextSwitchTo(ErrorContext);
741 EVALUATE_MESSAGE(context, true);
743 MemoryContextSwitchTo(oldcontext);
745 return 0; /* return value does not matter */
750 * errfunction --- add reporting function name to the current error
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.
757 errfunction(const char *funcname)
759 ErrorData *edata = &errordata[errordata_stack_depth];
761 /* we don't bother incrementing recursion_depth */
764 edata->funcname = funcname;
765 edata->show_funcname = true;
767 return 0; /* return value does not matter */
771 * errposition --- add cursor position to the current error
774 errposition(int cursorpos)
776 ErrorData *edata = &errordata[errordata_stack_depth];
778 /* we don't bother incrementing recursion_depth */
781 edata->cursorpos = cursorpos;
783 return 0; /* return value does not matter */
787 * internalerrposition --- add internal cursor position to the current error
790 internalerrposition(int cursorpos)
792 ErrorData *edata = &errordata[errordata_stack_depth];
794 /* we don't bother incrementing recursion_depth */
797 edata->internalpos = cursorpos;
799 return 0; /* return value does not matter */
803 * internalerrquery --- add internal query text to the current error
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.
810 internalerrquery(const char *query)
812 ErrorData *edata = &errordata[errordata_stack_depth];
814 /* we don't bother incrementing recursion_depth */
817 if (edata->internalquery)
819 pfree(edata->internalquery);
820 edata->internalquery = NULL;
824 edata->internalquery = MemoryContextStrdup(ErrorContext, query);
826 return 0; /* return value does not matter */
830 * geterrposition --- return the currently set error position (0 if none)
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.
838 ErrorData *edata = &errordata[errordata_stack_depth];
840 /* we don't bother incrementing recursion_depth */
843 return edata->cursorpos;
847 * getinternalerrposition --- same for internal error position
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.
853 getinternalerrposition(void)
855 ErrorData *edata = &errordata[errordata_stack_depth];
857 /* we don't bother incrementing recursion_depth */
860 return edata->internalpos;
865 * elog_finish --- finish up for old-style API
867 * The elog() macro already called errstart, but with ERROR rather than
871 elog_finish(int elevel, const char *fmt,...)
873 ErrorData *edata = &errordata[errordata_stack_depth];
874 MemoryContext oldcontext;
879 * We need to redo errstart() because the elog macro had to call it
882 errordata_stack_depth--;
883 errno = edata->saved_errno;
884 if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname))
885 return; /* nothing to do */
888 * Format error message just like errmsg().
891 oldcontext = MemoryContextSwitchTo(ErrorContext);
893 EVALUATE_MESSAGE(message, false);
895 MemoryContextSwitchTo(oldcontext);
899 * And let errfinish() finish up.
905 * Actual output of the top-of-stack error message
907 * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
908 * if the error is caught by somebody). For all other severity levels this
909 * is called by errfinish.
912 EmitErrorReport(void)
914 ErrorData *edata = &errordata[errordata_stack_depth];
915 MemoryContext oldcontext;
919 oldcontext = MemoryContextSwitchTo(ErrorContext);
921 /* Send to server log, if enabled */
922 if (edata->output_to_server)
923 send_message_to_server_log(edata);
925 /* Send to client, if enabled */
926 if (edata->output_to_client)
927 send_message_to_frontend(edata);
929 MemoryContextSwitchTo(oldcontext);
934 * CopyErrorData --- obtain a copy of the topmost error stack entry
936 * This is only for use in error handler code. The data is copied into the
937 * current memory context, so callers should always switch away from
938 * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
943 ErrorData *edata = &errordata[errordata_stack_depth];
947 * we don't increment recursion_depth because out-of-memory here does
948 * not indicate a problem within the error subsystem.
952 Assert(CurrentMemoryContext != ErrorContext);
954 /* Copy the struct itself */
955 newedata = (ErrorData *) palloc(sizeof(ErrorData));
956 memcpy(newedata, edata, sizeof(ErrorData));
958 /* Make copies of separately-allocated fields */
959 if (newedata->message)
960 newedata->message = pstrdup(newedata->message);
961 if (newedata->detail)
962 newedata->detail = pstrdup(newedata->detail);
964 newedata->hint = pstrdup(newedata->hint);
965 if (newedata->context)
966 newedata->context = pstrdup(newedata->context);
967 if (newedata->internalquery)
968 newedata->internalquery = pstrdup(newedata->internalquery);
974 * FreeErrorData --- free the structure returned by CopyErrorData.
976 * Error handlers should use this in preference to assuming they know all
977 * the separately-allocated fields.
980 FreeErrorData(ErrorData *edata)
983 pfree(edata->message);
985 pfree(edata->detail);
989 pfree(edata->context);
990 if (edata->internalquery)
991 pfree(edata->internalquery);
996 * FlushErrorState --- flush the error state after error recovery
998 * This should be called by an error handler after it's done processing
999 * the error; or as soon as it's done CopyErrorData, if it intends to
1000 * do stuff that is likely to provoke another error. You are not "out" of
1001 * the error subsystem until you have done this.
1004 FlushErrorState(void)
1007 * Reset stack to empty. The only case where it would be more than
1008 * one deep is if we serviced an error that interrupted construction
1009 * of another message. We assume control escaped out of that message
1010 * construction and won't ever go back.
1012 errordata_stack_depth = -1;
1013 recursion_depth = 0;
1014 /* Delete all data in ErrorContext */
1015 MemoryContextResetAndDeleteChildren(ErrorContext);
1019 * ReThrowError --- re-throw a previously copied error
1021 * A handler can do CopyErrorData/FlushErrorState to get out of the error
1022 * subsystem, then do some processing, and finally ReThrowError to re-throw
1023 * the original error. This is slower than just PG_RE_THROW() but should
1024 * be used if the "some processing" is likely to incur another error.
1027 ReThrowError(ErrorData *edata)
1029 ErrorData *newedata;
1031 Assert(edata->elevel == ERROR);
1033 /* Push the data back into the error context */
1035 MemoryContextSwitchTo(ErrorContext);
1037 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1040 * Wups, stack not big enough. We treat this as a PANIC condition
1041 * because it suggests an infinite loop of errors during error
1044 errordata_stack_depth = -1; /* make room on stack */
1045 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1048 newedata = &errordata[errordata_stack_depth];
1049 memcpy(newedata, edata, sizeof(ErrorData));
1051 /* Make copies of separately-allocated fields */
1052 if (newedata->message)
1053 newedata->message = pstrdup(newedata->message);
1054 if (newedata->detail)
1055 newedata->detail = pstrdup(newedata->detail);
1057 newedata->hint = pstrdup(newedata->hint);
1058 if (newedata->context)
1059 newedata->context = pstrdup(newedata->context);
1060 if (newedata->internalquery)
1061 newedata->internalquery = pstrdup(newedata->internalquery);
1068 * Initialization of error output file
1076 if (OutputFileName[0])
1079 * A debug-output file name was given.
1081 * Make sure we can write the file, and find out if it's a tty.
1083 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
1086 (errcode_for_file_access(),
1087 errmsg("could not open file \"%s\": %m", OutputFileName)));
1092 * Redirect our stderr to the debug output file.
1094 if (!freopen(OutputFileName, "a", stderr))
1096 (errcode_for_file_access(),
1097 errmsg("could not reopen file \"%s\" as stderr: %m",
1101 * If the file is a tty and we're running under the postmaster,
1102 * try to send stdout there as well (if it isn't a tty then stderr
1103 * will block out stdout, so we may as well let stdout go wherever
1104 * it was going before).
1106 if (istty && IsUnderPostmaster)
1107 if (!freopen(OutputFileName, "a", stdout))
1109 (errcode_for_file_access(),
1110 errmsg("could not reopen file \"%s\" as stdout: %m",
1119 #ifndef PG_SYSLOG_LIMIT
1120 #define PG_SYSLOG_LIMIT 128
1124 * Write a message line to syslog if the syslog option is set.
1126 * Our problem here is that many syslog implementations don't handle
1127 * long messages in an acceptable manner. While this function doesn't
1128 * help that fact, it does work around by splitting up messages into
1132 write_syslog(int level, const char *line)
1134 static bool openlog_done = false;
1135 static unsigned long seq = 0;
1136 static int syslog_fac = LOG_LOCAL0;
1138 int len = strlen(line);
1142 if (pg_strcasecmp(Syslog_facility, "LOCAL0") == 0)
1143 syslog_fac = LOG_LOCAL0;
1144 if (pg_strcasecmp(Syslog_facility, "LOCAL1") == 0)
1145 syslog_fac = LOG_LOCAL1;
1146 if (pg_strcasecmp(Syslog_facility, "LOCAL2") == 0)
1147 syslog_fac = LOG_LOCAL2;
1148 if (pg_strcasecmp(Syslog_facility, "LOCAL3") == 0)
1149 syslog_fac = LOG_LOCAL3;
1150 if (pg_strcasecmp(Syslog_facility, "LOCAL4") == 0)
1151 syslog_fac = LOG_LOCAL4;
1152 if (pg_strcasecmp(Syslog_facility, "LOCAL5") == 0)
1153 syslog_fac = LOG_LOCAL5;
1154 if (pg_strcasecmp(Syslog_facility, "LOCAL6") == 0)
1155 syslog_fac = LOG_LOCAL6;
1156 if (pg_strcasecmp(Syslog_facility, "LOCAL7") == 0)
1157 syslog_fac = LOG_LOCAL7;
1158 openlog(Syslog_ident, LOG_PID | LOG_NDELAY | LOG_NOWAIT, syslog_fac);
1159 openlog_done = true;
1163 * We add a sequence number to each log message to suppress "same"
1168 /* divide into multiple syslog() calls if message is too long */
1169 /* or if the message contains embedded NewLine(s) '\n' */
1170 if (len > PG_SYSLOG_LIMIT || strchr(line, '\n') != NULL)
1176 char buf[PG_SYSLOG_LIMIT + 1];
1180 /* if we start at a newline, move ahead one char */
1181 if (line[0] == '\n')
1188 strncpy(buf, line, PG_SYSLOG_LIMIT);
1189 buf[PG_SYSLOG_LIMIT] = '\0';
1190 if (strchr(buf, '\n') != NULL)
1191 *strchr(buf, '\n') = '\0';
1193 buflen = strlen(buf);
1195 /* trim to multibyte letter boundary */
1196 buflen = pg_mbcliplen(buf, buflen, buflen);
1201 /* already word boundary? */
1202 if (!isspace((unsigned char) line[buflen]) &&
1203 line[buflen] != '\0')
1205 /* try to divide at word boundary */
1207 while (i > 0 && !isspace((unsigned char) buf[i]))
1210 if (i > 0) /* else couldn't divide word boundary */
1219 syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1226 /* message short enough */
1227 syslog(level, "[%lu] %s", seq, line);
1230 #endif /* HAVE_SYSLOG */
1233 * Write a message line to the windows event log
1236 write_eventlog(int level, const char *line)
1238 static HANDLE evtHandle = INVALID_HANDLE_VALUE;
1240 if (evtHandle == INVALID_HANDLE_VALUE)
1242 evtHandle = RegisterEventSource(NULL, "PostgreSQL");
1243 if (evtHandle == NULL)
1245 evtHandle = INVALID_HANDLE_VALUE;
1250 ReportEvent(evtHandle,
1253 0, /* All events are Id 0 */
1263 * Format tag info for log lines; append to the provided buffer.
1266 log_line_prefix(StringInfo buf)
1268 /* static counter for line numbers */
1269 static long log_line_number = 0;
1271 /* has counter been reset in current process? */
1272 static int log_my_pid = 0;
1278 * This is one of the few places where we'd rather not inherit a
1279 * static variable's value from the postmaster. But since we will,
1280 * reset it when MyProcPid changes.
1282 if (log_my_pid != MyProcPid)
1284 log_line_number = 0;
1285 log_my_pid = MyProcPid;
1289 if (Log_line_prefix == NULL)
1290 return; /* in case guc hasn't run yet */
1292 format_len = strlen(Log_line_prefix);
1294 for (i = 0; i < format_len; i++)
1296 if (Log_line_prefix[i] != '%')
1298 /* literal char, just copy */
1299 appendStringInfoChar(buf, Log_line_prefix[i]);
1302 /* go to char after '%' */
1304 if (i >= format_len)
1306 /* format error - ignore it */
1310 /* process the option */
1311 switch (Log_line_prefix[i])
1316 const char *username = MyProcPort->user_name;
1318 if (username == NULL || *username == '\0')
1319 username = gettext("[unknown]");
1320 appendStringInfo(buf, "%s", username);
1326 const char *dbname = MyProcPort->database_name;
1328 if (dbname == NULL || *dbname == '\0')
1329 dbname = gettext("[unknown]");
1330 appendStringInfo(buf, "%s", dbname);
1336 appendStringInfo(buf, "%lx.%lx",
1337 (long) (MyProcPort->session_start.tv_sec),
1342 appendStringInfo(buf, "%ld", (long) MyProcPid);
1345 appendStringInfo(buf, "%ld", log_line_number);
1350 * Note: for %t and %s we deliberately use the C
1351 * library's strftime/localtime, and not the
1352 * equivalent functions from src/timezone. This
1353 * ensures that all backends will report log entries
1354 * in the same timezone, namely whatever C-library
1355 * setting they inherit from the postmaster. If we
1356 * used src/timezone then local settings of the
1357 * TimeZone GUC variable would confuse the log.
1359 time_t stamp_time = time(NULL);
1362 strftime(strfbuf, sizeof(strfbuf),
1363 "%Y-%m-%d %H:%M:%S %Z",
1364 localtime(&stamp_time));
1365 appendStringInfoString(buf, strfbuf);
1371 time_t stamp_time = MyProcPort->session_start.tv_sec;
1374 strftime(strfbuf, sizeof(strfbuf),
1375 "%Y-%m-%d %H:%M:%S %Z",
1376 localtime(&stamp_time));
1377 appendStringInfoString(buf, strfbuf);
1382 appendStringInfo(buf, "%s", MyProcPort->commandTag);
1387 appendStringInfo(buf, "%s", MyProcPort->remote_host);
1388 if (strlen(MyProcPort->remote_port) > 0)
1389 appendStringInfo(buf, "(%s)",
1390 MyProcPort->remote_port);
1394 /* in postmaster and friends, stop if %x is seen */
1395 /* in a backend, just ignore */
1396 if (MyProcPort == NULL)
1400 appendStringInfoChar(buf, '%');
1403 /* format error - ignore it */
1411 * Write error report to server's log
1414 send_message_to_server_log(ErrorData *edata)
1418 initStringInfo(&buf);
1420 log_line_prefix(&buf);
1421 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
1423 if (Log_error_verbosity >= PGERROR_VERBOSE)
1425 /* unpack MAKE_SQLSTATE code */
1430 ssval = edata->sqlerrcode;
1431 for (i = 0; i < 5; i++)
1433 tbuf[i] = PGUNSIXBIT(ssval);
1437 appendStringInfo(&buf, "%s: ", tbuf);
1441 append_with_tabs(&buf, edata->message);
1443 append_with_tabs(&buf, gettext("missing error text"));
1445 if (edata->cursorpos > 0)
1446 appendStringInfo(&buf, gettext(" at character %d"),
1448 else if (edata->internalpos > 0)
1449 appendStringInfo(&buf, gettext(" at character %d"),
1450 edata->internalpos);
1452 appendStringInfoChar(&buf, '\n');
1454 if (Log_error_verbosity >= PGERROR_DEFAULT)
1458 log_line_prefix(&buf);
1459 appendStringInfoString(&buf, gettext("DETAIL: "));
1460 append_with_tabs(&buf, edata->detail);
1461 appendStringInfoChar(&buf, '\n');
1465 log_line_prefix(&buf);
1466 appendStringInfoString(&buf, gettext("HINT: "));
1467 append_with_tabs(&buf, edata->hint);
1468 appendStringInfoChar(&buf, '\n');
1470 if (edata->internalquery)
1472 log_line_prefix(&buf);
1473 appendStringInfoString(&buf, gettext("QUERY: "));
1474 append_with_tabs(&buf, edata->internalquery);
1475 appendStringInfoChar(&buf, '\n');
1479 log_line_prefix(&buf);
1480 appendStringInfoString(&buf, gettext("CONTEXT: "));
1481 append_with_tabs(&buf, edata->context);
1482 appendStringInfoChar(&buf, '\n');
1484 if (Log_error_verbosity >= PGERROR_VERBOSE)
1486 /* assume no newlines in funcname or filename... */
1487 if (edata->funcname && edata->filename)
1489 log_line_prefix(&buf);
1490 appendStringInfo(&buf, gettext("LOCATION: %s, %s:%d\n"),
1491 edata->funcname, edata->filename,
1494 else if (edata->filename)
1496 log_line_prefix(&buf);
1497 appendStringInfo(&buf, gettext("LOCATION: %s:%d\n"),
1498 edata->filename, edata->lineno);
1504 * If the user wants the query that generated this error logged, do
1507 if (edata->elevel >= log_min_error_statement && debug_query_string != NULL)
1509 log_line_prefix(&buf);
1510 appendStringInfoString(&buf, gettext("STATEMENT: "));
1511 append_with_tabs(&buf, debug_query_string);
1512 appendStringInfoChar(&buf, '\n');
1517 /* Write to syslog, if enabled */
1518 if (Log_destination & LOG_DESTINATION_SYSLOG)
1522 switch (edata->elevel)
1529 syslog_level = LOG_DEBUG;
1534 syslog_level = LOG_INFO;
1538 syslog_level = LOG_NOTICE;
1541 syslog_level = LOG_WARNING;
1544 syslog_level = LOG_ERR;
1548 syslog_level = LOG_CRIT;
1552 write_syslog(syslog_level, buf.data);
1554 #endif /* HAVE_SYSLOG */
1556 if (Log_destination & LOG_DESTINATION_EVENTLOG)
1560 switch (edata->elevel)
1571 eventlog_level = EVENTLOG_INFORMATION_TYPE;
1574 eventlog_level = EVENTLOG_WARNING_TYPE;
1580 eventlog_level = EVENTLOG_ERROR_TYPE;
1583 write_eventlog(eventlog_level, buf.data);
1586 /* Write to stderr, if enabled */
1587 if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == Debug)
1588 fprintf(stderr, "%s", buf.data);
1590 /* If in the syslogger process, try to write messages direct to file */
1592 write_syslogger_file(buf.data, buf.len);
1599 * Write error report to client
1602 send_message_to_frontend(ErrorData *edata)
1604 StringInfoData msgbuf;
1606 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
1607 pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
1609 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
1611 /* New style with separate fields */
1616 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
1617 pq_sendstring(&msgbuf, error_severity(edata->elevel));
1619 /* unpack MAKE_SQLSTATE code */
1620 ssval = edata->sqlerrcode;
1621 for (i = 0; i < 5; i++)
1623 tbuf[i] = PGUNSIXBIT(ssval);
1628 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
1629 pq_sendstring(&msgbuf, tbuf);
1631 /* M field is required per protocol, so always send something */
1632 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
1634 pq_sendstring(&msgbuf, edata->message);
1636 pq_sendstring(&msgbuf, gettext("missing error text"));
1640 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
1641 pq_sendstring(&msgbuf, edata->detail);
1646 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
1647 pq_sendstring(&msgbuf, edata->hint);
1652 pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
1653 pq_sendstring(&msgbuf, edata->context);
1656 if (edata->cursorpos > 0)
1658 snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
1659 pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
1660 pq_sendstring(&msgbuf, tbuf);
1663 if (edata->internalpos > 0)
1665 snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
1666 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
1667 pq_sendstring(&msgbuf, tbuf);
1670 if (edata->internalquery)
1672 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
1673 pq_sendstring(&msgbuf, edata->internalquery);
1676 if (edata->filename)
1678 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
1679 pq_sendstring(&msgbuf, edata->filename);
1682 if (edata->lineno > 0)
1684 snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
1685 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
1686 pq_sendstring(&msgbuf, tbuf);
1689 if (edata->funcname)
1691 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
1692 pq_sendstring(&msgbuf, edata->funcname);
1695 pq_sendbyte(&msgbuf, '\0'); /* terminator */
1699 /* Old style --- gin up a backwards-compatible message */
1702 initStringInfo(&buf);
1704 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
1706 if (edata->show_funcname && edata->funcname)
1707 appendStringInfo(&buf, "%s: ", edata->funcname);
1710 appendStringInfoString(&buf, edata->message);
1712 appendStringInfoString(&buf, gettext("missing error text"));
1714 if (edata->cursorpos > 0)
1715 appendStringInfo(&buf, gettext(" at character %d"),
1717 else if (edata->internalpos > 0)
1718 appendStringInfo(&buf, gettext(" at character %d"),
1719 edata->internalpos);
1721 appendStringInfoChar(&buf, '\n');
1723 pq_sendstring(&msgbuf, buf.data);
1728 pq_endmessage(&msgbuf);
1731 * This flush is normally not necessary, since postgres.c will flush
1732 * out waiting data when control returns to the main loop. But it
1733 * seems best to leave it here, so that the client has some clue what
1734 * happened if the backend dies before getting back to the main loop
1735 * ... error/notice messages should not be a performance-critical path
1736 * anyway, so an extra flush won't hurt much ...
1743 * Support routines for formatting error messages.
1748 * expand_fmt_string --- process special format codes in a format string
1750 * We must replace %m with the appropriate strerror string, since vsnprintf
1751 * won't know what to do with it.
1753 * The result is a palloc'd string.
1756 expand_fmt_string(const char *fmt, ErrorData *edata)
1761 initStringInfo(&buf);
1763 for (cp = fmt; *cp; cp++)
1765 if (cp[0] == '%' && cp[1] != '\0')
1771 * Replace %m by system error string. If there are any
1772 * %'s in the string, we'd better double them so that
1773 * vsnprintf won't misinterpret.
1777 cp2 = useful_strerror(edata->saved_errno);
1781 appendStringInfoCharMacro(&buf, '%');
1782 appendStringInfoCharMacro(&buf, *cp2);
1787 /* copy % and next char --- this avoids trouble with %%m */
1788 appendStringInfoCharMacro(&buf, '%');
1789 appendStringInfoCharMacro(&buf, *cp);
1793 appendStringInfoCharMacro(&buf, *cp);
1801 * A slightly cleaned-up version of strerror()
1804 useful_strerror(int errnum)
1806 /* this buffer is only used if errno has a bogus value */
1807 static char errorstr_buf[48];
1811 /* Winsock error code range, per WinError.h */
1812 if (errnum >= 10000 && errnum <= 11999)
1813 return pgwin32_socket_strerror(errnum);
1815 str = strerror(errnum);
1818 * Some strerror()s return an empty string for out-of-range errno.
1819 * This is ANSI C spec compliant, but not exactly useful.
1821 if (str == NULL || *str == '\0')
1824 * translator: This string will be truncated at 47 characters
1827 snprintf(errorstr_buf, sizeof(errorstr_buf),
1828 gettext("operating system error %d"), errnum);
1837 * error_severity --- get localized string representing elevel
1840 error_severity(int elevel)
1851 prefix = gettext("DEBUG");
1855 prefix = gettext("LOG");
1858 prefix = gettext("INFO");
1861 prefix = gettext("NOTICE");
1864 prefix = gettext("WARNING");
1867 prefix = gettext("ERROR");
1870 prefix = gettext("FATAL");
1873 prefix = gettext("PANIC");
1887 * Append the string to the StringInfo buffer, inserting a tab after any
1891 append_with_tabs(StringInfo buf, const char *str)
1895 while ((ch = *str++) != '\0')
1897 appendStringInfoCharMacro(buf, ch);
1899 appendStringInfoCharMacro(buf, '\t');
1905 * Write errors to stderr (or by equal means when stderr is
1906 * not available). Used before ereport/elog can be used
1907 * safely (memory context, GUC load etc)
1910 write_stderr(const char *fmt,...)
1918 /* On Unix, we just fprintf to stderr */
1919 vfprintf(stderr, fmt, ap);
1923 * On Win32, we print to stderr if running on a console, or write to
1924 * eventlog if running as a service
1926 if (pgwin32_is_service()) /* Running as a service */
1928 char errbuf[2048]; /* Arbitrary size? */
1930 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
1932 write_eventlog(EVENTLOG_ERROR_TYPE, errbuf);
1935 /* Not running as service, write to stderr */
1936 vfprintf(stderr, fmt, ap);