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