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