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