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-2007, 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.190 2007/07/21 22:12:04 tgl Exp $
47 *-------------------------------------------------------------------------
60 #include "access/transam.h"
61 #include "access/xact.h"
62 #include "libpq/libpq.h"
63 #include "libpq/pqformat.h"
64 #include "mb/pg_wchar.h"
65 #include "miscadmin.h"
66 #include "postmaster/postmaster.h"
67 #include "postmaster/syslogger.h"
68 #include "storage/ipc.h"
69 #include "tcop/tcopprot.h"
70 #include "utils/memutils.h"
71 #include "utils/ps_status.h"
74 /* Global variables */
75 ErrorContextCallback *error_context_stack = NULL;
77 sigjmp_buf *PG_exception_stack = NULL;
79 extern bool redirection_done;
82 PGErrorVerbosity Log_error_verbosity = PGERROR_VERBOSE;
83 char *Log_line_prefix = NULL; /* format for extra log line info */
84 int Log_destination = LOG_DESTINATION_STDERR;
87 static bool openlog_done = false;
88 static char *syslog_ident = NULL;
89 static int syslog_facility = LOG_LOCAL0;
91 static void write_syslog(int level, const char *line);
95 static void write_eventlog(int level, const char *line);
98 /* We provide a small stack of ErrorData records for re-entrant cases */
99 #define ERRORDATA_STACK_SIZE 5
101 static ErrorData errordata[ERRORDATA_STACK_SIZE];
103 static int errordata_stack_depth = -1; /* index of topmost active frame */
105 static int recursion_depth = 0; /* to detect actual recursion */
108 /* Macro for checking errordata_stack_depth is reasonable */
109 #define CHECK_STACK_DEPTH() \
111 if (errordata_stack_depth < 0) \
113 errordata_stack_depth = -1; \
114 ereport(ERROR, (errmsg_internal("errstart was not called"))); \
119 static void log_line_prefix(StringInfo buf);
120 static void send_message_to_server_log(ErrorData *edata);
121 static void send_message_to_frontend(ErrorData *edata);
122 static char *expand_fmt_string(const char *fmt, ErrorData *edata);
123 static const char *useful_strerror(int errnum);
124 static const char *error_severity(int elevel);
125 static void append_with_tabs(StringInfo buf, const char *str);
126 static bool is_log_level_output(int elevel, int log_min_level);
127 static void write_pipe_chunks(int fd, char *data, int len);
131 * errstart --- begin an error-reporting cycle
133 * Create a stack entry and store the given parameters in it. Subsequently,
134 * errmsg() and perhaps other routines will be called to further populate
135 * the stack entry. Finally, errfinish() will be called to actually process
138 * Returns TRUE in normal case. Returns FALSE to short-circuit the error
139 * report (if it's a warning or lower and not to be reported anywhere).
142 errstart(int elevel, const char *filename, int lineno,
143 const char *funcname)
146 bool output_to_server;
147 bool output_to_client = false;
151 * Check some cases in which we want to promote an error into a more
152 * severe error. None of this logic applies for non-error messages.
157 * If we are inside a critical section, all errors become PANIC
158 * errors. See miscadmin.h.
160 if (CritSectionCount > 0)
164 * Check reasons for treating ERROR as FATAL:
166 * 1. we have no handler to pass the error to (implies we are in the
167 * postmaster or in backend startup).
169 * 2. ExitOnAnyError mode switch is set (initdb uses this).
171 * 3. the error occurred after proc_exit has begun to run. (It's
172 * proc_exit's responsibility to see that this doesn't turn into
173 * infinite recursion!)
177 if (PG_exception_stack == NULL ||
179 proc_exit_inprogress)
184 * If the error level is ERROR or more, errfinish is not going to
185 * return to caller; therefore, if there is any stacked error already
186 * in progress it will be lost. This is more or less okay, except we
187 * do not want to have a FATAL or PANIC error downgraded because the
188 * reporting process was interrupted by a lower-grade error. So check
189 * the stack and make sure we panic if panic is warranted.
191 for (i = 0; i <= errordata_stack_depth; i++)
192 elevel = Max(elevel, errordata[i].elevel);
196 * Now decide whether we need to process this report at all; if it's
197 * warning or less and not enabled for logging, just return FALSE without
198 * starting up any error logging machinery.
201 /* Determine whether message is enabled for server log output */
202 if (IsPostmasterEnvironment)
203 output_to_server = is_log_level_output(elevel, log_min_messages);
205 /* In bootstrap/standalone case, do not sort LOG out-of-order */
206 output_to_server = (elevel >= log_min_messages);
208 /* Determine whether message is enabled for client output */
209 if (whereToSendOutput == DestRemote && elevel != COMMERROR)
212 * client_min_messages is honored only after we complete the
213 * authentication handshake. This is required both for security
214 * reasons and because many clients can't handle NOTICE messages
215 * during authentication.
217 if (ClientAuthInProgress)
218 output_to_client = (elevel >= ERROR);
220 output_to_client = (elevel >= client_min_messages ||
224 /* Skip processing effort if non-error message will not be output */
225 if (elevel < ERROR && !output_to_server && !output_to_client)
229 * Okay, crank up a stack entry to store the info in.
232 if (recursion_depth++ > 0 && elevel >= ERROR)
235 * Ooops, error during error processing. Clear ErrorContext as
236 * discussed at top of file. We will not return to the original
237 * error's reporter or handler, so we don't need it.
239 MemoryContextReset(ErrorContext);
242 * If we recurse more than once, the problem might be something broken
243 * in a context traceback routine. Abandon them too. We also
244 * abandon attempting to print the error statement (which, if long,
245 * could itself be the source of the recursive failure).
247 if (recursion_depth > 2)
249 error_context_stack = NULL;
250 debug_query_string = NULL;
253 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
256 * Wups, stack not big enough. We treat this as a PANIC condition
257 * because it suggests an infinite loop of errors during error
260 errordata_stack_depth = -1; /* make room on stack */
261 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
264 /* Initialize data for this error frame */
265 edata = &errordata[errordata_stack_depth];
266 MemSet(edata, 0, sizeof(ErrorData));
267 edata->elevel = elevel;
268 edata->output_to_server = output_to_server;
269 edata->output_to_client = output_to_client;
270 edata->filename = filename;
271 edata->lineno = lineno;
272 edata->funcname = funcname;
273 /* Select default errcode based on elevel */
275 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
276 else if (elevel == WARNING)
277 edata->sqlerrcode = ERRCODE_WARNING;
279 edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
280 /* errno is saved here so that error parameter eval can't change it */
281 edata->saved_errno = errno;
288 * errfinish --- end an error-reporting cycle
290 * Produce the appropriate error report(s) and pop the error stack.
292 * If elevel is ERROR or worse, control does not return to the caller.
293 * See elog.h for the error level definitions.
296 errfinish(int dummy,...)
298 ErrorData *edata = &errordata[errordata_stack_depth];
299 int elevel = edata->elevel;
300 MemoryContext oldcontext;
301 ErrorContextCallback *econtext;
307 * Do processing in ErrorContext, which we hope has enough reserved space
308 * to report an error.
310 oldcontext = MemoryContextSwitchTo(ErrorContext);
313 * Call any context callback functions. Errors occurring in callback
314 * functions will be treated as recursive errors --- this ensures we will
315 * avoid infinite recursion (see errstart).
317 for (econtext = error_context_stack;
319 econtext = econtext->previous)
320 (*econtext->callback) (econtext->arg);
323 * If ERROR (not more nor less) we pass it off to the current handler.
324 * Printing it and popping the stack is the responsibility of the handler.
329 * We do some minimal cleanup before longjmp'ing so that handlers can
330 * execute in a reasonably sane state.
333 /* This is just in case the error came while waiting for input */
334 ImmediateInterruptOK = false;
337 * Reset InterruptHoldoffCount in case we ereport'd from inside an
338 * interrupt holdoff section. (We assume here that no handler will
339 * itself be inside a holdoff section. If necessary, such a handler
340 * could save and restore InterruptHoldoffCount for itself, but this
341 * should make life easier for most.)
343 InterruptHoldoffCount = 0;
345 CritSectionCount = 0; /* should be unnecessary, but... */
348 * Note that we leave CurrentMemoryContext set to ErrorContext. The
349 * handler should reset it to something else soon.
357 * If we are doing FATAL or PANIC, abort any old-style COPY OUT in
358 * progress, so that we can report the message before dying. (Without
359 * this, pq_putmessage will refuse to send the message at all, which is
360 * what we want for NOTICE messages, but not for fatal exits.) This hack
361 * is necessary because of poor design of old-style copy protocol. Note
362 * we must do this even if client is fool enough to have set
363 * client_min_messages above FATAL, so don't look at output_to_client.
365 if (elevel >= FATAL && whereToSendOutput == DestRemote)
368 /* Emit the message to the right places */
371 /* Now free up subsidiary data attached to stack entry, and release it */
373 pfree(edata->message);
375 pfree(edata->detail);
379 pfree(edata->context);
380 if (edata->internalquery)
381 pfree(edata->internalquery);
383 errordata_stack_depth--;
385 /* Exit error-handling context */
386 MemoryContextSwitchTo(oldcontext);
390 * Perform error recovery action as specified by elevel.
395 * For a FATAL error, we let proc_exit clean up and exit.
397 ImmediateInterruptOK = false;
400 * If we just reported a startup failure, the client will disconnect
401 * on receiving it, so don't send any more to the client.
403 if (PG_exception_stack == NULL && whereToSendOutput == DestRemote)
404 whereToSendOutput = DestNone;
407 * fflush here is just to improve the odds that we get to see the
408 * error message, in case things are so hosed that proc_exit crashes.
409 * Any other code you might be tempted to add here should probably be
410 * in an on_proc_exit or on_shmem_exit callback instead.
416 * Do normal process-exit cleanup, then return exit code 1 to indicate
417 * FATAL termination. The postmaster may or may not consider this
418 * worthy of panic, depending on which subprocess returns it.
426 * Serious crash time. Postmaster will observe SIGABRT process exit
427 * status and kill the other backends too.
429 * XXX: what if we are *in* the postmaster? abort() won't kill our
432 ImmediateInterruptOK = false;
439 * We reach here if elevel <= WARNING. OK to return to caller.
441 * But check for cancel/die interrupt first --- this is so that the user
442 * can stop a query emitting tons of notice or warning messages, even if
443 * it's in a loop that otherwise fails to check for interrupts.
445 CHECK_FOR_INTERRUPTS();
450 * errcode --- add SQLSTATE error code to the current error
452 * The code is expected to be represented as per MAKE_SQLSTATE().
455 errcode(int sqlerrcode)
457 ErrorData *edata = &errordata[errordata_stack_depth];
459 /* we don't bother incrementing recursion_depth */
462 edata->sqlerrcode = sqlerrcode;
464 return 0; /* return value does not matter */
469 * errcode_for_file_access --- add SQLSTATE error code to the current error
471 * The SQLSTATE code is chosen based on the saved errno value. We assume
472 * that the failing operation was some type of disk file access.
474 * NOTE: the primary error message string should generally include %m
478 errcode_for_file_access(void)
480 ErrorData *edata = &errordata[errordata_stack_depth];
482 /* we don't bother incrementing recursion_depth */
485 switch (edata->saved_errno)
487 /* Permission-denied failures */
488 case EPERM: /* Not super-user */
489 case EACCES: /* Permission denied */
491 case EROFS: /* Read only file system */
493 edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
497 case ENOENT: /* No such file or directory */
498 edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
502 case EEXIST: /* File exists */
503 edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
506 /* Wrong object type or state */
507 case ENOTDIR: /* Not a directory */
508 case EISDIR: /* Is a directory */
509 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
510 case ENOTEMPTY: /* Directory not empty */
512 edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
515 /* Insufficient resources */
516 case ENOSPC: /* No space left on device */
517 edata->sqlerrcode = ERRCODE_DISK_FULL;
520 case ENFILE: /* File table overflow */
521 case EMFILE: /* Too many open files */
522 edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
525 /* Hardware failure */
526 case EIO: /* I/O error */
527 edata->sqlerrcode = ERRCODE_IO_ERROR;
530 /* All else is classified as internal errors */
532 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
536 return 0; /* return value does not matter */
540 * errcode_for_socket_access --- add SQLSTATE error code to the current error
542 * The SQLSTATE code is chosen based on the saved errno value. We assume
543 * that the failing operation was some type of socket access.
545 * NOTE: the primary error message string should generally include %m
549 errcode_for_socket_access(void)
551 ErrorData *edata = &errordata[errordata_stack_depth];
553 /* we don't bother incrementing recursion_depth */
556 switch (edata->saved_errno)
558 /* Loss of connection */
563 edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
566 /* All else is classified as internal errors */
568 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
572 return 0; /* return value does not matter */
577 * This macro handles expansion of a format string and associated parameters;
578 * it's common code for errmsg(), errdetail(), etc. Must be called inside
579 * a routine that is declared like "const char *fmt, ..." and has an edata
580 * pointer set up. The message is assigned to edata->targetfield, or
581 * appended to it if appendval is true.
583 * Note: we pstrdup the buffer rather than just transferring its storage
584 * to the edata field because the buffer might be considerably larger than
587 #define EVALUATE_MESSAGE(targetfield, appendval) \
590 StringInfoData buf; \
591 /* Internationalize the error format string */ \
593 /* Expand %m in format string */ \
594 fmtbuf = expand_fmt_string(fmt, edata); \
595 initStringInfo(&buf); \
596 if ((appendval) && edata->targetfield) \
597 appendStringInfo(&buf, "%s\n", edata->targetfield); \
598 /* Generate actual output --- have to use appendStringInfoVA */ \
603 va_start(args, fmt); \
604 success = appendStringInfoVA(&buf, fmtbuf, args); \
608 enlargeStringInfo(&buf, buf.maxlen); \
610 /* Done with expanded fmt */ \
612 /* Save the completed message into the stack item */ \
613 if (edata->targetfield) \
614 pfree(edata->targetfield); \
615 edata->targetfield = pstrdup(buf.data); \
621 * errmsg --- add a primary error message text to the current error
623 * In addition to the usual %-escapes recognized by printf, "%m" in
624 * fmt is replaced by the error message for the caller's value of errno.
626 * Note: no newline is needed at the end of the fmt string, since
627 * ereport will provide one for the output methods that need it.
630 errmsg(const char *fmt,...)
632 ErrorData *edata = &errordata[errordata_stack_depth];
633 MemoryContext oldcontext;
637 oldcontext = MemoryContextSwitchTo(ErrorContext);
639 EVALUATE_MESSAGE(message, false);
641 MemoryContextSwitchTo(oldcontext);
643 return 0; /* return value does not matter */
648 * errmsg_internal --- add a primary error message text to the current error
650 * This is exactly like errmsg() except that strings passed to errmsg_internal
651 * are customarily left out of the internationalization message dictionary.
652 * This should be used for "can't happen" cases that are probably not worth
653 * spending translation effort on.
656 errmsg_internal(const char *fmt,...)
658 ErrorData *edata = &errordata[errordata_stack_depth];
659 MemoryContext oldcontext;
663 oldcontext = MemoryContextSwitchTo(ErrorContext);
665 EVALUATE_MESSAGE(message, false);
667 MemoryContextSwitchTo(oldcontext);
669 return 0; /* return value does not matter */
674 * errdetail --- add a detail error message text to the current error
677 errdetail(const char *fmt,...)
679 ErrorData *edata = &errordata[errordata_stack_depth];
680 MemoryContext oldcontext;
684 oldcontext = MemoryContextSwitchTo(ErrorContext);
686 EVALUATE_MESSAGE(detail, false);
688 MemoryContextSwitchTo(oldcontext);
690 return 0; /* return value does not matter */
695 * errhint --- add a hint error message text to the current error
698 errhint(const char *fmt,...)
700 ErrorData *edata = &errordata[errordata_stack_depth];
701 MemoryContext oldcontext;
705 oldcontext = MemoryContextSwitchTo(ErrorContext);
707 EVALUATE_MESSAGE(hint, false);
709 MemoryContextSwitchTo(oldcontext);
711 return 0; /* return value does not matter */
716 * errcontext --- add a context error message text to the current error
718 * Unlike other cases, multiple calls are allowed to build up a stack of
719 * context information. We assume earlier calls represent more-closely-nested
723 errcontext(const char *fmt,...)
725 ErrorData *edata = &errordata[errordata_stack_depth];
726 MemoryContext oldcontext;
730 oldcontext = MemoryContextSwitchTo(ErrorContext);
732 EVALUATE_MESSAGE(context, true);
734 MemoryContextSwitchTo(oldcontext);
736 return 0; /* return value does not matter */
741 * errhidestmt --- optionally suppress STATEMENT: field of log entry
743 * This should be called if the message text already includes the statement.
746 errhidestmt(bool hide_stmt)
748 ErrorData *edata = &errordata[errordata_stack_depth];
750 /* we don't bother incrementing recursion_depth */
753 edata->hide_stmt = hide_stmt;
755 return 0; /* return value does not matter */
760 * errfunction --- add reporting function name to the current error
762 * This is used when backwards compatibility demands that the function
763 * name appear in messages sent to old-protocol clients. Note that the
764 * passed string is expected to be a non-freeable constant string.
767 errfunction(const char *funcname)
769 ErrorData *edata = &errordata[errordata_stack_depth];
771 /* we don't bother incrementing recursion_depth */
774 edata->funcname = funcname;
775 edata->show_funcname = true;
777 return 0; /* return value does not matter */
781 * errposition --- add cursor position to the current error
784 errposition(int cursorpos)
786 ErrorData *edata = &errordata[errordata_stack_depth];
788 /* we don't bother incrementing recursion_depth */
791 edata->cursorpos = cursorpos;
793 return 0; /* return value does not matter */
797 * internalerrposition --- add internal cursor position to the current error
800 internalerrposition(int cursorpos)
802 ErrorData *edata = &errordata[errordata_stack_depth];
804 /* we don't bother incrementing recursion_depth */
807 edata->internalpos = cursorpos;
809 return 0; /* return value does not matter */
813 * internalerrquery --- add internal query text to the current error
815 * Can also pass NULL to drop the internal query text entry. This case
816 * is intended for use in error callback subroutines that are editorializing
817 * on the layout of the error report.
820 internalerrquery(const char *query)
822 ErrorData *edata = &errordata[errordata_stack_depth];
824 /* we don't bother incrementing recursion_depth */
827 if (edata->internalquery)
829 pfree(edata->internalquery);
830 edata->internalquery = NULL;
834 edata->internalquery = MemoryContextStrdup(ErrorContext, query);
836 return 0; /* return value does not matter */
840 * geterrposition --- return the currently set error position (0 if none)
842 * This is only intended for use in error callback subroutines, since there
843 * is no other place outside elog.c where the concept is meaningful.
848 ErrorData *edata = &errordata[errordata_stack_depth];
850 /* we don't bother incrementing recursion_depth */
853 return edata->cursorpos;
857 * getinternalerrposition --- same for internal error position
859 * This is only intended for use in error callback subroutines, since there
860 * is no other place outside elog.c where the concept is meaningful.
863 getinternalerrposition(void)
865 ErrorData *edata = &errordata[errordata_stack_depth];
867 /* we don't bother incrementing recursion_depth */
870 return edata->internalpos;
875 * elog_start --- startup for old-style API
877 * All that we do here is stash the hidden filename/lineno/funcname
878 * arguments into a stack entry.
880 * We need this to be separate from elog_finish because there's no other
881 * portable way to deal with inserting extra arguments into the elog call.
882 * (If macros with variable numbers of arguments were portable, it'd be
883 * easy, but they aren't.)
886 elog_start(const char *filename, int lineno, const char *funcname)
890 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
893 * Wups, stack not big enough. We treat this as a PANIC condition
894 * because it suggests an infinite loop of errors during error
897 errordata_stack_depth = -1; /* make room on stack */
898 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
901 edata = &errordata[errordata_stack_depth];
902 edata->filename = filename;
903 edata->lineno = lineno;
904 edata->funcname = funcname;
905 /* errno is saved now so that error parameter eval can't change it */
906 edata->saved_errno = errno;
910 * elog_finish --- finish up for old-style API
913 elog_finish(int elevel, const char *fmt,...)
915 ErrorData *edata = &errordata[errordata_stack_depth];
916 MemoryContext oldcontext;
921 * Do errstart() to see if we actually want to report the message.
923 errordata_stack_depth--;
924 errno = edata->saved_errno;
925 if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname))
926 return; /* nothing to do */
929 * Format error message just like errmsg().
932 oldcontext = MemoryContextSwitchTo(ErrorContext);
934 EVALUATE_MESSAGE(message, false);
936 MemoryContextSwitchTo(oldcontext);
940 * And let errfinish() finish up.
946 * Actual output of the top-of-stack error message
948 * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
949 * if the error is caught by somebody). For all other severity levels this
950 * is called by errfinish.
953 EmitErrorReport(void)
955 ErrorData *edata = &errordata[errordata_stack_depth];
956 MemoryContext oldcontext;
960 oldcontext = MemoryContextSwitchTo(ErrorContext);
962 /* Send to server log, if enabled */
963 if (edata->output_to_server)
964 send_message_to_server_log(edata);
966 /* Send to client, if enabled */
967 if (edata->output_to_client)
968 send_message_to_frontend(edata);
970 MemoryContextSwitchTo(oldcontext);
975 * CopyErrorData --- obtain a copy of the topmost error stack entry
977 * This is only for use in error handler code. The data is copied into the
978 * current memory context, so callers should always switch away from
979 * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
984 ErrorData *edata = &errordata[errordata_stack_depth];
988 * we don't increment recursion_depth because out-of-memory here does not
989 * indicate a problem within the error subsystem.
993 Assert(CurrentMemoryContext != ErrorContext);
995 /* Copy the struct itself */
996 newedata = (ErrorData *) palloc(sizeof(ErrorData));
997 memcpy(newedata, edata, sizeof(ErrorData));
999 /* Make copies of separately-allocated fields */
1000 if (newedata->message)
1001 newedata->message = pstrdup(newedata->message);
1002 if (newedata->detail)
1003 newedata->detail = pstrdup(newedata->detail);
1005 newedata->hint = pstrdup(newedata->hint);
1006 if (newedata->context)
1007 newedata->context = pstrdup(newedata->context);
1008 if (newedata->internalquery)
1009 newedata->internalquery = pstrdup(newedata->internalquery);
1015 * FreeErrorData --- free the structure returned by CopyErrorData.
1017 * Error handlers should use this in preference to assuming they know all
1018 * the separately-allocated fields.
1021 FreeErrorData(ErrorData *edata)
1024 pfree(edata->message);
1026 pfree(edata->detail);
1030 pfree(edata->context);
1031 if (edata->internalquery)
1032 pfree(edata->internalquery);
1037 * FlushErrorState --- flush the error state after error recovery
1039 * This should be called by an error handler after it's done processing
1040 * the error; or as soon as it's done CopyErrorData, if it intends to
1041 * do stuff that is likely to provoke another error. You are not "out" of
1042 * the error subsystem until you have done this.
1045 FlushErrorState(void)
1048 * Reset stack to empty. The only case where it would be more than one
1049 * deep is if we serviced an error that interrupted construction of
1050 * another message. We assume control escaped out of that message
1051 * construction and won't ever go back.
1053 errordata_stack_depth = -1;
1054 recursion_depth = 0;
1055 /* Delete all data in ErrorContext */
1056 MemoryContextResetAndDeleteChildren(ErrorContext);
1060 * ReThrowError --- re-throw a previously copied error
1062 * A handler can do CopyErrorData/FlushErrorState to get out of the error
1063 * subsystem, then do some processing, and finally ReThrowError to re-throw
1064 * the original error. This is slower than just PG_RE_THROW() but should
1065 * be used if the "some processing" is likely to incur another error.
1068 ReThrowError(ErrorData *edata)
1070 ErrorData *newedata;
1072 Assert(edata->elevel == ERROR);
1074 /* Push the data back into the error context */
1076 MemoryContextSwitchTo(ErrorContext);
1078 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1081 * Wups, stack not big enough. We treat this as a PANIC condition
1082 * because it suggests an infinite loop of errors during error
1085 errordata_stack_depth = -1; /* make room on stack */
1086 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1089 newedata = &errordata[errordata_stack_depth];
1090 memcpy(newedata, edata, sizeof(ErrorData));
1092 /* Make copies of separately-allocated fields */
1093 if (newedata->message)
1094 newedata->message = pstrdup(newedata->message);
1095 if (newedata->detail)
1096 newedata->detail = pstrdup(newedata->detail);
1098 newedata->hint = pstrdup(newedata->hint);
1099 if (newedata->context)
1100 newedata->context = pstrdup(newedata->context);
1101 if (newedata->internalquery)
1102 newedata->internalquery = pstrdup(newedata->internalquery);
1109 * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
1114 /* If possible, throw the error to the next outer setjmp handler */
1115 if (PG_exception_stack != NULL)
1116 siglongjmp(*PG_exception_stack, 1);
1120 * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
1121 * we have now exited only to discover that there is no outer setjmp
1122 * handler to pass the error to. Had the error been thrown outside the
1123 * block to begin with, we'd have promoted the error to FATAL, so the
1124 * correct behavior is to make it FATAL now; that is, emit it and then
1127 ErrorData *edata = &errordata[errordata_stack_depth];
1129 Assert(errordata_stack_depth >= 0);
1130 Assert(edata->elevel == ERROR);
1131 edata->elevel = FATAL;
1134 * At least in principle, the increase in severity could have changed
1135 * where-to-output decisions, so recalculate. This should stay in
1136 * sync with errstart(), which see for comments.
1138 if (IsPostmasterEnvironment)
1139 edata->output_to_server = is_log_level_output(FATAL,
1142 edata->output_to_server = (FATAL >= log_min_messages);
1143 if (whereToSendOutput == DestRemote)
1145 if (ClientAuthInProgress)
1146 edata->output_to_client = true;
1148 edata->output_to_client = (FATAL >= client_min_messages);
1152 * We can use errfinish() for the rest, but we don't want it to call
1153 * any error context routines a second time. Since we know we are
1154 * about to exit, it should be OK to just clear the context stack.
1156 error_context_stack = NULL;
1161 /* We mustn't return... */
1162 ExceptionalCondition("pg_re_throw tried to return", "FailedAssertion",
1163 __FILE__, __LINE__);
1166 * Since ExceptionalCondition isn't declared noreturn because of
1167 * TrapMacro(), we need this to keep gcc from complaining.
1174 * Initialization of error output file
1182 if (OutputFileName[0])
1185 * A debug-output file name was given.
1187 * Make sure we can write the file, and find out if it's a tty.
1189 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
1192 (errcode_for_file_access(),
1193 errmsg("could not open file \"%s\": %m", OutputFileName)));
1198 * Redirect our stderr to the debug output file.
1200 if (!freopen(OutputFileName, "a", stderr))
1202 (errcode_for_file_access(),
1203 errmsg("could not reopen file \"%s\" as stderr: %m",
1207 * If the file is a tty and we're running under the postmaster, try to
1208 * send stdout there as well (if it isn't a tty then stderr will block
1209 * out stdout, so we may as well let stdout go wherever it was going
1212 if (istty && IsUnderPostmaster)
1213 if (!freopen(OutputFileName, "a", stdout))
1215 (errcode_for_file_access(),
1216 errmsg("could not reopen file \"%s\" as stdout: %m",
1226 * Set or update the parameters for syslog logging
1229 set_syslog_parameters(const char *ident, int facility)
1232 * guc.c is likely to call us repeatedly with same parameters, so don't
1233 * thrash the syslog connection unnecessarily. Also, we do not re-open
1234 * the connection until needed, since this routine will get called whether
1235 * or not Log_destination actually mentions syslog.
1237 * Note that we make our own copy of the ident string rather than relying
1238 * on guc.c's. This may be overly paranoid, but it ensures that we cannot
1239 * accidentally free a string that syslog is still using.
1241 if (syslog_ident == NULL || strcmp(syslog_ident, ident) != 0 ||
1242 syslog_facility != facility)
1247 openlog_done = false;
1251 syslog_ident = strdup(ident);
1252 /* if the strdup fails, we will cope in write_syslog() */
1253 syslog_facility = facility;
1258 #ifndef PG_SYSLOG_LIMIT
1259 #define PG_SYSLOG_LIMIT 128
1263 * Write a message line to syslog
1266 write_syslog(int level, const char *line)
1268 static unsigned long seq = 0;
1272 /* Open syslog connection if not done yet */
1275 openlog(syslog_ident ? syslog_ident : "postgres",
1276 LOG_PID | LOG_NDELAY | LOG_NOWAIT,
1278 openlog_done = true;
1282 * We add a sequence number to each log message to suppress "same"
1288 * Our problem here is that many syslog implementations don't handle long
1289 * messages in an acceptable manner. While this function doesn't help that
1290 * fact, it does work around by splitting up messages into smaller pieces.
1292 * We divide into multiple syslog() calls if message is too long or if the
1293 * message contains embedded NewLine(s) '\n'.
1296 if (len > PG_SYSLOG_LIMIT || strchr(line, '\n') != NULL)
1302 char buf[PG_SYSLOG_LIMIT + 1];
1307 /* if we start at a newline, move ahead one char */
1308 if (line[0] == '\n')
1315 /* copy one line, or as much as will fit, to buf */
1316 nlpos = strchr(line, '\n');
1318 buflen = nlpos - line;
1321 buflen = Min(buflen, PG_SYSLOG_LIMIT);
1322 memcpy(buf, line, buflen);
1325 /* trim to multibyte letter boundary */
1326 buflen = pg_mbcliplen(buf, buflen, buflen);
1331 /* already word boundary? */
1332 if (line[buflen] != '\0' &&
1333 !isspace((unsigned char) line[buflen]))
1335 /* try to divide at word boundary */
1337 while (i > 0 && !isspace((unsigned char) buf[i]))
1340 if (i > 0) /* else couldn't divide word boundary */
1349 syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1356 /* message short enough */
1357 syslog(level, "[%lu] %s", seq, line);
1360 #endif /* HAVE_SYSLOG */
1364 * Write a message line to the windows event log
1367 write_eventlog(int level, const char *line)
1369 int eventlevel = EVENTLOG_ERROR_TYPE;
1370 static HANDLE evtHandle = INVALID_HANDLE_VALUE;
1372 if (evtHandle == INVALID_HANDLE_VALUE)
1374 evtHandle = RegisterEventSource(NULL, "PostgreSQL");
1375 if (evtHandle == NULL)
1377 evtHandle = INVALID_HANDLE_VALUE;
1393 eventlevel = EVENTLOG_INFORMATION_TYPE;
1396 eventlevel = EVENTLOG_WARNING_TYPE;
1402 eventlevel = EVENTLOG_ERROR_TYPE;
1407 ReportEvent(evtHandle,
1410 0, /* All events are Id 0 */
1420 * Format tag info for log lines; append to the provided buffer.
1423 log_line_prefix(StringInfo buf)
1425 /* static counter for line numbers */
1426 static long log_line_number = 0;
1428 /* has counter been reset in current process? */
1429 static int log_my_pid = 0;
1435 * This is one of the few places where we'd rather not inherit a static
1436 * variable's value from the postmaster. But since we will, reset it when
1437 * MyProcPid changes.
1439 if (log_my_pid != MyProcPid)
1441 log_line_number = 0;
1442 log_my_pid = MyProcPid;
1446 if (Log_line_prefix == NULL)
1447 return; /* in case guc hasn't run yet */
1449 format_len = strlen(Log_line_prefix);
1451 for (i = 0; i < format_len; i++)
1453 if (Log_line_prefix[i] != '%')
1455 /* literal char, just copy */
1456 appendStringInfoChar(buf, Log_line_prefix[i]);
1459 /* go to char after '%' */
1461 if (i >= format_len)
1462 break; /* format error - ignore it */
1464 /* process the option */
1465 switch (Log_line_prefix[i])
1470 const char *username = MyProcPort->user_name;
1472 if (username == NULL || *username == '\0')
1473 username = _("[unknown]");
1474 appendStringInfo(buf, "%s", username);
1480 const char *dbname = MyProcPort->database_name;
1482 if (dbname == NULL || *dbname == '\0')
1483 dbname = _("[unknown]");
1484 appendStringInfo(buf, "%s", dbname);
1490 appendStringInfo(buf, "%lx.%x",
1491 (long) (MyProcPort->session_start),
1496 appendStringInfo(buf, "%d", MyProcPid);
1499 appendStringInfo(buf, "%ld", log_line_number);
1504 * Note: for %m, %t, and %s we deliberately use the C
1505 * library's strftime/localtime, and not the equivalent
1506 * functions from src/timezone. This ensures that all
1507 * backends will report log entries in the same timezone,
1508 * namely whatever C-library setting they inherit from the
1509 * postmaster. If we used src/timezone then local
1510 * settings of the TimeZone GUC variable would confuse the
1518 gettimeofday(&tv, NULL);
1519 stamp_time = tv.tv_sec;
1521 strftime(strfbuf, sizeof(strfbuf),
1522 /* leave room for milliseconds... */
1523 /* Win32 timezone names are too long so don't print them */
1525 "%Y-%m-%d %H:%M:%S %Z",
1527 "%Y-%m-%d %H:%M:%S ",
1529 localtime(&stamp_time));
1531 /* 'paste' milliseconds into place... */
1532 sprintf(msbuf, ".%03d", (int) (tv.tv_usec / 1000));
1533 strncpy(strfbuf + 19, msbuf, 4);
1535 appendStringInfoString(buf, strfbuf);
1540 time_t stamp_time = time(NULL);
1543 strftime(strfbuf, sizeof(strfbuf),
1544 /* Win32 timezone names are too long so don't print them */
1546 "%Y-%m-%d %H:%M:%S %Z",
1548 "%Y-%m-%d %H:%M:%S",
1550 localtime(&stamp_time));
1551 appendStringInfoString(buf, strfbuf);
1559 strftime(strfbuf, sizeof(strfbuf),
1560 /* Win32 timezone names are too long so don't print them */
1562 "%Y-%m-%d %H:%M:%S %Z",
1564 "%Y-%m-%d %H:%M:%S",
1566 localtime(&MyProcPort->session_start));
1567 appendStringInfoString(buf, strfbuf);
1576 psdisp = get_ps_display(&displen);
1577 appendStringInfo(buf, "%.*s", displen, psdisp);
1581 if (MyProcPort && MyProcPort->remote_host)
1583 appendStringInfo(buf, "%s", MyProcPort->remote_host);
1584 if (MyProcPort->remote_port &&
1585 MyProcPort->remote_port[0] != '\0')
1586 appendStringInfo(buf, "(%s)",
1587 MyProcPort->remote_port);
1591 if (MyProcPort && MyProcPort->remote_host)
1592 appendStringInfo(buf, "%s", MyProcPort->remote_host);
1595 /* in postmaster and friends, stop if %q is seen */
1596 /* in a backend, just ignore */
1597 if (MyProcPort == NULL)
1602 appendStringInfo(buf, "%u", GetTopTransactionId());
1605 appendStringInfoChar(buf, '%');
1608 /* format error - ignore it */
1615 * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
1619 unpack_sql_state(int sql_state)
1621 static char buf[12];
1624 for (i = 0; i < 5; i++)
1626 buf[i] = PGUNSIXBIT(sql_state);
1636 * Write error report to server's log
1639 send_message_to_server_log(ErrorData *edata)
1643 initStringInfo(&buf);
1645 log_line_prefix(&buf);
1646 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
1648 if (Log_error_verbosity >= PGERROR_VERBOSE)
1649 appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
1652 append_with_tabs(&buf, edata->message);
1654 append_with_tabs(&buf, _("missing error text"));
1656 if (edata->cursorpos > 0)
1657 appendStringInfo(&buf, _(" at character %d"),
1659 else if (edata->internalpos > 0)
1660 appendStringInfo(&buf, _(" at character %d"),
1661 edata->internalpos);
1663 appendStringInfoChar(&buf, '\n');
1665 if (Log_error_verbosity >= PGERROR_DEFAULT)
1669 log_line_prefix(&buf);
1670 appendStringInfoString(&buf, _("DETAIL: "));
1671 append_with_tabs(&buf, edata->detail);
1672 appendStringInfoChar(&buf, '\n');
1676 log_line_prefix(&buf);
1677 appendStringInfoString(&buf, _("HINT: "));
1678 append_with_tabs(&buf, edata->hint);
1679 appendStringInfoChar(&buf, '\n');
1681 if (edata->internalquery)
1683 log_line_prefix(&buf);
1684 appendStringInfoString(&buf, _("QUERY: "));
1685 append_with_tabs(&buf, edata->internalquery);
1686 appendStringInfoChar(&buf, '\n');
1690 log_line_prefix(&buf);
1691 appendStringInfoString(&buf, _("CONTEXT: "));
1692 append_with_tabs(&buf, edata->context);
1693 appendStringInfoChar(&buf, '\n');
1695 if (Log_error_verbosity >= PGERROR_VERBOSE)
1697 /* assume no newlines in funcname or filename... */
1698 if (edata->funcname && edata->filename)
1700 log_line_prefix(&buf);
1701 appendStringInfo(&buf, _("LOCATION: %s, %s:%d\n"),
1702 edata->funcname, edata->filename,
1705 else if (edata->filename)
1707 log_line_prefix(&buf);
1708 appendStringInfo(&buf, _("LOCATION: %s:%d\n"),
1709 edata->filename, edata->lineno);
1715 * If the user wants the query that generated this error logged, do it.
1717 if (is_log_level_output(edata->elevel, log_min_error_statement) &&
1718 debug_query_string != NULL &&
1721 log_line_prefix(&buf);
1722 appendStringInfoString(&buf, _("STATEMENT: "));
1723 append_with_tabs(&buf, debug_query_string);
1724 appendStringInfoChar(&buf, '\n');
1728 /* Write to syslog, if enabled */
1729 if (Log_destination & LOG_DESTINATION_SYSLOG)
1733 switch (edata->elevel)
1740 syslog_level = LOG_DEBUG;
1745 syslog_level = LOG_INFO;
1749 syslog_level = LOG_NOTICE;
1752 syslog_level = LOG_WARNING;
1755 syslog_level = LOG_ERR;
1759 syslog_level = LOG_CRIT;
1763 write_syslog(syslog_level, buf.data);
1765 #endif /* HAVE_SYSLOG */
1768 /* Write to eventlog, if enabled */
1769 if (Log_destination & LOG_DESTINATION_EVENTLOG)
1771 write_eventlog(edata->elevel, buf.data);
1775 /* Write to stderr, if enabled */
1776 if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == DestDebug)
1779 * Use the chunking protocol if we know the syslogger should
1780 * be catching stderr output, and we are not ourselves the
1781 * syslogger. Otherwise, just do a vanilla write to stderr.
1783 if (redirection_done && !am_syslogger)
1784 write_pipe_chunks(fileno(stderr), buf.data, buf.len);
1787 * In a win32 service environment, there is no usable stderr. Capture
1788 * anything going there and write it to the eventlog instead.
1790 * If stderr redirection is active, it was OK to write to stderr above
1791 * because that's really a pipe to the syslogger process.
1793 else if (pgwin32_is_service())
1794 write_eventlog(edata->elevel, buf.data);
1797 write(fileno(stderr), buf.data, buf.len);
1800 /* If in the syslogger process, try to write messages direct to file */
1802 write_syslogger_file(buf.data, buf.len);
1808 * Send data to the syslogger using the chunked protocol
1811 write_pipe_chunks(int fd, char *data, int len)
1817 p.proto.nuls[0] = p.proto.nuls[1] = '\0';
1818 p.proto.pid = MyProcPid;
1820 /* write all but the last chunk */
1821 while (len > PIPE_MAX_PAYLOAD)
1823 p.proto.is_last = 'f';
1824 p.proto.len = PIPE_MAX_PAYLOAD;
1825 memcpy(p.proto.data, data, PIPE_MAX_PAYLOAD);
1826 write(fd, &p, PIPE_HEADER_SIZE + PIPE_MAX_PAYLOAD);
1827 data += PIPE_MAX_PAYLOAD;
1828 len -= PIPE_MAX_PAYLOAD;
1831 /* write the last chunk */
1832 p.proto.is_last = 't';
1834 memcpy(p.proto.data, data, len);
1835 write(fd, &p, PIPE_HEADER_SIZE + len);
1840 * Write error report to client
1843 send_message_to_frontend(ErrorData *edata)
1845 StringInfoData msgbuf;
1847 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
1848 pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
1850 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
1852 /* New style with separate fields */
1857 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
1858 pq_sendstring(&msgbuf, error_severity(edata->elevel));
1860 /* unpack MAKE_SQLSTATE code */
1861 ssval = edata->sqlerrcode;
1862 for (i = 0; i < 5; i++)
1864 tbuf[i] = PGUNSIXBIT(ssval);
1869 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
1870 pq_sendstring(&msgbuf, tbuf);
1872 /* M field is required per protocol, so always send something */
1873 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
1875 pq_sendstring(&msgbuf, edata->message);
1877 pq_sendstring(&msgbuf, _("missing error text"));
1881 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
1882 pq_sendstring(&msgbuf, edata->detail);
1887 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
1888 pq_sendstring(&msgbuf, edata->hint);
1893 pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
1894 pq_sendstring(&msgbuf, edata->context);
1897 if (edata->cursorpos > 0)
1899 snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
1900 pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
1901 pq_sendstring(&msgbuf, tbuf);
1904 if (edata->internalpos > 0)
1906 snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
1907 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
1908 pq_sendstring(&msgbuf, tbuf);
1911 if (edata->internalquery)
1913 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
1914 pq_sendstring(&msgbuf, edata->internalquery);
1917 if (edata->filename)
1919 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
1920 pq_sendstring(&msgbuf, edata->filename);
1923 if (edata->lineno > 0)
1925 snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
1926 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
1927 pq_sendstring(&msgbuf, tbuf);
1930 if (edata->funcname)
1932 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
1933 pq_sendstring(&msgbuf, edata->funcname);
1936 pq_sendbyte(&msgbuf, '\0'); /* terminator */
1940 /* Old style --- gin up a backwards-compatible message */
1943 initStringInfo(&buf);
1945 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
1947 if (edata->show_funcname && edata->funcname)
1948 appendStringInfo(&buf, "%s: ", edata->funcname);
1951 appendStringInfoString(&buf, edata->message);
1953 appendStringInfoString(&buf, _("missing error text"));
1955 if (edata->cursorpos > 0)
1956 appendStringInfo(&buf, _(" at character %d"),
1958 else if (edata->internalpos > 0)
1959 appendStringInfo(&buf, _(" at character %d"),
1960 edata->internalpos);
1962 appendStringInfoChar(&buf, '\n');
1964 pq_sendstring(&msgbuf, buf.data);
1969 pq_endmessage(&msgbuf);
1972 * This flush is normally not necessary, since postgres.c will flush out
1973 * waiting data when control returns to the main loop. But it seems best
1974 * to leave it here, so that the client has some clue what happened if the
1975 * backend dies before getting back to the main loop ... error/notice
1976 * messages should not be a performance-critical path anyway, so an extra
1977 * flush won't hurt much ...
1984 * Support routines for formatting error messages.
1989 * expand_fmt_string --- process special format codes in a format string
1991 * We must replace %m with the appropriate strerror string, since vsnprintf
1992 * won't know what to do with it.
1994 * The result is a palloc'd string.
1997 expand_fmt_string(const char *fmt, ErrorData *edata)
2002 initStringInfo(&buf);
2004 for (cp = fmt; *cp; cp++)
2006 if (cp[0] == '%' && cp[1] != '\0')
2012 * Replace %m by system error string. If there are any %'s in
2013 * the string, we'd better double them so that vsnprintf won't
2018 cp2 = useful_strerror(edata->saved_errno);
2022 appendStringInfoCharMacro(&buf, '%');
2023 appendStringInfoCharMacro(&buf, *cp2);
2028 /* copy % and next char --- this avoids trouble with %%m */
2029 appendStringInfoCharMacro(&buf, '%');
2030 appendStringInfoCharMacro(&buf, *cp);
2034 appendStringInfoCharMacro(&buf, *cp);
2042 * A slightly cleaned-up version of strerror()
2045 useful_strerror(int errnum)
2047 /* this buffer is only used if errno has a bogus value */
2048 static char errorstr_buf[48];
2052 /* Winsock error code range, per WinError.h */
2053 if (errnum >= 10000 && errnum <= 11999)
2054 return pgwin32_socket_strerror(errnum);
2056 str = strerror(errnum);
2059 * Some strerror()s return an empty string for out-of-range errno. This is
2060 * ANSI C spec compliant, but not exactly useful.
2062 if (str == NULL || *str == '\0')
2064 snprintf(errorstr_buf, sizeof(errorstr_buf),
2066 translator: This string will be truncated at 47
2067 characters expanded. */
2068 _("operating system error %d"), errnum);
2077 * error_severity --- get localized string representing elevel
2080 error_severity(int elevel)
2091 prefix = _("DEBUG");
2101 prefix = _("NOTICE");
2104 prefix = _("WARNING");
2107 prefix = _("ERROR");
2110 prefix = _("FATAL");
2113 prefix = _("PANIC");
2127 * Append the string to the StringInfo buffer, inserting a tab after any
2131 append_with_tabs(StringInfo buf, const char *str)
2135 while ((ch = *str++) != '\0')
2137 appendStringInfoCharMacro(buf, ch);
2139 appendStringInfoCharMacro(buf, '\t');
2145 * Write errors to stderr (or by equal means when stderr is
2146 * not available). Used before ereport/elog can be used
2147 * safely (memory context, GUC load etc)
2150 write_stderr(const char *fmt,...)
2158 /* On Unix, we just fprintf to stderr */
2159 vfprintf(stderr, fmt, ap);
2164 * On Win32, we print to stderr if running on a console, or write to
2165 * eventlog if running as a service
2167 if (pgwin32_is_service()) /* Running as a service */
2169 char errbuf[2048]; /* Arbitrary size? */
2171 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
2173 write_eventlog(ERROR, errbuf);
2177 /* Not running as service, write to stderr */
2178 vfprintf(stderr, fmt, ap);
2187 * is_log_level_output -- is elevel logically >= log_min_level?
2189 * We use this for tests that should consider LOG to sort out-of-order,
2190 * between ERROR and FATAL. Generally this is the right thing for testing
2191 * whether a message should go to the postmaster log, whereas a simple >=
2192 * test is correct for testing whether the message should go to the client.
2195 is_log_level_output(int elevel, int log_min_level)
2197 if (elevel == LOG || elevel == COMMERROR)
2199 if (log_min_level == LOG || log_min_level <= ERROR)
2202 else if (log_min_level == LOG)
2205 if (elevel >= FATAL)
2208 /* Neither is LOG */
2209 else if (elevel >= log_min_level)