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