PageRenderTime 94ms CodeModel.GetById 4ms app.highlight 75ms RepoModel.GetById 1ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full 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 i…

Large files files are truncated, but you can click here to view the full file