1 /*--------------------------------------------------------------------
2  * Symbols referenced in this file:
3  * - elog_start
4  * - write_stderr
5  * - err_gettext
6  * - errstart
7  * - PG_exception_stack
8  * - in_error_recursion_trouble
9  * - error_context_stack
10  * - is_log_level_output
11  * - recursion_depth
12  * - errfinish
13  * - pg_re_throw
14  * - EmitErrorReport
15  * - emit_log_hook
16  * - send_message_to_server_log
17  * - send_message_to_frontend
18  * - errmsg_internal
19  * - errcode
20  * - errmsg
21  * - errdetail
22  * - expand_fmt_string
23  * - useful_strerror
24  * - get_errno_symbol
25  * - errordata_stack_depth
26  * - errordata
27  * - elog_finish
28  * - errhint
29  * - errposition
30  * - internalerrposition
31  * - internalerrquery
32  * - geterrposition
33  * - getinternalerrposition
34  * - set_errcontext_domain
35  * - errcontext_msg
36  * - CopyErrorData
37  * - FlushErrorState
38  *--------------------------------------------------------------------
39  */
40 
41 /*-------------------------------------------------------------------------
42  *
43  * elog.c
44  *	  error logging and reporting
45  *
46  * Because of the extremely high rate at which log messages can be generated,
47  * we need to be mindful of the performance cost of obtaining any information
48  * that may be logged.  Also, it's important to keep in mind that this code may
49  * get called from within an aborted transaction, in which case operations
50  * such as syscache lookups are unsafe.
51  *
52  * Some notes about recursion and errors during error processing:
53  *
54  * We need to be robust about recursive-error scenarios --- for example,
55  * if we run out of memory, it's important to be able to report that fact.
56  * There are a number of considerations that go into this.
57  *
58  * First, distinguish between re-entrant use and actual recursion.  It
59  * is possible for an error or warning message to be emitted while the
60  * parameters for an error message are being computed.  In this case
61  * errstart has been called for the outer message, and some field values
62  * may have already been saved, but we are not actually recursing.  We handle
63  * this by providing a (small) stack of ErrorData records.  The inner message
64  * can be computed and sent without disturbing the state of the outer message.
65  * (If the inner message is actually an error, this isn't very interesting
66  * because control won't come back to the outer message generator ... but
67  * if the inner message is only debug or log data, this is critical.)
68  *
69  * Second, actual recursion will occur if an error is reported by one of
70  * the elog.c routines or something they call.  By far the most probable
71  * scenario of this sort is "out of memory"; and it's also the nastiest
72  * to handle because we'd likely also run out of memory while trying to
73  * report this error!  Our escape hatch for this case is to reset the
74  * ErrorContext to empty before trying to process the inner error.  Since
75  * ErrorContext is guaranteed to have at least 8K of space in it (see mcxt.c),
76  * we should be able to process an "out of memory" message successfully.
77  * Since we lose the prior error state due to the reset, we won't be able
78  * to return to processing the original error, but we wouldn't have anyway.
79  * (NOTE: the escape hatch is not used for recursive situations where the
80  * inner message is of less than ERROR severity; in that case we just
81  * try to process it and return normally.  Usually this will work, but if
82  * it ends up in infinite recursion, we will PANIC due to error stack
83  * overflow.)
84  *
85  *
86  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
87  * Portions Copyright (c) 1994, Regents of the University of California
88  *
89  *
90  * IDENTIFICATION
91  *	  src/backend/utils/error/elog.c
92  *
93  *-------------------------------------------------------------------------
94  */
95 #include "postgres.h"
96 
97 #include <fcntl.h>
98 #include <time.h>
99 #include <unistd.h>
100 #include <signal.h>
101 #include <ctype.h>
102 #ifdef HAVE_SYSLOG
103 #include <syslog.h>
104 #endif
105 
106 #include "access/transam.h"
107 #include "access/xact.h"
108 #include "libpq/libpq.h"
109 #include "libpq/pqformat.h"
110 #include "mb/pg_wchar.h"
111 #include "miscadmin.h"
112 #include "postmaster/postmaster.h"
113 #include "postmaster/syslogger.h"
114 #include "storage/ipc.h"
115 #include "storage/proc.h"
116 #include "tcop/tcopprot.h"
117 #include "utils/guc.h"
118 #include "utils/memutils.h"
119 #include "utils/ps_status.h"
120 
121 
122 /* In this module, access gettext() via err_gettext() */
123 #undef _
124 #define _(x) err_gettext(x)
125 
126 
127 /* Global variables */
128 __thread ErrorContextCallback *error_context_stack = NULL;
129 
130 
131 __thread sigjmp_buf *PG_exception_stack = NULL;
132 
133 
134 extern bool redirection_done;
135 
136 /*
137  * Hook for intercepting messages before they are sent to the server log.
138  * Note that the hook will not get called for messages that are suppressed
139  * by log_min_messages.  Also note that logging hooks implemented in preload
140  * libraries will miss any log messages that are generated before the
141  * library is loaded.
142  */
143 __thread emit_log_hook_type emit_log_hook = NULL;
144 
145 
146 /* GUC parameters */
147 
148  /* format for extra log line info */
149 
150 
151 
152 
153 
154 #ifdef HAVE_SYSLOG
155 
156 /*
157  * Max string length to send to syslog().  Note that this doesn't count the
158  * sequence-number prefix we add, and of course it doesn't count the prefix
159  * added by syslog itself.  Solaris and sysklogd truncate the final message
160  * at 1024 bytes, so this value leaves 124 bytes for those prefixes.  (Most
161  * other syslog implementations seem to have limits of 2KB or so.)
162  */
163 #ifndef PG_SYSLOG_LIMIT
164 #define PG_SYSLOG_LIMIT 900
165 #endif
166 
167 
168 
169 
170 
171 static void write_syslog(int level, const char *line);
172 #endif
173 
174 #ifdef WIN32
175 extern char *event_source;
176 
177 static void write_eventlog(int level, const char *line, int len);
178 #endif
179 
180 /* We provide a small stack of ErrorData records for re-entrant cases */
181 #define ERRORDATA_STACK_SIZE  5
182 
183 static __thread ErrorData errordata[ERRORDATA_STACK_SIZE];
184 
185 
186 static __thread int	errordata_stack_depth = -1;
187  /* index of topmost active frame */
188 
189 static __thread int	recursion_depth = 0;
190 	/* to detect actual recursion */
191 
192 /*
193  * Saved timeval and buffers for formatted timestamps that might be used by
194  * both log_line_prefix and csv logs.
195  */
196 
197 
198 
199 #define FORMATTED_TS_LEN 128
200 
201 
202 
203 
204 /* Macro for checking errordata_stack_depth is reasonable */
205 #define CHECK_STACK_DEPTH() \
206 	do { \
207 		if (errordata_stack_depth < 0) \
208 		{ \
209 			errordata_stack_depth = -1; \
210 			ereport(ERROR, (errmsg_internal("errstart was not called"))); \
211 		} \
212 	} while (0)
213 
214 
215 static const char *err_gettext(const char *str) pg_attribute_format_arg(1);
216 static void set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str);
217 static void write_console(const char *line, int len);
218 static void setup_formatted_log_time(void);
219 static void setup_formatted_start_time(void);
220 static const char *process_log_prefix_padding(const char *p, int *padding);
221 static void log_line_prefix(StringInfo buf, ErrorData *edata);
222 static void write_csvlog(ErrorData *edata);
223 static void send_message_to_server_log(ErrorData *edata);
224 static void write_pipe_chunks(char *data, int len, int dest);
225 static void send_message_to_frontend(ErrorData *edata);
226 static char *expand_fmt_string(const char *fmt, ErrorData *edata);
227 static const char *useful_strerror(int errnum);
228 static const char *get_errno_symbol(int errnum);
229 static const char *error_severity(int elevel);
230 static void append_with_tabs(StringInfo buf, const char *str);
231 static bool is_log_level_output(int elevel, int log_min_level);
232 
233 
234 /*
235  * in_error_recursion_trouble --- are we at risk of infinite error recursion?
236  *
237  * This function exists to provide common control of various fallback steps
238  * that we take if we think we are facing infinite error recursion.  See the
239  * callers for details.
240  */
241 bool
in_error_recursion_trouble(void)242 in_error_recursion_trouble(void)
243 {
244 	/* Pull the plug if recurse more than once */
245 	return (recursion_depth > 2);
246 }
247 
248 /*
249  * One of those fallback steps is to stop trying to localize the error
250  * message, since there's a significant probability that that's exactly
251  * what's causing the recursion.
252  */
253 static inline const char *
err_gettext(const char * str)254 err_gettext(const char *str)
255 {
256 #ifdef ENABLE_NLS
257 	if (in_error_recursion_trouble())
258 		return str;
259 	else
260 		return gettext(str);
261 #else
262 	return str;
263 #endif
264 }
265 
266 
267 /*
268  * errstart --- begin an error-reporting cycle
269  *
270  * Create a stack entry and store the given parameters in it.  Subsequently,
271  * errmsg() and perhaps other routines will be called to further populate
272  * the stack entry.  Finally, errfinish() will be called to actually process
273  * the error report.
274  *
275  * Returns TRUE in normal case.  Returns FALSE to short-circuit the error
276  * report (if it's a warning or lower and not to be reported anywhere).
277  */
278 bool
errstart(int elevel,const char * filename,int lineno,const char * funcname,const char * domain)279 errstart(int elevel, const char *filename, int lineno,
280 		 const char *funcname, const char *domain)
281 {
282 	ErrorData  *edata;
283 	bool		output_to_server;
284 	bool		output_to_client = false;
285 	int			i;
286 
287 	/*
288 	 * Check some cases in which we want to promote an error into a more
289 	 * severe error.  None of this logic applies for non-error messages.
290 	 */
291 	if (elevel >= ERROR)
292 	{
293 		/*
294 		 * If we are inside a critical section, all errors become PANIC
295 		 * errors.  See miscadmin.h.
296 		 */
297 		if (CritSectionCount > 0)
298 			elevel = PANIC;
299 
300 		/*
301 		 * Check reasons for treating ERROR as FATAL:
302 		 *
303 		 * 1. we have no handler to pass the error to (implies we are in the
304 		 * postmaster or in backend startup).
305 		 *
306 		 * 2. ExitOnAnyError mode switch is set (initdb uses this).
307 		 *
308 		 * 3. the error occurred after proc_exit has begun to run.  (It's
309 		 * proc_exit's responsibility to see that this doesn't turn into
310 		 * infinite recursion!)
311 		 */
312 		if (elevel == ERROR)
313 		{
314 			if (PG_exception_stack == NULL ||
315 				ExitOnAnyError ||
316 				proc_exit_inprogress)
317 				elevel = FATAL;
318 		}
319 
320 		/*
321 		 * If the error level is ERROR or more, errfinish is not going to
322 		 * return to caller; therefore, if there is any stacked error already
323 		 * in progress it will be lost.  This is more or less okay, except we
324 		 * do not want to have a FATAL or PANIC error downgraded because the
325 		 * reporting process was interrupted by a lower-grade error.  So check
326 		 * the stack and make sure we panic if panic is warranted.
327 		 */
328 		for (i = 0; i <= errordata_stack_depth; i++)
329 			elevel = Max(elevel, errordata[i].elevel);
330 	}
331 
332 	/*
333 	 * Now decide whether we need to process this report at all; if it's
334 	 * warning or less and not enabled for logging, just return FALSE without
335 	 * starting up any error logging machinery.
336 	 */
337 
338 	/* Determine whether message is enabled for server log output */
339 	output_to_server = is_log_level_output(elevel, log_min_messages);
340 
341 	/* Determine whether message is enabled for client output */
342 	if (whereToSendOutput == DestRemote && elevel != LOG_SERVER_ONLY)
343 	{
344 		/*
345 		 * client_min_messages is honored only after we complete the
346 		 * authentication handshake.  This is required both for security
347 		 * reasons and because many clients can't handle NOTICE messages
348 		 * during authentication.
349 		 */
350 		if (ClientAuthInProgress)
351 			output_to_client = (elevel >= ERROR);
352 		else
353 			output_to_client = (elevel >= client_min_messages ||
354 								elevel == INFO);
355 	}
356 
357 	/* Skip processing effort if non-error message will not be output */
358 	if (elevel < ERROR && !output_to_server && !output_to_client)
359 		return false;
360 
361 	/*
362 	 * We need to do some actual work.  Make sure that memory context
363 	 * initialization has finished, else we can't do anything useful.
364 	 */
365 	if (ErrorContext == NULL)
366 	{
367 		/* Oops, hard crash time; very little we can do safely here */
368 		write_stderr("error occurred at %s:%d before error message processing is available\n",
369 					 filename ? filename : "(unknown file)", lineno);
370 		exit(2);
371 	}
372 
373 	/*
374 	 * Okay, crank up a stack entry to store the info in.
375 	 */
376 
377 	if (recursion_depth++ > 0 && elevel >= ERROR)
378 	{
379 		/*
380 		 * Oops, error during error processing.  Clear ErrorContext as
381 		 * discussed at top of file.  We will not return to the original
382 		 * error's reporter or handler, so we don't need it.
383 		 */
384 		MemoryContextReset(ErrorContext);
385 
386 		/*
387 		 * Infinite error recursion might be due to something broken in a
388 		 * context traceback routine.  Abandon them too.  We also abandon
389 		 * attempting to print the error statement (which, if long, could
390 		 * itself be the source of the recursive failure).
391 		 */
392 		if (in_error_recursion_trouble())
393 		{
394 			error_context_stack = NULL;
395 			debug_query_string = NULL;
396 		}
397 	}
398 	if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
399 	{
400 		/*
401 		 * Wups, stack not big enough.  We treat this as a PANIC condition
402 		 * because it suggests an infinite loop of errors during error
403 		 * recovery.
404 		 */
405 		errordata_stack_depth = -1; /* make room on stack */
406 		ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
407 	}
408 
409 	/* Initialize data for this error frame */
410 	edata = &errordata[errordata_stack_depth];
411 	MemSet(edata, 0, sizeof(ErrorData));
412 	edata->elevel = elevel;
413 	edata->output_to_server = output_to_server;
414 	edata->output_to_client = output_to_client;
415 	if (filename)
416 	{
417 		const char *slash;
418 
419 		/* keep only base name, useful especially for vpath builds */
420 		slash = strrchr(filename, '/');
421 		if (slash)
422 			filename = slash + 1;
423 	}
424 	edata->filename = filename;
425 	edata->lineno = lineno;
426 	edata->funcname = funcname;
427 	/* the default text domain is the backend's */
428 	edata->domain = domain ? domain : PG_TEXTDOMAIN("postgres");
429 	/* initialize context_domain the same way (see set_errcontext_domain()) */
430 	edata->context_domain = edata->domain;
431 	/* Select default errcode based on elevel */
432 	if (elevel >= ERROR)
433 		edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
434 	else if (elevel == WARNING)
435 		edata->sqlerrcode = ERRCODE_WARNING;
436 	else
437 		edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
438 	/* errno is saved here so that error parameter eval can't change it */
439 	edata->saved_errno = errno;
440 
441 	/*
442 	 * Any allocations for this error state level should go into ErrorContext
443 	 */
444 	edata->assoc_context = ErrorContext;
445 
446 	recursion_depth--;
447 	return true;
448 }
449 
450 /*
451  * errfinish --- end an error-reporting cycle
452  *
453  * Produce the appropriate error report(s) and pop the error stack.
454  *
455  * If elevel is ERROR or worse, control does not return to the caller.
456  * See elog.h for the error level definitions.
457  */
458 void
errfinish(int dummy,...)459 errfinish(int dummy,...)
460 {
461 	ErrorData  *edata = &errordata[errordata_stack_depth];
462 	int			elevel;
463 	MemoryContext oldcontext;
464 	ErrorContextCallback *econtext;
465 
466 	recursion_depth++;
467 	CHECK_STACK_DEPTH();
468 	elevel = edata->elevel;
469 
470 	/*
471 	 * Do processing in ErrorContext, which we hope has enough reserved space
472 	 * to report an error.
473 	 */
474 	oldcontext = MemoryContextSwitchTo(ErrorContext);
475 
476 	/*
477 	 * Call any context callback functions.  Errors occurring in callback
478 	 * functions will be treated as recursive errors --- this ensures we will
479 	 * avoid infinite recursion (see errstart).
480 	 */
481 	for (econtext = error_context_stack;
482 		 econtext != NULL;
483 		 econtext = econtext->previous)
484 		(*econtext->callback) (econtext->arg);
485 
486 	/*
487 	 * If ERROR (not more nor less) we pass it off to the current handler.
488 	 * Printing it and popping the stack is the responsibility of the handler.
489 	 */
490 	if (elevel == ERROR)
491 	{
492 		/*
493 		 * We do some minimal cleanup before longjmp'ing so that handlers can
494 		 * execute in a reasonably sane state.
495 		 *
496 		 * Reset InterruptHoldoffCount in case we ereport'd from inside an
497 		 * interrupt holdoff section.  (We assume here that no handler will
498 		 * itself be inside a holdoff section.  If necessary, such a handler
499 		 * could save and restore InterruptHoldoffCount for itself, but this
500 		 * should make life easier for most.)
501 		 */
502 		InterruptHoldoffCount = 0;
503 		QueryCancelHoldoffCount = 0;
504 
505 		CritSectionCount = 0;	/* should be unnecessary, but... */
506 
507 		/*
508 		 * Note that we leave CurrentMemoryContext set to ErrorContext. The
509 		 * handler should reset it to something else soon.
510 		 */
511 
512 		recursion_depth--;
513 		PG_RE_THROW();
514 	}
515 
516 	/*
517 	 * If we are doing FATAL or PANIC, abort any old-style COPY OUT in
518 	 * progress, so that we can report the message before dying.  (Without
519 	 * this, pq_putmessage will refuse to send the message at all, which is
520 	 * what we want for NOTICE messages, but not for fatal exits.) This hack
521 	 * is necessary because of poor design of old-style copy protocol.
522 	 */
523 	if (elevel >= FATAL && whereToSendOutput == DestRemote)
524 		pq_endcopyout(true);
525 
526 	/* Emit the message to the right places */
527 	EmitErrorReport();
528 
529 	/* Now free up subsidiary data attached to stack entry, and release it */
530 	if (edata->message)
531 		pfree(edata->message);
532 	if (edata->detail)
533 		pfree(edata->detail);
534 	if (edata->detail_log)
535 		pfree(edata->detail_log);
536 	if (edata->hint)
537 		pfree(edata->hint);
538 	if (edata->context)
539 		pfree(edata->context);
540 	if (edata->schema_name)
541 		pfree(edata->schema_name);
542 	if (edata->table_name)
543 		pfree(edata->table_name);
544 	if (edata->column_name)
545 		pfree(edata->column_name);
546 	if (edata->datatype_name)
547 		pfree(edata->datatype_name);
548 	if (edata->constraint_name)
549 		pfree(edata->constraint_name);
550 	if (edata->internalquery)
551 		pfree(edata->internalquery);
552 
553 	errordata_stack_depth--;
554 
555 	/* Exit error-handling context */
556 	MemoryContextSwitchTo(oldcontext);
557 	recursion_depth--;
558 
559 	/*
560 	 * Perform error recovery action as specified by elevel.
561 	 */
562 	if (elevel == FATAL)
563 	{
564 		/*
565 		 * For a FATAL error, we let proc_exit clean up and exit.
566 		 *
567 		 * If we just reported a startup failure, the client will disconnect
568 		 * on receiving it, so don't send any more to the client.
569 		 */
570 		if (PG_exception_stack == NULL && whereToSendOutput == DestRemote)
571 			whereToSendOutput = DestNone;
572 
573 		/*
574 		 * fflush here is just to improve the odds that we get to see the
575 		 * error message, in case things are so hosed that proc_exit crashes.
576 		 * Any other code you might be tempted to add here should probably be
577 		 * in an on_proc_exit or on_shmem_exit callback instead.
578 		 */
579 		fflush(stdout);
580 		fflush(stderr);
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 		 */
587 		proc_exit(1);
588 	}
589 
590 	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 		 */
599 		fflush(stdout);
600 		fflush(stderr);
601 		abort();
602 	}
603 
604 	/*
605 	 * Check for cancel/die interrupt first --- this is so that the user can
606 	 * stop a query emitting tons of notice or warning messages, even if it's
607 	 * in a loop that otherwise fails to check for interrupts.
608 	 */
609 	CHECK_FOR_INTERRUPTS();
610 }
611 
612 
613 /*
614  * errcode --- add SQLSTATE error code to the current error
615  *
616  * The code is expected to be represented as per MAKE_SQLSTATE().
617  */
618 int
errcode(int sqlerrcode)619 errcode(int sqlerrcode)
620 {
621 	ErrorData  *edata = &errordata[errordata_stack_depth];
622 
623 	/* we don't bother incrementing recursion_depth */
624 	CHECK_STACK_DEPTH();
625 
626 	edata->sqlerrcode = sqlerrcode;
627 
628 	return 0;					/* return value does not matter */
629 }
630 
631 
632 /*
633  * errcode_for_file_access --- add SQLSTATE error code to the current error
634  *
635  * The SQLSTATE code is chosen based on the saved errno value.  We assume
636  * that the failing operation was some type of disk file access.
637  *
638  * NOTE: the primary error message string should generally include %m
639  * when this is used.
640  */
641 #ifdef EROFS
642 #endif
643 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
644 #endif
645 
646 /*
647  * errcode_for_socket_access --- add SQLSTATE error code to the current error
648  *
649  * The SQLSTATE code is chosen based on the saved errno value.  We assume
650  * that the failing operation was some type of socket access.
651  *
652  * NOTE: the primary error message string should generally include %m
653  * when this is used.
654  */
655 #ifdef ECONNRESET
656 #endif
657 
658 
659 /*
660  * This macro handles expansion of a format string and associated parameters;
661  * it's common code for errmsg(), errdetail(), etc.  Must be called inside
662  * a routine that is declared like "const char *fmt, ..." and has an edata
663  * pointer set up.  The message is assigned to edata->targetfield, or
664  * appended to it if appendval is true.  The message is subject to translation
665  * if translateit is true.
666  *
667  * Note: we pstrdup the buffer rather than just transferring its storage
668  * to the edata field because the buffer might be considerably larger than
669  * really necessary.
670  */
671 #define EVALUATE_MESSAGE(domain, targetfield, appendval, translateit)	\
672 	{ \
673 		char		   *fmtbuf; \
674 		StringInfoData	buf; \
675 		/* Internationalize the error format string */ \
676 		if ((translateit) && !in_error_recursion_trouble()) \
677 			fmt = dgettext((domain), fmt);				  \
678 		/* Expand %m in format string */ \
679 		fmtbuf = expand_fmt_string(fmt, edata); \
680 		initStringInfo(&buf); \
681 		if ((appendval) && edata->targetfield) { \
682 			appendStringInfoString(&buf, edata->targetfield); \
683 			appendStringInfoChar(&buf, '\n'); \
684 		} \
685 		/* Generate actual output --- have to use appendStringInfoVA */ \
686 		for (;;) \
687 		{ \
688 			va_list		args; \
689 			int			needed; \
690 			va_start(args, fmt); \
691 			needed = appendStringInfoVA(&buf, fmtbuf, args); \
692 			va_end(args); \
693 			if (needed == 0) \
694 				break; \
695 			enlargeStringInfo(&buf, needed); \
696 		} \
697 		/* Done with expanded fmt */ \
698 		pfree(fmtbuf); \
699 		/* Save the completed message into the stack item */ \
700 		if (edata->targetfield) \
701 			pfree(edata->targetfield); \
702 		edata->targetfield = pstrdup(buf.data); \
703 		pfree(buf.data); \
704 	}
705 
706 /*
707  * Same as above, except for pluralized error messages.  The calling routine
708  * must be declared like "const char *fmt_singular, const char *fmt_plural,
709  * unsigned long n, ...".  Translation is assumed always wanted.
710  */
711 #define EVALUATE_MESSAGE_PLURAL(domain, targetfield, appendval)  \
712 	{ \
713 		const char	   *fmt; \
714 		char		   *fmtbuf; \
715 		StringInfoData	buf; \
716 		/* Internationalize the error format string */ \
717 		if (!in_error_recursion_trouble()) \
718 			fmt = dngettext((domain), fmt_singular, fmt_plural, n); \
719 		else \
720 			fmt = (n == 1 ? fmt_singular : fmt_plural); \
721 		/* Expand %m in format string */ \
722 		fmtbuf = expand_fmt_string(fmt, edata); \
723 		initStringInfo(&buf); \
724 		if ((appendval) && edata->targetfield) { \
725 			appendStringInfoString(&buf, edata->targetfield); \
726 			appendStringInfoChar(&buf, '\n'); \
727 		} \
728 		/* Generate actual output --- have to use appendStringInfoVA */ \
729 		for (;;) \
730 		{ \
731 			va_list		args; \
732 			int			needed; \
733 			va_start(args, n); \
734 			needed = appendStringInfoVA(&buf, fmtbuf, args); \
735 			va_end(args); \
736 			if (needed == 0) \
737 				break; \
738 			enlargeStringInfo(&buf, needed); \
739 		} \
740 		/* Done with expanded fmt */ \
741 		pfree(fmtbuf); \
742 		/* Save the completed message into the stack item */ \
743 		if (edata->targetfield) \
744 			pfree(edata->targetfield); \
745 		edata->targetfield = pstrdup(buf.data); \
746 		pfree(buf.data); \
747 	}
748 
749 
750 /*
751  * errmsg --- add a primary error message text to the current error
752  *
753  * In addition to the usual %-escapes recognized by printf, "%m" in
754  * fmt is replaced by the error message for the caller's value of errno.
755  *
756  * Note: no newline is needed at the end of the fmt string, since
757  * ereport will provide one for the output methods that need it.
758  */
759 int
errmsg(const char * fmt,...)760 errmsg(const char *fmt,...)
761 {
762 	ErrorData  *edata = &errordata[errordata_stack_depth];
763 	MemoryContext oldcontext;
764 
765 	recursion_depth++;
766 	CHECK_STACK_DEPTH();
767 	oldcontext = MemoryContextSwitchTo(edata->assoc_context);
768 
769 	edata->message_id = fmt;
770 	EVALUATE_MESSAGE(edata->domain, message, false, true);
771 
772 	MemoryContextSwitchTo(oldcontext);
773 	recursion_depth--;
774 	return 0;					/* return value does not matter */
775 }
776 
777 
778 /*
779  * errmsg_internal --- add a primary error message text to the current error
780  *
781  * This is exactly like errmsg() except that strings passed to errmsg_internal
782  * are not translated, and are customarily left out of the
783  * internationalization message dictionary.  This should be used for "can't
784  * happen" cases that are probably not worth spending translation effort on.
785  * We also use this for certain cases where we *must* not try to translate
786  * the message because the translation would fail and result in infinite
787  * error recursion.
788  */
789 int
errmsg_internal(const char * fmt,...)790 errmsg_internal(const char *fmt,...)
791 {
792 	ErrorData  *edata = &errordata[errordata_stack_depth];
793 	MemoryContext oldcontext;
794 
795 	recursion_depth++;
796 	CHECK_STACK_DEPTH();
797 	oldcontext = MemoryContextSwitchTo(edata->assoc_context);
798 
799 	edata->message_id = fmt;
800 	EVALUATE_MESSAGE(edata->domain, message, false, false);
801 
802 	MemoryContextSwitchTo(oldcontext);
803 	recursion_depth--;
804 	return 0;					/* return value does not matter */
805 }
806 
807 
808 /*
809  * errmsg_plural --- add a primary error message text to the current error,
810  * with support for pluralization of the message text
811  */
812 
813 
814 
815 /*
816  * errdetail --- add a detail error message text to the current error
817  */
818 int
errdetail(const char * fmt,...)819 errdetail(const char *fmt,...)
820 {
821 	ErrorData  *edata = &errordata[errordata_stack_depth];
822 	MemoryContext oldcontext;
823 
824 	recursion_depth++;
825 	CHECK_STACK_DEPTH();
826 	oldcontext = MemoryContextSwitchTo(edata->assoc_context);
827 
828 	EVALUATE_MESSAGE(edata->domain, detail, false, true);
829 
830 	MemoryContextSwitchTo(oldcontext);
831 	recursion_depth--;
832 	return 0;					/* return value does not matter */
833 }
834 
835 
836 /*
837  * errdetail_internal --- add a detail error message text to the current error
838  *
839  * This is exactly like errdetail() except that strings passed to
840  * errdetail_internal are not translated, and are customarily left out of the
841  * internationalization message dictionary.  This should be used for detail
842  * messages that seem not worth translating for one reason or another
843  * (typically, that they don't seem to be useful to average users).
844  */
845 
846 
847 
848 /*
849  * errdetail_log --- add a detail_log error message text to the current error
850  */
851 
852 
853 /*
854  * errdetail_log_plural --- add a detail_log error message text to the current error
855  * with support for pluralization of the message text
856  */
857 
858 
859 
860 /*
861  * errdetail_plural --- add a detail error message text to the current error,
862  * with support for pluralization of the message text
863  */
864 
865 
866 
867 /*
868  * errhint --- add a hint error message text to the current error
869  */
870 int
errhint(const char * fmt,...)871 errhint(const char *fmt,...)
872 {
873 	ErrorData  *edata = &errordata[errordata_stack_depth];
874 	MemoryContext oldcontext;
875 
876 	recursion_depth++;
877 	CHECK_STACK_DEPTH();
878 	oldcontext = MemoryContextSwitchTo(edata->assoc_context);
879 
880 	EVALUATE_MESSAGE(edata->domain, hint, false, true);
881 
882 	MemoryContextSwitchTo(oldcontext);
883 	recursion_depth--;
884 	return 0;					/* return value does not matter */
885 }
886 
887 
888 /*
889  * errcontext_msg --- add a context error message text to the current error
890  *
891  * Unlike other cases, multiple calls are allowed to build up a stack of
892  * context information.  We assume earlier calls represent more-closely-nested
893  * states.
894  */
895 int
errcontext_msg(const char * fmt,...)896 errcontext_msg(const char *fmt,...)
897 {
898 	ErrorData  *edata = &errordata[errordata_stack_depth];
899 	MemoryContext oldcontext;
900 
901 	recursion_depth++;
902 	CHECK_STACK_DEPTH();
903 	oldcontext = MemoryContextSwitchTo(edata->assoc_context);
904 
905 	EVALUATE_MESSAGE(edata->context_domain, context, true, true);
906 
907 	MemoryContextSwitchTo(oldcontext);
908 	recursion_depth--;
909 	return 0;					/* return value does not matter */
910 }
911 
912 /*
913  * set_errcontext_domain --- set message domain to be used by errcontext()
914  *
915  * errcontext_msg() can be called from a different module than the original
916  * ereport(), so we cannot use the message domain passed in errstart() to
917  * translate it.  Instead, each errcontext_msg() call should be preceded by
918  * a set_errcontext_domain() call to specify the domain.  This is usually
919  * done transparently by the errcontext() macro.
920  *
921  * Although errcontext is primarily meant for use at call sites distant from
922  * the original ereport call, there are a few places that invoke errcontext
923  * within ereport.  The expansion of errcontext as a comma expression calling
924  * set_errcontext_domain then errcontext_msg is problematic in this case,
925  * because the intended comma expression becomes two arguments to errfinish,
926  * which the compiler is at liberty to evaluate in either order.  But in
927  * such a case, the set_errcontext_domain calls must be selecting the same
928  * TEXTDOMAIN value that the errstart call did, so order does not matter
929  * so long as errstart initializes context_domain along with domain.
930  */
931 int
set_errcontext_domain(const char * domain)932 set_errcontext_domain(const char *domain)
933 {
934 	ErrorData  *edata = &errordata[errordata_stack_depth];
935 
936 	/* we don't bother incrementing recursion_depth */
937 	CHECK_STACK_DEPTH();
938 
939 	/* the default text domain is the backend's */
940 	edata->context_domain = domain ? domain : PG_TEXTDOMAIN("postgres");
941 
942 	return 0;					/* return value does not matter */
943 }
944 
945 
946 /*
947  * errhidestmt --- optionally suppress STATEMENT: field of log entry
948  *
949  * This should be called if the message text already includes the statement.
950  */
951 
952 
953 /*
954  * errhidecontext --- optionally suppress CONTEXT: field of log entry
955  *
956  * This should only be used for verbose debugging messages where the repeated
957  * inclusion of context would bloat the log volume too much.
958  */
959 
960 
961 
962 /*
963  * errfunction --- add reporting function name to the current error
964  *
965  * This is used when backwards compatibility demands that the function
966  * name appear in messages sent to old-protocol clients.  Note that the
967  * passed string is expected to be a non-freeable constant string.
968  */
969 
970 
971 /*
972  * errposition --- add cursor position to the current error
973  */
974 int
errposition(int cursorpos)975 errposition(int cursorpos)
976 {
977 	ErrorData  *edata = &errordata[errordata_stack_depth];
978 
979 	/* we don't bother incrementing recursion_depth */
980 	CHECK_STACK_DEPTH();
981 
982 	edata->cursorpos = cursorpos;
983 
984 	return 0;					/* return value does not matter */
985 }
986 
987 /*
988  * internalerrposition --- add internal cursor position to the current error
989  */
990 int
internalerrposition(int cursorpos)991 internalerrposition(int cursorpos)
992 {
993 	ErrorData  *edata = &errordata[errordata_stack_depth];
994 
995 	/* we don't bother incrementing recursion_depth */
996 	CHECK_STACK_DEPTH();
997 
998 	edata->internalpos = cursorpos;
999 
1000 	return 0;					/* return value does not matter */
1001 }
1002 
1003 /*
1004  * internalerrquery --- add internal query text to the current error
1005  *
1006  * Can also pass NULL to drop the internal query text entry.  This case
1007  * is intended for use in error callback subroutines that are editorializing
1008  * on the layout of the error report.
1009  */
1010 int
internalerrquery(const char * query)1011 internalerrquery(const char *query)
1012 {
1013 	ErrorData  *edata = &errordata[errordata_stack_depth];
1014 
1015 	/* we don't bother incrementing recursion_depth */
1016 	CHECK_STACK_DEPTH();
1017 
1018 	if (edata->internalquery)
1019 	{
1020 		pfree(edata->internalquery);
1021 		edata->internalquery = NULL;
1022 	}
1023 
1024 	if (query)
1025 		edata->internalquery = MemoryContextStrdup(edata->assoc_context, query);
1026 
1027 	return 0;					/* return value does not matter */
1028 }
1029 
1030 /*
1031  * err_generic_string -- used to set individual ErrorData string fields
1032  * identified by PG_DIAG_xxx codes.
1033  *
1034  * This intentionally only supports fields that don't use localized strings,
1035  * so that there are no translation considerations.
1036  *
1037  * Most potential callers should not use this directly, but instead prefer
1038  * higher-level abstractions, such as errtablecol() (see relcache.c).
1039  */
1040 
1041 
1042 /*
1043  * set_errdata_field --- set an ErrorData string field
1044  */
1045 
1046 
1047 /*
1048  * geterrcode --- return the currently set SQLSTATE error code
1049  *
1050  * This is only intended for use in error callback subroutines, since there
1051  * is no other place outside elog.c where the concept is meaningful.
1052  */
1053 
1054 
1055 /*
1056  * geterrposition --- return the currently set error position (0 if none)
1057  *
1058  * This is only intended for use in error callback subroutines, since there
1059  * is no other place outside elog.c where the concept is meaningful.
1060  */
1061 int
geterrposition(void)1062 geterrposition(void)
1063 {
1064 	ErrorData  *edata = &errordata[errordata_stack_depth];
1065 
1066 	/* we don't bother incrementing recursion_depth */
1067 	CHECK_STACK_DEPTH();
1068 
1069 	return edata->cursorpos;
1070 }
1071 
1072 /*
1073  * getinternalerrposition --- same for internal error position
1074  *
1075  * This is only intended for use in error callback subroutines, since there
1076  * is no other place outside elog.c where the concept is meaningful.
1077  */
1078 int
getinternalerrposition(void)1079 getinternalerrposition(void)
1080 {
1081 	ErrorData  *edata = &errordata[errordata_stack_depth];
1082 
1083 	/* we don't bother incrementing recursion_depth */
1084 	CHECK_STACK_DEPTH();
1085 
1086 	return edata->internalpos;
1087 }
1088 
1089 
1090 /*
1091  * elog_start --- startup for old-style API
1092  *
1093  * All that we do here is stash the hidden filename/lineno/funcname
1094  * arguments into a stack entry, along with the current value of errno.
1095  *
1096  * We need this to be separate from elog_finish because there's no other
1097  * C89-compliant way to deal with inserting extra arguments into the elog
1098  * call.  (When using C99's __VA_ARGS__, we could possibly merge this with
1099  * elog_finish, but there doesn't seem to be a good way to save errno before
1100  * evaluating the format arguments if we do that.)
1101  */
1102 void
elog_start(const char * filename,int lineno,const char * funcname)1103 elog_start(const char *filename, int lineno, const char *funcname)
1104 {
1105 	ErrorData  *edata;
1106 
1107 	/* Make sure that memory context initialization has finished */
1108 	if (ErrorContext == NULL)
1109 	{
1110 		/* Oops, hard crash time; very little we can do safely here */
1111 		write_stderr("error occurred at %s:%d before error message processing is available\n",
1112 					 filename ? filename : "(unknown file)", lineno);
1113 		exit(2);
1114 	}
1115 
1116 	if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1117 	{
1118 		/*
1119 		 * Wups, stack not big enough.  We treat this as a PANIC condition
1120 		 * because it suggests an infinite loop of errors during error
1121 		 * recovery.  Note that the message is intentionally not localized,
1122 		 * else failure to convert it to client encoding could cause further
1123 		 * recursion.
1124 		 */
1125 		errordata_stack_depth = -1; /* make room on stack */
1126 		ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1127 	}
1128 
1129 	edata = &errordata[errordata_stack_depth];
1130 	if (filename)
1131 	{
1132 		const char *slash;
1133 
1134 		/* keep only base name, useful especially for vpath builds */
1135 		slash = strrchr(filename, '/');
1136 		if (slash)
1137 			filename = slash + 1;
1138 	}
1139 	edata->filename = filename;
1140 	edata->lineno = lineno;
1141 	edata->funcname = funcname;
1142 	/* errno is saved now so that error parameter eval can't change it */
1143 	edata->saved_errno = errno;
1144 
1145 	/* Use ErrorContext for any allocations done at this level. */
1146 	edata->assoc_context = ErrorContext;
1147 }
1148 
1149 /*
1150  * elog_finish --- finish up for old-style API
1151  */
1152 void
elog_finish(int elevel,const char * fmt,...)1153 elog_finish(int elevel, const char *fmt,...)
1154 {
1155 	ErrorData  *edata = &errordata[errordata_stack_depth];
1156 	MemoryContext oldcontext;
1157 
1158 	CHECK_STACK_DEPTH();
1159 
1160 	/*
1161 	 * Do errstart() to see if we actually want to report the message.
1162 	 */
1163 	errordata_stack_depth--;
1164 	errno = edata->saved_errno;
1165 	if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname, NULL))
1166 		return;					/* nothing to do */
1167 
1168 	/*
1169 	 * Format error message just like errmsg_internal().
1170 	 */
1171 	recursion_depth++;
1172 	oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1173 
1174 	edata->message_id = fmt;
1175 	EVALUATE_MESSAGE(edata->domain, message, false, false);
1176 
1177 	MemoryContextSwitchTo(oldcontext);
1178 	recursion_depth--;
1179 
1180 	/*
1181 	 * And let errfinish() finish up.
1182 	 */
1183 	errfinish(0);
1184 }
1185 
1186 
1187 /*
1188  * Functions to allow construction of error message strings separately from
1189  * the ereport() call itself.
1190  *
1191  * The expected calling convention is
1192  *
1193  *	pre_format_elog_string(errno, domain), var = format_elog_string(format,...)
1194  *
1195  * which can be hidden behind a macro such as GUC_check_errdetail().  We
1196  * assume that any functions called in the arguments of format_elog_string()
1197  * cannot result in re-entrant use of these functions --- otherwise the wrong
1198  * text domain might be used, or the wrong errno substituted for %m.  This is
1199  * okay for the current usage with GUC check hooks, but might need further
1200  * effort someday.
1201  *
1202  * The result of format_elog_string() is stored in ErrorContext, and will
1203  * therefore survive until FlushErrorState() is called.
1204  */
1205 
1206 
1207 
1208 
1209 
1210 
1211 
1212 
1213 /*
1214  * Actual output of the top-of-stack error message
1215  *
1216  * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
1217  * if the error is caught by somebody).  For all other severity levels this
1218  * is called by errfinish.
1219  */
1220 void
EmitErrorReport(void)1221 EmitErrorReport(void)
1222 {
1223 	ErrorData  *edata = &errordata[errordata_stack_depth];
1224 	MemoryContext oldcontext;
1225 
1226 	recursion_depth++;
1227 	CHECK_STACK_DEPTH();
1228 	oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1229 
1230 	/*
1231 	 * Call hook before sending message to log.  The hook function is allowed
1232 	 * to turn off edata->output_to_server, so we must recheck that afterward.
1233 	 * Making any other change in the content of edata is not considered
1234 	 * supported.
1235 	 *
1236 	 * Note: the reason why the hook can only turn off output_to_server, and
1237 	 * not turn it on, is that it'd be unreliable: we will never get here at
1238 	 * all if errstart() deems the message uninteresting.  A hook that could
1239 	 * make decisions in that direction would have to hook into errstart(),
1240 	 * where it would have much less information available.  emit_log_hook is
1241 	 * intended for custom log filtering and custom log message transmission
1242 	 * mechanisms.
1243 	 *
1244 	 * The log hook has access to both the translated and original English
1245 	 * error message text, which is passed through to allow it to be used as a
1246 	 * message identifier. Note that the original text is not available for
1247 	 * detail, detail_log, hint and context text elements.
1248 	 */
1249 	if (edata->output_to_server && emit_log_hook)
1250 		(*emit_log_hook) (edata);
1251 
1252 	/* Send to server log, if enabled */
1253 	if (edata->output_to_server)
1254 		send_message_to_server_log(edata);
1255 
1256 	/* Send to client, if enabled */
1257 	if (edata->output_to_client)
1258 		send_message_to_frontend(edata);
1259 
1260 	MemoryContextSwitchTo(oldcontext);
1261 	recursion_depth--;
1262 }
1263 
1264 /*
1265  * CopyErrorData --- obtain a copy of the topmost error stack entry
1266  *
1267  * This is only for use in error handler code.  The data is copied into the
1268  * current memory context, so callers should always switch away from
1269  * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
1270  */
1271 ErrorData *
CopyErrorData(void)1272 CopyErrorData(void)
1273 {
1274 	ErrorData  *edata = &errordata[errordata_stack_depth];
1275 	ErrorData  *newedata;
1276 
1277 	/*
1278 	 * we don't increment recursion_depth because out-of-memory here does not
1279 	 * indicate a problem within the error subsystem.
1280 	 */
1281 	CHECK_STACK_DEPTH();
1282 
1283 	Assert(CurrentMemoryContext != ErrorContext);
1284 
1285 	/* Copy the struct itself */
1286 	newedata = (ErrorData *) palloc(sizeof(ErrorData));
1287 	memcpy(newedata, edata, sizeof(ErrorData));
1288 
1289 	/* Make copies of separately-allocated fields */
1290 	if (newedata->message)
1291 		newedata->message = pstrdup(newedata->message);
1292 	if (newedata->detail)
1293 		newedata->detail = pstrdup(newedata->detail);
1294 	if (newedata->detail_log)
1295 		newedata->detail_log = pstrdup(newedata->detail_log);
1296 	if (newedata->hint)
1297 		newedata->hint = pstrdup(newedata->hint);
1298 	if (newedata->context)
1299 		newedata->context = pstrdup(newedata->context);
1300 	if (newedata->schema_name)
1301 		newedata->schema_name = pstrdup(newedata->schema_name);
1302 	if (newedata->table_name)
1303 		newedata->table_name = pstrdup(newedata->table_name);
1304 	if (newedata->column_name)
1305 		newedata->column_name = pstrdup(newedata->column_name);
1306 	if (newedata->datatype_name)
1307 		newedata->datatype_name = pstrdup(newedata->datatype_name);
1308 	if (newedata->constraint_name)
1309 		newedata->constraint_name = pstrdup(newedata->constraint_name);
1310 	if (newedata->internalquery)
1311 		newedata->internalquery = pstrdup(newedata->internalquery);
1312 
1313 	/* Use the calling context for string allocation */
1314 	newedata->assoc_context = CurrentMemoryContext;
1315 
1316 	return newedata;
1317 }
1318 
1319 /*
1320  * FreeErrorData --- free the structure returned by CopyErrorData.
1321  *
1322  * Error handlers should use this in preference to assuming they know all
1323  * the separately-allocated fields.
1324  */
1325 
1326 
1327 /*
1328  * FlushErrorState --- flush the error state after error recovery
1329  *
1330  * This should be called by an error handler after it's done processing
1331  * the error; or as soon as it's done CopyErrorData, if it intends to
1332  * do stuff that is likely to provoke another error.  You are not "out" of
1333  * the error subsystem until you have done this.
1334  */
1335 void
FlushErrorState(void)1336 FlushErrorState(void)
1337 {
1338 	/*
1339 	 * Reset stack to empty.  The only case where it would be more than one
1340 	 * deep is if we serviced an error that interrupted construction of
1341 	 * another message.  We assume control escaped out of that message
1342 	 * construction and won't ever go back.
1343 	 */
1344 	errordata_stack_depth = -1;
1345 	recursion_depth = 0;
1346 	/* Delete all data in ErrorContext */
1347 	MemoryContextResetAndDeleteChildren(ErrorContext);
1348 }
1349 
1350 /*
1351  * ThrowErrorData --- report an error described by an ErrorData structure
1352  *
1353  * This is somewhat like ReThrowError, but it allows elevels besides ERROR,
1354  * and the boolean flags such as output_to_server are computed via the
1355  * default rules rather than being copied from the given ErrorData.
1356  * This is primarily used to re-report errors originally reported by
1357  * background worker processes and then propagated (with or without
1358  * modification) to the backend responsible for them.
1359  */
1360 
1361 
1362 /*
1363  * ReThrowError --- re-throw a previously copied error
1364  *
1365  * A handler can do CopyErrorData/FlushErrorState to get out of the error
1366  * subsystem, then do some processing, and finally ReThrowError to re-throw
1367  * the original error.  This is slower than just PG_RE_THROW() but should
1368  * be used if the "some processing" is likely to incur another error.
1369  */
1370 
1371 
1372 /*
1373  * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
1374  */
1375 void
pg_re_throw(void)1376 pg_re_throw(void)
1377 {
1378 	/* If possible, throw the error to the next outer setjmp handler */
1379 	if (PG_exception_stack != NULL)
1380 		siglongjmp(*PG_exception_stack, 1);
1381 	else
1382 	{
1383 		/*
1384 		 * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
1385 		 * we have now exited only to discover that there is no outer setjmp
1386 		 * handler to pass the error to.  Had the error been thrown outside
1387 		 * the block to begin with, we'd have promoted the error to FATAL, so
1388 		 * the correct behavior is to make it FATAL now; that is, emit it and
1389 		 * then call proc_exit.
1390 		 */
1391 		ErrorData  *edata = &errordata[errordata_stack_depth];
1392 
1393 		Assert(errordata_stack_depth >= 0);
1394 		Assert(edata->elevel == ERROR);
1395 		edata->elevel = FATAL;
1396 
1397 		/*
1398 		 * At least in principle, the increase in severity could have changed
1399 		 * where-to-output decisions, so recalculate.  This should stay in
1400 		 * sync with errstart(), which see for comments.
1401 		 */
1402 		if (IsPostmasterEnvironment)
1403 			edata->output_to_server = is_log_level_output(FATAL,
1404 														  log_min_messages);
1405 		else
1406 			edata->output_to_server = (FATAL >= log_min_messages);
1407 		if (whereToSendOutput == DestRemote)
1408 			edata->output_to_client = true;
1409 
1410 		/*
1411 		 * We can use errfinish() for the rest, but we don't want it to call
1412 		 * any error context routines a second time.  Since we know we are
1413 		 * about to exit, it should be OK to just clear the context stack.
1414 		 */
1415 		error_context_stack = NULL;
1416 
1417 		errfinish(0);
1418 	}
1419 
1420 	/* Doesn't return ... */
1421 	ExceptionalCondition("pg_re_throw tried to return", "FailedAssertion",
1422 						 __FILE__, __LINE__);
1423 }
1424 
1425 
1426 /*
1427  * GetErrorContextStack - Return the context stack, for display/diags
1428  *
1429  * Returns a pstrdup'd string in the caller's context which includes the PG
1430  * error call stack.  It is the caller's responsibility to ensure this string
1431  * is pfree'd (or its context cleaned up) when done.
1432  *
1433  * This information is collected by traversing the error contexts and calling
1434  * each context's callback function, each of which is expected to call
1435  * errcontext() to return a string which can be presented to the user.
1436  */
1437 
1438 
1439 
1440 /*
1441  * Initialization of error output file
1442  */
1443 
1444 
1445 
1446 #ifdef HAVE_SYSLOG
1447 
1448 /*
1449  * Set or update the parameters for syslog logging
1450  */
1451 
1452 
1453 
1454 /*
1455  * Write a message line to syslog
1456  */
1457 
1458 #endif							/* HAVE_SYSLOG */
1459 
1460 #ifdef WIN32
1461 /*
1462  * Get the PostgreSQL equivalent of the Windows ANSI code page.  "ANSI" system
1463  * interfaces (e.g. CreateFileA()) expect string arguments in this encoding.
1464  * Every process in a given system will find the same value at all times.
1465  */
1466 static int
GetACPEncoding(void)1467 GetACPEncoding(void)
1468 {
1469 	static int	encoding = -2;
1470 
1471 	if (encoding == -2)
1472 		encoding = pg_codepage_to_encoding(GetACP());
1473 
1474 	return encoding;
1475 }
1476 
1477 /*
1478  * Write a message line to the windows event log
1479  */
1480 static void
write_eventlog(int level,const char * line,int len)1481 write_eventlog(int level, const char *line, int len)
1482 {
1483 	WCHAR	   *utf16;
1484 	int			eventlevel = EVENTLOG_ERROR_TYPE;
1485 	static HANDLE evtHandle = INVALID_HANDLE_VALUE;
1486 
1487 	if (evtHandle == INVALID_HANDLE_VALUE)
1488 	{
1489 		evtHandle = RegisterEventSource(NULL,
1490 										event_source ? event_source : DEFAULT_EVENT_SOURCE);
1491 		if (evtHandle == NULL)
1492 		{
1493 			evtHandle = INVALID_HANDLE_VALUE;
1494 			return;
1495 		}
1496 	}
1497 
1498 	switch (level)
1499 	{
1500 		case DEBUG5:
1501 		case DEBUG4:
1502 		case DEBUG3:
1503 		case DEBUG2:
1504 		case DEBUG1:
1505 		case LOG:
1506 		case LOG_SERVER_ONLY:
1507 		case INFO:
1508 		case NOTICE:
1509 			eventlevel = EVENTLOG_INFORMATION_TYPE;
1510 			break;
1511 		case WARNING:
1512 			eventlevel = EVENTLOG_WARNING_TYPE;
1513 			break;
1514 		case ERROR:
1515 		case FATAL:
1516 		case PANIC:
1517 		default:
1518 			eventlevel = EVENTLOG_ERROR_TYPE;
1519 			break;
1520 	}
1521 
1522 	/*
1523 	 * If message character encoding matches the encoding expected by
1524 	 * ReportEventA(), call it to avoid the hazards of conversion.  Otherwise,
1525 	 * try to convert the message to UTF16 and write it with ReportEventW().
1526 	 * Fall back on ReportEventA() if conversion failed.
1527 	 *
1528 	 * Since we palloc the structure required for conversion, also fall
1529 	 * through to writing unconverted if we have not yet set up
1530 	 * CurrentMemoryContext.
1531 	 *
1532 	 * Also verify that we are not on our way into error recursion trouble due
1533 	 * to error messages thrown deep inside pgwin32_message_to_UTF16().
1534 	 */
1535 	if (!in_error_recursion_trouble() &&
1536 		CurrentMemoryContext != NULL &&
1537 		GetMessageEncoding() != GetACPEncoding())
1538 	{
1539 		utf16 = pgwin32_message_to_UTF16(line, len, NULL);
1540 		if (utf16)
1541 		{
1542 			ReportEventW(evtHandle,
1543 						 eventlevel,
1544 						 0,
1545 						 0,		/* All events are Id 0 */
1546 						 NULL,
1547 						 1,
1548 						 0,
1549 						 (LPCWSTR *) &utf16,
1550 						 NULL);
1551 			/* XXX Try ReportEventA() when ReportEventW() fails? */
1552 
1553 			pfree(utf16);
1554 			return;
1555 		}
1556 	}
1557 	ReportEventA(evtHandle,
1558 				 eventlevel,
1559 				 0,
1560 				 0,				/* All events are Id 0 */
1561 				 NULL,
1562 				 1,
1563 				 0,
1564 				 &line,
1565 				 NULL);
1566 }
1567 #endif							/* WIN32 */
1568 
1569 #ifdef WIN32
1570 #else
1571 #endif
1572 
1573 /*
1574  * setup formatted_log_time, for consistent times between CSV and regular logs
1575  */
1576 
1577 
1578 /*
1579  * setup formatted_start_time
1580  */
1581 
1582 
1583 /*
1584  * process_log_prefix_padding --- helper function for processing the format
1585  * string in log_line_prefix
1586  *
1587  * Note: This function returns NULL if it finds something which
1588  * it deems invalid in the format string.
1589  */
1590 
1591 
1592 /*
1593  * Format tag info for log lines; append to the provided buffer.
1594  */
1595 
1596 
1597 /*
1598  * append a CSV'd version of a string to a StringInfo
1599  * We use the PostgreSQL defaults for CSV, i.e. quote = escape = '"'
1600  * If it's NULL, append nothing.
1601  */
1602 
1603 
1604 /*
1605  * Constructs the error message, depending on the Errordata it gets, in a CSV
1606  * format which is described in doc/src/sgml/config.sgml.
1607  */
1608 
1609 
1610 /*
1611  * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
1612  * static buffer.
1613  */
1614 
1615 
1616 
1617 /*
1618  * Write error report to server's log
1619  */
send_message_to_server_log(ErrorData * edata)1620 static void send_message_to_server_log(ErrorData *edata) {}
1621 
1622 
1623 /*
1624  * Send data to the syslogger using the chunked protocol
1625  *
1626  * Note: when there are multiple backends writing into the syslogger pipe,
1627  * it's critical that each write go into the pipe indivisibly, and not
1628  * get interleaved with data from other processes.  Fortunately, the POSIX
1629  * spec requires that writes to pipes be atomic so long as they are not
1630  * more than PIPE_BUF bytes long.  So we divide long messages into chunks
1631  * that are no more than that length, and send one chunk per write() call.
1632  * The collector process knows how to reassemble the chunks.
1633  *
1634  * Because of the atomic write requirement, there are only two possible
1635  * results from write() here: -1 for failure, or the requested number of
1636  * bytes.  There is not really anything we can do about a failure; retry would
1637  * probably be an infinite loop, and we can't even report the error usefully.
1638  * (There is noplace else we could send it!)  So we might as well just ignore
1639  * the result from write().  However, on some platforms you get a compiler
1640  * warning from ignoring write()'s result, so do a little dance with casting
1641  * rc to void to shut up the compiler.
1642  */
1643 
1644 
1645 
1646 /*
1647  * Append a text string to the error report being built for the client.
1648  *
1649  * This is ordinarily identical to pq_sendstring(), but if we are in
1650  * error recursion trouble we skip encoding conversion, because of the
1651  * possibility that the problem is a failure in the encoding conversion
1652  * subsystem itself.  Code elsewhere should ensure that the passed-in
1653  * strings will be plain 7-bit ASCII, and thus not in need of conversion,
1654  * in such cases.  (In particular, we disable localization of error messages
1655  * to help ensure that's true.)
1656  */
1657 
1658 
1659 /*
1660  * Write error report to client
1661  */
send_message_to_frontend(ErrorData * edata)1662 static void send_message_to_frontend(ErrorData *edata) {}
1663 
1664 
1665 
1666 /*
1667  * Support routines for formatting error messages.
1668  */
1669 
1670 
1671 /*
1672  * expand_fmt_string --- process special format codes in a format string
1673  *
1674  * We must replace %m with the appropriate strerror string, since vsnprintf
1675  * won't know what to do with it.
1676  *
1677  * The result is a palloc'd string.
1678  */
1679 static char *
expand_fmt_string(const char * fmt,ErrorData * edata)1680 expand_fmt_string(const char *fmt, ErrorData *edata)
1681 {
1682 	StringInfoData buf;
1683 	const char *cp;
1684 
1685 	initStringInfo(&buf);
1686 
1687 	for (cp = fmt; *cp; cp++)
1688 	{
1689 		if (cp[0] == '%' && cp[1] != '\0')
1690 		{
1691 			cp++;
1692 			if (*cp == 'm')
1693 			{
1694 				/*
1695 				 * Replace %m by system error string.  If there are any %'s in
1696 				 * the string, we'd better double them so that vsnprintf won't
1697 				 * misinterpret.
1698 				 */
1699 				const char *cp2;
1700 
1701 				cp2 = useful_strerror(edata->saved_errno);
1702 				for (; *cp2; cp2++)
1703 				{
1704 					if (*cp2 == '%')
1705 						appendStringInfoCharMacro(&buf, '%');
1706 					appendStringInfoCharMacro(&buf, *cp2);
1707 				}
1708 			}
1709 			else
1710 			{
1711 				/* copy % and next char --- this avoids trouble with %%m */
1712 				appendStringInfoCharMacro(&buf, '%');
1713 				appendStringInfoCharMacro(&buf, *cp);
1714 			}
1715 		}
1716 		else
1717 			appendStringInfoCharMacro(&buf, *cp);
1718 	}
1719 
1720 	return buf.data;
1721 }
1722 
1723 
1724 /*
1725  * A slightly cleaned-up version of strerror()
1726  */
1727 static const char *
useful_strerror(int errnum)1728 useful_strerror(int errnum)
1729 {
1730 	/* this buffer is only used if strerror() and get_errno_symbol() fail */
1731 	static char errorstr_buf[48];
1732 	const char *str;
1733 
1734 #ifdef WIN32
1735 	/* Winsock error code range, per WinError.h */
1736 	if (errnum >= 10000 && errnum <= 11999)
1737 		return pgwin32_socket_strerror(errnum);
1738 #endif
1739 	str = strerror(errnum);
1740 
1741 	/*
1742 	 * Some strerror()s return an empty string for out-of-range errno.  This
1743 	 * is ANSI C spec compliant, but not exactly useful.  Also, we may get
1744 	 * back strings of question marks if libc cannot transcode the message to
1745 	 * the codeset specified by LC_CTYPE.  If we get nothing useful, first try
1746 	 * get_errno_symbol(), and if that fails, print the numeric errno.
1747 	 */
1748 	if (str == NULL || *str == '\0' || *str == '?')
1749 		str = get_errno_symbol(errnum);
1750 
1751 	if (str == NULL)
1752 	{
1753 		snprintf(errorstr_buf, sizeof(errorstr_buf),
1754 		/*------
1755 		  translator: This string will be truncated at 47
1756 		  characters expanded. */
1757 				 _("operating system error %d"), errnum);
1758 		str = errorstr_buf;
1759 	}
1760 
1761 	return str;
1762 }
1763 
1764 /*
1765  * Returns a symbol (e.g. "ENOENT") for an errno code.
1766  * Returns NULL if the code is unrecognized.
1767  */
1768 static const char *
get_errno_symbol(int errnum)1769 get_errno_symbol(int errnum)
1770 {
1771 	switch (errnum)
1772 	{
1773 		case E2BIG:
1774 			return "E2BIG";
1775 		case EACCES:
1776 			return "EACCES";
1777 #ifdef EADDRINUSE
1778 		case EADDRINUSE:
1779 			return "EADDRINUSE";
1780 #endif
1781 #ifdef EADDRNOTAVAIL
1782 		case EADDRNOTAVAIL:
1783 			return "EADDRNOTAVAIL";
1784 #endif
1785 		case EAFNOSUPPORT:
1786 			return "EAFNOSUPPORT";
1787 #ifdef EAGAIN
1788 		case EAGAIN:
1789 			return "EAGAIN";
1790 #endif
1791 #ifdef EALREADY
1792 		case EALREADY:
1793 			return "EALREADY";
1794 #endif
1795 		case EBADF:
1796 			return "EBADF";
1797 #ifdef EBADMSG
1798 		case EBADMSG:
1799 			return "EBADMSG";
1800 #endif
1801 		case EBUSY:
1802 			return "EBUSY";
1803 		case ECHILD:
1804 			return "ECHILD";
1805 #ifdef ECONNABORTED
1806 		case ECONNABORTED:
1807 			return "ECONNABORTED";
1808 #endif
1809 		case ECONNREFUSED:
1810 			return "ECONNREFUSED";
1811 #ifdef ECONNRESET
1812 		case ECONNRESET:
1813 			return "ECONNRESET";
1814 #endif
1815 		case EDEADLK:
1816 			return "EDEADLK";
1817 		case EDOM:
1818 			return "EDOM";
1819 		case EEXIST:
1820 			return "EEXIST";
1821 		case EFAULT:
1822 			return "EFAULT";
1823 		case EFBIG:
1824 			return "EFBIG";
1825 #ifdef EHOSTUNREACH
1826 		case EHOSTUNREACH:
1827 			return "EHOSTUNREACH";
1828 #endif
1829 		case EIDRM:
1830 			return "EIDRM";
1831 		case EINPROGRESS:
1832 			return "EINPROGRESS";
1833 		case EINTR:
1834 			return "EINTR";
1835 		case EINVAL:
1836 			return "EINVAL";
1837 		case EIO:
1838 			return "EIO";
1839 #ifdef EISCONN
1840 		case EISCONN:
1841 			return "EISCONN";
1842 #endif
1843 		case EISDIR:
1844 			return "EISDIR";
1845 #ifdef ELOOP
1846 		case ELOOP:
1847 			return "ELOOP";
1848 #endif
1849 		case EMFILE:
1850 			return "EMFILE";
1851 		case EMLINK:
1852 			return "EMLINK";
1853 		case EMSGSIZE:
1854 			return "EMSGSIZE";
1855 		case ENAMETOOLONG:
1856 			return "ENAMETOOLONG";
1857 		case ENFILE:
1858 			return "ENFILE";
1859 		case ENOBUFS:
1860 			return "ENOBUFS";
1861 		case ENODEV:
1862 			return "ENODEV";
1863 		case ENOENT:
1864 			return "ENOENT";
1865 		case ENOEXEC:
1866 			return "ENOEXEC";
1867 		case ENOMEM:
1868 			return "ENOMEM";
1869 		case ENOSPC:
1870 			return "ENOSPC";
1871 		case ENOSYS:
1872 			return "ENOSYS";
1873 #ifdef ENOTCONN
1874 		case ENOTCONN:
1875 			return "ENOTCONN";
1876 #endif
1877 		case ENOTDIR:
1878 			return "ENOTDIR";
1879 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
1880 		case ENOTEMPTY:
1881 			return "ENOTEMPTY";
1882 #endif
1883 #ifdef ENOTSOCK
1884 		case ENOTSOCK:
1885 			return "ENOTSOCK";
1886 #endif
1887 #ifdef ENOTSUP
1888 		case ENOTSUP:
1889 			return "ENOTSUP";
1890 #endif
1891 		case ENOTTY:
1892 			return "ENOTTY";
1893 		case ENXIO:
1894 			return "ENXIO";
1895 #if defined(EOPNOTSUPP) && (!defined(ENOTSUP) || (EOPNOTSUPP != ENOTSUP))
1896 		case EOPNOTSUPP:
1897 			return "EOPNOTSUPP";
1898 #endif
1899 #ifdef EOVERFLOW
1900 		case EOVERFLOW:
1901 			return "EOVERFLOW";
1902 #endif
1903 		case EPERM:
1904 			return "EPERM";
1905 		case EPIPE:
1906 			return "EPIPE";
1907 		case EPROTONOSUPPORT:
1908 			return "EPROTONOSUPPORT";
1909 		case ERANGE:
1910 			return "ERANGE";
1911 #ifdef EROFS
1912 		case EROFS:
1913 			return "EROFS";
1914 #endif
1915 		case ESRCH:
1916 			return "ESRCH";
1917 #ifdef ETIMEDOUT
1918 		case ETIMEDOUT:
1919 			return "ETIMEDOUT";
1920 #endif
1921 #ifdef ETXTBSY
1922 		case ETXTBSY:
1923 			return "ETXTBSY";
1924 #endif
1925 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1926 		case EWOULDBLOCK:
1927 			return "EWOULDBLOCK";
1928 #endif
1929 		case EXDEV:
1930 			return "EXDEV";
1931 	}
1932 
1933 	return NULL;
1934 }
1935 
1936 
1937 /*
1938  * error_severity --- get string representing elevel
1939  *
1940  * The string is not localized here, but we mark the strings for translation
1941  * so that callers can invoke _() on the result.
1942  */
1943 
1944 
1945 
1946 /*
1947  *	append_with_tabs
1948  *
1949  *	Append the string to the StringInfo buffer, inserting a tab after any
1950  *	newline.
1951  */
1952 
1953 
1954 
1955 /*
1956  * Write errors to stderr (or by equal means when stderr is
1957  * not available). Used before ereport/elog can be used
1958  * safely (memory context, GUC load etc)
1959  */
1960 void
write_stderr(const char * fmt,...)1961 write_stderr(const char *fmt,...)
1962 {
1963 	va_list		ap;
1964 
1965 #ifdef WIN32
1966 	char		errbuf[2048];	/* Arbitrary size? */
1967 #endif
1968 
1969 	fmt = _(fmt);
1970 
1971 	va_start(ap, fmt);
1972 #ifndef WIN32
1973 	/* On Unix, we just fprintf to stderr */
1974 	vfprintf(stderr, fmt, ap);
1975 	fflush(stderr);
1976 #else
1977 	vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
1978 
1979 	/*
1980 	 * On Win32, we print to stderr if running on a console, or write to
1981 	 * eventlog if running as a service
1982 	 */
1983 	if (pgwin32_is_service())	/* Running as a service */
1984 	{
1985 		write_eventlog(ERROR, errbuf, strlen(errbuf));
1986 	}
1987 	else
1988 	{
1989 		/* Not running as service, write to stderr */
1990 		write_console(errbuf, strlen(errbuf));
1991 		fflush(stderr);
1992 	}
1993 #endif
1994 	va_end(ap);
1995 }
1996 
1997 
1998 /*
1999  * is_log_level_output -- is elevel logically >= log_min_level?
2000  *
2001  * We use this for tests that should consider LOG to sort out-of-order,
2002  * between ERROR and FATAL.  Generally this is the right thing for testing
2003  * whether a message should go to the postmaster log, whereas a simple >=
2004  * test is correct for testing whether the message should go to the client.
2005  */
2006 static bool
is_log_level_output(int elevel,int log_min_level)2007 is_log_level_output(int elevel, int log_min_level)
2008 {
2009 	if (elevel == LOG || elevel == LOG_SERVER_ONLY)
2010 	{
2011 		if (log_min_level == LOG || log_min_level <= ERROR)
2012 			return true;
2013 	}
2014 	else if (log_min_level == LOG)
2015 	{
2016 		/* elevel != LOG */
2017 		if (elevel >= FATAL)
2018 			return true;
2019 	}
2020 	/* Neither is LOG */
2021 	else if (elevel >= log_min_level)
2022 		return true;
2023 
2024 	return false;
2025 }
2026 
2027 /*
2028  * Adjust the level of a recovery-related message per trace_recovery_messages.
2029  *
2030  * The argument is the default log level of the message, eg, DEBUG2.  (This
2031  * should only be applied to DEBUGn log messages, otherwise it's a no-op.)
2032  * If the level is >= trace_recovery_messages, we return LOG, causing the
2033  * message to be logged unconditionally (for most settings of
2034  * log_min_messages).  Otherwise, we return the argument unchanged.
2035  * The message will then be shown based on the setting of log_min_messages.
2036  *
2037  * Intention is to keep this for at least the whole of the 9.0 production
2038  * release, so we can more easily diagnose production problems in the field.
2039  * It should go away eventually, though, because it's an ugly and
2040  * hard-to-explain kluge.
2041  */
2042 
2043