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