PageRenderTime 101ms CodeModel.GetById 30ms app.highlight 54ms RepoModel.GetById 0ms app.codeStats 1ms

/postgresql-9.2.1/src/backend/utils/error/elog.c

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