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