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