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 cumulative stats system 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  free(syslog_ident);
1989  syslog_ident = strdup(ident);
1990  /* if the strdup fails, we will cope in write_syslog() */
1991  syslog_facility = facility;
1992  }
1993 }
1994 
1995 
1996 /*
1997  * Write a message line to syslog
1998  */
1999 static void
2000 write_syslog(int level, const char *line)
2001 {
2002  static unsigned long seq = 0;
2003 
2004  int len;
2005  const char *nlpos;
2006 
2007  /* Open syslog connection if not done yet */
2008  if (!openlog_done)
2009  {
2010  openlog(syslog_ident ? syslog_ident : "postgres",
2011  LOG_PID | LOG_NDELAY | LOG_NOWAIT,
2012  syslog_facility);
2013  openlog_done = true;
2014  }
2015 
2016  /*
2017  * We add a sequence number to each log message to suppress "same"
2018  * messages.
2019  */
2020  seq++;
2021 
2022  /*
2023  * Our problem here is that many syslog implementations don't handle long
2024  * messages in an acceptable manner. While this function doesn't help that
2025  * fact, it does work around by splitting up messages into smaller pieces.
2026  *
2027  * We divide into multiple syslog() calls if message is too long or if the
2028  * message contains embedded newline(s).
2029  */
2030  len = strlen(line);
2031  nlpos = strchr(line, '\n');
2032  if (syslog_split_messages && (len > PG_SYSLOG_LIMIT || nlpos != NULL))
2033  {
2034  int chunk_nr = 0;
2035 
2036  while (len > 0)
2037  {
2038  char buf[PG_SYSLOG_LIMIT + 1];
2039  int buflen;
2040  int i;
2041 
2042  /* if we start at a newline, move ahead one char */
2043  if (line[0] == '\n')
2044  {
2045  line++;
2046  len--;
2047  /* we need to recompute the next newline's position, too */
2048  nlpos = strchr(line, '\n');
2049  continue;
2050  }
2051 
2052  /* copy one line, or as much as will fit, to buf */
2053  if (nlpos != NULL)
2054  buflen = nlpos - line;
2055  else
2056  buflen = len;
2057  buflen = Min(buflen, PG_SYSLOG_LIMIT);
2058  memcpy(buf, line, buflen);
2059  buf[buflen] = '\0';
2060 
2061  /* trim to multibyte letter boundary */
2062  buflen = pg_mbcliplen(buf, buflen, buflen);
2063  if (buflen <= 0)
2064  return;
2065  buf[buflen] = '\0';
2066 
2067  /* already word boundary? */
2068  if (line[buflen] != '\0' &&
2069  !isspace((unsigned char) line[buflen]))
2070  {
2071  /* try to divide at word boundary */
2072  i = buflen - 1;
2073  while (i > 0 && !isspace((unsigned char) buf[i]))
2074  i--;
2075 
2076  if (i > 0) /* else couldn't divide word boundary */
2077  {
2078  buflen = i;
2079  buf[i] = '\0';
2080  }
2081  }
2082 
2083  chunk_nr++;
2084 
2086  syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
2087  else
2088  syslog(level, "[%d] %s", chunk_nr, buf);
2089 
2090  line += buflen;
2091  len -= buflen;
2092  }
2093  }
2094  else
2095  {
2096  /* message short enough */
2098  syslog(level, "[%lu] %s", seq, line);
2099  else
2100  syslog(level, "%s", line);
2101  }
2102 }
2103 #endif /* HAVE_SYSLOG */
2104 
2105 #ifdef WIN32
2106 /*
2107  * Get the PostgreSQL equivalent of the Windows ANSI code page. "ANSI" system
2108  * interfaces (e.g. CreateFileA()) expect string arguments in this encoding.
2109  * Every process in a given system will find the same value at all times.
2110  */
2111 static int
2112 GetACPEncoding(void)
2113 {
2114  static int encoding = -2;
2115 
2116  if (encoding == -2)
2117  encoding = pg_codepage_to_encoding(GetACP());
2118 
2119  return encoding;
2120 }
2121 
2122 /*
2123  * Write a message line to the windows event log
2124  */
2125 static void
2126 write_eventlog(int level, const char *line, int len)
2127 {
2128  WCHAR *utf16;
2129  int eventlevel = EVENTLOG_ERROR_TYPE;
2130  static HANDLE evtHandle = INVALID_HANDLE_VALUE;
2131 
2132  if (evtHandle == INVALID_HANDLE_VALUE)
2133  {
2134  evtHandle = RegisterEventSource(NULL,
2136  if (evtHandle == NULL)
2137  {
2138  evtHandle = INVALID_HANDLE_VALUE;
2139  return;
2140  }
2141  }
2142 
2143  switch (level)
2144  {
2145  case DEBUG5:
2146  case DEBUG4:
2147  case DEBUG3:
2148  case DEBUG2:
2149  case DEBUG1:
2150  case LOG:
2151  case LOG_SERVER_ONLY:
2152  case INFO:
2153  case NOTICE:
2154  eventlevel = EVENTLOG_INFORMATION_TYPE;
2155  break;
2156  case WARNING:
2157  case WARNING_CLIENT_ONLY:
2158  eventlevel = EVENTLOG_WARNING_TYPE;
2159  break;
2160  case ERROR:
2161  case FATAL:
2162  case PANIC:
2163  default:
2164  eventlevel = EVENTLOG_ERROR_TYPE;
2165  break;
2166  }
2167 
2168  /*
2169  * If message character encoding matches the encoding expected by
2170  * ReportEventA(), call it to avoid the hazards of conversion. Otherwise,
2171  * try to convert the message to UTF16 and write it with ReportEventW().
2172  * Fall back on ReportEventA() if conversion failed.
2173  *
2174  * Since we palloc the structure required for conversion, also fall
2175  * through to writing unconverted if we have not yet set up
2176  * CurrentMemoryContext.
2177  *
2178  * Also verify that we are not on our way into error recursion trouble due
2179  * to error messages thrown deep inside pgwin32_message_to_UTF16().
2180  */
2181  if (!in_error_recursion_trouble() &&
2182  CurrentMemoryContext != NULL &&
2183  GetMessageEncoding() != GetACPEncoding())
2184  {
2185  utf16 = pgwin32_message_to_UTF16(line, len, NULL);
2186  if (utf16)
2187  {
2188  ReportEventW(evtHandle,
2189  eventlevel,
2190  0,
2191  0, /* All events are Id 0 */
2192  NULL,
2193  1,
2194  0,
2195  (LPCWSTR *) &utf16,
2196  NULL);
2197  /* XXX Try ReportEventA() when ReportEventW() fails? */
2198 
2199  pfree(utf16);
2200  return;
2201  }
2202  }
2203  ReportEventA(evtHandle,
2204  eventlevel,
2205  0,
2206  0, /* All events are Id 0 */
2207  NULL,
2208  1,
2209  0,
2210  &line,
2211  NULL);
2212 }
2213 #endif /* WIN32 */
2214 
2215 static void
2216 write_console(const char *line, int len)
2217 {
2218  int rc;
2219 
2220 #ifdef WIN32
2221 
2222  /*
2223  * Try to convert the message to UTF16 and write it with WriteConsoleW().
2224  * Fall back on write() if anything fails.
2225  *
2226  * In contrast to write_eventlog(), don't skip straight to write() based
2227  * on the applicable encodings. Unlike WriteConsoleW(), write() depends
2228  * on the suitability of the console output code page. Since we put
2229  * stderr into binary mode in SubPostmasterMain(), write() skips the
2230  * necessary translation anyway.
2231  *
2232  * WriteConsoleW() will fail if stderr is redirected, so just fall through
2233  * to writing unconverted to the logfile in this case.
2234  *
2235  * Since we palloc the structure required for conversion, also fall
2236  * through to writing unconverted if we have not yet set up
2237  * CurrentMemoryContext.
2238  */
2239  if (!in_error_recursion_trouble() &&
2240  !redirection_done &&
2241  CurrentMemoryContext != NULL)
2242  {
2243  WCHAR *utf16;
2244  int utf16len;
2245 
2246  utf16 = pgwin32_message_to_UTF16(line, len, &utf16len);
2247  if (utf16 != NULL)
2248  {
2249  HANDLE stdHandle;
2250  DWORD written;
2251 
2252  stdHandle = GetStdHandle(STD_ERROR_HANDLE);
2253  if (WriteConsoleW(stdHandle, utf16, utf16len, &written, NULL))
2254  {
2255  pfree(utf16);
2256  return;
2257  }
2258 
2259  /*
2260  * In case WriteConsoleW() failed, fall back to writing the
2261  * message unconverted.
2262  */
2263  pfree(utf16);
2264  }
2265  }
2266 #else
2267 
2268  /*
2269  * Conversion on non-win32 platforms is not implemented yet. It requires
2270  * non-throw version of pg_do_encoding_conversion(), that converts
2271  * unconvertible characters to '?' without errors.
2272  *
2273  * XXX: We have a no-throw version now. It doesn't convert to '?' though.
2274  */
2275 #endif
2276 
2277  /*
2278  * We ignore any error from write() here. We have no useful way to report
2279  * it ... certainly whining on stderr isn't likely to be productive.
2280  */
2281  rc = write(fileno(stderr), line, len);
2282  (void) rc;
2283 }
2284 
2285 /*
2286  * get_formatted_log_time -- compute and get the log timestamp.
2287  *
2288  * The timestamp is computed if not set yet, so as it is kept consistent
2289  * among all the log destinations that require it to be consistent. Note
2290  * that the computed timestamp is returned in a static buffer, not
2291  * palloc()'d.
2292  */
2293 char *
2295 {
2296  pg_time_t stamp_time;
2297  char msbuf[13];
2298 
2299  /* leave if already computed */
2300  if (formatted_log_time[0] != '\0')
2301  return formatted_log_time;
2302 
2303  if (!saved_timeval_set)
2304  {
2305  gettimeofday(&saved_timeval, NULL);
2306  saved_timeval_set = true;
2307  }
2308 
2309  stamp_time = (pg_time_t) saved_timeval.tv_sec;
2310 
2311  /*
2312  * Note: we expect that guc.c will ensure that log_timezone is set up (at
2313  * least with a minimal GMT value) before Log_line_prefix can become
2314  * nonempty or CSV mode can be selected.
2315  */
2317  /* leave room for milliseconds... */
2318  "%Y-%m-%d %H:%M:%S %Z",
2319  pg_localtime(&stamp_time, log_timezone));
2320 
2321  /* 'paste' milliseconds into place... */
2322  sprintf(msbuf, ".%03d", (int) (saved_timeval.tv_usec / 1000));
2323  memcpy(formatted_log_time + 19, msbuf, 4);
2324 
2325  return formatted_log_time;
2326 }
2327 
2328 /*
2329  * reset_formatted_start_time -- reset the start timestamp
2330  */
2331 void
2333 {
2334  formatted_start_time[0] = '\0';
2335 }
2336 
2337 /*
2338  * get_formatted_start_time -- compute and get the start timestamp.
2339  *
2340  * The timestamp is computed if not set yet. Note that the computed
2341  * timestamp is returned in a static buffer, not palloc()'d.
2342  */
2343 char *
2345 {
2346  pg_time_t stamp_time = (pg_time_t) MyStartTime;
2347 
2348  /* leave if already computed */
2349  if (formatted_start_time[0] != '\0')
2350  return formatted_start_time;
2351 
2352  /*
2353  * Note: we expect that guc.c will ensure that log_timezone is set up (at
2354  * least with a minimal GMT value) before Log_line_prefix can become
2355  * nonempty or CSV mode can be selected.
2356  */
2358  "%Y-%m-%d %H:%M:%S %Z",
2359  pg_localtime(&stamp_time, log_timezone));
2360 
2361  return formatted_start_time;
2362 }
2363 
2364 /*
2365  * check_log_of_query -- check if a query can be logged
2366  */
2367 bool
2369 {
2370  /* log required? */
2372  return false;
2373 
2374  /* query log wanted? */
2375  if (edata->hide_stmt)
2376  return false;
2377 
2378  /* query string available? */
2379  if (debug_query_string == NULL)
2380  return false;
2381 
2382  return true;
2383 }
2384 
2385 /*
2386  * get_backend_type_for_log -- backend type for log entries
2387  *
2388  * Returns a pointer to a static buffer, not palloc()'d.
2389  */
2390 const char *
2392 {
2393  const char *backend_type_str;
2394 
2395  if (MyProcPid == PostmasterPid)
2396  backend_type_str = "postmaster";
2397  else if (MyBackendType == B_BG_WORKER)
2398  backend_type_str = MyBgworkerEntry->bgw_type;
2399  else
2400  backend_type_str = GetBackendTypeDesc(MyBackendType);
2401 
2402  return backend_type_str;
2403 }
2404 
2405 /*
2406  * process_log_prefix_padding --- helper function for processing the format
2407  * string in log_line_prefix
2408  *
2409  * Note: This function returns NULL if it finds something which
2410  * it deems invalid in the format string.
2411  */
2412 static const char *
2413 process_log_prefix_padding(const char *p, int *ppadding)
2414 {
2415  int paddingsign = 1;
2416  int padding = 0;
2417 
2418  if (*p == '-')
2419  {
2420  p++;
2421 
2422  if (*p == '\0') /* Did the buf end in %- ? */
2423  return NULL;
2424  paddingsign = -1;
2425  }
2426 
2427  /* generate an int version of the numerical string */
2428  while (*p >= '0' && *p <= '9')
2429  padding = padding * 10 + (*p++ - '0');
2430 
2431  /* format is invalid if it ends with the padding number */
2432  if (*p == '\0')
2433  return NULL;
2434 
2435  padding *= paddingsign;
2436  *ppadding = padding;
2437  return p;
2438 }
2439 
2440 /*
2441  * Format tag info for log lines; append to the provided buffer.
2442  */
2443 static void
2445 {
2446  /* static counter for line numbers */
2447  static long log_line_number = 0;
2448 
2449  /* has counter been reset in current process? */
2450  static int log_my_pid = 0;
2451  int padding;
2452  const char *p;
2453 
2454  /*
2455  * This is one of the few places where we'd rather not inherit a static
2456  * variable's value from the postmaster. But since we will, reset it when
2457  * MyProcPid changes. MyStartTime also changes when MyProcPid does, so
2458  * reset the formatted start timestamp too.
2459  */
2460  if (log_my_pid != MyProcPid)
2461  {
2462  log_line_number = 0;
2463  log_my_pid = MyProcPid;
2465  }
2466  log_line_number++;
2467 
2468  if (Log_line_prefix == NULL)
2469  return; /* in case guc hasn't run yet */
2470 
2471  for (p = Log_line_prefix; *p != '\0'; p++)
2472  {
2473  if (*p != '%')
2474  {
2475  /* literal char, just copy */
2477  continue;
2478  }
2479 
2480  /* must be a '%', so skip to the next char */
2481  p++;
2482  if (*p == '\0')
2483  break; /* format error - ignore it */
2484  else if (*p == '%')
2485  {
2486  /* string contains %% */
2487  appendStringInfoChar(buf, '%');
2488  continue;
2489  }
2490 
2491 
2492  /*
2493  * Process any formatting which may exist after the '%'. Note that
2494  * process_log_prefix_padding moves p past the padding number if it
2495  * exists.
2496  *
2497  * Note: Since only '-', '0' to '9' are valid formatting characters we
2498  * can do a quick check here to pre-check for formatting. If the char
2499  * is not formatting then we can skip a useless function call.
2500  *
2501  * Further note: At least on some platforms, passing %*s rather than
2502  * %s to appendStringInfo() is substantially slower, so many of the
2503  * cases below avoid doing that unless non-zero padding is in fact
2504  * specified.
2505  */
2506  if (*p > '9')
2507  padding = 0;
2508  else if ((p = process_log_prefix_padding(p, &padding)) == NULL)
2509  break;
2510 
2511  /* process the option */
2512  switch (*p)
2513  {
2514  case 'a':
2515  if (MyProcPort)
2516  {
2517  const char *appname = application_name;
2518 
2519  if (appname == NULL || *appname == '\0')
2520  appname = _("[unknown]");
2521  if (padding != 0)
2522  appendStringInfo(buf, "%*s", padding, appname);
2523  else
2524  appendStringInfoString(buf, appname);
2525  }
2526  else if (padding != 0)
2528  padding > 0 ? padding : -padding);
2529 
2530  break;
2531  case 'b':
2532  {
2533  const char *backend_type_str = get_backend_type_for_log();
2534 
2535  if (padding != 0)
2536  appendStringInfo(buf, "%*s", padding, backend_type_str);
2537  else
2538  appendStringInfoString(buf, backend_type_str);
2539  break;
2540  }
2541  case 'u':
2542  if (MyProcPort)
2543  {
2544  const char *username = MyProcPort->user_name;
2545 
2546  if (username == NULL || *username == '\0')
2547  username = _("[unknown]");
2548  if (padding != 0)
2549  appendStringInfo(buf, "%*s", padding, username);
2550  else
2552  }
2553  else if (padding != 0)
2555  padding > 0 ? padding : -padding);
2556  break;
2557  case 'd':
2558  if (MyProcPort)
2559  {
2560  const char *dbname = MyProcPort->database_name;
2561 
2562  if (dbname == NULL || *dbname == '\0')
2563  dbname = _("[unknown]");
2564  if (padding != 0)
2565  appendStringInfo(buf, "%*s", padding, dbname);
2566  else
2568  }
2569  else if (padding != 0)
2571  padding > 0 ? padding : -padding);
2572  break;
2573  case 'c':
2574  if (padding != 0)
2575  {
2576  char strfbuf[128];
2577 
2578  snprintf(strfbuf, sizeof(strfbuf) - 1, "%lx.%x",
2579  (long) (MyStartTime), MyProcPid);
2580  appendStringInfo(buf, "%*s", padding, strfbuf);
2581  }
2582  else
2583  appendStringInfo(buf, "%lx.%x", (long) (MyStartTime), MyProcPid);
2584  break;
2585  case 'p':
2586  if (padding != 0)
2587  appendStringInfo(buf, "%*d", padding, MyProcPid);
2588  else
2589  appendStringInfo(buf, "%d", MyProcPid);
2590  break;
2591 
2592  case 'P':
2593  if (MyProc)
2594  {
2595  PGPROC *leader = MyProc->lockGroupLeader;
2596 
2597  /*
2598  * Show the leader only for active parallel workers. This
2599  * leaves out the leader of a parallel group.
2600  */
2601  if (leader == NULL || leader->pid == MyProcPid)
2603  padding > 0 ? padding : -padding);
2604  else if (padding != 0)
2605  appendStringInfo(buf, "%*d", padding, leader->pid);
2606  else
2607  appendStringInfo(buf, "%d", leader->pid);
2608  }
2609  else if (padding != 0)
2611  padding > 0 ? padding : -padding);
2612  break;
2613 
2614  case 'l':
2615  if (padding != 0)
2616  appendStringInfo(buf, "%*ld", padding, log_line_number);
2617  else
2618  appendStringInfo(buf, "%ld", log_line_number);
2619  break;
2620  case 'm':
2621  /* force a log timestamp reset */
2622  formatted_log_time[0] = '\0';
2623  (void) get_formatted_log_time();
2624 
2625  if (padding != 0)
2626  appendStringInfo(buf, "%*s", padding, formatted_log_time);
2627  else
2629  break;
2630  case 't':
2631  {
2632  pg_time_t stamp_time = (pg_time_t) time(NULL);
2633  char strfbuf[128];
2634 
2635  pg_strftime(strfbuf, sizeof(strfbuf),
2636  "%Y-%m-%d %H:%M:%S %Z",
2637  pg_localtime(&stamp_time, log_timezone));
2638  if (padding != 0)
2639  appendStringInfo(buf, "%*s", padding, strfbuf);
2640  else
2641  appendStringInfoString(buf, strfbuf);
2642  }
2643  break;
2644  case 'n':
2645  {
2646  char strfbuf[128];
2647 
2648  if (!saved_timeval_set)
2649  {
2650  gettimeofday(&saved_timeval, NULL);
2651  saved_timeval_set = true;
2652  }
2653 
2654  snprintf(strfbuf, sizeof(strfbuf), "%ld.%03d",
2655  (long) saved_timeval.tv_sec,
2656  (int) (saved_timeval.tv_usec / 1000));
2657 
2658  if (padding != 0)
2659  appendStringInfo(buf, "%*s", padding, strfbuf);
2660  else
2661  appendStringInfoString(buf, strfbuf);
2662  }
2663  break;
2664  case 's':
2665  {
2667 
2668  if (padding != 0)
2669  appendStringInfo(buf, "%*s", padding, start_time);
2670  else
2672  }
2673  break;
2674  case 'i':
2675  if (MyProcPort)
2676  {
2677  const char *psdisp;
2678  int displen;
2679 
2680  psdisp = get_ps_display(&displen);
2681  if (padding != 0)
2682  appendStringInfo(buf, "%*s", padding, psdisp);
2683  else
2684  appendBinaryStringInfo(buf, psdisp, displen);
2685  }
2686  else if (padding != 0)
2688  padding > 0 ? padding : -padding);
2689  break;
2690  case 'r':
2692  {
2693  if (padding != 0)
2694  {
2695  if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
2696  {
2697  /*
2698  * This option is slightly special as the port
2699  * number may be appended onto the end. Here we
2700  * need to build 1 string which contains the
2701  * remote_host and optionally the remote_port (if
2702  * set) so we can properly align the string.
2703  */
2704 
2705  char *hostport;
2706 
2707  hostport = psprintf("%s(%s)", MyProcPort->remote_host, MyProcPort->remote_port);
2708  appendStringInfo(buf, "%*s", padding, hostport);
2709  pfree(hostport);
2710  }
2711  else
2712  appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
2713  }
2714  else
2715  {
2716  /* padding is 0, so we don't need a temp buffer */
2718  if (MyProcPort->remote_port &&
2719  MyProcPort->remote_port[0] != '\0')
2720  appendStringInfo(buf, "(%s)",
2722  }
2723  }
2724  else if (padding != 0)
2726  padding > 0 ? padding : -padding);
2727  break;
2728  case 'h':
2730  {
2731  if (padding != 0)
2732  appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
2733  else
2735  }
2736  else if (padding != 0)
2738  padding > 0 ? padding : -padding);
2739  break;
2740  case 'q':
2741  /* in postmaster and friends, stop if %q is seen */
2742  /* in a backend, just ignore */
2743  if (MyProcPort == NULL)
2744  return;
2745  break;
2746  case 'v':
2747  /* keep VXID format in sync with lockfuncs.c */
2748  if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
2749  {
2750  if (padding != 0)
2751  {
2752  char strfbuf[128];
2753 
2754  snprintf(strfbuf, sizeof(strfbuf) - 1, "%d/%u",
2756  appendStringInfo(buf, "%*s", padding, strfbuf);
2757  }
2758  else
2760  }
2761  else if (padding != 0)
2763  padding > 0 ? padding : -padding);
2764  break;
2765  case 'x':
2766  if (padding != 0)
2767  appendStringInfo(buf, "%*u", padding, GetTopTransactionIdIfAny());
2768  else
2770  break;
2771  case 'e':
2772  if (padding != 0)
2773  appendStringInfo(buf, "%*s", padding, unpack_sql_state(edata->sqlerrcode));
2774  else
2776  break;
2777  case 'Q':
2778  if (padding != 0)
2779  appendStringInfo(buf, "%*lld", padding,
2780  (long long) pgstat_get_my_query_id());
2781  else
2782  appendStringInfo(buf, "%lld",
2783  (long long) pgstat_get_my_query_id());
2784  break;
2785  default:
2786  /* format error - ignore it */
2787  break;
2788  }
2789  }
2790 }
2791 
2792 /*
2793  * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
2794  * static buffer.
2795  */
2796 char *
2797 unpack_sql_state(int sql_state)
2798 {
2799  static char buf[12];
2800  int i;
2801 
2802  for (i = 0; i < 5; i++)
2803  {
2804  buf[i] = PGUNSIXBIT(sql_state);
2805  sql_state >>= 6;
2806  }
2807 
2808  buf[i] = '\0';
2809  return buf;
2810 }
2811 
2812 
2813 /*
2814  * Write error report to server's log
2815  */
2816 static void
2818 {
2820  bool fallback_to_stderr = false;
2821 
2822  initStringInfo(&buf);
2823 
2824  saved_timeval_set = false;
2825  formatted_log_time[0] = '\0';
2826 
2827  log_line_prefix(&buf, edata);
2828  appendStringInfo(&buf, "%s: ", _(error_severity(edata->elevel)));
2829 
2831  appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
2832 
2833  if (edata->message)
2834  append_with_tabs(&buf, edata->message);
2835  else
2836  append_with_tabs(&buf, _("missing error text"));
2837 
2838  if (edata->cursorpos > 0)
2839  appendStringInfo(&buf, _(" at character %d"),
2840  edata->cursorpos);
2841  else if (edata->internalpos > 0)
2842  appendStringInfo(&buf, _(" at character %d"),
2843  edata->internalpos);
2844 
2845  appendStringInfoChar(&buf, '\n');
2846 
2848  {
2849  if (edata->detail_log)
2850  {
2851  log_line_prefix(&buf, edata);
2852  appendStringInfoString(&buf, _("DETAIL: "));
2853  append_with_tabs(&buf, edata->detail_log);
2854  appendStringInfoChar(&buf, '\n');
2855  }
2856  else if (edata->detail)
2857  {
2858  log_line_prefix(&buf, edata);
2859  appendStringInfoString(&buf, _("DETAIL: "));
2860  append_with_tabs(&buf, edata->detail);
2861  appendStringInfoChar(&buf, '\n');
2862  }
2863  if (edata->hint)
2864  {
2865  log_line_prefix(&buf, edata);
2866  appendStringInfoString(&buf, _("HINT: "));
2867  append_with_tabs(&buf, edata->hint);
2868  appendStringInfoChar(&buf, '\n');
2869  }
2870  if (edata->internalquery)
2871  {
2872  log_line_prefix(&buf, edata);
2873  appendStringInfoString(&buf, _("QUERY: "));
2875  appendStringInfoChar(&buf, '\n');
2876  }
2877  if (edata->context && !edata->hide_ctx)
2878  {
2879  log_line_prefix(&buf, edata);
2880  appendStringInfoString(&buf, _("CONTEXT: "));
2881  append_with_tabs(&buf, edata->context);
2882  appendStringInfoChar(&buf, '\n');
2883  }
2885  {
2886  /* assume no newlines in funcname or filename... */
2887  if (edata->funcname && edata->filename)
2888  {
2889  log_line_prefix(&buf, edata);
2890  appendStringInfo(&buf, _("LOCATION: %s, %s:%d\n"),
2891  edata->funcname, edata->filename,
2892  edata->lineno);
2893  }
2894  else if (edata->filename)
2895  {
2896  log_line_prefix(&buf, edata);
2897  appendStringInfo(&buf, _("LOCATION: %s:%d\n"),
2898  edata->filename, edata->lineno);
2899  }
2900  }
2901  if (edata->backtrace)
2902  {
2903  log_line_prefix(&buf, edata);
2904  appendStringInfoString(&buf, _("BACKTRACE: "));
2905  append_with_tabs(&buf, edata->backtrace);
2906  appendStringInfoChar(&buf, '\n');
2907  }
2908  }
2909 
2910  /*
2911  * If the user wants the query that generated this error logged, do it.
2912  */
2913  if (check_log_of_query(edata))
2914  {
2915  log_line_prefix(&buf, edata);
2916  appendStringInfoString(&buf, _("STATEMENT: "));
2918  appendStringInfoChar(&buf, '\n');
2919  }
2920 
2921 #ifdef HAVE_SYSLOG
2922  /* Write to syslog, if enabled */
2924  {
2925  int syslog_level;
2926 
2927  switch (edata->elevel)
2928  {
2929  case DEBUG5:
2930  case DEBUG4:
2931  case DEBUG3:
2932  case DEBUG2:
2933  case DEBUG1:
2934  syslog_level = LOG_DEBUG;
2935  break;
2936  case LOG:
2937  case LOG_SERVER_ONLY:
2938  case INFO:
2939  syslog_level = LOG_INFO;
2940  break;
2941  case NOTICE:
2942  case WARNING:
2943  case WARNING_CLIENT_ONLY:
2944  syslog_level = LOG_NOTICE;
2945  break;
2946  case ERROR:
2947  syslog_level = LOG_WARNING;
2948  break;
2949  case FATAL:
2950  syslog_level = LOG_ERR;
2951  break;
2952  case PANIC:
2953  default:
2954  syslog_level = LOG_CRIT;
2955  break;
2956  }
2957 
2958  write_syslog(syslog_level, buf.data);
2959  }
2960 #endif /* HAVE_SYSLOG */
2961 
2962 #ifdef WIN32
2963  /* Write to eventlog, if enabled */
2965  {
2966  write_eventlog(edata->elevel, buf.data, buf.len);
2967  }
2968 #endif /* WIN32 */
2969 
2970  /* Write to csvlog, if enabled */
2972  {
2973  /*
2974  * Send CSV data if it's safe to do so (syslogger doesn't need the
2975  * pipe). If this is not possible, fallback to an entry written to
2976  * stderr.
2977  */
2979  write_csvlog(edata);
2980  else
2981  fallback_to_stderr = true;
2982  }
2983 
2984  /* Write to JSON log, if enabled */
2986  {
2987  /*
2988  * Send JSON data if it's safe to do so (syslogger doesn't need the
2989  * pipe). If this is not possible, fallback to an entry written to
2990  * stderr.
2991  */
2993  {
2994  write_jsonlog(edata);
2995  }
2996  else
2997  fallback_to_stderr = true;
2998  }
2999 
3000  /*
3001  * Write to stderr, if enabled or if required because of a previous
3002  * limitation.
3003  */
3006  fallback_to_stderr)
3007  {
3008  /*
3009  * Use the chunking protocol if we know the syslogger should be
3010  * catching stderr output, and we are not ourselves the syslogger.
3011  * Otherwise, just do a vanilla write to stderr.
3012  */
3015 #ifdef WIN32
3016 
3017  /*
3018  * In a win32 service environment, there is no usable stderr. Capture
3019  * anything going there and write it to the eventlog instead.
3020  *
3021  * If stderr redirection is active, it was OK to write to stderr above
3022  * because that's really a pipe to the syslogger process.
3023  */
3024  else if (pgwin32_is_service())
3025  write_eventlog(edata->elevel, buf.data, buf.len);
3026 #endif
3027  else
3028  write_console(buf.data, buf.len);
3029  }
3030 
3031  /* If in the syslogger process, try to write messages direct to file */
3032  if (MyBackendType == B_LOGGER)
3034 
3035  /* No more need of the message formatted for stderr */
3036  pfree(buf.data);
3037 }
3038 
3039 /*
3040  * Send data to the syslogger using the chunked protocol
3041  *
3042  * Note: when there are multiple backends writing into the syslogger pipe,
3043  * it's critical that each write go into the pipe indivisibly, and not
3044  * get interleaved with data from other processes. Fortunately, the POSIX
3045  * spec requires that writes to pipes be atomic so long as they are not
3046  * more than PIPE_BUF bytes long. So we divide long messages into chunks
3047  * that are no more than that length, and send one chunk per write() call.
3048  * The collector process knows how to reassemble the chunks.
3049  *
3050  * Because of the atomic write requirement, there are only two possible
3051  * results from write() here: -1 for failure, or the requested number of
3052  * bytes. There is not really anything we can do about a failure; retry would
3053  * probably be an infinite loop, and we can't even report the error usefully.
3054  * (There is noplace else we could send it!) So we might as well just ignore
3055  * the result from write(). However, on some platforms you get a compiler
3056  * warning from ignoring write()'s result, so do a little dance with casting
3057  * rc to void to shut up the compiler.
3058  */
3059 void
3060 write_pipe_chunks(char *data, int len, int dest)
3061 {
3062  PipeProtoChunk p;
3063  int fd = fileno(stderr);
3064  int rc;
3065 
3066  Assert(len > 0);
3067 
3068  p.proto.nuls[0] = p.proto.nuls[1] = '\0';
3069  p.proto.pid = MyProcPid;
3070  p.proto.flags = 0;
3073  else if (dest == LOG_DESTINATION_CSVLOG)
3075  else if (dest == LOG_DESTINATION_JSONLOG)
3077 
3078  /* write all but the last chunk */
3079  while (len > PIPE_MAX_PAYLOAD)
3080  {
3081  /* no need to set PIPE_PROTO_IS_LAST yet */
3083  memcpy(p.proto.data, data, PIPE_MAX_PAYLOAD);
3085  (void) rc;
3087  len -= PIPE_MAX_PAYLOAD;
3088  }
3089 
3090  /* write the last chunk */
3092  p.proto.len = len;
3093  memcpy(p.proto.data, data, len);
3094  rc = write(fd, &p, PIPE_HEADER_SIZE + len);
3095  (void) rc;
3096 }
3097 
3098 
3099 /*
3100  * Append a text string to the error report being built for the client.
3101  *
3102  * This is ordinarily identical to pq_sendstring(), but if we are in
3103  * error recursion trouble we skip encoding conversion, because of the
3104  * possibility that the problem is a failure in the encoding conversion
3105  * subsystem itself. Code elsewhere should ensure that the passed-in
3106  * strings will be plain 7-bit ASCII, and thus not in need of conversion,
3107  * in such cases. (In particular, we disable localization of error messages
3108  * to help ensure that's true.)
3109  */
3110 static void
3112 {
3115  else
3116  pq_sendstring(buf, str);
3117 }
3118 
3119 /*
3120  * Write error report to client
3121  */
3122 static void
3124 {
3125  StringInfoData msgbuf;
3126 
3127  /*
3128  * We no longer support pre-3.0 FE/BE protocol, except here. If a client
3129  * tries to connect using an older protocol version, it's nice to send the
3130  * "protocol version not supported" error in a format the client
3131  * understands. If protocol hasn't been set yet, early in backend
3132  * startup, assume modern protocol.
3133  */
3135  {
3136  /* New style with separate fields */
3137  const char *sev;
3138  char tbuf[12];
3139 
3140  /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
3141  pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
3142 
3143  sev = error_severity(edata->elevel);
3144  pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
3145  err_sendstring(&msgbuf, _(sev));
3147  err_sendstring(&msgbuf, sev);
3148 
3149  pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
3150  err_sendstring(&msgbuf, unpack_sql_state(edata->sqlerrcode));
3151 
3152  /* M field is required per protocol, so always send something */
3154  if (edata->message)
3155  err_sendstring(&msgbuf, edata->message);
3156  else
3157  err_sendstring(&msgbuf, _("missing error text"));
3158 
3159  if (edata->detail)
3160  {
3162  err_sendstring(&msgbuf, edata->detail);
3163  }
3164 
3165  /* detail_log is intentionally not used here */
3166 
3167  if (edata->hint)
3168  {
3170  err_sendstring(&msgbuf, edata->hint);
3171  }
3172 
3173  if (edata->context)
3174  {
3175  pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
3176  err_sendstring(&msgbuf, edata->context);
3177  }
3178 
3179  if (edata->schema_name)
3180  {
3181  pq_sendbyte(&msgbuf, PG_DIAG_SCHEMA_NAME);
3182  err_sendstring(&msgbuf, edata->schema_name);
3183  }
3184 
3185  if (edata->table_name)
3186  {
3187  pq_sendbyte(&msgbuf, PG_DIAG_TABLE_NAME);
3188  err_sendstring(&msgbuf, edata->table_name);
3189  }
3190 
3191  if (edata->column_name)
3192  {
3193  pq_sendbyte(&msgbuf, PG_DIAG_COLUMN_NAME);
3194  err_sendstring(&msgbuf, edata->column_name);
3195  }
3196 
3197  if (edata->datatype_name)
3198  {
3200  err_sendstring(&msgbuf, edata->datatype_name);
3201  }
3202 
3203  if (edata->constraint_name)
3204  {
3206  err_sendstring(&msgbuf, edata->constraint_name);
3207  }
3208 
3209  if (edata->cursorpos > 0)
3210  {
3211  snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
3213  err_sendstring(&msgbuf, tbuf);
3214  }
3215 
3216  if (edata->internalpos > 0)
3217  {
3218  snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
3220  err_sendstring(&msgbuf, tbuf);
3221  }
3222 
3223  if (edata->internalquery)
3224  {
3226  err_sendstring(&msgbuf, edata->internalquery);
3227  }
3228 
3229  if (edata->filename)
3230  {
3231  pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
3232  err_sendstring(&msgbuf, edata->filename);
3233  }
3234 
3235  if (edata->lineno > 0)
3236  {
3237  snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
3238  pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
3239  err_sendstring(&msgbuf, tbuf);
3240  }
3241 
3242  if (edata->funcname)
3243  {
3245  err_sendstring(&msgbuf, edata->funcname);
3246  }
3247 
3248  pq_sendbyte(&msgbuf, '\0'); /* terminator */
3249 
3250  pq_endmessage(&msgbuf);
3251  }
3252  else
3253  {
3254  /* Old style --- gin up a backwards-compatible message */
3256 
3257  initStringInfo(&buf);
3258 
3259  appendStringInfo(&buf, "%s: ", _(error_severity(edata->elevel)));
3260 
3261  if (edata->message)
3263  else
3264  appendStringInfoString(&buf, _("missing error text"));
3265 
3266  appendStringInfoChar(&buf, '\n');
3267 
3268  /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
3269  pq_putmessage_v2((edata->elevel < ERROR) ? 'N' : 'E', buf.data, buf.len + 1);
3270 
3271  pfree(buf.data);
3272  }
3273 
3274  /*
3275  * This flush is normally not necessary, since postgres.c will flush out
3276  * waiting data when control returns to the main loop. But it seems best
3277  * to leave it here, so that the client has some clue what happened if the
3278  * backend dies before getting back to the main loop ... error/notice
3279  * messages should not be a performance-critical path anyway, so an extra
3280  * flush won't hurt much ...
3281  */
3282  pq_flush();
3283 }
3284 
3285 
3286 /*
3287  * Support routines for formatting error messages.
3288  */
3289 
3290 
3291 /*
3292  * error_severity --- get string representing elevel
3293  *
3294  * The string is not localized here, but we mark the strings for translation
3295  * so that callers can invoke _() on the result.
3296  */
3297 const char *
3298 error_severity(int elevel)
3299 {
3300  const char *prefix;
3301 
3302  switch (elevel)
3303  {
3304  case DEBUG1:
3305  case DEBUG2:
3306  case DEBUG3:
3307  case DEBUG4:
3308  case DEBUG5:
3309  prefix = gettext_noop("DEBUG");
3310  break;
3311  case LOG:
3312  case LOG_SERVER_ONLY:
3313  prefix = gettext_noop("LOG");
3314  break;
3315  case INFO:
3316  prefix = gettext_noop("INFO");
3317  break;
3318  case NOTICE:
3319  prefix = gettext_noop("NOTICE");
3320  break;
3321  case WARNING:
3322  case WARNING_CLIENT_ONLY:
3323  prefix = gettext_noop("WARNING");
3324  break;
3325  case ERROR:
3326  prefix = gettext_noop("ERROR");
3327  break;
3328  case FATAL:
3329  prefix = gettext_noop("FATAL");
3330  break;
3331  case PANIC:
3332  prefix = gettext_noop("PANIC");
3333  break;
3334  default:
3335  prefix = "???";
3336  break;
3337  }
3338 
3339  return prefix;
3340 }
3341 
3342 
3343 /*
3344  * append_with_tabs
3345  *
3346  * Append the string to the StringInfo buffer, inserting a tab after any
3347  * newline.
3348  */
3349 static void
3351 {
3352  char ch;
3353 
3354  while ((ch = *str++) != '\0')
3355  {
3357  if (ch == '\n')
3359  }
3360 }
3361 
3362 
3363 /*
3364  * Write errors to stderr (or by equal means when stderr is
3365  * not available). Used before ereport/elog can be used
3366  * safely (memory context, GUC load etc)
3367  */
3368 void
3369 write_stderr(const char *fmt,...)
3370 {
3371  va_list ap;
3372 
3373 #ifdef WIN32
3374  char errbuf[2048]; /* Arbitrary size? */
3375 #endif
3376 
3377  fmt = _(fmt);
3378 
3379  va_start(ap, fmt);
3380 #ifndef WIN32
3381  /* On Unix, we just fprintf to stderr */
3382  vfprintf(stderr, fmt, ap);
3383  fflush(stderr);
3384 #else
3385  vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
3386 
3387  /*
3388  * On Win32, we print to stderr if running on a console, or write to
3389  * eventlog if running as a service
3390  */
3391  if (pgwin32_is_service()) /* Running as a service */
3392  {
3393  write_eventlog(ERROR, errbuf, strlen(errbuf));
3394  }
3395  else
3396  {
3397  /* Not running as service, write to stderr */
3398  write_console(errbuf, strlen(errbuf));
3399  fflush(stderr);
3400  }
3401 #endif
3402  va_end(ap);
3403 }
3404 
3405 
3406 /*
3407  * Adjust the level of a recovery-related message per trace_recovery_messages.
3408  *
3409  * The argument is the default log level of the message, eg, DEBUG2. (This
3410  * should only be applied to DEBUGn log messages, otherwise it's a no-op.)
3411  * If the level is >= trace_recovery_messages, we return LOG, causing the
3412  * message to be logged unconditionally (for most settings of
3413  * log_min_messages). Otherwise, we return the argument unchanged.
3414  * The message will then be shown based on the setting of log_min_messages.
3415  *
3416  * Intention is to keep this for at least the whole of the 9.0 production
3417  * release, so we can more easily diagnose production problems in the field.
3418  * It should go away eventually, though, because it's an ugly and
3419  * hard-to-explain kluge.
3420  */
3421 int
3422 trace_recovery(int trace_level)
3423 {
3424  if (trace_level < LOG &&
3425  trace_level >= trace_recovery_messages)
3426  return LOG;
3427 
3428  return trace_level;
3429 }
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:174
#define pg_noinline
Definition: c.h:223
#define Min(x, y)
Definition: c.h:997
#define pg_attribute_cold
Definition: c.h:248
#define gettext_noop(x)
Definition: c.h:1205
#define Max(x, y)
Definition: c.h:991
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1223
#define gettext(x)
Definition: c.h:1188
#define lengthof(array)
Definition: c.h:745
#define MemSet(start, val, len)
Definition: c.h:1019
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:361
int errcode_for_socket_access(void)
Definition: elog.c:787
static void log_line_prefix(StringInfo buf, ErrorData *edata)
Definition: elog.c:2444
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:3123
bool check_log_of_query(ErrorData *edata)
Definition: elog.c:2368
static const char * process_log_prefix_padding(const char *p, int *padding)
Definition: elog.c:2413
int errmsg_internal(const char *fmt,...)
Definition: elog.c:991
static void append_with_tabs(StringInfo buf, const char *str)
Definition: elog.c:3350
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:2294
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:3111
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:3298
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:2391
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:3060
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:2817
char * Log_destination_string
Definition: elog.c:112
static void write_console(const char *line, int len)
Definition: elog.c:2216
#define EVALUATE_MESSAGE(domain, targetfield, appendval, translateit)
Definition: elog.c:823
char * unpack_sql_state(int sql_state)
Definition: elog.c:2797
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:3369
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:2344
#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:2332
static ErrorData errordata[ERRORDATA_STACK_SIZE]
Definition: elog.c:145
int trace_recovery(int trace_level)
Definition: elog.c:3422
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 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:41
ProtocolVersion FrontendProtocol
Definition: globals.c:28
pid_t PostmasterPid
Definition: globals.c:99
volatile uint32 InterruptHoldoffCount
Definition: globals.c:40
int MyProcPid
Definition: globals.c:44
bool IsUnderPostmaster
Definition: globals.c:113
volatile uint32 CritSectionCount
Definition: globals.c:42
bool ExitOnAnyError
Definition: globals.c:117
struct Port * MyProcPort
Definition: globals.c:47
pg_time_t MyStartTime
Definition: globals.c:45
char OutputFileName[MAXPGPATH]
Definition: globals.c:74
char * event_source
Definition: guc.c:623
int client_min_messages
Definition: guc.c:637
int log_min_error_statement
Definition: guc.c:635
static int syslog_facility
Definition: guc.c:188
int trace_recovery_messages
Definition: guc.c:645
char * backtrace_symbol_list
Definition: guc.c:647
char * application_name
Definition: guc.c:661
int log_min_messages
Definition: guc.c:636
char * backtrace_functions
Definition: guc.c:646
#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:1305
void pfree(void *pointer)
Definition: mcxt.c:1175
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1292
MemoryContext ErrorContext
Definition: mcxt.c:49
void * palloc(Size size)
Definition: mcxt.c:1068
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
@ B_LOGGER
Definition: miscadmin.h:338
@ B_BG_WORKER
Definition: miscadmin.h:330
const char * GetBackendTypeDesc(BackendType backendType)
Definition: miscinit.c:249
BackendType MyBackendType
Definition: miscinit.c:63
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:94
static char * buf
Definition: pg_test_fsync.c:67
const char * username
Definition: pgbench.c:309
@ DISCONNECT_FATAL
Definition: pgstat.h:80
@ DISCONNECT_NORMAL
Definition: pgstat.h:78
SessionEndType pgStatSessionEndCause
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
PGDLLIMPORT pg_tz * log_timezone
Definition: pgtz.c:31
#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:92
const char * debug_query_string
Definition: postgres.c:89
#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:358
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:197
int pq_putmessage_v2(char msgtype, const char *s, size_t len)
Definition: pqcomm.c:1552
#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:160
LocalTransactionId lxid
Definition: proc.h:181
BackendId backendId
Definition: proc.h:191
int pid
Definition: proc.h:184
PGPROC * lockGroupLeader
Definition: proc.h:289
char data[FLEXIBLE_ARRAY_MEMBER]
Definition: syslogger.h:50
char nuls[2]
Definition: syslogger.h:46
char * user_name
Definition: libpq-be.h:145
char * remote_port
Definition: libpq-be.h:136
char * database_name
Definition: libpq-be.h:144
char * remote_host
Definition: libpq-be.h:131
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:428