PageRenderTime 60ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/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
Possible License(s): AGPL-3.0

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