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