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