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