PageRenderTime 29ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

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

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

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