PageRenderTime 14ms CodeModel.GetById 144ms app.highlight 82ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://bitbucket.org/mhellegers/pghaikuport
C | 3001 lines | 1704 code | 401 blank | 896 comment | 317 complexity | 7cffc7a3537c53797b55fd5ec9be50f5 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-2013, 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(domain, 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((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(domain, 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((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(edata->domain, 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(edata->domain, 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(edata->domain, 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(edata->domain, 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(edata->domain, 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(edata->domain, 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(edata->domain, 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(edata->domain, hint, false, true);
 950
 951	MemoryContextSwitchTo(oldcontext);
 952	recursion_depth--;
 953	return 0;					/* return value does not matter */
 954}
 955
 956
 957/*
 958 * errcontext_msg --- 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_msg(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(edata->context_domain, context, true, true);
 975
 976	MemoryContextSwitchTo(oldcontext);
 977	recursion_depth--;
 978	return 0;					/* return value does not matter */
 979}
 980
 981/*
 982 * set_errcontext_domain --- set message domain to be used by errcontext()
 983 *
 984 * errcontext_msg() can be called from a different module than the original
 985 * ereport(), so we cannot use the message domain passed in errstart() to
 986 * translate it.  Instead, each errcontext_msg() call should be preceded by
 987 * a set_errcontext_domain() call to specify the domain.  This is usually
 988 * done transparently by the errcontext() macro.
 989 */
 990int
 991set_errcontext_domain(const char *domain)
 992{
 993	ErrorData  *edata = &errordata[errordata_stack_depth];
 994
 995	/* we don't bother incrementing recursion_depth */
 996	CHECK_STACK_DEPTH();
 997
 998	edata->context_domain = domain;
 999
1000	return 0;					/* return value does not matter */
1001}
1002
1003
1004/*
1005 * errhidestmt --- optionally suppress STATEMENT: field of log entry
1006 *
1007 * This should be called if the message text already includes the statement.
1008 */
1009int
1010errhidestmt(bool hide_stmt)
1011{
1012	ErrorData  *edata = &errordata[errordata_stack_depth];
1013
1014	/* we don't bother incrementing recursion_depth */
1015	CHECK_STACK_DEPTH();
1016
1017	edata->hide_stmt = hide_stmt;
1018
1019	return 0;					/* return value does not matter */
1020}
1021
1022
1023/*
1024 * errfunction --- add reporting function name to the current error
1025 *
1026 * This is used when backwards compatibility demands that the function
1027 * name appear in messages sent to old-protocol clients.  Note that the
1028 * passed string is expected to be a non-freeable constant string.
1029 */
1030int
1031errfunction(const char *funcname)
1032{
1033	ErrorData  *edata = &errordata[errordata_stack_depth];
1034
1035	/* we don't bother incrementing recursion_depth */
1036	CHECK_STACK_DEPTH();
1037
1038	edata->funcname = funcname;
1039	edata->show_funcname = true;
1040
1041	return 0;					/* return value does not matter */
1042}
1043
1044/*
1045 * errposition --- add cursor position to the current error
1046 */
1047int
1048errposition(int cursorpos)
1049{
1050	ErrorData  *edata = &errordata[errordata_stack_depth];
1051
1052	/* we don't bother incrementing recursion_depth */
1053	CHECK_STACK_DEPTH();
1054
1055	edata->cursorpos = cursorpos;
1056
1057	return 0;					/* return value does not matter */
1058}
1059
1060/*
1061 * internalerrposition --- add internal cursor position to the current error
1062 */
1063int
1064internalerrposition(int cursorpos)
1065{
1066	ErrorData  *edata = &errordata[errordata_stack_depth];
1067
1068	/* we don't bother incrementing recursion_depth */
1069	CHECK_STACK_DEPTH();
1070
1071	edata->internalpos = cursorpos;
1072
1073	return 0;					/* return value does not matter */
1074}
1075
1076/*
1077 * internalerrquery --- add internal query text to the current error
1078 *
1079 * Can also pass NULL to drop the internal query text entry.  This case
1080 * is intended for use in error callback subroutines that are editorializing
1081 * on the layout of the error report.
1082 */
1083int
1084internalerrquery(const char *query)
1085{
1086	ErrorData  *edata = &errordata[errordata_stack_depth];
1087
1088	/* we don't bother incrementing recursion_depth */
1089	CHECK_STACK_DEPTH();
1090
1091	if (edata->internalquery)
1092	{
1093		pfree(edata->internalquery);
1094		edata->internalquery = NULL;
1095	}
1096
1097	if (query)
1098		edata->internalquery = MemoryContextStrdup(ErrorContext, query);
1099
1100	return 0;					/* return value does not matter */
1101}
1102
1103/*
1104 * geterrcode --- return the currently set SQLSTATE error code
1105 *
1106 * This is only intended for use in error callback subroutines, since there
1107 * is no other place outside elog.c where the concept is meaningful.
1108 */
1109int
1110geterrcode(void)
1111{
1112	ErrorData  *edata = &errordata[errordata_stack_depth];
1113
1114	/* we don't bother incrementing recursion_depth */
1115	CHECK_STACK_DEPTH();
1116
1117	return edata->sqlerrcode;
1118}
1119
1120/*
1121 * geterrposition --- return the currently set error position (0 if none)
1122 *
1123 * This is only intended for use in error callback subroutines, since there
1124 * is no other place outside elog.c where the concept is meaningful.
1125 */
1126int
1127geterrposition(void)
1128{
1129	ErrorData  *edata = &errordata[errordata_stack_depth];
1130
1131	/* we don't bother incrementing recursion_depth */
1132	CHECK_STACK_DEPTH();
1133
1134	return edata->cursorpos;
1135}
1136
1137/*
1138 * getinternalerrposition --- same for internal error position
1139 *
1140 * This is only intended for use in error callback subroutines, since there
1141 * is no other place outside elog.c where the concept is meaningful.
1142 */
1143int
1144getinternalerrposition(void)
1145{
1146	ErrorData  *edata = &errordata[errordata_stack_depth];
1147
1148	/* we don't bother incrementing recursion_depth */
1149	CHECK_STACK_DEPTH();
1150
1151	return edata->internalpos;
1152}
1153
1154
1155/*
1156 * elog_start --- startup for old-style API
1157 *
1158 * All that we do here is stash the hidden filename/lineno/funcname
1159 * arguments into a stack entry.
1160 *
1161 * We need this to be separate from elog_finish because there's no other
1162 * portable way to deal with inserting extra arguments into the elog call.
1163 * (If macros with variable numbers of arguments were portable, it'd be
1164 * easy, but they aren't.)
1165 */
1166void
1167elog_start(const char *filename, int lineno, const char *funcname)
1168{
1169	ErrorData  *edata;
1170
1171	if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1172	{
1173		/*
1174		 * Wups, stack not big enough.	We treat this as a PANIC condition
1175		 * because it suggests an infinite loop of errors during error
1176		 * recovery.  Note that the message is intentionally not localized,
1177		 * else failure to convert it to client encoding could cause further
1178		 * recursion.
1179		 */
1180		errordata_stack_depth = -1;		/* make room on stack */
1181		ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1182	}
1183
1184	edata = &errordata[errordata_stack_depth];
1185	if (filename)
1186	{
1187		const char *slash;
1188
1189		/* keep only base name, useful especially for vpath builds */
1190		slash = strrchr(filename, '/');
1191		if (slash)
1192			filename = slash + 1;
1193	}
1194	edata->filename = filename;
1195	edata->lineno = lineno;
1196	edata->funcname = funcname;
1197	/* errno is saved now so that error parameter eval can't change it */
1198	edata->saved_errno = errno;
1199}
1200
1201/*
1202 * elog_finish --- finish up for old-style API
1203 */
1204void
1205elog_finish(int elevel, const char *fmt,...)
1206{
1207	ErrorData  *edata = &errordata[errordata_stack_depth];
1208	MemoryContext oldcontext;
1209
1210	CHECK_STACK_DEPTH();
1211
1212	/*
1213	 * Do errstart() to see if we actually want to report the message.
1214	 */
1215	errordata_stack_depth--;
1216	errno = edata->saved_errno;
1217	if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname, NULL))
1218		return;					/* nothing to do */
1219
1220	/*
1221	 * Format error message just like errmsg_internal().
1222	 */
1223	recursion_depth++;
1224	oldcontext = MemoryContextSwitchTo(ErrorContext);
1225
1226	EVALUATE_MESSAGE(edata->domain, message, false, false);
1227
1228	MemoryContextSwitchTo(oldcontext);
1229	recursion_depth--;
1230
1231	/*
1232	 * And let errfinish() finish up.
1233	 */
1234	errfinish(0);
1235}
1236
1237
1238/*
1239 * Functions to allow construction of error message strings separately from
1240 * the ereport() call itself.
1241 *
1242 * The expected calling convention is
1243 *
1244 *	pre_format_elog_string(errno, domain), var = format_elog_string(format,...)
1245 *
1246 * which can be hidden behind a macro such as GUC_check_errdetail().  We
1247 * assume that any functions called in the arguments of format_elog_string()
1248 * cannot result in re-entrant use of these functions --- otherwise the wrong
1249 * text domain might be used, or the wrong errno substituted for %m.  This is
1250 * okay for the current usage with GUC check hooks, but might need further
1251 * effort someday.
1252 *
1253 * The result of format_elog_string() is stored in ErrorContext, and will
1254 * therefore survive until FlushErrorState() is called.
1255 */
1256static int	save_format_errnumber;
1257static const char *save_format_domain;
1258
1259void
1260pre_format_elog_string(int errnumber, const char *domain)
1261{
1262	/* Save errno before evaluation of argument functions can change it */
1263	save_format_errnumber = errnumber;
1264	/* Save caller's text domain */
1265	save_format_domain = domain;
1266}
1267
1268char *
1269format_elog_string(const char *fmt,...)
1270{
1271	ErrorData	errdata;
1272	ErrorData  *edata;
1273	MemoryContext oldcontext;
1274
1275	/* Initialize a mostly-dummy error frame */
1276	edata = &errdata;
1277	MemSet(edata, 0, sizeof(ErrorData));
1278	/* the default text domain is the backend's */
1279	edata->domain = save_format_domain ? save_format_domain : PG_TEXTDOMAIN("postgres");
1280	/* set the errno to be used to interpret %m */
1281	edata->saved_errno = save_format_errnumber;
1282
1283	oldcontext = MemoryContextSwitchTo(ErrorContext);
1284
1285	EVALUATE_MESSAGE(edata->domain, message, false, true);
1286
1287	MemoryContextSwitchTo(oldcontext);
1288
1289	return edata->message;
1290}
1291
1292
1293/*
1294 * Actual output of the top-of-stack error message
1295 *
1296 * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
1297 * if the error is caught by somebody).  For all other severity levels this
1298 * is called by errfinish.
1299 */
1300void
1301EmitErrorReport(void)
1302{
1303	ErrorData  *edata = &errordata[errordata_stack_depth];
1304	MemoryContext oldcontext;
1305
1306	recursion_depth++;
1307	CHECK_STACK_DEPTH();
1308	oldcontext = MemoryContextSwitchTo(ErrorContext);
1309
1310	/*
1311	 * Call hook before sending message to log.  The hook function is allowed
1312	 * to turn off edata->output_to_server, so we must recheck that afterward.
1313	 * Making any other change in the content of edata is not considered
1314	 * supported.
1315	 *
1316	 * Note: the reason why the hook can only turn off output_to_server, and
1317	 * not turn it on, is that it'd be unreliable: we will never get here at
1318	 * all if errstart() deems the message uninteresting.  A hook that could
1319	 * make decisions in that direction would have to hook into errstart(),
1320	 * where it would have much less information available.  emit_log_hook is
1321	 * intended for custom log filtering and custom log message transmission
1322	 * mechanisms.
1323	 */
1324	if (edata->output_to_server && emit_log_hook)
1325		(*emit_log_hook) (edata);
1326
1327	/* Send to server log, if enabled */
1328	if (edata->output_to_server)
1329		send_message_to_server_log(edata);
1330
1331	/* Send to client, if enabled */
1332	if (edata->output_to_client)
1333		send_message_to_frontend(edata);
1334
1335	MemoryContextSwitchTo(oldcontext);
1336	recursion_depth--;
1337}
1338
1339/*
1340 * CopyErrorData --- obtain a copy of the topmost error stack entry
1341 *
1342 * This is only for use in error handler code.	The data is copied into the
1343 * current memory context, so callers should always switch away from
1344 * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
1345 */
1346ErrorData *
1347CopyErrorData(void)
1348{
1349	ErrorData  *edata = &errordata[errordata_stack_depth];
1350	ErrorData  *newedata;
1351
1352	/*
1353	 * we don't increment recursion_depth because out-of-memory here does not
1354	 * indicate a problem within the error subsystem.
1355	 */
1356	CHECK_STACK_DEPTH();
1357
1358	Assert(CurrentMemoryContext != ErrorContext);
1359
1360	/* Copy the struct itself */
1361	newedata = (ErrorData *) palloc(sizeof(ErrorData));
1362	memcpy(newedata, edata, sizeof(ErrorData));
1363
1364	/* Make copies of separately-allocated fields */
1365	if (newedata->message)
1366		newedata->message = pstrdup(newedata->message);
1367	if (newedata->detail)
1368		newedata->detail = pstrdup(newedata->detail);
1369	if (newedata->detail_log)
1370		newedata->detail_log = pstrdup(newedata->detail_log);
1371	if (newedata->hint)
1372		newedata->hint = pstrdup(newedata->hint);
1373	if (newedata->context)
1374		newedata->context = pstrdup(newedata->context);
1375	if (newedata->internalquery)
1376		newedata->internalquery = pstrdup(newedata->internalquery);
1377
1378	return newedata;
1379}
1380
1381/*
1382 * FreeErrorData --- free the structure returned by CopyErrorData.
1383 *
1384 * Error handlers should use this in preference to assuming they know all
1385 * the separately-allocated fields.
1386 */
1387void
1388FreeErrorData(ErrorData *edata)
1389{
1390	if (edata->message)
1391		pfree(edata->message);
1392	if (edata->detail)
1393		pfree(edata->detail);
1394	if (edata->detail_log)
1395		pfree(edata->detail_log);
1396	if (edata->hint)
1397		pfree(edata->hint);
1398	if (edata->context)
1399		pfree(edata->context);
1400	if (edata->internalquery)
1401		pfree(edata->internalquery);
1402	pfree(edata);
1403}
1404
1405/*
1406 * FlushErrorState --- flush the error state after error recovery
1407 *
1408 * This should be called by an error handler after it's done processing
1409 * the error; or as soon as it's done CopyErrorData, if it intends to
1410 * do stuff that is likely to provoke another error.  You are not "out" of
1411 * the error subsystem until you have done this.
1412 */
1413void
1414FlushErrorState(void)
1415{
1416	/*
1417	 * Reset stack to empty.  The only case where it would be more than one
1418	 * deep is if we serviced an error that interrupted construction of
1419	 * another message.  We assume control escaped out of that message
1420	 * construction and won't ever go back.
1421	 */
1422	errordata_stack_depth = -1;
1423	recursion_depth = 0;
1424	/* Delete all data in ErrorContext */
1425	MemoryContextResetAndDeleteChildren(ErrorContext);
1426}
1427
1428/*
1429 * ReThrowError --- re-throw a previously copied error
1430 *
1431 * A handler can do CopyErrorData/FlushErrorState to get out of the error
1432 * subsystem, then do some processing, and finally ReThrowError to re-throw
1433 * the original error.	This is slower than just PG_RE_THROW() but should
1434 * be used if the "some processing" is likely to incur another error.
1435 */
1436void
1437ReThrowError(ErrorData *edata)
1438{
1439	ErrorData  *newedata;
1440
1441	Assert(edata->elevel == ERROR);
1442
1443	/* Push the data back into the error context */
1444	recursion_depth++;
1445	MemoryContextSwitchTo(ErrorContext);
1446
1447	if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1448	{
1449		/*
1450		 * Wups, stack not big enough.	We treat this as a PANIC condition
1451		 * because it suggests an infinite loop of errors during error
1452		 * recovery.
1453		 */
1454		errordata_stack_depth = -1;		/* make room on stack */
1455		ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1456	}
1457
1458	newedata = &errordata[errordata_stack_depth];
1459	memcpy(newedata, edata, sizeof(ErrorData));
1460
1461	/* Make copies of separately-allocated fields */
1462	if (newedata->message)
1463		newedata->message = pstrdup(newedata->message);
1464	if (newedata->detail)
1465		newedata->detail = pstrdup(newedata->detail);
1466	if (newedata->detail_log)
1467		newedata->detail_log = pstrdup(newedata->detail_log);
1468	if (newedata->hint)
1469		newedata->hint = pstrdup(newedata->hint);
1470	if (newedata->context)
1471		newedata->context = pstrdup(newedata->context);
1472	if (newedata->internalquery)
1473		newedata->internalquery = pstrdup(newedata->internalquery);
1474
1475	recursion_depth--;
1476	PG_RE_THROW();
1477}
1478
1479/*
1480 * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
1481 */
1482void
1483pg_re_throw(void)
1484{
1485	/* If possible, throw the error to the next outer setjmp handler */
1486	if (PG_exception_stack != NULL)
1487		siglongjmp(*PG_exception_stack, 1);
1488	else
1489	{
1490		/*
1491		 * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
1492		 * we have now exited only to discover that there is no outer setjmp
1493		 * handler to pass the error to.  Had the error been thrown outside
1494		 * the block to begin with, we'd have promoted the error to FATAL, so
1495		 * the correct behavior is to make it FATAL now; that is, emit it and
1496		 * then call proc_exit.
1497		 */
1498		ErrorData  *edata = &errordata[errordata_stack_depth];
1499
1500		Assert(errordata_stack_depth >= 0);
1501		Assert(edata->elevel == ERROR);
1502		edata->elevel = FATAL;
1503
1504		/*
1505		 * At least in principle, the increase in severity could have changed
1506		 * where-to-output decisions, so recalculate.  This should stay in
1507		 * sync with errstart(), which see for comments.
1508		 */
1509		if (IsPostmasterEnvironment)
1510			edata->output_to_server = is_log_level_output(FATAL,
1511														  log_min_messages);
1512		else
1513			edata->output_to_server = (FATAL >= log_min_messages);
1514		if (whereToSendOutput == DestRemote)
1515		{
1516			if (ClientAuthInProgress)
1517				edata->output_to_client = true;
1518			else
1519				edata->output_to_client = (FATAL >= client_min_messages);
1520		}
1521
1522		/*
1523		 * We can use errfinish() for the rest, but we don't want it to call
1524		 * any error context routines a second time.  Since we know we are
1525		 * about to exit, it should be OK to just clear the context stack.
1526		 */
1527		error_context_stack = NULL;
1528
1529		errfinish(0);
1530	}
1531
1532	/* Doesn't return ... */
1533	ExceptionalCondition("pg_re_throw tried to return", "FailedAssertion",
1534						 __FILE__, __LINE__);
1535}
1536
1537
1538/*
1539 * Initialization of error output file
1540 */
1541void
1542DebugFileOpen(void)
1543{
1544	int			fd,
1545				istty;
1546
1547	if (OutputFileName[0])
1548	{
1549		/*
1550		 * A debug-output file name was given.
1551		 *
1552		 * Make sure we can write the file, and find out if it's a tty.
1553		 */
1554		if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
1555					   0666)) < 0)
1556			ereport(FATAL,
1557					(errcode_for_file_access(),
1558				  errmsg("could not open file \"%s\": %m", OutputFileName)));
1559		istty = isatty(fd);
1560		close(fd);
1561
1562		/*
1563		 * Redirect our stderr to the debug output file.
1564		 */
1565		if (!freopen(OutputFileName, "a", stderr))
1566			ereport(FATAL,
1567					(errcode_for_file_access(),
1568					 errmsg("could not reopen file \"%s\" as stderr: %m",
1569							OutputFileName)));
1570
1571		/*
1572		 * If the file is a tty and we're running under the postmaster, try to
1573		 * send stdout there as well (if it isn't a tty then stderr will block
1574		 * out stdout, so we may as well let stdout go wherever it was going
1575		 * before).
1576		 */
1577		if (istty && IsUnderPostmaster)
1578			if (!freopen(OutputFileName, "a", stdout))
1579				ereport(FATAL,
1580						(errcode_for_file_access(),
1581						 errmsg("could not reopen file \"%s\" as stdout: %m",
1582								OutputFileName)));
1583	}
1584}
1585
1586
1587#ifdef HAVE_SYSLOG
1588
1589/*
1590 * Set or update the parameters for syslog logging
1591 */
1592void
1593set_syslog_parameters(const char *ident, int facility)
1594{
1595	/*
1596	 * guc.c is likely to call us repeatedly with same parameters, so don't
1597	 * thrash the syslog connection unnecessarily.	Also, we do not re-open
1598	 * the connection until needed, since this routine will get called whether
1599	 * or not Log_destination actually mentions syslog.
1600	 *
1601	 * Note that we make our own copy of the ident string rather than relying
1602	 * on guc.c's.  This may be overly paranoid, but it ensures that we cannot
1603	 * accidentally free a string that syslog is still using.
1604	 */
1605	if (syslog_ident == NULL || strcmp(syslog_ident, ident) != 0 ||
1606		syslog_facility != facility)
1607	{
1608		if (openlog_done)
1609		{
1610			closelog();
1611			openlog_done = false;
1612		}
1613		if (syslog_ident)
1614			free(syslog_ident);
1615		syslog_ident = strdup(ident);
1616		/* if the strdup fails, we will cope in write_syslog() */
1617		syslog_facility = facility;
1618	}
1619}
1620
1621
1622/*
1623 * Write a message line to syslog
1624 */
1625static void
1626write_syslog(int level, const char *line)
1627{
1628	static unsigned long seq = 0;
1629
1630	int			len;
1631	const char *nlpos;
1632
1633	/* Open syslog connection if not done yet */
1634	if (!openlog_done)
1635	{
1636		openlog(syslog_ident ? syslog_ident : "postgres",
1637				LOG_PID | LOG_NDELAY | LOG_NOWAIT,
1638				syslog_facility);
1639		openlog_done = true;
1640	}
1641
1642	/*
1643	 * We add a sequence number to each log message to suppress "same"
1644	 * messages.
1645	 */
1646	seq++;
1647
1648	/*
1649	 * Our problem here is that many syslog implementations don't handle long
1650	 * messages in an acceptable manner. While this function doesn't help that
1651	 * fact, it does work around by splitting up messages into smaller pieces.
1652	 *
1653	 * We divide into multiple syslog() calls if message is too long or if the
1654	 * message contains embedded newline(s).
1655	 */
1656	len = strlen(line);
1657	nlpos = strchr(line, '\n');
1658	if (len > PG_SYSLOG_LIMIT || nlpos != NULL)
1659	{
1660		int			chunk_nr = 0;
1661
1662		while (len > 0)
1663		{
1664			char		buf[PG_SYSLOG_LIMIT + 1];
1665			int			buflen;
1666			int			i;
1667
1668			/* if we start at a newline, move ahead one char */
1669			if (line[0] == '\n')
1670			{
1671				line++;
1672				len--;
1673				/* we need to recompute the next newline's position, too */
1674				nlpos = strchr(line, '\n');
1675				continue;
1676			}
1677
1678			/* copy one line, or as much as will fit, to buf */
1679			if (nlpos != NULL)
1680				buflen = nlpos - line;
1681			else
1682				buflen = len;
1683			buflen = Min(buflen, PG_SYSLOG_LIMIT);
1684			memcpy(buf, line, buflen);
1685			buf[buflen] = '\0';
1686
1687			/* trim to multibyte letter boundary */
1688			buflen = pg_mbcliplen(buf, buflen, buflen);
1689			if (buflen <= 0)
1690				return;
1691			buf[buflen] = '\0';
1692
1693			/* already word boundary? */
1694			if (line[buflen] != '\0' &&
1695				!isspace((unsigned char) line[buflen]))
1696			{
1697				/* try to divide at word boundary */
1698				i = buflen - 1;
1699				while (i > 0 && !isspace((unsigned char) buf[i]))
1700					i--;
1701
1702				if (i > 0)		/* else couldn't divide word boundary */
1703				{
1704					buflen = i;
1705					buf[i] = '\0';
1706				}
1707			}
1708
1709			chunk_nr++;
1710
1711			syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1712			line += buflen;
1713			len -= buflen;
1714		}
1715	}
1716	else
1717	{
1718		/* message short enough */
1719		syslog(level, "[%lu] %s", seq, line);
1720	}
1721}
1722#endif   /* HAVE_SYSLOG */
1723
1724#ifdef WIN32
1725/*
1726 * Write a message line to the windows event log
1727 */
1728static void
1729write_eventlog(int level, const char *line, int len)
1730{
1731	WCHAR	   *utf16;
1732	int			eventlevel = EVENTLOG_ERROR_TYPE;
1733	static HANDLE evtHandle = INVALID_HANDLE_VALUE;
1734
1735	if (evtHandle == INVALID_HANDLE_VALUE)
1736	{
1737		evtHandle = RegisterEventSource(NULL, event_source ? event_source : "PostgreSQL");
1738		if (evtHandle == NULL)
1739		{
1740			evtHandle = INVALID_HANDLE_VALUE;
1741			return;
1742		}
1743	}
1744
1745	switch (level)
1746	{
1747		case DEBUG5:
1748		case DEBUG4:
1749		case DEBUG3:
1750		case DEBUG2:
1751		case DEBUG1:
1752		case LOG:
1753		case COMMERROR:
1754		case INFO:
1755		case NOTICE:
1756			eventlevel = EVENTLOG_INFORMATION_TYPE;
1757			break;
1758		case WARNING:
1759			eventlevel = EVENTLOG_WARNING_TYPE;
1760			break;
1761		case ERROR:
1762		case FATAL:
1763		case PANIC:
1764		default:
1765			eventlevel = EVENTLOG_ERROR_TYPE;
1766			break;
1767	}
1768
1769	/*
1770	 * Convert message to UTF16 text and write it with ReportEventW, but
1771	 * fall-back into ReportEventA if conversion failed.
1772	 *
1773	 * Also verify that we are not on our way into error recursion trouble due
1774	 * to error messages thrown deep inside pgwin32_toUTF16().
1775	 */
1776	if (GetDatabaseEncoding() != GetPlatformEncoding() &&
1777		!in_error_recursion_trouble())
1778	{
1779		utf16 = pgwin32_toUTF16(line, len, NULL);
1780		if (utf16)
1781		{
1782			ReportEventW(evtHandle,
1783						 eventlevel,
1784						 0,
1785						 0,		/* All events are Id 0 */
1786						 NULL,
1787						 1,
1788						 0,
1789						 (LPCWSTR *) &utf16,
1790						 NULL);
1791
1792			pfree(utf16);
1793			return;
1794		}
1795	}
1796	ReportEventA(evtHandle,
1797				 eventlevel,
1798				 0,
1799				 0,				/* All events are Id 0 */
1800				 NULL,
1801				 1,
1802				 0,
1803				 &line,
1804				 NULL);
1805}
1806#endif   /* WIN32 */
1807
1808static void
1809write_console(const char *line, int len)
1810{
1811	int			rc;
1812
1813#ifdef WIN32
1814
1815	/*
1816	 * WriteConsoleW() will fail if stdout is redirected, so just fall through
1817	 * to writing unconverted to the logfile in this case.
1818	 *
1819	 * Since we palloc the structure required for conversion, also fall
1820	 * through to writing unconverted if we have not yet set up
1821	 * CurrentMemoryContext.
1822	 */
1823	if (GetDatabaseEncoding() != GetPlatformEncoding() &&
1824		!in_error_recursion_trouble() &&
1825		!redirection_done &&
1826		CurrentMemoryContext != NULL)
1827	{
1828		WCHAR	   *utf16;
1829		int			utf16len;
1830
1831		utf16 = pgwin32_toUTF16(line, len, &utf16len);
1832		if (utf16 != NULL)
1833		{
1834			HANDLE		stdHandle;
1835			DWORD		written;
1836
1837			stdHandle = GetStdHandle(STD_ERROR_HANDLE);
1838			if (WriteConsoleW(stdHandle, utf16, utf16len, &written, NULL))
1839			{
1840				pfree(utf16);
1841				return;
1842			}
1843
1844			/*
1845			 * In case WriteConsoleW() failed, fall back to writing the
1846			 * message unconverted.
1847			 */
1848			pfree(utf16);
1849		}
1850	}
1851#else
1852
1853	/*
1854	 * Conversion on non-win32 platforms is not implemented yet. It requires
1855	 * non-throw version of pg_do_encoding_conversion(), that converts
1856	 * unconvertable characters to '?' without errors.
1857	 */
1858#endif
1859
1860	/*
1861	 * We ignore any error from write() here.  We have no useful way to report
1862	 * it ... certainly whining on stderr isn't likely to be productive.
1863	 */
1864	rc = write(fileno(stderr), line, len);
1865	(void) rc;
1866}
1867
1868/*
1869 * setup formatted_log_time, for consistent times between CSV and regular logs
1870 */
1871static void
1872setup_formatted_log_time(void)
1873{
1874	struct timeval tv;
1875	pg_time_t	stamp_time;
1876	char		msbuf[8];
1877
1878	gettimeofday(&tv, NULL);
1879	stamp_time = (pg_time_t) tv.tv_sec;
1880
1881	/*
1882	 * Note: we expect that guc.c will ensure that log_timezone is set up (at
1883	 * least with a minimal GMT value) before Log_line_prefix can become
1884	 * nonempty or CSV mode can be selected.
1885	 */
1886	pg_strftime(formatted_log_time, FORMATTED_TS_LEN,
1887	/* leave room for milliseconds... */
1888				"%Y-%m-%d %H:%M:%S     %Z",
1889				pg_localtime(&stamp_time, log_timezone));
1890
1891	/* 'paste' milliseconds into place... */
1892	sprintf(msbuf, ".%03d", (int) (tv.tv_usec / 1000));
1893	strncpy(formatted_log_time + 19, msbuf, 4);
1894}
1895
1896/*
1897 * setup formatted_start_time
1898 */
1899static void
1900setup_formatted_start_time(void)
1901{
1902	pg_time_t	stamp_time = (pg_time_t) MyStartTime;
1903
1904	/*
1905	 * Note: we expect that guc.c will ensure that log_timezone is set up (at
1906	 * least with a minimal GMT value) before Log_line_prefix can become
1907	 * nonempty or CSV mode can be selected.
1908	 */
1909	pg_strftime(formatted_start_time, FORMATTED_TS_LEN,
1910				"%Y-%m-%d %H:%M:%S %Z",
1911				pg_localtime(&stamp_time, log_timezone));
1912}
1913
1914/*
1915 * Format tag info for log lines; append to the provided buffer.
1916 */
1917static void
1918log_line_prefix(StringInfo buf, ErrorData *edata)
1919{
1920	/* static counter for line numbers */
1921	static long log_line_number = 0;
1922
1923	/* has counter been reset in current process? */
1924	static int	log_my_pid = 0;
1925
1926	int			format_len;
1927	int			i;
1928
1929	/*
1930	 * This is one of the few places where we'd rather not inherit a static
1931	 * variable's value from the postmaster.  But since we will, reset it when
1932	 * MyProcPid changes. MyStartTime also changes when MyProcPid does, so
1933	 * reset the formatted start timestamp too.
1934	 */
1935	if (log_my_pid != MyProcPid)
1936	{
1937		log_line_number = 0;
1938		log_my_pid = MyProcPid;
1939		formatted_start_time[0] = '\0';
1940	}
1941	log_line_number++;
1942
1943	if (Log_line_prefix == NULL)
1944		return;					/* in case guc hasn't run yet */
1945
1946	format_len = strlen(Log_line_prefix);
1947
1948	for (i = 0; i < format_len; i++)
1949	{
1950		if (Log_line_prefix[i] != '%')
1951		{
1952			/* literal char, just copy */
1953			appendStringInfoChar(buf, Log_line_prefix[i]);
1954			continue;
1955		}
1956		/* go to char after '%' */
1957		i++;
1958		if (i >= format_len)
1959			break;				/* format error - ignore it */
1960
1961		/* process the option */
1962		switch (Log_line_prefix[i])
1963		{
1964			case 'a':
1965				if (MyProcPort)
1966				{
1967					const char *appname = application_name;
1968
1969					if (appname == NULL || *appname == '\0')
1970						appname = _("[unknown]");
1971					appendStringInfoString(buf, appname);
1972				}
1973				break;
1974			case 'u':
1975				if (MyProcPort)
1976				{
1977					const char *username = MyProcPort->user_name;
1978
1979					if (username == NULL || *username == '\0')
1980						username = _("[unknown]");
1981					appendStringInfoString(buf, username);
1982				}
1983				break;
1984			case 'd':
1985				if (MyProcPort)
1986				{
1987					const char *dbname = MyProcPort->database_name;
1988
1989					if (dbname == NULL || *dbname == '\0')
1990						dbname = _("[unknown]");
1991					appendStringInfoString(buf, dbname);
1992				}
1993				break;
1994			case 'c':
1995				appendStringInfo(buf, "%lx.%04x", (long) (MyStartTime), MyProcPid);
1996				break;
1997			case 'p':
1998				appendStringInfo(buf, "%d", MyProcPid);
1999				break;
2000			case 'l':
2001				appendStringInfo(buf, "%ld", log_line_number);
2002				break;
2003			case 'm':
2004				setup_formatted_log_time();
2005				appendStringInfoString(buf, formatted_log_time);
2006				break;
2007			case 't':
2008				{
2009					pg_time_t	stamp_time = (pg_time_t) time(NULL);
2010					char		strfbuf[128];
2011
2012					pg_strftime(strfbuf, sizeof(strfbuf),
2013								"%Y-%m-%d %H:%M:%S %Z",
2014								pg_localtime(&stamp_time, log_timezone));
2015					appendStringInfoString(buf, strfbuf);
2016				}
2017				break;
2018			case 's':
2019				if (formatted_start_time[0] == '\0')
2020					setup_formatted_start_time();
2021				appendStringInfoString(buf, formatted_start_time);
2022				break;
2023			case 'i':
2024				if (MyProcPort)
2025				{
2026					const char *psdisp;
2027					int			displen;
2028
2029					psdisp = get_ps_display(&displen);
2030					appendBinaryStringInfo(buf, psdisp, displen);
2031				}
2032				break;
2033			case 'r':
2034				if (MyProcPort && MyProcPort->remote_host)
2035				{
2036					appendStringInfoString(buf, MyProcPort->remote_host);
2037					if (MyProcPort->remote_port &&
2038						MyProcPort->remote_port[0] != '\0')
2039						appendStringInfo(buf, "(%s)",
2040										 MyProcPort->remote_port);
2041				}
2042				break;
2043			case 'h':
2044				if (MyProcPort && MyProcPort->remote_host)
2045					appendStringInfoString(buf, MyProcPort->remote_host);
2046				break;
2047			case 'q':
2048				/* in postmaster and friends, stop if %q is seen */
2049				/* in a backend, just ignore */
2050				if (MyProcPort == NULL)
2051					i = format_len;
2052				break;
2053			case 'v':
2054				/* keep VXID format in sync with lockfuncs.c */
2055				if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
2056					appendStringInfo(buf, "%d/%u",
2057									 MyProc->backendId, MyProc->lxid);
2058				break;
2059			case 'x':
2060				appendStringInfo(buf, "%u", GetTopTransactionIdIfAny());
2061				break;
2062			case 'e':
2063				appendStringInfoString(buf, unpack_sql_state(edata->sqlerrcode));
2064				break;
2065			case '%':
2066				appendStringInfoChar(buf, '%');
2067				break;
2068			default:
2069				/* format error - ignore it */
2070				break;
2071		}
2072	}
2073}
2074
2075/*
2076 * append a CSV'd version of a string to a StringInfo
2077 * We use the PostgreSQL defaults for CSV, i.e. quote = escape = '"'
2078 * If it's NULL, append nothing.
2079 */
2080static inline void
2081appendCSVLiteral(StringInfo buf, const char *data)
2082{
2083	const char *p = data;
2084	char		c;
2085
2086	/* avoid confusing an empty string with NULL */
2087	if (p == NULL)
2088		return;
2089
2090	appendStringInfoCharMacro(buf, '"');
2091	while ((c = *p++) != '\0')
2092	{
2093		if (c == '"')
2094			appendStringInfoCharMacro(buf, '"');
2095		appendStringInfoCharMacro(buf, c);
2096	}
2097	appendStringInfoCharMacro(buf, '"');
2098}
2099
2100/*
2101 * Constructs the error message, depending on the Errordata it gets, in a CSV
2102 * format which is described in doc/src/sgml/config.sgml.
2103 */
2104static void
2105write_csvlog(ErrorData *edata)
2106{
2107	StringInfoData buf;
2108	bool		print_stmt = false;
2109
2110	/* static counter for line numbers */
2111	static long log_line_number = 0;
2112
2113	/* has counter been reset in current process? */
2114	static int	log_my_pid = 0;
2115
2116	/*
2117	 * This is one of the few places where we'd rather not inherit a static
2118	 * variable's value from the postmaster.  But since we will, reset it when
2119	 * MyProcPid changes.
2120	 */
2121	if (log_my_pid != MyProcPid)
2122	{
2123		log_line_number = 0;
2124		log_my_pid = MyProcPid;
2125		formatted_start_time[0] = '\0';
2126	}
2127	log_line_number++;
2128
2129	initStringInfo(&buf);
2130
2131	/*
2132	 * timestamp with milliseconds
2133	 *
2134	 * Check if the timestamp is already calculated for the syslog message,
2135	 * and use it if so.  Otherwise, get the current timestamp.  This is done
2136	 * to put same timestamp in both syslog and csvlog messages.
2137	 */
2138	if (formatted_log_time[0] == '\0')
2139		setup_formatted_log_time();
2140
2141	appendStringInfoString(&buf, formatted_log_time);
2142	appendStringInfoChar(&buf, ',');
2143
2144	/* username */
2145	if (MyProcPort)
2146		appendCSVLiteral(&buf, MyProcPort->user_name);
2147	appendStringInfoChar(&buf, ',');
2148
2149	/* database name */
2150	if (MyProcPort)
2151		appendCSVLiteral(&buf, MyProcPort->database_name);
2152	appendStringInfoChar(&buf, ',');
2153
2154	/* Process id  */
2155	if (MyProcPid != 0)
2156		appendStringInfo(&buf, "%d", MyProcPid);
2157	appendStringInfoChar(&buf, ',');
2158
2159	/* Remote host and port */
2160	if (MyProcPort && MyProcPort->remote_host)
2161	{
2162		appendStringInfoChar(&buf, '"');
2163		appendStringInfoString(&buf, MyProcPort->remote_host);
2164		if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
2165		{
2166			appendStringInfoChar(&buf, ':');
2167			appendStringInfoString(&buf, MyProcPort->remote_port);
2168		}
2169		appendStringInfoChar(&buf, '"');
2170	}
2171	appendStringInfoChar(&buf, ',');
2172
2173	/* session id */
2174	appendStringInfo(&buf, "%lx.%04x", (long) MyStartTime, MyProcPid);
2175	appendStringInfoChar(&buf, ',');
2176
2177	/* Line number */
2178	appendStringInfo(&buf, "%ld", log_line_number);
2179	appendStringInfoChar(&buf, ',');
2180
2181	/* PS display */
2182	if (MyProcPort)
2183	{
2184		StringInfoData msgbuf;
2185		const char *psdisp;
2186		int			displen;
2187
2188		initStringInfo(&msgbuf);
2189
2190		psdisp = get_ps_display(&displen);
2191		appendBinaryStringInfo(&msgbuf, psdisp, displen);
2192		appendCSVLiteral(&buf, msgbuf.data);
2193
2194		pfree(msgbuf.data);
2195	}
2196	appendStringInfoChar(&buf, ',');
2197
2198	/* session start timestamp */
2199	if (formatted_start_time[0] == '\0')
2200		setup_formatted_start_time();
2201	appendStringInfoString(&buf, formatted_start_time);
2202	appendStringInfoChar(&buf, ',');
2203
2204	/* Virtual transaction id */
2205	/* keep VXID format in sync with lockfuncs.c */
2206	if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
2207		appendStringInfo(&buf, "%d/%u", MyProc->backendId, MyProc->lxid);
2208	appendStringInfoChar(&buf, ',');
2209
2210	/* Transaction id */
2211	appendStringInfo(&buf, "%u", GetTopTransactionIdIfAny());
2212	appendStringInfoChar(&buf, ',');
2213
2214	/* Error severity */
2215	appendStringInfoString(&buf, error_severity(edata->elevel));
2216	appendStringInfoChar(&buf, ',');
2217
2218	/* SQL state code */
2219	appendStringInfoString(&buf, unpack_sql_state(edata->sqlerrcode));
2220	appendStringInfoChar(&buf, ',');
2221
2222	/* errmessage */
2223	appendCSVLiteral(&buf, edata->message);
2224	appendStringInfoChar(&buf, ',');
2225
2226	/* errdetail or errdetail_log */
2227	if (edata->detail_log)
2228		appendCSVLiteral(&buf, edata->detail_log);
2229	else
2230		appendCSVLiteral(&buf, edata->detail);
2231	appendStringInfoChar(&buf, ',');
2232
2233	/* errhint */
2234	appendCSVLiteral(&buf, edata->hint);
2235	appendStringInfoChar(&buf, ',');
2236
2237	/* internal query */
2238	appendCSVLiteral(&buf, edata->internalquery);
2239	appendStringInfoChar(&buf, ',');
2240
2241	/* if printed internal query, print internal pos too */
2242	if (edata->internalpos > 0 && edata->internalquery != NULL)
2243		appendStringInfo(&buf, "%d", edata->internalpos);
2244	appendStringInfoChar(&buf, ',');
2245
2246	/* errcontext */
2247	appendCSVLiteral(&buf, edata->context);
2248	appendStringInfoChar(&buf, ',');
2249
2250	/* user query --- only reported if not disabled by the caller */
2251	if (is_log_level_output(edata->elevel, log_min_error_statement) &&
2252		debug_query_string != NULL &&
2253		!edata->hide_stmt)
2254		print_stmt = true;
2255	if (print_stmt)
2256		appendCSVLiteral(&buf, debug_query_string);
2257	appendStringInfoChar(&buf, ',');
2258	if (print_stmt && edata->cursorpos > 0)
2259		appendStringInfo(&buf, "%d", edata->cursorpos);
2260	appendStringInfoChar(&buf, ',');
2261
2262	/* file error location */
2263	if (Log_error_verbosity >= PGERROR_VERBOSE)
2264	{
2265		StringInfoData msgbuf;
2266
2267		initStringInfo(&msgbuf);
2268
2269		if (edata->funcname && edata->filename)
2270			appendStringInfo(&msgbuf, "%s, %s:%d",
2271							 edata->funcname, edata->filename,
2272							 edata->lineno);
2273		else if (edata->filename)
2274			appendStringInfo(&msgbuf, "%s:%d",
2275							 edata->filename, edata->lineno);
2276		appendCSVLiteral(&buf, msgbuf.data);
2277		pfree(msgbuf.data);
2278	}
2279	appendStringInfoChar(&buf, ',');
2280
2281	/* application name */
2282	if (application_name)
2283		appendCSVLiteral(&buf, application_name);
2284
2285	appendStringInfoChar(&buf, '\n');
2286
2287	/* If in the syslogger process, try to write messages direct to file */
2288	if (am_syslogger)
2289		write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
2290	else
2291		write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
2292
2293	pfree(buf.data);
2294}
2295
2296/*
2297 * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
2298 * static buffer.
2299 */
2300char *
2301unpack_sql_state(int sql_state)
2302{
2303	static char buf[12];
2304	int			i;
2305
2306	for (i = 0; i < 5; i++)
2307	{
2308		buf[i] = PGUNSIXBIT(sql_state);
2309		sql_state >>= 6;
2310	}
2311
2312	buf[i] = '\0';
2313	return buf;
2314}
2315
2316
2317/*
2318 * Write error report to server's log
2319 */
2320static void
2321send_message_to_server_log(ErrorData *edata)
2322{
2323	StringInfoData buf;
2324
2325	initStringInfo(&buf);
2326
2327	formatted_log_time[0] = '\0';
2328
2329	log_line_prefix(&buf, edata);
2330	appendStringInfo(&buf, "%s:  ", error_severity(edata->elevel));
2331
2332	if (Log_error_verbosity >= PGERROR_VERBOSE)
2333		appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
2334
2335	if (edata->message)
2336		append_with_tabs(&buf, edata->message);
2337	else
2338		append_with_tabs(&buf, _("missing error text"));
2339
2340	if (edata->cursorpos > 0)
2341		appendStringInfo(&buf, _(" at character %d"),
2342						 edata->cursorpos);
2343	else if (edata->internalpos > 0)
2344		appendStringInfo(&buf, _(" at character %d"),
2345						 edata->internalpos);
2346
2347	appendStringInfoChar(&buf, '\n');
2348
2349	if (Log_error_verbosity >= PGERROR_DEFAULT)
2350	{
2351		if (edata->detail_log)
2352		{
2353			log_line_prefix(&buf, edata);
2354			appendStringInfoString(&buf, _("DETAIL:  "));
2355			append_with_tabs(&buf, edata->detail_log);
2356			appendStringInfoChar(&buf, '\n');
2357		}
2358		else if (edata->detail)
2359		{
2360			log_line_prefix(&buf, edata);
2361			appendStringInfoString(&buf, _("DETAIL:  "));
2362			append_with_tabs(&buf, edata->detail);
2363			appendStringInfoChar(&buf, '\n');
2364		}
2365		if (edata->hint)
2366		{
2367			log_line_prefix(&buf, edata);
2368			appendStringInfoString(&buf, _("HINT:  "));
2369			append_with_tabs(&buf, edata->hint);
2370			appendStringInfoChar(&buf, '\n');
2371		}
2372		if (edata->internalquery)
2373		{
2374			log_line_prefix(&buf, edata);
2375			appendStringInfoString(&buf, _("QUERY:  "));
2376			append_with_tabs(&buf, edata->internalquery);
2377			appendStringInfoChar(&buf, '\n');
2378		}
2379		if (edata->context)
2380		{
2381			log_line_prefix(&buf, edata);
2382			appendStringInfoString(&buf, _("CONTEXT:  "));
2383			append_with_tabs(&buf, edata->context);
2384			appendStringInfoChar(&buf, '\n');
2385		}
2386		if (Log_error_verbosity >= PGERROR_VERBOSE)
2387		{
2388			/* assume no newlines in funcname or filename... */
2389			if (edata->funcname && edata->filename)
2390			{
2391				log_line_prefix(&buf, edata);
2392				appendStringInfo(&buf, _("LOCATION:  %s, %s:%d\n"),
2393								 edata->funcname, edata->filename,
2394								 edata->lineno);
2395			}
2396			else if (edata->filename)
2397			{
2398				log_line_prefix(&buf, edata);
2399				appendStringInfo(&buf, _("LOCATION:  %s:%d\n"),
2400								 edata->filename, edata->lineno);
2401			}
2402		}
2403	}
2404
2405	/*
2406	 * If the user wants the query that generated this error logged, do it.
2407	 */
2408	if (is_log_level_output(edata->elevel, log_min_error_statement) &&
2409		debug_query_string != NULL &&
2410		!edata->hide_stmt)
2411	{
2412		log_line_prefix(&buf, edata);
2413		appendStringInfoString(&buf, _("STATEMENT:  "));
2414		append_with_tabs(&buf, debug_query_string);
2415		appendStringInfoChar(&buf, '\n');
2416	}
2417
2418#ifdef HAVE_SYSLOG
2419	/* Write to syslog, if enabled */
2420	if (Log_destination & LOG_DESTINATION_SYSLOG)
2421	{
2422		int			syslog_level;
2423
2424		switch (edata->elevel)
2425		{
2426			case DEBUG5:
2427			case DEBUG4:
2428			case DEBUG3:
2429			case DEBUG2:
2430			case DEBUG1:
2431				syslog_level = LOG_DEBUG;
2432				break;
2433			case LOG:
2434			case COMMERROR:
2435			case INFO:
2436				syslog_level = LOG_INFO;
2437				break;
2438			case NOTICE:
2439			case WARNING:
2440				syslog_level = LOG_NOTICE;
2441				break;
2442			case ERROR:
2443				syslog_level = LOG_WARNING;
2444				break;
2445			case FATAL:
2446				syslog_level = LOG_ERR;
2447				break;
2448			case PANIC:
2449			default:
2450				syslog_level = LOG_CRIT;
2451				break;
2452		}
2453
2454		write_syslog(syslog_level, buf.data);
2455	}
2456#endif   /* HAVE_SYSLOG */
2457
2458#ifdef WIN32
2459	/* Write to eventlog, if enabled */
2460	if (Log_destination & LOG_DESTINATION_EVENTLOG)
2461	{
2462		write_eventlog(edata->elevel, buf.data, buf.len);
2463	}
2464#endif   /* WIN32 */
2465
2466	/* Write to stderr, if enabled */
2467	if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == DestDebug)
2468	{
2469		/*
2470		 * Use the chunking protocol if we know the syslogger should be
2471		 * catching stderr output, and we are not ourselves the syslogger.
2472		 * Otherwise, just do a vanilla write to stderr.
2473		 */
2474		if (redirection_done && !am_syslogger)
2475			write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_STDERR);
2476#ifdef WIN32
2477
2478		/*
2479		 * In a win32 service environment, there is no usable stderr. Capture
2480		 * anything going there and write it to the eventlog instead.
2481		 *
2482		 * If stderr redirection is active, it was OK to write to stderr above
2483		 * because that's really a pipe to the syslogger process.
2484		 */
2485		else if (pgwin32_is_service())
2486			write_eventlog(edata->elevel, buf.data, buf.len);
2487#endif
2488		else
2489			write_console(buf.data, buf.len);
2490	}
2491
2492	/* If in the syslogger process, try to write messages direct to file */
2493	if (am_syslogger)
2494		write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_STDERR);
2495
2496	/* Write to CSV log if enabled */
2497	if (Log_destination & LOG_DESTINATION_CSVLOG)
2498	{
2499		if (redirection_done || am_syslogger)
2500		{
2501			/*
2502			 * send CSV data if it's safe to do so (syslogger doesn't need the
2503			 * pipe). First get back the space in the message buffer.
2504			 */
2505			pfree(buf.data);
2506			write_csvlog(edata);
2507		}
2508		else
2509		{
2510			/*
2511			 * syslogger not up (yet), so just dump the message to stderr,
2512			 * unless we already did so above.
2513			 */
2514			if (!(Log_destination & LOG_DESTINATION_STDERR) &&
2515				whereToSendOutput != DestDebug)
2516				write_console(buf.data, buf.len);
2517			pfree(buf.data);
2518		}
2519	}
2520	else
2521	{
2522		pfree(buf.data);
2523	}
2524}
2525
2526/*
2527 * Send data to the syslogger using the chunked protocol
2528 *
2529 * Note: when there are multiple backends writing into the syslogger pipe,
2530 * it's critical that each write go into the pipe indivisibly, and not
2531 * get interleaved with data from other processes.	Fortunately, the POSIX
2532 * spec requires that writes to pipes be atomic so long as they are not
2533 * more than PIPE_BUF bytes long.  So we divide long messages into chunks
2534 * that are no more than that length, and send one chunk per write() call.
2535 * The collector process knows how to reassemble the chunks.
2536 *
2537 * Because of the atomic write requirement, there are only two possible
2538 * results from write() here: -1 for failure, or the requested number of
2539 * bytes.  There is not really anything we can do about a failure; retry would
2540 * probably be an infinite loop, and we can't even report the error usefully.
2541 * (There is noplace else we could send it!)  So we might as well just ignore
2542 * the result from write().  However, on some platforms you get a compiler
2543 * warning from ignoring write()'s result, so do a little dance with casting
2544 * rc to void to shut up the compiler.
2545 */
2546static void
2547write_pipe_chunks(char *data, int len, int dest)
2548{
2549	PipeProtoChunk p;
2550	int			fd = fileno(stderr);
2551	int			rc;
2552
2553	Assert(len > 0);
2554
2555	p.proto.nuls[0] = p.proto.nuls[1] = '\0';
2556	p.proto.pid = MyProcPid;
2557
2558	/* write all but the last chunk */
2559	while (len > PIPE_MAX_PAYLOAD)
2560	{
2561		p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'F' : 'f');
2562		p.proto.len = PIPE_MAX_PAYLOAD;
2563		memcpy(p.proto.data, data, PIPE_MAX_PAYLOAD);
2564		rc = write(fd, &p, PIPE_HEADER_SIZE + PIPE_MAX_PAYLOAD);
2565		(void) rc;
2566		data += PIPE_MAX_PAYLOAD;
2567		len -= PIPE_MAX_PAYLOAD;
2568	}
2569
2570	/* write the last chunk */
2571	p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'T' : 't');
2572	p.proto.len = len;
2573	memcpy(p.proto.data, data, len);
2574	rc = write(fd, &p, PIPE_HEADER_SIZE + len);
2575	(void) rc;
2576}
2577
2578
2579/*
2580 * Append a text string to the error report being built for the client.
2581 *
2582 * This is ordinarily identical to pq_sendstring(), but if we are in
2583 * error recursion trouble we skip encoding conversion, because of the
2584 * possibility that the problem is a failure in the encoding conversion
2585 * subsystem itself.  Code elsewhere should ensure that the passed-in
2586 * strings will be plain 7-bit ASCII, and thus not in need of conversion,
2587 * in such cases.  (In particular, we disable localization of error messages
2588 * to help ensure that's true.)
2589 */
2590static void
2591err_sendstring(StringInfo buf, const char *str)
2592{
2593	if (in_error_recursion_trouble())
2594		pq_send_ascii_string(buf, str);
2595	else
2596		pq_sendstring(buf, str);
2597}
2598
2599/*
2600 * Write error report to client
2601 */
2602static void
2603send_message_to_frontend(ErrorData *edata)
2604{
2605	StringInfoData msgbuf;
2606
2607	/* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
2608	pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
2609
2610	if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
2611	{
2612		/* New style with separate fields */
2613		char		tbuf[12];
2614		int			ssval;
2615		int			i;
2616
2617		pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
2618		err_sendstring(&msgbuf, error_severity(edata->elevel));
2619
2620		/* unpack MAKE_SQLSTATE code */
2621		ssval = edata->sqlerrcode;
2622		for (i = 0; i < 5; i++)
2623		{
2624			tbuf[i] = PGUNSIXBIT(ssval);
2625			ssval >>= 6;
2626		}
2627		tbuf[i] = '\0';
2628
2629		pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
2630		err_sendstring(&msgbuf, tbuf);
2631
2632		/* M field is required per protocol, so always send something */
2633		pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
2634		if (edata->message)
2635			err_sendstring(&msgbuf, edata->message);
2636		else
2637			err_sendstring(&msgbuf, _("missing error text"));
2638
2639		if (edata->detail)
2640		{
2641			pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
2642			err_sendstring(&msgbuf, edata->detail);
2643		}
2644
2645		/* detail_log is intentionally not used here */
2646
2647		if (edata->hint)
2648		{
2649			pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
2650			err_sendstring(&msgbuf, edata->hint);
2651		}
2652
2653		if (edata->context)
2654		{
2655			pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
2656			err_sendstring(&msgbuf, edata->context);
2657		}
2658
2659		if (edata->cursorpos > 0)
2660		{
2661			snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
2662			pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
2663			err_sendstring(&msgbuf, tbuf);
2664		}
2665
2666		if (edata->internalpos > 0)
2667		{
2668			snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
2669			pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
2670			err_sendstring(&msgbuf, tbuf);
2671		}
2672
2673		if (edata->internalquery)
2674		{
2675			pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
2676			err_sendstring(&msgbuf, edata->internalquery);
2677		}
2678
2679		if (edata->filename)
2680		{
2681			pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
2682			err_sendstring(&msgbuf, edata->filename);
2683		}
2684
2685		if (edata->lineno > 0)
2686		{
2687			snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
2688			pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
2689			err_sendstring(&msgbuf, tbuf);
2690		}
2691
2692		if (edata->funcname)
2693		{
2694			pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
2695			err_sendstring(&msgbuf, edata->funcname);
2696		}
2697
2698		pq_sendbyte(&msgbuf, '\0');		/* terminator */
2699	}
2700	else
2701	{
2702		/* Old style --- gin up a backwards-compatible message */
2703		StringInfoData buf;
2704
2705		initStringInfo(&buf);
2706
2707		appendStringInfo(&buf, "%s:  ", error_severity(edata->elevel));
2708
2709		if (edata->show_funcname && edata->funcname)
2710			appendStringInfo(&buf, "%s: ", edata->funcname);
2711
2712		if (edata->message)
2713			appendStringInfoString(&buf, edata->message);
2714		else
2715			appendStringInfoString(&buf, _("missing error text"));
2716
2717		if (edata->cursorpos > 0)
2718			appendStringInfo(&buf, _(" at character %d"),
2719							 edata->cursorpos);
2720		else if (edata->internalpos > 0)
2721			appendStringInfo(&buf, _(" at character %d"),
2722							 edata->internalpos);
2723
2724		appendStringInfoChar(&buf, '\n');
2725
2726		err_sendstring(&msgbuf, buf.data);
2727
2728		pfree(buf.data);
2729	}
2730
2731	pq_endmessage(&msgbuf);
2732
2733	/*
2734	 * This flush is normally not necessary, since postgres.c will flush out
2735	 * waiting data when control returns to the main loop. But it seems best
2736	 * to leave it here, so that the client has some clue what happened if the
2737	 * backend dies before getting back to the main loop ... error/notice
2738	 * messages should not be a performance-critical path anyway, so an extra
2739	 * flush won't hurt much ...
2740	 */
2741	pq_flush();
2742}
2743
2744
2745/*
2746 * Support routines for formatting error messages.
2747 */
2748
2749
2750/*
2751 * expand_fmt_string --- process special format codes in a format string
2752 *
2753 * We must replace %m with the appropriate strerror string, since vsnprintf
2754 * won't know what to do with it.
2755 *
2756 * The result is a palloc'd string.
2757 */
2758static char *
2759expand_fmt_string(const char *fmt, ErrorData *edata)
2760{
2761	StringInfoData buf;
2762	const char *cp;
2763
2764	initStringInfo(&buf);
2765
2766	for (cp = fmt; *cp; cp++)
2767	{
2768		if (cp[0] == '%' && cp[1] != '\0')
2769		{
2770			cp++;
2771			if (*cp == 'm')
2772			{
2773				/*
2774				 * Replace %m by system error string.  If there are any %'s in
2775				 * the string, we'd better double them so that vsnprintf won't
2776				 * misinterpret.
2777				 */
2778				const char *cp2;
2779
2780				cp2 = useful_strerror(edata->saved_errno);
2781				for (; *cp2; cp2++)
2782				{
2783					if (*cp2 == '%')
2784						appendStringInfoCharMacro(&buf, '%');
2785					appendStringInfoCharMacro(&buf, *cp2);
2786				}
2787			}
2788			else
2789			{
2790				/* copy % and next char --- this avoids trouble with %%m */
2791				appendStringInfoCharMacro(&buf, '%');
2792				appendStringInfoCharMacro(&buf, *cp);
2793			}
2794		}
2795		else
2796			appendStringInfoCharMacro(&buf, *cp);
2797	}
2798
2799	return buf.data;
2800}
2801
2802
2803/*
2804 * A slightly cleaned-up version of strerror()
2805 */
2806static const char *
2807useful_strerror(int errnum)
2808{
2809	/* this buffer is only used if errno has a bogus value */
2810	static char errorstr_buf[48];
2811	const char *str;
2812
2813#ifdef WIN32
2814	/* Winsock error code range, per WinError.h */
2815	if (errnum >= 10000 && errnum <= 11999)
2816		return pgwin32_socket_strerror(errnum);
2817#endif
2818	str = strerror(errnum);
2819
2820	/*
2821	 * Some strerror()s return an empty string for out-of-range errno. This is
2822	 * ANSI C spec compliant, but not exactly useful.
2823	 */
2824	if (str == NULL || *str == '\0')
2825	{
2826		snprintf(errorstr_buf, sizeof(errorstr_buf),
2827		/*------
2828		  translator: This string will be truncated at 47
2829		  characters expanded. */
2830				 _("operating system error %d"), errnum);
2831		str = errorstr_buf;
2832	}
2833
2834	return str;
2835}
2836
2837
2838/*
2839 * error_severity --- get localized string representing elevel
2840 */
2841static const char *
2842error_severity(int elevel)
2843{
2844	const char *prefix;
2845
2846	switch (elevel)
2847	{
2848		case DEBUG1:
2849		case DEBUG2:
2850		case DEBUG3:
2851		case DEBUG4:
2852		case DEBUG5:
2853			prefix = _("DEBUG");
2854			break;
2855		case LOG:
2856		case COMMERROR:
2857			prefix = _("LOG");
2858			break;
2859		case INFO:
2860			prefix = _("INFO");
2861			break;
2862		case NOTICE:
2863			prefix = _("NOTICE");
2864			break;
2865		case WARNING:
2866			prefix = _("WARNING");
2867			break;
2868		case ERROR:
2869			prefix = _("ERROR");
2870			break;
2871		case FATAL:
2872			prefix = _("FATAL");
2873			break;
2874		case PANIC:
2875			prefix = _("PANIC");
2876			break;
2877		default:
2878			prefix = "???";
2879			break;
2880	}
2881
2882	return prefix;
2883}
2884
2885
2886/*
2887 *	append_with_tabs
2888 *
2889 *	Append the string to the StringInfo buffer, inserting a tab after any
2890 *	newline.
2891 */
2892static void
2893append_with_tabs(StringInfo buf, const char *str)
2894{
2895	char		ch;
2896
2897	while ((ch = *str++) != '\0')
2898	{
2899		appendStringInfoCharMacro(buf, ch);
2900		if (ch == '\n')
2901			appendStringInfoCharMacro(buf, '\t');
2902	}
2903}
2904
2905
2906/*
2907 * Write errors to stderr (or by equal means when stderr is
2908 * not available). Used before ereport/elog can be used
2909 * safely (memory context, GUC load etc)
2910 */
2911void
2912write_stderr(const char *fmt,...)
2913{
2914	va_list		ap;
2915
2916#ifdef WIN32
2917	char		errbuf[2048];	/* Arbitrary size? */
2918#endif
2919
2920	fmt = _(fmt);
2921
2922	va_start(ap, fmt);
2923#ifndef WIN32
2924	/* On Unix, we just fprintf to stderr */
2925	vfprintf(stderr, fmt, ap);
2926	fflush(stderr);
2927#else
2928	vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
2929
2930	/*
2931	 * On Win32, we print to stderr if running on a console, or write to
2932	 * eventlog if running as a service
2933	 */
2934	if (pgwin32_is_service())	/* Running as a service */
2935	{
2936		write_eventlog(ERROR, errbuf, strlen(errbuf));
2937	}
2938	else
2939	{
2940		/* Not running as service, write to stderr */
2941		write_console(errbuf, strlen(errbuf));
2942		fflush(stderr);
2943	}
2944#endif
2945	va_end(ap);
2946}
2947
2948
2949/*
2950 * is_log_level_output -- is elevel logically >= log_min_level?
2951 *
2952 * We use this for tests that should consider LOG to sort out-of-order,
2953 * between ERROR and FATAL.  Generally this is the right thing for testing
2954 * whether a message should go to the postmaster log, whereas a simple >=
2955 * test is correct for testing whether the message should go to the client.
2956 */
2957static bool
2958is_log_level_output(int elevel, int log_min_level)
2959{
2960	if (elevel == LOG || elevel == COMMERROR)
2961	{
2962		if (log_min_level == LOG || log_min_level <= ERROR)
2963			return true;
2964	}
2965	else if (log_min_level == LOG)
2966	{
2967		/* elevel != LOG */
2968		if (elevel >= FATAL)
2969			return true;
2970	}
2971	/* Neither is LOG */
2972	else if (elevel >= log_min_level)
2973		return true;
2974
2975	return false;
2976}
2977
2978/*
2979 * Adjust the level of a recovery-related message per trace_recovery_messages.
2980 *
2981 * The argument is the default log level of the message, eg, DEBUG2.  (This
2982 * should only be applied to DEBUGn log messages, otherwise it's a no-op.)
2983 * If the level is >= trace_recovery_messages, we return LOG, causing the
2984 * message to be logged unconditionally (for most settings of
2985 * log_min_messages).  Otherwise, we return the argument unchanged.
2986 * The message will then be shown based on the setting of log_min_messages.
2987 *
2988 * Intention is to keep this for at least the whole of the 9.0 production
2989 * release, so we can more easily diagnose production problems in the field.
2990 * It should go away eventually, though, because it's an ugly and
2991 * hard-to-explain kluge.
2992 */
2993int
2994trace_recovery(int trace_level)
2995{
2996	if (trace_level < LOG &&
2997		trace_level >= trace_recovery_messages)
2998		return LOG;
2999
3000	return trace_level;
3001}