PostgreSQL Source Code git master
Loading...
Searching...
No Matches
elog.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * elog.c
4 * error logging and reporting
5 *
6 * Because of the extremely high rate at which log messages can be generated,
7 * we need to be mindful of the performance cost of obtaining any information
8 * that may be logged. Also, it's important to keep in mind that this code may
9 * get called from within an aborted transaction, in which case operations
10 * such as syscache lookups are unsafe.
11 *
12 * Some notes about recursion and errors during error processing:
13 *
14 * We need to be robust about recursive-error scenarios --- for example,
15 * if we run out of memory, it's important to be able to report that fact.
16 * There are a number of considerations that go into this.
17 *
18 * First, distinguish between re-entrant use and actual recursion. It
19 * is possible for an error or warning message to be emitted while the
20 * parameters for an error message are being computed. In this case
21 * errstart has been called for the outer message, and some field values
22 * may have already been saved, but we are not actually recursing. We handle
23 * this by providing a (small) stack of ErrorData records. The inner message
24 * can be computed and sent without disturbing the state of the outer message.
25 * (If the inner message is actually an error, this isn't very interesting
26 * because control won't come back to the outer message generator ... but
27 * if the inner message is only debug or log data, this is critical.)
28 *
29 * Second, actual recursion will occur if an error is reported by one of
30 * the elog.c routines or something they call. By far the most probable
31 * scenario of this sort is "out of memory"; and it's also the nastiest
32 * to handle because we'd likely also run out of memory while trying to
33 * report this error! Our escape hatch for this case is to reset the
34 * ErrorContext to empty before trying to process the inner error. Since
35 * ErrorContext is guaranteed to have at least 8K of space in it (see mcxt.c),
36 * we should be able to process an "out of memory" message successfully.
37 * Since we lose the prior error state due to the reset, we won't be able
38 * to return to processing the original error, but we wouldn't have anyway.
39 * (NOTE: the escape hatch is not used for recursive situations where the
40 * inner message is of less than ERROR severity; in that case we just
41 * try to process it and return normally. Usually this will work, but if
42 * it ends up in infinite recursion, we will PANIC due to error stack
43 * overflow.)
44 *
45 *
46 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
47 * Portions Copyright (c) 1994, Regents of the University of California
48 *
49 *
50 * IDENTIFICATION
51 * src/backend/utils/error/elog.c
52 *
53 *-------------------------------------------------------------------------
54 */
55#include "postgres.h"
56
57#include <fcntl.h>
58#include <time.h>
59#include <unistd.h>
60#include <signal.h>
61#include <ctype.h>
62#ifdef HAVE_SYSLOG
63#include <syslog.h>
64#endif
65#ifdef HAVE_EXECINFO_H
66#include <execinfo.h>
67#endif
68
69#include "access/xact.h"
70#include "common/ip.h"
71#include "libpq/libpq.h"
72#include "libpq/pqformat.h"
73#include "mb/pg_wchar.h"
74#include "miscadmin.h"
75#include "nodes/miscnodes.h"
76#include "pgstat.h"
77#include "postmaster/bgworker.h"
80#include "storage/ipc.h"
81#include "storage/proc.h"
82#include "tcop/tcopprot.h"
83#include "utils/guc_hooks.h"
84#include "utils/memutils.h"
85#include "utils/ps_status.h"
86#include "utils/varlena.h"
87
88
89/* In this module, access gettext() via err_gettext() */
90#undef _
91#define _(x) err_gettext(x)
92
93
94/* Global variables */
96
98
99/*
100 * Hook for intercepting messages before they are sent to the server log.
101 * Note that the hook will not get called for messages that are suppressed
102 * by log_min_messages. Also note that logging hooks implemented in preload
103 * libraries will miss any log messages that are generated before the
104 * library is loaded.
105 */
107
108/* GUC parameters */
110char *Log_line_prefix = NULL; /* format for extra log line info */
115
116/* Processed form of backtrace_functions GUC */
118
119#ifdef HAVE_SYSLOG
120
121/*
122 * Max string length to send to syslog(). Note that this doesn't count the
123 * sequence-number prefix we add, and of course it doesn't count the prefix
124 * added by syslog itself. Solaris and sysklogd truncate the final message
125 * at 1024 bytes, so this value leaves 124 bytes for those prefixes. (Most
126 * other syslog implementations seem to have limits of 2KB or so.)
127 */
128#ifndef PG_SYSLOG_LIMIT
129#define PG_SYSLOG_LIMIT 900
130#endif
131
132static bool openlog_done = false;
133static char *syslog_ident = NULL;
134static int syslog_facility = LOG_LOCAL0;
135
136static void write_syslog(int level, const char *line);
137#endif
138
139#ifdef WIN32
140static void write_eventlog(int level, const char *line, int len);
141#endif
142
143/* We provide a small stack of ErrorData records for re-entrant cases */
144#define ERRORDATA_STACK_SIZE 5
145
147
148static int errordata_stack_depth = -1; /* index of topmost active frame */
149
150static int recursion_depth = 0; /* to detect actual recursion */
151
152/*
153 * Saved timeval and buffers for formatted timestamps that might be used by
154 * log_line_prefix, csv logs and JSON logs.
155 */
156static struct timeval saved_timeval;
157static bool saved_timeval_set = false;
158
159#define FORMATTED_TS_LEN 128
162
163
164/* Macro for checking errordata_stack_depth is reasonable */
165#define CHECK_STACK_DEPTH() \
166 do { \
167 if (errordata_stack_depth < 0) \
168 { \
169 errordata_stack_depth = -1; \
170 ereport(ERROR, (errmsg_internal("errstart was not called"))); \
171 } \
172 } while (0)
173
174
175static const char *err_gettext(const char *str) pg_attribute_format_arg(1);
176static ErrorData *get_error_stack_entry(void);
177static void set_stack_entry_domain(ErrorData *edata, const char *domain);
179 const char *filename, int lineno,
180 const char *funcname);
181static bool matches_backtrace_functions(const char *funcname);
183static void set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str);
185static void write_console(const char *line, int len);
186static const char *process_log_prefix_padding(const char *p, int *ppadding);
190static void append_with_tabs(StringInfo buf, const char *str);
191
192
193/*
194 * is_log_level_output -- is elevel logically >= log_min_level?
195 *
196 * We use this for tests that should consider LOG to sort out-of-order,
197 * between ERROR and FATAL. Generally this is the right thing for testing
198 * whether a message should go to the postmaster log, whereas a simple >=
199 * test is correct for testing whether the message should go to the client.
200 */
201static inline bool
203{
204 if (elevel == LOG || elevel == LOG_SERVER_ONLY)
205 {
207 return true;
208 }
209 else if (elevel == WARNING_CLIENT_ONLY)
210 {
211 /* never sent to log, regardless of log_min_level */
212 return false;
213 }
214 else if (log_min_level == LOG)
215 {
216 /* elevel != LOG */
217 if (elevel >= FATAL)
218 return true;
219 }
220 /* Neither is LOG */
221 else if (elevel >= log_min_level)
222 return true;
223
224 return false;
225}
226
227/*
228 * Policy-setting subroutines. These are fairly simple, but it seems wise
229 * to have the code in just one place.
230 */
231
232/*
233 * should_output_to_server --- should message of given elevel go to the log?
234 */
235static inline bool
237{
239}
240
241/*
242 * should_output_to_client --- should message of given elevel go to the client?
243 */
244static inline bool
246{
247 if (whereToSendOutput == DestRemote && elevel != LOG_SERVER_ONLY)
248 {
249 /*
250 * client_min_messages is honored only after we complete the
251 * authentication handshake. This is required both for security
252 * reasons and because many clients can't handle NOTICE messages
253 * during authentication.
254 */
256 return (elevel >= ERROR);
257 else
258 return (elevel >= client_min_messages || elevel == INFO);
259 }
260 return false;
261}
262
263
264/*
265 * message_level_is_interesting --- would ereport/elog do anything?
266 *
267 * Returns true if ereport/elog with this elevel will not be a no-op.
268 * This is useful to short-circuit any expensive preparatory work that
269 * might be needed for a logging message. There is no point in
270 * prepending this to a bare ereport/elog call, however.
271 */
272bool
274{
275 /*
276 * Keep this in sync with the decision-making in errstart().
277 */
278 if (elevel >= ERROR ||
279 should_output_to_server(elevel) ||
281 return true;
282 return false;
283}
284
285
286/*
287 * in_error_recursion_trouble --- are we at risk of infinite error recursion?
288 *
289 * This function exists to provide common control of various fallback steps
290 * that we take if we think we are facing infinite error recursion. See the
291 * callers for details.
292 */
293bool
295{
296 /* Pull the plug if recurse more than once */
297 return (recursion_depth > 2);
298}
299
300/*
301 * One of those fallback steps is to stop trying to localize the error
302 * message, since there's a significant probability that that's exactly
303 * what's causing the recursion.
304 */
305static inline const char *
306err_gettext(const char *str)
307{
308#ifdef ENABLE_NLS
310 return str;
311 else
312 return gettext(str);
313#else
314 return str;
315#endif
316}
317
318/*
319 * errstart_cold
320 * A simple wrapper around errstart, but hinted to be "cold". Supporting
321 * compilers are more likely to move code for branches containing this
322 * function into an area away from the calling function's code. This can
323 * result in more commonly executed code being more compact and fitting
324 * on fewer cache lines.
325 */
327errstart_cold(int elevel, const char *domain)
328{
329 return errstart(elevel, domain);
330}
331
332/*
333 * errstart --- begin an error-reporting cycle
334 *
335 * Create and initialize error stack entry. Subsequently, errmsg() and
336 * perhaps other routines will be called to further populate the stack entry.
337 * Finally, errfinish() will be called to actually process the error report.
338 *
339 * Returns true in normal case. Returns false to short-circuit the error
340 * report (if it's a warning or lower and not to be reported anywhere).
341 */
342bool
343errstart(int elevel, const char *domain)
344{
346 bool output_to_server;
347 bool output_to_client = false;
348 int i;
349
350 /*
351 * Check some cases in which we want to promote an error into a more
352 * severe error. None of this logic applies for non-error messages.
353 */
354 if (elevel >= ERROR)
355 {
356 /*
357 * If we are inside a critical section, all errors become PANIC
358 * errors. See miscadmin.h.
359 */
360 if (CritSectionCount > 0)
361 elevel = PANIC;
362
363 /*
364 * Check reasons for treating ERROR as FATAL:
365 *
366 * 1. we have no handler to pass the error to (implies we are in the
367 * postmaster or in backend startup).
368 *
369 * 2. ExitOnAnyError mode switch is set (initdb uses this).
370 *
371 * 3. the error occurred after proc_exit has begun to run. (It's
372 * proc_exit's responsibility to see that this doesn't turn into
373 * infinite recursion!)
374 */
375 if (elevel == ERROR)
376 {
377 if (PG_exception_stack == NULL ||
380 elevel = FATAL;
381 }
382
383 /*
384 * If the error level is ERROR or more, errfinish is not going to
385 * return to caller; therefore, if there is any stacked error already
386 * in progress it will be lost. This is more or less okay, except we
387 * do not want to have a FATAL or PANIC error downgraded because the
388 * reporting process was interrupted by a lower-grade error. So check
389 * the stack and make sure we panic if panic is warranted.
390 */
391 for (i = 0; i <= errordata_stack_depth; i++)
392 elevel = Max(elevel, errordata[i].elevel);
393 }
394
395 /*
396 * Now decide whether we need to process this report at all; if it's
397 * warning or less and not enabled for logging, just return false without
398 * starting up any error logging machinery.
399 */
400 output_to_server = should_output_to_server(elevel);
401 output_to_client = should_output_to_client(elevel);
402 if (elevel < ERROR && !output_to_server && !output_to_client)
403 return false;
404
405 /*
406 * We need to do some actual work. Make sure that memory context
407 * initialization has finished, else we can't do anything useful.
408 */
409 if (ErrorContext == NULL)
410 {
411 /* Oops, hard crash time; very little we can do safely here */
412 write_stderr("error occurred before error message processing is available\n");
413 exit(2);
414 }
415
416 /*
417 * Okay, crank up a stack entry to store the info in.
418 */
419
420 if (recursion_depth++ > 0 && elevel >= ERROR)
421 {
422 /*
423 * Oops, error during error processing. Clear ErrorContext as
424 * discussed at top of file. We will not return to the original
425 * error's reporter or handler, so we don't need it.
426 */
428
429 /*
430 * Infinite error recursion might be due to something broken in a
431 * context traceback routine. Abandon them too. We also abandon
432 * attempting to print the error statement (which, if long, could
433 * itself be the source of the recursive failure).
434 */
436 {
439 }
440 }
441
442 /* Initialize data for this error frame */
444 edata->elevel = elevel;
445 edata->output_to_server = output_to_server;
446 edata->output_to_client = output_to_client;
448 /* Select default errcode based on elevel */
449 if (elevel >= ERROR)
450 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
451 else if (elevel >= WARNING)
452 edata->sqlerrcode = ERRCODE_WARNING;
453 else
455
456 /*
457 * Any allocations for this error state level should go into ErrorContext
458 */
459 edata->assoc_context = ErrorContext;
460
462 return true;
463}
464
465/*
466 * errfinish --- end an error-reporting cycle
467 *
468 * Produce the appropriate error report(s) and pop the error stack.
469 *
470 * If elevel, as passed to errstart(), is ERROR or worse, control does not
471 * return to the caller. See elog.h for the error level definitions.
472 */
473void
474errfinish(const char *filename, int lineno, const char *funcname)
475{
477 int elevel;
478 MemoryContext oldcontext;
479 ErrorContextCallback *econtext;
480
483
484 /* Save the last few bits of error state into the stack entry */
486
487 elevel = edata->elevel;
488
489 /*
490 * Do processing in ErrorContext, which we hope has enough reserved space
491 * to report an error.
492 */
494
495 /* Collect backtrace, if enabled and we didn't already */
496 if (!edata->backtrace &&
497 edata->funcname &&
501
502 /*
503 * Call any context callback functions. Errors occurring in callback
504 * functions will be treated as recursive errors --- this ensures we will
505 * avoid infinite recursion (see errstart).
506 */
507 for (econtext = error_context_stack;
508 econtext != NULL;
509 econtext = econtext->previous)
510 econtext->callback(econtext->arg);
511
512 /*
513 * If ERROR (not more nor less) we pass it off to the current handler.
514 * Printing it and popping the stack is the responsibility of the handler.
515 */
516 if (elevel == ERROR)
517 {
518 /*
519 * We do some minimal cleanup before longjmp'ing so that handlers can
520 * execute in a reasonably sane state.
521 *
522 * Reset InterruptHoldoffCount in case we ereport'd from inside an
523 * interrupt holdoff section. (We assume here that no handler will
524 * itself be inside a holdoff section. If necessary, such a handler
525 * could save and restore InterruptHoldoffCount for itself, but this
526 * should make life easier for most.)
527 */
530
531 CritSectionCount = 0; /* should be unnecessary, but... */
532
533 /*
534 * Note that we leave CurrentMemoryContext set to ErrorContext. The
535 * handler should reset it to something else soon.
536 */
537
539 PG_RE_THROW();
540 }
541
542 /* Emit the message to the right places */
544
545 /*
546 * If this is the outermost recursion level, we can clean up by resetting
547 * ErrorContext altogether (compare FlushErrorState), which is good
548 * because it cleans up any random leakages that might have occurred in
549 * places such as context callback functions. If we're nested, we can
550 * only safely remove the subsidiary data of the current stack entry.
551 */
552 if (errordata_stack_depth == 0 && recursion_depth == 1)
554 else
556
557 /* Release stack entry and exit error-handling context */
559 MemoryContextSwitchTo(oldcontext);
561
562 /*
563 * Perform error recovery action as specified by elevel.
564 */
565 if (elevel == FATAL)
566 {
567 /*
568 * For a FATAL error, we let proc_exit clean up and exit.
569 *
570 * If we just reported a startup failure, the client will disconnect
571 * on receiving it, so don't send any more to the client.
572 */
575
576 /*
577 * fflush here is just to improve the odds that we get to see the
578 * error message, in case things are so hosed that proc_exit crashes.
579 * Any other code you might be tempted to add here should probably be
580 * in an on_proc_exit or on_shmem_exit callback instead.
581 */
582 fflush(NULL);
583
584 /*
585 * Let the cumulative stats system know. Only mark the session as
586 * terminated by fatal error if there is no other known cause.
587 */
590
591 /*
592 * Do normal process-exit cleanup, then return exit code 1 to indicate
593 * FATAL termination. The postmaster may or may not consider this
594 * worthy of panic, depending on which subprocess returns it.
595 */
596 proc_exit(1);
597 }
598
599 if (elevel >= PANIC)
600 {
601 /*
602 * Serious crash time. Postmaster will observe SIGABRT process exit
603 * status and kill the other backends too.
604 *
605 * XXX: what if we are *in* the postmaster? abort() won't kill our
606 * children...
607 */
608 fflush(NULL);
609 abort();
610 }
611
612 /*
613 * Check for cancel/die interrupt first --- this is so that the user can
614 * stop a query emitting tons of notice or warning messages, even if it's
615 * in a loop that otherwise fails to check for interrupts.
616 */
618}
619
620
621/*
622 * errsave_start --- begin a "soft" error-reporting cycle
623 *
624 * If "context" isn't an ErrorSaveContext node, this behaves as
625 * errstart(ERROR, domain), and the errsave() macro ends up acting
626 * exactly like ereport(ERROR, ...).
627 *
628 * If "context" is an ErrorSaveContext node, but the node creator only wants
629 * notification of the fact of a soft error without any details, we just set
630 * the error_occurred flag in the ErrorSaveContext node and return false,
631 * which will cause us to skip the remaining error processing steps.
632 *
633 * Otherwise, create and initialize error stack entry and return true.
634 * Subsequently, errmsg() and perhaps other routines will be called to further
635 * populate the stack entry. Finally, errsave_finish() will be called to
636 * tidy up.
637 */
638bool
639errsave_start(struct Node *context, const char *domain)
640{
641 ErrorSaveContext *escontext;
643
644 /*
645 * Do we have a context for soft error reporting? If not, just punt to
646 * errstart().
647 */
648 if (context == NULL || !IsA(context, ErrorSaveContext))
649 return errstart(ERROR, domain);
650
651 /* Report that a soft error was detected */
652 escontext = (ErrorSaveContext *) context;
653 escontext->error_occurred = true;
654
655 /* Nothing else to do if caller wants no further details */
656 if (!escontext->details_wanted)
657 return false;
658
659 /*
660 * Okay, crank up a stack entry to store the info in.
661 */
662
664
665 /* Initialize data for this error frame */
667 edata->elevel = LOG; /* signal all is well to errsave_finish */
669 /* Select default errcode based on the assumed elevel of ERROR */
670 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
671
672 /*
673 * Any allocations for this error state level should go into the caller's
674 * context. We don't need to pollute ErrorContext, or even require it to
675 * exist, in this code path.
676 */
677 edata->assoc_context = CurrentMemoryContext;
678
680 return true;
681}
682
683/*
684 * errsave_finish --- end a "soft" error-reporting cycle
685 *
686 * If errsave_start() decided this was a regular error, behave as
687 * errfinish(). Otherwise, package up the error details and save
688 * them in the ErrorSaveContext node.
689 */
690void
691errsave_finish(struct Node *context, const char *filename, int lineno,
692 const char *funcname)
693{
694 ErrorSaveContext *escontext = (ErrorSaveContext *) context;
696
697 /* verify stack depth before accessing *edata */
699
700 /*
701 * If errsave_start punted to errstart, then elevel will be ERROR or
702 * perhaps even PANIC. Punt likewise to errfinish.
703 */
704 if (edata->elevel >= ERROR)
705 {
706 errfinish(filename, lineno, funcname);
708 }
709
710 /*
711 * Else, we should package up the stack entry contents and deliver them to
712 * the caller.
713 */
715
716 /* Save the last few bits of error state into the stack entry */
718
719 /* Replace the LOG value that errsave_start inserted */
720 edata->elevel = ERROR;
721
722 /*
723 * We skip calling backtrace and context functions, which are more likely
724 * to cause trouble than provide useful context; they might act on the
725 * assumption that a transaction abort is about to occur.
726 */
727
728 /*
729 * Make a copy of the error info for the caller. All the subsidiary
730 * strings are already in the caller's context, so it's sufficient to
731 * flat-copy the stack entry.
732 */
733 escontext->error_data = palloc_object(ErrorData);
734 memcpy(escontext->error_data, edata, sizeof(ErrorData));
735
736 /* Exit error-handling context */
739}
740
741
742/*
743 * get_error_stack_entry --- allocate and initialize a new stack entry
744 *
745 * The entry should be freed, when we're done with it, by calling
746 * FreeErrorDataContents() and then decrementing errordata_stack_depth.
747 *
748 * Returning the entry's address is just a notational convenience,
749 * since it had better be errordata[errordata_stack_depth].
750 *
751 * Although the error stack is not large, we don't expect to run out of space.
752 * Using more than one entry implies a new error report during error recovery,
753 * which is possible but already suggests we're in trouble. If we exhaust the
754 * stack, almost certainly we are in an infinite loop of errors during error
755 * recovery, so we give up and PANIC.
756 *
757 * (Note that this is distinct from the recursion_depth checks, which
758 * guard against recursion while handling a single stack entry.)
759 */
760static ErrorData *
762{
764
765 /* Allocate error frame */
768 {
769 /* Wups, stack not big enough */
770 errordata_stack_depth = -1; /* make room on stack */
771 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
772 }
773
774 /* Initialize error frame to all zeroes/NULLs */
776 memset(edata, 0, sizeof(ErrorData));
777
778 /* Save errno immediately to ensure error parameter eval can't change it */
779 edata->saved_errno = errno;
780
781 return edata;
782}
783
784/*
785 * set_stack_entry_domain --- fill in the internationalization domain
786 */
787static void
789{
790 /* the default text domain is the backend's */
791 edata->domain = domain ? domain : PG_TEXTDOMAIN("postgres");
792 /* initialize context_domain the same way (see set_errcontext_domain()) */
793 edata->context_domain = edata->domain;
794}
795
796/*
797 * set_stack_entry_location --- fill in code-location details
798 *
799 * Store the values of __FILE__, __LINE__, and __func__ from the call site.
800 * We make an effort to normalize __FILE__, since compilers are inconsistent
801 * about how much of the path they'll include, and we'd prefer that the
802 * behavior not depend on that (especially, that it not vary with build path).
803 */
804static void
806 const char *filename, int lineno,
807 const char *funcname)
808{
809 if (filename)
810 {
811 const char *slash;
812
813 /* keep only base name, useful especially for vpath builds */
814 slash = strrchr(filename, '/');
815 if (slash)
816 filename = slash + 1;
817 /* Some Windows compilers use backslashes in __FILE__ strings */
818 slash = strrchr(filename, '\\');
819 if (slash)
820 filename = slash + 1;
821 }
822
823 edata->filename = filename;
824 edata->lineno = lineno;
825 edata->funcname = funcname;
826}
827
828/*
829 * matches_backtrace_functions --- checks whether the given funcname matches
830 * backtrace_functions
831 *
832 * See check_backtrace_functions.
833 */
834static bool
836{
837 const char *p;
838
839 if (!backtrace_function_list || funcname == NULL || funcname[0] == '\0')
840 return false;
841
843 for (;;)
844 {
845 if (*p == '\0') /* end of backtrace_function_list */
846 break;
847
848 if (strcmp(funcname, p) == 0)
849 return true;
850 p += strlen(p) + 1;
851 }
852
853 return false;
854}
855
856
857/*
858 * errcode --- add SQLSTATE error code to the current error
859 *
860 * The code is expected to be represented as per MAKE_SQLSTATE().
861 */
862int
863errcode(int sqlerrcode)
864{
866
867 /* we don't bother incrementing recursion_depth */
869
870 edata->sqlerrcode = sqlerrcode;
871
872 return 0; /* return value does not matter */
873}
874
875
876/*
877 * errcode_for_file_access --- add SQLSTATE error code to the current error
878 *
879 * The SQLSTATE code is chosen based on the saved errno value. We assume
880 * that the failing operation was some type of disk file access.
881 *
882 * NOTE: the primary error message string should generally include %m
883 * when this is used.
884 */
885int
887{
889
890 /* we don't bother incrementing recursion_depth */
892
893 switch (edata->saved_errno)
894 {
895 /* Permission-denied failures */
896 case EPERM: /* Not super-user */
897 case EACCES: /* Permission denied */
898#ifdef EROFS
899 case EROFS: /* Read only file system */
900#endif
902 break;
903
904 /* File not found */
905 case ENOENT: /* No such file or directory */
906 edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
907 break;
908
909 /* Duplicate file */
910 case EEXIST: /* File exists */
911 edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
912 break;
913
914 /* Wrong object type or state */
915 case ENOTDIR: /* Not a directory */
916 case EISDIR: /* Is a directory */
917 case ENOTEMPTY: /* Directory not empty */
918 edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
919 break;
920
921 /* Insufficient resources */
922 case ENOSPC: /* No space left on device */
923 edata->sqlerrcode = ERRCODE_DISK_FULL;
924 break;
925
926 case ENOMEM: /* Out of memory */
927 edata->sqlerrcode = ERRCODE_OUT_OF_MEMORY;
928 break;
929
930 case ENFILE: /* File table overflow */
931 case EMFILE: /* Too many open files */
933 break;
934
935 /* Hardware failure */
936 case EIO: /* I/O error */
937 edata->sqlerrcode = ERRCODE_IO_ERROR;
938 break;
939
940 case ENAMETOOLONG: /* File name too long */
941 edata->sqlerrcode = ERRCODE_FILE_NAME_TOO_LONG;
942 break;
943
944 /* All else is classified as internal errors */
945 default:
946 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
947 break;
948 }
949
950 return 0; /* return value does not matter */
951}
952
953/*
954 * errcode_for_socket_access --- add SQLSTATE error code to the current error
955 *
956 * The SQLSTATE code is chosen based on the saved errno value. We assume
957 * that the failing operation was some type of socket access.
958 *
959 * NOTE: the primary error message string should generally include %m
960 * when this is used.
961 */
962int
964{
966
967 /* we don't bother incrementing recursion_depth */
969
970 switch (edata->saved_errno)
971 {
972 /* Loss of connection */
974 edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
975 break;
976
977 /* All else is classified as internal errors */
978 default:
979 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
980 break;
981 }
982
983 return 0; /* return value does not matter */
984}
985
986
987/*
988 * This macro handles expansion of a format string and associated parameters;
989 * it's common code for errmsg(), errdetail(), etc. Must be called inside
990 * a routine that is declared like "const char *fmt, ..." and has an edata
991 * pointer set up. The message is assigned to edata->targetfield, or
992 * appended to it if appendval is true. The message is subject to translation
993 * if translateit is true.
994 *
995 * Note: we pstrdup the buffer rather than just transferring its storage
996 * to the edata field because the buffer might be considerably larger than
997 * really necessary.
998 */
999#define EVALUATE_MESSAGE(domain, targetfield, appendval, translateit) \
1000 { \
1001 StringInfoData buf; \
1002 /* Internationalize the error format string */ \
1003 if ((translateit) && !in_error_recursion_trouble()) \
1004 fmt = dgettext((domain), fmt); \
1005 initStringInfo(&buf); \
1006 if ((appendval) && edata->targetfield) { \
1007 appendStringInfoString(&buf, edata->targetfield); \
1008 appendStringInfoChar(&buf, '\n'); \
1009 } \
1010 /* Generate actual output --- have to use appendStringInfoVA */ \
1011 for (;;) \
1012 { \
1013 va_list args; \
1014 int needed; \
1015 errno = edata->saved_errno; \
1016 va_start(args, fmt); \
1017 needed = appendStringInfoVA(&buf, fmt, args); \
1018 va_end(args); \
1019 if (needed == 0) \
1020 break; \
1021 enlargeStringInfo(&buf, needed); \
1022 } \
1023 /* Save the completed message into the stack item */ \
1024 if (edata->targetfield) \
1025 pfree(edata->targetfield); \
1026 edata->targetfield = pstrdup(buf.data); \
1027 pfree(buf.data); \
1028 }
1029
1030/*
1031 * Same as above, except for pluralized error messages. The calling routine
1032 * must be declared like "const char *fmt_singular, const char *fmt_plural,
1033 * unsigned long n, ...". Translation is assumed always wanted.
1034 */
1035#define EVALUATE_MESSAGE_PLURAL(domain, targetfield, appendval) \
1036 { \
1037 const char *fmt; \
1038 StringInfoData buf; \
1039 /* Internationalize the error format string */ \
1040 if (!in_error_recursion_trouble()) \
1041 fmt = dngettext((domain), fmt_singular, fmt_plural, n); \
1042 else \
1043 fmt = (n == 1 ? fmt_singular : fmt_plural); \
1044 initStringInfo(&buf); \
1045 if ((appendval) && edata->targetfield) { \
1046 appendStringInfoString(&buf, edata->targetfield); \
1047 appendStringInfoChar(&buf, '\n'); \
1048 } \
1049 /* Generate actual output --- have to use appendStringInfoVA */ \
1050 for (;;) \
1051 { \
1052 va_list args; \
1053 int needed; \
1054 errno = edata->saved_errno; \
1055 va_start(args, n); \
1056 needed = appendStringInfoVA(&buf, fmt, args); \
1057 va_end(args); \
1058 if (needed == 0) \
1059 break; \
1060 enlargeStringInfo(&buf, needed); \
1061 } \
1062 /* Save the completed message into the stack item */ \
1063 if (edata->targetfield) \
1064 pfree(edata->targetfield); \
1065 edata->targetfield = pstrdup(buf.data); \
1066 pfree(buf.data); \
1067 }
1068
1069
1070/*
1071 * errmsg --- add a primary error message text to the current error
1072 *
1073 * In addition to the usual %-escapes recognized by printf, "%m" in
1074 * fmt is replaced by the error message for the caller's value of errno.
1075 *
1076 * Note: no newline is needed at the end of the fmt string, since
1077 * ereport will provide one for the output methods that need it.
1078 */
1079int
1080errmsg(const char *fmt,...)
1081{
1083 MemoryContext oldcontext;
1084
1087 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1088
1089 edata->message_id = fmt;
1090 EVALUATE_MESSAGE(edata->domain, message, false, true);
1091
1092 MemoryContextSwitchTo(oldcontext);
1094 return 0; /* return value does not matter */
1095}
1096
1097/*
1098 * Add a backtrace to the containing ereport() call. This is intended to be
1099 * added temporarily during debugging.
1100 */
1101int
1103{
1105 MemoryContext oldcontext;
1106
1109 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1110
1111 set_backtrace(edata, 1);
1112
1113 MemoryContextSwitchTo(oldcontext);
1115
1116 return 0;
1117}
1118
1119/*
1120 * Compute backtrace data and add it to the supplied ErrorData. num_skip
1121 * specifies how many inner frames to skip. Use this to avoid showing the
1122 * internal backtrace support functions in the backtrace. This requires that
1123 * this and related functions are not inlined.
1124 */
1125static void
1127{
1129
1131
1132#ifdef HAVE_BACKTRACE_SYMBOLS
1133 {
1134 void *buf[100];
1135 int nframes;
1136 char **strfrms;
1137
1138 nframes = backtrace(buf, lengthof(buf));
1140 if (strfrms != NULL)
1141 {
1142 for (int i = num_skip; i < nframes; i++)
1143 appendStringInfo(&errtrace, "\n%s", strfrms[i]);
1144 free(strfrms);
1145 }
1146 else
1148 "insufficient memory for backtrace generation");
1149 }
1150#else
1152 "backtrace generation is not supported by this installation");
1153#endif
1154
1155 edata->backtrace = errtrace.data;
1156}
1157
1158/*
1159 * errmsg_internal --- add a primary error message text to the current error
1160 *
1161 * This is exactly like errmsg() except that strings passed to errmsg_internal
1162 * are not translated, and are customarily left out of the
1163 * internationalization message dictionary. This should be used for "can't
1164 * happen" cases that are probably not worth spending translation effort on.
1165 * We also use this for certain cases where we *must* not try to translate
1166 * the message because the translation would fail and result in infinite
1167 * error recursion.
1168 */
1169int
1170errmsg_internal(const char *fmt,...)
1171{
1173 MemoryContext oldcontext;
1174
1177 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1178
1179 edata->message_id = fmt;
1180 EVALUATE_MESSAGE(edata->domain, message, false, false);
1181
1182 MemoryContextSwitchTo(oldcontext);
1184 return 0; /* return value does not matter */
1185}
1186
1187
1188/*
1189 * errmsg_plural --- add a primary error message text to the current error,
1190 * with support for pluralization of the message text
1191 */
1192int
1193errmsg_plural(const char *fmt_singular, const char *fmt_plural,
1194 unsigned long n,...)
1195{
1197 MemoryContext oldcontext;
1198
1201 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1202
1203 edata->message_id = fmt_singular;
1204 EVALUATE_MESSAGE_PLURAL(edata->domain, message, false);
1205
1206 MemoryContextSwitchTo(oldcontext);
1208 return 0; /* return value does not matter */
1209}
1210
1211
1212/*
1213 * errdetail --- add a detail error message text to the current error
1214 */
1215int
1216errdetail(const char *fmt,...)
1217{
1219 MemoryContext oldcontext;
1220
1223 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1224
1225 EVALUATE_MESSAGE(edata->domain, detail, false, true);
1226
1227 MemoryContextSwitchTo(oldcontext);
1229 return 0; /* return value does not matter */
1230}
1231
1232
1233/*
1234 * errdetail_internal --- add a detail error message text to the current error
1235 *
1236 * This is exactly like errdetail() except that strings passed to
1237 * errdetail_internal are not translated, and are customarily left out of the
1238 * internationalization message dictionary. This should be used for detail
1239 * messages that seem not worth translating for one reason or another
1240 * (typically, that they don't seem to be useful to average users).
1241 */
1242int
1243errdetail_internal(const char *fmt,...)
1244{
1246 MemoryContext oldcontext;
1247
1250 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1251
1252 EVALUATE_MESSAGE(edata->domain, detail, false, false);
1253
1254 MemoryContextSwitchTo(oldcontext);
1256 return 0; /* return value does not matter */
1257}
1258
1259
1260/*
1261 * errdetail_log --- add a detail_log error message text to the current error
1262 */
1263int
1264errdetail_log(const char *fmt,...)
1265{
1267 MemoryContext oldcontext;
1268
1271 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1272
1273 EVALUATE_MESSAGE(edata->domain, detail_log, false, true);
1274
1275 MemoryContextSwitchTo(oldcontext);
1277 return 0; /* return value does not matter */
1278}
1279
1280/*
1281 * errdetail_log_plural --- add a detail_log error message text to the current error
1282 * with support for pluralization of the message text
1283 */
1284int
1286 unsigned long n,...)
1287{
1289 MemoryContext oldcontext;
1290
1293 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1294
1295 EVALUATE_MESSAGE_PLURAL(edata->domain, detail_log, false);
1296
1297 MemoryContextSwitchTo(oldcontext);
1299 return 0; /* return value does not matter */
1300}
1301
1302
1303/*
1304 * errdetail_plural --- add a detail error message text to the current error,
1305 * with support for pluralization of the message text
1306 */
1307int
1309 unsigned long n,...)
1310{
1312 MemoryContext oldcontext;
1313
1316 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1317
1318 EVALUATE_MESSAGE_PLURAL(edata->domain, detail, false);
1319
1320 MemoryContextSwitchTo(oldcontext);
1322 return 0; /* return value does not matter */
1323}
1324
1325
1326/*
1327 * errhint --- add a hint error message text to the current error
1328 */
1329int
1330errhint(const char *fmt,...)
1331{
1333 MemoryContext oldcontext;
1334
1337 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1338
1339 EVALUATE_MESSAGE(edata->domain, hint, false, true);
1340
1341 MemoryContextSwitchTo(oldcontext);
1343 return 0; /* return value does not matter */
1344}
1345
1346/*
1347 * errhint_internal --- add a hint error message text to the current error
1348 *
1349 * Non-translated version of errhint(), see also errmsg_internal().
1350 */
1351int
1352errhint_internal(const char *fmt,...)
1353{
1355 MemoryContext oldcontext;
1356
1359 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1360
1361 EVALUATE_MESSAGE(edata->domain, hint, false, false);
1362
1363 MemoryContextSwitchTo(oldcontext);
1365 return 0; /* return value does not matter */
1366}
1367
1368/*
1369 * errhint_plural --- add a hint error message text to the current error,
1370 * with support for pluralization of the message text
1371 */
1372int
1373errhint_plural(const char *fmt_singular, const char *fmt_plural,
1374 unsigned long n,...)
1375{
1377 MemoryContext oldcontext;
1378
1381 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1382
1383 EVALUATE_MESSAGE_PLURAL(edata->domain, hint, false);
1384
1385 MemoryContextSwitchTo(oldcontext);
1387 return 0; /* return value does not matter */
1388}
1389
1390
1391/*
1392 * errcontext_msg --- add a context error message text to the current error
1393 *
1394 * Unlike other cases, multiple calls are allowed to build up a stack of
1395 * context information. We assume earlier calls represent more-closely-nested
1396 * states.
1397 */
1398int
1399errcontext_msg(const char *fmt,...)
1400{
1402 MemoryContext oldcontext;
1403
1406 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1407
1408 EVALUATE_MESSAGE(edata->context_domain, context, true, true);
1409
1410 MemoryContextSwitchTo(oldcontext);
1412 return 0; /* return value does not matter */
1413}
1414
1415/*
1416 * set_errcontext_domain --- set message domain to be used by errcontext()
1417 *
1418 * errcontext_msg() can be called from a different module than the original
1419 * ereport(), so we cannot use the message domain passed in errstart() to
1420 * translate it. Instead, each errcontext_msg() call should be preceded by
1421 * a set_errcontext_domain() call to specify the domain. This is usually
1422 * done transparently by the errcontext() macro.
1423 */
1424int
1425set_errcontext_domain(const char *domain)
1426{
1428
1429 /* we don't bother incrementing recursion_depth */
1431
1432 /* the default text domain is the backend's */
1433 edata->context_domain = domain ? domain : PG_TEXTDOMAIN("postgres");
1434
1435 return 0; /* return value does not matter */
1436}
1437
1438
1439/*
1440 * errhidestmt --- optionally suppress STATEMENT: field of log entry
1441 *
1442 * This should be called if the message text already includes the statement.
1443 */
1444int
1445errhidestmt(bool hide_stmt)
1446{
1448
1449 /* we don't bother incrementing recursion_depth */
1451
1452 edata->hide_stmt = hide_stmt;
1453
1454 return 0; /* return value does not matter */
1455}
1456
1457/*
1458 * errhidecontext --- optionally suppress CONTEXT: field of log entry
1459 *
1460 * This should only be used for verbose debugging messages where the repeated
1461 * inclusion of context would bloat the log volume too much.
1462 */
1463int
1464errhidecontext(bool hide_ctx)
1465{
1467
1468 /* we don't bother incrementing recursion_depth */
1470
1471 edata->hide_ctx = hide_ctx;
1472
1473 return 0; /* return value does not matter */
1474}
1475
1476/*
1477 * errposition --- add cursor position to the current error
1478 */
1479int
1480errposition(int cursorpos)
1481{
1483
1484 /* we don't bother incrementing recursion_depth */
1486
1487 edata->cursorpos = cursorpos;
1488
1489 return 0; /* return value does not matter */
1490}
1491
1492/*
1493 * internalerrposition --- add internal cursor position to the current error
1494 */
1495int
1497{
1499
1500 /* we don't bother incrementing recursion_depth */
1502
1503 edata->internalpos = cursorpos;
1504
1505 return 0; /* return value does not matter */
1506}
1507
1508/*
1509 * internalerrquery --- add internal query text to the current error
1510 *
1511 * Can also pass NULL to drop the internal query text entry. This case
1512 * is intended for use in error callback subroutines that are editorializing
1513 * on the layout of the error report.
1514 */
1515int
1516internalerrquery(const char *query)
1517{
1519
1520 /* we don't bother incrementing recursion_depth */
1522
1523 if (edata->internalquery)
1524 {
1525 pfree(edata->internalquery);
1526 edata->internalquery = NULL;
1527 }
1528
1529 if (query)
1530 edata->internalquery = MemoryContextStrdup(edata->assoc_context, query);
1531
1532 return 0; /* return value does not matter */
1533}
1534
1535/*
1536 * err_generic_string -- used to set individual ErrorData string fields
1537 * identified by PG_DIAG_xxx codes.
1538 *
1539 * This intentionally only supports fields that don't use localized strings,
1540 * so that there are no translation considerations.
1541 *
1542 * Most potential callers should not use this directly, but instead prefer
1543 * higher-level abstractions, such as errtablecol() (see relcache.c).
1544 */
1545int
1546err_generic_string(int field, const char *str)
1547{
1549
1550 /* we don't bother incrementing recursion_depth */
1552
1553 switch (field)
1554 {
1556 set_errdata_field(edata->assoc_context, &edata->schema_name, str);
1557 break;
1558 case PG_DIAG_TABLE_NAME:
1559 set_errdata_field(edata->assoc_context, &edata->table_name, str);
1560 break;
1562 set_errdata_field(edata->assoc_context, &edata->column_name, str);
1563 break;
1565 set_errdata_field(edata->assoc_context, &edata->datatype_name, str);
1566 break;
1568 set_errdata_field(edata->assoc_context, &edata->constraint_name, str);
1569 break;
1570 default:
1571 elog(ERROR, "unsupported ErrorData field id: %d", field);
1572 break;
1573 }
1574
1575 return 0; /* return value does not matter */
1576}
1577
1578/*
1579 * set_errdata_field --- set an ErrorData string field
1580 */
1581static void
1582set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str)
1583{
1584 Assert(*ptr == NULL);
1585 *ptr = MemoryContextStrdup(cxt, str);
1586}
1587
1588/*
1589 * geterrcode --- return the currently set SQLSTATE error code
1590 *
1591 * This is only intended for use in error callback subroutines, since there
1592 * is no other place outside elog.c where the concept is meaningful.
1593 */
1594int
1596{
1598
1599 /* we don't bother incrementing recursion_depth */
1601
1602 return edata->sqlerrcode;
1603}
1604
1605/*
1606 * geterrposition --- return the currently set error position (0 if none)
1607 *
1608 * This is only intended for use in error callback subroutines, since there
1609 * is no other place outside elog.c where the concept is meaningful.
1610 */
1611int
1613{
1615
1616 /* we don't bother incrementing recursion_depth */
1618
1619 return edata->cursorpos;
1620}
1621
1622/*
1623 * getinternalerrposition --- same for internal error position
1624 *
1625 * This is only intended for use in error callback subroutines, since there
1626 * is no other place outside elog.c where the concept is meaningful.
1627 */
1628int
1630{
1632
1633 /* we don't bother incrementing recursion_depth */
1635
1636 return edata->internalpos;
1637}
1638
1639
1640/*
1641 * Functions to allow construction of error message strings separately from
1642 * the ereport() call itself.
1643 *
1644 * The expected calling convention is
1645 *
1646 * pre_format_elog_string(errno, domain), var = format_elog_string(format,...)
1647 *
1648 * which can be hidden behind a macro such as GUC_check_errdetail(). We
1649 * assume that any functions called in the arguments of format_elog_string()
1650 * cannot result in re-entrant use of these functions --- otherwise the wrong
1651 * text domain might be used, or the wrong errno substituted for %m. This is
1652 * okay for the current usage with GUC check hooks, but might need further
1653 * effort someday.
1654 *
1655 * The result of format_elog_string() is stored in ErrorContext, and will
1656 * therefore survive until FlushErrorState() is called.
1657 */
1659static const char *save_format_domain;
1660
1661void
1662pre_format_elog_string(int errnumber, const char *domain)
1663{
1664 /* Save errno before evaluation of argument functions can change it */
1666 /* Save caller's text domain */
1667 save_format_domain = domain;
1668}
1669
1670char *
1671format_elog_string(const char *fmt,...)
1672{
1675 MemoryContext oldcontext;
1676
1677 /* Initialize a mostly-dummy error frame */
1678 edata = &errdata;
1679 MemSet(edata, 0, sizeof(ErrorData));
1680 /* the default text domain is the backend's */
1681 edata->domain = save_format_domain ? save_format_domain : PG_TEXTDOMAIN("postgres");
1682 /* set the errno to be used to interpret %m */
1683 edata->saved_errno = save_format_errnumber;
1684
1685 oldcontext = MemoryContextSwitchTo(ErrorContext);
1686
1687 edata->message_id = fmt;
1688 EVALUATE_MESSAGE(edata->domain, message, false, true);
1689
1690 MemoryContextSwitchTo(oldcontext);
1691
1692 return edata->message;
1693}
1694
1695
1696/*
1697 * Actual output of the top-of-stack error message
1698 *
1699 * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
1700 * if the error is caught by somebody). For all other severity levels this
1701 * is called by errfinish.
1702 */
1703void
1705{
1707 MemoryContext oldcontext;
1708
1711 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1712
1713 /*
1714 * Reset the formatted timestamp fields before emitting any logs. This
1715 * includes all the log destinations and emit_log_hook, as the latter
1716 * could use log_line_prefix or the formatted timestamps.
1717 */
1718 saved_timeval_set = false;
1719 formatted_log_time[0] = '\0';
1720
1721 /*
1722 * Call hook before sending message to log. The hook function is allowed
1723 * to turn off edata->output_to_server, so we must recheck that afterward.
1724 * Making any other change in the content of edata is not considered
1725 * supported.
1726 *
1727 * Note: the reason why the hook can only turn off output_to_server, and
1728 * not turn it on, is that it'd be unreliable: we will never get here at
1729 * all if errstart() deems the message uninteresting. A hook that could
1730 * make decisions in that direction would have to hook into errstart(),
1731 * where it would have much less information available. emit_log_hook is
1732 * intended for custom log filtering and custom log message transmission
1733 * mechanisms.
1734 *
1735 * The log hook has access to both the translated and original English
1736 * error message text, which is passed through to allow it to be used as a
1737 * message identifier. Note that the original text is not available for
1738 * detail, detail_log, hint and context text elements.
1739 */
1740 if (edata->output_to_server && emit_log_hook)
1741 (*emit_log_hook) (edata);
1742
1743 /* Send to server log, if enabled */
1744 if (edata->output_to_server)
1746
1747 /* Send to client, if enabled */
1748 if (edata->output_to_client)
1750
1751 MemoryContextSwitchTo(oldcontext);
1753}
1754
1755/*
1756 * CopyErrorData --- obtain a copy of the topmost error stack entry
1757 *
1758 * This is only for use in error handler code. The data is copied into the
1759 * current memory context, so callers should always switch away from
1760 * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
1761 */
1762ErrorData *
1764{
1767
1768 /*
1769 * we don't increment recursion_depth because out-of-memory here does not
1770 * indicate a problem within the error subsystem.
1771 */
1773
1775
1776 /* Copy the struct itself */
1778 memcpy(newedata, edata, sizeof(ErrorData));
1779
1780 /*
1781 * Make copies of separately-allocated strings. Note that we copy even
1782 * theoretically-constant strings such as filename. This is because those
1783 * could point into JIT-created code segments that might get unloaded at
1784 * transaction cleanup. In some cases we need the copied ErrorData to
1785 * survive transaction boundaries, so we'd better copy those strings too.
1786 */
1787 if (newedata->filename)
1788 newedata->filename = pstrdup(newedata->filename);
1789 if (newedata->funcname)
1790 newedata->funcname = pstrdup(newedata->funcname);
1791 if (newedata->domain)
1792 newedata->domain = pstrdup(newedata->domain);
1793 if (newedata->context_domain)
1794 newedata->context_domain = pstrdup(newedata->context_domain);
1795 if (newedata->message)
1796 newedata->message = pstrdup(newedata->message);
1797 if (newedata->detail)
1798 newedata->detail = pstrdup(newedata->detail);
1799 if (newedata->detail_log)
1800 newedata->detail_log = pstrdup(newedata->detail_log);
1801 if (newedata->hint)
1802 newedata->hint = pstrdup(newedata->hint);
1803 if (newedata->context)
1804 newedata->context = pstrdup(newedata->context);
1805 if (newedata->backtrace)
1806 newedata->backtrace = pstrdup(newedata->backtrace);
1807 if (newedata->message_id)
1808 newedata->message_id = pstrdup(newedata->message_id);
1809 if (newedata->schema_name)
1810 newedata->schema_name = pstrdup(newedata->schema_name);
1811 if (newedata->table_name)
1812 newedata->table_name = pstrdup(newedata->table_name);
1813 if (newedata->column_name)
1814 newedata->column_name = pstrdup(newedata->column_name);
1815 if (newedata->datatype_name)
1816 newedata->datatype_name = pstrdup(newedata->datatype_name);
1817 if (newedata->constraint_name)
1818 newedata->constraint_name = pstrdup(newedata->constraint_name);
1819 if (newedata->internalquery)
1820 newedata->internalquery = pstrdup(newedata->internalquery);
1821
1822 /* Use the calling context for string allocation */
1823 newedata->assoc_context = CurrentMemoryContext;
1824
1825 return newedata;
1826}
1827
1828/*
1829 * FreeErrorData --- free the structure returned by CopyErrorData.
1830 *
1831 * Error handlers should use this in preference to assuming they know all
1832 * the separately-allocated fields.
1833 */
1834void
1840
1841/*
1842 * FreeErrorDataContents --- free the subsidiary data of an ErrorData.
1843 *
1844 * This can be used on either an error stack entry or a copied ErrorData.
1845 */
1846static void
1848{
1849 if (edata->message)
1850 pfree(edata->message);
1851 if (edata->detail)
1852 pfree(edata->detail);
1853 if (edata->detail_log)
1854 pfree(edata->detail_log);
1855 if (edata->hint)
1856 pfree(edata->hint);
1857 if (edata->context)
1858 pfree(edata->context);
1859 if (edata->backtrace)
1860 pfree(edata->backtrace);
1861 if (edata->schema_name)
1862 pfree(edata->schema_name);
1863 if (edata->table_name)
1864 pfree(edata->table_name);
1865 if (edata->column_name)
1866 pfree(edata->column_name);
1867 if (edata->datatype_name)
1868 pfree(edata->datatype_name);
1869 if (edata->constraint_name)
1870 pfree(edata->constraint_name);
1871 if (edata->internalquery)
1872 pfree(edata->internalquery);
1873}
1874
1875/*
1876 * FlushErrorState --- flush the error state after error recovery
1877 *
1878 * This should be called by an error handler after it's done processing
1879 * the error; or as soon as it's done CopyErrorData, if it intends to
1880 * do stuff that is likely to provoke another error. You are not "out" of
1881 * the error subsystem until you have done this.
1882 */
1883void
1885{
1886 /*
1887 * Reset stack to empty. The only case where it would be more than one
1888 * deep is if we serviced an error that interrupted construction of
1889 * another message. We assume control escaped out of that message
1890 * construction and won't ever go back.
1891 */
1893 recursion_depth = 0;
1894 /* Delete all data in ErrorContext */
1896}
1897
1898/*
1899 * ThrowErrorData --- report an error described by an ErrorData structure
1900 *
1901 * This function should be called on an ErrorData structure that isn't stored
1902 * on the errordata stack and hasn't been processed yet. It will call
1903 * errstart() and errfinish() as needed, so those should not have already been
1904 * called.
1905 *
1906 * ThrowErrorData() is useful for handling soft errors. It's also useful for
1907 * re-reporting errors originally reported by background worker processes and
1908 * then propagated (with or without modification) to the backend responsible
1909 * for them.
1910 */
1911void
1913{
1915 MemoryContext oldcontext;
1916
1917 if (!errstart(edata->elevel, edata->domain))
1918 return; /* error is not to be reported at all */
1919
1922 oldcontext = MemoryContextSwitchTo(newedata->assoc_context);
1923
1924 /* Copy the supplied fields to the error stack entry. */
1925 if (edata->sqlerrcode != 0)
1926 newedata->sqlerrcode = edata->sqlerrcode;
1927 if (edata->message)
1928 newedata->message = pstrdup(edata->message);
1929 if (edata->detail)
1930 newedata->detail = pstrdup(edata->detail);
1931 if (edata->detail_log)
1932 newedata->detail_log = pstrdup(edata->detail_log);
1933 if (edata->hint)
1934 newedata->hint = pstrdup(edata->hint);
1935 if (edata->context)
1936 newedata->context = pstrdup(edata->context);
1937 if (edata->backtrace)
1938 newedata->backtrace = pstrdup(edata->backtrace);
1939 /* assume message_id is not available */
1940 if (edata->schema_name)
1941 newedata->schema_name = pstrdup(edata->schema_name);
1942 if (edata->table_name)
1943 newedata->table_name = pstrdup(edata->table_name);
1944 if (edata->column_name)
1945 newedata->column_name = pstrdup(edata->column_name);
1946 if (edata->datatype_name)
1947 newedata->datatype_name = pstrdup(edata->datatype_name);
1948 if (edata->constraint_name)
1949 newedata->constraint_name = pstrdup(edata->constraint_name);
1950 newedata->cursorpos = edata->cursorpos;
1951 newedata->internalpos = edata->internalpos;
1952 if (edata->internalquery)
1953 newedata->internalquery = pstrdup(edata->internalquery);
1954
1955 MemoryContextSwitchTo(oldcontext);
1957
1958 /* Process the error. */
1959 errfinish(edata->filename, edata->lineno, edata->funcname);
1960}
1961
1962/*
1963 * ReThrowError --- re-throw a previously copied error
1964 *
1965 * A handler can do CopyErrorData/FlushErrorState to get out of the error
1966 * subsystem, then do some processing, and finally ReThrowError to re-throw
1967 * the original error. This is slower than just PG_RE_THROW() but should
1968 * be used if the "some processing" is likely to incur another error.
1969 */
1970void
1972{
1974
1975 Assert(edata->elevel == ERROR);
1976
1977 /* Push the data back into the error context */
1980
1982 memcpy(newedata, edata, sizeof(ErrorData));
1983
1984 /* Make copies of separately-allocated fields */
1985 if (newedata->message)
1986 newedata->message = pstrdup(newedata->message);
1987 if (newedata->detail)
1988 newedata->detail = pstrdup(newedata->detail);
1989 if (newedata->detail_log)
1990 newedata->detail_log = pstrdup(newedata->detail_log);
1991 if (newedata->hint)
1992 newedata->hint = pstrdup(newedata->hint);
1993 if (newedata->context)
1994 newedata->context = pstrdup(newedata->context);
1995 if (newedata->backtrace)
1996 newedata->backtrace = pstrdup(newedata->backtrace);
1997 if (newedata->schema_name)
1998 newedata->schema_name = pstrdup(newedata->schema_name);
1999 if (newedata->table_name)
2000 newedata->table_name = pstrdup(newedata->table_name);
2001 if (newedata->column_name)
2002 newedata->column_name = pstrdup(newedata->column_name);
2003 if (newedata->datatype_name)
2004 newedata->datatype_name = pstrdup(newedata->datatype_name);
2005 if (newedata->constraint_name)
2006 newedata->constraint_name = pstrdup(newedata->constraint_name);
2007 if (newedata->internalquery)
2008 newedata->internalquery = pstrdup(newedata->internalquery);
2009
2010 /* Reset the assoc_context to be ErrorContext */
2011 newedata->assoc_context = ErrorContext;
2012
2014 PG_RE_THROW();
2015}
2016
2017/*
2018 * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
2019 */
2020void
2022{
2023 /* If possible, throw the error to the next outer setjmp handler */
2024 if (PG_exception_stack != NULL)
2026 else
2027 {
2028 /*
2029 * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
2030 * we have now exited only to discover that there is no outer setjmp
2031 * handler to pass the error to. Had the error been thrown outside
2032 * the block to begin with, we'd have promoted the error to FATAL, so
2033 * the correct behavior is to make it FATAL now; that is, emit it and
2034 * then call proc_exit.
2035 */
2037
2039 Assert(edata->elevel == ERROR);
2040 edata->elevel = FATAL;
2041
2042 /*
2043 * At least in principle, the increase in severity could have changed
2044 * where-to-output decisions, so recalculate.
2045 */
2046 edata->output_to_server = should_output_to_server(FATAL);
2047 edata->output_to_client = should_output_to_client(FATAL);
2048
2049 /*
2050 * We can use errfinish() for the rest, but we don't want it to call
2051 * any error context routines a second time. Since we know we are
2052 * about to exit, it should be OK to just clear the context stack.
2053 */
2055
2056 errfinish(edata->filename, edata->lineno, edata->funcname);
2057 }
2058
2059 /* Doesn't return ... */
2060 ExceptionalCondition("pg_re_throw tried to return", __FILE__, __LINE__);
2061}
2062
2063
2064/*
2065 * GetErrorContextStack - Return the context stack, for display/diags
2066 *
2067 * Returns a pstrdup'd string in the caller's context which includes the PG
2068 * error call stack. It is the caller's responsibility to ensure this string
2069 * is pfree'd (or its context cleaned up) when done.
2070 *
2071 * This information is collected by traversing the error contexts and calling
2072 * each context's callback function, each of which is expected to call
2073 * errcontext() to return a string which can be presented to the user.
2074 */
2075char *
2077{
2079 ErrorContextCallback *econtext;
2080
2081 /*
2082 * Crank up a stack entry to store the info in.
2083 */
2085
2087
2088 /*
2089 * Set up assoc_context to be the caller's context, so any allocations
2090 * done (which will include edata->context) will use their context.
2091 */
2092 edata->assoc_context = CurrentMemoryContext;
2093
2094 /*
2095 * Call any context callback functions to collect the context information
2096 * into edata->context.
2097 *
2098 * Errors occurring in callback functions should go through the regular
2099 * error handling code which should handle any recursive errors, though we
2100 * double-check above, just in case.
2101 */
2102 for (econtext = error_context_stack;
2103 econtext != NULL;
2104 econtext = econtext->previous)
2105 econtext->callback(econtext->arg);
2106
2107 /*
2108 * Clean ourselves off the stack, any allocations done should have been
2109 * using edata->assoc_context, which we set up earlier to be the caller's
2110 * context, so we're free to just remove our entry off the stack and
2111 * decrement recursion depth and exit.
2112 */
2115
2116 /*
2117 * Return a pointer to the string the caller asked for, which should have
2118 * been allocated in their context.
2119 */
2120 return edata->context;
2121}
2122
2123
2124/*
2125 * Initialization of error output file
2126 */
2127void
2129{
2130 int fd,
2131 istty;
2132
2133 if (OutputFileName[0])
2134 {
2135 /*
2136 * A debug-output file name was given.
2137 *
2138 * Make sure we can write the file, and find out if it's a tty.
2139 */
2141 0666)) < 0)
2142 ereport(FATAL,
2144 errmsg("could not open file \"%s\": %m", OutputFileName)));
2145 istty = isatty(fd);
2146 close(fd);
2147
2148 /*
2149 * Redirect our stderr to the debug output file.
2150 */
2151 if (!freopen(OutputFileName, "a", stderr))
2152 ereport(FATAL,
2154 errmsg("could not reopen file \"%s\" as stderr: %m",
2155 OutputFileName)));
2156
2157 /*
2158 * If the file is a tty and we're running under the postmaster, try to
2159 * send stdout there as well (if it isn't a tty then stderr will block
2160 * out stdout, so we may as well let stdout go wherever it was going
2161 * before).
2162 */
2163 if (istty && IsUnderPostmaster)
2164 if (!freopen(OutputFileName, "a", stdout))
2165 ereport(FATAL,
2167 errmsg("could not reopen file \"%s\" as stdout: %m",
2168 OutputFileName)));
2169 }
2170}
2171
2172
2173/*
2174 * GUC check_hook for backtrace_functions
2175 *
2176 * We split the input string, where commas separate function names
2177 * and certain whitespace chars are ignored, into a \0-separated (and
2178 * \0\0-terminated) list of function names. This formulation allows
2179 * easy scanning when an error is thrown while avoiding the use of
2180 * non-reentrant strtok(), as well as keeping the output data in a
2181 * single palloc() chunk.
2182 */
2183bool
2185{
2186 int newvallen = strlen(*newval);
2187 char *someval;
2188 int validlen;
2189 int i;
2190 int j;
2191
2192 /*
2193 * Allow characters that can be C identifiers and commas as separators, as
2194 * well as some whitespace for readability.
2195 */
2197 "0123456789_"
2198 "abcdefghijklmnopqrstuvwxyz"
2199 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2200 ", \n\t");
2201 if (validlen != newvallen)
2202 {
2203 GUC_check_errdetail("Invalid character.");
2204 return false;
2205 }
2206
2207 if (*newval[0] == '\0')
2208 {
2209 *extra = NULL;
2210 return true;
2211 }
2212
2213 /*
2214 * Allocate space for the output and create the copy. We could discount
2215 * whitespace chars to save some memory, but it doesn't seem worth the
2216 * trouble.
2217 */
2218 someval = guc_malloc(LOG, newvallen + 1 + 1);
2219 if (!someval)
2220 return false;
2221 for (i = 0, j = 0; i < newvallen; i++)
2222 {
2223 if ((*newval)[i] == ',')
2224 someval[j++] = '\0'; /* next item */
2225 else if ((*newval)[i] == ' ' ||
2226 (*newval)[i] == '\n' ||
2227 (*newval)[i] == '\t')
2228 ; /* ignore these */
2229 else
2230 someval[j++] = (*newval)[i]; /* copy anything else */
2231 }
2232
2233 /* two \0s end the setting */
2234 someval[j] = '\0';
2235 someval[j + 1] = '\0';
2236
2237 *extra = someval;
2238 return true;
2239}
2240
2241/*
2242 * GUC assign_hook for backtrace_functions
2243 */
2244void
2245assign_backtrace_functions(const char *newval, void *extra)
2246{
2247 backtrace_function_list = (char *) extra;
2248}
2249
2250/*
2251 * GUC check_hook for log_destination
2252 */
2253bool
2255{
2256 char *rawstring;
2257 List *elemlist;
2258 ListCell *l;
2259 int newlogdest = 0;
2260 int *myextra;
2261
2262 /* Need a modifiable copy of string */
2264
2265 /* Parse string into list of identifiers */
2267 {
2268 /* syntax error in list */
2269 GUC_check_errdetail("List syntax is invalid.");
2272 return false;
2273 }
2274
2275 foreach(l, elemlist)
2276 {
2277 char *tok = (char *) lfirst(l);
2278
2279 if (pg_strcasecmp(tok, "stderr") == 0)
2281 else if (pg_strcasecmp(tok, "csvlog") == 0)
2283 else if (pg_strcasecmp(tok, "jsonlog") == 0)
2285#ifdef HAVE_SYSLOG
2286 else if (pg_strcasecmp(tok, "syslog") == 0)
2288#endif
2289#ifdef WIN32
2290 else if (pg_strcasecmp(tok, "eventlog") == 0)
2292#endif
2293 else
2294 {
2295 GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
2298 return false;
2299 }
2300 }
2301
2304
2305 myextra = (int *) guc_malloc(LOG, sizeof(int));
2306 if (!myextra)
2307 return false;
2309 *extra = myextra;
2310
2311 return true;
2312}
2313
2314/*
2315 * GUC assign_hook for log_destination
2316 */
2317void
2318assign_log_destination(const char *newval, void *extra)
2319{
2320 Log_destination = *((int *) extra);
2321}
2322
2323/*
2324 * GUC assign_hook for syslog_ident
2325 */
2326void
2327assign_syslog_ident(const char *newval, void *extra)
2328{
2329#ifdef HAVE_SYSLOG
2330 /*
2331 * guc.c is likely to call us repeatedly with same parameters, so don't
2332 * thrash the syslog connection unnecessarily. Also, we do not re-open
2333 * the connection until needed, since this routine will get called whether
2334 * or not Log_destination actually mentions syslog.
2335 *
2336 * Note that we make our own copy of the ident string rather than relying
2337 * on guc.c's. This may be overly paranoid, but it ensures that we cannot
2338 * accidentally free a string that syslog is still using.
2339 */
2340 if (syslog_ident == NULL || strcmp(syslog_ident, newval) != 0)
2341 {
2342 if (openlog_done)
2343 {
2344 closelog();
2345 openlog_done = false;
2346 }
2349 /* if the strdup fails, we will cope in write_syslog() */
2350 }
2351#endif
2352 /* Without syslog support, just ignore it */
2353}
2354
2355/*
2356 * GUC assign_hook for syslog_facility
2357 */
2358void
2360{
2361#ifdef HAVE_SYSLOG
2362 /*
2363 * As above, don't thrash the syslog connection unnecessarily.
2364 */
2365 if (syslog_facility != newval)
2366 {
2367 if (openlog_done)
2368 {
2369 closelog();
2370 openlog_done = false;
2371 }
2373 }
2374#endif
2375 /* Without syslog support, just ignore it */
2376}
2377
2378#ifdef HAVE_SYSLOG
2379
2380/*
2381 * Write a message line to syslog
2382 */
2383static void
2384write_syslog(int level, const char *line)
2385{
2386 static unsigned long seq = 0;
2387
2388 int len;
2389 const char *nlpos;
2390
2391 /* Open syslog connection if not done yet */
2392 if (!openlog_done)
2393 {
2394 openlog(syslog_ident ? syslog_ident : "postgres",
2397 openlog_done = true;
2398 }
2399
2400 /*
2401 * We add a sequence number to each log message to suppress "same"
2402 * messages.
2403 */
2404 seq++;
2405
2406 /*
2407 * Our problem here is that many syslog implementations don't handle long
2408 * messages in an acceptable manner. While this function doesn't help that
2409 * fact, it does work around by splitting up messages into smaller pieces.
2410 *
2411 * We divide into multiple syslog() calls if message is too long or if the
2412 * message contains embedded newline(s).
2413 */
2414 len = strlen(line);
2415 nlpos = strchr(line, '\n');
2417 {
2418 int chunk_nr = 0;
2419
2420 while (len > 0)
2421 {
2422 char buf[PG_SYSLOG_LIMIT + 1];
2423 int buflen;
2424 int i;
2425
2426 /* if we start at a newline, move ahead one char */
2427 if (line[0] == '\n')
2428 {
2429 line++;
2430 len--;
2431 /* we need to recompute the next newline's position, too */
2432 nlpos = strchr(line, '\n');
2433 continue;
2434 }
2435
2436 /* copy one line, or as much as will fit, to buf */
2437 if (nlpos != NULL)
2438 buflen = nlpos - line;
2439 else
2440 buflen = len;
2441 buflen = Min(buflen, PG_SYSLOG_LIMIT);
2442 memcpy(buf, line, buflen);
2443 buf[buflen] = '\0';
2444
2445 /* trim to multibyte letter boundary */
2446 buflen = pg_mbcliplen(buf, buflen, buflen);
2447 if (buflen <= 0)
2448 return;
2449 buf[buflen] = '\0';
2450
2451 /* already word boundary? */
2452 if (line[buflen] != '\0' &&
2453 !isspace((unsigned char) line[buflen]))
2454 {
2455 /* try to divide at word boundary */
2456 i = buflen - 1;
2457 while (i > 0 && !isspace((unsigned char) buf[i]))
2458 i--;
2459
2460 if (i > 0) /* else couldn't divide word boundary */
2461 {
2462 buflen = i;
2463 buf[i] = '\0';
2464 }
2465 }
2466
2467 chunk_nr++;
2468
2470 syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
2471 else
2472 syslog(level, "[%d] %s", chunk_nr, buf);
2473
2474 line += buflen;
2475 len -= buflen;
2476 }
2477 }
2478 else
2479 {
2480 /* message short enough */
2482 syslog(level, "[%lu] %s", seq, line);
2483 else
2484 syslog(level, "%s", line);
2485 }
2486}
2487#endif /* HAVE_SYSLOG */
2488
2489#ifdef WIN32
2490/*
2491 * Get the PostgreSQL equivalent of the Windows ANSI code page. "ANSI" system
2492 * interfaces (e.g. CreateFileA()) expect string arguments in this encoding.
2493 * Every process in a given system will find the same value at all times.
2494 */
2495static int
2496GetACPEncoding(void)
2497{
2498 static int encoding = -2;
2499
2500 if (encoding == -2)
2502
2503 return encoding;
2504}
2505
2506/*
2507 * Write a message line to the windows event log
2508 */
2509static void
2510write_eventlog(int level, const char *line, int len)
2511{
2512 WCHAR *utf16;
2515
2517 {
2520 if (evtHandle == NULL)
2521 {
2523 return;
2524 }
2525 }
2526
2527 switch (level)
2528 {
2529 case DEBUG5:
2530 case DEBUG4:
2531 case DEBUG3:
2532 case DEBUG2:
2533 case DEBUG1:
2534 case LOG:
2535 case LOG_SERVER_ONLY:
2536 case INFO:
2537 case NOTICE:
2539 break;
2540 case WARNING:
2543 break;
2544 case ERROR:
2545 case FATAL:
2546 case PANIC:
2547 default:
2549 break;
2550 }
2551
2552 /*
2553 * If message character encoding matches the encoding expected by
2554 * ReportEventA(), call it to avoid the hazards of conversion. Otherwise,
2555 * try to convert the message to UTF16 and write it with ReportEventW().
2556 * Fall back on ReportEventA() if conversion failed.
2557 *
2558 * Since we palloc the structure required for conversion, also fall
2559 * through to writing unconverted if we have not yet set up
2560 * CurrentMemoryContext.
2561 *
2562 * Also verify that we are not on our way into error recursion trouble due
2563 * to error messages thrown deep inside pgwin32_message_to_UTF16().
2564 */
2568 {
2570 if (utf16)
2571 {
2573 eventlevel,
2574 0,
2575 0, /* All events are Id 0 */
2576 NULL,
2577 1,
2578 0,
2579 (LPCWSTR *) &utf16,
2580 NULL);
2581 /* XXX Try ReportEventA() when ReportEventW() fails? */
2582
2583 pfree(utf16);
2584 return;
2585 }
2586 }
2588 eventlevel,
2589 0,
2590 0, /* All events are Id 0 */
2591 NULL,
2592 1,
2593 0,
2594 &line,
2595 NULL);
2596}
2597#endif /* WIN32 */
2598
2599static void
2600write_console(const char *line, int len)
2601{
2602 int rc;
2603
2604#ifdef WIN32
2605
2606 /*
2607 * Try to convert the message to UTF16 and write it with WriteConsoleW().
2608 * Fall back on write() if anything fails.
2609 *
2610 * In contrast to write_eventlog(), don't skip straight to write() based
2611 * on the applicable encodings. Unlike WriteConsoleW(), write() depends
2612 * on the suitability of the console output code page. Since we put
2613 * stderr into binary mode in SubPostmasterMain(), write() skips the
2614 * necessary translation anyway.
2615 *
2616 * WriteConsoleW() will fail if stderr is redirected, so just fall through
2617 * to writing unconverted to the logfile in this case.
2618 *
2619 * Since we palloc the structure required for conversion, also fall
2620 * through to writing unconverted if we have not yet set up
2621 * CurrentMemoryContext.
2622 */
2626 {
2627 WCHAR *utf16;
2628 int utf16len;
2629
2631 if (utf16 != NULL)
2632 {
2634 DWORD written;
2635
2638 {
2639 pfree(utf16);
2640 return;
2641 }
2642
2643 /*
2644 * In case WriteConsoleW() failed, fall back to writing the
2645 * message unconverted.
2646 */
2647 pfree(utf16);
2648 }
2649 }
2650#else
2651
2652 /*
2653 * Conversion on non-win32 platforms is not implemented yet. It requires
2654 * non-throw version of pg_do_encoding_conversion(), that converts
2655 * unconvertible characters to '?' without errors.
2656 *
2657 * XXX: We have a no-throw version now. It doesn't convert to '?' though.
2658 */
2659#endif
2660
2661 /*
2662 * We ignore any error from write() here. We have no useful way to report
2663 * it ... certainly whining on stderr isn't likely to be productive.
2664 */
2665 rc = write(fileno(stderr), line, len);
2666 (void) rc;
2667}
2668
2669/*
2670 * get_formatted_log_time -- compute and get the log timestamp.
2671 *
2672 * The timestamp is computed if not set yet, so as it is kept consistent
2673 * among all the log destinations that require it to be consistent. Note
2674 * that the computed timestamp is returned in a static buffer, not
2675 * palloc()'d.
2676 */
2677char *
2679{
2681 char msbuf[13];
2682
2683 /* leave if already computed */
2684 if (formatted_log_time[0] != '\0')
2685 return formatted_log_time;
2686
2687 if (!saved_timeval_set)
2688 {
2690 saved_timeval_set = true;
2691 }
2692
2694
2695 /*
2696 * Note: we expect that guc.c will ensure that log_timezone is set up (at
2697 * least with a minimal GMT value) before Log_line_prefix can become
2698 * nonempty or CSV/JSON mode can be selected.
2699 */
2701 /* leave room for milliseconds... */
2702 "%Y-%m-%d %H:%M:%S %Z",
2704
2705 /* 'paste' milliseconds into place... */
2706 sprintf(msbuf, ".%03d", (int) (saved_timeval.tv_usec / 1000));
2708
2709 return formatted_log_time;
2710}
2711
2712/*
2713 * reset_formatted_start_time -- reset the start timestamp
2714 */
2715void
2717{
2718 formatted_start_time[0] = '\0';
2719}
2720
2721/*
2722 * get_formatted_start_time -- compute and get the start timestamp.
2723 *
2724 * The timestamp is computed if not set yet. Note that the computed
2725 * timestamp is returned in a static buffer, not palloc()'d.
2726 */
2727char *
2729{
2731
2732 /* leave if already computed */
2733 if (formatted_start_time[0] != '\0')
2734 return formatted_start_time;
2735
2736 /*
2737 * Note: we expect that guc.c will ensure that log_timezone is set up (at
2738 * least with a minimal GMT value) before Log_line_prefix can become
2739 * nonempty or CSV/JSON mode can be selected.
2740 */
2742 "%Y-%m-%d %H:%M:%S %Z",
2744
2745 return formatted_start_time;
2746}
2747
2748/*
2749 * check_log_of_query -- check if a query can be logged
2750 */
2751bool
2753{
2754 /* log required? */
2756 return false;
2757
2758 /* query log wanted? */
2759 if (edata->hide_stmt)
2760 return false;
2761
2762 /* query string available? */
2763 if (debug_query_string == NULL)
2764 return false;
2765
2766 return true;
2767}
2768
2769/*
2770 * get_backend_type_for_log -- backend type for log entries
2771 *
2772 * Returns a pointer to a static buffer, not palloc()'d.
2773 */
2774const char *
2776{
2777 const char *backend_type_str;
2778
2779 if (MyProcPid == PostmasterPid)
2780 backend_type_str = "postmaster";
2781 else if (MyBackendType == B_BG_WORKER)
2782 {
2783 if (MyBgworkerEntry)
2785 else
2786 backend_type_str = "early bgworker";
2787 }
2788 else
2790
2791 return backend_type_str;
2792}
2793
2794/*
2795 * process_log_prefix_padding --- helper function for processing the format
2796 * string in log_line_prefix
2797 *
2798 * Note: This function returns NULL if it finds something which
2799 * it deems invalid in the format string.
2800 */
2801static const char *
2803{
2804 int paddingsign = 1;
2805 int padding = 0;
2806
2807 if (*p == '-')
2808 {
2809 p++;
2810
2811 if (*p == '\0') /* Did the buf end in %- ? */
2812 return NULL;
2813 paddingsign = -1;
2814 }
2815
2816 /* generate an int version of the numerical string */
2817 while (*p >= '0' && *p <= '9')
2818 padding = padding * 10 + (*p++ - '0');
2819
2820 /* format is invalid if it ends with the padding number */
2821 if (*p == '\0')
2822 return NULL;
2823
2824 padding *= paddingsign;
2825 *ppadding = padding;
2826 return p;
2827}
2828
2829/*
2830 * Format log status information using Log_line_prefix.
2831 */
2832static void
2837
2838/*
2839 * Format log status info; append to the provided buffer.
2840 */
2841void
2843{
2844 /* static counter for line numbers */
2845 static long log_line_number = 0;
2846
2847 /* has counter been reset in current process? */
2848 static int log_my_pid = 0;
2849 int padding;
2850 const char *p;
2851
2852 /*
2853 * This is one of the few places where we'd rather not inherit a static
2854 * variable's value from the postmaster. But since we will, reset it when
2855 * MyProcPid changes. MyStartTime also changes when MyProcPid does, so
2856 * reset the formatted start timestamp too.
2857 */
2858 if (log_my_pid != MyProcPid)
2859 {
2860 log_line_number = 0;
2863 }
2865
2866 if (format == NULL)
2867 return; /* in case guc hasn't run yet */
2868
2869 for (p = format; *p != '\0'; p++)
2870 {
2871 if (*p != '%')
2872 {
2873 /* literal char, just copy */
2875 continue;
2876 }
2877
2878 /* must be a '%', so skip to the next char */
2879 p++;
2880 if (*p == '\0')
2881 break; /* format error - ignore it */
2882 else if (*p == '%')
2883 {
2884 /* string contains %% */
2886 continue;
2887 }
2888
2889
2890 /*
2891 * Process any formatting which may exist after the '%'. Note that
2892 * process_log_prefix_padding moves p past the padding number if it
2893 * exists.
2894 *
2895 * Note: Since only '-', '0' to '9' are valid formatting characters we
2896 * can do a quick check here to pre-check for formatting. If the char
2897 * is not formatting then we can skip a useless function call.
2898 *
2899 * Further note: At least on some platforms, passing %*s rather than
2900 * %s to appendStringInfo() is substantially slower, so many of the
2901 * cases below avoid doing that unless non-zero padding is in fact
2902 * specified.
2903 */
2904 if (*p > '9')
2905 padding = 0;
2906 else if ((p = process_log_prefix_padding(p, &padding)) == NULL)
2907 break;
2908
2909 /* process the option */
2910 switch (*p)
2911 {
2912 case 'a':
2913 if (MyProcPort)
2914 {
2915 const char *appname = application_name;
2916
2917 if (appname == NULL || *appname == '\0')
2918 appname = _("[unknown]");
2919 if (padding != 0)
2920 appendStringInfo(buf, "%*s", padding, appname);
2921 else
2922 appendStringInfoString(buf, appname);
2923 }
2924 else if (padding != 0)
2926 padding > 0 ? padding : -padding);
2927
2928 break;
2929 case 'b':
2930 {
2932
2933 if (padding != 0)
2934 appendStringInfo(buf, "%*s", padding, backend_type_str);
2935 else
2937 break;
2938 }
2939 case 'u':
2940 if (MyProcPort)
2941 {
2942 const char *username = MyProcPort->user_name;
2943
2944 if (username == NULL || *username == '\0')
2945 username = _("[unknown]");
2946 if (padding != 0)
2947 appendStringInfo(buf, "%*s", padding, username);
2948 else
2950 }
2951 else if (padding != 0)
2953 padding > 0 ? padding : -padding);
2954 break;
2955 case 'd':
2956 if (MyProcPort)
2957 {
2958 const char *dbname = MyProcPort->database_name;
2959
2960 if (dbname == NULL || *dbname == '\0')
2961 dbname = _("[unknown]");
2962 if (padding != 0)
2963 appendStringInfo(buf, "%*s", padding, dbname);
2964 else
2966 }
2967 else if (padding != 0)
2969 padding > 0 ? padding : -padding);
2970 break;
2971 case 'c':
2972 if (padding != 0)
2973 {
2974 char strfbuf[128];
2975
2976 snprintf(strfbuf, sizeof(strfbuf) - 1, "%" PRIx64 ".%x",
2978 appendStringInfo(buf, "%*s", padding, strfbuf);
2979 }
2980 else
2982 break;
2983 case 'p':
2984 if (padding != 0)
2985 appendStringInfo(buf, "%*d", padding, MyProcPid);
2986 else
2988 break;
2989
2990 case 'P':
2991 if (MyProc)
2992 {
2993 PGPROC *leader = MyProc->lockGroupLeader;
2994
2995 /*
2996 * Show the leader only for active parallel workers. This
2997 * leaves out the leader of a parallel group.
2998 */
2999 if (leader == NULL || leader->pid == MyProcPid)
3001 padding > 0 ? padding : -padding);
3002 else if (padding != 0)
3003 appendStringInfo(buf, "%*d", padding, leader->pid);
3004 else
3005 appendStringInfo(buf, "%d", leader->pid);
3006 }
3007 else if (padding != 0)
3009 padding > 0 ? padding : -padding);
3010 break;
3011
3012 case 'l':
3013 if (padding != 0)
3014 appendStringInfo(buf, "%*ld", padding, log_line_number);
3015 else
3017 break;
3018 case 'm':
3019 /* force a log timestamp reset */
3020 formatted_log_time[0] = '\0';
3022
3023 if (padding != 0)
3024 appendStringInfo(buf, "%*s", padding, formatted_log_time);
3025 else
3027 break;
3028 case 't':
3029 {
3031 char strfbuf[128];
3032
3033 pg_strftime(strfbuf, sizeof(strfbuf),
3034 "%Y-%m-%d %H:%M:%S %Z",
3036 if (padding != 0)
3037 appendStringInfo(buf, "%*s", padding, strfbuf);
3038 else
3040 }
3041 break;
3042 case 'n':
3043 {
3044 char strfbuf[128];
3045
3046 if (!saved_timeval_set)
3047 {
3049 saved_timeval_set = true;
3050 }
3051
3052 snprintf(strfbuf, sizeof(strfbuf), "%ld.%03d",
3053 (long) saved_timeval.tv_sec,
3054 (int) (saved_timeval.tv_usec / 1000));
3055
3056 if (padding != 0)
3057 appendStringInfo(buf, "%*s", padding, strfbuf);
3058 else
3060 }
3061 break;
3062 case 's':
3063 {
3065
3066 if (padding != 0)
3067 appendStringInfo(buf, "%*s", padding, start_time);
3068 else
3070 }
3071 break;
3072 case 'i':
3073 if (MyProcPort)
3074 {
3075 const char *psdisp;
3076 int displen;
3077
3079 if (padding != 0)
3080 appendStringInfo(buf, "%*s", padding, psdisp);
3081 else
3083 }
3084 else if (padding != 0)
3086 padding > 0 ? padding : -padding);
3087 break;
3088 case 'L':
3089 {
3090 const char *local_host;
3091
3092 if (MyProcPort)
3093 {
3094 if (MyProcPort->local_host[0] == '\0')
3095 {
3096 /*
3097 * First time through: cache the lookup, since it
3098 * might not have trivial cost.
3099 */
3103 sizeof(MyProcPort->local_host),
3104 NULL, 0,
3106 }
3107 local_host = MyProcPort->local_host;
3108 }
3109 else
3110 {
3111 /* Background process, or connection not yet made */
3112 local_host = "[none]";
3113 }
3114 if (padding != 0)
3115 appendStringInfo(buf, "%*s", padding, local_host);
3116 else
3117 appendStringInfoString(buf, local_host);
3118 }
3119 break;
3120 case 'r':
3122 {
3123 if (padding != 0)
3124 {
3125 if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
3126 {
3127 /*
3128 * This option is slightly special as the port
3129 * number may be appended onto the end. Here we
3130 * need to build 1 string which contains the
3131 * remote_host and optionally the remote_port (if
3132 * set) so we can properly align the string.
3133 */
3134
3135 char *hostport;
3136
3138 appendStringInfo(buf, "%*s", padding, hostport);
3139 pfree(hostport);
3140 }
3141 else
3142 appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
3143 }
3144 else
3145 {
3146 /* padding is 0, so we don't need a temp buffer */
3148 if (MyProcPort->remote_port &&
3149 MyProcPort->remote_port[0] != '\0')
3150 appendStringInfo(buf, "(%s)",
3152 }
3153 }
3154 else if (padding != 0)
3156 padding > 0 ? padding : -padding);
3157 break;
3158 case 'h':
3160 {
3161 if (padding != 0)
3162 appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
3163 else
3165 }
3166 else if (padding != 0)
3168 padding > 0 ? padding : -padding);
3169 break;
3170 case 'q':
3171 /* in postmaster and friends, stop if %q is seen */
3172 /* in a backend, just ignore */
3173 if (MyProcPort == NULL)
3174 return;
3175 break;
3176 case 'v':
3177 /* keep VXID format in sync with lockfuncs.c */
3179 {
3180 if (padding != 0)
3181 {
3182 char strfbuf[128];
3183
3184 snprintf(strfbuf, sizeof(strfbuf) - 1, "%d/%u",
3186 appendStringInfo(buf, "%*s", padding, strfbuf);
3187 }
3188 else
3190 }
3191 else if (padding != 0)
3193 padding > 0 ? padding : -padding);
3194 break;
3195 case 'x':
3196 if (padding != 0)
3197 appendStringInfo(buf, "%*u", padding, GetTopTransactionIdIfAny());
3198 else
3200 break;
3201 case 'e':
3202 if (padding != 0)
3203 appendStringInfo(buf, "%*s", padding, unpack_sql_state(edata->sqlerrcode));
3204 else
3206 break;
3207 case 'Q':
3208 if (padding != 0)
3209 appendStringInfo(buf, "%*" PRId64, padding,
3211 else
3214 break;
3215 default:
3216 /* format error - ignore it */
3217 break;
3218 }
3219 }
3220}
3221
3222/*
3223 * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
3224 * static buffer.
3225 */
3226char *
3228{
3229 static char buf[12];
3230 int i;
3231
3232 for (i = 0; i < 5; i++)
3233 {
3235 sql_state >>= 6;
3236 }
3237
3238 buf[i] = '\0';
3239 return buf;
3240}
3241
3242
3243/*
3244 * Write error report to server's log
3245 */
3246static void
3248{
3250 bool fallback_to_stderr = false;
3251
3253
3255 appendStringInfo(&buf, "%s: ", _(error_severity(edata->elevel)));
3256
3258 appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
3259
3260 if (edata->message)
3261 append_with_tabs(&buf, edata->message);
3262 else
3263 append_with_tabs(&buf, _("missing error text"));
3264
3265 if (edata->cursorpos > 0)
3266 appendStringInfo(&buf, _(" at character %d"),
3267 edata->cursorpos);
3268 else if (edata->internalpos > 0)
3269 appendStringInfo(&buf, _(" at character %d"),
3270 edata->internalpos);
3271
3272 appendStringInfoChar(&buf, '\n');
3273
3275 {
3276 if (edata->detail_log)
3277 {
3279 appendStringInfoString(&buf, _("DETAIL: "));
3280 append_with_tabs(&buf, edata->detail_log);
3281 appendStringInfoChar(&buf, '\n');
3282 }
3283 else if (edata->detail)
3284 {
3286 appendStringInfoString(&buf, _("DETAIL: "));
3287 append_with_tabs(&buf, edata->detail);
3288 appendStringInfoChar(&buf, '\n');
3289 }
3290 if (edata->hint)
3291 {
3293 appendStringInfoString(&buf, _("HINT: "));
3294 append_with_tabs(&buf, edata->hint);
3295 appendStringInfoChar(&buf, '\n');
3296 }
3297 if (edata->internalquery)
3298 {
3300 appendStringInfoString(&buf, _("QUERY: "));
3301 append_with_tabs(&buf, edata->internalquery);
3302 appendStringInfoChar(&buf, '\n');
3303 }
3304 if (edata->context && !edata->hide_ctx)
3305 {
3307 appendStringInfoString(&buf, _("CONTEXT: "));
3308 append_with_tabs(&buf, edata->context);
3309 appendStringInfoChar(&buf, '\n');
3310 }
3312 {
3313 /* assume no newlines in funcname or filename... */
3314 if (edata->funcname && edata->filename)
3315 {
3317 appendStringInfo(&buf, _("LOCATION: %s, %s:%d\n"),
3318 edata->funcname, edata->filename,
3319 edata->lineno);
3320 }
3321 else if (edata->filename)
3322 {
3324 appendStringInfo(&buf, _("LOCATION: %s:%d\n"),
3325 edata->filename, edata->lineno);
3326 }
3327 }
3328 if (edata->backtrace)
3329 {
3331 appendStringInfoString(&buf, _("BACKTRACE: "));
3332 append_with_tabs(&buf, edata->backtrace);
3333 appendStringInfoChar(&buf, '\n');
3334 }
3335 }
3336
3337 /*
3338 * If the user wants the query that generated this error logged, do it.
3339 */
3341 {
3343 appendStringInfoString(&buf, _("STATEMENT: "));
3345 appendStringInfoChar(&buf, '\n');
3346 }
3347
3348#ifdef HAVE_SYSLOG
3349 /* Write to syslog, if enabled */
3351 {
3352 int syslog_level;
3353
3354 switch (edata->elevel)
3355 {
3356 case DEBUG5:
3357 case DEBUG4:
3358 case DEBUG3:
3359 case DEBUG2:
3360 case DEBUG1:
3362 break;
3363 case LOG:
3364 case LOG_SERVER_ONLY:
3365 case INFO:
3367 break;
3368 case NOTICE:
3369 case WARNING:
3372 break;
3373 case ERROR:
3375 break;
3376 case FATAL:
3378 break;
3379 case PANIC:
3380 default:
3382 break;
3383 }
3384
3386 }
3387#endif /* HAVE_SYSLOG */
3388
3389#ifdef WIN32
3390 /* Write to eventlog, if enabled */
3392 {
3393 write_eventlog(edata->elevel, buf.data, buf.len);
3394 }
3395#endif /* WIN32 */
3396
3397 /* Write to csvlog, if enabled */
3399 {
3400 /*
3401 * Send CSV data if it's safe to do so (syslogger doesn't need the
3402 * pipe). If this is not possible, fallback to an entry written to
3403 * stderr.
3404 */
3407 else
3408 fallback_to_stderr = true;
3409 }
3410
3411 /* Write to JSON log, if enabled */
3413 {
3414 /*
3415 * Send JSON data if it's safe to do so (syslogger doesn't need the
3416 * pipe). If this is not possible, fallback to an entry written to
3417 * stderr.
3418 */
3420 {
3422 }
3423 else
3424 fallback_to_stderr = true;
3425 }
3426
3427 /*
3428 * Write to stderr, if enabled or if required because of a previous
3429 * limitation.
3430 */
3434 {
3435 /*
3436 * Use the chunking protocol if we know the syslogger should be
3437 * catching stderr output, and we are not ourselves the syslogger.
3438 * Otherwise, just do a vanilla write to stderr.
3439 */
3442#ifdef WIN32
3443
3444 /*
3445 * In a win32 service environment, there is no usable stderr. Capture
3446 * anything going there and write it to the eventlog instead.
3447 *
3448 * If stderr redirection is active, it was OK to write to stderr above
3449 * because that's really a pipe to the syslogger process.
3450 */
3451 else if (pgwin32_is_service())
3452 write_eventlog(edata->elevel, buf.data, buf.len);
3453#endif
3454 else
3455 write_console(buf.data, buf.len);
3456 }
3457
3458 /* If in the syslogger process, try to write messages direct to file */
3459 if (MyBackendType == B_LOGGER)
3461
3462 /* No more need of the message formatted for stderr */
3463 pfree(buf.data);
3464}
3465
3466/*
3467 * Send data to the syslogger using the chunked protocol
3468 *
3469 * Note: when there are multiple backends writing into the syslogger pipe,
3470 * it's critical that each write go into the pipe indivisibly, and not
3471 * get interleaved with data from other processes. Fortunately, the POSIX
3472 * spec requires that writes to pipes be atomic so long as they are not
3473 * more than PIPE_BUF bytes long. So we divide long messages into chunks
3474 * that are no more than that length, and send one chunk per write() call.
3475 * The collector process knows how to reassemble the chunks.
3476 *
3477 * Because of the atomic write requirement, there are only two possible
3478 * results from write() here: -1 for failure, or the requested number of
3479 * bytes. There is not really anything we can do about a failure; retry would
3480 * probably be an infinite loop, and we can't even report the error usefully.
3481 * (There is noplace else we could send it!) So we might as well just ignore
3482 * the result from write(). However, on some platforms you get a compiler
3483 * warning from ignoring write()'s result, so do a little dance with casting
3484 * rc to void to shut up the compiler.
3485 */
3486void
3487write_pipe_chunks(char *data, int len, int dest)
3488{
3490 int fd = fileno(stderr);
3491 int rc;
3492
3493 Assert(len > 0);
3494
3495 p.proto.nuls[0] = p.proto.nuls[1] = '\0';
3496 p.proto.pid = MyProcPid;
3497 p.proto.flags = 0;
3498 if (dest == LOG_DESTINATION_STDERR)
3500 else if (dest == LOG_DESTINATION_CSVLOG)
3502 else if (dest == LOG_DESTINATION_JSONLOG)
3504
3505 /* write all but the last chunk */
3506 while (len > PIPE_MAX_PAYLOAD)
3507 {
3508 /* no need to set PIPE_PROTO_IS_LAST yet */
3512 (void) rc;
3515 }
3516
3517 /* write the last chunk */
3519 p.proto.len = len;
3520 memcpy(p.proto.data, data, len);
3521 rc = write(fd, &p, PIPE_HEADER_SIZE + len);
3522 (void) rc;
3523}
3524
3525
3526/*
3527 * Append a text string to the error report being built for the client.
3528 *
3529 * This is ordinarily identical to pq_sendstring(), but if we are in
3530 * error recursion trouble we skip encoding conversion, because of the
3531 * possibility that the problem is a failure in the encoding conversion
3532 * subsystem itself. Code elsewhere should ensure that the passed-in
3533 * strings will be plain 7-bit ASCII, and thus not in need of conversion,
3534 * in such cases. (In particular, we disable localization of error messages
3535 * to help ensure that's true.)
3536 */
3537static void
3539{
3542 else
3544}
3545
3546/*
3547 * Write error report to client
3548 */
3549static void
3551{
3553
3554 /*
3555 * We no longer support pre-3.0 FE/BE protocol, except here. If a client
3556 * tries to connect using an older protocol version, it's nice to send the
3557 * "protocol version not supported" error in a format the client
3558 * understands. If protocol hasn't been set yet, early in backend
3559 * startup, assume modern protocol.
3560 */
3562 {
3563 /* New style with separate fields */
3564 const char *sev;
3565 char tbuf[12];
3566
3567 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
3568 if (edata->elevel < ERROR)
3570 else
3572
3573 sev = error_severity(edata->elevel);
3578
3581
3582 /* M field is required per protocol, so always send something */
3584 if (edata->message)
3585 err_sendstring(&msgbuf, edata->message);
3586 else
3587 err_sendstring(&msgbuf, _("missing error text"));
3588
3589 if (edata->detail)
3590 {
3592 err_sendstring(&msgbuf, edata->detail);
3593 }
3594
3595 /* detail_log is intentionally not used here */
3596
3597 if (edata->hint)
3598 {
3600 err_sendstring(&msgbuf, edata->hint);
3601 }
3602
3603 if (edata->context)
3604 {
3606 err_sendstring(&msgbuf, edata->context);
3607 }
3608
3609 if (edata->schema_name)
3610 {
3612 err_sendstring(&msgbuf, edata->schema_name);
3613 }
3614
3615 if (edata->table_name)
3616 {
3618 err_sendstring(&msgbuf, edata->table_name);
3619 }
3620
3621 if (edata->column_name)
3622 {
3624 err_sendstring(&msgbuf, edata->column_name);
3625 }
3626
3627 if (edata->datatype_name)
3628 {
3630 err_sendstring(&msgbuf, edata->datatype_name);
3631 }
3632
3633 if (edata->constraint_name)
3634 {
3636 err_sendstring(&msgbuf, edata->constraint_name);
3637 }
3638
3639 if (edata->cursorpos > 0)
3640 {
3641 snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
3644 }
3645
3646 if (edata->internalpos > 0)
3647 {
3648 snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
3651 }
3652
3653 if (edata->internalquery)
3654 {
3656 err_sendstring(&msgbuf, edata->internalquery);
3657 }
3658
3659 if (edata->filename)
3660 {
3662 err_sendstring(&msgbuf, edata->filename);
3663 }
3664
3665 if (edata->lineno > 0)
3666 {
3667 snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
3670 }
3671
3672 if (edata->funcname)
3673 {
3675 err_sendstring(&msgbuf, edata->funcname);
3676 }
3677
3678 pq_sendbyte(&msgbuf, '\0'); /* terminator */
3679
3681 }
3682 else
3683 {
3684 /* Old style --- gin up a backwards-compatible message */
3686
3688
3689 appendStringInfo(&buf, "%s: ", _(error_severity(edata->elevel)));
3690
3691 if (edata->message)
3692 appendStringInfoString(&buf, edata->message);
3693 else
3694 appendStringInfoString(&buf, _("missing error text"));
3695
3696 appendStringInfoChar(&buf, '\n');
3697
3698 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
3699 pq_putmessage_v2((edata->elevel < ERROR) ? 'N' : 'E', buf.data, buf.len + 1);
3700
3701 pfree(buf.data);
3702 }
3703
3704 /*
3705 * This flush is normally not necessary, since postgres.c will flush out
3706 * waiting data when control returns to the main loop. But it seems best
3707 * to leave it here, so that the client has some clue what happened if the
3708 * backend dies before getting back to the main loop ... error/notice
3709 * messages should not be a performance-critical path anyway, so an extra
3710 * flush won't hurt much ...
3711 */
3712 pq_flush();
3713}
3714
3715
3716/*
3717 * Support routines for formatting error messages.
3718 */
3719
3720
3721/*
3722 * error_severity --- get string representing elevel
3723 *
3724 * The string is not localized here, but we mark the strings for translation
3725 * so that callers can invoke _() on the result.
3726 */
3727const char *
3729{
3730 const char *prefix;
3731
3732 switch (elevel)
3733 {
3734 case DEBUG1:
3735 case DEBUG2:
3736 case DEBUG3:
3737 case DEBUG4:
3738 case DEBUG5:
3739 prefix = gettext_noop("DEBUG");
3740 break;
3741 case LOG:
3742 case LOG_SERVER_ONLY:
3743 prefix = gettext_noop("LOG");
3744 break;
3745 case INFO:
3746 prefix = gettext_noop("INFO");
3747 break;
3748 case NOTICE:
3749 prefix = gettext_noop("NOTICE");
3750 break;
3751 case WARNING:
3753 prefix = gettext_noop("WARNING");
3754 break;
3755 case ERROR:
3756 prefix = gettext_noop("ERROR");
3757 break;
3758 case FATAL:
3759 prefix = gettext_noop("FATAL");
3760 break;
3761 case PANIC:
3762 prefix = gettext_noop("PANIC");
3763 break;
3764 default:
3765 prefix = "???";
3766 break;
3767 }
3768
3769 return prefix;
3770}
3771
3772
3773/*
3774 * append_with_tabs
3775 *
3776 * Append the string to the StringInfo buffer, inserting a tab after any
3777 * newline.
3778 */
3779static void
3781{
3782 char ch;
3783
3784 while ((ch = *str++) != '\0')
3785 {
3787 if (ch == '\n')
3789 }
3790}
3791
3792
3793/*
3794 * Write errors to stderr (or by equal means when stderr is
3795 * not available). Used before ereport/elog can be used
3796 * safely (memory context, GUC load etc)
3797 */
3798void
3799write_stderr(const char *fmt,...)
3800{
3801 va_list ap;
3802
3803 va_start(ap, fmt);
3805 va_end(ap);
3806}
3807
3808
3809/*
3810 * Write errors to stderr (or by equal means when stderr is
3811 * not available) - va_list version
3812 */
3813void
3815{
3816#ifdef WIN32
3817 char errbuf[2048]; /* Arbitrary size? */
3818#endif
3819
3820 fmt = _(fmt);
3821#ifndef WIN32
3822 /* On Unix, we just fprintf to stderr */
3823 vfprintf(stderr, fmt, ap);
3824 fflush(stderr);
3825#else
3826 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
3827
3828 /*
3829 * On Win32, we print to stderr if running on a console, or write to
3830 * eventlog if running as a service
3831 */
3832 if (pgwin32_is_service()) /* Running as a service */
3833 {
3834 write_eventlog(ERROR, errbuf, strlen(errbuf));
3835 }
3836 else
3837 {
3838 /* Not running as service, write to stderr */
3839 write_console(errbuf, strlen(errbuf));
3840 fflush(stderr);
3841 }
3842#endif
3843}
void ExceptionalCondition(const char *conditionName, const char *fileName, int lineNumber)
Definition assert.c:30
int64 pgstat_get_my_query_id(void)
#define write_stderr(str)
Definition parallel.c:186
#define pg_attribute_format_arg(a)
Definition c.h:241
#define pg_noinline
Definition c.h:295
#define Min(x, y)
Definition c.h:997
#define pg_attribute_cold
Definition c.h:320
#define gettext_noop(x)
Definition c.h:1191
#define Max(x, y)
Definition c.h:991
#define Assert(condition)
Definition c.h:873
#define PG_TEXTDOMAIN(domain)
Definition c.h:1209
#define gettext(x)
Definition c.h:1174
#define pg_unreachable()
Definition c.h:341
#define unlikely(x)
Definition c.h:412
#define lengthof(array)
Definition c.h:803
#define MemSet(start, val, len)
Definition c.h:1013
void write_csvlog(ErrorData *edata)
Definition csvlog.c:63
@ DestRemote
Definition dest.h:89
@ DestDebug
Definition dest.h:88
@ DestNone
Definition dest.h:87
void assign_syslog_facility(int newval, void *extra)
Definition elog.c:2359
int getinternalerrposition(void)
Definition elog.c:1629
static bool should_output_to_client(int elevel)
Definition elog.c:245
void assign_syslog_ident(const char *newval, void *extra)
Definition elog.c:2327
int errcode_for_socket_access(void)
Definition elog.c:963
bool errsave_start(struct Node *context, const char *domain)
Definition elog.c:639
static void log_line_prefix(StringInfo buf, ErrorData *edata)
Definition elog.c:2833
static const char * process_log_prefix_padding(const char *p, int *ppadding)
Definition elog.c:2802
int err_generic_string(int field, const char *str)
Definition elog.c:1546
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition elog.c:1193
void errsave_finish(struct Node *context, const char *filename, int lineno, const char *funcname)
Definition elog.c:691
static char formatted_log_time[FORMATTED_TS_LEN]
Definition elog.c:161
int internalerrquery(const char *query)
Definition elog.c:1516
static char formatted_start_time[FORMATTED_TS_LEN]
Definition elog.c:160
int internalerrposition(int cursorpos)
Definition elog.c:1496
static void send_message_to_frontend(ErrorData *edata)
Definition elog.c:3550
bool check_log_of_query(ErrorData *edata)
Definition elog.c:2752
int errmsg_internal(const char *fmt,...)
Definition elog.c:1170
static void append_with_tabs(StringInfo buf, const char *str)
Definition elog.c:3780
int geterrcode(void)
Definition elog.c:1595
char * format_elog_string(const char *fmt,...)
Definition elog.c:1671
int errhidestmt(bool hide_stmt)
Definition elog.c:1445
bool errstart(int elevel, const char *domain)
Definition elog.c:343
void EmitErrorReport(void)
Definition elog.c:1704
bool syslog_split_messages
Definition elog.c:114
static void FreeErrorDataContents(ErrorData *edata)
Definition elog.c:1847
static int errordata_stack_depth
Definition elog.c:148
char * GetErrorContextStack(void)
Definition elog.c:2076
void DebugFileOpen(void)
Definition elog.c:2128
static void err_sendstring(StringInfo buf, const char *str)
Definition elog.c:3538
void FreeErrorData(ErrorData *edata)
Definition elog.c:1835
void assign_backtrace_functions(const char *newval, void *extra)
Definition elog.c:2245
const char * error_severity(int elevel)
Definition elog.c:3728
static ErrorData * get_error_stack_entry(void)
Definition elog.c:761
#define FORMATTED_TS_LEN
Definition elog.c:159
int errdetail_internal(const char *fmt,...)
Definition elog.c:1243
static bool saved_timeval_set
Definition elog.c:157
int errcode_for_file_access(void)
Definition elog.c:886
static char * backtrace_function_list
Definition elog.c:117
int errdetail(const char *fmt,...)
Definition elog.c:1216
int Log_error_verbosity
Definition elog.c:109
void pg_re_throw(void)
Definition elog.c:2021
int errcontext_msg(const char *fmt,...)
Definition elog.c:1399
static int save_format_errnumber
Definition elog.c:1658
bool check_backtrace_functions(char **newval, void **extra, GucSource source)
Definition elog.c:2184
void pre_format_elog_string(int errnumber, const char *domain)
Definition elog.c:1662
static int recursion_depth
Definition elog.c:150
ErrorContextCallback * error_context_stack
Definition elog.c:95
int errhint_internal(const char *fmt,...)
Definition elog.c:1352
int errbacktrace(void)
Definition elog.c:1102
static struct timeval saved_timeval
Definition elog.c:156
int Log_destination
Definition elog.c:111
void ReThrowError(ErrorData *edata)
Definition elog.c:1971
static void set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str)
Definition elog.c:1582
char * get_formatted_start_time(void)
Definition elog.c:2728
static bool matches_backtrace_functions(const char *funcname)
Definition elog.c:835
ErrorData * CopyErrorData(void)
Definition elog.c:1763
bool check_log_destination(char **newval, void **extra, GucSource source)
Definition elog.c:2254
void FlushErrorState(void)
Definition elog.c:1884
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition elog.c:1308
int errhint(const char *fmt,...)
Definition elog.c:1330
static bool is_log_level_output(int elevel, int log_min_level)
Definition elog.c:202
void ThrowErrorData(ErrorData *edata)
Definition elog.c:1912
bool message_level_is_interesting(int elevel)
Definition elog.c:273
void write_pipe_chunks(char *data, int len, int dest)
Definition elog.c:3487
int errhidecontext(bool hide_ctx)
Definition elog.c:1464
emit_log_hook_type emit_log_hook
Definition elog.c:106
bool syslog_sequence_numbers
Definition elog.c:113
int geterrposition(void)
Definition elog.c:1612
static void send_message_to_server_log(ErrorData *edata)
Definition elog.c:3247
char * Log_destination_string
Definition elog.c:112
static void write_console(const char *line, int len)
Definition elog.c:2600
#define EVALUATE_MESSAGE(domain, targetfield, appendval, translateit)
Definition elog.c:999
static void set_stack_entry_location(ErrorData *edata, const char *filename, int lineno, const char *funcname)
Definition elog.c:805
pg_attribute_cold bool errstart_cold(int elevel, const char *domain)
Definition elog.c:327
#define CHECK_STACK_DEPTH()
Definition elog.c:165
static void set_stack_entry_domain(ErrorData *edata, const char *domain)
Definition elog.c:788
#define EVALUATE_MESSAGE_PLURAL(domain, targetfield, appendval)
Definition elog.c:1035
static bool should_output_to_server(int elevel)
Definition elog.c:236
const char * get_backend_type_for_log(void)
Definition elog.c:2775
int errcode(int sqlerrcode)
Definition elog.c:863
int errdetail_log_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition elog.c:1285
int errmsg(const char *fmt,...)
Definition elog.c:1080
void vwrite_stderr(const char *fmt, va_list ap)
Definition elog.c:3814
void log_status_format(StringInfo buf, const char *format, ErrorData *edata)
Definition elog.c:2842
char * get_formatted_log_time(void)
Definition elog.c:2678
bool in_error_recursion_trouble(void)
Definition elog.c:294
void errfinish(const char *filename, int lineno, const char *funcname)
Definition elog.c:474
static const char * err_gettext(const char *str) pg_attribute_format_arg(1)
Definition elog.c:306
int errposition(int cursorpos)
Definition elog.c:1480
#define ERRORDATA_STACK_SIZE
Definition elog.c:144
int errhint_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition elog.c:1373
int errdetail_log(const char *fmt,...)
Definition elog.c:1264
char * unpack_sql_state(int sql_state)
Definition elog.c:3227
static pg_noinline void set_backtrace(ErrorData *edata, int num_skip)
Definition elog.c:1126
char * Log_line_prefix
Definition elog.c:110
#define _(x)
Definition elog.c:91
int set_errcontext_domain(const char *domain)
Definition elog.c:1425
void reset_formatted_start_time(void)
Definition elog.c:2716
static ErrorData errordata[ERRORDATA_STACK_SIZE]
Definition elog.c:146
sigjmp_buf * PG_exception_stack
Definition elog.c:97
static const char * save_format_domain
Definition elog.c:1659
void assign_log_destination(const char *newval, void *extra)
Definition elog.c:2318
@ PGERROR_VERBOSE
Definition elog.h:474
@ PGERROR_DEFAULT
Definition elog.h:473
#define LOG
Definition elog.h:31
void(* emit_log_hook_type)(ErrorData *edata)
Definition elog.h:464
#define PG_RE_THROW()
Definition elog.h:405
#define DEBUG3
Definition elog.h:28
#define LOG_SERVER_ONLY
Definition elog.h:32
#define WARNING_CLIENT_ONLY
Definition elog.h:38
#define FATAL
Definition elog.h:41
#define WARNING
Definition elog.h:36
#define LOG_DESTINATION_JSONLOG
Definition elog.h:489
#define DEBUG2
Definition elog.h:29
#define PGUNSIXBIT(val)
Definition elog.h:54
#define PANIC
Definition elog.h:42
#define DEBUG1
Definition elog.h:30
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define NOTICE
Definition elog.h:35
#define LOG_DESTINATION_SYSLOG
Definition elog.h:486
#define LOG_DESTINATION_STDERR
Definition elog.h:485
#define INFO
Definition elog.h:34
#define ereport(elevel,...)
Definition elog.h:150
#define LOG_DESTINATION_EVENTLOG
Definition elog.h:487
#define DEBUG5
Definition elog.h:26
#define LOG_DESTINATION_CSVLOG
Definition elog.h:488
#define DEBUG4
Definition elog.h:27
#define palloc_object(type)
Definition fe_memutils.h:74
volatile uint32 QueryCancelHoldoffCount
Definition globals.c:44
ProtocolVersion FrontendProtocol
Definition globals.c:30
pid_t PostmasterPid
Definition globals.c:106
volatile uint32 InterruptHoldoffCount
Definition globals.c:43
int MyProcPid
Definition globals.c:47
bool IsUnderPostmaster
Definition globals.c:120
volatile uint32 CritSectionCount
Definition globals.c:45
bool ExitOnAnyError
Definition globals.c:123
struct Port * MyProcPort
Definition globals.c:51
pg_time_t MyStartTime
Definition globals.c:48
char OutputFileName[MAXPGPATH]
Definition globals.c:79
void * guc_malloc(int elevel, size_t size)
Definition guc.c:636
#define newval
#define GUC_check_errdetail
Definition guc.h:505
GucSource
Definition guc.h:112
char * event_source
Definition guc_tables.c:535
int client_min_messages
Definition guc_tables.c:550
int log_min_error_statement
Definition guc_tables.c:548
static int syslog_facility
Definition guc_tables.c:613
char * application_name
Definition guc_tables.c:570
int log_min_messages
Definition guc_tables.c:549
char * backtrace_functions
Definition guc_tables.c:558
const char * str
#define funcname
static char * username
Definition initdb.c:153
static char * encoding
Definition initdb.c:139
#define close(a)
Definition win32.h:12
#define write(a, b, c)
Definition win32.h:14
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
Definition ip.c:117
bool proc_exit_inprogress
Definition ipc.c:41
void proc_exit(int code)
Definition ipc.c:105
int j
Definition isn.c:78
int i
Definition isn.c:77
void write_jsonlog(ErrorData *edata)
Definition jsonlog.c:109
#define pq_flush()
Definition libpq.h:46
void list_free(List *list)
Definition list.c:1546
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition mbutils.c:1086
int GetMessageEncoding(void)
Definition mbutils.c:1311
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition mcxt.c:1768
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:403
char * pstrdup(const char *in)
Definition mcxt.c:1781
void pfree(void *pointer)
Definition mcxt.c:1616
MemoryContext CurrentMemoryContext
Definition mcxt.c:160
MemoryContext ErrorContext
Definition mcxt.c:167
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:123
@ B_LOGGER
Definition miscadmin.h:374
@ B_BG_WORKER
Definition miscadmin.h:346
const char * GetBackendTypeDesc(BackendType backendType)
Definition miscinit.c:263
BackendType MyBackendType
Definition miscinit.c:64
#define IsA(nodeptr, _type_)
Definition nodes.h:164
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
static char format
#define DEFAULT_EVENT_SOURCE
const void size_t len
const void * data
static time_t start_time
Definition pg_ctl.c:96
static char * filename
Definition pg_dumpall.c:120
#define lfirst(lc)
Definition pg_list.h:172
static rewind_source * source
Definition pg_rewind.c:89
static char buf[DEFAULT_XLOG_SEG_SIZE]
@ DISCONNECT_FATAL
Definition pgstat.h:59
@ DISCONNECT_NORMAL
Definition pgstat.h:57
SessionEndType pgStatSessionEndCause
int64 pg_time_t
Definition pgtime.h:23
size_t pg_strftime(char *s, size_t maxsize, const char *format, const struct pg_tm *t)
Definition strftime.c:128
struct pg_tm * pg_localtime(const pg_time_t *timep, const pg_tz *tz)
Definition localtime.c:1345
PGDLLIMPORT pg_tz * log_timezone
Definition pgtz.c:31
#define vsnprintf
Definition port.h:259
#define ALL_CONNECTION_FAILURE_ERRNOS
Definition port.h:122
int pg_strcasecmp(const char *s1, const char *s2)
#define sprintf
Definition port.h:262
#define vfprintf
Definition port.h:263
#define snprintf
Definition port.h:260
CommandDest whereToSendOutput
Definition postgres.c:92
const char * debug_query_string
Definition postgres.c:89
#define PG_DIAG_INTERNAL_QUERY
#define PG_DIAG_SCHEMA_NAME
#define PG_DIAG_CONSTRAINT_NAME
#define PG_DIAG_DATATYPE_NAME
#define PG_DIAG_SOURCE_LINE
#define PG_DIAG_STATEMENT_POSITION
#define PG_DIAG_SOURCE_FILE
#define PG_DIAG_MESSAGE_HINT
#define PG_DIAG_SQLSTATE
#define PG_DIAG_SEVERITY_NONLOCALIZED
#define PG_DIAG_TABLE_NAME
#define PG_DIAG_MESSAGE_PRIMARY
#define PG_DIAG_COLUMN_NAME
#define PG_DIAG_MESSAGE_DETAIL
#define PG_DIAG_CONTEXT
#define PG_DIAG_SEVERITY
#define PG_DIAG_SOURCE_FUNCTION
#define PG_DIAG_INTERNAL_POSITION
bool redirection_done
Definition postmaster.c:375
bool ClientAuthInProgress
Definition postmaster.c:372
BackgroundWorker * MyBgworkerEntry
Definition postmaster.c:200
int pq_putmessage_v2(char msgtype, const char *s, size_t len)
Definition pqcomm.c:1561
#define PG_PROTOCOL_MAJOR(v)
Definition pqcomm.h:86
void pq_sendstring(StringInfo buf, const char *str)
Definition pqformat.c:195
void pq_endmessage(StringInfo buf)
Definition pqformat.c:296
void pq_beginmessage(StringInfo buf, char msgtype)
Definition pqformat.c:88
void pq_send_ascii_string(StringInfo buf, const char *str)
Definition pqformat.c:227
static void pq_sendbyte(StringInfo buf, uint8 byt)
Definition pqformat.h:160
static int fd(const char *x, int i)
static int fb(int x)
#define INVALID_PROC_NUMBER
Definition procnumber.h:26
#define PqMsg_ErrorResponse
Definition protocol.h:44
#define PqMsg_NoticeResponse
Definition protocol.h:49
const char * get_ps_display(int *displen)
Definition ps_status.c:548
char * psprintf(const char *fmt,...)
Definition psprintf.c:43
#define free(a)
PGPROC * MyProc
Definition proc.c:67
char * dbname
Definition streamutil.c:49
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
Definition stringinfo.c:281
void appendStringInfoSpaces(StringInfo str, int count)
Definition stringinfo.c:260
void appendStringInfoString(StringInfo str, const char *s)
Definition stringinfo.c:230
void appendStringInfoChar(StringInfo str, char ch)
Definition stringinfo.c:242
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
#define appendStringInfoCharMacro(str, ch)
Definition stringinfo.h:231
char bgw_type[BGW_MAXLEN]
Definition bgworker.h:99
struct ErrorContextCallback * previous
Definition elog.h:297
void(* callback)(void *arg)
Definition elog.h:298
ErrorData * error_data
Definition miscnodes.h:49
Definition pg_list.h:54
Definition nodes.h:135
Definition proc.h:180
LocalTransactionId lxid
Definition proc.h:218
ProcNumber procNumber
Definition proc.h:213
int pid
Definition proc.h:200
struct PGPROC::@131 vxid
PGPROC * lockGroupLeader
Definition proc.h:321
char data[FLEXIBLE_ARRAY_MEMBER]
Definition syslogger.h:50
char * user_name
Definition libpq-be.h:151
char * remote_port
Definition libpq-be.h:140
SockAddr laddr
Definition libpq-be.h:133
char * database_name
Definition libpq-be.h:150
char * remote_host
Definition libpq-be.h:135
char local_host[64]
Definition libpq-be.h:143
struct sockaddr_storage addr
Definition pqcomm.h:32
socklen_t salen
Definition pqcomm.h:33
void write_syslogger_file(const char *buffer, int count, int destination)
Definition syslogger.c:1092
#define PIPE_PROTO_DEST_JSONLOG
Definition syslogger.h:67
#define PIPE_PROTO_IS_LAST
Definition syslogger.h:63
#define PIPE_PROTO_DEST_CSVLOG
Definition syslogger.h:66
#define PIPE_PROTO_DEST_STDERR
Definition syslogger.h:65
#define PIPE_MAX_PAYLOAD
Definition syslogger.h:60
#define PIPE_HEADER_SIZE
Definition syslogger.h:59
PipeProtoHeader proto
Definition syslogger.h:55
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition varlena.c:2730
int pgwin32_is_service(void)
int gettimeofday(struct timeval *tp, void *tzp)
TransactionId GetTopTransactionIdIfAny(void)
Definition xact.c:442