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