PageRenderTime 4ms CodeModel.GetById 4ms app.highlight 43ms RepoModel.GetById 1ms app.codeStats 1ms

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

https://bitbucket.org/definex/4707
C | 2979 lines | 1696 code | 397 blank | 886 comment | 317 complexity | b7ef106a34096bc391138ad9b511de79 MD5 | raw file

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-2012, PostgreSQL Global Development Group
  47 * Portions Copyright (c) 1994, Regents of the University of California
  48 *
  49 *
  50 * IDENTIFICATION
  51 *	  src/backend/utils/error/elog.c
  52 *
  53 *-------------------------------------------------------------------------
  54 */
  55#include "postgres.h"
  56
  57#include <fcntl.h>
  58#include <time.h>
  59#include <unistd.h>
  60#include <signal.h>
  61#include <ctype.h>
  62#ifdef HAVE_SYSLOG
  63#include <syslog.h>
  64#endif
  65
  66#include "access/transam.h"
  67#include "access/xact.h"
  68#include "libpq/libpq.h"
  69#include "libpq/pqformat.h"
  70#include "mb/pg_wchar.h"
  71#include "miscadmin.h"
  72#include "postmaster/postmaster.h"
  73#include "postmaster/syslogger.h"
  74#include "storage/ipc.h"
  75#include "storage/proc.h"
  76#include "tcop/tcopprot.h"
  77#include "utils/guc.h"
  78#include "utils/memutils.h"
  79#include "utils/ps_status.h"
  80
  81
  82#undef _
  83#define _(x) err_gettext(x)
  84
  85static const char *
  86err_gettext(const char *str)
  87/* This extension allows gcc to check the format string for consistency with
  88   the supplied arguments. */
  89__attribute__((format_arg(1)));
  90
  91/* Global variables */
  92ErrorContextCallback *error_context_stack = NULL;
  93
  94sigjmp_buf *PG_exception_stack = NULL;
  95
  96extern bool redirection_done;
  97
  98/*
  99 * Hook for intercepting messages before they are sent to the server log.
 100 * Note that the hook will not get called for messages that are suppressed
 101 * by log_min_messages.  Also note that logging hooks implemented in preload
 102 * libraries will miss any log messages that are generated before the
 103 * library is loaded.
 104 */
 105emit_log_hook_type emit_log_hook = NULL;
 106
 107/* GUC parameters */
 108int			Log_error_verbosity = PGERROR_VERBOSE;
 109char	   *Log_line_prefix = NULL;		/* format for extra log line info */
 110int			Log_destination = LOG_DESTINATION_STDERR;
 111
 112#ifdef HAVE_SYSLOG
 113
 114/*
 115 * Max string length to send to syslog().  Note that this doesn't count the
 116 * sequence-number prefix we add, and of course it doesn't count the prefix
 117 * added by syslog itself.	Solaris and sysklogd truncate the final message
 118 * at 1024 bytes, so this value leaves 124 bytes for those prefixes.  (Most
 119 * other syslog implementations seem to have limits of 2KB or so.)
 120 */
 121#ifndef PG_SYSLOG_LIMIT
 122#define PG_SYSLOG_LIMIT 900
 123#endif
 124
 125static bool openlog_done = false;
 126static char *syslog_ident = NULL;
 127static int	syslog_facility = LOG_LOCAL0;
 128
 129static void write_syslog(int level, const char *line);
 130#endif
 131
 132static void write_console(const char *line, int len);
 133
 134#ifdef WIN32
 135extern char *event_source;
 136static void write_eventlog(int level, const char *line, int len);
 137#endif
 138
 139/* We provide a small stack of ErrorData records for re-entrant cases */
 140#define ERRORDATA_STACK_SIZE  5
 141
 142static ErrorData errordata[ERRORDATA_STACK_SIZE];
 143
 144static int	errordata_stack_depth = -1; /* index of topmost active frame */
 145
 146static int	recursion_depth = 0;	/* to detect actual recursion */
 147
 148/* buffers for formatted timestamps that might be used by both
 149 * log_line_prefix and csv logs.
 150 */
 151
 152#define FORMATTED_TS_LEN 128
 153static char formatted_start_time[FORMATTED_TS_LEN];
 154static char formatted_log_time[FORMATTED_TS_LEN];
 155
 156
 157/* Macro for checking errordata_stack_depth is reasonable */
 158#define CHECK_STACK_DEPTH() \
 159	do { \
 160		if (errordata_stack_depth < 0) \
 161		{ \
 162			errordata_stack_depth = -1; \
 163			ereport(ERROR, (errmsg_internal("errstart was not called"))); \
 164		} \
 165	} while (0)
 166
 167
 168static void log_line_prefix(StringInfo buf, ErrorData *edata);
 169static void send_message_to_server_log(ErrorData *edata);
 170static void send_message_to_frontend(ErrorData *edata);
 171static char *expand_fmt_string(const char *fmt, ErrorData *edata);
 172static const char *useful_strerror(int errnum);
 173static const char *error_severity(int elevel);
 174static void append_with_tabs(StringInfo buf, const char *str);
 175static bool is_log_level_output(int elevel, int log_min_level);
 176static void write_pipe_chunks(char *data, int len, int dest);
 177static void write_csvlog(ErrorData *edata);
 178static void setup_formatted_log_time(void);
 179static void setup_formatted_start_time(void);
 180
 181
 182/*
 183 * in_error_recursion_trouble --- are we at risk of infinite error recursion?
 184 *
 185 * This function exists to provide common control of various fallback steps
 186 * that we take if we think we are facing infinite error recursion.  See the
 187 * callers for details.
 188 */
 189bool
 190in_error_recursion_trouble(void)
 191{
 192	/* Pull the plug if recurse more than once */
 193	return (recursion_depth > 2);
 194}
 195
 196/*
 197 * One of those fallback steps is to stop trying to localize the error
 198 * message, since there's a significant probability that that's exactly
 199 * what's causing the recursion.
 200 */
 201static inline const char *
 202err_gettext(const char *str)
 203{
 204#ifdef ENABLE_NLS
 205	if (in_error_recursion_trouble())
 206		return str;
 207	else
 208		return gettext(str);
 209#else
 210	return str;
 211#endif
 212}
 213
 214
 215/*
 216 * errstart --- begin an error-reporting cycle
 217 *
 218 * Create a stack entry and store the given parameters in it.  Subsequently,
 219 * errmsg() and perhaps other routines will be called to further populate
 220 * the stack entry.  Finally, errfinish() will be called to actually process
 221 * the error report.
 222 *
 223 * Returns TRUE in normal case.  Returns FALSE to short-circuit the error
 224 * report (if it's a warning or lower and not to be reported anywhere).
 225 */
 226bool
 227errstart(int elevel, const char *filename, int lineno,
 228		 const char *funcname, const char *domain)
 229{
 230	ErrorData  *edata;
 231	bool		output_to_server;
 232	bool		output_to_client = false;
 233	int			i;
 234
 235	/*
 236	 * Check some cases in which we want to promote an error into a more
 237	 * severe error.  None of this logic applies for non-error messages.
 238	 */
 239	if (elevel >= ERROR)
 240	{
 241		/*
 242		 * If we are inside a critical section, all errors become PANIC
 243		 * errors.	See miscadmin.h.
 244		 */
 245		if (CritSectionCount > 0)
 246			elevel = PANIC;
 247
 248		/*
 249		 * Check reasons for treating ERROR as FATAL:
 250		 *
 251		 * 1. we have no handler to pass the error to (implies we are in the
 252		 * postmaster or in backend startup).
 253		 *
 254		 * 2. ExitOnAnyError mode switch is set (initdb uses this).
 255		 *
 256		 * 3. the error occurred after proc_exit has begun to run.	(It's
 257		 * proc_exit's responsibility to see that this doesn't turn into
 258		 * infinite recursion!)
 259		 */
 260		if (elevel == ERROR)
 261		{
 262			if (PG_exception_stack == NULL ||
 263				ExitOnAnyError ||
 264				proc_exit_inprogress)
 265				elevel = FATAL;
 266		}
 267
 268		/*
 269		 * If the error level is ERROR or more, errfinish is not going to
 270		 * return to caller; therefore, if there is any stacked error already
 271		 * in progress it will be lost.  This is more or less okay, except we
 272		 * do not want to have a FATAL or PANIC error downgraded because the
 273		 * reporting process was interrupted by a lower-grade error.  So check
 274		 * the stack and make sure we panic if panic is warranted.
 275		 */
 276		for (i = 0; i <= errordata_stack_depth; i++)
 277			elevel = Max(elevel, errordata[i].elevel);
 278	}
 279
 280	/*
 281	 * Now decide whether we need to process this report at all; if it's
 282	 * warning or less and not enabled for logging, just return FALSE without
 283	 * starting up any error logging machinery.
 284	 */
 285
 286	/* Determine whether message is enabled for server log output */
 287	if (IsPostmasterEnvironment)
 288		output_to_server = is_log_level_output(elevel, log_min_messages);
 289	else
 290		/* In bootstrap/standalone case, do not sort LOG out-of-order */
 291		output_to_server = (elevel >= log_min_messages);
 292
 293	/* Determine whether message is enabled for client output */
 294	if (whereToSendOutput == DestRemote && elevel != COMMERROR)
 295	{
 296		/*
 297		 * client_min_messages is honored only after we complete the
 298		 * authentication handshake.  This is required both for security
 299		 * reasons and because many clients can't handle NOTICE messages
 300		 * during authentication.
 301		 */
 302		if (ClientAuthInProgress)
 303			output_to_client = (elevel >= ERROR);
 304		else
 305			output_to_client = (elevel >= client_min_messages ||
 306								elevel == INFO);
 307	}
 308
 309	/* Skip processing effort if non-error message will not be output */
 310	if (elevel < ERROR && !output_to_server && !output_to_client)
 311		return false;
 312
 313	/*
 314	 * Okay, crank up a stack entry to store the info in.
 315	 */
 316
 317	if (recursion_depth++ > 0 && elevel >= ERROR)
 318	{
 319		/*
 320		 * Ooops, error during error processing.  Clear ErrorContext as
 321		 * discussed at top of file.  We will not return to the original
 322		 * error's reporter or handler, so we don't need it.
 323		 */
 324		MemoryContextReset(ErrorContext);
 325
 326		/*
 327		 * Infinite error recursion might be due to something broken in a
 328		 * context traceback routine.  Abandon them too.  We also abandon
 329		 * attempting to print the error statement (which, if long, could
 330		 * itself be the source of the recursive failure).
 331		 */
 332		if (in_error_recursion_trouble())
 333		{
 334			error_context_stack = NULL;
 335			debug_query_string = NULL;
 336		}
 337	}
 338	if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
 339	{
 340		/*
 341		 * Wups, stack not big enough.	We treat this as a PANIC condition
 342		 * because it suggests an infinite loop of errors during error
 343		 * recovery.
 344		 */
 345		errordata_stack_depth = -1;		/* make room on stack */
 346		ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
 347	}
 348
 349	/* Initialize data for this error frame */
 350	edata = &errordata[errordata_stack_depth];
 351	MemSet(edata, 0, sizeof(ErrorData));
 352	edata->elevel = elevel;
 353	edata->output_to_server = output_to_server;
 354	edata->output_to_client = output_to_client;
 355	if (filename)
 356	{
 357		const char *slash;
 358
 359		/* keep only base name, useful especially for vpath builds */
 360		slash = strrchr(filename, '/');
 361		if (slash)
 362			filename = slash + 1;
 363	}
 364	edata->filename = filename;
 365	edata->lineno = lineno;
 366	edata->funcname = funcname;
 367	/* the default text domain is the backend's */
 368	edata->domain = domain ? domain : PG_TEXTDOMAIN("postgres");
 369	/* Select default errcode based on elevel */
 370	if (elevel >= ERROR)
 371		edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
 372	else if (elevel == WARNING)
 373		edata->sqlerrcode = ERRCODE_WARNING;
 374	else
 375		edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
 376	/* errno is saved here so that error parameter eval can't change it */
 377	edata->saved_errno = errno;
 378
 379	recursion_depth--;
 380	return true;
 381}
 382
 383/*
 384 * errfinish --- end an error-reporting cycle
 385 *
 386 * Produce the appropriate error report(s) and pop the error stack.
 387 *
 388 * If elevel is ERROR or worse, control does not return to the caller.
 389 * See elog.h for the error level definitions.
 390 */
 391void
 392errfinish(int dummy,...)
 393{
 394	ErrorData  *edata = &errordata[errordata_stack_depth];
 395	int			elevel = edata->elevel;
 396	MemoryContext oldcontext;
 397	ErrorContextCallback *econtext;
 398
 399	recursion_depth++;
 400	CHECK_STACK_DEPTH();
 401
 402	/*
 403	 * Do processing in ErrorContext, which we hope has enough reserved space
 404	 * to report an error.
 405	 */
 406	oldcontext = MemoryContextSwitchTo(ErrorContext);
 407
 408	/*
 409	 * Call any context callback functions.  Errors occurring in callback
 410	 * functions will be treated as recursive errors --- this ensures we will
 411	 * avoid infinite recursion (see errstart).
 412	 */
 413	for (econtext = error_context_stack;
 414		 econtext != NULL;
 415		 econtext = econtext->previous)
 416		(*econtext->callback) (econtext->arg);
 417
 418	/*
 419	 * If ERROR (not more nor less) we pass it off to the current handler.
 420	 * Printing it and popping the stack is the responsibility of the handler.
 421	 */
 422	if (elevel == ERROR)
 423	{
 424		/*
 425		 * We do some minimal cleanup before longjmp'ing so that handlers can
 426		 * execute in a reasonably sane state.
 427		 */
 428
 429		/* This is just in case the error came while waiting for input */
 430		ImmediateInterruptOK = false;
 431
 432		/*
 433		 * Reset InterruptHoldoffCount in case we ereport'd from inside an
 434		 * interrupt holdoff section.  (We assume here that no handler will
 435		 * itself be inside a holdoff section.	If necessary, such a handler
 436		 * could save and restore InterruptHoldoffCount for itself, but this
 437		 * should make life easier for most.)
 438		 */
 439		InterruptHoldoffCount = 0;
 440
 441		CritSectionCount = 0;	/* should be unnecessary, but... */
 442
 443		/*
 444		 * Note that we leave CurrentMemoryContext set to ErrorContext. The
 445		 * handler should reset it to something else soon.
 446		 */
 447
 448		recursion_depth--;
 449		PG_RE_THROW();
 450	}
 451
 452	/*
 453	 * If we are doing FATAL or PANIC, abort any old-style COPY OUT in
 454	 * progress, so that we can report the message before dying.  (Without
 455	 * this, pq_putmessage will refuse to send the message at all, which is
 456	 * what we want for NOTICE messages, but not for fatal exits.) This hack
 457	 * is necessary because of poor design of old-style copy protocol.	Note
 458	 * we must do this even if client is fool enough to have set
 459	 * client_min_messages above FATAL, so don't look at output_to_client.
 460	 */
 461	if (elevel >= FATAL && whereToSendOutput == DestRemote)
 462		pq_endcopyout(true);
 463
 464	/* Emit the message to the right places */
 465	EmitErrorReport();
 466
 467	/* Now free up subsidiary data attached to stack entry, and release it */
 468	if (edata->message)
 469		pfree(edata->message);
 470	if (edata->detail)
 471		pfree(edata->detail);
 472	if (edata->detail_log)
 473		pfree(edata->detail_log);
 474	if (edata->hint)
 475		pfree(edata->hint);
 476	if (edata->context)
 477		pfree(edata->context);
 478	if (edata->internalquery)
 479		pfree(edata->internalquery);
 480
 481	errordata_stack_depth--;
 482
 483	/* Exit error-handling context */
 484	MemoryContextSwitchTo(oldcontext);
 485	recursion_depth--;
 486
 487	/*
 488	 * Perform error recovery action as specified by elevel.
 489	 */
 490	if (elevel == FATAL)
 491	{
 492		/*
 493		 * For a FATAL error, we let proc_exit clean up and exit.
 494		 */
 495		ImmediateInterruptOK = false;
 496
 497		/*
 498		 * If we just reported a startup failure, the client will disconnect
 499		 * on receiving it, so don't send any more to the client.
 500		 */
 501		if (PG_exception_stack == NULL && whereToSendOutput == DestRemote)
 502			whereToSendOutput = DestNone;
 503
 504		/*
 505		 * fflush here is just to improve the odds that we get to see the
 506		 * error message, in case things are so hosed that proc_exit crashes.
 507		 * Any other code you might be tempted to add here should probably be
 508		 * in an on_proc_exit or on_shmem_exit callback instead.
 509		 */
 510		fflush(stdout);
 511		fflush(stderr);
 512
 513		/*
 514		 * Do normal process-exit cleanup, then return exit code 1 to indicate
 515		 * FATAL termination.  The postmaster may or may not consider this
 516		 * worthy of panic, depending on which subprocess returns it.
 517		 */
 518		proc_exit(1);
 519	}
 520
 521	if (elevel >= PANIC)
 522	{
 523		/*
 524		 * Serious crash time. Postmaster will observe SIGABRT process exit
 525		 * status and kill the other backends too.
 526		 *
 527		 * XXX: what if we are *in* the postmaster?  abort() won't kill our
 528		 * children...
 529		 */
 530		ImmediateInterruptOK = false;
 531		fflush(stdout);
 532		fflush(stderr);
 533		abort();
 534	}
 535
 536	/*
 537	 * We reach here if elevel <= WARNING. OK to return to caller.
 538	 *
 539	 * But check for cancel/die interrupt first --- this is so that the user
 540	 * can stop a query emitting tons of notice or warning messages, even if
 541	 * it's in a loop that otherwise fails to check for interrupts.
 542	 */
 543	CHECK_FOR_INTERRUPTS();
 544}
 545
 546
 547/*
 548 * errcode --- add SQLSTATE error code to the current error
 549 *
 550 * The code is expected to be represented as per MAKE_SQLSTATE().
 551 */
 552int
 553errcode(int sqlerrcode)
 554{
 555	ErrorData  *edata = &errordata[errordata_stack_depth];
 556
 557	/* we don't bother incrementing recursion_depth */
 558	CHECK_STACK_DEPTH();
 559
 560	edata->sqlerrcode = sqlerrcode;
 561
 562	return 0;					/* return value does not matter */
 563}
 564
 565
 566/*
 567 * errcode_for_file_access --- add SQLSTATE error code to the current error
 568 *
 569 * The SQLSTATE code is chosen based on the saved errno value.	We assume
 570 * that the failing operation was some type of disk file access.
 571 *
 572 * NOTE: the primary error message string should generally include %m
 573 * when this is used.
 574 */
 575int
 576errcode_for_file_access(void)
 577{
 578	ErrorData  *edata = &errordata[errordata_stack_depth];
 579
 580	/* we don't bother incrementing recursion_depth */
 581	CHECK_STACK_DEPTH();
 582
 583	switch (edata->saved_errno)
 584	{
 585			/* Permission-denied failures */
 586		case EPERM:				/* Not super-user */
 587		case EACCES:			/* Permission denied */
 588#ifdef EROFS
 589		case EROFS:				/* Read only file system */
 590#endif
 591			edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
 592			break;
 593
 594			/* File not found */
 595		case ENOENT:			/* No such file or directory */
 596			edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
 597			break;
 598
 599			/* Duplicate file */
 600		case EEXIST:			/* File exists */
 601			edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
 602			break;
 603
 604			/* Wrong object type or state */
 605		case ENOTDIR:			/* Not a directory */
 606		case EISDIR:			/* Is a directory */
 607#if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
 608		case ENOTEMPTY: /* Directory not empty */
 609#endif
 610			edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
 611			break;
 612
 613			/* Insufficient resources */
 614		case ENOSPC:			/* No space left on device */
 615			edata->sqlerrcode = ERRCODE_DISK_FULL;
 616			break;
 617
 618		case ENFILE:			/* File table overflow */
 619		case EMFILE:			/* Too many open files */
 620			edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
 621			break;
 622
 623			/* Hardware failure */
 624		case EIO:				/* I/O error */
 625			edata->sqlerrcode = ERRCODE_IO_ERROR;
 626			break;
 627
 628			/* All else is classified as internal errors */
 629		default:
 630			edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
 631			break;
 632	}
 633
 634	return 0;					/* return value does not matter */
 635}
 636
 637/*
 638 * errcode_for_socket_access --- add SQLSTATE error code to the current error
 639 *
 640 * The SQLSTATE code is chosen based on the saved errno value.	We assume
 641 * that the failing operation was some type of socket access.
 642 *
 643 * NOTE: the primary error message string should generally include %m
 644 * when this is used.
 645 */
 646int
 647errcode_for_socket_access(void)
 648{
 649	ErrorData  *edata = &errordata[errordata_stack_depth];
 650
 651	/* we don't bother incrementing recursion_depth */
 652	CHECK_STACK_DEPTH();
 653
 654	switch (edata->saved_errno)
 655	{
 656			/* Loss of connection */
 657		case EPIPE:
 658#ifdef ECONNRESET
 659		case ECONNRESET:
 660#endif
 661			edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
 662			break;
 663
 664			/* All else is classified as internal errors */
 665		default:
 666			edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
 667			break;
 668	}
 669
 670	return 0;					/* return value does not matter */
 671}
 672
 673
 674/*
 675 * This macro handles expansion of a format string and associated parameters;
 676 * it's common code for errmsg(), errdetail(), etc.  Must be called inside
 677 * a routine that is declared like "const char *fmt, ..." and has an edata
 678 * pointer set up.	The message is assigned to edata->targetfield, or
 679 * appended to it if appendval is true.  The message is subject to translation
 680 * if translateit is true.
 681 *
 682 * Note: we pstrdup the buffer rather than just transferring its storage
 683 * to the edata field because the buffer might be considerably larger than
 684 * really necessary.
 685 */
 686#define EVALUATE_MESSAGE(targetfield, appendval, translateit)  \
 687	{ \
 688		char		   *fmtbuf; \
 689		StringInfoData	buf; \
 690		/* Internationalize the error format string */ \
 691		if (translateit && !in_error_recursion_trouble()) \
 692			fmt = dgettext(edata->domain, fmt); \
 693		/* Expand %m in format string */ \
 694		fmtbuf = expand_fmt_string(fmt, edata); \
 695		initStringInfo(&buf); \
 696		if ((appendval) && edata->targetfield) { \
 697			appendStringInfoString(&buf, edata->targetfield); \
 698			appendStringInfoChar(&buf, '\n'); \
 699		} \
 700		/* Generate actual output --- have to use appendStringInfoVA */ \
 701		for (;;) \
 702		{ \
 703			va_list		args; \
 704			bool		success; \
 705			va_start(args, fmt); \
 706			success = appendStringInfoVA(&buf, fmtbuf, args); \
 707			va_end(args); \
 708			if (success) \
 709				break; \
 710			enlargeStringInfo(&buf, buf.maxlen); \
 711		} \
 712		/* Done with expanded fmt */ \
 713		pfree(fmtbuf); \
 714		/* Save the completed message into the stack item */ \
 715		if (edata->targetfield) \
 716			pfree(edata->targetfield); \
 717		edata->targetfield = pstrdup(buf.data); \
 718		pfree(buf.data); \
 719	}
 720
 721/*
 722 * Same as above, except for pluralized error messages.  The calling routine
 723 * must be declared like "const char *fmt_singular, const char *fmt_plural,
 724 * unsigned long n, ...".  Translation is assumed always wanted.
 725 */
 726#define EVALUATE_MESSAGE_PLURAL(targetfield, appendval)  \
 727	{ \
 728		const char	   *fmt; \
 729		char		   *fmtbuf; \
 730		StringInfoData	buf; \
 731		/* Internationalize the error format string */ \
 732		if (!in_error_recursion_trouble()) \
 733			fmt = dngettext(edata->domain, fmt_singular, fmt_plural, n); \
 734		else \
 735			fmt = (n == 1 ? fmt_singular : fmt_plural); \
 736		/* Expand %m in format string */ \
 737		fmtbuf = expand_fmt_string(fmt, edata); \
 738		initStringInfo(&buf); \
 739		if ((appendval) && edata->targetfield) { \
 740			appendStringInfoString(&buf, edata->targetfield); \
 741			appendStringInfoChar(&buf, '\n'); \
 742		} \
 743		/* Generate actual output --- have to use appendStringInfoVA */ \
 744		for (;;) \
 745		{ \
 746			va_list		args; \
 747			bool		success; \
 748			va_start(args, n); \
 749			success = appendStringInfoVA(&buf, fmtbuf, args); \
 750			va_end(args); \
 751			if (success) \
 752				break; \
 753			enlargeStringInfo(&buf, buf.maxlen); \
 754		} \
 755		/* Done with expanded fmt */ \
 756		pfree(fmtbuf); \
 757		/* Save the completed message into the stack item */ \
 758		if (edata->targetfield) \
 759			pfree(edata->targetfield); \
 760		edata->targetfield = pstrdup(buf.data); \
 761		pfree(buf.data); \
 762	}
 763
 764
 765/*
 766 * errmsg --- add a primary error message text to the current error
 767 *
 768 * In addition to the usual %-escapes recognized by printf, "%m" in
 769 * fmt is replaced by the error message for the caller's value of errno.
 770 *
 771 * Note: no newline is needed at the end of the fmt string, since
 772 * ereport will provide one for the output methods that need it.
 773 */
 774int
 775errmsg(const char *fmt,...)
 776{
 777	ErrorData  *edata = &errordata[errordata_stack_depth];
 778	MemoryContext oldcontext;
 779
 780	recursion_depth++;
 781	CHECK_STACK_DEPTH();
 782	oldcontext = MemoryContextSwitchTo(ErrorContext);
 783
 784	EVALUATE_MESSAGE(message, false, true);
 785
 786	MemoryContextSwitchTo(oldcontext);
 787	recursion_depth--;
 788	return 0;					/* return value does not matter */
 789}
 790
 791
 792/*
 793 * errmsg_internal --- add a primary error message text to the current error
 794 *
 795 * This is exactly like errmsg() except that strings passed to errmsg_internal
 796 * are not translated, and are customarily left out of the
 797 * internationalization message dictionary.  This should be used for "can't
 798 * happen" cases that are probably not worth spending translation effort on.
 799 * We also use this for certain cases where we *must* not try to translate
 800 * the message because the translation would fail and result in infinite
 801 * error recursion.
 802 */
 803int
 804errmsg_internal(const char *fmt,...)
 805{
 806	ErrorData  *edata = &errordata[errordata_stack_depth];
 807	MemoryContext oldcontext;
 808
 809	recursion_depth++;
 810	CHECK_STACK_DEPTH();
 811	oldcontext = MemoryContextSwitchTo(ErrorContext);
 812
 813	EVALUATE_MESSAGE(message, false, false);
 814
 815	MemoryContextSwitchTo(oldcontext);
 816	recursion_depth--;
 817	return 0;					/* return value does not matter */
 818}
 819
 820
 821/*
 822 * errmsg_plural --- add a primary error message text to the current error,
 823 * with support for pluralization of the message text
 824 */
 825int
 826errmsg_plural(const char *fmt_singular, const char *fmt_plural,
 827			  unsigned long n,...)
 828{
 829	ErrorData  *edata = &errordata[errordata_stack_depth];
 830	MemoryContext oldcontext;
 831
 832	recursion_depth++;
 833	CHECK_STACK_DEPTH();
 834	oldcontext = MemoryContextSwitchTo(ErrorContext);
 835
 836	EVALUATE_MESSAGE_PLURAL(message, false);
 837
 838	MemoryContextSwitchTo(oldcontext);
 839	recursion_depth--;
 840	return 0;					/* return value does not matter */
 841}
 842
 843
 844/*
 845 * errdetail --- add a detail error message text to the current error
 846 */
 847int
 848errdetail(const char *fmt,...)
 849{
 850	ErrorData  *edata = &errordata[errordata_stack_depth];
 851	MemoryContext oldcontext;
 852
 853	recursion_depth++;
 854	CHECK_STACK_DEPTH();
 855	oldcontext = MemoryContextSwitchTo(ErrorContext);
 856
 857	EVALUATE_MESSAGE(detail, false, true);
 858
 859	MemoryContextSwitchTo(oldcontext);
 860	recursion_depth--;
 861	return 0;					/* return value does not matter */
 862}
 863
 864
 865/*
 866 * errdetail_internal --- add a detail error message text to the current error
 867 *
 868 * This is exactly like errdetail() except that strings passed to
 869 * errdetail_internal are not translated, and are customarily left out of the
 870 * internationalization message dictionary.  This should be used for detail
 871 * messages that seem not worth translating for one reason or another
 872 * (typically, that they don't seem to be useful to average users).
 873 */
 874int
 875errdetail_internal(const char *fmt,...)
 876{
 877	ErrorData  *edata = &errordata[errordata_stack_depth];
 878	MemoryContext oldcontext;
 879
 880	recursion_depth++;
 881	CHECK_STACK_DEPTH();
 882	oldcontext = MemoryContextSwitchTo(ErrorContext);
 883
 884	EVALUATE_MESSAGE(detail, false, false);
 885
 886	MemoryContextSwitchTo(oldcontext);
 887	recursion_depth--;
 888	return 0;					/* return value does not matter */
 889}
 890
 891
 892/*
 893 * errdetail_log --- add a detail_log error message text to the current error
 894 */
 895int
 896errdetail_log(const char *fmt,...)
 897{
 898	ErrorData  *edata = &errordata[errordata_stack_depth];
 899	MemoryContext oldcontext;
 900
 901	recursion_depth++;
 902	CHECK_STACK_DEPTH();
 903	oldcontext = MemoryContextSwitchTo(ErrorContext);
 904
 905	EVALUATE_MESSAGE(detail_log, false, true);
 906
 907	MemoryContextSwitchTo(oldcontext);
 908	recursion_depth--;
 909	return 0;					/* return value does not matter */
 910}
 911
 912
 913/*
 914 * errdetail_plural --- add a detail error message text to the current error,
 915 * with support for pluralization of the message text
 916 */
 917int
 918errdetail_plural(const char *fmt_singular, const char *fmt_plural,
 919				 unsigned long n,...)
 920{
 921	ErrorData  *edata = &errordata[errordata_stack_depth];
 922	MemoryContext oldcontext;
 923
 924	recursion_depth++;
 925	CHECK_STACK_DEPTH();
 926	oldcontext = MemoryContextSwitchTo(ErrorContext);
 927
 928	EVALUATE_MESSAGE_PLURAL(detail, false);
 929
 930	MemoryContextSwitchTo(oldcontext);
 931	recursion_depth--;
 932	return 0;					/* return value does not matter */
 933}
 934
 935
 936/*
 937 * errhint --- add a hint error message text to the current error
 938 */
 939int
 940errhint(const char *fmt,...)
 941{
 942	ErrorData  *edata = &errordata[errordata_stack_depth];
 943	MemoryContext oldcontext;
 944
 945	recursion_depth++;
 946	CHECK_STACK_DEPTH();
 947	oldcontext = MemoryContextSwitchTo(ErrorContext);
 948
 949	EVALUATE_MESSAGE(hint, false, true);
 950
 951	MemoryContextSwitchTo(oldcontext);
 952	recursion_depth--;
 953	return 0;					/* return value does not matter */
 954}
 955
 956
 957/*
 958 * errcontext --- add a context error message text to the current error
 959 *
 960 * Unlike other cases, multiple calls are allowed to build up a stack of
 961 * context information.  We assume earlier calls represent more-closely-nested
 962 * states.
 963 */
 964int
 965errcontext(const char *fmt,...)
 966{
 967	ErrorData  *edata = &errordata[errordata_stack_depth];
 968	MemoryContext oldcontext;
 969
 970	recursion_depth++;
 971	CHECK_STACK_DEPTH();
 972	oldcontext = MemoryContextSwitchTo(ErrorContext);
 973
 974	EVALUATE_MESSAGE(context, true, true);
 975
 976	MemoryContextSwitchTo(oldcontext);
 977	recursion_depth--;
 978	return 0;					/* return value does not matter */
 979}
 980
 981
 982/*
 983 * errhidestmt --- optionally suppress STATEMENT: field of log entry
 984 *
 985 * This should be called if the message text already includes the statement.
 986 */
 987int
 988errhidestmt(bool hide_stmt)
 989{
 990	ErrorData  *edata = &errordata[errordata_stack_depth];
 991
 992	/* we don't bother incrementing recursion_depth */
 993	CHECK_STACK_DEPTH();
 994
 995	edata->hide_stmt = hide_stmt;
 996
 997	return 0;					/* return value does not matter */
 998}
 999
