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#ifdef _MSC_VER
70#include <dbghelp.h>
71#endif
72
73#include "access/xact.h"
74#include "common/ip.h"
75#include "libpq/libpq.h"
76#include "libpq/pqformat.h"
77#include "mb/pg_wchar.h"
78#include "miscadmin.h"
79#include "nodes/miscnodes.h"
80#include "pgstat.h"
81#include "postmaster/bgworker.h"
84#include "storage/ipc.h"
85#include "storage/proc.h"
86#include "tcop/tcopprot.h"
87#include "utils/guc_hooks.h"
88#include "utils/memutils.h"
89#include "utils/ps_status.h"
90#include "utils/varlena.h"
91
92
93/* In this module, access gettext() via err_gettext() */
94#undef _
95#define _(x) err_gettext(x)
96
97
98/* Global variables */
100
102
103/*
104 * Hook for intercepting messages before they are sent to the server log.
105 * Note that the hook will not get called for messages that are suppressed
106 * by log_min_messages. Also note that logging hooks implemented in preload
107 * libraries will miss any log messages that are generated before the
108 * library is loaded.
109 */
111
112/* GUC parameters */
114char *Log_line_prefix = NULL; /* format for extra log line info */
119
120/* Processed form of backtrace_functions GUC */
122
123#ifdef HAVE_SYSLOG
124
125/*
126 * Max string length to send to syslog(). Note that this doesn't count the
127 * sequence-number prefix we add, and of course it doesn't count the prefix
128 * added by syslog itself. Solaris and sysklogd truncate the final message
129 * at 1024 bytes, so this value leaves 124 bytes for those prefixes. (Most
130 * other syslog implementations seem to have limits of 2KB or so.)
131 */
132#ifndef PG_SYSLOG_LIMIT
133#define PG_SYSLOG_LIMIT 900
134#endif
135
136static bool openlog_done = false;
137static char *syslog_ident = NULL;
138static int syslog_facility = LOG_LOCAL0;
139
140static void write_syslog(int level, const char *line);
141#endif
142
143#ifdef WIN32
144static void write_eventlog(int level, const char *line, int len);
145#endif
146
147#ifdef _MSC_VER
148static bool backtrace_symbols_initialized = false;
150#endif
151
152/* We provide a small stack of ErrorData records for re-entrant cases */
153#define ERRORDATA_STACK_SIZE 5
154
156
157static int errordata_stack_depth = -1; /* index of topmost active frame */
158
159static int recursion_depth = 0; /* to detect actual recursion */
160
161/*
162 * Saved timeval and buffers for formatted timestamps that might be used by
163 * log_line_prefix, csv logs and JSON logs.
164 */
165static struct timeval saved_timeval;
166static bool saved_timeval_set = false;
167
168#define FORMATTED_TS_LEN 128
171
172
173/* Macro for checking errordata_stack_depth is reasonable */
174#define CHECK_STACK_DEPTH() \
175 do { \
176 if (errordata_stack_depth < 0) \
177 { \
178 errordata_stack_depth = -1; \
179 ereport(ERROR, (errmsg_internal("errstart was not called"))); \
180 } \
181 } while (0)
182
183
184static const char *err_gettext(const char *str) pg_attribute_format_arg(1);
185static ErrorData *get_error_stack_entry(void);
186static void set_stack_entry_domain(ErrorData *edata, const char *domain);
188 const char *filename, int lineno,
189 const char *funcname);
190static bool matches_backtrace_functions(const char *funcname);
192static void backtrace_cleanup(int code, Datum arg);
193static void set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str);
195static int log_min_messages_cmp(const ListCell *a, const ListCell *b);
196static void write_console(const char *line, int len);
197static const char *process_log_prefix_padding(const char *p, int *ppadding);
201static void append_with_tabs(StringInfo buf, const char *str);
202
203
204/*
205 * is_log_level_output -- is elevel logically >= log_min_level?
206 *
207 * We use this for tests that should consider LOG to sort out-of-order,
208 * between ERROR and FATAL. Generally this is the right thing for testing
209 * whether a message should go to the postmaster log, whereas a simple >=
210 * test is correct for testing whether the message should go to the client.
211 */
212static inline bool
214{
215 if (elevel == LOG || elevel == LOG_SERVER_ONLY)
216 {
218 return true;
219 }
220 else if (elevel == WARNING_CLIENT_ONLY)
221 {
222 /* never sent to log, regardless of log_min_level */
223 return false;
224 }
225 else if (log_min_level == LOG)
226 {
227 /* elevel != LOG */
228 if (elevel >= FATAL)
229 return true;
230 }
231 /* Neither is LOG */
232 else if (elevel >= log_min_level)
233 return true;
234
235 return false;
236}
237
238/*
239 * Policy-setting subroutines. These are fairly simple, but it seems wise
240 * to have the code in just one place.
241 */
242
243/*
244 * should_output_to_server --- should message of given elevel go to the log?
245 */
246static inline bool
251
252/*
253 * should_output_to_client --- should message of given elevel go to the client?
254 */
255static inline bool
257{
258 if (whereToSendOutput == DestRemote && elevel != LOG_SERVER_ONLY)
259 {
260 /*
261 * client_min_messages is honored only after we complete the
262 * authentication handshake. This is required both for security
263 * reasons and because many clients can't handle NOTICE messages
264 * during authentication.
265 */
267 return (elevel >= ERROR);
268 else
269 return (elevel >= client_min_messages || elevel == INFO);
270 }
271 return false;
272}
273
274
275/*
276 * message_level_is_interesting --- would ereport/elog do anything?
277 *
278 * Returns true if ereport/elog with this elevel will not be a no-op.
279 * This is useful to short-circuit any expensive preparatory work that
280 * might be needed for a logging message. There is no point in
281 * prepending this to a bare ereport/elog call, however.
282 */
283bool
285{
286 /*
287 * Keep this in sync with the decision-making in errstart().
288 */
289 if (elevel >= ERROR ||
290 should_output_to_server(elevel) ||
292 return true;
293 return false;
294}
295
296
297/*
298 * in_error_recursion_trouble --- are we at risk of infinite error recursion?
299 *
300 * This function exists to provide common control of various fallback steps
301 * that we take if we think we are facing infinite error recursion. See the
302 * callers for details.
303 */
304bool
306{
307 /* Pull the plug if recurse more than once */
308 return (recursion_depth > 2);
309}
310
311/*
312 * One of those fallback steps is to stop trying to localize the error
313 * message, since there's a significant probability that that's exactly
314 * what's causing the recursion.
315 */
316static inline const char *
317err_gettext(const char *str)
318{
319#ifdef ENABLE_NLS
321 return str;
322 else
323 return gettext(str);
324#else
325 return str;
326#endif
327}
328
329/*
330 * errstart_cold
331 * A simple wrapper around errstart, but hinted to be "cold". Supporting
332 * compilers are more likely to move code for branches containing this
333 * function into an area away from the calling function's code. This can
334 * result in more commonly executed code being more compact and fitting
335 * on fewer cache lines.
336 */
338errstart_cold(int elevel, const char *domain)
339{
340 return errstart(elevel, domain);
341}
342
343/*
344 * errstart --- begin an error-reporting cycle
345 *
346 * Create and initialize error stack entry. Subsequently, errmsg() and
347 * perhaps other routines will be called to further populate the stack entry.
348 * Finally, errfinish() will be called to actually process the error report.
349 *
350 * Returns true in normal case. Returns false to short-circuit the error
351 * report (if it's a warning or lower and not to be reported anywhere).
352 */
353bool
354errstart(int elevel, const char *domain)
355{
357 bool output_to_server;
358 bool output_to_client = false;
359 int i;
360
361 /*
362 * Check some cases in which we want to promote an error into a more
363 * severe error. None of this logic applies for non-error messages.
364 */
365 if (elevel >= ERROR)
366 {
367 /*
368 * If we are inside a critical section, all errors become PANIC
369 * errors. See miscadmin.h.
370 */
371 if (CritSectionCount > 0)
372 elevel = PANIC;
373
374 /*
375 * Check reasons for treating ERROR as FATAL:
376 *
377 * 1. we have no handler to pass the error to (implies we are in the
378 * postmaster or in backend startup).
379 *
380 * 2. ExitOnAnyError mode switch is set (initdb uses this).
381 *
382 * 3. the error occurred after proc_exit has begun to run. (It's
383 * proc_exit's responsibility to see that this doesn't turn into
384 * infinite recursion!)
385 */
386 if (elevel == ERROR)
387 {
388 if (PG_exception_stack == NULL ||
391 elevel = FATAL;
392 }
393
394 /*
395 * If the error level is ERROR or more, errfinish is not going to
396 * return to caller; therefore, if there is any stacked error already
397 * in progress it will be lost. This is more or less okay, except we
398 * do not want to have a FATAL or PANIC error downgraded because the
399 * reporting process was interrupted by a lower-grade error. So check
400 * the stack and make sure we panic if panic is warranted.
401 */
402 for (i = 0; i <= errordata_stack_depth; i++)
403 elevel = Max(elevel, errordata[i].elevel);
404 }
405
406 /*
407 * Now decide whether we need to process this report at all; if it's
408 * warning or less and not enabled for logging, just return false without
409 * starting up any error logging machinery.
410 */
411 output_to_server = should_output_to_server(elevel);
412 output_to_client = should_output_to_client(elevel);
413 if (elevel < ERROR && !output_to_server && !output_to_client)
414 return false;
415
416 /*
417 * We need to do some actual work. Make sure that memory context
418 * initialization has finished, else we can't do anything useful.
419 */
420 if (ErrorContext == NULL)
421 {
422 /* Oops, hard crash time; very little we can do safely here */
423 write_stderr("error occurred before error message processing is available\n");
424 exit(2);
425 }
426
427 /*
428 * Okay, crank up a stack entry to store the info in.
429 */
430
431 if (recursion_depth++ > 0 && elevel >= ERROR)
432 {
433 /*
434 * Oops, error during error processing. Clear ErrorContext as
435 * discussed at top of file. We will not return to the original
436 * error's reporter or handler, so we don't need it.
437 */
439
440 /*
441 * Infinite error recursion might be due to something broken in a
442 * context traceback routine. Abandon them too. We also abandon
443 * attempting to print the error statement (which, if long, could
444 * itself be the source of the recursive failure).
445 */
447 {
450 }
451 }
452
453 /* Initialize data for this error frame */
455 edata->elevel = elevel;
456 edata->output_to_server = output_to_server;
457 edata->output_to_client = output_to_client;
459 /* Select default errcode based on elevel */
460 if (elevel >= ERROR)
461 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
462 else if (elevel >= WARNING)
463 edata->sqlerrcode = ERRCODE_WARNING;
464 else
466
467 /*
468 * Any allocations for this error state level should go into ErrorContext
469 */
470 edata->assoc_context = ErrorContext;
471
473 return true;
474}
475
476/*
477 * errfinish --- end an error-reporting cycle
478 *
479 * Produce the appropriate error report(s) and pop the error stack.
480 *
481 * If elevel, as passed to errstart(), is ERROR or worse, control does not
482 * return to the caller. See elog.h for the error level definitions.
483 */
484void
485errfinish(const char *filename, int lineno, const char *funcname)
486{
488 int elevel;
489 MemoryContext oldcontext;
490 ErrorContextCallback *econtext;
491
494
495 /* Save the last few bits of error state into the stack entry */
497
498 elevel = edata->elevel;
499
500 /*
501 * Do processing in ErrorContext, which we hope has enough reserved space
502 * to report an error.
503 */
505
506 /* Collect backtrace, if enabled and we didn't already */
507 if (!edata->backtrace &&
508 edata->funcname &&
512
513 /*
514 * Call any context callback functions. Errors occurring in callback
515 * functions will be treated as recursive errors --- this ensures we will
516 * avoid infinite recursion (see errstart).
517 */
518 for (econtext = error_context_stack;
519 econtext != NULL;
520 econtext = econtext->previous)
521 econtext->callback(econtext->arg);
522
523 /*
524 * If ERROR (not more nor less) we pass it off to the current handler.
525 * Printing it and popping the stack is the responsibility of the handler.
526 */
527 if (elevel == ERROR)
528 {
529 /*
530 * We do some minimal cleanup before longjmp'ing so that handlers can
531 * execute in a reasonably sane state.
532 *
533 * Reset InterruptHoldoffCount in case we ereport'd from inside an
534 * interrupt holdoff section. (We assume here that no handler will
535 * itself be inside a holdoff section. If necessary, such a handler
536 * could save and restore InterruptHoldoffCount for itself, but this
537 * should make life easier for most.)
538 */
541
542 CritSectionCount = 0; /* should be unnecessary, but... */
543
544 /*
545 * Note that we leave CurrentMemoryContext set to ErrorContext. The
546 * handler should reset it to something else soon.
547 */
548
550 PG_RE_THROW();
551 }
552
553 /* Emit the message to the right places */
555
556 /*
557 * If this is the outermost recursion level, we can clean up by resetting
558 * ErrorContext altogether (compare FlushErrorState), which is good
559 * because it cleans up any random leakages that might have occurred in
560 * places such as context callback functions. If we're nested, we can
561 * only safely remove the subsidiary data of the current stack entry.
562 */
563 if (errordata_stack_depth == 0 && recursion_depth == 1)
565 else
567
568 /* Release stack entry and exit error-handling context */
570 MemoryContextSwitchTo(oldcontext);
572
573 /*
574 * Perform error recovery action as specified by elevel.
575 */
576 if (elevel == FATAL)
577 {
578 /*
579 * For a FATAL error, we let proc_exit clean up and exit.
580 *
581 * If we just reported a startup failure, the client will disconnect
582 * on receiving it, so don't send any more to the client.
583 */
586
587 /*
588 * fflush here is just to improve the odds that we get to see the
589 * error message, in case things are so hosed that proc_exit crashes.
590 * Any other code you might be tempted to add here should probably be
591 * in an on_proc_exit or on_shmem_exit callback instead.
592 */
593 fflush(NULL);
594
595 /*
596 * Let the cumulative stats system know. Only mark the session as
597 * terminated by fatal error if there is no other known cause.
598 */
601
602 /*
603 * Do normal process-exit cleanup, then return exit code 1 to indicate
604 * FATAL termination. The postmaster may or may not consider this
605 * worthy of panic, depending on which subprocess returns it.
606 */
607 proc_exit(1);
608 }
609
610 if (elevel >= PANIC)
611 {
612 /*
613 * Serious crash time. Postmaster will observe SIGABRT process exit
614 * status and kill the other backends too.
615 *
616 * XXX: what if we are *in* the postmaster? abort() won't kill our
617 * children...
618 */
619 fflush(NULL);
620 abort();
621 }
622
623 /*
624 * Check for cancel/die interrupt first --- this is so that the user can
625 * stop a query emitting tons of notice or warning messages, even if it's
626 * in a loop that otherwise fails to check for interrupts.
627 */
629}
630
631
632/*
633 * errsave_start --- begin a "soft" error-reporting cycle
634 *
635 * If "context" isn't an ErrorSaveContext node, this behaves as
636 * errstart(ERROR, domain), and the errsave() macro ends up acting
637 * exactly like ereport(ERROR, ...).
638 *
639 * If "context" is an ErrorSaveContext node, but the node creator only wants
640 * notification of the fact of a soft error without any details, we just set
641 * the error_occurred flag in the ErrorSaveContext node and return false,
642 * which will cause us to skip the remaining error processing steps.
643 *
644 * Otherwise, create and initialize error stack entry and return true.
645 * Subsequently, errmsg() and perhaps other routines will be called to further
646 * populate the stack entry. Finally, errsave_finish() will be called to
647 * tidy up.
648 */
649bool
650errsave_start(struct Node *context, const char *domain)
651{
652 ErrorSaveContext *escontext;
654
655 /*
656 * Do we have a context for soft error reporting? If not, just punt to
657 * errstart().
658 */
659 if (context == NULL || !IsA(context, ErrorSaveContext))
660 return errstart(ERROR, domain);
661
662 /* Report that a soft error was detected */
663 escontext = (ErrorSaveContext *) context;
664 escontext->error_occurred = true;
665
666 /* Nothing else to do if caller wants no further details */
667 if (!escontext->details_wanted)
668 return false;
669
670 /*
671 * Okay, crank up a stack entry to store the info in.
672 */
673
675
676 /* Initialize data for this error frame */
678 edata->elevel = LOG; /* signal all is well to errsave_finish */
680 /* Select default errcode based on the assumed elevel of ERROR */
681 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
682
683 /*
684 * Any allocations for this error state level should go into the caller's
685 * context. We don't need to pollute ErrorContext, or even require it to
686 * exist, in this code path.
687 */
688 edata->assoc_context = CurrentMemoryContext;
689
691 return true;
692}
693
694/*
695 * errsave_finish --- end a "soft" error-reporting cycle
696 *
697 * If errsave_start() decided this was a regular error, behave as
698 * errfinish(). Otherwise, package up the error details and save
699 * them in the ErrorSaveContext node.
700 */
701void
702errsave_finish(struct Node *context, const char *filename, int lineno,
703 const char *funcname)
704{
705 ErrorSaveContext *escontext = (ErrorSaveContext *) context;
707
708 /* verify stack depth before accessing *edata */
710
711 /*
712 * If errsave_start punted to errstart, then elevel will be ERROR or
713 * perhaps even PANIC. Punt likewise to errfinish.
714 */
715 if (edata->elevel >= ERROR)
716 {
717 errfinish(filename, lineno, funcname);
719 }
720
721 /*
722 * Else, we should package up the stack entry contents and deliver them to
723 * the caller.
724 */
726
727 /* Save the last few bits of error state into the stack entry */
729
730 /* Replace the LOG value that errsave_start inserted */
731 edata->elevel = ERROR;
732
733 /*
734 * We skip calling backtrace and context functions, which are more likely
735 * to cause trouble than provide useful context; they might act on the
736 * assumption that a transaction abort is about to occur.
737 */
738
739 /*
740 * Make a copy of the error info for the caller. All the subsidiary
741 * strings are already in the caller's context, so it's sufficient to
742 * flat-copy the stack entry.
743 */
744 escontext->error_data = palloc_object(ErrorData);
745 memcpy(escontext->error_data, edata, sizeof(ErrorData));
746
747 /* Exit error-handling context */
750}
751
752
753/*
754 * get_error_stack_entry --- allocate and initialize a new stack entry
755 *
756 * The entry should be freed, when we're done with it, by calling
757 * FreeErrorDataContents() and then decrementing errordata_stack_depth.
758 *
759 * Returning the entry's address is just a notational convenience,
760 * since it had better be errordata[errordata_stack_depth].
761 *
762 * Although the error stack is not large, we don't expect to run out of space.
763 * Using more than one entry implies a new error report during error recovery,
764 * which is possible but already suggests we're in trouble. If we exhaust the
765 * stack, almost certainly we are in an infinite loop of errors during error
766 * recovery, so we give up and PANIC.
767 *
768 * (Note that this is distinct from the recursion_depth checks, which
769 * guard against recursion while handling a single stack entry.)
770 */
771static ErrorData *
773{
775
776 /* Allocate error frame */
779 {
780 /* Wups, stack not big enough */
781 errordata_stack_depth = -1; /* make room on stack */
782 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
783 }
784
785 /* Initialize error frame to all zeroes/NULLs */
787 memset(edata, 0, sizeof(ErrorData));
788
789 /* Save errno immediately to ensure error parameter eval can't change it */
790 edata->saved_errno = errno;
791
792 return edata;
793}
794
795/*
796 * set_stack_entry_domain --- fill in the internationalization domain
797 */
798static void
800{
801 /* the default text domain is the backend's */
802 edata->domain = domain ? domain : PG_TEXTDOMAIN("postgres");
803 /* initialize context_domain the same way (see set_errcontext_domain()) */
804 edata->context_domain = edata->domain;
805}
806
807/*
808 * set_stack_entry_location --- fill in code-location details
809 *
810 * Store the values of __FILE__, __LINE__, and __func__ from the call site.
811 * We make an effort to normalize __FILE__, since compilers are inconsistent
812 * about how much of the path they'll include, and we'd prefer that the
813 * behavior not depend on that (especially, that it not vary with build path).
814 */
815static void
817 const char *filename, int lineno,
818 const char *funcname)
819{
820 if (filename)
821 {
822 const char *slash;
823
824 /* keep only base name, useful especially for vpath builds */
825 slash = strrchr(filename, '/');
826 if (slash)
827 filename = slash + 1;
828 /* Some Windows compilers use backslashes in __FILE__ strings */
829 slash = strrchr(filename, '\\');
830 if (slash)
831 filename = slash + 1;
832 }
833
834 edata->filename = filename;
835 edata->lineno = lineno;
836 edata->funcname = funcname;
837}
838
839/*
840 * matches_backtrace_functions --- checks whether the given funcname matches
841 * backtrace_functions
842 *
843 * See check_backtrace_functions.
844 */
845static bool
847{
848 const char *p;
849
850 if (!backtrace_function_list || funcname == NULL || funcname[0] == '\0')
851 return false;
852
854 for (;;)
855 {
856 if (*p == '\0') /* end of backtrace_function_list */
857 break;
858
859 if (strcmp(funcname, p) == 0)
860 return true;
861 p += strlen(p) + 1;
862 }
863
864 return false;
865}
866
867
868/*
869 * errcode --- add SQLSTATE error code to the current error
870 *
871 * The code is expected to be represented as per MAKE_SQLSTATE().
872 */
873int
874errcode(int sqlerrcode)
875{
877
878 /* we don't bother incrementing recursion_depth */
880
881 edata->sqlerrcode = sqlerrcode;
882
883 return 0; /* return value does not matter */
884}
885
886
887/*
888 * errcode_for_file_access --- add SQLSTATE error code to the current error
889 *
890 * The SQLSTATE code is chosen based on the saved errno value. We assume
891 * that the failing operation was some type of disk file access.
892 *
893 * NOTE: the primary error message string should generally include %m
894 * when this is used.
895 */
896int
898{
900
901 /* we don't bother incrementing recursion_depth */
903
904 switch (edata->saved_errno)
905 {
906 /* Permission-denied failures */
907 case EPERM: /* Not super-user */
908 case EACCES: /* Permission denied */
909#ifdef EROFS
910 case EROFS: /* Read only file system */
911#endif
913 break;
914
915 /* File not found */
916 case ENOENT: /* No such file or directory */
917 edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
918 break;
919
920 /* Duplicate file */
921 case EEXIST: /* File exists */
922 edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
923 break;
924
925 /* Wrong object type or state */
926 case ENOTDIR: /* Not a directory */
927 case EISDIR: /* Is a directory */
928#if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
929 case ENOTEMPTY: /* Directory not empty */
930#endif
931 edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
932 break;
933
934 /* Insufficient resources */
935 case ENOSPC: /* No space left on device */
936 edata->sqlerrcode = ERRCODE_DISK_FULL;
937 break;
938
939 case ENOMEM: /* Out of memory */
940 edata->sqlerrcode = ERRCODE_OUT_OF_MEMORY;
941 break;
942
943 case ENFILE: /* File table overflow */
944 case EMFILE: /* Too many open files */
946 break;
947
948 /* Hardware failure */
949 case EIO: /* I/O error */
950 edata->sqlerrcode = ERRCODE_IO_ERROR;
951 break;
952
953 case ENAMETOOLONG: /* File name too long */
954 edata->sqlerrcode = ERRCODE_FILE_NAME_TOO_LONG;
955 break;
956
957 /* All else is classified as internal errors */
958 default:
959 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
960 break;
961 }
962
963 return 0; /* return value does not matter */
964}
965
966/*
967 * errcode_for_socket_access --- add SQLSTATE error code to the current error
968 *
969 * The SQLSTATE code is chosen based on the saved errno value. We assume
970 * that the failing operation was some type of socket access.
971 *
972 * NOTE: the primary error message string should generally include %m
973 * when this is used.
974 */
975int
977{
979
980 /* we don't bother incrementing recursion_depth */
982
983 switch (edata->saved_errno)
984 {
985 /* Loss of connection */
987 edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
988 break;
989
990 /* All else is classified as internal errors */
991 default:
992 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
993 break;
994 }
995
996 return 0; /* return value does not matter */
997}
998
999
1000/*
1001 * This macro handles expansion of a format string and associated parameters;
1002 * it's common code for errmsg(), errdetail(), etc. Must be called inside
1003 * a routine that is declared like "const char *fmt, ..." and has an edata
1004 * pointer set up. The message is assigned to edata->targetfield, or
1005 * appended to it if appendval is true. The message is subject to translation
1006 * if translateit is true.
1007 *
1008 * Note: we pstrdup the buffer rather than just transferring its storage
1009 * to the edata field because the buffer might be considerably larger than
1010 * really necessary.
1011 */
1012#define EVALUATE_MESSAGE(domain, targetfield, appendval, translateit) \
1013 { \
1014 StringInfoData buf; \
1015 /* Internationalize the error format string */ \
1016 if ((translateit) && !in_error_recursion_trouble()) \
1017 fmt = dgettext((domain), fmt); \
1018 initStringInfo(&buf); \
1019 if ((appendval) && edata->targetfield) { \
1020 appendStringInfoString(&buf, edata->targetfield); \
1021 appendStringInfoChar(&buf, '\n'); \
1022 } \
1023 /* Generate actual output --- have to use appendStringInfoVA */ \
1024 for (;;) \
1025 { \
1026 va_list args; \
1027 int needed; \
1028 errno = edata->saved_errno; \
1029 va_start(args, fmt); \
1030 needed = appendStringInfoVA(&buf, fmt, args); \
1031 va_end(args); \
1032 if (needed == 0) \
1033 break; \
1034 enlargeStringInfo(&buf, needed); \
1035 } \
1036 /* Save the completed message into the stack item */ \
1037 if (edata->targetfield) \
1038 pfree(edata->targetfield); \
1039 edata->targetfield = pstrdup(buf.data); \
1040 pfree(buf.data); \
1041 }
1042
1043/*
1044 * Same as above, except for pluralized error messages. The calling routine
1045 * must be declared like "const char *fmt_singular, const char *fmt_plural,
1046 * unsigned long n, ...". Translation is assumed always wanted.
1047 */
1048#define EVALUATE_MESSAGE_PLURAL(domain, targetfield, appendval) \
1049 { \
1050 const char *fmt; \
1051 StringInfoData buf; \
1052 /* Internationalize the error format string */ \
1053 if (!in_error_recursion_trouble()) \
1054 fmt = dngettext((domain), fmt_singular, fmt_plural, n); \
1055 else \
1056 fmt = (n == 1 ? fmt_singular : fmt_plural); \
1057 initStringInfo(&buf); \
1058 if ((appendval) && edata->targetfield) { \
1059 appendStringInfoString(&buf, edata->targetfield); \
1060 appendStringInfoChar(&buf, '\n'); \
1061 } \
1062 /* Generate actual output --- have to use appendStringInfoVA */ \
1063 for (;;) \
1064 { \
1065 va_list args; \
1066 int needed; \
1067 errno = edata->saved_errno; \
1068 va_start(args, n); \
1069 needed = appendStringInfoVA(&buf, fmt, args); \
1070 va_end(args); \
1071 if (needed == 0) \
1072 break; \
1073 enlargeStringInfo(&buf, needed); \
1074 } \
1075 /* Save the completed message into the stack item */ \
1076 if (edata->targetfield) \
1077 pfree(edata->targetfield); \
1078 edata->targetfield = pstrdup(buf.data); \
1079 pfree(buf.data); \
1080 }
1081
1082
1083/*
1084 * errmsg --- add a primary error message text to the current error
1085 *
1086 * In addition to the usual %-escapes recognized by printf, "%m" in
1087 * fmt is replaced by the error message for the caller's value of errno.
1088 *
1089 * Note: no newline is needed at the end of the fmt string, since
1090 * ereport will provide one for the output methods that need it.
1091 */
1092int
1093errmsg(const char *fmt,...)
1094{
1096 MemoryContext oldcontext;
1097
1100 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1101
1102 edata->message_id = fmt;
1103 EVALUATE_MESSAGE(edata->domain, message, false, true);
1104
1105 MemoryContextSwitchTo(oldcontext);
1107 return 0; /* return value does not matter */
1108}
1109
1110/*
1111 * Add a backtrace to the containing ereport() call. This is intended to be
1112 * added temporarily during debugging.
1113 */
1114int
1116{
1118 MemoryContext oldcontext;
1119
1122 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1123
1124 set_backtrace(edata, 1);
1125
1126 MemoryContextSwitchTo(oldcontext);
1128
1129 return 0;
1130}
1131
1132/*
1133 * Compute backtrace data and add it to the supplied ErrorData. num_skip
1134 * specifies how many inner frames to skip. Use this to avoid showing the
1135 * internal backtrace support functions in the backtrace. This requires that
1136 * this and related functions are not inlined.
1137 *
1138 * The implementation is, unsurprisingly, platform-specific:
1139 * - GNU libc and copycats: Uses backtrace() and backtrace_symbols()
1140 * - Windows: Uses CaptureStackBackTrace() with DbgHelp for symbol resolution
1141 * (requires PDB files; falls back to exported functions/raw addresses if
1142 * unavailable)
1143 * - Others (musl libc): unsupported
1144 */
1145static void
1147{
1149
1151
1152#ifdef HAVE_BACKTRACE_SYMBOLS
1153 {
1154 void *frames[100];
1155 int nframes;
1156 char **strfrms;
1157
1158 nframes = backtrace(frames, lengthof(frames));
1160 if (strfrms != NULL)
1161 {
1162 for (int i = num_skip; i < nframes; i++)
1163 appendStringInfo(&errtrace, "\n%s", strfrms[i]);
1164 free(strfrms);
1165 }
1166 else
1168 "insufficient memory for backtrace generation");
1169 }
1170#elif defined(_MSC_VER)
1171 {
1172 void *frames[100];
1173 int nframes;
1174 char buffer[sizeof(SYMBOL_INFOW) + MAX_SYM_NAME * sizeof(wchar_t)];
1176
1177 /*
1178 * This is arranged so that we don't retry if we happen to fail to
1179 * initialize state on the first attempt in any one process.
1180 */
1182 {
1184
1189 0,
1190 FALSE,
1192 {
1194 "could not get process handle for backtrace: error code %lu",
1195 GetLastError());
1196 edata->backtrace = errtrace.data;
1197 return;
1198 }
1199
1204
1206 {
1210 "could not initialize symbol handler: error code %lu",
1211 GetLastError());
1212 edata->backtrace = errtrace.data;
1213 return;
1214 }
1215
1217 }
1218
1219 if (backtrace_process == NULL)
1220 return;
1221
1223
1224 if (nframes == 0)
1225 {
1226 appendStringInfoString(&errtrace, "zero stack frames captured");
1227 edata->backtrace = errtrace.data;
1228 return;
1229 }
1230
1231 psymbol = (PSYMBOL_INFOW) buffer;
1232 psymbol->MaxNameLen = MAX_SYM_NAME;
1233 psymbol->SizeOfStruct = sizeof(SYMBOL_INFOW);
1234
1235 for (int i = 0; i < nframes; i++)
1236 {
1237 DWORD64 address = (DWORD64) frames[i];
1240
1242 address,
1243 &displacement,
1244 psymbol);
1245 if (sym_result == TRUE)
1246 {
1248 size_t result;
1249
1250 /*
1251 * Convert symbol name from UTF-16 to database encoding using
1252 * wchar2char(), which handles both UTF-8 and non-UTF-8
1253 * databases correctly on Windows.
1254 */
1255 result = wchar2char(symbol_name, (const wchar_t *) psymbol->Name,
1256 sizeof(symbol_name), NULL);
1257
1258 if (result == (size_t) -1 || result == sizeof(symbol_name))
1259 {
1260 /* Conversion failed, use address only */
1262 "\n[0x%llx]",
1263 (unsigned long long) address);
1264 }
1265 else
1266 {
1267 IMAGEHLP_LINEW64 line;
1269 char filename[MAX_PATH];
1270
1271 line.SizeOfStruct = sizeof(IMAGEHLP_LINEW64);
1272
1273 /* Start with the common part: symbol+offset [address] */
1275 "\n%s+0x%llx [0x%llx]",
1277 (unsigned long long) displacement,
1278 (unsigned long long) address);
1279
1280 /* Try to append line info if available */
1282 address,
1284 &line))
1285 {
1286 result = wchar2char(filename, (const wchar_t *) line.FileName,
1287 sizeof(filename), NULL);
1288
1289 if (result != (size_t) -1 && result != sizeof(filename))
1290 {
1292 " [%s:%lu]",
1293 filename,
1294 (unsigned long) line.LineNumber);
1295 }
1296 }
1297 }
1298 }
1299 else
1300 {
1302 "\n[0x%llx] (symbol lookup failed: error code %lu)",
1303 (unsigned long long) address,
1304 GetLastError());
1305 }
1306 }
1307 }
1308#else
1310 "backtrace generation is not supported by this installation");
1311#endif
1312
1313 edata->backtrace = errtrace.data;
1314}
1315
1316/*
1317 * Cleanup function for set_backtrace().
1318 */
1320static void
1322{
1323#ifdef _MSC_VER
1324 /*
1325 * Currently only used to clean up after SymInitialize. We shouldn't ever
1326 * be called if backtrace_process is NULL, but better be safe.
1327 */
1329 {
1332 }
1333#endif
1334}
1335
1336/*
1337 * errmsg_internal --- add a primary error message text to the current error
1338 *
1339 * This is exactly like errmsg() except that strings passed to errmsg_internal
1340 * are not translated, and are customarily left out of the
1341 * internationalization message dictionary. This should be used for "can't
1342 * happen" cases that are probably not worth spending translation effort on.
1343 * We also use this for certain cases where we *must* not try to translate
1344 * the message because the translation would fail and result in infinite
1345 * error recursion.
1346 */
1347int
1348errmsg_internal(const char *fmt,...)
1349{
1351 MemoryContext oldcontext;
1352
1355 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1356
1357 edata->message_id = fmt;
1358 EVALUATE_MESSAGE(edata->domain, message, false, false);
1359
1360 MemoryContextSwitchTo(oldcontext);
1362 return 0; /* return value does not matter */
1363}
1364
1365
1366/*
1367 * errmsg_plural --- add a primary error message text to the current error,
1368 * with support for pluralization of the message text
1369 */
1370int
1371errmsg_plural(const char *fmt_singular, const char *fmt_plural,
1372 unsigned long n,...)
1373{
1375 MemoryContext oldcontext;
1376
1379 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1380
1381 edata->message_id = fmt_singular;
1382 EVALUATE_MESSAGE_PLURAL(edata->domain, message, false);
1383
1384 MemoryContextSwitchTo(oldcontext);
1386 return 0; /* return value does not matter */
1387}
1388
1389
1390/*
1391 * errdetail --- add a detail error message text to the current error
1392 */
1393int
1394errdetail(const char *fmt,...)
1395{
1397 MemoryContext oldcontext;
1398
1401 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1402
1403 EVALUATE_MESSAGE(edata->domain, detail, false, true);
1404
1405 MemoryContextSwitchTo(oldcontext);
1407 return 0; /* return value does not matter */
1408}
1409
1410
1411/*
1412 * errdetail_internal --- add a detail error message text to the current error
1413 *
1414 * This is exactly like errdetail() except that strings passed to
1415 * errdetail_internal are not translated, and are customarily left out of the
1416 * internationalization message dictionary. This should be used for detail
1417 * messages that seem not worth translating for one reason or another
1418 * (typically, that they don't seem to be useful to average users).
1419 */
1420int
1421errdetail_internal(const char *fmt,...)
1422{
1424 MemoryContext oldcontext;
1425
1428 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1429
1430 EVALUATE_MESSAGE(edata->domain, detail, false, false);
1431
1432 MemoryContextSwitchTo(oldcontext);
1434 return 0; /* return value does not matter */
1435}
1436
1437
1438/*
1439 * errdetail_log --- add a detail_log error message text to the current error
1440 */
1441int
1442errdetail_log(const char *fmt,...)
1443{
1445 MemoryContext oldcontext;
1446
1449 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1450
1451 EVALUATE_MESSAGE(edata->domain, detail_log, false, true);
1452
1453 MemoryContextSwitchTo(oldcontext);
1455 return 0; /* return value does not matter */
1456}
1457
1458/*
1459 * errdetail_log_plural --- add a detail_log error message text to the current error
1460 * with support for pluralization of the message text
1461 */
1462int
1463errdetail_log_plural(const char *fmt_singular, const char *fmt_plural,
1464 unsigned long n,...)
1465{
1467 MemoryContext oldcontext;
1468
1471 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1472
1473 EVALUATE_MESSAGE_PLURAL(edata->domain, detail_log, false);
1474
1475 MemoryContextSwitchTo(oldcontext);
1477 return 0; /* return value does not matter */
1478}
1479
1480
1481/*
1482 * errdetail_plural --- add a detail error message text to the current error,
1483 * with support for pluralization of the message text
1484 */
1485int
1486errdetail_plural(const char *fmt_singular, const char *fmt_plural,
1487 unsigned long n,...)
1488{
1490 MemoryContext oldcontext;
1491
1494 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1495
1496 EVALUATE_MESSAGE_PLURAL(edata->domain, detail, false);
1497
1498 MemoryContextSwitchTo(oldcontext);
1500 return 0; /* return value does not matter */
1501}
1502
1503
1504/*
1505 * errhint --- add a hint error message text to the current error
1506 */
1507int
1508errhint(const char *fmt,...)
1509{
1511 MemoryContext oldcontext;
1512
1515 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1516
1517 EVALUATE_MESSAGE(edata->domain, hint, false, true);
1518
1519 MemoryContextSwitchTo(oldcontext);
1521 return 0; /* return value does not matter */
1522}
1523
1524/*
1525 * errhint_internal --- add a hint error message text to the current error
1526 *
1527 * Non-translated version of errhint(), see also errmsg_internal().
1528 */
1529int
1530errhint_internal(const char *fmt,...)
1531{
1533 MemoryContext oldcontext;
1534
1537 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1538
1539 EVALUATE_MESSAGE(edata->domain, hint, false, false);
1540
1541 MemoryContextSwitchTo(oldcontext);
1543 return 0; /* return value does not matter */
1544}
1545
1546/*
1547 * errhint_plural --- add a hint error message text to the current error,
1548 * with support for pluralization of the message text
1549 */
1550int
1551errhint_plural(const char *fmt_singular, const char *fmt_plural,
1552 unsigned long n,...)
1553{
1555 MemoryContext oldcontext;
1556
1559 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1560
1561 EVALUATE_MESSAGE_PLURAL(edata->domain, hint, false);
1562
1563 MemoryContextSwitchTo(oldcontext);
1565 return 0; /* return value does not matter */
1566}
1567
1568
1569/*
1570 * errcontext_msg --- add a context error message text to the current error
1571 *
1572 * Unlike other cases, multiple calls are allowed to build up a stack of
1573 * context information. We assume earlier calls represent more-closely-nested
1574 * states.
1575 */
1576int
1577errcontext_msg(const char *fmt,...)
1578{
1580 MemoryContext oldcontext;
1581
1584 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1585
1586 EVALUATE_MESSAGE(edata->context_domain, context, true, true);
1587
1588 MemoryContextSwitchTo(oldcontext);
1590 return 0; /* return value does not matter */
1591}
1592
1593/*
1594 * set_errcontext_domain --- set message domain to be used by errcontext()
1595 *
1596 * errcontext_msg() can be called from a different module than the original
1597 * ereport(), so we cannot use the message domain passed in errstart() to
1598 * translate it. Instead, each errcontext_msg() call should be preceded by
1599 * a set_errcontext_domain() call to specify the domain. This is usually
1600 * done transparently by the errcontext() macro.
1601 */
1602int
1603set_errcontext_domain(const char *domain)
1604{
1606
1607 /* we don't bother incrementing recursion_depth */
1609
1610 /* the default text domain is the backend's */
1611 edata->context_domain = domain ? domain : PG_TEXTDOMAIN("postgres");
1612
1613 return 0; /* return value does not matter */
1614}
1615
1616
1617/*
1618 * errhidestmt --- optionally suppress STATEMENT: field of log entry
1619 *
1620 * This should be called if the message text already includes the statement.
1621 */
1622int
1623errhidestmt(bool hide_stmt)
1624{
1626
1627 /* we don't bother incrementing recursion_depth */
1629
1630 edata->hide_stmt = hide_stmt;
1631
1632 return 0; /* return value does not matter */
1633}
1634
1635/*
1636 * errhidecontext --- optionally suppress CONTEXT: field of log entry
1637 *
1638 * This should only be used for verbose debugging messages where the repeated
1639 * inclusion of context would bloat the log volume too much.
1640 */
1641int
1642errhidecontext(bool hide_ctx)
1643{
1645
1646 /* we don't bother incrementing recursion_depth */
1648
1649 edata->hide_ctx = hide_ctx;
1650
1651 return 0; /* return value does not matter */
1652}
1653
1654/*
1655 * errposition --- add cursor position to the current error
1656 */
1657int
1658errposition(int cursorpos)
1659{
1661
1662 /* we don't bother incrementing recursion_depth */
1664
1665 edata->cursorpos = cursorpos;
1666
1667 return 0; /* return value does not matter */
1668}
1669
1670/*
1671 * internalerrposition --- add internal cursor position to the current error
1672 */
1673int
1674internalerrposition(int cursorpos)
1675{
1677
1678 /* we don't bother incrementing recursion_depth */
1680
1681 edata->internalpos = cursorpos;
1682
1683 return 0; /* return value does not matter */
1684}
1685
1686/*
1687 * internalerrquery --- add internal query text to the current error
1688 *
1689 * Can also pass NULL to drop the internal query text entry. This case
1690 * is intended for use in error callback subroutines that are editorializing
1691 * on the layout of the error report.
1692 */
1693int
1694internalerrquery(const char *query)
1695{
1697
1698 /* we don't bother incrementing recursion_depth */
1700
1701 if (edata->internalquery)
1702 {
1703 pfree(edata->internalquery);
1704 edata->internalquery = NULL;
1705 }
1706
1707 if (query)
1708 edata->internalquery = MemoryContextStrdup(edata->assoc_context, query);
1709
1710 return 0; /* return value does not matter */
1711}
1712
1713/*
1714 * err_generic_string -- used to set individual ErrorData string fields
1715 * identified by PG_DIAG_xxx codes.
1716 *
1717 * This intentionally only supports fields that don't use localized strings,
1718 * so that there are no translation considerations.
1719 *
1720 * Most potential callers should not use this directly, but instead prefer
1721 * higher-level abstractions, such as errtablecol() (see relcache.c).
1722 */
1723int
1724err_generic_string(int field, const char *str)
1725{
1727
1728 /* we don't bother incrementing recursion_depth */
1730
1731 switch (field)
1732 {
1734 set_errdata_field(edata->assoc_context, &edata->schema_name, str);
1735 break;
1736 case PG_DIAG_TABLE_NAME:
1737 set_errdata_field(edata->assoc_context, &edata->table_name, str);
1738 break;
1740 set_errdata_field(edata->assoc_context, &edata->column_name, str);
1741 break;
1743 set_errdata_field(edata->assoc_context, &edata->datatype_name, str);
1744 break;
1746 set_errdata_field(edata->assoc_context, &edata->constraint_name, str);
1747 break;
1748 default:
1749 elog(ERROR, "unsupported ErrorData field id: %d", field);
1750 break;
1751 }
1752
1753 return 0; /* return value does not matter */
1754}
1755
1756/*
1757 * set_errdata_field --- set an ErrorData string field
1758 */
1759static void
1760set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str)
1761{
1762 Assert(*ptr == NULL);
1763 *ptr = MemoryContextStrdup(cxt, str);
1764}
1765
1766/*
1767 * geterrcode --- return the currently set SQLSTATE error code
1768 *
1769 * This is only intended for use in error callback subroutines, since there
1770 * is no other place outside elog.c where the concept is meaningful.
1771 */
1772int
1773geterrcode(void)
1774{
1776
1777 /* we don't bother incrementing recursion_depth */
1779
1780 return edata->sqlerrcode;
1781}
1782
1783/*
1784 * geterrposition --- return the currently set error position (0 if none)
1785 *
1786 * This is only intended for use in error callback subroutines, since there
1787 * is no other place outside elog.c where the concept is meaningful.
1788 */
1789int
1790geterrposition(void)
1791{
1793
1794 /* we don't bother incrementing recursion_depth */
1796
1797 return edata->cursorpos;
1798}
1799
1800/*
1801 * getinternalerrposition --- same for internal error position
1802 *
1803 * This is only intended for use in error callback subroutines, since there
1804 * is no other place outside elog.c where the concept is meaningful.
1805 */
1806int
1808{
1810
1811 /* we don't bother incrementing recursion_depth */
1813
1814 return edata->internalpos;
1815}
1816
1817
1818/*
1819 * Functions to allow construction of error message strings separately from
1820 * the ereport() call itself.
1821 *
1822 * The expected calling convention is
1823 *
1824 * pre_format_elog_string(errno, domain), var = format_elog_string(format,...)
1825 *
1826 * which can be hidden behind a macro such as GUC_check_errdetail(). We
1827 * assume that any functions called in the arguments of format_elog_string()
1828 * cannot result in re-entrant use of these functions --- otherwise the wrong
1829 * text domain might be used, or the wrong errno substituted for %m. This is
1830 * okay for the current usage with GUC check hooks, but might need further
1831 * effort someday.
1832 *
1833 * The result of format_elog_string() is stored in ErrorContext, and will
1834 * therefore survive until FlushErrorState() is called.
1835 */
1836static int save_format_errnumber;
1837static const char *save_format_domain;
1838
1839void
1840pre_format_elog_string(int errnumber, const char *domain)
1841{
1842 /* Save errno before evaluation of argument functions can change it */
1844 /* Save caller's text domain */
1845 save_format_domain = domain;
1846}
1847
1848char *
1849format_elog_string(const char *fmt,...)
1850{
1853 MemoryContext oldcontext;
1854
1855 /* Initialize a mostly-dummy error frame */
1856 edata = &errdata;
1857 MemSet(edata, 0, sizeof(ErrorData));
1858 /* the default text domain is the backend's */
1859 edata->domain = save_format_domain ? save_format_domain : PG_TEXTDOMAIN("postgres");
1860 /* set the errno to be used to interpret %m */
1861 edata->saved_errno = save_format_errnumber;
1862
1863 oldcontext = MemoryContextSwitchTo(ErrorContext);
1864
1865 edata->message_id = fmt;
1866 EVALUATE_MESSAGE(edata->domain, message, false, true);
1867
1868 MemoryContextSwitchTo(oldcontext);
1869
1870 return edata->message;
1871}
1872
1873
1874/*
1875 * Actual output of the top-of-stack error message
1876 *
1877 * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
1878 * if the error is caught by somebody). For all other severity levels this
1879 * is called by errfinish.
1880 */
1881void
1883{
1885 MemoryContext oldcontext;
1886
1889 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1890
1891 /*
1892 * Reset the formatted timestamp fields before emitting any logs. This
1893 * includes all the log destinations and emit_log_hook, as the latter
1894 * could use log_line_prefix or the formatted timestamps.
1895 */
1896 saved_timeval_set = false;
1897 formatted_log_time[0] = '\0';
1898
1899 /*
1900 * Call hook before sending message to log. The hook function is allowed
1901 * to turn off edata->output_to_server, so we must recheck that afterward.
1902 * Making any other change in the content of edata is not considered
1903 * supported.
1904 *
1905 * Note: the reason why the hook can only turn off output_to_server, and
1906 * not turn it on, is that it'd be unreliable: we will never get here at
1907 * all if errstart() deems the message uninteresting. A hook that could
1908 * make decisions in that direction would have to hook into errstart(),
1909 * where it would have much less information available. emit_log_hook is
1910 * intended for custom log filtering and custom log message transmission
1911 * mechanisms.
1912 *
1913 * The log hook has access to both the translated and original English
1914 * error message text, which is passed through to allow it to be used as a
1915 * message identifier. Note that the original text is not available for
1916 * detail, detail_log, hint and context text elements.
1917 */
1918 if (edata->output_to_server && emit_log_hook)
1919 (*emit_log_hook) (edata);
1920
1921 /* Send to server log, if enabled */
1922 if (edata->output_to_server)
1924
1925 /* Send to client, if enabled */
1926 if (edata->output_to_client)
1928
1929 MemoryContextSwitchTo(oldcontext);
1931}
1932
1933/*
1934 * CopyErrorData --- obtain a copy of the topmost error stack entry
1935 *
1936 * This is only for use in error handler code. The data is copied into the
1937 * current memory context, so callers should always switch away from
1938 * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
1939 */
1940ErrorData *
1942{
1945
1946 /*
1947 * we don't increment recursion_depth because out-of-memory here does not
1948 * indicate a problem within the error subsystem.
1949 */
1951
1953
1954 /* Copy the struct itself */
1956 memcpy(newedata, edata, sizeof(ErrorData));
1957
1958 /*
1959 * Make copies of separately-allocated strings. Note that we copy even
1960 * theoretically-constant strings such as filename. This is because those
1961 * could point into JIT-created code segments that might get unloaded at
1962 * transaction cleanup. In some cases we need the copied ErrorData to
1963 * survive transaction boundaries, so we'd better copy those strings too.
1964 */
1965 if (newedata->filename)
1966 newedata->filename = pstrdup(newedata->filename);
1967 if (newedata->funcname)
1968 newedata->funcname = pstrdup(newedata->funcname);
1969 if (newedata->domain)
1970 newedata->domain = pstrdup(newedata->domain);
1971 if (newedata->context_domain)
1972 newedata->context_domain = pstrdup(newedata->context_domain);
1973 if (newedata->message)
1974 newedata->message = pstrdup(newedata->message);
1975 if (newedata->detail)
1976 newedata->detail = pstrdup(newedata->detail);
1977 if (newedata->detail_log)
1978 newedata->detail_log = pstrdup(newedata->detail_log);
1979 if (newedata->hint)
1980 newedata->hint = pstrdup(newedata->hint);
1981 if (newedata->context)
1982 newedata->context = pstrdup(newedata->context);
1983 if (newedata->backtrace)
1984 newedata->backtrace = pstrdup(newedata->backtrace);
1985 if (newedata->message_id)
1986 newedata->message_id = pstrdup(newedata->message_id);
1987 if (newedata->schema_name)
1988 newedata->schema_name = pstrdup(newedata->schema_name);
1989 if (newedata->table_name)
1990 newedata->table_name = pstrdup(newedata->table_name);
1991 if (newedata->column_name)
1992 newedata->column_name = pstrdup(newedata->column_name);
1993 if (newedata->datatype_name)
1994 newedata->datatype_name = pstrdup(newedata->datatype_name);
1995 if (newedata->constraint_name)
1996 newedata->constraint_name = pstrdup(newedata->constraint_name);
1997 if (newedata->internalquery)
1998 newedata->internalquery = pstrdup(newedata->internalquery);
1999
2000 /* Use the calling context for string allocation */
2001 newedata->assoc_context = CurrentMemoryContext;
2002
2003 return newedata;
2004}
2005
2006/*
2007 * FreeErrorData --- free the structure returned by CopyErrorData.
2008 *
2009 * Error handlers should use this in preference to assuming they know all
2010 * the separately-allocated fields.
2011 */
2012void
2018
2019/*
2020 * FreeErrorDataContents --- free the subsidiary data of an ErrorData.
2021 *
2022 * This can be used on either an error stack entry or a copied ErrorData.
2023 */
2024static void
2026{
2027 if (edata->message)
2028 pfree(edata->message);
2029 if (edata->detail)
2030 pfree(edata->detail);
2031 if (edata->detail_log)
2032 pfree(edata->detail_log);
2033 if (edata->hint)
2034 pfree(edata->hint);
2035 if (edata->context)
2036 pfree(edata->context);
2037 if (edata->backtrace)
2038 pfree(edata->backtrace);
2039 if (edata->schema_name)
2040 pfree(edata->schema_name);
2041 if (edata->table_name)
2042 pfree(edata->table_name);
2043 if (edata->column_name)
2044 pfree(edata->column_name);
2045 if (edata->datatype_name)
2046 pfree(edata->datatype_name);
2047 if (edata->constraint_name)
2048 pfree(edata->constraint_name);
2049 if (edata->internalquery)
2050 pfree(edata->internalquery);
2051}
2052
2053/*
2054 * FlushErrorState --- flush the error state after error recovery
2055 *
2056 * This should be called by an error handler after it's done processing
2057 * the error; or as soon as it's done CopyErrorData, if it intends to
2058 * do stuff that is likely to provoke another error. You are not "out" of
2059 * the error subsystem until you have done this.
2060 */
2061void
2063{
2064 /*
2065 * Reset stack to empty. The only case where it would be more than one
2066 * deep is if we serviced an error that interrupted construction of
2067 * another message. We assume control escaped out of that message
2068 * construction and won't ever go back.
2069 */
2071 recursion_depth = 0;
2072 /* Delete all data in ErrorContext */
2074}
2075
2076/*
2077 * ThrowErrorData --- report an error described by an ErrorData structure
2078 *
2079 * This function should be called on an ErrorData structure that isn't stored
2080 * on the errordata stack and hasn't been processed yet. It will call
2081 * errstart() and errfinish() as needed, so those should not have already been
2082 * called.
2083 *
2084 * ThrowErrorData() is useful for handling soft errors. It's also useful for
2085 * re-reporting errors originally reported by background worker processes and
2086 * then propagated (with or without modification) to the backend responsible
2087 * for them.
2088 */
2089void
2091{
2093 MemoryContext oldcontext;
2094
2095 if (!errstart(edata->elevel, edata->domain))
2096 return; /* error is not to be reported at all */
2097
2100 oldcontext = MemoryContextSwitchTo(newedata->assoc_context);
2101
2102 /* Copy the supplied fields to the error stack entry. */
2103 if (edata->sqlerrcode != 0)
2104 newedata->sqlerrcode = edata->sqlerrcode;
2105 if (edata->message)
2106 newedata->message = pstrdup(edata->message);
2107 if (edata->detail)
2108 newedata->detail = pstrdup(edata->detail);
2109 if (edata->detail_log)
2110 newedata->detail_log = pstrdup(edata->detail_log);
2111 if (edata->hint)
2112 newedata->hint = pstrdup(edata->hint);
2113 if (edata->context)
2114 newedata->context = pstrdup(edata->context);
2115 if (edata->backtrace)
2116 newedata->backtrace = pstrdup(edata->backtrace);
2117 /* assume message_id is not available */
2118 if (edata->schema_name)
2119 newedata->schema_name = pstrdup(edata->schema_name);
2120 if (edata->table_name)
2121 newedata->table_name = pstrdup(edata->table_name);
2122 if (edata->column_name)
2123 newedata->column_name = pstrdup(edata->column_name);
2124 if (edata->datatype_name)
2125 newedata->datatype_name = pstrdup(edata->datatype_name);
2126 if (edata->constraint_name)
2127 newedata->constraint_name = pstrdup(edata->constraint_name);
2128 newedata->cursorpos = edata->cursorpos;
2129 newedata->internalpos = edata->internalpos;
2130 if (edata->internalquery)
2131 newedata->internalquery = pstrdup(edata->internalquery);
2132
2133 MemoryContextSwitchTo(oldcontext);
2135
2136 /* Process the error. */
2137 errfinish(edata->filename, edata->lineno, edata->funcname);
2138}
2139
2140/*
2141 * ReThrowError --- re-throw a previously copied error
2142 *
2143 * A handler can do CopyErrorData/FlushErrorState to get out of the error
2144 * subsystem, then do some processing, and finally ReThrowError to re-throw
2145 * the original error. This is slower than just PG_RE_THROW() but should
2146 * be used if the "some processing" is likely to incur another error.
2147 */
2148void
2150{
2152
2153 Assert(edata->elevel == ERROR);
2154
2155 /* Push the data back into the error context */
2158
2160 memcpy(newedata, edata, sizeof(ErrorData));
2161
2162 /* Make copies of separately-allocated fields */
2163 if (newedata->message)
2164 newedata->message = pstrdup(newedata->message);
2165 if (newedata->detail)
2166 newedata->detail = pstrdup(newedata->detail);
2167 if (newedata->detail_log)
2168 newedata->detail_log = pstrdup(newedata->detail_log);
2169 if (newedata->hint)
2170 newedata->hint = pstrdup(newedata->hint);
2171 if (newedata->context)
2172 newedata->context = pstrdup(newedata->context);
2173 if (newedata->backtrace)
2174 newedata->backtrace = pstrdup(newedata->backtrace);
2175 if (newedata->schema_name)
2176 newedata->schema_name = pstrdup(newedata->schema_name);
2177 if (newedata->table_name)
2178 newedata->table_name = pstrdup(newedata->table_name);
2179 if (newedata->column_name)
2180 newedata->column_name = pstrdup(newedata->column_name);
2181 if (newedata->datatype_name)
2182 newedata->datatype_name = pstrdup(newedata->datatype_name);
2183 if (newedata->constraint_name)
2184 newedata->constraint_name = pstrdup(newedata->constraint_name);
2185 if (newedata->internalquery)
2186 newedata->internalquery = pstrdup(newedata->internalquery);
2187
2188 /* Reset the assoc_context to be ErrorContext */
2189 newedata->assoc_context = ErrorContext;
2190
2192 PG_RE_THROW();
2193}
2194
2195/*
2196 * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
2197 */
2198void
2200{
2201 /* If possible, throw the error to the next outer setjmp handler */
2202 if (PG_exception_stack != NULL)
2204 else
2205 {
2206 /*
2207 * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
2208 * we have now exited only to discover that there is no outer setjmp
2209 * handler to pass the error to. Had the error been thrown outside
2210 * the block to begin with, we'd have promoted the error to FATAL, so
2211 * the correct behavior is to make it FATAL now; that is, emit it and
2212 * then call proc_exit.
2213 */
2215
2217 Assert(edata->elevel == ERROR);
2218 edata->elevel = FATAL;
2219
2220 /*
2221 * At least in principle, the increase in severity could have changed
2222 * where-to-output decisions, so recalculate.
2223 */
2224 edata->output_to_server = should_output_to_server(FATAL);
2225 edata->output_to_client = should_output_to_client(FATAL);
2226
2227 /*
2228 * We can use errfinish() for the rest, but we don't want it to call
2229 * any error context routines a second time. Since we know we are
2230 * about to exit, it should be OK to just clear the context stack.
2231 */
2233
2234 errfinish(edata->filename, edata->lineno, edata->funcname);
2235 }
2236
2237 /* Doesn't return ... */
2238 ExceptionalCondition("pg_re_throw tried to return", __FILE__, __LINE__);
2239}
2240
2241
2242/*
2243 * GetErrorContextStack - Return the context stack, for display/diags
2244 *
2245 * Returns a pstrdup'd string in the caller's context which includes the PG
2246 * error call stack. It is the caller's responsibility to ensure this string
2247 * is pfree'd (or its context cleaned up) when done.
2248 *
2249 * This information is collected by traversing the error contexts and calling
2250 * each context's callback function, each of which is expected to call
2251 * errcontext() to return a string which can be presented to the user.
2252 */
2253char *
2255{
2257 ErrorContextCallback *econtext;
2258
2259 /*
2260 * Crank up a stack entry to store the info in.
2261 */
2263
2265
2266 /*
2267 * Set up assoc_context to be the caller's context, so any allocations
2268 * done (which will include edata->context) will use their context.
2269 */
2270 edata->assoc_context = CurrentMemoryContext;
2271
2272 /*
2273 * Call any context callback functions to collect the context information
2274 * into edata->context.
2275 *
2276 * Errors occurring in callback functions should go through the regular
2277 * error handling code which should handle any recursive errors, though we
2278 * double-check above, just in case.
2279 */
2280 for (econtext = error_context_stack;
2281 econtext != NULL;
2282 econtext = econtext->previous)
2283 econtext->callback(econtext->arg);
2284
2285 /*
2286 * Clean ourselves off the stack, any allocations done should have been
2287 * using edata->assoc_context, which we set up earlier to be the caller's
2288 * context, so we're free to just remove our entry off the stack and
2289 * decrement recursion depth and exit.
2290 */
2293
2294 /*
2295 * Return a pointer to the string the caller asked for, which should have
2296 * been allocated in their context.
2297 */
2298 return edata->context;
2299}
2300
2301
2302/*
2303 * Initialization of error output file
2304 */
2305void
2307{
2308 int fd,
2309 istty;
2310
2311 if (OutputFileName[0])
2312 {
2313 /*
2314 * A debug-output file name was given.
2315 *
2316 * Make sure we can write the file, and find out if it's a tty.
2317 */
2319 0666)) < 0)
2320 ereport(FATAL,
2322 errmsg("could not open file \"%s\": %m", OutputFileName)));
2323 istty = isatty(fd);
2324 close(fd);
2325
2326 /*
2327 * Redirect our stderr to the debug output file.
2328 */
2329 if (!freopen(OutputFileName, "a", stderr))
2330 ereport(FATAL,
2332 errmsg("could not reopen file \"%s\" as stderr: %m",
2333 OutputFileName)));
2334
2335 /*
2336 * If the file is a tty and we're running under the postmaster, try to
2337 * send stdout there as well (if it isn't a tty then stderr will block
2338 * out stdout, so we may as well let stdout go wherever it was going
2339 * before).
2340 */
2341 if (istty && IsUnderPostmaster)
2342 if (!freopen(OutputFileName, "a", stdout))
2343 ereport(FATAL,
2345 errmsg("could not reopen file \"%s\" as stdout: %m",
2346 OutputFileName)));
2347 }
2348}
2349
2350
2351/*
2352 * GUC check_hook for log_min_messages
2353 *
2354 * This value is parsed as a comma-separated list of zero or more TYPE:LEVEL
2355 * elements. For each element, TYPE corresponds to a bk_category value (see
2356 * postmaster/proctypelist.h); LEVEL is one of server_message_level_options.
2357 *
2358 * In addition, there must be a single LEVEL element (with no TYPE part)
2359 * which sets the default level for process types that aren't specified.
2360 */
2361bool
2363{
2364 char *rawstring;
2365 List *elemlist;
2367 char *result;
2369 bool assigned[BACKEND_NUM_TYPES] = {0};
2370 int defaultlevel = -1; /* -1 means not assigned */
2371
2372 const char *const process_types[] = {
2373#define PG_PROCTYPE(bktype, bkcategory, description, main_func, shmem_attach) \
2374 [bktype] = bkcategory,
2376#undef PG_PROCTYPE
2377 };
2378
2379 /* Need a modifiable copy of string. */
2381 if (rawstring == NULL)
2382 return false;
2383
2384 /* Parse the string into a list. */
2385 if (!SplitGUCList(rawstring, ',', &elemlist))
2386 {
2387 /* syntax error in list */
2388 GUC_check_errdetail("List syntax is invalid.");
2391 return false;
2392 }
2393
2394 /* Validate and assign log level and process type. */
2395 foreach_ptr(char, elem, elemlist)
2396 {
2397 char *sep = strchr(elem, ':');
2398
2399 /*
2400 * If there's no ':' separator in the entry, this is the default log
2401 * level. Otherwise it's a process type-specific entry.
2402 */
2403 if (sep == NULL)
2404 {
2405 const struct config_enum_entry *entry;
2406 bool found;
2407
2408 /* Reject duplicates for default log level. */
2409 if (defaultlevel != -1)
2410 {
2411 GUC_check_errdetail("Redundant specification of default log level.");
2412 goto lmm_fail;
2413 }
2414
2415 /* Validate the log level */
2416 found = false;
2417 for (entry = server_message_level_options; entry && entry->name; entry++)
2418 {
2419 if (pg_strcasecmp(entry->name, elem) == 0)
2420 {
2421 defaultlevel = entry->val;
2422 found = true;
2423 break;
2424 }
2425 }
2426
2427 if (!found)
2428 {
2429 GUC_check_errdetail("Unrecognized log level: \"%s\".", elem);
2430 goto lmm_fail;
2431 }
2432 }
2433 else
2434 {
2435 char *loglevel = sep + 1;
2436 char *ptype = elem;
2437 bool found;
2438 int level;
2439 const struct config_enum_entry *entry;
2440
2441 /*
2442 * Temporarily clobber the ':' with a string terminator, so that
2443 * we can validate it. We restore this at the bottom.
2444 */
2445 *sep = '\0';
2446
2447 /* Validate the log level */
2448 found = false;
2449 for (entry = server_message_level_options; entry && entry->name; entry++)
2450 {
2451 if (pg_strcasecmp(entry->name, loglevel) == 0)
2452 {
2453 level = entry->val;
2454 found = true;
2455 break;
2456 }
2457 }
2458
2459 if (!found)
2460 {
2461 GUC_check_errdetail("Unrecognized log level for process type \"%s\": \"%s\".",
2462 ptype, loglevel);
2463 goto lmm_fail;
2464 }
2465
2466 /* Is the process type name valid and unique? */
2467 found = false;
2468 for (int i = 0; i < BACKEND_NUM_TYPES; i++)
2469 {
2470 if (pg_strcasecmp(process_types[i], ptype) == 0)
2471 {
2472 /* Reject duplicates for a process type. */
2473 if (assigned[i])
2474 {
2475 GUC_check_errdetail("Redundant log level specification for process type \"%s\".",
2476 ptype);
2477 goto lmm_fail;
2478 }
2479
2480 newlevel[i] = level;
2481 assigned[i] = true;
2482 found = true;
2483
2484 /*
2485 * note: we must keep looking! some process types appear
2486 * multiple times in proctypelist.h.
2487 */
2488 }
2489 }
2490
2491 if (!found)
2492 {
2493 GUC_check_errdetail("Unrecognized process type \"%s\".", ptype);
2494 goto lmm_fail;
2495 }
2496
2497 /* Put the separator back in place */
2498 *sep = ':';
2499 }
2500
2501 /* all good */
2502 continue;
2503
2504lmm_fail:
2507 return false;
2508 }
2509
2510 /*
2511 * The default log level must be specified. It is the fallback value.
2512 */
2513 if (defaultlevel == -1)
2514 {
2515 GUC_check_errdetail("Default log level was not defined.");
2518 return false;
2519 }
2520
2521 /* Apply the default log level to all processes not listed. */
2522 for (int i = 0; i < BACKEND_NUM_TYPES; i++)
2523 {
2524 if (!assigned[i])
2526 }
2527
2528 /*
2529 * Save an ordered representation of the user-specified string, for the
2530 * show_hook.
2531 */
2533
2535 foreach_ptr(char, elem, elemlist)
2536 {
2537 if (foreach_current_index(elem) == 0)
2539 else
2540 appendStringInfo(&buf, ", %s", elem);
2541 }
2542
2543 result = guc_strdup(LOG, buf.data);
2544 if (!result)
2545 {
2546 pfree(buf.data);
2547 return false;
2548 }
2549
2550 guc_free(*newval);
2551 *newval = result;
2552
2555 pfree(buf.data);
2556
2557 /*
2558 * Pass back data for assign_log_min_messages to use.
2559 */
2560 *extra = guc_malloc(LOG, BACKEND_NUM_TYPES * sizeof(int));
2561 if (!*extra)
2562 return false;
2563 memcpy(*extra, newlevel, BACKEND_NUM_TYPES * sizeof(int));
2564
2565 return true;
2566}
2567
2568/*
2569 * list_sort() callback for check_log_min_messages. The default element
2570 * goes first; the rest are ordered by strcmp() of the process type.
2571 */
2572static int
2574{
2575 const char *s = lfirst(a);
2576 const char *t = lfirst(b);
2577
2578 if (strchr(s, ':') == NULL)
2579 return -1;
2580 else if (strchr(t, ':') == NULL)
2581 return 1;
2582 else
2583 return strcmp(s, t);
2584}
2585
2586/*
2587 * GUC assign_hook for log_min_messages
2588 */
2589void
2590assign_log_min_messages(const char *newval, void *extra)
2591{
2592 for (int i = 0; i < BACKEND_NUM_TYPES; i++)
2593 log_min_messages[i] = ((int *) extra)[i];
2594}
2595
2596/*
2597 * GUC check_hook for backtrace_functions
2598 *
2599 * We split the input string, where commas separate function names
2600 * and certain whitespace chars are ignored, into a \0-separated (and
2601 * \0\0-terminated) list of function names. This formulation allows
2602 * easy scanning when an error is thrown while avoiding the use of
2603 * non-reentrant strtok(), as well as keeping the output data in a
2604 * single palloc() chunk.
2605 */
2606bool
2608{
2609 int newvallen = strlen(*newval);
2610 char *someval;
2611 int validlen;
2612 int i;
2613 int j;
2614
2615 /*
2616 * Allow characters that can be C identifiers and commas as separators, as
2617 * well as some whitespace for readability.
2618 */
2620 "0123456789_"
2621 "abcdefghijklmnopqrstuvwxyz"
2622 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2623 ", \n\t");
2624 if (validlen != newvallen)
2625 {
2626 GUC_check_errdetail("Invalid character.");
2627 return false;
2628 }
2629
2630 if (*newval[0] == '\0')
2631 {
2632 *extra = NULL;
2633 return true;
2634 }
2635
2636 /*
2637 * Allocate space for the output and create the copy. We could discount
2638 * whitespace chars to save some memory, but it doesn't seem worth the
2639 * trouble.
2640 */
2641 someval = guc_malloc(LOG, newvallen + 1 + 1);
2642 if (!someval)
2643 return false;
2644 for (i = 0, j = 0; i < newvallen; i++)
2645 {
2646 if ((*newval)[i] == ',')
2647 someval[j++] = '\0'; /* next item */
2648 else if ((*newval)[i] == ' ' ||
2649 (*newval)[i] == '\n' ||
2650 (*newval)[i] == '\t')
2651 ; /* ignore these */
2652 else
2653 someval[j++] = (*newval)[i]; /* copy anything else */
2654 }
2655
2656 /* two \0s end the setting */
2657 someval[j] = '\0';
2658 someval[j + 1] = '\0';
2659
2660 *extra = someval;
2661 return true;
2662}
2663
2664/*
2665 * GUC assign_hook for backtrace_functions
2666 */
2667void
2668assign_backtrace_functions(const char *newval, void *extra)
2669{
2670 backtrace_function_list = (char *) extra;
2671}
2672
2673/*
2674 * GUC check_hook for log_destination
2675 */
2676bool
2678{
2679 char *rawstring;
2680 List *elemlist;
2681 ListCell *l;
2682 int newlogdest = 0;
2683 int *myextra;
2684
2685 /* Need a modifiable copy of string */
2687
2688 /* Parse string into list of identifiers */
2690 {
2691 /* syntax error in list */
2692 GUC_check_errdetail("List syntax is invalid.");
2695 return false;
2696 }
2697
2698 foreach(l, elemlist)
2699 {
2700 char *tok = (char *) lfirst(l);
2701
2702 if (pg_strcasecmp(tok, "stderr") == 0)
2704 else if (pg_strcasecmp(tok, "csvlog") == 0)
2706 else if (pg_strcasecmp(tok, "jsonlog") == 0)
2708#ifdef HAVE_SYSLOG
2709 else if (pg_strcasecmp(tok, "syslog") == 0)
2711#endif
2712#ifdef WIN32
2713 else if (pg_strcasecmp(tok, "eventlog") == 0)
2715#endif
2716 else
2717 {
2718 GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
2721 return false;
2722 }
2723 }
2724
2727
2728 myextra = (int *) guc_malloc(LOG, sizeof(int));
2729 if (!myextra)
2730 return false;
2732 *extra = myextra;
2733
2734 return true;
2735}
2736
2737/*
2738 * GUC assign_hook for log_destination
2739 */
2740void
2741assign_log_destination(const char *newval, void *extra)
2742{
2743 Log_destination = *((int *) extra);
2744}
2745
2746/*
2747 * GUC assign_hook for syslog_ident
2748 */
2749void
2750assign_syslog_ident(const char *newval, void *extra)
2751{
2752#ifdef HAVE_SYSLOG
2753 /*
2754 * guc.c is likely to call us repeatedly with same parameters, so don't
2755 * thrash the syslog connection unnecessarily. Also, we do not re-open
2756 * the connection until needed, since this routine will get called whether
2757 * or not Log_destination actually mentions syslog.
2758 *
2759 * Note that we make our own copy of the ident string rather than relying
2760 * on guc.c's. This may be overly paranoid, but it ensures that we cannot
2761 * accidentally free a string that syslog is still using.
2762 */
2763 if (syslog_ident == NULL || strcmp(syslog_ident, newval) != 0)
2764 {
2765 if (openlog_done)
2766 {
2767 closelog();
2768 openlog_done = false;
2769 }
2772 /* if the strdup fails, we will cope in write_syslog() */
2773 }
2774#endif
2775 /* Without syslog support, just ignore it */
2776}
2777
2778/*
2779 * GUC assign_hook for syslog_facility
2780 */
2781void
2783{
2784#ifdef HAVE_SYSLOG
2785 /*
2786 * As above, don't thrash the syslog connection unnecessarily.
2787 */
2788 if (syslog_facility != newval)
2789 {
2790 if (openlog_done)
2791 {
2792 closelog();
2793 openlog_done = false;
2794 }
2796 }
2797#endif
2798 /* Without syslog support, just ignore it */
2799}
2800
2801#ifdef HAVE_SYSLOG
2802
2803/*
2804 * Write a message line to syslog
2805 */
2806static void
2807write_syslog(int level, const char *line)
2808{
2809 static unsigned long seq = 0;
2810
2811 int len;
2812 const char *nlpos;
2813
2814 /* Open syslog connection if not done yet */
2815 if (!openlog_done)
2816 {
2817 openlog(syslog_ident ? syslog_ident : "postgres",
2820 openlog_done = true;
2821 }
2822
2823 /*
2824 * We add a sequence number to each log message to suppress "same"
2825 * messages.
2826 */
2827 seq++;
2828
2829 /*
2830 * Our problem here is that many syslog implementations don't handle long
2831 * messages in an acceptable manner. While this function doesn't help that
2832 * fact, it does work around by splitting up messages into smaller pieces.
2833 *
2834 * We divide into multiple syslog() calls if message is too long or if the
2835 * message contains embedded newline(s).
2836 */
2837 len = strlen(line);
2838 nlpos = strchr(line, '\n');
2840 {
2841 int chunk_nr = 0;
2842
2843 while (len > 0)
2844 {
2845 char buf[PG_SYSLOG_LIMIT + 1];
2846 int buflen;
2847 int i;
2848
2849 /* if we start at a newline, move ahead one char */
2850 if (line[0] == '\n')
2851 {
2852 line++;
2853 len--;
2854 /* we need to recompute the next newline's position, too */
2855 nlpos = strchr(line, '\n');
2856 continue;
2857 }
2858
2859 /* copy one line, or as much as will fit, to buf */
2860 if (nlpos != NULL)
2861 buflen = nlpos - line;
2862 else
2863 buflen = len;
2864 buflen = Min(buflen, PG_SYSLOG_LIMIT);
2865 memcpy(buf, line, buflen);
2866 buf[buflen] = '\0';
2867
2868 /* trim to multibyte letter boundary */
2869 buflen = pg_mbcliplen(buf, buflen, buflen);
2870 if (buflen <= 0)
2871 return;
2872 buf[buflen] = '\0';
2873
2874 /* already word boundary? */
2875 if (line[buflen] != '\0' &&
2876 !isspace((unsigned char) line[buflen]))
2877 {
2878 /* try to divide at word boundary */
2879 i = buflen - 1;
2880 while (i > 0 && !isspace((unsigned char) buf[i]))
2881 i--;
2882
2883 if (i > 0) /* else couldn't divide word boundary */
2884 {
2885 buflen = i;
2886 buf[i] = '\0';
2887 }
2888 }
2889
2890 chunk_nr++;
2891
2893 syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
2894 else
2895 syslog(level, "[%d] %s", chunk_nr, buf);
2896
2897 line += buflen;
2898 len -= buflen;
2899 }
2900 }
2901 else
2902 {
2903 /* message short enough */
2905 syslog(level, "[%lu] %s", seq, line);
2906 else
2907 syslog(level, "%s", line);
2908 }
2909}
2910#endif /* HAVE_SYSLOG */
2911
2912#ifdef WIN32
2913/*
2914 * Get the PostgreSQL equivalent of the Windows ANSI code page. "ANSI" system
2915 * interfaces (e.g. CreateFileA()) expect string arguments in this encoding.
2916 * Every process in a given system will find the same value at all times.
2917 */
2918static int
2919GetACPEncoding(void)
2920{
2921 static int encoding = -2;
2922
2923 if (encoding == -2)
2925
2926 return encoding;
2927}
2928
2929/*
2930 * Write a message line to the windows event log
2931 */
2932static void
2933write_eventlog(int level, const char *line, int len)
2934{
2937
2939 {
2942 if (evtHandle == NULL)
2943 {
2945 return;
2946 }
2947 }
2948
2949 switch (level)
2950 {
2951 case DEBUG5:
2952 case DEBUG4:
2953 case DEBUG3:
2954 case DEBUG2:
2955 case DEBUG1:
2956 case LOG:
2957 case LOG_SERVER_ONLY:
2958 case INFO:
2959 case NOTICE:
2961 break;
2962 case WARNING:
2965 break;
2966 case ERROR:
2967 case FATAL:
2968 case PANIC:
2969 default:
2971 break;
2972 }
2973
2974 /*
2975 * If message character encoding matches the encoding expected by
2976 * ReportEventA(), call it to avoid the hazards of conversion. Otherwise,
2977 * try to convert the message to UTF16 and write it with ReportEventW().
2978 * Fall back on ReportEventA() if conversion failed.
2979 *
2980 * Since we palloc the structure required for conversion, also fall
2981 * through to writing unconverted if we have not yet set up
2982 * CurrentMemoryContext.
2983 *
2984 * Also verify that we are not on our way into error recursion trouble due
2985 * to error messages thrown deep inside pgwin32_message_to_UTF16().
2986 */
2990 {
2991 WCHAR *utf16;
2992
2994 if (utf16)
2995 {
2996 const WCHAR *utf16_const = utf16;
2997
2999 eventlevel,
3000 0,
3001 0, /* All events are Id 0 */
3002 NULL,
3003 1,
3004 0,
3005 &utf16_const,
3006 NULL);
3007 /* XXX Try ReportEventA() when ReportEventW() fails? */
3008
3009 pfree(utf16);
3010 return;
3011 }
3012 }
3014 eventlevel,
3015 0,
3016 0, /* All events are Id 0 */
3017 NULL,
3018 1,
3019 0,
3020 &line,
3021 NULL);
3022}
3023#endif /* WIN32 */
3024
3025static void
3026write_console(const char *line, int len)
3027{
3028 int rc;
3029
3030#ifdef WIN32
3031
3032 /*
3033 * Try to convert the message to UTF16 and write it with WriteConsoleW().
3034 * Fall back on write() if anything fails.
3035 *
3036 * In contrast to write_eventlog(), don't skip straight to write() based
3037 * on the applicable encodings. Unlike WriteConsoleW(), write() depends
3038 * on the suitability of the console output code page. Since we put
3039 * stderr into binary mode in SubPostmasterMain(), write() skips the
3040 * necessary translation anyway.
3041 *
3042 * WriteConsoleW() will fail if stderr is redirected, so just fall through
3043 * to writing unconverted to the logfile in this case.
3044 *
3045 * Since we palloc the structure required for conversion, also fall
3046 * through to writing unconverted if we have not yet set up
3047 * CurrentMemoryContext.
3048 */
3052 {
3053 WCHAR *utf16;
3054 int utf16len;
3055
3057 if (utf16 != NULL)
3058 {
3060 DWORD written;
3061
3064 {
3065 pfree(utf16);
3066 return;
3067 }
3068
3069 /*
3070 * In case WriteConsoleW() failed, fall back to writing the
3071 * message unconverted.
3072 */
3073 pfree(utf16);
3074 }
3075 }
3076#else
3077
3078 /*
3079 * Conversion on non-win32 platforms is not implemented yet. It requires
3080 * non-throw version of pg_do_encoding_conversion(), that converts
3081 * unconvertible characters to '?' without errors.
3082 *
3083 * XXX: We have a no-throw version now. It doesn't convert to '?' though.
3084 */
3085#endif
3086
3087 /*
3088 * We ignore any error from write() here. We have no useful way to report
3089 * it ... certainly whining on stderr isn't likely to be productive.
3090 */
3091 rc = write(fileno(stderr), line, len);
3092 (void) rc;
3093}
3094
3095/*
3096 * get_formatted_log_time -- compute and get the log timestamp.
3097 *
3098 * The timestamp is computed if not set yet, so as it is kept consistent
3099 * among all the log destinations that require it to be consistent. Note
3100 * that the computed timestamp is returned in a static buffer, not
3101 * palloc()'d.
3102 */
3103char *
3105{
3107 char msbuf[13];
3108
3109 /* leave if already computed */
3110 if (formatted_log_time[0] != '\0')
3111 return formatted_log_time;
3112
3113 if (!saved_timeval_set)
3114 {
3116 saved_timeval_set = true;
3117 }
3118
3120
3121 /*
3122 * Note: we expect that guc.c will ensure that log_timezone is set up (at
3123 * least with a minimal GMT value) before Log_line_prefix can become
3124 * nonempty or CSV/JSON mode can be selected.
3125 */
3127 /* leave room for milliseconds... */
3128 "%Y-%m-%d %H:%M:%S %Z",
3130
3131 /* 'paste' milliseconds into place... */
3132 sprintf(msbuf, ".%03d", (int) (saved_timeval.tv_usec / 1000));
3134
3135 return formatted_log_time;
3136}
3137
3138/*
3139 * reset_formatted_start_time -- reset the start timestamp
3140 */
3141void
3143{
3144 formatted_start_time[0] = '\0';
3145}
3146
3147/*
3148 * get_formatted_start_time -- compute and get the start timestamp.
3149 *
3150 * The timestamp is computed if not set yet. Note that the computed
3151 * timestamp is returned in a static buffer, not palloc()'d.
3152 */
3153char *
3155{
3157
3158 /* leave if already computed */
3159 if (formatted_start_time[0] != '\0')
3160 return formatted_start_time;
3161
3162 /*
3163 * Note: we expect that guc.c will ensure that log_timezone is set up (at
3164 * least with a minimal GMT value) before Log_line_prefix can become
3165 * nonempty or CSV/JSON mode can be selected.
3166 */
3168 "%Y-%m-%d %H:%M:%S %Z",
3170
3171 return formatted_start_time;
3172}
3173
3174/*
3175 * check_log_of_query -- check if a query can be logged
3176 */
3177bool
3179{
3180 /* log required? */
3182 return false;
3183
3184 /* query log wanted? */
3185 if (edata->hide_stmt)
3186 return false;
3187
3188 /* query string available? */
3189 if (debug_query_string == NULL)
3190 return false;
3191
3192 return true;
3193}
3194
3195/*
3196 * get_backend_type_for_log -- backend type for log entries
3197 *
3198 * Returns a pointer to a static buffer, not palloc()'d.
3199 */
3200const char *
3202{
3203 const char *backend_type_str;
3204
3205 if (MyProcPid == PostmasterPid)
3206 backend_type_str = "postmaster";
3207 else if (MyBackendType == B_BG_WORKER)
3208 {
3209 if (MyBgworkerEntry)
3211 else
3212 backend_type_str = "early bgworker";
3213 }
3214 else
3216
3217 return backend_type_str;
3218}
3219
3220/*
3221 * process_log_prefix_padding --- helper function for processing the format
3222 * string in log_line_prefix
3223 *
3224 * Note: This function returns NULL if it finds something which
3225 * it deems invalid in the format string.
3226 */
3227static const char *
3229{
3230 int paddingsign = 1;
3231 int padding = 0;
3232
3233 if (*p == '-')
3234 {
3235 p++;
3236
3237 if (*p == '\0') /* Did the buf end in %- ? */
3238 return NULL;
3239 paddingsign = -1;
3240 }
3241
3242 /* generate an int version of the numerical string */
3243 while (*p >= '0' && *p <= '9')
3244 padding = padding * 10 + (*p++ - '0');
3245
3246 /* format is invalid if it ends with the padding number */
3247 if (*p == '\0')
3248 return NULL;
3249
3250 padding *= paddingsign;
3251 *ppadding = padding;
3252 return p;
3253}
3254
3255/*
3256 * Format log status information using Log_line_prefix.
3257 */
3258static void
3263
3264/*
3265 * Format log status info; append to the provided buffer.
3266 */
3267void
3269{
3270 /* static counter for line numbers */
3271 static long log_line_number = 0;
3272
3273 /* has counter been reset in current process? */
3274 static int log_my_pid = 0;
3275 int padding;
3276 const char *p;
3277
3278 /*
3279 * This is one of the few places where we'd rather not inherit a static
3280 * variable's value from the postmaster. But since we will, reset it when
3281 * MyProcPid changes. MyStartTime also changes when MyProcPid does, so
3282 * reset the formatted start timestamp too.
3283 */
3284 if (log_my_pid != MyProcPid)
3285 {
3286 log_line_number = 0;
3289 }
3291
3292 if (format == NULL)
3293 return; /* in case guc hasn't run yet */
3294
3295 for (p = format; *p != '\0'; p++)
3296 {
3297 if (*p != '%')
3298 {
3299 /* literal char, just copy */
3301 continue;
3302 }
3303
3304 /* must be a '%', so skip to the next char */
3305 p++;
3306 if (*p == '\0')
3307 break; /* format error - ignore it */
3308 else if (*p == '%')
3309 {
3310 /* string contains %% */
3312 continue;
3313 }
3314
3315
3316 /*
3317 * Process any formatting which may exist after the '%'. Note that
3318 * process_log_prefix_padding moves p past the padding number if it
3319 * exists.
3320 *
3321 * Note: Since only '-', '0' to '9' are valid formatting characters we
3322 * can do a quick check here to pre-check for formatting. If the char
3323 * is not formatting then we can skip a useless function call.
3324 *
3325 * Further note: At least on some platforms, passing %*s rather than
3326 * %s to appendStringInfo() is substantially slower, so many of the
3327 * cases below avoid doing that unless non-zero padding is in fact
3328 * specified.
3329 */
3330 if (*p > '9')
3331 padding = 0;
3332 else if ((p = process_log_prefix_padding(p, &padding)) == NULL)
3333 break;
3334
3335 /* process the option */
3336 switch (*p)
3337 {
3338 case 'a':
3339 if (MyProcPort)
3340 {
3341 const char *appname = application_name;
3342
3343 if (appname == NULL || *appname == '\0')
3344 appname = _("[unknown]");
3345 if (padding != 0)
3346 appendStringInfo(buf, "%*s", padding, appname);
3347 else
3348 appendStringInfoString(buf, appname);
3349 }
3350 else if (padding != 0)
3352 padding > 0 ? padding : -padding);
3353
3354 break;
3355 case 'b':
3356 {
3358
3359 if (padding != 0)
3360 appendStringInfo(buf, "%*s", padding, backend_type_str);
3361 else
3363 break;
3364 }
3365 case 'u':
3366 if (MyProcPort)
3367 {
3368 const char *username = MyProcPort->user_name;
3369
3370 if (username == NULL || *username == '\0')
3371 username = _("[unknown]");
3372 if (padding != 0)
3373 appendStringInfo(buf, "%*s", padding, username);
3374 else
3376 }
3377 else if (padding != 0)
3379 padding > 0 ? padding : -padding);
3380 break;
3381 case 'd':
3382 if (MyProcPort)
3383 {
3384 const char *dbname = MyProcPort->database_name;
3385
3386 if (dbname == NULL || *dbname == '\0')
3387 dbname = _("[unknown]");
3388 if (padding != 0)
3389 appendStringInfo(buf, "%*s", padding, dbname);
3390 else
3392 }
3393 else if (padding != 0)
3395 padding > 0 ? padding : -padding);
3396 break;
3397 case 'c':
3398 if (padding != 0)
3399 {
3400 char strfbuf[128];
3401
3402 snprintf(strfbuf, sizeof(strfbuf) - 1, "%" PRIx64 ".%x",
3404 appendStringInfo(buf, "%*s", padding, strfbuf);
3405 }
3406 else
3408 break;
3409 case 'p':
3410 if (padding != 0)
3411 appendStringInfo(buf, "%*d", padding, MyProcPid);
3412 else
3414 break;
3415
3416 case 'P':
3417 if (MyProc)
3418 {
3419 PGPROC *leader = MyProc->lockGroupLeader;
3420
3421 /*
3422 * Show the leader only for active parallel workers. This
3423 * leaves out the leader of a parallel group.
3424 */
3425 if (leader == NULL || leader->pid == MyProcPid)
3427 padding > 0 ? padding : -padding);
3428 else if (padding != 0)
3429 appendStringInfo(buf, "%*d", padding, leader->pid);
3430 else
3431 appendStringInfo(buf, "%d", leader->pid);
3432 }
3433 else if (padding != 0)
3435 padding > 0 ? padding : -padding);
3436 break;
3437
3438 case 'l':
3439 if (padding != 0)
3440 appendStringInfo(buf, "%*ld", padding, log_line_number);
3441 else
3443 break;
3444 case 'm':
3445 /* force a log timestamp reset */
3446 formatted_log_time[0] = '\0';
3448
3449 if (padding != 0)
3450 appendStringInfo(buf, "%*s", padding, formatted_log_time);
3451 else
3453 break;
3454 case 't':
3455 {
3457 char strfbuf[128];
3458
3459 pg_strftime(strfbuf, sizeof(strfbuf),
3460 "%Y-%m-%d %H:%M:%S %Z",
3462 if (padding != 0)
3463 appendStringInfo(buf, "%*s", padding, strfbuf);
3464 else
3466 }
3467 break;
3468 case 'n':
3469 {
3470 char strfbuf[128];
3471
3472 if (!saved_timeval_set)
3473 {
3475 saved_timeval_set = true;
3476 }
3477
3478 snprintf(strfbuf, sizeof(strfbuf), "%ld.%03d",
3479 (long) saved_timeval.tv_sec,
3480 (int) (saved_timeval.tv_usec / 1000));
3481
3482 if (padding != 0)
3483 appendStringInfo(buf, "%*s", padding, strfbuf);
3484 else
3486 }
3487 break;
3488 case 's':
3489 {
3491
3492 if (padding != 0)
3493 appendStringInfo(buf, "%*s", padding, start_time);
3494 else
3496 }
3497 break;
3498 case 'i':
3499 if (MyProcPort)
3500 {
3501 const char *psdisp;
3502 int displen;
3503
3505 if (padding != 0)
3506 appendStringInfo(buf, "%*s", padding, psdisp);
3507 else
3509 }
3510 else if (padding != 0)
3512 padding > 0 ? padding : -padding);
3513 break;
3514 case 'L':
3515 {
3516 const char *local_host;
3517
3518 if (MyProcPort)
3519 {
3520 if (MyProcPort->local_host[0] == '\0')
3521 {
3522 /*
3523 * First time through: cache the lookup, since it
3524 * might not have trivial cost.
3525 */
3529 sizeof(MyProcPort->local_host),
3530 NULL, 0,
3532 }
3533 local_host = MyProcPort->local_host;
3534 }
3535 else
3536 {
3537 /* Background process, or connection not yet made */
3538 local_host = "[none]";
3539 }
3540 if (padding != 0)
3541 appendStringInfo(buf, "%*s", padding, local_host);
3542 else
3543 appendStringInfoString(buf, local_host);
3544 }
3545 break;
3546 case 'r':
3548 {
3549 if (padding != 0)
3550 {
3551 if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
3552 {
3553 /*
3554 * This option is slightly special as the port
3555 * number may be appended onto the end. Here we
3556 * need to build 1 string which contains the
3557 * remote_host and optionally the remote_port (if
3558 * set) so we can properly align the string.
3559 */
3560
3561 char *hostport;
3562
3564 appendStringInfo(buf, "%*s", padding, hostport);
3565 pfree(hostport);
3566 }
3567 else
3568 appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
3569 }
3570 else
3571 {
3572 /* padding is 0, so we don't need a temp buffer */
3574 if (MyProcPort->remote_port &&
3575 MyProcPort->remote_port[0] != '\0')
3576 appendStringInfo(buf, "(%s)",
3578 }
3579 }
3580 else if (padding != 0)
3582 padding > 0 ? padding : -padding);
3583 break;
3584 case 'h':
3586 {
3587 if (padding != 0)
3588 appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
3589 else
3591 }
3592 else if (padding != 0)
3594 padding > 0 ? padding : -padding);
3595 break;
3596 case 'q':
3597 /* in postmaster and friends, stop if %q is seen */
3598 /* in a backend, just ignore */
3599 if (MyProcPort == NULL)
3600 return;
3601 break;
3602 case 'v':
3603 /* keep VXID format in sync with lockfuncs.c */
3605 {
3606 if (padding != 0)
3607 {
3608 char strfbuf[128];
3609
3610 snprintf(strfbuf, sizeof(strfbuf) - 1, "%d/%u",
3612 appendStringInfo(buf, "%*s", padding, strfbuf);
3613 }
3614 else
3616 }
3617 else if (padding != 0)
3619 padding > 0 ? padding : -padding);
3620 break;
3621 case 'x':
3622 if (padding != 0)
3623 appendStringInfo(buf, "%*u", padding, GetTopTransactionIdIfAny());
3624 else
3626 break;
3627 case 'e':
3628 if (padding != 0)
3629 appendStringInfo(buf, "%*s", padding, unpack_sql_state(edata->sqlerrcode));
3630 else
3632 break;
3633 case 'Q':
3634 if (padding != 0)
3635 appendStringInfo(buf, "%*" PRId64, padding,
3637 else
3640 break;
3641 default:
3642 /* format error - ignore it */
3643 break;
3644 }
3645 }
3646}
3647
3648/*
3649 * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
3650 * static buffer.
3651 */
3652char *
3654{
3655 static char buf[12];
3656 int i;
3657
3658 for (i = 0; i < 5; i++)
3659 {
3661 sql_state >>= 6;
3662 }
3663
3664 buf[i] = '\0';
3665 return buf;
3666}
3667
3668
3669/*
3670 * Write error report to server's log
3671 */
3672static void
3674{
3676 bool fallback_to_stderr = false;
3677
3679
3681 appendStringInfo(&buf, "%s: ", _(error_severity(edata->elevel)));
3682
3684 appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
3685
3686 if (edata->message)
3687 append_with_tabs(&buf, edata->message);
3688 else
3689 append_with_tabs(&buf, _("missing error text"));
3690
3691 if (edata->cursorpos > 0)
3692 appendStringInfo(&buf, _(" at character %d"),
3693 edata->cursorpos);
3694 else if (edata->internalpos > 0)
3695 appendStringInfo(&buf, _(" at character %d"),
3696 edata->internalpos);
3697
3698 appendStringInfoChar(&buf, '\n');
3699
3701 {
3702 if (edata->detail_log)
3703 {
3705 appendStringInfoString(&buf, _("DETAIL: "));
3706 append_with_tabs(&buf, edata->detail_log);
3707 appendStringInfoChar(&buf, '\n');
3708 }
3709 else if (edata->detail)
3710 {
3712 appendStringInfoString(&buf, _("DETAIL: "));
3713 append_with_tabs(&buf, edata->detail);
3714 appendStringInfoChar(&buf, '\n');
3715 }
3716 if (edata->hint)
3717 {
3719 appendStringInfoString(&buf, _("HINT: "));
3720 append_with_tabs(&buf, edata->hint);
3721 appendStringInfoChar(&buf, '\n');
3722 }
3723 if (edata->internalquery)
3724 {
3726 appendStringInfoString(&buf, _("QUERY: "));
3727 append_with_tabs(&buf, edata->internalquery);
3728 appendStringInfoChar(&buf, '\n');
3729 }
3730 if (edata->context && !edata->hide_ctx)
3731 {
3733 appendStringInfoString(&buf, _("CONTEXT: "));
3734 append_with_tabs(&buf, edata->context);
3735 appendStringInfoChar(&buf, '\n');
3736 }
3738 {
3739 /* assume no newlines in funcname or filename... */
3740 if (edata->funcname && edata->filename)
3741 {
3743 appendStringInfo(&buf, _("LOCATION: %s, %s:%d\n"),
3744 edata->funcname, edata->filename,
3745 edata->lineno);
3746 }
3747 else if (edata->filename)
3748 {
3750 appendStringInfo(&buf, _("LOCATION: %s:%d\n"),
3751 edata->filename, edata->lineno);
3752 }
3753 }
3754 if (edata->backtrace)
3755 {
3757 appendStringInfoString(&buf, _("BACKTRACE: "));
3758 append_with_tabs(&buf, edata->backtrace);
3759 appendStringInfoChar(&buf, '\n');
3760 }
3761 }
3762
3763 /*
3764 * If the user wants the query that generated this error logged, do it.
3765 */
3767 {
3769 appendStringInfoString(&buf, _("STATEMENT: "));
3771 appendStringInfoChar(&buf, '\n');
3772 }
3773
3774#ifdef HAVE_SYSLOG
3775 /* Write to syslog, if enabled */
3777 {
3778 int syslog_level;
3779
3780 switch (edata->elevel)
3781 {
3782 case DEBUG5:
3783 case DEBUG4:
3784 case DEBUG3:
3785 case DEBUG2:
3786 case DEBUG1:
3788 break;
3789 case LOG:
3790 case LOG_SERVER_ONLY:
3791 case INFO:
3793 break;
3794 case NOTICE:
3795 case WARNING:
3798 break;
3799 case ERROR:
3801 break;
3802 case FATAL:
3804 break;
3805 case PANIC:
3806 default:
3808 break;
3809 }
3810
3812 }
3813#endif /* HAVE_SYSLOG */
3814
3815#ifdef WIN32
3816 /* Write to eventlog, if enabled */
3818 {
3819 write_eventlog(edata->elevel, buf.data, buf.len);
3820 }
3821#endif /* WIN32 */
3822
3823 /* Write to csvlog, if enabled */
3825 {
3826 /*
3827 * Send CSV data if it's safe to do so (syslogger doesn't need the
3828 * pipe). If this is not possible, fallback to an entry written to
3829 * stderr.
3830 */
3833 else
3834 fallback_to_stderr = true;
3835 }
3836
3837 /* Write to JSON log, if enabled */
3839 {
3840 /*
3841 * Send JSON data if it's safe to do so (syslogger doesn't need the
3842 * pipe). If this is not possible, fallback to an entry written to
3843 * stderr.
3844 */
3846 {
3848 }
3849 else
3850 fallback_to_stderr = true;
3851 }
3852
3853 /*
3854 * Write to stderr, if enabled or if required because of a previous
3855 * limitation.
3856 */
3860 {
3861 /*
3862 * Use the chunking protocol if we know the syslogger should be
3863 * catching stderr output, and we are not ourselves the syslogger.
3864 * Otherwise, just do a vanilla write to stderr.
3865 */
3868#ifdef WIN32
3869
3870 /*
3871 * In a win32 service environment, there is no usable stderr. Capture
3872 * anything going there and write it to the eventlog instead.
3873 *
3874 * If stderr redirection is active, it was OK to write to stderr above
3875 * because that's really a pipe to the syslogger process.
3876 */
3877 else if (pgwin32_is_service())
3878 write_eventlog(edata->elevel, buf.data, buf.len);
3879#endif
3880 else
3881 write_console(buf.data, buf.len);
3882 }
3883
3884 /* If in the syslogger process, try to write messages direct to file */
3885 if (MyBackendType == B_LOGGER)
3887
3888 /* No more need of the message formatted for stderr */
3889 pfree(buf.data);
3890}
3891
3892/*
3893 * Send data to the syslogger using the chunked protocol
3894 *
3895 * Note: when there are multiple backends writing into the syslogger pipe,
3896 * it's critical that each write go into the pipe indivisibly, and not
3897 * get interleaved with data from other processes. Fortunately, the POSIX
3898 * spec requires that writes to pipes be atomic so long as they are not
3899 * more than PIPE_BUF bytes long. So we divide long messages into chunks
3900 * that are no more than that length, and send one chunk per write() call.
3901 * The collector process knows how to reassemble the chunks.
3902 *
3903 * Because of the atomic write requirement, there are only two possible
3904 * results from write() here: -1 for failure, or the requested number of
3905 * bytes. There is not really anything we can do about a failure; retry would
3906 * probably be an infinite loop, and we can't even report the error usefully.
3907 * (There is noplace else we could send it!) So we might as well just ignore
3908 * the result from write(). However, on some platforms you get a compiler
3909 * warning from ignoring write()'s result, so do a little dance with casting
3910 * rc to void to shut up the compiler.
3911 */
3912void
3913write_pipe_chunks(char *data, int len, int dest)
3914{
3916 int fd = fileno(stderr);
3917 int rc;
3918
3919 Assert(len > 0);
3920
3921 p.proto.nuls[0] = p.proto.nuls[1] = '\0';
3922 p.proto.pid = MyProcPid;
3923 p.proto.flags = 0;
3924 if (dest == LOG_DESTINATION_STDERR)
3926 else if (dest == LOG_DESTINATION_CSVLOG)
3928 else if (dest == LOG_DESTINATION_JSONLOG)
3930
3931 /* write all but the last chunk */
3932 while (len > PIPE_MAX_PAYLOAD)
3933 {
3934 /* no need to set PIPE_PROTO_IS_LAST yet */
3938 (void) rc;
3941 }
3942
3943 /* write the last chunk */
3945 p.proto.len = len;
3946 memcpy(p.proto.data, data, len);
3947 rc = write(fd, &p, PIPE_HEADER_SIZE + len);
3948 (void) rc;
3949}
3950
3951
3952/*
3953 * Append a text string to the error report being built for the client.
3954 *
3955 * This is ordinarily identical to pq_sendstring(), but if we are in
3956 * error recursion trouble we skip encoding conversion, because of the
3957 * possibility that the problem is a failure in the encoding conversion
3958 * subsystem itself. Code elsewhere should ensure that the passed-in
3959 * strings will be plain 7-bit ASCII, and thus not in need of conversion,
3960 * in such cases. (In particular, we disable localization of error messages
3961 * to help ensure that's true.)
3962 */
3963static void
3965{
3968 else
3970}
3971
3972/*
3973 * Write error report to client
3974 */
3975static void
3977{
3979
3980 /*
3981 * We no longer support pre-3.0 FE/BE protocol, except here. If a client
3982 * tries to connect using an older protocol version, it's nice to send the
3983 * "protocol version not supported" error in a format the client
3984 * understands. If protocol hasn't been set yet, early in backend
3985 * startup, assume modern protocol.
3986 */
3988 {
3989 /* New style with separate fields */
3990 const char *sev;
3991 char tbuf[12];
3992
3993 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
3994 if (edata->elevel < ERROR)
3996 else
3998
3999 sev = error_severity(edata->elevel);
4004
4007
4008 /* M field is required per protocol, so always send something */
4010 if (edata->message)
4011 err_sendstring(&msgbuf, edata->message);
4012 else
4013 err_sendstring(&msgbuf, _("missing error text"));
4014
4015 if (edata->detail)
4016 {
4018 err_sendstring(&msgbuf, edata->detail);
4019 }
4020
4021 /* detail_log is intentionally not used here */
4022
4023 if (edata->hint)
4024 {
4026 err_sendstring(&msgbuf, edata->hint);
4027 }
4028
4029 if (edata->context)
4030 {
4032 err_sendstring(&msgbuf, edata->context);
4033 }
4034
4035 if (edata->schema_name)
4036 {
4038 err_sendstring(&msgbuf, edata->schema_name);
4039 }
4040
4041 if (edata->table_name)
4042 {
4044 err_sendstring(&msgbuf, edata->table_name);
4045 }
4046
4047 if (edata->column_name)
4048 {
4050 err_sendstring(&msgbuf, edata->column_name);
4051 }
4052
4053 if (edata->datatype_name)
4054 {
4056 err_sendstring(&msgbuf, edata->datatype_name);
4057 }
4058
4059 if (edata->constraint_name)
4060 {
4062 err_sendstring(&msgbuf, edata->constraint_name);
4063 }
4064
4065 if (edata->cursorpos > 0)
4066 {
4067 snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
4070 }
4071
4072 if (edata->internalpos > 0)
4073 {
4074 snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
4077 }
4078
4079 if (edata->internalquery)
4080 {
4082 err_sendstring(&msgbuf, edata->internalquery);
4083 }
4084
4085 if (edata->filename)
4086 {
4088 err_sendstring(&msgbuf, edata->filename);
4089 }
4090
4091 if (edata->lineno > 0)
4092 {
4093 snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
4096 }
4097
4098 if (edata->funcname)
4099 {
4101 err_sendstring(&msgbuf, edata->funcname);
4102 }
4103
4104 pq_sendbyte(&msgbuf, '\0'); /* terminator */
4105
4107 }
4108 else
4109 {
4110 /* Old style --- gin up a backwards-compatible message */
4112
4114
4115 appendStringInfo(&buf, "%s: ", _(error_severity(edata->elevel)));
4116
4117 if (edata->message)
4118 appendStringInfoString(&buf, edata->message);
4119 else
4120 appendStringInfoString(&buf, _("missing error text"));
4121
4122 appendStringInfoChar(&buf, '\n');
4123
4124 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
4125 pq_putmessage_v2((edata->elevel < ERROR) ? 'N' : 'E', buf.data, buf.len + 1);
4126
4127 pfree(buf.data);
4128 }
4129
4130 /*
4131 * This flush is normally not necessary, since postgres.c will flush out
4132 * waiting data when control returns to the main loop. But it seems best
4133 * to leave it here, so that the client has some clue what happened if the
4134 * backend dies before getting back to the main loop ... error/notice
4135 * messages should not be a performance-critical path anyway, so an extra
4136 * flush won't hurt much ...
4137 */
4138 pq_flush();
4139}
4140
4141
4142/*
4143 * Support routines for formatting error messages.
4144 */
4145
4146
4147/*
4148 * error_severity --- get string representing elevel
4149 *
4150 * The string is not localized here, but we mark the strings for translation
4151 * so that callers can invoke _() on the result.
4152 */
4153const char *
4155{
4156 const char *prefix;
4157
4158 switch (elevel)
4159 {
4160 case DEBUG1:
4161 case DEBUG2:
4162 case DEBUG3:
4163 case DEBUG4:
4164 case DEBUG5:
4165 prefix = gettext_noop("DEBUG");
4166 break;
4167 case LOG:
4168 case LOG_SERVER_ONLY:
4169 prefix = gettext_noop("LOG");
4170 break;
4171 case INFO:
4172 prefix = gettext_noop("INFO");
4173 break;
4174 case NOTICE:
4175 prefix = gettext_noop("NOTICE");
4176 break;
4177 case WARNING:
4179 prefix = gettext_noop("WARNING");
4180 break;
4181 case ERROR:
4182 prefix = gettext_noop("ERROR");
4183 break;
4184 case FATAL:
4185 prefix = gettext_noop("FATAL");
4186 break;
4187 case PANIC:
4188 prefix = gettext_noop("PANIC");
4189 break;
4190 default:
4191 prefix = "???";
4192 break;
4193 }
4194
4195 return prefix;
4196}
4197
4198
4199/*
4200 * append_with_tabs
4201 *
4202 * Append the string to the StringInfo buffer, inserting a tab after any
4203 * newline.
4204 */
4205static void
4207{
4208 char ch;
4209
4210 while ((ch = *str++) != '\0')
4211 {
4213 if (ch == '\n')
4215 }
4216}
4217
4218
4219/*
4220 * Write errors to stderr (or by equal means when stderr is
4221 * not available). Used before ereport/elog can be used
4222 * safely (memory context, GUC load etc)
4223 */
4224void
4225write_stderr(const char *fmt,...)
4226{
4227 va_list ap;
4228
4229 va_start(ap, fmt);
4231 va_end(ap);
4232}
4233
4234
4235/*
4236 * Write errors to stderr (or by equal means when stderr is
4237 * not available) - va_list version
4238 */
4239void
4241{
4242#ifdef WIN32
4243 char errbuf[2048]; /* Arbitrary size? */
4244#endif
4245
4246 fmt = _(fmt);
4247#ifndef WIN32
4248 /* On Unix, we just fprintf to stderr */
4249 vfprintf(stderr, fmt, ap);
4250 fflush(stderr);
4251#else
4252 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
4253
4254 /*
4255 * On Win32, we print to stderr if running on a console, or write to
4256 * eventlog if running as a service
4257 */
4258 if (pgwin32_is_service()) /* Running as a service */
4259 {
4260 write_eventlog(ERROR, errbuf, strlen(errbuf));
4261 }
4262 else
4263 {
4264 /* Not running as service, write to stderr */
4265 write_console(errbuf, strlen(errbuf));
4266 fflush(stderr);
4267 }
4268#endif
4269}
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:253
#define pg_noinline
Definition c.h:307
#define Min(x, y)
Definition c.h:1040
#define pg_attribute_cold
Definition c.h:332
#define gettext_noop(x)
Definition c.h:1234
#define Max(x, y)
Definition c.h:1034
#define Assert(condition)
Definition c.h:906
#define PG_TEXTDOMAIN(domain)
Definition c.h:1252
#define gettext(x)
Definition c.h:1217
#define pg_unreachable()
Definition c.h:353
#define unlikely(x)
Definition c.h:424
#define lengthof(array)
Definition c.h:836
#define MemSet(start, val, len)
Definition c.h:1056
void write_csvlog(ErrorData *edata)
Definition csvlog.c:63
@ DestRemote
Definition dest.h:89
@ DestDebug
Definition dest.h:88
@ DestNone
Definition dest.h:87
Datum arg
Definition elog.c:1322
void assign_syslog_facility(int newval, void *extra)
Definition elog.c:2782
static bool should_output_to_client(int elevel)
Definition elog.c:256
void assign_syslog_ident(const char *newval, void *extra)
Definition elog.c:2750
int errcode_for_socket_access(void)
Definition elog.c:976
bool errsave_start(struct Node *context, const char *domain)
Definition elog.c:650
static void log_line_prefix(StringInfo buf, ErrorData *edata)
Definition elog.c:3259
static const char * process_log_prefix_padding(const char *p, int *ppadding)
Definition elog.c:3228
void errsave_finish(struct Node *context, const char *filename, int lineno, const char *funcname)
Definition elog.c:702
static char formatted_log_time[FORMATTED_TS_LEN]
Definition elog.c:170
static char formatted_start_time[FORMATTED_TS_LEN]
Definition elog.c:169
static void send_message_to_frontend(ErrorData *edata)
Definition elog.c:3976
bool check_log_of_query(ErrorData *edata)
Definition elog.c:3178
static void append_with_tabs(StringInfo buf, const char *str)
Definition elog.c:4206
char * format_elog_string(const char *fmt,...)
Definition elog.c:1849
bool errstart(int elevel, const char *domain)
Definition elog.c:354
void EmitErrorReport(void)
Definition elog.c:1882
bool syslog_split_messages
Definition elog.c:118
static void FreeErrorDataContents(ErrorData *edata)
Definition elog.c:2025
static int errordata_stack_depth
Definition elog.c:157
char * GetErrorContextStack(void)
Definition elog.c:2254
void DebugFileOpen(void)
Definition elog.c:2306
static void err_sendstring(StringInfo buf, const char *str)
Definition elog.c:3964
void FreeErrorData(ErrorData *edata)
Definition elog.c:2013
void assign_backtrace_functions(const char *newval, void *extra)
Definition elog.c:2668
const char * error_severity(int elevel)
Definition elog.c:4154
void assign_log_min_messages(const char *newval, void *extra)
Definition elog.c:2590
static ErrorData * get_error_stack_entry(void)
Definition elog.c:772
#define FORMATTED_TS_LEN
Definition elog.c:168
static bool saved_timeval_set
Definition elog.c:166
int errcode_for_file_access(void)
Definition elog.c:897
static char * backtrace_function_list
Definition elog.c:121
int Log_error_verbosity
Definition elog.c:113
void pg_re_throw(void)
Definition elog.c:2199
bool check_backtrace_functions(char **newval, void **extra, GucSource source)
Definition elog.c:2607
void pre_format_elog_string(int errnumber, const char *domain)
Definition elog.c:1840
static int recursion_depth
Definition elog.c:159
ErrorContextCallback * error_context_stack
Definition elog.c:99
int errbacktrace(void)
Definition elog.c:1115
static int log_min_messages_cmp(const ListCell *a, const ListCell *b)
Definition elog.c:2573
static struct timeval saved_timeval
Definition elog.c:165
int Log_destination
Definition elog.c:115
void ReThrowError(ErrorData *edata)
Definition elog.c:2149
static void set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str)
char * get_formatted_start_time(void)
Definition elog.c:3154
static bool matches_backtrace_functions(const char *funcname)
Definition elog.c:846
ErrorData * CopyErrorData(void)
Definition elog.c:1941
bool check_log_destination(char **newval, void **extra, GucSource source)
Definition elog.c:2677
void FlushErrorState(void)
Definition elog.c:2062
bool check_log_min_messages(char **newval, void **extra, GucSource source)
Definition elog.c:2362
static bool is_log_level_output(int elevel, int log_min_level)
Definition elog.c:213
void ThrowErrorData(ErrorData *edata)
Definition elog.c:2090
pg_attribute_unused() static void backtrace_cleanup(int code
bool message_level_is_interesting(int elevel)
Definition elog.c:284
void write_pipe_chunks(char *data, int len, int dest)
Definition elog.c:3913
emit_log_hook_type emit_log_hook
Definition elog.c:110
bool syslog_sequence_numbers
Definition elog.c:117
static void send_message_to_server_log(ErrorData *edata)
Definition elog.c:3673
char * Log_destination_string
Definition elog.c:116
static void write_console(const char *line, int len)
Definition elog.c:3026
#define EVALUATE_MESSAGE(domain, targetfield, appendval, translateit)
Definition elog.c:1012
static void set_stack_entry_location(ErrorData *edata, const char *filename, int lineno, const char *funcname)
Definition elog.c:816
pg_attribute_cold bool errstart_cold(int elevel, const char *domain)
Definition elog.c:338
#define CHECK_STACK_DEPTH()
Definition elog.c:174
static void set_stack_entry_domain(ErrorData *edata, const char *domain)
Definition elog.c:799
#define EVALUATE_MESSAGE_PLURAL(domain, targetfield, appendval)
Definition elog.c:1048
static bool should_output_to_server(int elevel)
Definition elog.c:247
const char * get_backend_type_for_log(void)
Definition elog.c:3201
int errcode(int sqlerrcode)
Definition elog.c:874
static void backtrace_cleanup(int code, Datum arg)
int errmsg(const char *fmt,...)
Definition elog.c:1093
void vwrite_stderr(const char *fmt, va_list ap)
Definition elog.c:4240
void log_status_format(StringInfo buf, const char *format, ErrorData *edata)
Definition elog.c:3268
char * get_formatted_log_time(void)
Definition elog.c:3104
bool in_error_recursion_trouble(void)
Definition elog.c:305
void errfinish(const char *filename, int lineno, const char *funcname)
Definition elog.c:485
static const char * err_gettext(const char *str) pg_attribute_format_arg(1)
Definition elog.c:317
#define ERRORDATA_STACK_SIZE
Definition elog.c:153
char * unpack_sql_state(int sql_state)
Definition elog.c:3653
static pg_noinline void set_backtrace(ErrorData *edata, int num_skip)
Definition elog.c:1146
char * Log_line_prefix
Definition elog.c:114
#define _(x)
Definition elog.c:95
void reset_formatted_start_time(void)
Definition elog.c:3142
static ErrorData errordata[ERRORDATA_STACK_SIZE]
Definition elog.c:155
sigjmp_buf * PG_exception_stack
Definition elog.c:101
static const char * save_format_domain
Definition elog.c:1837
void assign_log_destination(const char *newval, void *extra)
Definition elog.c:2741
@ PGERROR_VERBOSE
Definition elog.h:474
@ PGERROR_DEFAULT
Definition elog.h:473
int getinternalerrposition(void)
int int errhidestmt(bool hide_stmt)
#define LOG
Definition elog.h:31
void(* emit_log_hook_type)(ErrorData *edata)
Definition elog.h:464
int err_generic_string(int field, const char *str)
#define PG_RE_THROW()
Definition elog.h:405
int int errdetail_internal(const char *fmt,...) pg_attribute_printf(1
int errhint(const char *fmt,...) pg_attribute_printf(1
int internalerrquery(const char *query)
int int int errhint_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...) pg_attribute_printf(1
#define DEBUG3
Definition elog.h:28
int internalerrposition(int cursorpos)
int geterrcode(void)
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define LOG_SERVER_ONLY
Definition elog.h:32
#define WARNING_CLIENT_ONLY
Definition elog.h:38
#define FATAL
Definition elog.h:41
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define WARNING
Definition elog.h:36
int int int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...) pg_attribute_printf(1
#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
int errcontext_msg(const char *fmt,...) pg_attribute_printf(1
#define ERROR
Definition elog.h:39
int errhidecontext(bool hide_ctx)
int int int errdetail_log(const char *fmt,...) pg_attribute_printf(1
int geterrposition(void)
#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
int errposition(int cursorpos)
#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
int int int int errdetail_log_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...) pg_attribute_printf(1
#define LOG_DESTINATION_CSVLOG
Definition elog.h:488
int set_errcontext_domain(const char *domain)
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...) pg_attribute_printf(1
#define DEBUG4
Definition elog.h:27
int int errhint_internal(const char *fmt,...) pg_attribute_printf(1
#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_free(void *ptr)
Definition guc.c:687
void * guc_malloc(int elevel, size_t size)
Definition guc.c:636
#define newval
char * guc_strdup(int elevel, const char *src)
Definition guc.c:675
#define GUC_check_errdetail
Definition guc.h:506
GucSource
Definition guc.h:112
char * event_source
Definition guc_tables.c:536
int client_min_messages
Definition guc_tables.c:550
int log_min_messages[]
Definition guc_tables.c:663
int log_min_error_statement
Definition guc_tables.c:549
static int syslog_facility
Definition guc_tables.c:614
char * application_name
Definition guc_tables.c:570
const struct config_enum_entry server_message_level_options[]
Definition guc_tables.c:151
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
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition ipc.c:316
bool proc_exit_inprogress
Definition ipc.c:41
void proc_exit(int code)
Definition ipc.c:105
int b
Definition isn.c:74
int a
Definition isn.c:73
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:49
void list_sort(List *list, list_sort_comparator cmp)
Definition list.c:1674
void list_free(List *list)
Definition list.c:1546
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition mbutils.c:1211
int GetMessageEncoding(void)
Definition mbutils.c:1436
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 BACKEND_NUM_TYPES
Definition miscadmin.h:377
#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:132
#define lfirst(lc)
Definition pg_list.h:172
#define foreach_current_index(var_or_cell)
Definition pg_list.h:403
#define foreach_ptr(type, var, lst)
Definition pg_list.h:469
size_t wchar2char(char *to, const wchar_t *from, size_t tolen, locale_t loc)
static rewind_source * source
Definition pg_rewind.c:89
static char buf[DEFAULT_XLOG_SEG_SIZE]
@ DISCONNECT_FATAL
Definition pgstat.h:63
@ DISCONNECT_NORMAL
Definition pgstat.h:61
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:93
const char * debug_query_string
Definition postgres.c:90
uint64_t Datum
Definition postgres.h:70
#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:1562
#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 initStringInfoExt(StringInfo str, int initsize)
Definition stringinfo.c:111
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:176
LocalTransactionId lxid
Definition proc.h:223
struct PGPROC::@133 vxid
ProcNumber procNumber
Definition proc.h:218
int pid
Definition proc.h:189
PGPROC * lockGroupLeader
Definition proc.h:290
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
Definition guc.h:174
const char * name
Definition guc.h:175
int val
Definition guc.h:176
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 SplitGUCList(char *rawstring, char separator, List **namelist)
Definition varlena.c:3023
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition varlena.c:2775
int pgwin32_is_service(void)
int gettimeofday(struct timeval *tp, void *tzp)
TransactionId GetTopTransactionIdIfAny(void)
Definition xact.c:442