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