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