PageRenderTime 151ms CodeModel.GetById 3ms app.highlight 126ms RepoModel.GetById 1ms app.codeStats 1ms

/src/backend/utils/error/elog.c

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