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