1000
1001/*
1002 * errfunction --- add reporting function name to the current error
1003 *
1004 * This is used when backwards compatibility demands that the function
1005 * name appear in messages sent to old-protocol clients.  Note that the
1006 * passed string is expected to be a non-freeable constant string.
1007 */
1008int
1009errfunction(const char *funcname)
1010{
1011	ErrorData  *edata = &errordata[errordata_stack_depth];
1012
1013	/* we don't bother incrementing recursion_depth */
1014	CHECK_STACK_DEPTH();
1015
1016	edata->funcname = funcname;
1017	edata->show_funcname = true;
1018
1019	return 0;					/* return value does not matter */
1020}
1021
1022/*
1023 * errposition --- add cursor position to the current error
1024 */
1025int
1026errposition(int cursorpos)
1027{
1028	ErrorData  *edata = &errordata[errordata_stack_depth];
1029
1030	/* we don't bother incrementing recursion_depth */
1031	CHECK_STACK_DEPTH();
1032
1033	edata->cursorpos = cursorpos;
1034
1035	return 0;					/* return value does not matter */
1036}
1037
1038/*
1039 * internalerrposition --- add internal cursor position to the current error
1040 */
1041int
1042internalerrposition(int cursorpos)
1043{
1044	ErrorData  *edata = &errordata[errordata_stack_depth];
1045
1046	/* we don't bother incrementing recursion_depth */
1047	CHECK_STACK_DEPTH();
1048
1049	edata->internalpos = cursorpos;
1050
1051	return 0;					/* return value does not matter */
1052}
1053
1054/*
1055 * internalerrquery --- add internal query text to the current error
1056 *
1057 * Can also pass NULL to drop the internal query text entry.  This case
1058 * is intended for use in error callback subroutines that are editorializing
1059 * on the layout of the error report.
1060 */
1061int
1062internalerrquery(const char *query)
1063{
1064	ErrorData  *edata = &errordata[errordata_stack_depth];
1065
1066	/* we don't bother incrementing recursion_depth */
1067	CHECK_STACK_DEPTH();
1068
1069	if (edata->internalquery)
1070	{
1071		pfree(edata->internalquery);
1072		edata->internalquery = NULL;
1073	}
1074
1075	if (query)
1076		edata->internalquery = MemoryContextStrdup(ErrorContext, query);
1077
1078	return 0;					/* return value does not matter */
1079}
1080
1081/*
1082 * geterrcode --- return the currently set SQLSTATE error code
1083 *
1084 * This is only intended for use in error callback subroutines, since there
1085 * is no other place outside elog.c where the concept is meaningful.
1086 */
1087int
1088geterrcode(void)
1089{
1090	ErrorData  *edata = &errordata[errordata_stack_depth];
1091
1092	/* we don't bother incrementing recursion_depth */
1093	CHECK_STACK_DEPTH();
1094
1095	return edata->sqlerrcode;
1096}
1097
1098/*
1099 * geterrposition --- return the currently set error position (0 if none)
1100 *
1101 * This is only intended for use in error callback subroutines, since there
1102 * is no other place outside elog.c where the concept is meaningful.
1103 */
1104int
1105geterrposition(void)
1106{
1107	ErrorData  *edata = &errordata[errordata_stack_depth];
1108
1109	/* we don't bother incrementing recursion_depth */
1110	CHECK_STACK_DEPTH();
1111
1112	return edata->cursorpos;
1113}
1114
1115/*
1116 * getinternalerrposition --- same for internal error position
1117 *
1118 * This is only intended for use in error callback subroutines, since there
1119 * is no other place outside elog.c where the concept is meaningful.
1120 */
1121int
1122getinternalerrposition(void)
1123{
1124	ErrorData  *edata = &errordata[errordata_stack_depth];
1125
1126	/* we don't bother incrementing recursion_depth */
1127	CHECK_STACK_DEPTH();
1128
1129	return edata->internalpos;
1130}
1131
1132
1133/*
1134 * elog_start --- startup for old-style API
1135 *
1136 * All that we do here is stash the hidden filename/lineno/funcname
1137 * arguments into a stack entry.
1138 *
1139 * We need this to be separate from elog_finish because there's no other
1140 * portable way to deal with inserting extra arguments into the elog call.
1141 * (If macros with variable numbers of arguments were portable, it'd be
1142 * easy, but they aren't.)
1143 */
1144void
1145elog_start(const char *filename, int lineno, const char *funcname)
1146{
1147	ErrorData  *edata;
1148
1149	if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1150	{
1151		/*
1152		 * Wups, stack not big enough.	We treat this as a PANIC condition
1153		 * because it suggests an infinite loop of errors during error
1154		 * recovery.  Note that the message is intentionally not localized,
1155		 * else failure to convert it to client encoding could cause further
1156		 * recursion.
1157		 */
1158		errordata_stack_depth = -1;		/* make room on stack */
1159		ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1160	}
1161
1162	edata = &errordata[errordata_stack_depth];
1163	if (filename)
1164	{
1165		const char *slash;
1166
1167		/* keep only base name, useful especially for vpath builds */
1168		slash = strrchr(filename, '/');
1169		if (slash)
1170			filename = slash + 1;
1171	}
1172	edata->filename = filename;
1173	edata->lineno = lineno;
1174	edata->funcname = funcname;
1175	/* errno is saved now so that error parameter eval can't change it */
1176	edata->saved_errno = errno;
1177}
1178
1179/*
1180 * elog_finish --- finish up for old-style API
1181 */
1182void
1183elog_finish(int elevel, const char *fmt,...)
1184{
1185	ErrorData  *edata = &errordata[errordata_stack_depth];
1186	MemoryContext oldcontext;
1187
1188	CHECK_STACK_DEPTH();
1189
1190	/*
1191	 * Do errstart() to see if we actually want to report the message.
1192	 */
1193	errordata_stack_depth--;
1194	errno = edata->saved_errno;
1195	if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname, NULL))
1196		return;					/* nothing to do */
1197
1198	/*
1199	 * Format error message just like errmsg_internal().
1200	 */
1201	recursion_depth++;
1202	oldcontext = MemoryContextSwitchTo(ErrorContext);
1203
1204	EVALUATE_MESSAGE(message, false, false);
1205
1206	MemoryContextSwitchTo(oldcontext);
1207	recursion_depth--;
1208
1209	/*
1210	 * And let errfinish() finish up.
1211	 */
1212	errfinish(0);
1213}
1214
1215
1216/*
1217 * Functions to allow construction of error message strings separately from
1218 * the ereport() call itself.
1219 *
1220 * The expected calling convention is
1221 *
1222 *	pre_format_elog_string(errno, domain), var = format_elog_string(format,...)
1223 *
1224 * which can be hidden behind a macro such as GUC_check_errdetail().  We
1225 * assume that any functions called in the arguments of format_elog_string()
1226 * cannot result in re-entrant use of these functions --- otherwise the wrong
1227 * text domain might be used, or the wrong errno substituted for %m.  This is
1228 * okay for the current usage with GUC check hooks, but might need further
1229 * effort someday.
1230 *
1231 * The result of format_elog_string() is stored in ErrorContext, and will
1232 * therefore survive until FlushErrorState() is called.
1233 */
1234static int	save_format_errnumber;
1235static const char *save_format_domain;
1236
1237void
1238pre_format_elog_string(int errnumber, const char *domain)
1239{
1240	/* Save errno before evaluation of argument functions can change it */
1241	save_format_errnumber = errnumber;
1242	/* Save caller's text domain */
1243	save_format_domain = domain;
1244}
1245
1246char *
1247format_elog_string(const char *fmt,...)
1248{
1249	ErrorData	errdata;
1250	ErrorData  *edata;
1251	MemoryContext oldcontext;
1252
1253	/* Initialize a mostly-dummy error frame */
1254	edata = &errdata;
1255	MemSet(edata, 0, sizeof(ErrorData));
1256	/* the default text domain is the backend's */
1257	edata->domain = save_format_domain ? save_format_domain : PG_TEXTDOMAIN("postgres");
1258	/* set the errno to be used to interpret %m */
1259	edata->saved_errno = save_format_errnumber;
1260
1261	oldcontext = MemoryContextSwitchTo(ErrorContext);
1262
1263	EVALUATE_MESSAGE(message, false, true);
1264
1265	MemoryContextSwitchTo(oldcontext);
1266
1267	return edata->message;
1268}
1269
1270
1271/*
1272 * Actual output of the top-of-stack error message
1273 *
1274 * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
1275 * if the error is caught by somebody).  For all other severity levels this
1276 * is called by errfinish.
1277 */
1278void
1279EmitErrorReport(void)
1280{
1281	ErrorData  *edata = &errordata[errordata_stack_depth];
1282	MemoryContext oldcontext;
1283
1284	recursion_depth++;
1285	CHECK_STACK_DEPTH();
1286	oldcontext = MemoryContextSwitchTo(ErrorContext);
1287
1288	/*
1289	 * Call hook before sending message to log.  The hook function is allowed
1290	 * to turn off edata->output_to_server, so we must recheck that afterward.
1291	 * Making any other change in the content of edata is not considered
1292	 * supported.
1293	 *
1294	 * Note: the reason why the hook can only turn off output_to_server, and
1295	 * not turn it on, is that it'd be unreliable: we will never get here at
1296	 * all if errstart() deems the message uninteresting.  A hook that could
1297	 * make decisions in that direction would have to hook into errstart(),
1298	 * where it would have much less information available.  emit_log_hook is
1299	 * intended for custom log filtering and custom log message transmission
1300	 * mechanisms.
1301	 */
1302	if (edata->output_to_server && emit_log_hook)
1303		(*emit_log_hook) (edata);
1304
1305	/* Send to server log, if enabled */
1306	if (edata->output_to_server)
1307		send_message_to_server_log(edata);
1308
1309	/* Send to client, if enabled */
1310	if (edata->output_to_client)
1311		send_message_to_frontend(edata);
1312
1313	MemoryContextSwitchTo(oldcontext);
1314	recursion_depth--;
1315}
1316
1317/*
1318 * CopyErrorData --- obtain a copy of the topmost error stack entry
1319 *
1320 * This is only for use in error handler code.	The data is copied into the
1321 * current memory context, so callers should always switch away from
1322 * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
1323 */
1324ErrorData *
1325CopyErrorData(void)
1326{
1327	ErrorData  *edata = &errordata[errordata_stack_depth];
1328	ErrorData  *newedata;
1329
1330	/*
1331	 * we don't increment recursion_depth because out-of-memory here does not
1332	 * indicate a problem within the error subsystem.
1333	 */
1334	CHECK_STACK_DEPTH();
1335
1336	Assert(CurrentMemoryContext != ErrorContext);
1337
1338	/* Copy the struct itself */
1339	newedata = (ErrorData *) palloc(sizeof(ErrorData));
1340	memcpy(newedata, edata, sizeof(ErrorData));
1341
1342	/* Make copies of separately-allocated fields */
1343	if (newedata->message)
1344		newedata->message = pstrdup(newedata->message);
1345	if (newedata->detail)
1346		newedata->detail = pstrdup(newedata->detail);
1347	if (newedata->detail_log)
1348		newedata->detail_log = pstrdup(newedata->detail_log);
1349	if (newedata->hint)
1350		newedata->hint = pstrdup(newedata->hint);
1351	if (newedata->context)
1352		newedata->context = pstrdup(newedata->context);
1353	if (newedata->internalquery)
1354		newedata->internalquery = pstrdup(newedata->internalquery);
1355
1356	return newedata;
1357}
1358
1359/*
1360 * FreeErrorData --- free the structure returned by CopyErrorData.
1361 *
1362 * Error handlers should use this in preference to assuming they know all
1363 * the separately-allocated fields.
1364 */
1365void
1366FreeErrorData(ErrorData *edata)
1367{
1368	if (edata->message)
1369		pfree(edata->message);
1370	if (edata->detail)
1371		pfree(edata->detail);
1372	if (edata->detail_log)
1373		pfree(edata->detail_log);
1374	if (edata->hint)
1375		pfree(edata->hint);
1376	if (edata->context)
1377		pfree(edata->context);
1378	if (edata->internalquery)
1379		pfree(edata->internalquery);
1380	pfree(edata);
1381}
1382
1383/*
1384 * FlushErrorState --- flush the error state after error recovery
1385 *
1386 * This should be called by an error handler after it's done processing
1387 * the error; or as soon as it's done CopyErrorData, if it intends to
1388 * do stuff that is likely to provoke another error.  You are not "out" of
1389 * the error subsystem until you have done this.
1390 */
1391void
1392FlushErrorState(void)
1393{
1394	/*
1395	 * Reset stack to empty.  The only case where it would be more than one
1396	 * deep is if we serviced an error that interrupted construction of
1397	 * another message.  We assume control escaped out of that message
1398	 * construction and won't ever go back.
1399	 */
1400	errordata_stack_depth = -1;
1401	recursion_depth = 0;
1402	/* Delete all data in ErrorContext */
1403	MemoryContextResetAndDeleteChildren(ErrorContext);
1404}
1405
1406/*
1407 * ReThrowError --- re-throw a previously copied error
1408 *
1409 * A handler can do CopyErrorData/FlushErrorState to get out of the error
1410 * subsystem, then do some processing, and finally ReThrowError to re-throw
1411 * the original error.	This is slower than just PG_RE_THROW() but should
1412 * be used if the "some processing" is likely to incur another error.
1413 */
1414void
1415ReThrowError(ErrorData *edata)
1416{
1417	ErrorData  *newedata;
1418
1419	Assert(edata->elevel == ERROR);
1420
1421	/* Push the data back into the error context */
1422	recursion_depth++;
1423	MemoryContextSwitchTo(ErrorContext);
1424
1425	if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1426	{
1427		/*
1428		 * Wups, stack not big enough.	We treat this as a PANIC condition
1429		 * because it suggests an infinite loop of errors during error
1430		 * recovery.
1431		 */
1432		errordata_stack_depth = -1;		/* make room on stack */
1433		ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1434	}
1435
1436	newedata = &errordata[errordata_stack_depth];
1437	memcpy(newedata, edata, sizeof(ErrorData));
1438
1439	/* Make copies of separately-allocated fields */
1440	if (newedata->message)
1441		newedata->message = pstrdup(newedata->message);
1442	if (newedata->detail)
1443		newedata->detail = pstrdup(newedata->detail);
1444	if (newedata->detail_log)
1445		newedata->detail_log = pstrdup(newedata->detail_log);
1446	if (newedata->hint)
1447		newedata->hint = pstrdup(newedata->hint);
1448	if (newedata->context)
1449		newedata->context = pstrdup(newedata->context);
1450	if (newedata->internalquery)
1451		newedata->internalquery = pstrdup(newedata->internalquery);
1452
1453	recursion_depth--;
1454	PG_RE_THROW();
1455}
1456
1457/*
1458 * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
1459 */
1460void
1461pg_re_throw(void)
1462{
1463	/* If possible, throw the error to the next outer setjmp handler */
1464	if (PG_exception_stack != NULL)
1465		siglongjmp(*PG_exception_stack, 1);
1466	else
1467	{
1468		/*
1469		 * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
1470		 * we have now exited only to discover that there is no outer setjmp
1471		 * handler to pass the error to.  Had the error been thrown outside
1472		 * the block to begin with, we'd have promoted the error to FATAL, so
1473		 * the correct behavior is to make it FATAL now; that is, emit it and
1474		 * then call proc_exit.
1475		 */
1476		ErrorData  *edata = &errordata[errordata_stack_depth];
1477
1478		Assert(errordata_stack_depth >= 0);
1479		Assert(edata->elevel == ERROR);
1480		edata->elevel = FATAL;
1481
1482		/*
1483		 * At least in principle, the increase in severity could have changed
1484		 * where-to-output decisions, so recalculate.  This should stay in
1485		 * sync with errstart(), which see for comments.
1486		 */
1487		if (IsPostmasterEnvironment)
1488			edata->output_to_server = is_log_level_output(FATAL,
1489														  log_min_messages);
1490		else
1491			edata->output_to_server = (FATAL >= log_min_messages);
1492		if (whereToSendOutput == DestRemote)
1493		{
1494			if (ClientAuthInProgress)
1495				edata->output_to_client = true;
1496			else
1497				edata->output_to_client = (FATAL >= client_min_messages);
1498		}
1499
1500		/*
1501		 * We can use errfinish() for the rest, but we don't want it to call
1502		 * any error context routines a second time.  Since we know we are
1503		 * about to exit, it should be OK to just clear the context stack.
1504		 */
1505		error_context_stack = NULL;
1506
1507		errfinish(0);
1508	}
1509
1510	/* Doesn't return ... */
1511	ExceptionalCondition("pg_re_throw tried to return", "FailedAssertion",
1512						 __FILE__, __LINE__);
1513}
1514
1515
1516/*
1517 * Initialization of error output file
1518 */
1519void
1520DebugFileOpen(void)
1521{
1522	int			fd,
1523				istty;
1524
1525	if (OutputFileName[0])
1526	{
1527		/*
1528		 * A debug-output file name was given.
1529		 *
1530		 * Make sure we can write the file, and find out if it's a tty.
1531		 */
1532		if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
1533					   0666)) < 0)
1534			ereport(FATAL,
1535					(errcode_for_file_access(),
1536				  errmsg("could not open file \"%s\": %m", OutputFileName)));
1537		istty = isatty(fd);
1538		close(fd);
1539
1540		/*
1541		 * Redirect our stderr to the debug output file.
1542		 */
1543		if (!freopen(OutputFileName, "a", stderr))
1544			ereport(FATAL,
1545					(errcode_for_file_access(),
1546					 errmsg("could not reopen file \"%s\" as stderr: %m",
1547							OutputFileName)));
1548
1549		/*
1550		 * If the file is a tty and we're running under the postmaster, try to
1551		 * send stdout there as well (if it isn't a tty then stderr will block
1552		 * out stdout, so we may as well let stdout go wherever it was going
1553		 * before).
1554		 */
1555		if (istty && IsUnderPostmaster)
1556			if (!freopen(OutputFileName, "a", stdout))
1557				ereport(FATAL,
1558						(errcode_for_file_access(),
1559						 errmsg("could not reopen file \"%s\" as stdout: %m",
1560								OutputFileName)));
1561	}
1562}
1563
1564
1565#ifdef HAVE_SYSLOG
1566
1567/*
1568 * Set or update the parameters for syslog logging
1569 */
1570void
1571set_syslog_parameters(const char *ident, int facility)
1572{
1573	/*
1574	 * guc.c is likely to call us repeatedly with same parameters, so don't
1575	 * thrash the syslog connection unnecessarily.	Also, we do not re-open
1576	 * the connection until needed, since this routine will get called whether
1577	 * or not Log_destination actually mentions syslog.
1578	 *
1579	 * Note that we make our own copy of the ident string rather than relying
1580	 * on guc.c's.  This may be overly paranoid, but it ensures that we cannot
1581	 * accidentally free a string that syslog is still using.
1582	 */
1583	if (syslog_ident == NULL || strcmp(syslog_ident, ident) != 0 ||
1584		syslog_facility != facility)
1585	{
1586		if (openlog_done)
1587		{
1588			closelog();
1589			openlog_done = false;
1590		}
1591		if (syslog_ident)
1592			free(syslog_ident);
1593		syslog_ident = strdup(ident);
1594		/* if the strdup fails, we will cope in write_syslog() */
1595		syslog_facility = facility;
1596	}
1597}
1598
1599
1600/*
1601 * Write a message line to syslog
1602 */
1603static void
1604write_syslog(int level, const char *line)
1605{
1606	static unsigned long seq = 0;
1607
1608	int			len;
1609	const char *nlpos;
1610
1611	/* Open syslog connection if not done yet */
1612	if (!openlog_done)
1613	{
1614		openlog(syslog_ident ? syslog_ident : "postgres",
1615				LOG_PID | LOG_NDELAY | LOG_NOWAIT,
1616				syslog_facility);
1617		openlog_done = true;
1618	}
1619
1620	/*
1621	 * We add a sequence number to each log message to suppress "same"
1622	 * messages.
1623	 */
1624	seq++;
1625
1626	/*
1627	 * Our problem here is that many syslog implementations don't handle long
1628	 * messages in an acceptable manner. While this function doesn't help that
1629	 * fact, it does work around by splitting up messages into smaller pieces.
1630	 *
1631	 * We divide into multiple syslog() calls if message is too long or if the
1632	 * message contains embedded newline(s).
1633	 */
1634	len = strlen(line);
1635	nlpos = strchr(line, '\n');
1636	if (len > PG_SYSLOG_LIMIT || nlpos != NULL)
1637	{
1638		int			chunk_nr = 0;
1639
1640		while (len > 0)
1641		{
1642			char		buf[PG_SYSLOG_LIMIT + 1];
1643			int			buflen;
1644			int			i;
1645
1646			/* if we start at a newline, move ahead one char */
1647			if (line[0] == '\n')
1648			{
1649				line++;
1650				len--;
1651				/* we need to recompute the next newline's position, too */
1652				nlpos = strchr(line, '\n');
1653				continue;
1654			}
1655
1656			/* copy one line, or as much as will fit, to buf */
1657			if (nlpos != NULL)
1658				buflen = nlpos - line;
1659			else
1660				buflen = len;
1661			buflen = Min(buflen, PG_SYSLOG_LIMIT);
1662			memcpy(buf, line, buflen);
1663			buf[buflen] = '\0';
1664
1665			/* trim to multibyte letter boundary */
1666			buflen = pg_mbcliplen(buf, buflen, buflen);
1667			if (buflen <= 0)
1668				return;
1669			buf[buflen] = '\0';
1670
1671			/* already word boundary? */
1672			if (line[buflen] != '\0' &&
1673				!isspace((unsigned char) line[buflen]))
1674			{
1675				/* try to divide at word boundary */
1676				i = buflen - 1;
1677				while (i > 0 && !isspace((unsigned char) buf[i]))
1678					i--;
1679
1680				if (i > 0)		/* else couldn't divide word boundary */
1681				{
1682					buflen = i;
1683					buf[i] = '\0';
1684				}
1685			}
1686
1687			chunk_nr++;
1688
1689			syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1690			line += buflen;
1691			len -= buflen;
1692		}
1693	}
1694	else
1695	{
1696		/* message short enough */
1697		syslog(level, "[%lu] %s", seq, line);
1698	}
1699}
1700#endif   /* HAVE_SYSLOG */
1701
1702#ifdef WIN32
1703/*
1704 * Write a message line to the windows event log
1705 */
1706static void
1707write_eventlog(int level, const char *line, int len)
1708{
1709	WCHAR	   *utf16;
1710	int			eventlevel = EVENTLOG_ERROR_TYPE;
1711	static HANDLE evtHandle = INVALID_HANDLE_VALUE;
1712
1713	if (evtHandle == INVALID_HANDLE_VALUE)
1714	{
1715		evtHandle = RegisterEventSource(NULL, event_source ? event_source : "PostgreSQL");
1716		if (evtHandle == NULL)
1717		{
1718			evtHandle = INVALID_HANDLE_VALUE;
1719			return;
1720		}
1721	}
1722
1723	switch (level)
1724	{
1725		case DEBUG5:
1726		case DEBUG4:
1727		case DEBUG3:
1728		case DEBUG2:
1729		case DEBUG1:
1730		case LOG:
1731		case COMMERROR:
1732		case INFO:
1733		case NOTICE:
1734			eventlevel = EVENTLOG_INFORMATION_TYPE;
1735			break;
1736		case WARNING:
1737			eventlevel = EVENTLOG_WARNING_TYPE;
1738			break;
1739		case ERROR:
1740		case FATAL:
1741		case PANIC:
1742		default:
1743			eventlevel = EVENTLOG_ERROR_TYPE;
1744			break;
1745	}
1746
1747	/*
1748	 * Convert message to UTF16 text and write it with ReportEventW, but
1749	 * fall-back into ReportEventA if conversion failed.
1750	 *
1751	 * Also verify that we are not on our way into error recursion trouble due
1752	 * to error messages thrown deep inside pgwin32_toUTF16().
1753	 */
1754	if (GetDatabaseEncoding() != GetPlatformEncoding() &&
1755		!in_error_recursion_trouble())
1756	{
1757		utf16 = pgwin32_toUTF16(line, len, NULL);
1758		if (utf16)
1759		{
1760			ReportEventW(evtHandle,
1761						 eventlevel,
1762						 0,
1763						 0,		/* All events are Id 0 */
1764						 NULL,
1765						 1,
1766						 0,
1767						 (LPCWSTR *) &utf16,
1768						 NULL);
1769
1770			pfree(utf16);
1771			return;
1772		}
1773	}
1774	ReportEventA(evtHandle,
1775				 eventlevel,
1776				 0,
1777				 0,				/* All events are Id 0 */
1778				 NULL,
1779				 1,
1780				 0,
1781				 &line,
1782				 NULL);
1783}
1784#endif   /* WIN32 */
1785
1786static void
1787write_console(const char *line, int len)
1788{
1789	int			rc;
1790
1791#ifdef WIN32
1792
1793	/*
1794	 * WriteConsoleW() will fail if stdout is redirected, so just fall through
1795	 * to writing unconverted to the logfile in thiā€¦

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