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