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