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