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