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-2005, 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.156 2005/02/22 04:37:38 momjian 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 */ \
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_start --- startup for old-style API
867 * All that we do here is stash the hidden filename/lineno/funcname
868 * arguments into a stack entry.
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.)
876 elog_start(const char *filename, int lineno, const char *funcname)
880 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
883 * Wups, stack not big enough. We treat this as a PANIC condition
884 * because it suggests an infinite loop of errors during error
887 errordata_stack_depth = -1; /* make room on stack */
888 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
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;
900 * elog_finish --- finish up for old-style API
903 elog_finish(int elevel, const char *fmt,...)
905 ErrorData *edata = &errordata[errordata_stack_depth];
906 MemoryContext oldcontext;
911 * Do errstart() to see if we actually want to report the message.
913 errordata_stack_depth--;
914 errno = edata->saved_errno;
915 if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname))
916 return; /* nothing to do */
919 * Format error message just like errmsg().
922 oldcontext = MemoryContextSwitchTo(ErrorContext);
924 EVALUATE_MESSAGE(message, false);
926 MemoryContextSwitchTo(oldcontext);
930 * And let errfinish() finish up.
936 * Actual output of the top-of-stack error message
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.
943 EmitErrorReport(void)
945 ErrorData *edata = &errordata[errordata_stack_depth];
946 MemoryContext oldcontext;
950 oldcontext = MemoryContextSwitchTo(ErrorContext);
952 /* Send to server log, if enabled */
953 if (edata->output_to_server)
954 send_message_to_server_log(edata);
956 /* Send to client, if enabled */
957 if (edata->output_to_client)
958 send_message_to_frontend(edata);
960 MemoryContextSwitchTo(oldcontext);
965 * CopyErrorData --- obtain a copy of the topmost error stack entry
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.
974 ErrorData *edata = &errordata[errordata_stack_depth];
978 * we don't increment recursion_depth because out-of-memory here does
979 * not indicate a problem within the error subsystem.
983 Assert(CurrentMemoryContext != ErrorContext);
985 /* Copy the struct itself */
986 newedata = (ErrorData *) palloc(sizeof(ErrorData));
987 memcpy(newedata, edata, sizeof(ErrorData));
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);
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);
1005 * FreeErrorData --- free the structure returned by CopyErrorData.
1007 * Error handlers should use this in preference to assuming they know all
1008 * the separately-allocated fields.
1011 FreeErrorData(ErrorData *edata)
1014 pfree(edata->message);
1016 pfree(edata->detail);
1020 pfree(edata->context);
1021 if (edata->internalquery)
1022 pfree(edata->internalquery);
1027 * FlushErrorState --- flush the error state after error recovery
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.
1035 FlushErrorState(void)
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.
1043 errordata_stack_depth = -1;
1044 recursion_depth = 0;
1045 /* Delete all data in ErrorContext */
1046 MemoryContextResetAndDeleteChildren(ErrorContext);
1050 * ReThrowError --- re-throw a previously copied error
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.
1058 ReThrowError(ErrorData *edata)
1060 ErrorData *newedata;
1062 Assert(edata->elevel == ERROR);
1064 /* Push the data back into the error context */
1066 MemoryContextSwitchTo(ErrorContext);
1068 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1071 * Wups, stack not big enough. We treat this as a PANIC condition
1072 * because it suggests an infinite loop of errors during error
1075 errordata_stack_depth = -1; /* make room on stack */
1076 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1079 newedata = &errordata[errordata_stack_depth];
1080 memcpy(newedata, edata, sizeof(ErrorData));
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);
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);
1099 * Initialization of error output file
1107 if (OutputFileName[0])
1110 * A debug-output file name was given.
1112 * Make sure we can write the file, and find out if it's a tty.
1114 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
1117 (errcode_for_file_access(),
1118 errmsg("could not open file \"%s\": %m", OutputFileName)));
1123 * Redirect our stderr to the debug output file.
1125 if (!freopen(OutputFileName, "a", stderr))
1127 (errcode_for_file_access(),
1128 errmsg("could not reopen file \"%s\" as stderr: %m",
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).
1137 if (istty && IsUnderPostmaster)
1138 if (!freopen(OutputFileName, "a", stdout))
1140 (errcode_for_file_access(),
1141 errmsg("could not reopen file \"%s\" as stdout: %m",
1150 #ifndef PG_SYSLOG_LIMIT
1151 #define PG_SYSLOG_LIMIT 128
1155 * Write a message line to syslog if the syslog option is set.
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
1163 write_syslog(int level, const char *line)
1165 static bool openlog_done = false;
1166 static unsigned long seq = 0;
1167 static int syslog_fac = LOG_LOCAL0;
1169 int len = strlen(line);
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;
1194 * We add a sequence number to each log message to suppress "same"
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)
1207 char buf[PG_SYSLOG_LIMIT + 1];
1211 /* if we start at a newline, move ahead one char */
1212 if (line[0] == '\n')
1219 strncpy(buf, line, PG_SYSLOG_LIMIT);
1220 buf[PG_SYSLOG_LIMIT] = '\0';
1221 if (strchr(buf, '\n') != NULL)
1222 *strchr(buf, '\n') = '\0';
1224 buflen = strlen(buf);
1226 /* trim to multibyte letter boundary */
1227 buflen = pg_mbcliplen(buf, buflen, buflen);
1232 /* already word boundary? */
1233 if (!isspace((unsigned char) line[buflen]) &&
1234 line[buflen] != '\0')
1236 /* try to divide at word boundary */
1238 while (i > 0 && !isspace((unsigned char) buf[i]))
1241 if (i > 0) /* else couldn't divide word boundary */
1250 syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1257 /* message short enough */
1258 syslog(level, "[%lu] %s", seq, line);
1261 #endif /* HAVE_SYSLOG */
1264 * Write a message line to the windows event log
1267 write_eventlog(int level, const char *line)
1269 static HANDLE evtHandle = INVALID_HANDLE_VALUE;
1271 if (evtHandle == INVALID_HANDLE_VALUE)
1273 evtHandle = RegisterEventSource(NULL, "PostgreSQL");
1274 if (evtHandle == NULL)
1276 evtHandle = INVALID_HANDLE_VALUE;
1281 ReportEvent(evtHandle,
1284 0, /* All events are Id 0 */
1294 * Format tag info for log lines; append to the provided buffer.
1297 log_line_prefix(StringInfo buf)
1299 /* static counter for line numbers */
1300 static long log_line_number = 0;
1302 /* has counter been reset in current process? */
1303 static int log_my_pid = 0;
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.
1313 if (log_my_pid != MyProcPid)
1315 log_line_number = 0;
1316 log_my_pid = MyProcPid;
1320 if (Log_line_prefix == NULL)
1321 return; /* in case guc hasn't run yet */
1323 format_len = strlen(Log_line_prefix);
1325 for (i = 0; i < format_len; i++)
1327 if (Log_line_prefix[i] != '%')
1329 /* literal char, just copy */
1330 appendStringInfoChar(buf, Log_line_prefix[i]);
1333 /* go to char after '%' */
1335 if (i >= format_len)
1337 /* format error - ignore it */
1341 /* process the option */
1342 switch (Log_line_prefix[i])
1347 const char *username = MyProcPort->user_name;
1349 if (username == NULL || *username == '\0')
1350 username = _("[unknown]");
1351 appendStringInfo(buf, "%s", username);
1357 const char *dbname = MyProcPort->database_name;
1359 if (dbname == NULL || *dbname == '\0')
1360 dbname = _("[unknown]");
1361 appendStringInfo(buf, "%s", dbname);
1367 appendStringInfo(buf, "%lx.%x",
1368 (long) (MyProcPort->session_start.tv_sec),
1373 appendStringInfo(buf, "%d", MyProcPid);
1376 appendStringInfo(buf, "%ld", log_line_number);
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.
1390 time_t stamp_time = time(NULL);
1393 strftime(strfbuf, sizeof(strfbuf),
1394 /* Win32 timezone names are too long so don't print them. */
1396 "%Y-%m-%d %H:%M:%S %Z",
1398 "%Y-%m-%d %H:%M:%S",
1400 localtime(&stamp_time));
1401 appendStringInfoString(buf, strfbuf);
1407 time_t stamp_time = MyProcPort->session_start.tv_sec;
1410 strftime(strfbuf, sizeof(strfbuf),
1411 "%Y-%m-%d %H:%M:%S %Z",
1412 localtime(&stamp_time));
1413 appendStringInfoString(buf, strfbuf);
1418 appendStringInfo(buf, "%s", MyProcPort->commandTag);
1423 appendStringInfo(buf, "%s", MyProcPort->remote_host);
1424 if (strlen(MyProcPort->remote_port) > 0)
1425 appendStringInfo(buf, "(%s)",
1426 MyProcPort->remote_port);
1430 /* in postmaster and friends, stop if %q is seen */
1431 /* in a backend, just ignore */
1432 if (MyProcPort == NULL)
1438 if (IsTransactionState())
1439 appendStringInfo(buf, "%u", GetTopTransactionId());
1441 appendStringInfo(buf, "%u", InvalidTransactionId);
1445 appendStringInfoChar(buf, '%');
1448 /* format error - ignore it */
1456 * Write error report to server's log
1459 send_message_to_server_log(ErrorData *edata)
1463 initStringInfo(&buf);
1465 log_line_prefix(&buf);
1466 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
1468 if (Log_error_verbosity >= PGERROR_VERBOSE)
1470 /* unpack MAKE_SQLSTATE code */
1475 ssval = edata->sqlerrcode;
1476 for (i = 0; i < 5; i++)
1478 tbuf[i] = PGUNSIXBIT(ssval);
1482 appendStringInfo(&buf, "%s: ", tbuf);
1486 append_with_tabs(&buf, edata->message);
1488 append_with_tabs(&buf, _("missing error text"));
1490 if (edata->cursorpos > 0)
1491 appendStringInfo(&buf, _(" at character %d"),
1493 else if (edata->internalpos > 0)
1494 appendStringInfo(&buf, _(" at character %d"),
1495 edata->internalpos);
1497 appendStringInfoChar(&buf, '\n');
1499 if (Log_error_verbosity >= PGERROR_DEFAULT)
1503 log_line_prefix(&buf);
1504 appendStringInfoString(&buf, _("DETAIL: "));
1505 append_with_tabs(&buf, edata->detail);
1506 appendStringInfoChar(&buf, '\n');
1510 log_line_prefix(&buf);
1511 appendStringInfoString(&buf, _("HINT: "));
1512 append_with_tabs(&buf, edata->hint);
1513 appendStringInfoChar(&buf, '\n');
1515 if (edata->internalquery)
1517 log_line_prefix(&buf);
1518 appendStringInfoString(&buf, _("QUERY: "));
1519 append_with_tabs(&buf, edata->internalquery);
1520 appendStringInfoChar(&buf, '\n');
1524 log_line_prefix(&buf);
1525 appendStringInfoString(&buf, _("CONTEXT: "));
1526 append_with_tabs(&buf, edata->context);
1527 appendStringInfoChar(&buf, '\n');
1529 if (Log_error_verbosity >= PGERROR_VERBOSE)
1531 /* assume no newlines in funcname or filename... */
1532 if (edata->funcname && edata->filename)
1534 log_line_prefix(&buf);
1535 appendStringInfo(&buf, _("LOCATION: %s, %s:%d\n"),
1536 edata->funcname, edata->filename,
1539 else if (edata->filename)
1541 log_line_prefix(&buf);
1542 appendStringInfo(&buf, _("LOCATION: %s:%d\n"),
1543 edata->filename, edata->lineno);
1549 * If the user wants the query that generated this error logged, do
1552 if (edata->elevel >= log_min_error_statement && debug_query_string != NULL)
1554 log_line_prefix(&buf);
1555 appendStringInfoString(&buf, _("STATEMENT: "));
1556 append_with_tabs(&buf, debug_query_string);
1557 appendStringInfoChar(&buf, '\n');
1562 /* Write to syslog, if enabled */
1563 if (Log_destination & LOG_DESTINATION_SYSLOG)
1567 switch (edata->elevel)
1574 syslog_level = LOG_DEBUG;
1579 syslog_level = LOG_INFO;
1583 syslog_level = LOG_NOTICE;
1586 syslog_level = LOG_WARNING;
1589 syslog_level = LOG_ERR;
1593 syslog_level = LOG_CRIT;
1597 write_syslog(syslog_level, buf.data);
1599 #endif /* HAVE_SYSLOG */
1601 if (Log_destination & LOG_DESTINATION_EVENTLOG)
1605 switch (edata->elevel)
1616 eventlog_level = EVENTLOG_INFORMATION_TYPE;
1619 eventlog_level = EVENTLOG_WARNING_TYPE;
1625 eventlog_level = EVENTLOG_ERROR_TYPE;
1628 write_eventlog(eventlog_level, buf.data);
1631 /* Write to stderr, if enabled */
1632 if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == Debug)
1633 fprintf(stderr, "%s", buf.data);
1635 /* If in the syslogger process, try to write messages direct to file */
1637 write_syslogger_file(buf.data, buf.len);
1644 * Write error report to client
1647 send_message_to_frontend(ErrorData *edata)
1649 StringInfoData msgbuf;
1651 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
1652 pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
1654 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
1656 /* New style with separate fields */
1661 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
1662 pq_sendstring(&msgbuf, error_severity(edata->elevel));
1664 /* unpack MAKE_SQLSTATE code */
1665 ssval = edata->sqlerrcode;
1666 for (i = 0; i < 5; i++)
1668 tbuf[i] = PGUNSIXBIT(ssval);
1673 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
1674 pq_sendstring(&msgbuf, tbuf);
1676 /* M field is required per protocol, so always send something */
1677 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
1679 pq_sendstring(&msgbuf, edata->message);
1681 pq_sendstring(&msgbuf, _("missing error text"));
1685 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
1686 pq_sendstring(&msgbuf, edata->detail);
1691 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
1692 pq_sendstring(&msgbuf, edata->hint);
1697 pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
1698 pq_sendstring(&msgbuf, edata->context);
1701 if (edata->cursorpos > 0)
1703 snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
1704 pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
1705 pq_sendstring(&msgbuf, tbuf);
1708 if (edata->internalpos > 0)
1710 snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
1711 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
1712 pq_sendstring(&msgbuf, tbuf);
1715 if (edata->internalquery)
1717 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
1718 pq_sendstring(&msgbuf, edata->internalquery);
1721 if (edata->filename)
1723 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
1724 pq_sendstring(&msgbuf, edata->filename);
1727 if (edata->lineno > 0)
1729 snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
1730 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
1731 pq_sendstring(&msgbuf, tbuf);
1734 if (edata->funcname)
1736 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
1737 pq_sendstring(&msgbuf, edata->funcname);
1740 pq_sendbyte(&msgbuf, '\0'); /* terminator */
1744 /* Old style --- gin up a backwards-compatible message */
1747 initStringInfo(&buf);
1749 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
1751 if (edata->show_funcname && edata->funcname)
1752 appendStringInfo(&buf, "%s: ", edata->funcname);
1755 appendStringInfoString(&buf, edata->message);
1757 appendStringInfoString(&buf, _("missing error text"));
1759 if (edata->cursorpos > 0)
1760 appendStringInfo(&buf, _(" at character %d"),
1762 else if (edata->internalpos > 0)
1763 appendStringInfo(&buf, _(" at character %d"),
1764 edata->internalpos);
1766 appendStringInfoChar(&buf, '\n');
1768 pq_sendstring(&msgbuf, buf.data);
1773 pq_endmessage(&msgbuf);
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 ...
1788 * Support routines for formatting error messages.
1793 * expand_fmt_string --- process special format codes in a format string
1795 * We must replace %m with the appropriate strerror string, since vsnprintf
1796 * won't know what to do with it.
1798 * The result is a palloc'd string.
1801 expand_fmt_string(const char *fmt, ErrorData *edata)
1806 initStringInfo(&buf);
1808 for (cp = fmt; *cp; cp++)
1810 if (cp[0] == '%' && cp[1] != '\0')
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.
1822 cp2 = useful_strerror(edata->saved_errno);
1826 appendStringInfoCharMacro(&buf, '%');
1827 appendStringInfoCharMacro(&buf, *cp2);
1832 /* copy % and next char --- this avoids trouble with %%m */
1833 appendStringInfoCharMacro(&buf, '%');
1834 appendStringInfoCharMacro(&buf, *cp);
1838 appendStringInfoCharMacro(&buf, *cp);
1846 * A slightly cleaned-up version of strerror()
1849 useful_strerror(int errnum)
1851 /* this buffer is only used if errno has a bogus value */
1852 static char errorstr_buf[48];
1856 /* Winsock error code range, per WinError.h */
1857 if (errnum >= 10000 && errnum <= 11999)
1858 return pgwin32_socket_strerror(errnum);
1860 str = strerror(errnum);
1863 * Some strerror()s return an empty string for out-of-range errno.
1864 * This is ANSI C spec compliant, but not exactly useful.
1866 if (str == NULL || *str == '\0')
1869 * translator: This string will be truncated at 47 characters
1872 snprintf(errorstr_buf, sizeof(errorstr_buf),
1873 _("operating system error %d"), errnum);
1882 * error_severity --- get localized string representing elevel
1885 error_severity(int elevel)
1896 prefix = _("DEBUG");
1906 prefix = _("NOTICE");
1909 prefix = _("WARNING");
1912 prefix = _("ERROR");
1915 prefix = _("FATAL");
1918 prefix = _("PANIC");
1932 * Append the string to the StringInfo buffer, inserting a tab after any
1936 append_with_tabs(StringInfo buf, const char *str)
1940 while ((ch = *str++) != '\0')
1942 appendStringInfoCharMacro(buf, ch);
1944 appendStringInfoCharMacro(buf, '\t');
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)
1955 write_stderr(const char *fmt,...)
1963 /* On Unix, we just fprintf to stderr */
1964 vfprintf(stderr, fmt, ap);
1968 * On Win32, we print to stderr if running on a console, or write to
1969 * eventlog if running as a service
1971 if (pgwin32_is_service()) /* Running as a service */
1973 char errbuf[2048]; /* Arbitrary size? */
1975 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
1977 write_eventlog(EVENTLOG_ERROR_TYPE, errbuf);
1980 /* Not running as service, write to stderr */
1981 vfprintf(stderr, fmt, ap);