Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

PostgreSQL Source Code git master
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 {
1133 for (int i = num_skip; i < nframes; i++)
1134 appendStringInfo(&errtrace, "\n%s", strfrms[i]);
1135 free(strfrms);
1136 }
1137 else
1138 appendStringInfoString(&errtrace,
1139 "insufficient memory for backtrace generation");
1140 }
1141#else
1142 appendStringInfoString(&errtrace,
1143 "backtrace generation is not supported by this installation");
1144#endif
1145
1146 edata->backtrace = errtrace.data;
1147}
1148
1149/*
1150 * errmsg_internal --- add a primary error message text to the current error
1151 *
1152 * This is exactly like errmsg() except that strings passed to errmsg_internal
1153 * are not translated, and are customarily left out of the
1154 * internationalization message dictionary. This should be used for "can't
1155 * happen" cases that are probably not worth spending translation effort on.
1156 * We also use this for certain cases where we *must* not try to translate
1157 * the message because the translation would fail and result in infinite
1158 * error recursion.
1159 */
1160int
1161errmsg_internal(const char *fmt,...)
1162{
1164 MemoryContext oldcontext;
1165
1168 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1169
1170 edata->message_id = fmt;
1171 EVALUATE_MESSAGE(edata->domain, message, false, false);
1172
1173 MemoryContextSwitchTo(oldcontext);
1175 return 0; /* return value does not matter */
1176}
1177
1178
1179/*
1180 * errmsg_plural --- add a primary error message text to the current error,
1181 * with support for pluralization of the message text
1182 */
1183int
1184errmsg_plural(const char *fmt_singular, const char *fmt_plural,
1185 unsigned long n,...)
1186{
1188 MemoryContext oldcontext;
1189
1192 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1193
1194 edata->message_id = fmt_singular;
1195 EVALUATE_MESSAGE_PLURAL(edata->domain, message, false);
1196
1197 MemoryContextSwitchTo(oldcontext);
1199 return 0; /* return value does not matter */
1200}
1201
1202
1203/*
1204 * errdetail --- add a detail error message text to the current error
1205 */
1206int
1207errdetail(const char *fmt,...)
1208{
1210 MemoryContext oldcontext;
1211
1214 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1215
1216 EVALUATE_MESSAGE(edata->domain, detail, false, true);
1217
1218 MemoryContextSwitchTo(oldcontext);
1220 return 0; /* return value does not matter */
1221}
1222
1223
1224/*
1225 * errdetail_internal --- add a detail error message text to the current error
1226 *
1227 * This is exactly like errdetail() except that strings passed to
1228 * errdetail_internal are not translated, and are customarily left out of the
1229 * internationalization message dictionary. This should be used for detail
1230 * messages that seem not worth translating for one reason or another
1231 * (typically, that they don't seem to be useful to average users).
1232 */
1233int
1234errdetail_internal(const char *fmt,...)
1235{
1237 MemoryContext oldcontext;
1238
1241 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1242
1243 EVALUATE_MESSAGE(edata->domain, detail, false, false);
1244
1245 MemoryContextSwitchTo(oldcontext);
1247 return 0; /* return value does not matter */
1248}
1249
1250
1251/*
1252 * errdetail_log --- add a detail_log error message text to the current error
1253 */
1254int
1255errdetail_log(const char *fmt,...)
1256{
1258 MemoryContext oldcontext;
1259
1262 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1263
1264 EVALUATE_MESSAGE(edata->domain, detail_log, false, true);
1265
1266 MemoryContextSwitchTo(oldcontext);
1268 return 0; /* return value does not matter */
1269}
1270
1271/*
1272 * errdetail_log_plural --- add a detail_log error message text to the current error
1273 * with support for pluralization of the message text
1274 */
1275int
1276errdetail_log_plural(const char *fmt_singular, const char *fmt_plural,
1277 unsigned long n,...)
1278{
1280 MemoryContext oldcontext;
1281
1284 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1285
1286 EVALUATE_MESSAGE_PLURAL(edata->domain, detail_log, false);
1287
1288 MemoryContextSwitchTo(oldcontext);
1290 return 0; /* return value does not matter */
1291}
1292
1293
1294/*
1295 * errdetail_plural --- add a detail error message text to the current error,
1296 * with support for pluralization of the message text
1297 */
1298int
1299errdetail_plural(const char *fmt_singular, const char *fmt_plural,
1300 unsigned long n,...)
1301{
1303 MemoryContext oldcontext;
1304
1307 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1308
1309 EVALUATE_MESSAGE_PLURAL(edata->domain, detail, false);
1310
1311 MemoryContextSwitchTo(oldcontext);
1313 return 0; /* return value does not matter */
1314}
1315
1316
1317/*
1318 * errhint --- add a hint error message text to the current error
1319 */
1320int
1321errhint(const char *fmt,...)
1322{
1324 MemoryContext oldcontext;
1325
1328 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1329
1330 EVALUATE_MESSAGE(edata->domain, hint, false, true);
1331
1332 MemoryContextSwitchTo(oldcontext);
1334 return 0; /* return value does not matter */
1335}
1336
1337/*
1338 * errhint_internal --- add a hint error message text to the current error
1339 *
1340 * Non-translated version of errhint(), see also errmsg_internal().
1341 */
1342int
1343errhint_internal(const char *fmt,...)
1344{
1346 MemoryContext oldcontext;
1347
1350 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1351
1352 EVALUATE_MESSAGE(edata->domain, hint, false, false);
1353
1354 MemoryContextSwitchTo(oldcontext);
1356 return 0; /* return value does not matter */
1357}
1358
1359/*
1360 * errhint_plural --- add a hint error message text to the current error,
1361 * with support for pluralization of the message text
1362 */
1363int
1364errhint_plural(const char *fmt_singular, const char *fmt_plural,
1365 unsigned long n,...)
1366{
1368 MemoryContext oldcontext;
1369
1372 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1373
1374 EVALUATE_MESSAGE_PLURAL(edata->domain, hint, false);
1375
1376 MemoryContextSwitchTo(oldcontext);
1378 return 0; /* return value does not matter */
1379}
1380
1381
1382/*
1383 * errcontext_msg --- add a context error message text to the current error
1384 *
1385 * Unlike other cases, multiple calls are allowed to build up a stack of
1386 * context information. We assume earlier calls represent more-closely-nested
1387 * states.
1388 */
1389int
1390errcontext_msg(const char *fmt,...)
1391{
1393 MemoryContext oldcontext;
1394
1397 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1398
1399 EVALUATE_MESSAGE(edata->context_domain, context, true, true);
1400
1401 MemoryContextSwitchTo(oldcontext);
1403 return 0; /* return value does not matter */
1404}
1405
1406/*
1407 * set_errcontext_domain --- set message domain to be used by errcontext()
1408 *
1409 * errcontext_msg() can be called from a different module than the original
1410 * ereport(), so we cannot use the message domain passed in errstart() to
1411 * translate it. Instead, each errcontext_msg() call should be preceded by
1412 * a set_errcontext_domain() call to specify the domain. This is usually
1413 * done transparently by the errcontext() macro.
1414 */
1415int
1416set_errcontext_domain(const char *domain)
1417{
1419
1420 /* we don't bother incrementing recursion_depth */
1422
1423 /* the default text domain is the backend's */
1424 edata->context_domain = domain ? domain : PG_TEXTDOMAIN("postgres");
1425
1426 return 0; /* return value does not matter */
1427}
1428
1429
1430/*
1431 * errhidestmt --- optionally suppress STATEMENT: field of log entry
1432 *
1433 * This should be called if the message text already includes the statement.
1434 */
1435int
1436errhidestmt(bool hide_stmt)
1437{
1439
1440 /* we don't bother incrementing recursion_depth */
1442
1443 edata->hide_stmt = hide_stmt;
1444
1445 return 0; /* return value does not matter */
1446}
1447
1448/*
1449 * errhidecontext --- optionally suppress CONTEXT: field of log entry
1450 *
1451 * This should only be used for verbose debugging messages where the repeated
1452 * inclusion of context would bloat the log volume too much.
1453 */
1454int
1455errhidecontext(bool hide_ctx)
1456{
1458
1459 /* we don't bother incrementing recursion_depth */
1461
1462 edata->hide_ctx = hide_ctx;
1463
1464 return 0; /* return value does not matter */
1465}
1466
1467/*
1468 * errposition --- add cursor position to the current error
1469 */
1470int
1471errposition(int cursorpos)
1472{
1474
1475 /* we don't bother incrementing recursion_depth */
1477
1478 edata->cursorpos = cursorpos;
1479
1480 return 0; /* return value does not matter */
1481}
1482
1483/*
1484 * internalerrposition --- add internal cursor position to the current error
1485 */
1486int
1488{
1490
1491 /* we don't bother incrementing recursion_depth */
1493
1494 edata->internalpos = cursorpos;
1495
1496 return 0; /* return value does not matter */
1497}
1498
1499/*
1500 * internalerrquery --- add internal query text to the current error
1501 *
1502 * Can also pass NULL to drop the internal query text entry. This case
1503 * is intended for use in error callback subroutines that are editorializing
1504 * on the layout of the error report.
1505 */
1506int
1507internalerrquery(const char *query)
1508{
1510
1511 /* we don't bother incrementing recursion_depth */
1513
1514 if (edata->internalquery)
1515 {
1516 pfree(edata->internalquery);
1517 edata->internalquery = NULL;
1518 }
1519
1520 if (query)
1521 edata->internalquery = MemoryContextStrdup(edata->assoc_context, query);
1522
1523 return 0; /* return value does not matter */
1524}
1525
1526/*
1527 * err_generic_string -- used to set individual ErrorData string fields
1528 * identified by PG_DIAG_xxx codes.
1529 *
1530 * This intentionally only supports fields that don't use localized strings,
1531 * so that there are no translation considerations.
1532 *
1533 * Most potential callers should not use this directly, but instead prefer
1534 * higher-level abstractions, such as errtablecol() (see relcache.c).
1535 */
1536int
1537err_generic_string(int field, const char *str)
1538{
1540
1541 /* we don't bother incrementing recursion_depth */
1543
1544 switch (field)
1545 {
1548 break;
1549 case PG_DIAG_TABLE_NAME:
1551 break;
1554 break;
1557 break;
1560 break;
1561 default:
1562 elog(ERROR, "unsupported ErrorData field id: %d", field);
1563 break;
1564 }
1565
1566 return 0; /* return value does not matter */
1567}
1568
1569/*
1570 * set_errdata_field --- set an ErrorData string field
1571 */
1572static void
1573set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str)
1574{
1575 Assert(*ptr == NULL);
1576 *ptr = MemoryContextStrdup(cxt, str);
1577}
1578
1579/*
1580 * geterrcode --- return the currently set SQLSTATE error code
1581 *
1582 * This is only intended for use in error callback subroutines, since there
1583 * is no other place outside elog.c where the concept is meaningful.
1584 */
1585int
1587{
1589
1590 /* we don't bother incrementing recursion_depth */
1592
1593 return edata->sqlerrcode;
1594}
1595
1596/*
1597 * geterrposition --- return the currently set error position (0 if none)
1598 *
1599 * This is only intended for use in error callback subroutines, since there
1600 * is no other place outside elog.c where the concept is meaningful.
1601 */
1602int
1604{
1606
1607 /* we don't bother incrementing recursion_depth */
1609
1610 return edata->cursorpos;
1611}
1612
1613/*
1614 * getinternalerrposition --- same for internal error position
1615 *
1616 * This is only intended for use in error callback subroutines, since there
1617 * is no other place outside elog.c where the concept is meaningful.
1618 */
1619int
1621{
1623
1624 /* we don't bother incrementing recursion_depth */
1626
1627 return edata->internalpos;
1628}
1629
1630
1631/*
1632 * Functions to allow construction of error message strings separately from
1633 * the ereport() call itself.
1634 *
1635 * The expected calling convention is
1636 *
1637 * pre_format_elog_string(errno, domain), var = format_elog_string(format,...)
1638 *
1639 * which can be hidden behind a macro such as GUC_check_errdetail(). We
1640 * assume that any functions called in the arguments of format_elog_string()
1641 * cannot result in re-entrant use of these functions --- otherwise the wrong
1642 * text domain might be used, or the wrong errno substituted for %m. This is
1643 * okay for the current usage with GUC check hooks, but might need further
1644 * effort someday.
1645 *
1646 * The result of format_elog_string() is stored in ErrorContext, and will
1647 * therefore survive until FlushErrorState() is called.
1648 */
1650static const char *save_format_domain;
1651
1652void
1653pre_format_elog_string(int errnumber, const char *domain)
1654{
1655 /* Save errno before evaluation of argument functions can change it */
1656 save_format_errnumber = errnumber;
1657 /* Save caller's text domain */
1658 save_format_domain = domain;
1659}
1660
1661char *
1662format_elog_string(const char *fmt,...)
1663{
1664 ErrorData errdata;
1665 ErrorData *edata;
1666 MemoryContext oldcontext;
1667
1668 /* Initialize a mostly-dummy error frame */
1669 edata = &errdata;
1670 MemSet(edata, 0, sizeof(ErrorData));
1671 /* the default text domain is the backend's */
1673 /* set the errno to be used to interpret %m */
1675
1676 oldcontext = MemoryContextSwitchTo(ErrorContext);
1677
1678 edata->message_id = fmt;
1679 EVALUATE_MESSAGE(edata->domain, message, false, true);
1680
1681 MemoryContextSwitchTo(oldcontext);
1682
1683 return edata->message;
1684}
1685
1686
1687/*
1688 * Actual output of the top-of-stack error message
1689 *
1690 * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
1691 * if the error is caught by somebody). For all other severity levels this
1692 * is called by errfinish.
1693 */
1694void
1696{
1698 MemoryContext oldcontext;
1699
1702 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1703
1704 /*
1705 * Reset the formatted timestamp fields before emitting any logs. This
1706 * includes all the log destinations and emit_log_hook, as the latter
1707 * could use log_line_prefix or the formatted timestamps.
1708 */
1709 saved_timeval_set = false;
1710 formatted_log_time[0] = '\0';
1711
1712 /*
1713 * Call hook before sending message to log. The hook function is allowed
1714 * to turn off edata->output_to_server, so we must recheck that afterward.
1715 * Making any other change in the content of edata is not considered
1716 * supported.
1717 *
1718 * Note: the reason why the hook can only turn off output_to_server, and
1719 * not turn it on, is that it'd be unreliable: we will never get here at
1720 * all if errstart() deems the message uninteresting. A hook that could
1721 * make decisions in that direction would have to hook into errstart(),
1722 * where it would have much less information available. emit_log_hook is
1723 * intended for custom log filtering and custom log message transmission
1724 * mechanisms.
1725 *
1726 * The log hook has access to both the translated and original English
1727 * error message text, which is passed through to allow it to be used as a
1728 * message identifier. Note that the original text is not available for
1729 * detail, detail_log, hint and context text elements.
1730 */
1731 if (edata->output_to_server && emit_log_hook)
1732 (*emit_log_hook) (edata);
1733
1734 /* Send to server log, if enabled */
1735 if (edata->output_to_server)
1737
1738 /* Send to client, if enabled */
1739 if (edata->output_to_client)
1741
1742 MemoryContextSwitchTo(oldcontext);
1744}
1745
1746/*
1747 * CopyErrorData --- obtain a copy of the topmost error stack entry
1748 *
1749 * This is only for use in error handler code. The data is copied into the
1750 * current memory context, so callers should always switch away from
1751 * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
1752 */
1753ErrorData *
1755{
1757 ErrorData *newedata;
1758
1759 /*
1760 * we don't increment recursion_depth because out-of-memory here does not
1761 * indicate a problem within the error subsystem.
1762 */
1764
1766
1767 /* Copy the struct itself */
1768 newedata = (ErrorData *) palloc(sizeof(ErrorData));
1769 memcpy(newedata, edata, sizeof(ErrorData));
1770
1771 /*
1772 * Make copies of separately-allocated strings. Note that we copy even
1773 * theoretically-constant strings such as filename. This is because those
1774 * could point into JIT-created code segments that might get unloaded at
1775 * transaction cleanup. In some cases we need the copied ErrorData to
1776 * survive transaction boundaries, so we'd better copy those strings too.
1777 */
1778 if (newedata->filename)
1779 newedata->filename = pstrdup(newedata->filename);
1780 if (newedata->funcname)
1781 newedata->funcname = pstrdup(newedata->funcname);
1782 if (newedata->domain)
1783 newedata->domain = pstrdup(newedata->domain);
1784 if (newedata->context_domain)
1785 newedata->context_domain = pstrdup(newedata->context_domain);
1786 if (newedata->message)
1787 newedata->message = pstrdup(newedata->message);
1788 if (newedata->detail)
1789 newedata->detail = pstrdup(newedata->detail);
1790 if (newedata->detail_log)
1791 newedata->detail_log = pstrdup(newedata->detail_log);
1792 if (newedata->hint)
1793 newedata->hint = pstrdup(newedata->hint);
1794 if (newedata->context)
1795 newedata->context = pstrdup(newedata->context);
1796 if (newedata->backtrace)
1797 newedata->backtrace = pstrdup(newedata->backtrace);
1798 if (newedata->message_id)
1799 newedata->message_id = pstrdup(newedata->message_id);
1800 if (newedata->schema_name)
1801 newedata->schema_name = pstrdup(newedata->schema_name);
1802 if (newedata->table_name)
1803 newedata->table_name = pstrdup(newedata->table_name);
1804 if (newedata->column_name)
1805 newedata->column_name = pstrdup(newedata->column_name);
1806 if (newedata->datatype_name)
1807 newedata->datatype_name = pstrdup(newedata->datatype_name);
1808 if (newedata->constraint_name)
1809 newedata->constraint_name = pstrdup(newedata->constraint_name);
1810 if (newedata->internalquery)
1811 newedata->internalquery = pstrdup(newedata->internalquery);
1812
1813 /* Use the calling context for string allocation */
1815
1816 return newedata;
1817}
1818
1819/*
1820 * FreeErrorData --- free the structure returned by CopyErrorData.
1821 *
1822 * Error handlers should use this in preference to assuming they know all
1823 * the separately-allocated fields.
1824 */
1825void
1827{
1828 FreeErrorDataContents(edata);
1829 pfree(edata);
1830}
1831
1832/*
1833 * FreeErrorDataContents --- free the subsidiary data of an ErrorData.
1834 *
1835 * This can be used on either an error stack entry or a copied ErrorData.
1836 */
1837static void
1839{
1840 if (edata->message)
1841 pfree(edata->message);
1842 if (edata->detail)
1843 pfree(edata->detail);
1844 if (edata->detail_log)
1845 pfree(edata->detail_log);
1846 if (edata->hint)
1847 pfree(edata->hint);
1848 if (edata->context)
1849 pfree(edata->context);
1850 if (edata->backtrace)
1851 pfree(edata->backtrace);
1852 if (edata->schema_name)
1853 pfree(edata->schema_name);
1854 if (edata->table_name)
1855 pfree(edata->table_name);
1856 if (edata->column_name)
1857 pfree(edata->column_name);
1858 if (edata->datatype_name)
1859 pfree(edata->datatype_name);
1860 if (edata->constraint_name)
1861 pfree(edata->constraint_name);
1862 if (edata->internalquery)
1863 pfree(edata->internalquery);
1864}
1865
1866/*
1867 * FlushErrorState --- flush the error state after error recovery
1868 *
1869 * This should be called by an error handler after it's done processing
1870 * the error; or as soon as it's done CopyErrorData, if it intends to
1871 * do stuff that is likely to provoke another error. You are not "out" of
1872 * the error subsystem until you have done this.
1873 */
1874void
1876{
1877 /*
1878 * Reset stack to empty. The only case where it would be more than one
1879 * deep is if we serviced an error that interrupted construction of
1880 * another message. We assume control escaped out of that message
1881 * construction and won't ever go back.
1882 */
1884 recursion_depth = 0;
1885 /* Delete all data in ErrorContext */
1887}
1888
1889/*
1890 * ThrowErrorData --- report an error described by an ErrorData structure
1891 *
1892 * This function should be called on an ErrorData structure that isn't stored
1893 * on the errordata stack and hasn't been processed yet. It will call
1894 * errstart() and errfinish() as needed, so those should not have already been
1895 * called.
1896 *
1897 * ThrowErrorData() is useful for handling soft errors. It's also useful for
1898 * re-reporting errors originally reported by background worker processes and
1899 * then propagated (with or without modification) to the backend responsible
1900 * for them.
1901 */
1902void
1904{
1905 ErrorData *newedata;
1906 MemoryContext oldcontext;
1907
1908 if (!errstart(edata->elevel, edata->domain))
1909 return; /* error is not to be reported at all */
1910
1911 newedata = &errordata[errordata_stack_depth];
1913 oldcontext = MemoryContextSwitchTo(newedata->assoc_context);
1914
1915 /* Copy the supplied fields to the error stack entry. */
1916 if (edata->sqlerrcode != 0)
1917 newedata->sqlerrcode = edata->sqlerrcode;
1918 if (edata->message)
1919 newedata->message = pstrdup(edata->message);
1920 if (edata->detail)
1921 newedata->detail = pstrdup(edata->detail);
1922 if (edata->detail_log)
1923 newedata->detail_log = pstrdup(edata->detail_log);
1924 if (edata->hint)
1925 newedata->hint = pstrdup(edata->hint);
1926 if (edata->context)
1927 newedata->context = pstrdup(edata->context);
1928 if (edata->backtrace)
1929 newedata->backtrace = pstrdup(edata->backtrace);
1930 /* assume message_id is not available */
1931 if (edata->schema_name)
1932 newedata->schema_name = pstrdup(edata->schema_name);
1933 if (edata->table_name)
1934 newedata->table_name = pstrdup(edata->table_name);
1935 if (edata->column_name)
1936 newedata->column_name = pstrdup(edata->column_name);
1937 if (edata->datatype_name)
1938 newedata->datatype_name = pstrdup(edata->datatype_name);
1939 if (edata->constraint_name)
1940 newedata->constraint_name = pstrdup(edata->constraint_name);
1941 newedata->cursorpos = edata->cursorpos;
1942 newedata->internalpos = edata->internalpos;
1943 if (edata->internalquery)
1944 newedata->internalquery = pstrdup(edata->internalquery);
1945
1946 MemoryContextSwitchTo(oldcontext);
1948
1949 /* Process the error. */
1950 errfinish(edata->filename, edata->lineno, edata->funcname);
1951}
1952
1953/*
1954 * ReThrowError --- re-throw a previously copied error
1955 *
1956 * A handler can do CopyErrorData/FlushErrorState to get out of the error
1957 * subsystem, then do some processing, and finally ReThrowError to re-throw
1958 * the original error. This is slower than just PG_RE_THROW() but should
1959 * be used if the "some processing" is likely to incur another error.
1960 */
1961void
1963{
1964 ErrorData *newedata;
1965
1966 Assert(edata->elevel == ERROR);
1967
1968 /* Push the data back into the error context */
1971
1972 newedata = get_error_stack_entry();
1973 memcpy(newedata, edata, sizeof(ErrorData));
1974
1975 /* Make copies of separately-allocated fields */
1976 if (newedata->message)
1977 newedata->message = pstrdup(newedata->message);
1978 if (newedata->detail)
1979 newedata->detail = pstrdup(newedata->detail);
1980 if (newedata->detail_log)
1981 newedata->detail_log = pstrdup(newedata->detail_log);
1982 if (newedata->hint)
1983 newedata->hint = pstrdup(newedata->hint);
1984 if (newedata->context)
1985 newedata->context = pstrdup(newedata->context);
1986 if (newedata->backtrace)
1987 newedata->backtrace = pstrdup(newedata->backtrace);
1988 if (newedata->schema_name)
1989 newedata->schema_name = pstrdup(newedata->schema_name);
1990 if (newedata->table_name)
1991 newedata->table_name = pstrdup(newedata->table_name);
1992 if (newedata->column_name)
1993 newedata->column_name = pstrdup(newedata->column_name);
1994 if (newedata->datatype_name)
1995 newedata->datatype_name = pstrdup(newedata->datatype_name);
1996 if (newedata->constraint_name)
1997 newedata->constraint_name = pstrdup(newedata->constraint_name);
1998 if (newedata->internalquery)
1999 newedata->internalquery = pstrdup(newedata->internalquery);
2000
2001 /* Reset the assoc_context to be ErrorContext */
2002 newedata->assoc_context = ErrorContext;
2003
2005 PG_RE_THROW();
2006}
2007
2008/*
2009 * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
2010 */
2011void
2013{
2014 /* If possible, throw the error to the next outer setjmp handler */
2015 if (PG_exception_stack != NULL)
2016 siglongjmp(*PG_exception_stack, 1);
2017 else
2018 {
2019 /*
2020 * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
2021 * we have now exited only to discover that there is no outer setjmp
2022 * handler to pass the error to. Had the error been thrown outside
2023 * the block to begin with, we'd have promoted the error to FATAL, so
2024 * the correct behavior is to make it FATAL now; that is, emit it and
2025 * then call proc_exit.
2026 */
2028
2030 Assert(edata->elevel == ERROR);
2031 edata->elevel = FATAL;
2032
2033 /*
2034 * At least in principle, the increase in severity could have changed
2035 * where-to-output decisions, so recalculate.
2036 */
2039
2040 /*
2041 * We can use errfinish() for the rest, but we don't want it to call
2042 * any error context routines a second time. Since we know we are
2043 * about to exit, it should be OK to just clear the context stack.
2044 */
2045 error_context_stack = NULL;
2046
2047 errfinish(edata->filename, edata->lineno, edata->funcname);
2048 }
2049
2050 /* Doesn't return ... */
2051 ExceptionalCondition("pg_re_throw tried to return", __FILE__, __LINE__);
2052}
2053
2054
2055/*
2056 * GetErrorContextStack - Return the context stack, for display/diags
2057 *
2058 * Returns a pstrdup'd string in the caller's context which includes the PG
2059 * error call stack. It is the caller's responsibility to ensure this string
2060 * is pfree'd (or its context cleaned up) when done.
2061 *
2062 * This information is collected by traversing the error contexts and calling
2063 * each context's callback function, each of which is expected to call
2064 * errcontext() to return a string which can be presented to the user.
2065 */
2066char *
2068{
2069 ErrorData *edata;
2070 ErrorContextCallback *econtext;
2071
2072 /*
2073 * Crank up a stack entry to store the info in.
2074 */
2076
2077 edata = get_error_stack_entry();
2078
2079 /*
2080 * Set up assoc_context to be the caller's context, so any allocations
2081 * done (which will include edata->context) will use their context.
2082 */
2084
2085 /*
2086 * Call any context callback functions to collect the context information
2087 * into edata->context.
2088 *
2089 * Errors occurring in callback functions should go through the regular
2090 * error handling code which should handle any recursive errors, though we
2091 * double-check above, just in case.
2092 */
2093 for (econtext = error_context_stack;
2094 econtext != NULL;
2095 econtext = econtext->previous)
2096 econtext->callback(econtext->arg);
2097
2098 /*
2099 * Clean ourselves off the stack, any allocations done should have been
2100 * using edata->assoc_context, which we set up earlier to be the caller's
2101 * context, so we're free to just remove our entry off the stack and
2102 * decrement recursion depth and exit.
2103 */
2106
2107 /*
2108 * Return a pointer to the string the caller asked for, which should have
2109 * been allocated in their context.
2110 */
2111 return edata->context;
2112}
2113
2114
2115/*
2116 * Initialization of error output file
2117 */
2118void
2120{
2121 int fd,
2122 istty;
2123
2124 if (OutputFileName[0])
2125 {
2126 /*
2127 * A debug-output file name was given.
2128 *
2129 * Make sure we can write the file, and find out if it's a tty.
2130 */
2131 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
2132 0666)) < 0)
2133 ereport(FATAL,
2135 errmsg("could not open file \"%s\": %m", OutputFileName)));
2136 istty = isatty(fd);
2137 close(fd);
2138
2139 /*
2140 * Redirect our stderr to the debug output file.
2141 */
2142 if (!freopen(OutputFileName, "a", stderr))
2143 ereport(FATAL,
2145 errmsg("could not reopen file \"%s\" as stderr: %m",
2146 OutputFileName)));
2147
2148 /*
2149 * If the file is a tty and we're running under the postmaster, try to
2150 * send stdout there as well (if it isn't a tty then stderr will block
2151 * out stdout, so we may as well let stdout go wherever it was going
2152 * before).
2153 */
2154 if (istty && IsUnderPostmaster)
2155 if (!freopen(OutputFileName, "a", stdout))
2156 ereport(FATAL,
2158 errmsg("could not reopen file \"%s\" as stdout: %m",
2159 OutputFileName)));
2160 }
2161}
2162
2163
2164/*
2165 * GUC check_hook for backtrace_functions
2166 *
2167 * We split the input string, where commas separate function names
2168 * and certain whitespace chars are ignored, into a \0-separated (and
2169 * \0\0-terminated) list of function names. This formulation allows
2170 * easy scanning when an error is thrown while avoiding the use of
2171 * non-reentrant strtok(), as well as keeping the output data in a
2172 * single palloc() chunk.
2173 */
2174bool
2176{
2177 int newvallen = strlen(*newval);
2178 char *someval;
2179 int validlen;
2180 int i;
2181 int j;
2182
2183 /*
2184 * Allow characters that can be C identifiers and commas as separators, as
2185 * well as some whitespace for readability.
2186 */
2187 validlen = strspn(*newval,
2188 "0123456789_"
2189 "abcdefghijklmnopqrstuvwxyz"
2190 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2191 ", \n\t");
2192 if (validlen != newvallen)
2193 {
2194 GUC_check_errdetail("Invalid character.");
2195 return false;
2196 }
2197
2198 if (*newval[0] == '\0')
2199 {
2200 *extra = NULL;
2201 return true;
2202 }
2203
2204 /*
2205 * Allocate space for the output and create the copy. We could discount
2206 * whitespace chars to save some memory, but it doesn't seem worth the
2207 * trouble.
2208 */
2209 someval = guc_malloc(LOG, newvallen + 1 + 1);
2210 if (!someval)
2211 return false;
2212 for (i = 0, j = 0; i < newvallen; i++)
2213 {
2214 if ((*newval)[i] == ',')
2215 someval[j++] = '\0'; /* next item */
2216 else if ((*newval)[i] == ' ' ||
2217 (*newval)[i] == '\n' ||
2218 (*newval)[i] == '\t')
2219 ; /* ignore these */
2220 else
2221 someval[j++] = (*newval)[i]; /* copy anything else */
2222 }
2223
2224 /* two \0s end the setting */
2225 someval[j] = '\0';
2226 someval[j + 1] = '\0';
2227
2228 *extra = someval;
2229 return true;
2230}
2231
2232/*
2233 * GUC assign_hook for backtrace_functions
2234 */
2235void
2236assign_backtrace_functions(const char *newval, void *extra)
2237{
2238 backtrace_function_list = (char *) extra;
2239}
2240
2241/*
2242 * GUC check_hook for log_destination
2243 */
2244bool
2246{
2247 char *rawstring;
2248 List *elemlist;
2249 ListCell *l;
2250 int newlogdest = 0;
2251 int *myextra;
2252
2253 /* Need a modifiable copy of string */
2254 rawstring = pstrdup(*newval);
2255
2256 /* Parse string into list of identifiers */
2257 if (!SplitIdentifierString(rawstring, ',', &elemlist))
2258 {
2259 /* syntax error in list */
2260 GUC_check_errdetail("List syntax is invalid.");
2261 pfree(rawstring);
2262 list_free(elemlist);
2263 return false;
2264 }
2265
2266 foreach(l, elemlist)
2267 {
2268 char *tok = (char *) lfirst(l);
2269
2270 if (pg_strcasecmp(tok, "stderr") == 0)
2271 newlogdest |= LOG_DESTINATION_STDERR;
2272 else if (pg_strcasecmp(tok, "csvlog") == 0)
2273 newlogdest |= LOG_DESTINATION_CSVLOG;
2274 else if (pg_strcasecmp(tok, "jsonlog") == 0)
2275 newlogdest |= LOG_DESTINATION_JSONLOG;
2276#ifdef HAVE_SYSLOG
2277 else if (pg_strcasecmp(tok, "syslog") == 0)
2278 newlogdest |= LOG_DESTINATION_SYSLOG;
2279#endif
2280#ifdef WIN32
2281 else if (pg_strcasecmp(tok, "eventlog") == 0)
2282 newlogdest |= LOG_DESTINATION_EVENTLOG;
2283#endif
2284 else
2285 {
2286 GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
2287 pfree(rawstring);
2288 list_free(elemlist);
2289 return false;
2290 }
2291 }
2292
2293 pfree(rawstring);
2294 list_free(elemlist);
2295
2296 myextra = (int *) guc_malloc(LOG, sizeof(int));
2297 if (!myextra)
2298 return false;
2299 *myextra = newlogdest;
2300 *extra = myextra;
2301
2302 return true;
2303}
2304
2305/*
2306 * GUC assign_hook for log_destination
2307 */
2308void
2309assign_log_destination(const char *newval, void *extra)
2310{
2311 Log_destination = *((int *) extra);
2312}
2313
2314/*
2315 * GUC assign_hook for syslog_ident
2316 */
2317void
2318assign_syslog_ident(const char *newval, void *extra)
2319{
2320#ifdef HAVE_SYSLOG
2321 /*
2322 * guc.c is likely to call us repeatedly with same parameters, so don't
2323 * thrash the syslog connection unnecessarily. Also, we do not re-open
2324 * the connection until needed, since this routine will get called whether
2325 * or not Log_destination actually mentions syslog.
2326 *
2327 * Note that we make our own copy of the ident string rather than relying
2328 * on guc.c's. This may be overly paranoid, but it ensures that we cannot
2329 * accidentally free a string that syslog is still using.
2330 */
2331 if (syslog_ident == NULL || strcmp(syslog_ident, newval) != 0)
2332 {
2333 if (openlog_done)
2334 {
2335 closelog();
2336 openlog_done = false;
2337 }
2338 free(syslog_ident);
2339 syslog_ident = strdup(newval);
2340 /* if the strdup fails, we will cope in write_syslog() */
2341 }
2342#endif
2343 /* Without syslog support, just ignore it */
2344}
2345
2346/*
2347 * GUC assign_hook for syslog_facility
2348 */
2349void
2351{
2352#ifdef HAVE_SYSLOG
2353 /*
2354 * As above, don't thrash the syslog connection unnecessarily.
2355 */
2356 if (syslog_facility != newval)
2357 {
2358 if (openlog_done)
2359 {
2360 closelog();
2361 openlog_done = false;
2362 }
2364 }
2365#endif
2366 /* Without syslog support, just ignore it */
2367}
2368
2369#ifdef HAVE_SYSLOG
2370
2371/*
2372 * Write a message line to syslog
2373 */
2374static void
2375write_syslog(int level, const char *line)
2376{
2377 static unsigned long seq = 0;
2378
2379 int len;
2380 const char *nlpos;
2381
2382 /* Open syslog connection if not done yet */
2383 if (!openlog_done)
2384 {
2385 openlog(syslog_ident ? syslog_ident : "postgres",
2386 LOG_PID | LOG_NDELAY | LOG_NOWAIT,
2388 openlog_done = true;
2389 }
2390
2391 /*
2392 * We add a sequence number to each log message to suppress "same"
2393 * messages.
2394 */
2395 seq++;
2396
2397 /*
2398 * Our problem here is that many syslog implementations don't handle long
2399 * messages in an acceptable manner. While this function doesn't help that
2400 * fact, it does work around by splitting up messages into smaller pieces.
2401 *
2402 * We divide into multiple syslog() calls if message is too long or if the
2403 * message contains embedded newline(s).
2404 */
2405 len = strlen(line);
2406 nlpos = strchr(line, '\n');
2407 if (syslog_split_messages && (len > PG_SYSLOG_LIMIT || nlpos != NULL))
2408 {
2409 int chunk_nr = 0;
2410
2411 while (len > 0)
2412 {
2413 char buf[PG_SYSLOG_LIMIT + 1];
2414 int buflen;
2415 int i;
2416
2417 /* if we start at a newline, move ahead one char */
2418 if (line[0] == '\n')
2419 {
2420 line++;
2421 len--;
2422 /* we need to recompute the next newline's position, too */
2423 nlpos = strchr(line, '\n');
2424 continue;
2425 }
2426
2427 /* copy one line, or as much as will fit, to buf */
2428 if (nlpos != NULL)
2429 buflen = nlpos - line;
2430 else
2431 buflen = len;
2432 buflen = Min(buflen, PG_SYSLOG_LIMIT);
2433 memcpy(buf, line, buflen);
2434 buf[buflen] = '\0';
2435
2436 /* trim to multibyte letter boundary */
2437 buflen = pg_mbcliplen(buf, buflen, buflen);
2438 if (buflen <= 0)
2439 return;
2440 buf[buflen] = '\0';
2441
2442 /* already word boundary? */
2443 if (line[buflen] != '\0' &&
2444 !isspace((unsigned char) line[buflen]))
2445 {
2446 /* try to divide at word boundary */
2447 i = buflen - 1;
2448 while (i > 0 && !isspace((unsigned char) buf[i]))
2449 i--;
2450
2451 if (i > 0) /* else couldn't divide word boundary */
2452 {
2453 buflen = i;
2454 buf[i] = '\0';
2455 }
2456 }
2457
2458 chunk_nr++;
2459
2461 syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
2462 else
2463 syslog(level, "[%d] %s", chunk_nr, buf);
2464
2465 line += buflen;
2466 len -= buflen;
2467 }
2468 }
2469 else
2470 {
2471 /* message short enough */
2473 syslog(level, "[%lu] %s", seq, line);
2474 else
2475 syslog(level, "%s", line);
2476 }
2477}
2478#endif /* HAVE_SYSLOG */
2479
2480#ifdef WIN32
2481/*
2482 * Get the PostgreSQL equivalent of the Windows ANSI code page. "ANSI" system
2483 * interfaces (e.g. CreateFileA()) expect string arguments in this encoding.
2484 * Every process in a given system will find the same value at all times.
2485 */
2486static int
2487GetACPEncoding(void)
2488{
2489 static int encoding = -2;
2490
2491 if (encoding == -2)
2492 encoding = pg_codepage_to_encoding(GetACP());
2493
2494 return encoding;
2495}
2496
2497/*
2498 * Write a message line to the windows event log
2499 */
2500static void
2501write_eventlog(int level, const char *line, int len)
2502{
2503 WCHAR *utf16;
2504 int eventlevel = EVENTLOG_ERROR_TYPE;
2505 static HANDLE evtHandle = INVALID_HANDLE_VALUE;
2506
2507 if (evtHandle == INVALID_HANDLE_VALUE)
2508 {
2509 evtHandle = RegisterEventSource(NULL,
2511 if (evtHandle == NULL)
2512 {
2513 evtHandle = INVALID_HANDLE_VALUE;
2514 return;
2515 }
2516 }
2517
2518 switch (level)
2519 {
2520 case DEBUG5:
2521 case DEBUG4:
2522 case DEBUG3:
2523 case DEBUG2:
2524 case DEBUG1:
2525 case LOG:
2526 case LOG_SERVER_ONLY:
2527 case INFO:
2528 case NOTICE:
2529 eventlevel = EVENTLOG_INFORMATION_TYPE;
2530 break;
2531 case WARNING:
2533 eventlevel = EVENTLOG_WARNING_TYPE;
2534 break;
2535 case ERROR:
2536 case FATAL:
2537 case PANIC:
2538 default:
2539 eventlevel = EVENTLOG_ERROR_TYPE;
2540 break;
2541 }
2542
2543 /*
2544 * If message character encoding matches the encoding expected by
2545 * ReportEventA(), call it to avoid the hazards of conversion. Otherwise,
2546 * try to convert the message to UTF16 and write it with ReportEventW().
2547 * Fall back on ReportEventA() if conversion failed.
2548 *
2549 * Since we palloc the structure required for conversion, also fall
2550 * through to writing unconverted if we have not yet set up
2551 * CurrentMemoryContext.
2552 *
2553 * Also verify that we are not on our way into error recursion trouble due
2554 * to error messages thrown deep inside pgwin32_message_to_UTF16().
2555 */
2557 CurrentMemoryContext != NULL &&
2558 GetMessageEncoding() != GetACPEncoding())
2559 {
2560 utf16 = pgwin32_message_to_UTF16(line, len, NULL);
2561 if (utf16)
2562 {
2563 ReportEventW(evtHandle,
2564 eventlevel,
2565 0,
2566 0, /* All events are Id 0 */
2567 NULL,
2568 1,
2569 0,
2570 (LPCWSTR *) &utf16,
2571 NULL);
2572 /* XXX Try ReportEventA() when ReportEventW() fails? */
2573
2574 pfree(utf16);
2575 return;
2576 }
2577 }
2578 ReportEventA(evtHandle,
2579 eventlevel,
2580 0,
2581 0, /* All events are Id 0 */
2582 NULL,
2583 1,
2584 0,
2585 &line,
2586 NULL);
2587}
2588#endif /* WIN32 */
2589
2590static void
2591write_console(const char *line, int len)
2592{
2593 int rc;
2594
2595#ifdef WIN32
2596
2597 /*
2598 * Try to convert the message to UTF16 and write it with WriteConsoleW().
2599 * Fall back on write() if anything fails.
2600 *
2601 * In contrast to write_eventlog(), don't skip straight to write() based
2602 * on the applicable encodings. Unlike WriteConsoleW(), write() depends
2603 * on the suitability of the console output code page. Since we put
2604 * stderr into binary mode in SubPostmasterMain(), write() skips the
2605 * necessary translation anyway.
2606 *
2607 * WriteConsoleW() will fail if stderr is redirected, so just fall through
2608 * to writing unconverted to the logfile in this case.
2609 *
2610 * Since we palloc the structure required for conversion, also fall
2611 * through to writing unconverted if we have not yet set up
2612 * CurrentMemoryContext.
2613 */
2616 CurrentMemoryContext != NULL)
2617 {
2618 WCHAR *utf16;
2619 int utf16len;
2620
2621 utf16 = pgwin32_message_to_UTF16(line, len, &utf16len);
2622 if (utf16 != NULL)
2623 {
2624 HANDLE stdHandle;
2625 DWORD written;
2626
2627 stdHandle = GetStdHandle(STD_ERROR_HANDLE);
2628 if (WriteConsoleW(stdHandle, utf16, utf16len, &written, NULL))
2629 {
2630 pfree(utf16);
2631 return;
2632 }
2633
2634 /*
2635 * In case WriteConsoleW() failed, fall back to writing the
2636 * message unconverted.
2637 */
2638 pfree(utf16);
2639 }
2640 }
2641#else
2642
2643 /*
2644 * Conversion on non-win32 platforms is not implemented yet. It requires
2645 * non-throw version of pg_do_encoding_conversion(), that converts
2646 * unconvertible characters to '?' without errors.
2647 *
2648 * XXX: We have a no-throw version now. It doesn't convert to '?' though.
2649 */
2650#endif
2651
2652 /*
2653 * We ignore any error from write() here. We have no useful way to report
2654 * it ... certainly whining on stderr isn't likely to be productive.
2655 */
2656 rc = write(fileno(stderr), line, len);
2657 (void) rc;
2658}
2659
2660/*
2661 * get_formatted_log_time -- compute and get the log timestamp.
2662 *
2663 * The timestamp is computed if not set yet, so as it is kept consistent
2664 * among all the log destinations that require it to be consistent. Note
2665 * that the computed timestamp is returned in a static buffer, not
2666 * palloc()'d.
2667 */
2668char *
2670{
2671 pg_time_t stamp_time;
2672 char msbuf[13];
2673
2674 /* leave if already computed */
2675 if (formatted_log_time[0] != '\0')
2676 return formatted_log_time;
2677
2678 if (!saved_timeval_set)
2679 {
2681 saved_timeval_set = true;
2682 }
2683
2684 stamp_time = (pg_time_t) saved_timeval.tv_sec;
2685
2686 /*
2687 * Note: we expect that guc.c will ensure that log_timezone is set up (at
2688 * least with a minimal GMT value) before Log_line_prefix can become
2689 * nonempty or CSV/JSON mode can be selected.
2690 */
2692 /* leave room for milliseconds... */
2693 "%Y-%m-%d %H:%M:%S %Z",
2694 pg_localtime(&stamp_time, log_timezone));
2695
2696 /* 'paste' milliseconds into place... */
2697 sprintf(msbuf, ".%03d", (int) (saved_timeval.tv_usec / 1000));
2698 memcpy(formatted_log_time + 19, msbuf, 4);
2699
2700 return formatted_log_time;
2701}
2702
2703/*
2704 * reset_formatted_start_time -- reset the start timestamp
2705 */
2706void
2708{
2709 formatted_start_time[0] = '\0';
2710}
2711
2712/*
2713 * get_formatted_start_time -- compute and get the start timestamp.
2714 *
2715 * The timestamp is computed if not set yet. Note that the computed
2716 * timestamp is returned in a static buffer, not palloc()'d.
2717 */
2718char *
2720{
2721 pg_time_t stamp_time = (pg_time_t) MyStartTime;
2722
2723 /* leave if already computed */
2724 if (formatted_start_time[0] != '\0')
2725 return formatted_start_time;
2726
2727 /*
2728 * Note: we expect that guc.c will ensure that log_timezone is set up (at
2729 * least with a minimal GMT value) before Log_line_prefix can become
2730 * nonempty or CSV/JSON mode can be selected.
2731 */
2733 "%Y-%m-%d %H:%M:%S %Z",
2734 pg_localtime(&stamp_time, log_timezone));
2735
2736 return formatted_start_time;
2737}
2738
2739/*
2740 * check_log_of_query -- check if a query can be logged
2741 */
2742bool
2744{
2745 /* log required? */
2747 return false;
2748
2749 /* query log wanted? */
2750 if (edata->hide_stmt)
2751 return false;
2752
2753 /* query string available? */
2754 if (debug_query_string == NULL)
2755 return false;
2756
2757 return true;
2758}
2759
2760/*
2761 * get_backend_type_for_log -- backend type for log entries
2762 *
2763 * Returns a pointer to a static buffer, not palloc()'d.
2764 */
2765const char *
2767{
2768 const char *backend_type_str;
2769
2770 if (MyProcPid == PostmasterPid)
2771 backend_type_str = "postmaster";
2772 else if (MyBackendType == B_BG_WORKER)
2773 backend_type_str = MyBgworkerEntry->bgw_type;
2774 else
2775 backend_type_str = GetBackendTypeDesc(MyBackendType);
2776
2777 return backend_type_str;
2778}
2779
2780/*
2781 * process_log_prefix_padding --- helper function for processing the format
2782 * string in log_line_prefix
2783 *
2784 * Note: This function returns NULL if it finds something which
2785 * it deems invalid in the format string.
2786 */
2787static const char *
2788process_log_prefix_padding(const char *p, int *ppadding)
2789{
2790 int paddingsign = 1;
2791 int padding = 0;
2792
2793 if (*p == '-')
2794 {
2795 p++;
2796
2797 if (*p == '\0') /* Did the buf end in %- ? */
2798 return NULL;
2799 paddingsign = -1;
2800 }
2801
2802 /* generate an int version of the numerical string */
2803 while (*p >= '0' && *p <= '9')
2804 padding = padding * 10 + (*p++ - '0');
2805
2806 /* format is invalid if it ends with the padding number */
2807 if (*p == '\0')
2808 return NULL;
2809
2810 padding *= paddingsign;
2811 *ppadding = padding;
2812 return p;
2813}
2814
2815/*
2816 * Format log status information using Log_line_prefix.
2817 */
2818static void
2820{
2822}
2823
2824/*
2825 * Format log status info; append to the provided buffer.
2826 */
2827void
2829{
2830 /* static counter for line numbers */
2831 static long log_line_number = 0;
2832
2833 /* has counter been reset in current process? */
2834 static int log_my_pid = 0;
2835 int padding;
2836 const char *p;
2837
2838 /*
2839 * This is one of the few places where we'd rather not inherit a static
2840 * variable's value from the postmaster. But since we will, reset it when
2841 * MyProcPid changes. MyStartTime also changes when MyProcPid does, so
2842 * reset the formatted start timestamp too.
2843 */
2844 if (log_my_pid != MyProcPid)
2845 {
2846 log_line_number = 0;
2847 log_my_pid = MyProcPid;
2849 }
2850 log_line_number++;
2851
2852 if (format == NULL)
2853 return; /* in case guc hasn't run yet */
2854
2855 for (p = format; *p != '\0'; p++)
2856 {
2857 if (*p != '%')
2858 {
2859 /* literal char, just copy */
2861 continue;
2862 }
2863
2864 /* must be a '%', so skip to the next char */
2865 p++;
2866 if (*p == '\0')
2867 break; /* format error - ignore it */
2868 else if (*p == '%')
2869 {
2870 /* string contains %% */
2872 continue;
2873 }
2874
2875
2876 /*
2877 * Process any formatting which may exist after the '%'. Note that
2878 * process_log_prefix_padding moves p past the padding number if it
2879 * exists.
2880 *
2881 * Note: Since only '-', '0' to '9' are valid formatting characters we
2882 * can do a quick check here to pre-check for formatting. If the char
2883 * is not formatting then we can skip a useless function call.
2884 *
2885 * Further note: At least on some platforms, passing %*s rather than
2886 * %s to appendStringInfo() is substantially slower, so many of the
2887 * cases below avoid doing that unless non-zero padding is in fact
2888 * specified.
2889 */
2890 if (*p > '9')
2891 padding = 0;
2892 else if ((p = process_log_prefix_padding(p, &padding)) == NULL)
2893 break;
2894
2895 /* process the option */
2896 switch (*p)
2897 {
2898 case 'a':
2899 if (MyProcPort)
2900 {
2901 const char *appname = application_name;
2902
2903 if (appname == NULL || *appname == '\0')
2904 appname = _("[unknown]");
2905 if (padding != 0)
2906 appendStringInfo(buf, "%*s", padding, appname);
2907 else
2908 appendStringInfoString(buf, appname);
2909 }
2910 else if (padding != 0)
2912 padding > 0 ? padding : -padding);
2913
2914 break;
2915 case 'b':
2916 {
2917 const char *backend_type_str = get_backend_type_for_log();
2918
2919 if (padding != 0)
2920 appendStringInfo(buf, "%*s", padding, backend_type_str);
2921 else
2922 appendStringInfoString(buf, backend_type_str);
2923 break;
2924 }
2925 case 'u':
2926 if (MyProcPort)
2927 {
2928 const char *username = MyProcPort->user_name;
2929
2930 if (username == NULL || *username == '\0')
2931 username = _("[unknown]");
2932 if (padding != 0)
2933 appendStringInfo(buf, "%*s", padding, username);
2934 else
2936 }
2937 else if (padding != 0)
2939 padding > 0 ? padding : -padding);
2940 break;
2941 case 'd':
2942 if (MyProcPort)
2943 {
2944 const char *dbname = MyProcPort->database_name;
2945
2946 if (dbname == NULL || *dbname == '\0')
2947 dbname = _("[unknown]");
2948 if (padding != 0)
2949 appendStringInfo(buf, "%*s", padding, dbname);
2950 else
2952 }
2953 else if (padding != 0)
2955 padding > 0 ? padding : -padding);
2956 break;
2957 case 'c':
2958 if (padding != 0)
2959 {
2960 char strfbuf[128];
2961
2962 snprintf(strfbuf, sizeof(strfbuf) - 1, "%" PRIx64 ".%x",
2964 appendStringInfo(buf, "%*s", padding, strfbuf);
2965 }
2966 else
2967 appendStringInfo(buf, "%" PRIx64 ".%x", MyStartTime, MyProcPid);
2968 break;
2969 case 'p':
2970 if (padding != 0)
2971 appendStringInfo(buf, "%*d", padding, MyProcPid);
2972 else
2974 break;
2975
2976 case 'P':
2977 if (MyProc)
2978 {
2979 PGPROC *leader = MyProc->lockGroupLeader;
2980
2981 /*
2982 * Show the leader only for active parallel workers. This
2983 * leaves out the leader of a parallel group.
2984 */
2985 if (leader == NULL || leader->pid == MyProcPid)
2987 padding > 0 ? padding : -padding);
2988 else if (padding != 0)
2989 appendStringInfo(buf, "%*d", padding, leader->pid);
2990 else
2991 appendStringInfo(buf, "%d", leader->pid);
2992 }
2993 else if (padding != 0)
2995 padding > 0 ? padding : -padding);
2996 break;
2997
2998 case 'l':
2999 if (padding != 0)
3000 appendStringInfo(buf, "%*ld", padding, log_line_number);
3001 else
3002 appendStringInfo(buf, "%ld", log_line_number);
3003 break;
3004 case 'm':
3005 /* force a log timestamp reset */
3006 formatted_log_time[0] = '\0';
3007 (void) get_formatted_log_time();
3008
3009 if (padding != 0)
3010 appendStringInfo(buf, "%*s", padding, formatted_log_time);
3011 else
3013 break;
3014 case 't':
3015 {
3016 pg_time_t stamp_time = (pg_time_t) time(NULL);
3017 char strfbuf[128];
3018
3019 pg_strftime(strfbuf, sizeof(strfbuf),
3020 "%Y-%m-%d %H:%M:%S %Z",
3021 pg_localtime(&stamp_time, log_timezone));
3022 if (padding != 0)
3023 appendStringInfo(buf, "%*s", padding, strfbuf);
3024 else
3025 appendStringInfoString(buf, strfbuf);
3026 }
3027 break;
3028 case 'n':
3029 {
3030 char strfbuf[128];
3031
3032 if (!saved_timeval_set)
3033 {
3035 saved_timeval_set = true;
3036 }
3037
3038 snprintf(strfbuf, sizeof(strfbuf), "%ld.%03d",
3039 (long) saved_timeval.tv_sec,
3040 (int) (saved_timeval.tv_usec / 1000));
3041
3042 if (padding != 0)
3043 appendStringInfo(buf, "%*s", padding, strfbuf);
3044 else
3045 appendStringInfoString(buf, strfbuf);
3046 }
3047 break;
3048 case 's':
3049 {
3051
3052 if (padding != 0)
3053 appendStringInfo(buf, "%*s", padding, start_time);
3054 else
3056 }
3057 break;
3058 case 'i':
3059 if (MyProcPort)
3060 {
3061 const char *psdisp;
3062 int displen;
3063
3064 psdisp = get_ps_display(&displen);
3065 if (padding != 0)
3066 appendStringInfo(buf, "%*s", padding, psdisp);
3067 else
3068 appendBinaryStringInfo(buf, psdisp, displen);
3069 }
3070 else if (padding != 0)
3072 padding > 0 ? padding : -padding);
3073 break;
3074 case 'L':
3075 {
3076 const char *local_host;
3077
3078 if (MyProcPort)
3079 {
3080 if (MyProcPort->local_host[0] == '\0')
3081 {
3082 /*
3083 * First time through: cache the lookup, since it
3084 * might not have trivial cost.
3085 */
3089 sizeof(MyProcPort->local_host),
3090 NULL, 0,
3091 NI_NUMERICHOST | NI_NUMERICSERV);
3092 }
3093 local_host = MyProcPort->local_host;
3094 }
3095 else
3096 {
3097 /* Background process, or connection not yet made */
3098 local_host = "[none]";
3099 }
3100 if (padding != 0)
3101 appendStringInfo(buf, "%*s", padding, local_host);
3102 else
3103 appendStringInfoString(buf, local_host);
3104 }
3105 break;
3106 case 'r':
3108 {
3109 if (padding != 0)
3110 {
3111 if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
3112 {
3113 /*
3114 * This option is slightly special as the port
3115 * number may be appended onto the end. Here we
3116 * need to build 1 string which contains the
3117 * remote_host and optionally the remote_port (if
3118 * set) so we can properly align the string.
3119 */
3120
3121 char *hostport;
3122
3123 hostport = psprintf("%s(%s)", MyProcPort->remote_host, MyProcPort->remote_port);
3124 appendStringInfo(buf, "%*s", padding, hostport);
3125 pfree(hostport);
3126 }
3127 else
3128 appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
3129 }
3130 else
3131 {
3132 /* padding is 0, so we don't need a temp buffer */
3134 if (MyProcPort->remote_port &&
3135 MyProcPort->remote_port[0] != '\0')
3136 appendStringInfo(buf, "(%s)",
3138 }
3139 }
3140 else if (padding != 0)
3142 padding > 0 ? padding : -padding);
3143 break;
3144 case 'h':
3146 {
3147 if (padding != 0)
3148 appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
3149 else
3151 }
3152 else if (padding != 0)
3154 padding > 0 ? padding : -padding);
3155 break;
3156 case 'q':
3157 /* in postmaster and friends, stop if %q is seen */
3158 /* in a backend, just ignore */
3159 if (MyProcPort == NULL)
3160 return;
3161 break;
3162 case 'v':
3163 /* keep VXID format in sync with lockfuncs.c */
3164 if (MyProc != NULL && MyProc->vxid.procNumber != INVALID_PROC_NUMBER)
3165 {
3166 if (padding != 0)
3167 {
3168 char strfbuf[128];
3169
3170 snprintf(strfbuf, sizeof(strfbuf) - 1, "%d/%u",
3172 appendStringInfo(buf, "%*s", padding, strfbuf);
3173 }
3174 else
3176 }
3177 else if (padding != 0)
3179 padding > 0 ? padding : -padding);
3180 break;
3181 case 'x':
3182 if (padding != 0)
3183 appendStringInfo(buf, "%*u", padding, GetTopTransactionIdIfAny());
3184 else
3186 break;
3187 case 'e':
3188 if (padding != 0)
3189 appendStringInfo(buf, "%*s", padding, unpack_sql_state(edata->sqlerrcode));
3190 else
3192 break;
3193 case 'Q':
3194 if (padding != 0)
3195 appendStringInfo(buf, "%*" PRId64, padding,
3197 else
3198 appendStringInfo(buf, "%" PRId64,
3200 break;
3201 default:
3202 /* format error - ignore it */
3203 break;
3204 }
3205 }
3206}
3207
3208/*
3209 * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
3210 * static buffer.
3211 */
3212char *
3213unpack_sql_state(int sql_state)
3214{
3215 static char buf[12];
3216 int i;
3217
3218 for (i = 0; i < 5; i++)
3219 {
3220 buf[i] = PGUNSIXBIT(sql_state);
3221 sql_state >>= 6;
3222 }
3223
3224 buf[i] = '\0';
3225 return buf;
3226}
3227
3228
3229/*
3230 * Write error report to server's log
3231 */
3232static void
3234{
3236 bool fallback_to_stderr = false;
3237
3239
3240 log_line_prefix(&buf, edata);
3241 appendStringInfo(&buf, "%s: ", _(error_severity(edata->elevel)));
3242
3245
3246 if (edata->message)
3247 append_with_tabs(&buf, edata->message);
3248 else
3249 append_with_tabs(&buf, _("missing error text"));
3250
3251 if (edata->cursorpos > 0)
3252 appendStringInfo(&buf, _(" at character %d"),
3253 edata->cursorpos);
3254 else if (edata->internalpos > 0)
3255 appendStringInfo(&buf, _(" at character %d"),
3256 edata->internalpos);
3257
3258 appendStringInfoChar(&buf, '\n');
3259
3261 {
3262 if (edata->detail_log)
3263 {
3264 log_line_prefix(&buf, edata);
3265 appendStringInfoString(&buf, _("DETAIL: "));
3267 appendStringInfoChar(&buf, '\n');
3268 }
3269 else if (edata->detail)
3270 {
3271 log_line_prefix(&buf, edata);
3272 appendStringInfoString(&buf, _("DETAIL: "));
3273 append_with_tabs(&buf, edata->detail);
3274 appendStringInfoChar(&buf, '\n');
3275 }
3276 if (edata->hint)
3277 {
3278 log_line_prefix(&buf, edata);
3279 appendStringInfoString(&buf, _("HINT: "));
3280 append_with_tabs(&buf, edata->hint);
3281 appendStringInfoChar(&buf, '\n');
3282 }
3283 if (edata->internalquery)
3284 {
3285 log_line_prefix(&buf, edata);
3286 appendStringInfoString(&buf, _("QUERY: "));
3288 appendStringInfoChar(&buf, '\n');
3289 }
3290 if (edata->context && !edata->hide_ctx)
3291 {
3292 log_line_prefix(&buf, edata);
3293 appendStringInfoString(&buf, _("CONTEXT: "));
3294 append_with_tabs(&buf, edata->context);
3295 appendStringInfoChar(&buf, '\n');
3296 }
3298 {
3299 /* assume no newlines in funcname or filename... */
3300 if (edata->funcname && edata->filename)
3301 {
3302 log_line_prefix(&buf, edata);
3303 appendStringInfo(&buf, _("LOCATION: %s, %s:%d\n"),
3304 edata->funcname, edata->filename,
3305 edata->lineno);
3306 }
3307 else if (edata->filename)
3308 {
3309 log_line_prefix(&buf, edata);
3310 appendStringInfo(&buf, _("LOCATION: %s:%d\n"),
3311 edata->filename, edata->lineno);
3312 }
3313 }
3314 if (edata->backtrace)
3315 {
3316 log_line_prefix(&buf, edata);
3317 appendStringInfoString(&buf, _("BACKTRACE: "));
3318 append_with_tabs(&buf, edata->backtrace);
3319 appendStringInfoChar(&buf, '\n');
3320 }
3321 }
3322
3323 /*
3324 * If the user wants the query that generated this error logged, do it.
3325 */
3326 if (check_log_of_query(edata))
3327 {
3328 log_line_prefix(&buf, edata);
3329 appendStringInfoString(&buf, _("STATEMENT: "));
3331 appendStringInfoChar(&buf, '\n');
3332 }
3333
3334#ifdef HAVE_SYSLOG
3335 /* Write to syslog, if enabled */
3337 {
3338 int syslog_level;
3339
3340 switch (edata->elevel)
3341 {
3342 case DEBUG5:
3343 case DEBUG4:
3344 case DEBUG3:
3345 case DEBUG2:
3346 case DEBUG1:
3347 syslog_level = LOG_DEBUG;
3348 break;
3349 case LOG:
3350 case LOG_SERVER_ONLY:
3351 case INFO:
3352 syslog_level = LOG_INFO;
3353 break;
3354 case NOTICE:
3355 case WARNING:
3357 syslog_level = LOG_NOTICE;
3358 break;
3359 case ERROR:
3360 syslog_level = LOG_WARNING;
3361 break;
3362 case FATAL:
3363 syslog_level = LOG_ERR;
3364 break;
3365 case PANIC:
3366 default:
3367 syslog_level = LOG_CRIT;
3368 break;
3369 }
3370
3371 write_syslog(syslog_level, buf.data);
3372 }
3373#endif /* HAVE_SYSLOG */
3374
3375#ifdef WIN32
3376 /* Write to eventlog, if enabled */
3378 {
3379 write_eventlog(edata->elevel, buf.data, buf.len);
3380 }
3381#endif /* WIN32 */
3382
3383 /* Write to csvlog, if enabled */
3385 {
3386 /*
3387 * Send CSV data if it's safe to do so (syslogger doesn't need the
3388 * pipe). If this is not possible, fallback to an entry written to
3389 * stderr.
3390 */
3392 write_csvlog(edata);
3393 else
3394 fallback_to_stderr = true;
3395 }
3396
3397 /* Write to JSON log, if enabled */
3399 {
3400 /*
3401 * Send JSON 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 {
3407 write_jsonlog(edata);
3408 }
3409 else
3410 fallback_to_stderr = true;
3411 }
3412
3413 /*
3414 * Write to stderr, if enabled or if required because of a previous
3415 * limitation.
3416 */
3419 fallback_to_stderr)
3420 {
3421 /*
3422 * Use the chunking protocol if we know the syslogger should be
3423 * catching stderr output, and we are not ourselves the syslogger.
3424 * Otherwise, just do a vanilla write to stderr.
3425 */
3428#ifdef WIN32
3429
3430 /*
3431 * In a win32 service environment, there is no usable stderr. Capture
3432 * anything going there and write it to the eventlog instead.
3433 *
3434 * If stderr redirection is active, it was OK to write to stderr above
3435 * because that's really a pipe to the syslogger process.
3436 */
3437 else if (pgwin32_is_service())
3438 write_eventlog(edata->elevel, buf.data, buf.len);
3439#endif
3440 else
3441 write_console(buf.data, buf.len);
3442 }
3443
3444 /* If in the syslogger process, try to write messages direct to file */
3445 if (MyBackendType == B_LOGGER)
3447
3448 /* No more need of the message formatted for stderr */
3449 pfree(buf.data);
3450}
3451
3452/*
3453 * Send data to the syslogger using the chunked protocol
3454 *
3455 * Note: when there are multiple backends writing into the syslogger pipe,
3456 * it's critical that each write go into the pipe indivisibly, and not
3457 * get interleaved with data from other processes. Fortunately, the POSIX
3458 * spec requires that writes to pipes be atomic so long as they are not
3459 * more than PIPE_BUF bytes long. So we divide long messages into chunks
3460 * that are no more than that length, and send one chunk per write() call.
3461 * The collector process knows how to reassemble the chunks.
3462 *
3463 * Because of the atomic write requirement, there are only two possible
3464 * results from write() here: -1 for failure, or the requested number of
3465 * bytes. There is not really anything we can do about a failure; retry would
3466 * probably be an infinite loop, and we can't even report the error usefully.
3467 * (There is noplace else we could send it!) So we might as well just ignore
3468 * the result from write(). However, on some platforms you get a compiler
3469 * warning from ignoring write()'s result, so do a little dance with casting
3470 * rc to void to shut up the compiler.
3471 */
3472void
3474{
3476 int fd = fileno(stderr);
3477 int rc;
3478
3479 Assert(len > 0);
3480
3481 p.proto.nuls[0] = p.proto.nuls[1] = '\0';
3482 p.proto.pid = MyProcPid;
3483 p.proto.flags = 0;
3486 else if (dest == LOG_DESTINATION_CSVLOG)
3488 else if (dest == LOG_DESTINATION_JSONLOG)
3490
3491 /* write all but the last chunk */
3492 while (len > PIPE_MAX_PAYLOAD)
3493 {
3494 /* no need to set PIPE_PROTO_IS_LAST yet */
3496 memcpy(p.proto.data, data, PIPE_MAX_PAYLOAD);
3498 (void) rc;
3501 }
3502
3503 /* write the last chunk */
3505 p.proto.len = len;
3506 memcpy(p.proto.data, data, len);
3507 rc = write(fd, &p, PIPE_HEADER_SIZE + len);
3508 (void) rc;
3509}
3510
3511
3512/*
3513 * Append a text string to the error report being built for the client.
3514 *
3515 * This is ordinarily identical to pq_sendstring(), but if we are in
3516 * error recursion trouble we skip encoding conversion, because of the
3517 * possibility that the problem is a failure in the encoding conversion
3518 * subsystem itself. Code elsewhere should ensure that the passed-in
3519 * strings will be plain 7-bit ASCII, and thus not in need of conversion,
3520 * in such cases. (In particular, we disable localization of error messages
3521 * to help ensure that's true.)
3522 */
3523static void
3525{
3528 else
3530}
3531
3532/*
3533 * Write error report to client
3534 */
3535static void
3537{
3538 StringInfoData msgbuf;
3539
3540 /*
3541 * We no longer support pre-3.0 FE/BE protocol, except here. If a client
3542 * tries to connect using an older protocol version, it's nice to send the
3543 * "protocol version not supported" error in a format the client
3544 * understands. If protocol hasn't been set yet, early in backend
3545 * startup, assume modern protocol.
3546 */
3548 {
3549 /* New style with separate fields */
3550 const char *sev;
3551 char tbuf[12];
3552
3553 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
3554 if (edata->elevel < ERROR)
3556 else
3558
3559 sev = error_severity(edata->elevel);
3560 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
3561 err_sendstring(&msgbuf, _(sev));
3563 err_sendstring(&msgbuf, sev);
3564
3565 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
3566 err_sendstring(&msgbuf, unpack_sql_state(edata->sqlerrcode));
3567
3568 /* M field is required per protocol, so always send something */
3570 if (edata->message)
3571 err_sendstring(&msgbuf, edata->message);
3572 else
3573 err_sendstring(&msgbuf, _("missing error text"));
3574
3575 if (edata->detail)
3576 {
3578 err_sendstring(&msgbuf, edata->detail);
3579 }
3580
3581 /* detail_log is intentionally not used here */
3582
3583 if (edata->hint)
3584 {
3586 err_sendstring(&msgbuf, edata->hint);
3587 }
3588
3589 if (edata->context)
3590 {
3591 pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
3592 err_sendstring(&msgbuf, edata->context);
3593 }
3594
3595 if (edata->schema_name)
3596 {
3598 err_sendstring(&msgbuf, edata->schema_name);
3599 }
3600
3601 if (edata->table_name)
3602 {
3604 err_sendstring(&msgbuf, edata->table_name);
3605 }
3606
3607 if (edata->column_name)
3608 {
3610 err_sendstring(&msgbuf, edata->column_name);
3611 }
3612
3613 if (edata->datatype_name)
3614 {
3616 err_sendstring(&msgbuf, edata->datatype_name);
3617 }
3618
3619 if (edata->constraint_name)
3620 {
3622 err_sendstring(&msgbuf, edata->constraint_name);
3623 }
3624
3625 if (edata->cursorpos > 0)
3626 {
3627 snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
3629 err_sendstring(&msgbuf, tbuf);
3630 }
3631
3632 if (edata->internalpos > 0)
3633 {
3634 snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
3636 err_sendstring(&msgbuf, tbuf);
3637 }
3638
3639 if (edata->internalquery)
3640 {
3642 err_sendstring(&msgbuf, edata->internalquery);
3643 }
3644
3645 if (edata->filename)
3646 {
3648 err_sendstring(&msgbuf, edata->filename);
3649 }
3650
3651 if (edata->lineno > 0)
3652 {
3653 snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
3655 err_sendstring(&msgbuf, tbuf);
3656 }
3657
3658 if (edata->funcname)
3659 {
3661 err_sendstring(&msgbuf, edata->funcname);
3662 }
3663
3664 pq_sendbyte(&msgbuf, '\0'); /* terminator */
3665
3666 pq_endmessage(&msgbuf);
3667 }
3668 else
3669 {
3670 /* Old style --- gin up a backwards-compatible message */
3672
3674
3675 appendStringInfo(&buf, "%s: ", _(error_severity(edata->elevel)));
3676
3677 if (edata->message)
3679 else
3680 appendStringInfoString(&buf, _("missing error text"));
3681
3682 appendStringInfoChar(&buf, '\n');
3683
3684 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
3685 pq_putmessage_v2((edata->elevel < ERROR) ? 'N' : 'E', buf.data, buf.len + 1);
3686
3687 pfree(buf.data);
3688 }
3689
3690 /*
3691 * This flush is normally not necessary, since postgres.c will flush out
3692 * waiting data when control returns to the main loop. But it seems best
3693 * to leave it here, so that the client has some clue what happened if the
3694 * backend dies before getting back to the main loop ... error/notice
3695 * messages should not be a performance-critical path anyway, so an extra
3696 * flush won't hurt much ...
3697 */
3698 pq_flush();
3699}
3700
3701
3702/*
3703 * Support routines for formatting error messages.
3704 */
3705
3706
3707/*
3708 * error_severity --- get string representing elevel
3709 *
3710 * The string is not localized here, but we mark the strings for translation
3711 * so that callers can invoke _() on the result.
3712 */
3713const char *
3715{
3716 const char *prefix;
3717
3718 switch (elevel)
3719 {
3720 case DEBUG1:
3721 case DEBUG2:
3722 case DEBUG3:
3723 case DEBUG4:
3724 case DEBUG5:
3725 prefix = gettext_noop("DEBUG");
3726 break;
3727 case LOG:
3728 case LOG_SERVER_ONLY:
3729 prefix = gettext_noop("LOG");
3730 break;
3731 case INFO:
3732 prefix = gettext_noop("INFO");
3733 break;
3734 case NOTICE:
3735 prefix = gettext_noop("NOTICE");
3736 break;
3737 case WARNING:
3739 prefix = gettext_noop("WARNING");
3740 break;
3741 case ERROR:
3742 prefix = gettext_noop("ERROR");
3743 break;
3744 case FATAL:
3745 prefix = gettext_noop("FATAL");
3746 break;
3747 case PANIC:
3748 prefix = gettext_noop("PANIC");
3749 break;
3750 default:
3751 prefix = "???";
3752 break;
3753 }
3754
3755 return prefix;
3756}
3757
3758
3759/*
3760 * append_with_tabs
3761 *
3762 * Append the string to the StringInfo buffer, inserting a tab after any
3763 * newline.
3764 */
3765static void
3767{
3768 char ch;
3769
3770 while ((ch = *str++) != '\0')
3771 {
3773 if (ch == '\n')
3775 }
3776}
3777
3778
3779/*
3780 * Write errors to stderr (or by equal means when stderr is
3781 * not available). Used before ereport/elog can be used
3782 * safely (memory context, GUC load etc)
3783 */
3784void
3785write_stderr(const char *fmt,...)
3786{
3787 va_list ap;
3788
3789#ifdef WIN32
3790 char errbuf[2048]; /* Arbitrary size? */
3791#endif
3792
3793 fmt = _(fmt);
3794
3795 va_start(ap, fmt);
3796#ifndef WIN32
3797 /* On Unix, we just fprintf to stderr */
3798 vfprintf(stderr, fmt, ap);
3799 fflush(stderr);
3800#else
3801 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
3802
3803 /*
3804 * On Win32, we print to stderr if running on a console, or write to
3805 * eventlog if running as a service
3806 */
3807 if (pgwin32_is_service()) /* Running as a service */
3808 {
3809 write_eventlog(ERROR, errbuf, strlen(errbuf));
3810 }
3811 else
3812 {
3813 /* Not running as service, write to stderr */
3814 write_console(errbuf, strlen(errbuf));
3815 fflush(stderr);
3816 }
3817#endif
3818 va_end(ap);
3819}
void ExceptionalCondition(const char *conditionName, const char *fileName, int lineNumber)
Definition: assert.c:30
int64 pgstat_get_my_query_id(void)
#define pg_attribute_format_arg(a)
Definition: c.h:231
#define pg_noinline
Definition: c.h:285
#define Min(x, y)
Definition: c.h:1004
#define pg_attribute_cold
Definition: c.h:310
#define gettext_noop(x)
Definition: c.h:1196
#define Max(x, y)
Definition: c.h:998
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1214
#define gettext(x)
Definition: c.h:1179
#define pg_unreachable()
Definition: c.h:331
#define unlikely(x)
Definition: c.h:403
#define lengthof(array)
Definition: c.h:788
#define MemSet(start, val, len)
Definition: c.h:1020
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:2350
int getinternalerrposition(void)
Definition: elog.c:1620
static bool should_output_to_client(int elevel)
Definition: elog.c:245
void assign_syslog_ident(const char *newval, void *extra)
Definition: elog.c:2318
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:2819
static const char * process_log_prefix_padding(const char *p, int *ppadding)
Definition: elog.c:2788
int err_generic_string(int field, const char *str)
Definition: elog.c:1537
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1184
void errsave_finish(struct Node *context, const char *filename, int lineno, const char *funcname)
Definition: elog.c:682
static char formatted_log_time[FORMATTED_TS_LEN]
Definition: elog.c:161
int internalerrquery(const char *query)
Definition: elog.c:1507
static char formatted_start_time[FORMATTED_TS_LEN]
Definition: elog.c:160
int internalerrposition(int cursorpos)
Definition: elog.c:1487
static void send_message_to_frontend(ErrorData *edata)
Definition: elog.c:3536
bool check_log_of_query(ErrorData *edata)
Definition: elog.c:2743
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1161
static void append_with_tabs(StringInfo buf, const char *str)
Definition: elog.c:3766
int geterrcode(void)
Definition: elog.c:1586
char * format_elog_string(const char *fmt,...)
Definition: elog.c:1662
int errhidestmt(bool hide_stmt)
Definition: elog.c:1436
bool errstart(int elevel, const char *domain)
Definition: elog.c:343
void EmitErrorReport(void)
Definition: elog.c:1695
bool syslog_split_messages
Definition: elog.c:114
static void FreeErrorDataContents(ErrorData *edata)
Definition: elog.c:1838
static int errordata_stack_depth
Definition: elog.c:148
char * GetErrorContextStack(void)
Definition: elog.c:2067
void DebugFileOpen(void)
Definition: elog.c:2119
static void err_sendstring(StringInfo buf, const char *str)
Definition: elog.c:3524
void FreeErrorData(ErrorData *edata)
Definition: elog.c:1826
void assign_backtrace_functions(const char *newval, void *extra)
Definition: elog.c:2236
const char * error_severity(int elevel)
Definition: elog.c:3714
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:1234
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:1207
int Log_error_verbosity
Definition: elog.c:109
void pg_re_throw(void)
Definition: elog.c:2012
int errcontext_msg(const char *fmt,...)
Definition: elog.c:1390
static int save_format_errnumber
Definition: elog.c:1649
bool check_backtrace_functions(char **newval, void **extra, GucSource source)
Definition: elog.c:2175
void pre_format_elog_string(int errnumber, const char *domain)
Definition: elog.c:1653
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:1343
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:1962
static void set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str)
Definition: elog.c:1573
char * get_formatted_start_time(void)
Definition: elog.c:2719
static bool matches_backtrace_functions(const char *funcname)
Definition: elog.c:826
ErrorData * CopyErrorData(void)
Definition: elog.c:1754
bool check_log_destination(char **newval, void **extra, GucSource source)
Definition: elog.c:2245
void FlushErrorState(void)
Definition: elog.c:1875
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1299
int errhint(const char *fmt,...)
Definition: elog.c:1321
static bool is_log_level_output(int elevel, int log_min_level)
Definition: elog.c:202
void ThrowErrorData(ErrorData *edata)
Definition: elog.c:1903
bool message_level_is_interesting(int elevel)
Definition: elog.c:273
void write_pipe_chunks(char *data, int len, int dest)
Definition: elog.c:3473
int errhidecontext(bool hide_ctx)
Definition: elog.c:1455
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:1603
static void send_message_to_server_log(ErrorData *edata)
Definition: elog.c:3233
char * Log_destination_string
Definition: elog.c:112
static void write_console(const char *line, int len)
Definition: elog.c:2591
#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:2766
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:1276
void write_stderr(const char *fmt,...)
Definition: elog.c:3785
int errmsg(const char *fmt,...)
Definition: elog.c:1071
void log_status_format(StringInfo buf, const char *format, ErrorData *edata)
Definition: elog.c:2828
char * get_formatted_log_time(void)
Definition: elog.c:2669
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:1471
#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:1364
int errdetail_log(const char *fmt,...)
Definition: elog.c:1255
char * unpack_sql_state(int sql_state)
Definition: elog.c:3213
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:1416
void reset_formatted_start_time(void)
Definition: elog.c:2707
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:1650
void assign_log_destination(const char *newval, void *extra)
Definition: elog.c:2309
@ PGERROR_VERBOSE
Definition: elog.h:474
@ PGERROR_DEFAULT
Definition: elog.h:473
#define LOG
Definition: elog.h:31
void(* emit_log_hook_type)(ErrorData *edata)
Definition: elog.h:464
#define PG_RE_THROW()
Definition: elog.h:405
#define DEBUG3
Definition: elog.h:28
#define LOG_SERVER_ONLY
Definition: elog.h:32
#define WARNING_CLIENT_ONLY
Definition: elog.h:38
#define FATAL
Definition: elog.h:41
#define WARNING
Definition: elog.h:36
#define LOG_DESTINATION_JSONLOG
Definition: elog.h:489
#define DEBUG2
Definition: elog.h:29
#define PGUNSIXBIT(val)
Definition: elog.h:54
#define PANIC
Definition: elog.h:42
#define DEBUG1
Definition: elog.h:30
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
#define NOTICE
Definition: elog.h:35
#define LOG_DESTINATION_SYSLOG
Definition: elog.h:486
#define LOG_DESTINATION_STDERR
Definition: elog.h:485
#define INFO
Definition: elog.h:34
#define ereport(elevel,...)
Definition: elog.h:150
#define LOG_DESTINATION_EVENTLOG
Definition: elog.h:487
#define DEBUG5
Definition: elog.h:26
#define LOG_DESTINATION_CSVLOG
Definition: elog.h:488
#define DEBUG4
Definition: elog.h:27
#define palloc_object(type)
Definition: fe_memutils.h:74
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:44
ProtocolVersion FrontendProtocol
Definition: globals.c:30
pid_t PostmasterPid
Definition: globals.c:106
volatile uint32 InterruptHoldoffCount
Definition: globals.c:43
int MyProcPid
Definition: globals.c:47
bool IsUnderPostmaster
Definition: globals.c:120
volatile uint32 CritSectionCount
Definition: globals.c:45
bool ExitOnAnyError
Definition: globals.c:123
struct Port * MyProcPort
Definition: globals.c:51
pg_time_t MyStartTime
Definition: globals.c:48
char OutputFileName[MAXPGPATH]
Definition: globals.c:79
void * guc_malloc(int elevel, size_t size)
Definition: guc.c:639
#define newval
#define GUC_check_errdetail
Definition: guc.h:505
GucSource
Definition: guc.h:112
char * event_source
Definition: guc_tables.c:526
int client_min_messages
Definition: guc_tables.c:541
int log_min_error_statement
Definition: guc_tables.c:539
static int syslog_facility
Definition: guc_tables.c:604
char * application_name
Definition: guc_tables.c:561
int log_min_messages
Definition: guc_tables.c:540
char * backtrace_functions
Definition: guc_tables.c:549
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:1084
int GetMessageEncoding(void)
Definition: mbutils.c:1309
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1746
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:400
char * pstrdup(const char *in)
Definition: mcxt.c:1759
void pfree(void *pointer)
Definition: mcxt.c:1594
void * palloc(Size size)
Definition: mcxt.c:1365
MemoryContext CurrentMemoryContext
Definition: mcxt.c:160
MemoryContext ErrorContext
Definition: mcxt.c:167
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
@ B_LOGGER
Definition: miscadmin.h:373
@ B_BG_WORKER
Definition: miscadmin.h:345
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:120
#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:58
@ DISCONNECT_NORMAL
Definition: pgstat.h:56
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:63
#define PG_DIAG_SCHEMA_NAME
Definition: postgres_ext.h:65
#define PG_DIAG_CONSTRAINT_NAME
Definition: postgres_ext.h:69
#define PG_DIAG_DATATYPE_NAME
Definition: postgres_ext.h:68
#define PG_DIAG_SOURCE_LINE
Definition: postgres_ext.h:71
#define PG_DIAG_STATEMENT_POSITION
Definition: postgres_ext.h:61
#define PG_DIAG_SOURCE_FILE
Definition: postgres_ext.h:70
#define PG_DIAG_MESSAGE_HINT
Definition: postgres_ext.h:60
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:57
#define PG_DIAG_SEVERITY_NONLOCALIZED
Definition: postgres_ext.h:56
#define PG_DIAG_TABLE_NAME
Definition: postgres_ext.h:66
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:58
#define PG_DIAG_COLUMN_NAME
Definition: postgres_ext.h:67
#define PG_DIAG_MESSAGE_DETAIL
Definition: postgres_ext.h:59
#define PG_DIAG_CONTEXT
Definition: postgres_ext.h:64
#define PG_DIAG_SEVERITY
Definition: postgres_ext.h:55
#define PG_DIAG_SOURCE_FUNCTION
Definition: postgres_ext.h:72
#define PG_DIAG_INTERNAL_POSITION
Definition: postgres_ext.h:62
bool redirection_done
Definition: postmaster.c:375
bool ClientAuthInProgress
Definition: postmaster.c:372
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:200
int pq_putmessage_v2(char msgtype, const char *s, size_t len)
Definition: pqcomm.c:1561
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h: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:548
char * psprintf(const char *fmt,...)
Definition: psprintf.c:43
PGPROC * MyProc
Definition: proc.c:66
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:179
LocalTransactionId lxid
Definition: proc.h:217
struct PGPROC::@128 vxid
ProcNumber procNumber
Definition: proc.h:212
int pid
Definition: proc.h:199
PGPROC * lockGroupLeader
Definition: proc.h:321
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:2744
int pgwin32_is_service(void)
int gettimeofday(struct timeval *tp, void *tzp)
TransactionId GetTopTransactionIdIfAny(void)
Definition: xact.c:441