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