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