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
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
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 */
715  edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
716  break;
717 
718  /* All else is classified as internal errors */
719  default:
720  edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
721  break;
722  }
723 
724  return 0; /* return value does not matter */
725 }
726 
727 
728 /*
729  * This macro handles expansion of a format string and associated parameters;
730  * it's common code for errmsg(), errdetail(), etc. Must be called inside
731  * a routine that is declared like "const char *fmt, ..." and has an edata
732  * pointer set up. The message is assigned to edata->targetfield, or
733  * appended to it if appendval is true. The message is subject to translation
734  * if translateit is true.
735  *
736  * Note: we pstrdup the buffer rather than just transferring its storage
737  * to the edata field because the buffer might be considerably larger than
738  * really necessary.
739  */
740 #define EVALUATE_MESSAGE(domain, targetfield, appendval, translateit) \
741  { \
742  StringInfoData buf; \
743  /* Internationalize the error format string */ \
744  if ((translateit) && !in_error_recursion_trouble()) \
745  fmt = dgettext((domain), fmt); \
746  initStringInfo(&buf); \
747  if ((appendval) && edata->targetfield) { \
748  appendStringInfoString(&buf, edata->targetfield); \
749  appendStringInfoChar(&buf, '\n'); \
750  } \
751  /* Generate actual output --- have to use appendStringInfoVA */ \
752  for (;;) \
753  { \
754  va_list args; \
755  int needed; \
756  errno = edata->saved_errno; \
757  va_start(args, fmt); \
758  needed = appendStringInfoVA(&buf, fmt, args); \
759  va_end(args); \
760  if (needed == 0) \
761  break; \
762  enlargeStringInfo(&buf, needed); \
763  } \
764  /* Save the completed message into the stack item */ \
765  if (edata->targetfield) \
766  pfree(edata->targetfield); \
767  edata->targetfield = pstrdup(buf.data); \
768  pfree(buf.data); \
769  }
770 
771 /*
772  * Same as above, except for pluralized error messages. The calling routine
773  * must be declared like "const char *fmt_singular, const char *fmt_plural,
774  * unsigned long n, ...". Translation is assumed always wanted.
775  */
776 #define EVALUATE_MESSAGE_PLURAL(domain, targetfield, appendval) \
777  { \
778  const char *fmt; \
779  StringInfoData buf; \
780  /* Internationalize the error format string */ \
781  if (!in_error_recursion_trouble()) \
782  fmt = dngettext((domain), fmt_singular, fmt_plural, n); \
783  else \
784  fmt = (n == 1 ? fmt_singular : fmt_plural); \
785  initStringInfo(&buf); \
786  if ((appendval) && edata->targetfield) { \
787  appendStringInfoString(&buf, edata->targetfield); \
788  appendStringInfoChar(&buf, '\n'); \
789  } \
790  /* Generate actual output --- have to use appendStringInfoVA */ \
791  for (;;) \
792  { \
793  va_list args; \
794  int needed; \
795  errno = edata->saved_errno; \
796  va_start(args, n); \
797  needed = appendStringInfoVA(&buf, fmt, args); \
798  va_end(args); \
799  if (needed == 0) \
800  break; \
801  enlargeStringInfo(&buf, needed); \
802  } \
803  /* Save the completed message into the stack item */ \
804  if (edata->targetfield) \
805  pfree(edata->targetfield); \
806  edata->targetfield = pstrdup(buf.data); \
807  pfree(buf.data); \
808  }
809 
810 
811 /*
812  * errmsg --- add a primary error message text to the current error
813  *
814  * In addition to the usual %-escapes recognized by printf, "%m" in
815  * fmt is replaced by the error message for the caller's value of errno.
816  *
817  * Note: no newline is needed at the end of the fmt string, since
818  * ereport will provide one for the output methods that need it.
819  */
820 int
821 errmsg(const char *fmt,...)
822 {
823  ErrorData *edata = &errordata[errordata_stack_depth];
824  MemoryContext oldcontext;
825 
826  recursion_depth++;
828  oldcontext = MemoryContextSwitchTo(edata->assoc_context);
829 
830  edata->message_id = fmt;
831  EVALUATE_MESSAGE(edata->domain, message, false, true);
832 
833  MemoryContextSwitchTo(oldcontext);
834  recursion_depth--;
835  return 0; /* return value does not matter */
836 }
837 
838 /*
839  * Add a backtrace to the containing ereport() call. This is intended to be
840  * added temporarily during debugging.
841  */
842 int
844 {
845  ErrorData *edata = &errordata[errordata_stack_depth];
846  MemoryContext oldcontext;
847 
848  recursion_depth++;
850  oldcontext = MemoryContextSwitchTo(edata->assoc_context);
851 
852  set_backtrace(edata, 1);
853 
854  MemoryContextSwitchTo(oldcontext);
855  recursion_depth--;
856 
857  return 0;
858 }
859 
860 /*
861  * Compute backtrace data and add it to the supplied ErrorData. num_skip
862  * specifies how many inner frames to skip. Use this to avoid showing the
863  * internal backtrace support functions in the backtrace. This requires that
864  * this and related functions are not inlined.
865  */
866 static void
867 set_backtrace(ErrorData *edata, int num_skip)
868 {
869  StringInfoData errtrace;
870 
871  initStringInfo(&errtrace);
872 
873 #ifdef HAVE_BACKTRACE_SYMBOLS
874  {
875  void *buf[100];
876  int nframes;
877  char **strfrms;
878 
879  nframes = backtrace(buf, lengthof(buf));
880  strfrms = backtrace_symbols(buf, nframes);
881  if (strfrms == NULL)
882  return;
883 
884  for (int i = num_skip; i < nframes; i++)
885  appendStringInfo(&errtrace, "\n%s", strfrms[i]);
886  free(strfrms);
887  }
888 #else
889  appendStringInfoString(&errtrace,
890  "backtrace generation is not supported by this installation");
891 #endif
892 
893  edata->backtrace = errtrace.data;
894 }
895 
896 /*
897  * errmsg_internal --- add a primary error message text to the current error
898  *
899  * This is exactly like errmsg() except that strings passed to errmsg_internal
900  * are not translated, and are customarily left out of the
901  * internationalization message dictionary. This should be used for "can't
902  * happen" cases that are probably not worth spending translation effort on.
903  * We also use this for certain cases where we *must* not try to translate
904  * the message because the translation would fail and result in infinite
905  * error recursion.
906  */
907 int
908 errmsg_internal(const char *fmt,...)
909 {
910  ErrorData *edata = &errordata[errordata_stack_depth];
911  MemoryContext oldcontext;
912 
913  recursion_depth++;
915  oldcontext = MemoryContextSwitchTo(edata->assoc_context);
916 
917  edata->message_id = fmt;
918  EVALUATE_MESSAGE(edata->domain, message, false, false);
919 
920  MemoryContextSwitchTo(oldcontext);
921  recursion_depth--;
922  return 0; /* return value does not matter */
923 }
924 
925 
926 /*
927  * errmsg_plural --- add a primary error message text to the current error,
928  * with support for pluralization of the message text
929  */
930 int
931 errmsg_plural(const char *fmt_singular, const char *fmt_plural,
932  unsigned long n,...)
933 {
934  ErrorData *edata = &errordata[errordata_stack_depth];
935  MemoryContext oldcontext;
936 
937  recursion_depth++;
939  oldcontext = MemoryContextSwitchTo(edata->assoc_context);
940 
941  edata->message_id = fmt_singular;
942  EVALUATE_MESSAGE_PLURAL(edata->domain, message, false);
943 
944  MemoryContextSwitchTo(oldcontext);
945  recursion_depth--;
946  return 0; /* return value does not matter */
947 }
948 
949 
950 /*
951  * errdetail --- add a detail error message text to the current error
952  */
953 int
954 errdetail(const char *fmt,...)
955 {
956  ErrorData *edata = &errordata[errordata_stack_depth];
957  MemoryContext oldcontext;
958 
959  recursion_depth++;
961  oldcontext = MemoryContextSwitchTo(edata->assoc_context);
962 
963  EVALUATE_MESSAGE(edata->domain, detail, false, true);
964 
965  MemoryContextSwitchTo(oldcontext);
966  recursion_depth--;
967  return 0; /* return value does not matter */
968 }
969 
970 
971 /*
972  * errdetail_internal --- add a detail error message text to the current error
973  *
974  * This is exactly like errdetail() except that strings passed to
975  * errdetail_internal are not translated, and are customarily left out of the
976  * internationalization message dictionary. This should be used for detail
977  * messages that seem not worth translating for one reason or another
978  * (typically, that they don't seem to be useful to average users).
979  */
980 int
981 errdetail_internal(const char *fmt,...)
982 {
983  ErrorData *edata = &errordata[errordata_stack_depth];
984  MemoryContext oldcontext;
985 
986  recursion_depth++;
988  oldcontext = MemoryContextSwitchTo(edata->assoc_context);
989 
990  EVALUATE_MESSAGE(edata->domain, detail, false, false);
991 
992  MemoryContextSwitchTo(oldcontext);
993  recursion_depth--;
994  return 0; /* return value does not matter */
995 }
996 
997 
998 /*
999  * errdetail_log --- add a detail_log error message text to the current error
1000  */
1001 int
1002 errdetail_log(const char *fmt,...)
1003 {
1004  ErrorData *edata = &errordata[errordata_stack_depth];
1005  MemoryContext oldcontext;
1006 
1007  recursion_depth++;
1009  oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1010 
1011  EVALUATE_MESSAGE(edata->domain, detail_log, false, true);
1012 
1013  MemoryContextSwitchTo(oldcontext);
1014  recursion_depth--;
1015  return 0; /* return value does not matter */
1016 }
1017 
1018 /*
1019  * errdetail_log_plural --- add a detail_log error message text to the current error
1020  * with support for pluralization of the message text
1021  */
1022 int
1023 errdetail_log_plural(const char *fmt_singular, const char *fmt_plural,
1024  unsigned long n,...)
1025 {
1026  ErrorData *edata = &errordata[errordata_stack_depth];
1027  MemoryContext oldcontext;
1028 
1029  recursion_depth++;
1031  oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1032 
1033  EVALUATE_MESSAGE_PLURAL(edata->domain, detail_log, false);
1034 
1035  MemoryContextSwitchTo(oldcontext);
1036  recursion_depth--;
1037  return 0; /* return value does not matter */
1038 }
1039 
1040 
1041 /*
1042  * errdetail_plural --- add a detail error message text to the current error,
1043  * with support for pluralization of the message text
1044  */
1045 int
1046 errdetail_plural(const char *fmt_singular, const char *fmt_plural,
1047  unsigned long n,...)
1048 {
1049  ErrorData *edata = &errordata[errordata_stack_depth];
1050  MemoryContext oldcontext;
1051 
1052  recursion_depth++;
1054  oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1055 
1056  EVALUATE_MESSAGE_PLURAL(edata->domain, detail, false);
1057 
1058  MemoryContextSwitchTo(oldcontext);
1059  recursion_depth--;
1060  return 0; /* return value does not matter */
1061 }
1062 
1063 
1064 /*
1065  * errhint --- add a hint error message text to the current error
1066  */
1067 int
1068 errhint(const char *fmt,...)
1069 {
1070  ErrorData *edata = &errordata[errordata_stack_depth];
1071  MemoryContext oldcontext;
1072 
1073  recursion_depth++;
1075  oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1076 
1077  EVALUATE_MESSAGE(edata->domain, hint, false, true);
1078 
1079  MemoryContextSwitchTo(oldcontext);
1080  recursion_depth--;
1081  return 0; /* return value does not matter */
1082 }
1083 
1084 
1085 /*
1086  * errcontext_msg --- add a context error message text to the current error
1087  *
1088  * Unlike other cases, multiple calls are allowed to build up a stack of
1089  * context information. We assume earlier calls represent more-closely-nested
1090  * states.
1091  */
1092 int
1093 errcontext_msg(const char *fmt,...)
1094 {
1095  ErrorData *edata = &errordata[errordata_stack_depth];
1096  MemoryContext oldcontext;
1097 
1098  recursion_depth++;
1100  oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1101 
1102  EVALUATE_MESSAGE(edata->context_domain, context, true, true);
1103 
1104  MemoryContextSwitchTo(oldcontext);
1105  recursion_depth--;
1106  return 0; /* return value does not matter */
1107 }
1108 
1109 /*
1110  * set_errcontext_domain --- set message domain to be used by errcontext()
1111  *
1112  * errcontext_msg() can be called from a different module than the original
1113  * ereport(), so we cannot use the message domain passed in errstart() to
1114  * translate it. Instead, each errcontext_msg() call should be preceded by
1115  * a set_errcontext_domain() call to specify the domain. This is usually
1116  * done transparently by the errcontext() macro.
1117  */
1118 int
1119 set_errcontext_domain(const char *domain)
1120 {
1121  ErrorData *edata = &errordata[errordata_stack_depth];
1122 
1123  /* we don't bother incrementing recursion_depth */
1125 
1126  /* the default text domain is the backend's */
1127  edata->context_domain = domain ? domain : PG_TEXTDOMAIN("postgres");
1128 
1129  return 0; /* return value does not matter */
1130 }
1131 
1132 
1133 /*
1134  * errhidestmt --- optionally suppress STATEMENT: field of log entry
1135  *
1136  * This should be called if the message text already includes the statement.
1137  */
1138 int
1139 errhidestmt(bool hide_stmt)
1140 {
1141  ErrorData *edata = &errordata[errordata_stack_depth];
1142 
1143  /* we don't bother incrementing recursion_depth */
1145 
1146  edata->hide_stmt = hide_stmt;
1147 
1148  return 0; /* return value does not matter */
1149 }
1150 
1151 /*
1152  * errhidecontext --- optionally suppress CONTEXT: field of log entry
1153  *
1154  * This should only be used for verbose debugging messages where the repeated
1155  * inclusion of context would bloat the log volume too much.
1156  */
1157 int
1158 errhidecontext(bool hide_ctx)
1159 {
1160  ErrorData *edata = &errordata[errordata_stack_depth];
1161 
1162  /* we don't bother incrementing recursion_depth */
1164 
1165  edata->hide_ctx = hide_ctx;
1166 
1167  return 0; /* return value does not matter */
1168 }
1169 
1170 
1171 /*
1172  * errfunction --- add reporting function name to the current error
1173  *
1174  * This is used when backwards compatibility demands that the function
1175  * name appear in messages sent to old-protocol clients. Note that the
1176  * passed string is expected to be a non-freeable constant string.
1177  */
1178 int
1179 errfunction(const char *funcname)
1180 {
1181  ErrorData *edata = &errordata[errordata_stack_depth];
1182 
1183  /* we don't bother incrementing recursion_depth */
1185 
1186  edata->funcname = funcname;
1187  edata->show_funcname = true;
1188 
1189  return 0; /* return value does not matter */
1190 }
1191 
1192 /*
1193  * errposition --- add cursor position to the current error
1194  */
1195 int
1196 errposition(int cursorpos)
1197 {
1198  ErrorData *edata = &errordata[errordata_stack_depth];
1199 
1200  /* we don't bother incrementing recursion_depth */
1202 
1203  edata->cursorpos = cursorpos;
1204 
1205  return 0; /* return value does not matter */
1206 }
1207 
1208 /*
1209  * internalerrposition --- add internal cursor position to the current error
1210  */
1211 int
1212 internalerrposition(int cursorpos)
1213 {
1214  ErrorData *edata = &errordata[errordata_stack_depth];
1215 
1216  /* we don't bother incrementing recursion_depth */
1218 
1219  edata->internalpos = cursorpos;
1220 
1221  return 0; /* return value does not matter */
1222 }
1223 
1224 /*
1225  * internalerrquery --- add internal query text to the current error
1226  *
1227  * Can also pass NULL to drop the internal query text entry. This case
1228  * is intended for use in error callback subroutines that are editorializing
1229  * on the layout of the error report.
1230  */
1231 int
1232 internalerrquery(const char *query)
1233 {
1234  ErrorData *edata = &errordata[errordata_stack_depth];
1235 
1236  /* we don't bother incrementing recursion_depth */
1238 
1239  if (edata->internalquery)
1240  {
1241  pfree(edata->internalquery);
1242  edata->internalquery = NULL;
1243  }
1244 
1245  if (query)
1246  edata->internalquery = MemoryContextStrdup(edata->assoc_context, query);
1247 
1248  return 0; /* return value does not matter */
1249 }
1250 
1251 /*
1252  * err_generic_string -- used to set individual ErrorData string fields
1253  * identified by PG_DIAG_xxx codes.
1254  *
1255  * This intentionally only supports fields that don't use localized strings,
1256  * so that there are no translation considerations.
1257  *
1258  * Most potential callers should not use this directly, but instead prefer
1259  * higher-level abstractions, such as errtablecol() (see relcache.c).
1260  */
1261 int
1262 err_generic_string(int field, const char *str)
1263 {
1264  ErrorData *edata = &errordata[errordata_stack_depth];
1265 
1266  /* we don't bother incrementing recursion_depth */
1268 
1269  switch (field)
1270  {
1271  case PG_DIAG_SCHEMA_NAME:
1272  set_errdata_field(edata->assoc_context, &edata->schema_name, str);
1273  break;
1274  case PG_DIAG_TABLE_NAME:
1275  set_errdata_field(edata->assoc_context, &edata->table_name, str);
1276  break;
1277  case PG_DIAG_COLUMN_NAME:
1278  set_errdata_field(edata->assoc_context, &edata->column_name, str);
1279  break;
1280  case PG_DIAG_DATATYPE_NAME:
1281  set_errdata_field(edata->assoc_context, &edata->datatype_name, str);
1282  break;
1284  set_errdata_field(edata->assoc_context, &edata->constraint_name, str);
1285  break;
1286  default:
1287  elog(ERROR, "unsupported ErrorData field id: %d", field);
1288  break;
1289  }
1290 
1291  return 0; /* return value does not matter */
1292 }
1293 
1294 /*
1295  * set_errdata_field --- set an ErrorData string field
1296  */
1297 static void
1298 set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str)
1299 {
1300  Assert(*ptr == NULL);
1301  *ptr = MemoryContextStrdup(cxt, str);
1302 }
1303 
1304 /*
1305  * geterrcode --- return the currently set SQLSTATE error code
1306  *
1307  * This is only intended for use in error callback subroutines, since there
1308  * is no other place outside elog.c where the concept is meaningful.
1309  */
1310 int
1312 {
1313  ErrorData *edata = &errordata[errordata_stack_depth];
1314 
1315  /* we don't bother incrementing recursion_depth */
1317 
1318  return edata->sqlerrcode;
1319 }
1320 
1321 /*
1322  * geterrposition --- return the currently set error position (0 if none)
1323  *
1324  * This is only intended for use in error callback subroutines, since there
1325  * is no other place outside elog.c where the concept is meaningful.
1326  */
1327 int
1329 {
1330  ErrorData *edata = &errordata[errordata_stack_depth];
1331 
1332  /* we don't bother incrementing recursion_depth */
1334 
1335  return edata->cursorpos;
1336 }
1337 
1338 /*
1339  * getinternalerrposition --- same for internal error position
1340  *
1341  * This is only intended for use in error callback subroutines, since there
1342  * is no other place outside elog.c where the concept is meaningful.
1343  */
1344 int
1346 {
1347  ErrorData *edata = &errordata[errordata_stack_depth];
1348 
1349  /* we don't bother incrementing recursion_depth */
1351 
1352  return edata->internalpos;
1353 }
1354 
1355 
1356 /*
1357  * Functions to allow construction of error message strings separately from
1358  * the ereport() call itself.
1359  *
1360  * The expected calling convention is
1361  *
1362  * pre_format_elog_string(errno, domain), var = format_elog_string(format,...)
1363  *
1364  * which can be hidden behind a macro such as GUC_check_errdetail(). We
1365  * assume that any functions called in the arguments of format_elog_string()
1366  * cannot result in re-entrant use of these functions --- otherwise the wrong
1367  * text domain might be used, or the wrong errno substituted for %m. This is
1368  * okay for the current usage with GUC check hooks, but might need further
1369  * effort someday.
1370  *
1371  * The result of format_elog_string() is stored in ErrorContext, and will
1372  * therefore survive until FlushErrorState() is called.
1373  */
1375 static const char *save_format_domain;
1376 
1377 void
1378 pre_format_elog_string(int errnumber, const char *domain)
1379 {
1380  /* Save errno before evaluation of argument functions can change it */
1381  save_format_errnumber = errnumber;
1382  /* Save caller's text domain */
1383  save_format_domain = domain;
1384 }
1385 
1386 char *
1387 format_elog_string(const char *fmt,...)
1388 {
1389  ErrorData errdata;
1390  ErrorData *edata;
1391  MemoryContext oldcontext;
1392 
1393  /* Initialize a mostly-dummy error frame */
1394  edata = &errdata;
1395  MemSet(edata, 0, sizeof(ErrorData));
1396  /* the default text domain is the backend's */
1397  edata->domain = save_format_domain ? save_format_domain : PG_TEXTDOMAIN("postgres");
1398  /* set the errno to be used to interpret %m */
1400 
1401  oldcontext = MemoryContextSwitchTo(ErrorContext);
1402 
1403  edata->message_id = fmt;
1404  EVALUATE_MESSAGE(edata->domain, message, false, true);
1405 
1406  MemoryContextSwitchTo(oldcontext);
1407 
1408  return edata->message;
1409 }
1410 
1411 
1412 /*
1413  * Actual output of the top-of-stack error message
1414  *
1415  * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
1416  * if the error is caught by somebody). For all other severity levels this
1417  * is called by errfinish.
1418  */
1419 void
1421 {
1422  ErrorData *edata = &errordata[errordata_stack_depth];
1423  MemoryContext oldcontext;
1424 
1425  recursion_depth++;
1427  oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1428 
1429  /*
1430  * Call hook before sending message to log. The hook function is allowed
1431  * to turn off edata->output_to_server, so we must recheck that afterward.
1432  * Making any other change in the content of edata is not considered
1433  * supported.
1434  *
1435  * Note: the reason why the hook can only turn off output_to_server, and
1436  * not turn it on, is that it'd be unreliable: we will never get here at
1437  * all if errstart() deems the message uninteresting. A hook that could
1438  * make decisions in that direction would have to hook into errstart(),
1439  * where it would have much less information available. emit_log_hook is
1440  * intended for custom log filtering and custom log message transmission
1441  * mechanisms.
1442  *
1443  * The log hook has access to both the translated and original English
1444  * error message text, which is passed through to allow it to be used as a
1445  * message identifier. Note that the original text is not available for
1446  * detail, detail_log, hint and context text elements.
1447  */
1448  if (edata->output_to_server && emit_log_hook)
1449  (*emit_log_hook) (edata);
1450 
1451  /* Send to server log, if enabled */
1452  if (edata->output_to_server)
1454 
1455  /* Send to client, if enabled */
1456  if (edata->output_to_client)
1457  send_message_to_frontend(edata);
1458 
1459  MemoryContextSwitchTo(oldcontext);
1460  recursion_depth--;
1461 }
1462 
1463 /*
1464  * CopyErrorData --- obtain a copy of the topmost error stack entry
1465  *
1466  * This is only for use in error handler code. The data is copied into the
1467  * current memory context, so callers should always switch away from
1468  * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
1469  */
1470 ErrorData *
1472 {
1473  ErrorData *edata = &errordata[errordata_stack_depth];
1474  ErrorData *newedata;
1475 
1476  /*
1477  * we don't increment recursion_depth because out-of-memory here does not
1478  * indicate a problem within the error subsystem.
1479  */
1481 
1483 
1484  /* Copy the struct itself */
1485  newedata = (ErrorData *) palloc(sizeof(ErrorData));
1486  memcpy(newedata, edata, sizeof(ErrorData));
1487 
1488  /* Make copies of separately-allocated fields */
1489  if (newedata->message)
1490  newedata->message = pstrdup(newedata->message);
1491  if (newedata->detail)
1492  newedata->detail = pstrdup(newedata->detail);
1493  if (newedata->detail_log)
1494  newedata->detail_log = pstrdup(newedata->detail_log);
1495  if (newedata->hint)
1496  newedata->hint = pstrdup(newedata->hint);
1497  if (newedata->context)
1498  newedata->context = pstrdup(newedata->context);
1499  if (newedata->backtrace)
1500  newedata->backtrace = pstrdup(newedata->backtrace);
1501  if (newedata->schema_name)
1502  newedata->schema_name = pstrdup(newedata->schema_name);
1503  if (newedata->table_name)
1504  newedata->table_name = pstrdup(newedata->table_name);
1505  if (newedata->column_name)
1506  newedata->column_name = pstrdup(newedata->column_name);
1507  if (newedata->datatype_name)
1508  newedata->datatype_name = pstrdup(newedata->datatype_name);
1509  if (newedata->constraint_name)
1510  newedata->constraint_name = pstrdup(newedata->constraint_name);
1511  if (newedata->internalquery)
1512  newedata->internalquery = pstrdup(newedata->internalquery);
1513 
1514  /* Use the calling context for string allocation */
1515  newedata->assoc_context = CurrentMemoryContext;
1516 
1517  return newedata;
1518 }
1519 
1520 /*
1521  * FreeErrorData --- free the structure returned by CopyErrorData.
1522  *
1523  * Error handlers should use this in preference to assuming they know all
1524  * the separately-allocated fields.
1525  */
1526 void
1528 {
1529  if (edata->message)
1530  pfree(edata->message);
1531  if (edata->detail)
1532  pfree(edata->detail);
1533  if (edata->detail_log)
1534  pfree(edata->detail_log);
1535  if (edata->hint)
1536  pfree(edata->hint);
1537  if (edata->context)
1538  pfree(edata->context);
1539  if (edata->backtrace)
1540  pfree(edata->backtrace);
1541  if (edata->schema_name)
1542  pfree(edata->schema_name);
1543  if (edata->table_name)
1544  pfree(edata->table_name);
1545  if (edata->column_name)
1546  pfree(edata->column_name);
1547  if (edata->datatype_name)
1548  pfree(edata->datatype_name);
1549  if (edata->constraint_name)
1550  pfree(edata->constraint_name);
1551  if (edata->internalquery)
1552  pfree(edata->internalquery);
1553  pfree(edata);
1554 }
1555 
1556 /*
1557  * FlushErrorState --- flush the error state after error recovery
1558  *
1559  * This should be called by an error handler after it's done processing
1560  * the error; or as soon as it's done CopyErrorData, if it intends to
1561  * do stuff that is likely to provoke another error. You are not "out" of
1562  * the error subsystem until you have done this.
1563  */
1564 void
1566 {
1567  /*
1568  * Reset stack to empty. The only case where it would be more than one
1569  * deep is if we serviced an error that interrupted construction of
1570  * another message. We assume control escaped out of that message
1571  * construction and won't ever go back.
1572  */
1573  errordata_stack_depth = -1;
1574  recursion_depth = 0;
1575  /* Delete all data in ErrorContext */
1577 }
1578 
1579 /*
1580  * ThrowErrorData --- report an error described by an ErrorData structure
1581  *
1582  * This is somewhat like ReThrowError, but it allows elevels besides ERROR,
1583  * and the boolean flags such as output_to_server are computed via the
1584  * default rules rather than being copied from the given ErrorData.
1585  * This is primarily used to re-report errors originally reported by
1586  * background worker processes and then propagated (with or without
1587  * modification) to the backend responsible for them.
1588  */
1589 void
1591 {
1592  ErrorData *newedata;
1593  MemoryContext oldcontext;
1594 
1595  if (!errstart(edata->elevel, edata->domain))
1596  return; /* error is not to be reported at all */
1597 
1598  newedata = &errordata[errordata_stack_depth];
1599  recursion_depth++;
1600  oldcontext = MemoryContextSwitchTo(newedata->assoc_context);
1601 
1602  /* Copy the supplied fields to the error stack entry. */
1603  if (edata->sqlerrcode != 0)
1604  newedata->sqlerrcode = edata->sqlerrcode;
1605  if (edata->message)
1606  newedata->message = pstrdup(edata->message);
1607  if (edata->detail)
1608  newedata->detail = pstrdup(edata->detail);
1609  if (edata->detail_log)
1610  newedata->detail_log = pstrdup(edata->detail_log);
1611  if (edata->hint)
1612  newedata->hint = pstrdup(edata->hint);
1613  if (edata->context)
1614  newedata->context = pstrdup(edata->context);
1615  if (edata->backtrace)
1616  newedata->backtrace = pstrdup(edata->backtrace);
1617  /* assume message_id is not available */
1618  if (edata->schema_name)
1619  newedata->schema_name = pstrdup(edata->schema_name);
1620  if (edata->table_name)
1621  newedata->table_name = pstrdup(edata->table_name);
1622  if (edata->column_name)
1623  newedata->column_name = pstrdup(edata->column_name);
1624  if (edata->datatype_name)
1625  newedata->datatype_name = pstrdup(edata->datatype_name);
1626  if (edata->constraint_name)
1627  newedata->constraint_name = pstrdup(edata->constraint_name);
1628  newedata->cursorpos = edata->cursorpos;
1629  newedata->internalpos = edata->internalpos;
1630  if (edata->internalquery)
1631  newedata->internalquery = pstrdup(edata->internalquery);
1632 
1633  MemoryContextSwitchTo(oldcontext);
1634  recursion_depth--;
1635 
1636  /* Process the error. */
1637  errfinish(edata->filename, edata->lineno, edata->funcname);
1638 }
1639 
1640 /*
1641  * ReThrowError --- re-throw a previously copied error
1642  *
1643  * A handler can do CopyErrorData/FlushErrorState to get out of the error
1644  * subsystem, then do some processing, and finally ReThrowError to re-throw
1645  * the original error. This is slower than just PG_RE_THROW() but should
1646  * be used if the "some processing" is likely to incur another error.
1647  */
1648 void
1650 {
1651  ErrorData *newedata;
1652 
1653  Assert(edata->elevel == ERROR);
1654 
1655  /* Push the data back into the error context */
1656  recursion_depth++;
1658 
1660  {
1661  /*
1662  * Wups, stack not big enough. We treat this as a PANIC condition
1663  * because it suggests an infinite loop of errors during error
1664  * recovery.
1665  */
1666  errordata_stack_depth = -1; /* make room on stack */
1667  ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1668  }
1669 
1670  newedata = &errordata[errordata_stack_depth];
1671  memcpy(newedata, edata, sizeof(ErrorData));
1672 
1673  /* Make copies of separately-allocated fields */
1674  if (newedata->message)
1675  newedata->message = pstrdup(newedata->message);
1676  if (newedata->detail)
1677  newedata->detail = pstrdup(newedata->detail);
1678  if (newedata->detail_log)
1679  newedata->detail_log = pstrdup(newedata->detail_log);
1680  if (newedata->hint)
1681  newedata->hint = pstrdup(newedata->hint);
1682  if (newedata->context)
1683  newedata->context = pstrdup(newedata->context);
1684  if (newedata->backtrace)
1685  newedata->backtrace = pstrdup(newedata->backtrace);
1686  if (newedata->schema_name)
1687  newedata->schema_name = pstrdup(newedata->schema_name);
1688  if (newedata->table_name)
1689  newedata->table_name = pstrdup(newedata->table_name);
1690  if (newedata->column_name)
1691  newedata->column_name = pstrdup(newedata->column_name);
1692  if (newedata->datatype_name)
1693  newedata->datatype_name = pstrdup(newedata->datatype_name);
1694  if (newedata->constraint_name)
1695  newedata->constraint_name = pstrdup(newedata->constraint_name);
1696  if (newedata->internalquery)
1697  newedata->internalquery = pstrdup(newedata->internalquery);
1698 
1699  /* Reset the assoc_context to be ErrorContext */
1700  newedata->assoc_context = ErrorContext;
1701 
1702  recursion_depth--;
1703  PG_RE_THROW();
1704 }
1705 
1706 /*
1707  * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
1708  */
1709 void
1711 {
1712  /* If possible, throw the error to the next outer setjmp handler */
1713  if (PG_exception_stack != NULL)
1714  siglongjmp(*PG_exception_stack, 1);
1715  else
1716  {
1717  /*
1718  * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
1719  * we have now exited only to discover that there is no outer setjmp
1720  * handler to pass the error to. Had the error been thrown outside
1721  * the block to begin with, we'd have promoted the error to FATAL, so
1722  * the correct behavior is to make it FATAL now; that is, emit it and
1723  * then call proc_exit.
1724  */
1725  ErrorData *edata = &errordata[errordata_stack_depth];
1726 
1728  Assert(edata->elevel == ERROR);
1729  edata->elevel = FATAL;
1730 
1731  /*
1732  * At least in principle, the increase in severity could have changed
1733  * where-to-output decisions, so recalculate. This should stay in
1734  * sync with errstart(), which see for comments.
1735  */
1739  else
1740  edata->output_to_server = (FATAL >= log_min_messages);
1742  edata->output_to_client = true;
1743 
1744  /*
1745  * We can use errfinish() for the rest, but we don't want it to call
1746  * any error context routines a second time. Since we know we are
1747  * about to exit, it should be OK to just clear the context stack.
1748  */
1749  error_context_stack = NULL;
1750 
1751  errfinish(edata->filename, edata->lineno, edata->funcname);
1752  }
1753 
1754  /* Doesn't return ... */
1755  ExceptionalCondition("pg_re_throw tried to return", "FailedAssertion",
1756  __FILE__, __LINE__);
1757 }
1758 
1759 
1760 /*
1761  * GetErrorContextStack - Return the context stack, for display/diags
1762  *
1763  * Returns a pstrdup'd string in the caller's context which includes the PG
1764  * error call stack. It is the caller's responsibility to ensure this string
1765  * is pfree'd (or its context cleaned up) when done.
1766  *
1767  * This information is collected by traversing the error contexts and calling
1768  * each context's callback function, each of which is expected to call
1769  * errcontext() to return a string which can be presented to the user.
1770  */
1771 char *
1773 {
1774  ErrorData *edata;
1775  ErrorContextCallback *econtext;
1776 
1777  /*
1778  * Okay, crank up a stack entry to store the info in.
1779  */
1780  recursion_depth++;
1781 
1783  {
1784  /*
1785  * Wups, stack not big enough. We treat this as a PANIC condition
1786  * because it suggests an infinite loop of errors during error
1787  * recovery.
1788  */
1789  errordata_stack_depth = -1; /* make room on stack */
1790  ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1791  }
1792 
1793  /*
1794  * Things look good so far, so initialize our error frame
1795  */
1796  edata = &errordata[errordata_stack_depth];
1797  MemSet(edata, 0, sizeof(ErrorData));
1798 
1799  /*
1800  * Set up assoc_context to be the caller's context, so any allocations
1801  * done (which will include edata->context) will use their context.
1802  */
1804 
1805  /*
1806  * Call any context callback functions to collect the context information
1807  * into edata->context.
1808  *
1809  * Errors occurring in callback functions should go through the regular
1810  * error handling code which should handle any recursive errors, though we
1811  * double-check above, just in case.
1812  */
1813  for (econtext = error_context_stack;
1814  econtext != NULL;
1815  econtext = econtext->previous)
1816  econtext->callback(econtext->arg);
1817 
1818  /*
1819  * Clean ourselves off the stack, any allocations done should have been
1820  * using edata->assoc_context, which we set up earlier to be the caller's
1821  * context, so we're free to just remove our entry off the stack and
1822  * decrement recursion depth and exit.
1823  */
1825  recursion_depth--;
1826 
1827  /*
1828  * Return a pointer to the string the caller asked for, which should have
1829  * been allocated in their context.
1830  */
1831  return edata->context;
1832 }
1833 
1834 
1835 /*
1836  * Initialization of error output file
1837  */
1838 void
1840 {
1841  int fd,
1842  istty;
1843 
1844  if (OutputFileName[0])
1845  {
1846  /*
1847  * A debug-output file name was given.
1848  *
1849  * Make sure we can write the file, and find out if it's a tty.
1850  */
1851  if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
1852  0666)) < 0)
1853  ereport(FATAL,
1855  errmsg("could not open file \"%s\": %m", OutputFileName)));
1856  istty = isatty(fd);
1857  close(fd);
1858 
1859  /*
1860  * Redirect our stderr to the debug output file.
1861  */
1862  if (!freopen(OutputFileName, "a", stderr))
1863  ereport(FATAL,
1865  errmsg("could not reopen file \"%s\" as stderr: %m",
1866  OutputFileName)));
1867 
1868  /*
1869  * If the file is a tty and we're running under the postmaster, try to
1870  * send stdout there as well (if it isn't a tty then stderr will block
1871  * out stdout, so we may as well let stdout go wherever it was going
1872  * before).
1873  */
1874  if (istty && IsUnderPostmaster)
1875  if (!freopen(OutputFileName, "a", stdout))
1876  ereport(FATAL,
1878  errmsg("could not reopen file \"%s\" as stdout: %m",
1879  OutputFileName)));
1880  }
1881 }
1882 
1883 
1884 #ifdef HAVE_SYSLOG
1885 
1886 /*
1887  * Set or update the parameters for syslog logging
1888  */
1889 void
1890 set_syslog_parameters(const char *ident, int facility)
1891 {
1892  /*
1893  * guc.c is likely to call us repeatedly with same parameters, so don't
1894  * thrash the syslog connection unnecessarily. Also, we do not re-open
1895  * the connection until needed, since this routine will get called whether
1896  * or not Log_destination actually mentions syslog.
1897  *
1898  * Note that we make our own copy of the ident string rather than relying
1899  * on guc.c's. This may be overly paranoid, but it ensures that we cannot
1900  * accidentally free a string that syslog is still using.
1901  */
1902  if (syslog_ident == NULL || strcmp(syslog_ident, ident) != 0 ||
1903  syslog_facility != facility)
1904  {
1905  if (openlog_done)
1906  {
1907  closelog();
1908  openlog_done = false;
1909  }
1910  if (syslog_ident)
1911  free(syslog_ident);
1912  syslog_ident = strdup(ident);
1913  /* if the strdup fails, we will cope in write_syslog() */
1914  syslog_facility = facility;
1915  }
1916 }
1917 
1918 
1919 /*
1920  * Write a message line to syslog
1921  */
1922 static void
1923 write_syslog(int level, const char *line)
1924 {
1925  static unsigned long seq = 0;
1926 
1927  int len;
1928  const char *nlpos;
1929 
1930  /* Open syslog connection if not done yet */
1931  if (!openlog_done)
1932  {
1933  openlog(syslog_ident ? syslog_ident : "postgres",
1934  LOG_PID | LOG_NDELAY | LOG_NOWAIT,
1935  syslog_facility);
1936  openlog_done = true;
1937  }
1938 
1939  /*
1940  * We add a sequence number to each log message to suppress "same"
1941  * messages.
1942  */
1943  seq++;
1944 
1945  /*
1946  * Our problem here is that many syslog implementations don't handle long
1947  * messages in an acceptable manner. While this function doesn't help that
1948  * fact, it does work around by splitting up messages into smaller pieces.
1949  *
1950  * We divide into multiple syslog() calls if message is too long or if the
1951  * message contains embedded newline(s).
1952  */
1953  len = strlen(line);
1954  nlpos = strchr(line, '\n');
1955  if (syslog_split_messages && (len > PG_SYSLOG_LIMIT || nlpos != NULL))
1956  {
1957  int chunk_nr = 0;
1958 
1959  while (len > 0)
1960  {
1961  char buf[PG_SYSLOG_LIMIT + 1];
1962  int buflen;
1963  int i;
1964 
1965  /* if we start at a newline, move ahead one char */
1966  if (line[0] == '\n')
1967  {
1968  line++;
1969  len--;
1970  /* we need to recompute the next newline's position, too */
1971  nlpos = strchr(line, '\n');
1972  continue;
1973  }
1974 
1975  /* copy one line, or as much as will fit, to buf */
1976  if (nlpos != NULL)
1977  buflen = nlpos - line;
1978  else
1979  buflen = len;
1980  buflen = Min(buflen, PG_SYSLOG_LIMIT);
1981  memcpy(buf, line, buflen);
1982  buf[buflen] = '\0';
1983 
1984  /* trim to multibyte letter boundary */
1985  buflen = pg_mbcliplen(buf, buflen, buflen);
1986  if (buflen <= 0)
1987  return;
1988  buf[buflen] = '\0';
1989 
1990  /* already word boundary? */
1991  if (line[buflen] != '\0' &&
1992  !isspace((unsigned char) line[buflen]))
1993  {
1994  /* try to divide at word boundary */
1995  i = buflen - 1;
1996  while (i > 0 && !isspace((unsigned char) buf[i]))
1997  i--;
1998 
1999  if (i > 0) /* else couldn't divide word boundary */
2000  {
2001  buflen = i;
2002  buf[i] = '\0';
2003  }
2004  }
2005 
2006  chunk_nr++;
2007 
2009  syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
2010  else
2011  syslog(level, "[%d] %s", chunk_nr, buf);
2012 
2013  line += buflen;
2014  len -= buflen;
2015  }
2016  }
2017  else
2018  {
2019  /* message short enough */
2021  syslog(level, "[%lu] %s", seq, line);
2022  else
2023  syslog(level, "%s", line);
2024  }
2025 }
2026 #endif /* HAVE_SYSLOG */
2027 
2028 #ifdef WIN32
2029 /*
2030  * Get the PostgreSQL equivalent of the Windows ANSI code page. "ANSI" system
2031  * interfaces (e.g. CreateFileA()) expect string arguments in this encoding.
2032  * Every process in a given system will find the same value at all times.
2033  */
2034 static int
2035 GetACPEncoding(void)
2036 {
2037  static int encoding = -2;
2038 
2039  if (encoding == -2)
2040  encoding = pg_codepage_to_encoding(GetACP());
2041 
2042  return encoding;
2043 }
2044 
2045 /*
2046  * Write a message line to the windows event log
2047  */
2048 static void
2049 write_eventlog(int level, const char *line, int len)
2050 {
2051  WCHAR *utf16;
2052  int eventlevel = EVENTLOG_ERROR_TYPE;
2053  static HANDLE evtHandle = INVALID_HANDLE_VALUE;
2054 
2055  if (evtHandle == INVALID_HANDLE_VALUE)
2056  {
2057  evtHandle = RegisterEventSource(NULL,
2059  if (evtHandle == NULL)
2060  {
2061  evtHandle = INVALID_HANDLE_VALUE;
2062  return;
2063  }
2064  }
2065 
2066  switch (level)
2067  {
2068  case DEBUG5:
2069  case DEBUG4:
2070  case DEBUG3:
2071  case DEBUG2:
2072  case DEBUG1:
2073  case LOG:
2074  case LOG_SERVER_ONLY:
2075  case INFO:
2076  case NOTICE:
2077  eventlevel = EVENTLOG_INFORMATION_TYPE;
2078  break;
2079  case WARNING:
2080  eventlevel = EVENTLOG_WARNING_TYPE;
2081  break;
2082  case ERROR:
2083  case FATAL:
2084  case PANIC:
2085  default:
2086  eventlevel = EVENTLOG_ERROR_TYPE;
2087  break;
2088  }
2089 
2090  /*
2091  * If message character encoding matches the encoding expected by
2092  * ReportEventA(), call it to avoid the hazards of conversion. Otherwise,
2093  * try to convert the message to UTF16 and write it with ReportEventW().
2094  * Fall back on ReportEventA() if conversion failed.
2095  *
2096  * Since we palloc the structure required for conversion, also fall
2097  * through to writing unconverted if we have not yet set up
2098  * CurrentMemoryContext.
2099  *
2100  * Also verify that we are not on our way into error recursion trouble due
2101  * to error messages thrown deep inside pgwin32_message_to_UTF16().
2102  */
2103  if (!in_error_recursion_trouble() &&
2104  CurrentMemoryContext != NULL &&
2105  GetMessageEncoding() != GetACPEncoding())
2106  {
2107  utf16 = pgwin32_message_to_UTF16(line, len, NULL);
2108  if (utf16)
2109  {
2110  ReportEventW(evtHandle,
2111  eventlevel,
2112  0,
2113  0, /* All events are Id 0 */
2114  NULL,
2115  1,
2116  0,
2117  (LPCWSTR *) &utf16,
2118  NULL);
2119  /* XXX Try ReportEventA() when ReportEventW() fails? */
2120 
2121  pfree(utf16);
2122  return;
2123  }
2124  }
2125  ReportEventA(evtHandle,
2126  eventlevel,
2127  0,
2128  0, /* All events are Id 0 */
2129  NULL,
2130  1,
2131  0,
2132  &line,
2133  NULL);
2134 }
2135 #endif /* WIN32 */
2136 
2137 static void
2138 write_console(const char *line, int len)
2139 {
2140  int rc;
2141 
2142 #ifdef WIN32
2143 
2144  /*
2145  * Try to convert the message to UTF16 and write it with WriteConsoleW().
2146  * Fall back on write() if anything fails.
2147  *
2148  * In contrast to write_eventlog(), don't skip straight to write() based
2149  * on the applicable encodings. Unlike WriteConsoleW(), write() depends
2150  * on the suitability of the console output code page. Since we put
2151  * stderr into binary mode in SubPostmasterMain(), write() skips the
2152  * necessary translation anyway.
2153  *
2154  * WriteConsoleW() will fail if stderr is redirected, so just fall through
2155  * to writing unconverted to the logfile in this case.
2156  *
2157  * Since we palloc the structure required for conversion, also fall
2158  * through to writing unconverted if we have not yet set up
2159  * CurrentMemoryContext.
2160  */
2161  if (!in_error_recursion_trouble() &&
2162  !redirection_done &&
2163  CurrentMemoryContext != NULL)
2164  {
2165  WCHAR *utf16;
2166  int utf16len;
2167 
2168  utf16 = pgwin32_message_to_UTF16(line, len, &utf16len);
2169  if (utf16 != NULL)
2170  {
2171  HANDLE stdHandle;
2172  DWORD written;
2173 
2174  stdHandle = GetStdHandle(STD_ERROR_HANDLE);
2175  if (WriteConsoleW(stdHandle, utf16, utf16len, &written, NULL))
2176  {
2177  pfree(utf16);
2178  return;
2179  }
2180 
2181  /*
2182  * In case WriteConsoleW() failed, fall back to writing the
2183  * message unconverted.
2184  */
2185  pfree(utf16);
2186  }
2187  }
2188 #else
2189 
2190  /*
2191  * Conversion on non-win32 platforms is not implemented yet. It requires
2192  * non-throw version of pg_do_encoding_conversion(), that converts
2193  * unconvertable characters to '?' without errors.
2194  */
2195 #endif
2196 
2197  /*
2198  * We ignore any error from write() here. We have no useful way to report
2199  * it ... certainly whining on stderr isn't likely to be productive.
2200  */
2201  rc = write(fileno(stderr), line, len);
2202  (void) rc;
2203 }
2204 
2205 /*
2206  * setup formatted_log_time, for consistent times between CSV and regular logs
2207  */
2208 static void
2210 {
2211  pg_time_t stamp_time;
2212  char msbuf[13];
2213 
2214  if (!saved_timeval_set)
2215  {
2216  gettimeofday(&saved_timeval, NULL);
2217  saved_timeval_set = true;
2218  }
2219 
2220  stamp_time = (pg_time_t) saved_timeval.tv_sec;
2221 
2222  /*
2223  * Note: we expect that guc.c will ensure that log_timezone is set up (at
2224  * least with a minimal GMT value) before Log_line_prefix can become
2225  * nonempty or CSV mode can be selected.
2226  */
2228  /* leave room for milliseconds... */
2229  "%Y-%m-%d %H:%M:%S %Z",
2230  pg_localtime(&stamp_time, log_timezone));
2231 
2232  /* 'paste' milliseconds into place... */
2233  sprintf(msbuf, ".%03d", (int) (saved_timeval.tv_usec / 1000));
2234  memcpy(formatted_log_time + 19, msbuf, 4);
2235 }
2236 
2237 /*
2238  * setup formatted_start_time
2239  */
2240 static void
2242 {
2243  pg_time_t stamp_time = (pg_time_t) MyStartTime;
2244 
2245  /*
2246  * Note: we expect that guc.c will ensure that log_timezone is set up (at
2247  * least with a minimal GMT value) before Log_line_prefix can become
2248  * nonempty or CSV mode can be selected.
2249  */
2251  "%Y-%m-%d %H:%M:%S %Z",
2252  pg_localtime(&stamp_time, log_timezone));
2253 }
2254 
2255 /*
2256  * process_log_prefix_padding --- helper function for processing the format
2257  * string in log_line_prefix
2258  *
2259  * Note: This function returns NULL if it finds something which
2260  * it deems invalid in the format string.
2261  */
2262 static const char *
2263 process_log_prefix_padding(const char *p, int *ppadding)
2264 {
2265  int paddingsign = 1;
2266  int padding = 0;
2267 
2268  if (*p == '-')
2269  {
2270  p++;
2271 
2272  if (*p == '\0') /* Did the buf end in %- ? */
2273  return NULL;
2274  paddingsign = -1;
2275  }
2276 
2277  /* generate an int version of the numerical string */
2278  while (*p >= '0' && *p <= '9')
2279  padding = padding * 10 + (*p++ - '0');
2280 
2281  /* format is invalid if it ends with the padding number */
2282  if (*p == '\0')
2283  return NULL;
2284 
2285  padding *= paddingsign;
2286  *ppadding = padding;
2287  return p;
2288 }
2289 
2290 /*
2291  * Format tag info for log lines; append to the provided buffer.
2292  */
2293 static void
2295 {
2296  /* static counter for line numbers */
2297  static long log_line_number = 0;
2298 
2299  /* has counter been reset in current process? */
2300  static int log_my_pid = 0;
2301  int padding;
2302  const char *p;
2303 
2304  /*
2305  * This is one of the few places where we'd rather not inherit a static
2306  * variable's value from the postmaster. But since we will, reset it when
2307  * MyProcPid changes. MyStartTime also changes when MyProcPid does, so
2308  * reset the formatted start timestamp too.
2309  */
2310  if (log_my_pid != MyProcPid)
2311  {
2312  log_line_number = 0;
2313  log_my_pid = MyProcPid;
2314  formatted_start_time[0] = '\0';
2315  }
2316  log_line_number++;
2317 
2318  if (Log_line_prefix == NULL)
2319  return; /* in case guc hasn't run yet */
2320 
2321  for (p = Log_line_prefix; *p != '\0'; p++)
2322  {
2323  if (*p != '%')
2324  {
2325  /* literal char, just copy */
2326  appendStringInfoChar(buf, *p);
2327  continue;
2328  }
2329 
2330  /* must be a '%', so skip to the next char */
2331  p++;
2332  if (*p == '\0')
2333  break; /* format error - ignore it */
2334  else if (*p == '%')
2335  {
2336  /* string contains %% */
2337  appendStringInfoChar(buf, '%');
2338  continue;
2339  }
2340 
2341 
2342  /*
2343  * Process any formatting which may exist after the '%'. Note that
2344  * process_log_prefix_padding moves p past the padding number if it
2345  * exists.
2346  *
2347  * Note: Since only '-', '0' to '9' are valid formatting characters we
2348  * can do a quick check here to pre-check for formatting. If the char
2349  * is not formatting then we can skip a useless function call.
2350  *
2351  * Further note: At least on some platforms, passing %*s rather than
2352  * %s to appendStringInfo() is substantially slower, so many of the
2353  * cases below avoid doing that unless non-zero padding is in fact
2354  * specified.
2355  */
2356  if (*p > '9')
2357  padding = 0;
2358  else if ((p = process_log_prefix_padding(p, &padding)) == NULL)
2359  break;
2360 
2361  /* process the option */
2362  switch (*p)
2363  {
2364  case 'a':
2365  if (MyProcPort)
2366  {
2367  const char *appname = application_name;
2368 
2369  if (appname == NULL || *appname == '\0')
2370  appname = _("[unknown]");
2371  if (padding != 0)
2372  appendStringInfo(buf, "%*s", padding, appname);
2373  else
2374  appendStringInfoString(buf, appname);
2375  }
2376  else if (padding != 0)
2378  padding > 0 ? padding : -padding);
2379 
2380  break;
2381  case 'b':
2382  {
2383  const char *backend_type_str;
2384 
2385  if (MyProcPid == PostmasterPid)
2386  backend_type_str = "postmaster";
2387  else if (MyBackendType == B_BG_WORKER)
2388  backend_type_str = MyBgworkerEntry->bgw_type;
2389  else
2390  backend_type_str = GetBackendTypeDesc(MyBackendType);
2391 
2392  if (padding != 0)
2393  appendStringInfo(buf, "%*s", padding, backend_type_str);
2394  else
2395  appendStringInfoString(buf, backend_type_str);
2396  break;
2397  }
2398  case 'u':
2399  if (MyProcPort)
2400  {
2401  const char *username = MyProcPort->user_name;
2402 
2403  if (username == NULL || *username == '\0')
2404  username = _("[unknown]");
2405  if (padding != 0)
2406  appendStringInfo(buf, "%*s", padding, username);
2407  else
2408  appendStringInfoString(buf, username);
2409  }
2410  else if (padding != 0)
2412  padding > 0 ? padding : -padding);
2413  break;
2414  case 'd':
2415  if (MyProcPort)
2416  {
2417  const char *dbname = MyProcPort->database_name;
2418 
2419  if (dbname == NULL || *dbname == '\0')
2420  dbname = _("[unknown]");
2421  if (padding != 0)
2422  appendStringInfo(buf, "%*s", padding, dbname);
2423  else
2424  appendStringInfoString(buf, dbname);
2425  }
2426  else if (padding != 0)
2428  padding > 0 ? padding : -padding);
2429  break;
2430  case 'c':
2431  if (padding != 0)
2432  {
2433  char strfbuf[128];
2434 
2435  snprintf(strfbuf, sizeof(strfbuf) - 1, "%lx.%x",
2436  (long) (MyStartTime), MyProcPid);
2437  appendStringInfo(buf, "%*s", padding, strfbuf);
2438  }
2439  else
2440  appendStringInfo(buf, "%lx.%x", (long) (MyStartTime), MyProcPid);
2441  break;
2442  case 'p':
2443  if (padding != 0)
2444  appendStringInfo(buf, "%*d", padding, MyProcPid);
2445  else
2446  appendStringInfo(buf, "%d", MyProcPid);
2447  break;
2448 
2449  case 'P':
2450  if (MyProc)
2451  {
2452  PGPROC *leader = MyProc->lockGroupLeader;
2453 
2454  /*
2455  * Show the leader only for active parallel workers. This
2456  * leaves out the leader of a parallel group.
2457  */
2458  if (leader == NULL || leader->pid == MyProcPid)
2460  padding > 0 ? padding : -padding);
2461  else if (padding != 0)
2462  appendStringInfo(buf, "%*d", padding, leader->pid);
2463  else
2464  appendStringInfo(buf, "%d", leader->pid);
2465  }
2466  else if (padding != 0)
2468  padding > 0 ? padding : -padding);
2469  break;
2470 
2471  case 'l':
2472  if (padding != 0)
2473  appendStringInfo(buf, "%*ld", padding, log_line_number);
2474  else
2475  appendStringInfo(buf, "%ld", log_line_number);
2476  break;
2477  case 'm':
2479  if (padding != 0)
2480  appendStringInfo(buf, "%*s", padding, formatted_log_time);
2481  else
2483  break;
2484  case 't':
2485  {
2486  pg_time_t stamp_time = (pg_time_t) time(NULL);
2487  char strfbuf[128];
2488 
2489  pg_strftime(strfbuf, sizeof(strfbuf),
2490  "%Y-%m-%d %H:%M:%S %Z",
2491  pg_localtime(&stamp_time, log_timezone));
2492  if (padding != 0)
2493  appendStringInfo(buf, "%*s", padding, strfbuf);
2494  else
2495  appendStringInfoString(buf, strfbuf);
2496  }
2497  break;
2498  case 'n':
2499  {
2500  char strfbuf[128];
2501 
2502  if (!saved_timeval_set)
2503  {
2504  gettimeofday(&saved_timeval, NULL);
2505  saved_timeval_set = true;
2506  }
2507 
2508  snprintf(strfbuf, sizeof(strfbuf), "%ld.%03d",
2509  (long) saved_timeval.tv_sec,
2510  (int) (saved_timeval.tv_usec / 1000));
2511 
2512  if (padding != 0)
2513  appendStringInfo(buf, "%*s", padding, strfbuf);
2514  else
2515  appendStringInfoString(buf, strfbuf);
2516  }
2517  break;
2518  case 's':
2519  if (formatted_start_time[0] == '\0')
2521  if (padding != 0)
2522  appendStringInfo(buf, "%*s", padding, formatted_start_time);
2523  else
2525  break;
2526  case 'i':
2527  if (MyProcPort)
2528  {
2529  const char *psdisp;
2530  int displen;
2531 
2532  psdisp = get_ps_display(&displen);
2533  if (padding != 0)
2534  appendStringInfo(buf, "%*s", padding, psdisp);
2535  else
2536  appendBinaryStringInfo(buf, psdisp, displen);
2537 
2538  }
2539  else if (padding != 0)
2541  padding > 0 ? padding : -padding);
2542  break;
2543  case 'r':
2545  {
2546  if (padding != 0)
2547  {
2548  if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
2549  {
2550  /*
2551  * This option is slightly special as the port
2552  * number may be appended onto the end. Here we
2553  * need to build 1 string which contains the
2554  * remote_host and optionally the remote_port (if
2555  * set) so we can properly align the string.
2556  */
2557 
2558  char *hostport;
2559 
2560  hostport = psprintf("%s(%s)", MyProcPort->remote_host, MyProcPort->remote_port);
2561  appendStringInfo(buf, "%*s", padding, hostport);
2562  pfree(hostport);
2563  }
2564  else
2565  appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
2566  }
2567  else
2568  {
2569  /* padding is 0, so we don't need a temp buffer */
2571  if (MyProcPort->remote_port &&
2572  MyProcPort->remote_port[0] != '\0')
2573  appendStringInfo(buf, "(%s)",
2575  }
2576 
2577  }
2578  else if (padding != 0)
2580  padding > 0 ? padding : -padding);
2581  break;
2582  case 'h':
2584  {
2585  if (padding != 0)
2586  appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
2587  else
2589  }
2590  else if (padding != 0)
2592  padding > 0 ? padding : -padding);
2593  break;
2594  case 'q':
2595  /* in postmaster and friends, stop if %q is seen */
2596  /* in a backend, just ignore */
2597  if (MyProcPort == NULL)
2598  return;
2599  break;
2600  case 'v':
2601  /* keep VXID format in sync with lockfuncs.c */
2602  if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
2603  {
2604  if (padding != 0)
2605  {
2606  char strfbuf[128];
2607 
2608  snprintf(strfbuf, sizeof(strfbuf) - 1, "%d/%u",
2610  appendStringInfo(buf, "%*s", padding, strfbuf);
2611  }
2612  else
2613  appendStringInfo(buf, "%d/%u", MyProc->backendId, MyProc->lxid);
2614  }
2615  else if (padding != 0)
2617  padding > 0 ? padding : -padding);
2618  break;
2619  case 'x':
2620  if (padding != 0)
2621  appendStringInfo(buf, "%*u", padding, GetTopTransactionIdIfAny());
2622  else
2624  break;
2625  case 'e':
2626  if (padding != 0)
2627  appendStringInfo(buf, "%*s", padding, unpack_sql_state(edata->sqlerrcode));
2628  else
2630  break;
2631  default:
2632  /* format error - ignore it */
2633  break;
2634  }
2635  }
2636 }
2637 
2638 /*
2639  * append a CSV'd version of a string to a StringInfo
2640  * We use the PostgreSQL defaults for CSV, i.e. quote = escape = '"'
2641  * If it's NULL, append nothing.
2642  */
2643 static inline void
2644 appendCSVLiteral(StringInfo buf, const char *data)
2645 {
2646  const char *p = data;
2647  char c;
2648 
2649  /* avoid confusing an empty string with NULL */
2650  if (p == NULL)
2651  return;
2652 
2653  appendStringInfoCharMacro(buf, '"');
2654  while ((c = *p++) != '\0')
2655  {
2656  if (c == '"')
2657  appendStringInfoCharMacro(buf, '"');
2658  appendStringInfoCharMacro(buf, c);
2659  }
2660  appendStringInfoCharMacro(buf, '"');
2661 }
2662 
2663 /*
2664  * Constructs the error message, depending on the Errordata it gets, in a CSV
2665  * format which is described in doc/src/sgml/config.sgml.
2666  */
2667 static void
2669 {
2671  bool print_stmt = false;
2672 
2673  /* static counter for line numbers */
2674  static long log_line_number = 0;
2675 
2676  /* has counter been reset in current process? */
2677  static int log_my_pid = 0;
2678 
2679  /*
2680  * This is one of the few places where we'd rather not inherit a static
2681  * variable's value from the postmaster. But since we will, reset it when
2682  * MyProcPid changes.
2683  */
2684  if (log_my_pid != MyProcPid)
2685  {
2686  log_line_number = 0;
2687  log_my_pid = MyProcPid;
2688  formatted_start_time[0] = '\0';
2689  }
2690  log_line_number++;
2691 
2692  initStringInfo(&buf);
2693 
2694  /*
2695  * timestamp with milliseconds
2696  *
2697  * Check if the timestamp is already calculated for the syslog message,
2698  * and use it if so. Otherwise, get the current timestamp. This is done
2699  * to put same timestamp in both syslog and csvlog messages.
2700  */
2701  if (formatted_log_time[0] == '\0')
2703 
2705  appendStringInfoChar(&buf, ',');
2706 
2707  /* username */
2708  if (MyProcPort)
2710  appendStringInfoChar(&buf, ',');
2711 
2712  /* database name */
2713  if (MyProcPort)
2715  appendStringInfoChar(&buf, ',');
2716 
2717  /* Process id */
2718  if (MyProcPid != 0)
2719  appendStringInfo(&buf, "%d", MyProcPid);
2720  appendStringInfoChar(&buf, ',');
2721 
2722  /* Remote host and port */
2724  {
2725  appendStringInfoChar(&buf, '"');
2727  if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
2728  {
2729  appendStringInfoChar(&buf, ':');
2731  }
2732  appendStringInfoChar(&buf, '"');
2733  }
2734  appendStringInfoChar(&buf, ',');
2735 
2736  /* session id */
2737  appendStringInfo(&buf, "%lx.%x", (long) MyStartTime, MyProcPid);
2738  appendStringInfoChar(&buf, ',');
2739 
2740  /* Line number */
2741  appendStringInfo(&buf, "%ld", log_line_number);
2742  appendStringInfoChar(&buf, ',');
2743 
2744  /* PS display */
2745  if (MyProcPort)
2746  {
2747  StringInfoData msgbuf;
2748  const char *psdisp;
2749  int displen;
2750 
2751  initStringInfo(&msgbuf);
2752 
2753  psdisp = get_ps_display(&displen);
2754  appendBinaryStringInfo(&msgbuf, psdisp, displen);
2755  appendCSVLiteral(&buf, msgbuf.data);
2756 
2757  pfree(msgbuf.data);
2758  }
2759  appendStringInfoChar(&buf, ',');
2760 
2761  /* session start timestamp */
2762  if (formatted_start_time[0] == '\0')
2765  appendStringInfoChar(&buf, ',');
2766 
2767  /* Virtual transaction id */
2768  /* keep VXID format in sync with lockfuncs.c */
2769  if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
2770  appendStringInfo(&buf, "%d/%u", MyProc->backendId, MyProc->lxid);
2771  appendStringInfoChar(&buf, ',');
2772 
2773  /* Transaction id */
2775  appendStringInfoChar(&buf, ',');
2776 
2777  /* Error severity */
2779  appendStringInfoChar(&buf, ',');
2780 
2781  /* SQL state code */
2783  appendStringInfoChar(&buf, ',');
2784 
2785  /* errmessage */
2786  appendCSVLiteral(&buf, edata->message);
2787  appendStringInfoChar(&buf, ',');
2788 
2789  /* errdetail or errdetail_log */
2790  if (edata->detail_log)
2791  appendCSVLiteral(&buf, edata->detail_log);
2792  else
2793  appendCSVLiteral(&buf, edata->detail);
2794  appendStringInfoChar(&buf, ',');
2795 
2796  /* errhint */
2797  appendCSVLiteral(&buf, edata->hint);
2798  appendStringInfoChar(&buf, ',');
2799 
2800  /* internal query */
2801  appendCSVLiteral(&buf, edata->internalquery);
2802  appendStringInfoChar(&buf, ',');
2803 
2804  /* if printed internal query, print internal pos too */
2805  if (edata->internalpos > 0 && edata->internalquery != NULL)
2806  appendStringInfo(&buf, "%d", edata->internalpos);
2807  appendStringInfoChar(&buf, ',');
2808 
2809  /* errcontext */
2810  if (!edata->hide_ctx)
2811  appendCSVLiteral(&buf, edata->context);
2812  appendStringInfoChar(&buf, ',');
2813 
2814  /* user query --- only reported if not disabled by the caller */
2816  debug_query_string != NULL &&
2817  !edata->hide_stmt)
2818  print_stmt = true;
2819  if (print_stmt)
2821  appendStringInfoChar(&buf, ',');
2822  if (print_stmt && edata->cursorpos > 0)
2823  appendStringInfo(&buf, "%d", edata->cursorpos);
2824  appendStringInfoChar(&buf, ',');
2825 
2826  /* file error location */
2828  {
2829  StringInfoData msgbuf;
2830 
2831  initStringInfo(&msgbuf);
2832 
2833  if (edata->funcname && edata->filename)
2834  appendStringInfo(&msgbuf, "%s, %s:%d",
2835  edata->funcname, edata->filename,
2836  edata->lineno);
2837  else if (edata->filename)
2838  appendStringInfo(&msgbuf, "%s:%d",
2839  edata->filename, edata->lineno);
2840  appendCSVLiteral(&buf, msgbuf.data);
2841  pfree(msgbuf.data);
2842  }
2843  appendStringInfoChar(&buf, ',');
2844 
2845  /* application name */
2846  if (application_name)
2848 
2849  appendStringInfoChar(&buf, ',');
2850 
2851  /* backend type */
2852  if (MyProcPid == PostmasterPid)
2853  appendCSVLiteral(&buf, "postmaster");
2854  else if (MyBackendType == B_BG_WORKER)
2856  else
2858 
2859  appendStringInfoChar(&buf, ',');
2860 
2861  /* leader PID */
2862  if (MyProc)
2863  {
2864  PGPROC *leader = MyProc->lockGroupLeader;
2865 
2866  /*
2867  * Show the leader only for active parallel workers. This leaves out
2868  * the leader of a parallel group.
2869  */
2870  if (leader && leader->pid != MyProcPid)
2871  appendStringInfo(&buf, "%d", leader->pid);
2872  }
2873 
2874  appendStringInfoChar(&buf, '\n');
2875 
2876  /* If in the syslogger process, try to write messages direct to file */
2877  if (MyBackendType == B_LOGGER)
2879  else
2881 
2882  pfree(buf.data);
2883 }
2884 
2885 /*
2886  * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
2887  * static buffer.
2888  */
2889 char *
2890 unpack_sql_state(int sql_state)
2891 {
2892  static char buf[12];
2893  int i;
2894 
2895  for (i = 0; i < 5; i++)
2896  {
2897  buf[i] = PGUNSIXBIT(sql_state);
2898  sql_state >>= 6;
2899  }
2900 
2901  buf[i] = '\0';
2902  return buf;
2903 }
2904 
2905 
2906 /*
2907  * Write error report to server's log
2908  */
2909 static void
2911 {
2913 
2914  initStringInfo(&buf);
2915 
2916  saved_timeval_set = false;
2917  formatted_log_time[0] = '\0';
2918 
2919  log_line_prefix(&buf, edata);
2920  appendStringInfo(&buf, "%s: ", _(error_severity(edata->elevel)));
2921 
2923  appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
2924 
2925  if (edata->message)
2926  append_with_tabs(&buf, edata->message);
2927  else
2928  append_with_tabs(&buf, _("missing error text"));
2929 
2930  if (edata->cursorpos > 0)
2931  appendStringInfo(&buf, _(" at character %d"),
2932  edata->cursorpos);
2933  else if (edata->internalpos > 0)
2934  appendStringInfo(&buf, _(" at character %d"),
2935  edata->internalpos);
2936 
2937  appendStringInfoChar(&buf, '\n');
2938 
2940  {
2941  if (edata->detail_log)
2942  {
2943  log_line_prefix(&buf, edata);
2944  appendStringInfoString(&buf, _("DETAIL: "));
2945  append_with_tabs(&buf, edata->detail_log);
2946  appendStringInfoChar(&buf, '\n');
2947  }
2948  else if (edata->detail)
2949  {
2950  log_line_prefix(&buf, edata);
2951  appendStringInfoString(&buf, _("DETAIL: "));
2952  append_with_tabs(&buf, edata->detail);
2953  appendStringInfoChar(&buf, '\n');
2954  }
2955  if (edata->hint)
2956  {
2957  log_line_prefix(&buf, edata);
2958  appendStringInfoString(&buf, _("HINT: "));
2959  append_with_tabs(&buf, edata->hint);
2960  appendStringInfoChar(&buf, '\n');
2961  }
2962  if (edata->internalquery)
2963  {
2964  log_line_prefix(&buf, edata);
2965  appendStringInfoString(&buf, _("QUERY: "));
2966  append_with_tabs(&buf, edata->internalquery);
2967  appendStringInfoChar(&buf, '\n');
2968  }
2969  if (edata->context && !edata->hide_ctx)
2970  {
2971  log_line_prefix(&buf, edata);
2972  appendStringInfoString(&buf, _("CONTEXT: "));
2973  append_with_tabs(&buf, edata->context);
2974  appendStringInfoChar(&buf, '\n');
2975  }
2977  {
2978  /* assume no newlines in funcname or filename... */
2979  if (edata->funcname && edata->filename)
2980  {
2981  log_line_prefix(&buf, edata);
2982  appendStringInfo(&buf, _("LOCATION: %s, %s:%d\n"),
2983  edata->funcname, edata->filename,
2984  edata->lineno);
2985  }
2986  else if (edata->filename)
2987  {
2988  log_line_prefix(&buf, edata);
2989  appendStringInfo(&buf, _("LOCATION: %s:%d\n"),
2990  edata->filename, edata->lineno);
2991  }
2992  }
2993  if (edata->backtrace)
2994  {
2995  log_line_prefix(&buf, edata);
2996  appendStringInfoString(&buf, _("BACKTRACE: "));
2997  append_with_tabs(&buf, edata->backtrace);
2998  appendStringInfoChar(&buf, '\n');
2999  }
3000  }
3001 
3002  /*
3003  * If the user wants the query that generated this error logged, do it.
3004  */
3006  debug_query_string != NULL &&
3007  !edata->hide_stmt)
3008  {
3009  log_line_prefix(&buf, edata);
3010  appendStringInfoString(&buf, _("STATEMENT: "));
3012  appendStringInfoChar(&buf, '\n');
3013  }
3014 
3015 #ifdef HAVE_SYSLOG
3016  /* Write to syslog, if enabled */
3018  {
3019  int syslog_level;
3020 
3021  switch (edata->elevel)
3022  {
3023  case DEBUG5:
3024  case DEBUG4:
3025  case DEBUG3:
3026  case DEBUG2:
3027  case DEBUG1:
3028  syslog_level = LOG_DEBUG;
3029  break;
3030  case LOG:
3031  case LOG_SERVER_ONLY:
3032  case INFO:
3033  syslog_level = LOG_INFO;
3034  break;
3035  case NOTICE:
3036  case WARNING:
3037  syslog_level = LOG_NOTICE;
3038  break;
3039  case ERROR:
3040  syslog_level = LOG_WARNING;
3041  break;
3042  case FATAL:
3043  syslog_level = LOG_ERR;
3044  break;
3045  case PANIC:
3046  default:
3047  syslog_level = LOG_CRIT;
3048  break;
3049  }
3050 
3051  write_syslog(syslog_level, buf.data);
3052  }
3053 #endif /* HAVE_SYSLOG */
3054 
3055 #ifdef WIN32
3056  /* Write to eventlog, if enabled */
3058  {
3059  write_eventlog(edata->elevel, buf.data, buf.len);
3060  }
3061 #endif /* WIN32 */
3062 
3063  /* Write to stderr, if enabled */
3065  {
3066  /*
3067  * Use the chunking protocol if we know the syslogger should be
3068  * catching stderr output, and we are not ourselves the syslogger.
3069  * Otherwise, just do a vanilla write to stderr.
3070  */
3072  write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_STDERR);
3073 #ifdef WIN32
3074 
3075  /*
3076  * In a win32 service environment, there is no usable stderr. Capture
3077  * anything going there and write it to the eventlog instead.
3078  *
3079  * If stderr redirection is active, it was OK to write to stderr above
3080  * because that's really a pipe to the syslogger process.
3081  */
3082  else if (pgwin32_is_service())
3083  write_eventlog(edata->elevel, buf.data, buf.len);
3084 #endif
3085  else
3086  write_console(buf.data, buf.len);
3087  }
3088 
3089  /* If in the syslogger process, try to write messages direct to file */
3090  if (MyBackendType == B_LOGGER)
3091  write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_STDERR);
3092 
3093  /* Write to CSV log if enabled */
3095  {
3097  {
3098  /*
3099  * send CSV data if it's safe to do so (syslogger doesn't need the
3100  * pipe). First get back the space in the message buffer.
3101  */
3102  pfree(buf.data);
3103  write_csvlog(edata);
3104  }
3105  else
3106  {
3107  /*
3108  * syslogger not up (yet), so just dump the message to stderr,
3109  * unless we already did so above.
3110  */
3111  if (!(Log_destination & LOG_DESTINATION_STDERR) &&
3113  write_console(buf.data, buf.len);
3114  pfree(buf.data);
3115  }
3116  }
3117  else
3118  {
3119  pfree(buf.data);
3120  }
3121 }
3122 
3123 /*
3124  * Send data to the syslogger using the chunked protocol
3125  *
3126  * Note: when there are multiple backends writing into the syslogger pipe,
3127  * it's critical that each write go into the pipe indivisibly, and not
3128  * get interleaved with data from other processes. Fortunately, the POSIX
3129  * spec requires that writes to pipes be atomic so long as they are not
3130  * more than PIPE_BUF bytes long. So we divide long messages into chunks
3131  * that are no more than that length, and send one chunk per write() call.
3132  * The collector process knows how to reassemble the chunks.
3133  *
3134  * Because of the atomic write requirement, there are only two possible
3135  * results from write() here: -1 for failure, or the requested number of
3136  * bytes. There is not really anything we can do about a failure; retry would
3137  * probably be an infinite loop, and we can't even report the error usefully.
3138  * (There is noplace else we could send it!) So we might as well just ignore
3139  * the result from write(). However, on some platforms you get a compiler
3140  * warning from ignoring write()'s result, so do a little dance with casting
3141  * rc to void to shut up the compiler.
3142  */
3143 static void
3144 write_pipe_chunks(char *data, int len, int dest)
3145 {
3146  PipeProtoChunk p;
3147  int fd = fileno(stderr);
3148  int rc;
3149 
3150  Assert(len > 0);
3151 
3152  p.proto.nuls[0] = p.proto.nuls[1] = '\0';
3153  p.proto.pid = MyProcPid;
3154 
3155  /* write all but the last chunk */
3156  while (len > PIPE_MAX_PAYLOAD)
3157  {
3158  p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'F' : 'f');
3160  memcpy(p.proto.data, data, PIPE_MAX_PAYLOAD);
3161  rc = write(fd, &p, PIPE_HEADER_SIZE + PIPE_MAX_PAYLOAD);
3162  (void) rc;
3163  data += PIPE_MAX_PAYLOAD;
3164  len -= PIPE_MAX_PAYLOAD;
3165  }
3166 
3167  /* write the last chunk */
3168  p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'T' : 't');
3169  p.proto.len = len;
3170  memcpy(p.proto.data, data, len);
3171  rc = write(fd, &p, PIPE_HEADER_SIZE + len);
3172  (void) rc;
3173 }
3174 
3175 
3176 /*
3177  * Append a text string to the error report being built for the client.
3178  *
3179  * This is ordinarily identical to pq_sendstring(), but if we are in
3180  * error recursion trouble we skip encoding conversion, because of the
3181  * possibility that the problem is a failure in the encoding conversion
3182  * subsystem itself. Code elsewhere should ensure that the passed-in
3183  * strings will be plain 7-bit ASCII, and thus not in need of conversion,
3184  * in such cases. (In particular, we disable localization of error messages
3185  * to help ensure that's true.)
3186  */
3187 static void
3189 {
3191  pq_send_ascii_string(buf, str);
3192  else
3193  pq_sendstring(buf, str);
3194 }
3195 
3196 /*
3197  * Write error report to client
3198  */
3199 static void
3201 {
3202  StringInfoData msgbuf;
3203 
3204  /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
3205  pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
3206 
3208  {
3209  /* New style with separate fields */
3210  const char *sev;
3211  char tbuf[12];
3212  int ssval;
3213  int i;
3214 
3215  sev = error_severity(edata->elevel);
3216  pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
3217  err_sendstring(&msgbuf, _(sev));
3219  err_sendstring(&msgbuf, sev);
3220 
3221  /* unpack MAKE_SQLSTATE code */
3222  ssval = edata->sqlerrcode;
3223  for (i = 0; i < 5; i++)
3224  {
3225  tbuf[i] = PGUNSIXBIT(ssval);
3226  ssval >>= 6;
3227  }
3228  tbuf[i] = '\0';
3229 
3230  pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
3231  err_sendstring(&msgbuf, tbuf);
3232 
3233  /* M field is required per protocol, so always send something */
3235  if (edata->message)
3236  err_sendstring(&msgbuf, edata->message);
3237  else
3238  err_sendstring(&msgbuf, _("missing error text"));
3239 
3240  if (edata->detail)
3241  {
3243  err_sendstring(&msgbuf, edata->detail);
3244  }
3245 
3246  /* detail_log is intentionally not used here */
3247 
3248  if (edata->hint)
3249  {
3251  err_sendstring(&msgbuf, edata->hint);
3252  }
3253 
3254  if (edata->context)
3255  {
3256  pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
3257  err_sendstring(&msgbuf, edata->context);
3258  }
3259 
3260  if (edata->schema_name)
3261  {
3262  pq_sendbyte(&msgbuf, PG_DIAG_SCHEMA_NAME);
3263  err_sendstring(&msgbuf, edata->schema_name);
3264  }
3265 
3266  if (edata->table_name)
3267  {
3268  pq_sendbyte(&msgbuf, PG_DIAG_TABLE_NAME);
3269  err_sendstring(&msgbuf, edata->table_name);
3270  }
3271 
3272  if (edata->column_name)
3273  {
3274  pq_sendbyte(&msgbuf, PG_DIAG_COLUMN_NAME);
3275  err_sendstring(&msgbuf, edata->column_name);
3276  }
3277 
3278  if (edata->datatype_name)
3279  {
3281  err_sendstring(&msgbuf, edata->datatype_name);
3282  }
3283 
3284  if (edata->constraint_name)
3285  {
3287  err_sendstring(&msgbuf, edata->constraint_name);
3288  }
3289 
3290  if (edata->cursorpos > 0)
3291  {
3292  snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
3294  err_sendstring(&msgbuf, tbuf);
3295  }
3296 
3297  if (edata->internalpos > 0)
3298  {
3299  snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
3301  err_sendstring(&msgbuf, tbuf);
3302  }
3303 
3304  if (edata->internalquery)
3305  {
3307  err_sendstring(&msgbuf, edata->internalquery);
3308  }
3309 
3310  if (edata->filename)
3311  {
3312  pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
3313  err_sendstring(&msgbuf, edata->filename);
3314  }
3315 
3316  if (edata->lineno > 0)
3317  {
3318  snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
3319  pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
3320  err_sendstring(&msgbuf, tbuf);
3321  }
3322 
3323  if (edata->funcname)
3324  {
3326  err_sendstring(&msgbuf, edata->funcname);
3327  }
3328 
3329  pq_sendbyte(&msgbuf, '\0'); /* terminator */
3330  }
3331  else
3332  {
3333  /* Old style --- gin up a backwards-compatible message */
3335 
3336  initStringInfo(&buf);
3337 
3338  appendStringInfo(&buf, "%s: ", _(error_severity(edata->elevel)));
3339 
3340  if (edata->show_funcname && edata->funcname)
3341  appendStringInfo(&buf, "%s: ", edata->funcname);
3342 
3343  if (edata->message)
3344  appendStringInfoString(&buf, edata->message);
3345  else
3346  appendStringInfoString(&buf, _("missing error text"));
3347 
3348  if (edata->cursorpos > 0)
3349  appendStringInfo(&buf, _(" at character %d"),
3350  edata->cursorpos);
3351  else if (edata->internalpos > 0)
3352  appendStringInfo(&buf, _(" at character %d"),
3353  edata->internalpos);
3354 
3355  appendStringInfoChar(&buf, '\n');
3356 
3357  err_sendstring(&msgbuf, buf.data);
3358 
3359  pfree(buf.data);
3360  }
3361 
3362  pq_endmessage(&msgbuf);
3363 
3364  /*
3365  * This flush is normally not necessary, since postgres.c will flush out
3366  * waiting data when control returns to the main loop. But it seems best
3367  * to leave it here, so that the client has some clue what happened if the
3368  * backend dies before getting back to the main loop ... error/notice
3369  * messages should not be a performance-critical path anyway, so an extra
3370  * flush won't hurt much ...
3371  */
3372  pq_flush();
3373 }
3374 
3375 
3376 /*
3377  * Support routines for formatting error messages.
3378  */
3379 
3380 
3381 /*
3382  * error_severity --- get string representing elevel
3383  *
3384  * The string is not localized here, but we mark the strings for translation
3385  * so that callers can invoke _() on the result.
3386  */
3387 static const char *
3389 {
3390  const char *prefix;
3391 
3392  switch (elevel)
3393  {
3394  case DEBUG1:
3395  case DEBUG2:
3396  case DEBUG3:
3397  case DEBUG4:
3398  case DEBUG5:
3399  prefix = gettext_noop("DEBUG");
3400  break;
3401  case LOG:
3402  case LOG_SERVER_ONLY:
3403  prefix = gettext_noop("LOG");
3404  break;
3405  case INFO:
3406  prefix = gettext_noop("INFO");
3407  break;
3408  case NOTICE:
3409  prefix = gettext_noop("NOTICE");
3410  break;
3411  case WARNING:
3412  prefix = gettext_noop("WARNING");
3413  break;
3414  case ERROR:
3415  prefix = gettext_noop("ERROR");
3416  break;
3417  case FATAL:
3418  prefix = gettext_noop("FATAL");
3419  break;
3420  case PANIC:
3421  prefix = gettext_noop("PANIC");
3422  break;
3423  default:
3424  prefix = "???";
3425  break;
3426  }
3427 
3428  return prefix;
3429 }
3430 
3431 
3432 /*
3433  * append_with_tabs
3434  *
3435  * Append the string to the StringInfo buffer, inserting a tab after any
3436  * newline.
3437  */
3438 static void
3440 {
3441  char ch;
3442 
3443  while ((ch = *str++) != '\0')
3444  {
3445  appendStringInfoCharMacro(buf, ch);
3446  if (ch == '\n')
3447  appendStringInfoCharMacro(buf, '\t');
3448  }
3449 }
3450 
3451 
3452 /*
3453  * Write errors to stderr (or by equal means when stderr is
3454  * not available). Used before ereport/elog can be used
3455  * safely (memory context, GUC load etc)
3456  */
3457 void
3458 write_stderr(const char *fmt,...)
3459 {
3460  va_list ap;
3461 
3462 #ifdef WIN32
3463  char errbuf[2048]; /* Arbitrary size? */
3464 #endif
3465 
3466  fmt = _(fmt);
3467 
3468  va_start(ap, fmt);
3469 #ifndef WIN32
3470  /* On Unix, we just fprintf to stderr */
3471  vfprintf(stderr, fmt, ap);
3472  fflush(stderr);
3473 #else
3474  vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
3475 
3476  /*
3477  * On Win32, we print to stderr if running on a console, or write to
3478  * eventlog if running as a service
3479  */
3480  if (pgwin32_is_service()) /* Running as a service */
3481  {
3482  write_eventlog(ERROR, errbuf, strlen(errbuf));
3483  }
3484  else
3485  {
3486  /* Not running as service, write to stderr */
3487  write_console(errbuf, strlen(errbuf));
3488  fflush(stderr);
3489  }
3490 #endif
3491  va_end(ap);
3492 }
3493 
3494 
3495 /*
3496  * is_log_level_output -- is elevel logically >= log_min_level?
3497  *
3498  * We use this for tests that should consider LOG to sort out-of-order,
3499  * between ERROR and FATAL. Generally this is the right thing for testing
3500  * whether a message should go to the postmaster log, whereas a simple >=
3501  * test is correct for testing whether the message should go to the client.
3502  */
3503 static bool
3504 is_log_level_output(int elevel, int log_min_level)
3505 {
3506  if (elevel == LOG || elevel == LOG_SERVER_ONLY)
3507  {
3508  if (log_min_level == LOG || log_min_level <= ERROR)
3509  return true;
3510  }
3511  else if (log_min_level == LOG)
3512  {
3513  /* elevel != LOG */
3514  if (elevel >= FATAL)
3515  return true;
3516  }
3517  /* Neither is LOG */
3518  else if (elevel >= log_min_level)
3519  return true;
3520 
3521  return false;
3522 }
3523 
3524 /*
3525  * Adjust the level of a recovery-related message per trace_recovery_messages.
3526  *
3527  * The argument is the default log level of the message, eg, DEBUG2. (This
3528  * should only be applied to DEBUGn log messages, otherwise it's a no-op.)
3529  * If the level is >= trace_recovery_messages, we return LOG, causing the
3530  * message to be logged unconditionally (for most settings of
3531  * log_min_messages). Otherwise, we return the argument unchanged.
3532  * The message will then be shown based on the setting of log_min_messages.
3533  *
3534  * Intention is to keep this for at least the whole of the 9.0 production
3535  * release, so we can more easily diagnose production problems in the field.
3536  * It should go away eventually, though, because it's an ugly and
3537  * hard-to-explain kluge.
3538  */
3539 int
3540 trace_recovery(int trace_level)
3541 {
3542  if (trace_level < LOG &&
3543  trace_level >= trace_recovery_messages)
3544  return LOG;
3545 
3546  return trace_level;
3547 }
#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:1068
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:144
const char * GetBackendTypeDesc(BackendType backendType)
Definition: miscinit.c:230
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:1374
#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:931
BackendType MyBackendType
Definition: miscinit.c:62
#define write(a, b, c)
Definition: win32.h:14
ErrorData * CopyErrorData(void)
Definition: elog.c:1471
#define FORMATTED_TS_LEN
Definition: elog.c:157
static pg_noinline void set_backtrace(ErrorData *edata, int num_skip)
Definition: elog.c:867
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:1187
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:2890
pg_time_t MyStartTime
Definition: globals.c:41
#define Min(x, y)
Definition: c.h:928
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:1139
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:1311
int errhidestmt(bool hide_stmt)
Definition: elog.c:1139
#define MemSet(start, val, len)
Definition: c.h:950
#define INFO
Definition: elog.h:33
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:195
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:137
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:1772
void pq_send_ascii_string(StringInfo buf, const char *str)
Definition: pqformat.c:229
#define lengthof(array)
Definition: c.h:676
#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:2241
struct ErrorContextCallback * previous
Definition: elog.h:228
#define PANIC
Definition: elog.h:53
#define EVALUATE_MESSAGE(domain, targetfield, appendval, translateit)
Definition: elog.c:740
static int fd(const char *x, int i)
Definition: preproc-init.c:105
void FlushErrorState(void)
Definition: elog.c:1565
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:87
int errdetail_internal(const char *fmt,...)
Definition: elog.c:981
int trace_recovery(int trace_level)
Definition: elog.c:3540
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:30
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:2910
#define pg_noinline
Definition: c.h:179
#define sprintf
Definition: port.h:217
bool ClientAuthInProgress
Definition: postmaster.c:368
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:1387
#define ERRCODE_WRONG_OBJECT_TYPE
void pfree(void *pointer)
Definition: mcxt.c:1057
#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:2644
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERRCODE_INSUFFICIENT_PRIVILEGE
void FreeErrorData(ErrorData *edata)
Definition: elog.c:1527
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:3504
#define vsnprintf
Definition: port.h:214
#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:2668
static void append_with_tabs(StringInfo buf, const char *str)
Definition: elog.c:3439
void pg_re_throw(void)
Definition: elog.c:1710
#define DEBUG2
Definition: elog.h:24
int errbacktrace(void)
Definition: elog.c:843
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static void write_console(const char *line, int len)
Definition: elog.c:2138
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:68
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:1122
int errdetail(const char *fmt,...)
Definition: elog.c:954
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:1328
#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:1002
#define EVALUATE_MESSAGE_PLURAL(domain, targetfield, appendval)
Definition: elog.c:776
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:425
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:1839
#define pg_attribute_format_arg(a)
Definition: c.h:130
int getinternalerrposition(void)
Definition: elog.c:1345
int errcode_for_socket_access(void)
Definition: elog.c:704
void ThrowErrorData(ErrorData *edata)
Definition: elog.c:1590
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:3200
char * datatype_name
Definition: elog.h:375
static const char * process_log_prefix_padding(const char *p, int *padding)
Definition: elog.c:2263
int elevel
Definition: elog.h:353
static int elevel
Definition: vacuumlazy.c:333
#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:1157
#define InvalidBackendId
Definition: backendid.h:23
static void set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str)
Definition: elog.c:1298
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:1119
void EmitErrorReport(void)
Definition: elog.c:1420
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:1375
#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:1179
int errdetail_log_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1023
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:134
#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:3144
#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:1232
#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:371
int errmsg_internal(const char *fmt,...)
Definition: elog.c:908
#define Max(x, y)
Definition: c.h:922
#define DEFAULT_EVENT_SOURCE
#define Assert(condition)
Definition: c.h:746
void write_stderr(const char *fmt,...)
Definition: elog.c:3458
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:51
bool syslog_split_messages
Definition: elog.c:113
int errcontext_msg(const char *fmt,...)
Definition: elog.c:1093
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1046
static void err_sendstring(StringInfo buf, const char *str)
Definition: elog.c:3188
#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
#define ALL_CONNECTION_FAILURE_ERRNOS
Definition: port.h:114
static char * filename
Definition: pg_dumpall.c:91
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:950
int errmsg(const char *fmt,...)
Definition: elog.c:821
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1174
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:2209
int client_min_messages
Definition: guc.c:539
static const char * error_severity(int elevel)
Definition: elog.c:3388
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:218
#define DEBUG5
Definition: elog.h:20
CommandDest whereToSendOutput
Definition: postgres.c:91
int err_generic_string(int field, const char *str)
Definition: elog.c:1262
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:1378
char * constraint_name
Definition: elog.h:376
Definition: proc.h:112
#define snprintf
Definition: port.h:215
int pid
Definition: proc.h:137
#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:1649
char * message
Definition: elog.h:365
PGPROC * lockGroupLeader
Definition: proc.h:239
int errhidecontext(bool hide_ctx)
Definition: elog.c:1158
int errposition(int cursorpos)
Definition: elog.c:1196
#define PG_DIAG_CONTEXT
Definition: postgres_ext.h:64
static void log_line_prefix(StringInfo buf, ErrorData *edata)
Definition: elog.c:2294
static char formatted_start_time[FORMATTED_TS_LEN]
Definition: elog.c:158
LocalTransactionId lxid
Definition: proc.h:134
int internalerrposition(int cursorpos)
Definition: elog.c:1212