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