PageRenderTime 74ms CodeModel.GetById 4ms app.highlight 56ms RepoModel.GetById 1ms app.codeStats 1ms

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

https://bitbucket.org/gencer/postgres
C | 3632 lines | 2149 code | 444 blank | 1039 comment | 437 complexity | 510896950c351b1d229f235678bc8735 MD5 | raw file

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

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