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