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