PageRenderTime 740ms CodeModel.GetById 40ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://bitbucket.org/definex/4707
C | 2979 lines | 1696 code | 397 blank | 886 comment | 317 complexity | b7ef106a34096bc391138ad9b511de79 MD5 | raw file
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-2012, PostgreSQL Global Development Group
  47. * Portions Copyright (c) 1994, Regents of the University of California
  48. *
  49. *
  50. * IDENTIFICATION
  51. * src/backend/utils/error/elog.c
  52. *
  53. *-------------------------------------------------------------------------
  54. */
  55. #include "postgres.h"
  56. #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(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(edata->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(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(edata->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(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(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(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(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(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(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(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(hint, false, true);
  821. MemoryContextSwitchTo(oldcontext);
  822. recursion_depth--;
  823. return 0; /* return value does not matter */
  824. }
  825. /*
  826. * errcontext --- 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(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(context, true, true);
  841. MemoryContextSwitchTo(oldcontext);
  842. recursion_depth--;
  843. return 0; /* return value does not matter */
  844. }
  845. /*
  846. * errhidestmt --- optionally suppress STATEMENT: field of log entry
  847. *
  848. * This should be called if the message text already includes the statement.
  849. */
  850. int
  851. errhidestmt(bool hide_stmt)
  852. {
  853. ErrorData *edata = &errordata[errordata_stack_depth];
  854. /* we don't bother incrementing recursion_depth */
  855. CHECK_STACK_DEPTH();
  856. edata->hide_stmt = hide_stmt;
  857. return 0; /* return value does not matter */
  858. }
  859. /*
  860. * errfunction --- add reporting function name to the current error
  861. *
  862. * This is used when backwards compatibility demands that the function
  863. * name appear in messages sent to old-protocol clients. Note that the
  864. * passed string is expected to be a non-freeable constant string.
  865. */
  866. int
  867. errfunction(const char *funcname)
  868. {
  869. ErrorData *edata = &errordata[errordata_stack_depth];
  870. /* we don't bother incrementing recursion_depth */
  871. CHECK_STACK_DEPTH();
  872. edata->funcname = funcname;
  873. edata->show_funcname = true;
  874. return 0; /* return value does not matter */
  875. }
  876. /*
  877. * errposition --- add cursor position to the current error
  878. */
  879. int
  880. errposition(int cursorpos)
  881. {
  882. ErrorData *edata = &errordata[errordata_stack_depth];
  883. /* we don't bother incrementing recursion_depth */
  884. CHECK_STACK_DEPTH();
  885. edata->cursorpos = cursorpos;
  886. return 0; /* return value does not matter */
  887. }
  888. /*
  889. * internalerrposition --- add internal cursor position to the current error
  890. */
  891. int
  892. internalerrposition(int cursorpos)
  893. {
  894. ErrorData *edata = &errordata[errordata_stack_depth];
  895. /* we don't bother incrementing recursion_depth */
  896. CHECK_STACK_DEPTH();
  897. edata->internalpos = cursorpos;
  898. return 0; /* return value does not matter */
  899. }
  900. /*
  901. * internalerrquery --- add internal query text to the current error
  902. *
  903. * Can also pass NULL to drop the internal query text entry. This case
  904. * is intended for use in error callback subroutines that are editorializing
  905. * on the layout of the error report.
  906. */
  907. int
  908. internalerrquery(const char *query)
  909. {
  910. ErrorData *edata = &errordata[errordata_stack_depth];
  911. /* we don't bother incrementing recursion_depth */
  912. CHECK_STACK_DEPTH();
  913. if (edata->internalquery)
  914. {
  915. pfree(edata->internalquery);
  916. edata->internalquery = NULL;
  917. }
  918. if (query)
  919. edata->internalquery = MemoryContextStrdup(ErrorContext, query);
  920. return 0; /* return value does not matter */
  921. }
  922. /*
  923. * geterrcode --- return the currently set SQLSTATE error code
  924. *
  925. * This is only intended for use in error callback subroutines, since there
  926. * is no other place outside elog.c where the concept is meaningful.
  927. */
  928. int
  929. geterrcode(void)
  930. {
  931. ErrorData *edata = &errordata[errordata_stack_depth];
  932. /* we don't bother incrementing recursion_depth */
  933. CHECK_STACK_DEPTH();
  934. return edata->sqlerrcode;
  935. }
  936. /*
  937. * geterrposition --- return the currently set error position (0 if none)
  938. *
  939. * This is only intended for use in error callback subroutines, since there
  940. * is no other place outside elog.c where the concept is meaningful.
  941. */
  942. int
  943. geterrposition(void)
  944. {
  945. ErrorData *edata = &errordata[errordata_stack_depth];
  946. /* we don't bother incrementing recursion_depth */
  947. CHECK_STACK_DEPTH();
  948. return edata->cursorpos;
  949. }
  950. /*
  951. * getinternalerrposition --- same for internal error position
  952. *
  953. * This is only intended for use in error callback subroutines, since there
  954. * is no other place outside elog.c where the concept is meaningful.
  955. */
  956. int
  957. getinternalerrposition(void)
  958. {
  959. ErrorData *edata = &errordata[errordata_stack_depth];
  960. /* we don't bother incrementing recursion_depth */
  961. CHECK_STACK_DEPTH();
  962. return edata->internalpos;
  963. }
  964. /*
  965. * elog_start --- startup for old-style API
  966. *
  967. * All that we do here is stash the hidden filename/lineno/funcname
  968. * arguments into a stack entry.
  969. *
  970. * We need this to be separate from elog_finish because there's no other
  971. * portable way to deal with inserting extra arguments into the elog call.
  972. * (If macros with variable numbers of arguments were portable, it'd be
  973. * easy, but they aren't.)
  974. */
  975. void
  976. elog_start(const char *filename, int lineno, const char *funcname)
  977. {
  978. ErrorData *edata;
  979. if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
  980. {
  981. /*
  982. * Wups, stack not big enough. We treat this as a PANIC condition
  983. * because it suggests an infinite loop of errors during error
  984. * recovery. Note that the message is intentionally not localized,
  985. * else failure to convert it to client encoding could cause further
  986. * recursion.
  987. */
  988. errordata_stack_depth = -1; /* make room on stack */
  989. ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
  990. }
  991. edata = &errordata[errordata_stack_depth];
  992. if (filename)
  993. {
  994. const char *slash;
  995. /* keep only base name, useful especially for vpath builds */
  996. slash = strrchr(filename, '/');
  997. if (slash)
  998. filename = slash + 1;
  999. }
  1000. edata->filename = filename;
  1001. edata->lineno = lineno;
  1002. edata->funcname = funcname;
  1003. /* errno is saved now so that error parameter eval can't change it */
  1004. edata->saved_errno = errno;
  1005. }
  1006. /*
  1007. * elog_finish --- finish up for old-style API
  1008. */
  1009. void
  1010. elog_finish(int elevel, const char *fmt,...)
  1011. {
  1012. ErrorData *edata = &errordata[errordata_stack_depth];
  1013. MemoryContext oldcontext;
  1014. CHECK_STACK_DEPTH();
  1015. /*
  1016. * Do errstart() to see if we actually want to report the message.
  1017. */
  1018. errordata_stack_depth--;
  1019. errno = edata->saved_errno;
  1020. if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname, NULL))
  1021. return; /* nothing to do */
  1022. /*
  1023. * Format error message just like errmsg_internal().
  1024. */
  1025. recursion_depth++;
  1026. oldcontext = MemoryContextSwitchTo(ErrorContext);
  1027. EVALUATE_MESSAGE(message, false, false);
  1028. MemoryContextSwitchTo(oldcontext);
  1029. recursion_depth--;
  1030. /*
  1031. * And let errfinish() finish up.
  1032. */
  1033. errfinish(0);
  1034. }
  1035. /*
  1036. * Functions to allow construction of error message strings separately from
  1037. * the ereport() call itself.
  1038. *
  1039. * The expected calling convention is
  1040. *
  1041. * pre_format_elog_string(errno, domain), var = format_elog_string(format,...)
  1042. *
  1043. * which can be hidden behind a macro such as GUC_check_errdetail(). We
  1044. * assume that any functions called in the arguments of format_elog_string()
  1045. * cannot result in re-entrant use of these functions --- otherwise the wrong
  1046. * text domain might be used, or the wrong errno substituted for %m. This is
  1047. * okay for the current usage with GUC check hooks, but might need further
  1048. * effort someday.
  1049. *
  1050. * The result of format_elog_string() is stored in ErrorContext, and will
  1051. * therefore survive until FlushErrorState() is called.
  1052. */
  1053. static int save_format_errnumber;
  1054. static const char *save_format_domain;
  1055. void
  1056. pre_format_elog_string(int errnumber, const char *domain)
  1057. {
  1058. /* Save errno before evaluation of argument functions can change it */
  1059. save_format_errnumber = errnumber;
  1060. /* Save caller's text domain */
  1061. save_format_domain = domain;
  1062. }
  1063. char *
  1064. format_elog_string(const char *fmt,...)
  1065. {
  1066. ErrorData errdata;
  1067. ErrorData *edata;
  1068. MemoryContext oldcontext;
  1069. /* Initialize a mostly-dummy error frame */
  1070. edata = &errdata;
  1071. MemSet(edata, 0, sizeof(ErrorData));
  1072. /* the default text domain is the backend's */
  1073. edata->domain = save_format_domain ? save_format_domain : PG_TEXTDOMAIN("postgres");
  1074. /* set the errno to be used to interpret %m */
  1075. edata->saved_errno = save_format_errnumber;
  1076. oldcontext = MemoryContextSwitchTo(ErrorContext);
  1077. EVALUATE_MESSAGE(message, false, true);
  1078. MemoryContextSwitchTo(oldcontext);
  1079. return edata->message;
  1080. }
  1081. /*
  1082. * Actual output of the top-of-stack error message
  1083. *
  1084. * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
  1085. * if the error is caught by somebody). For all other severity levels this
  1086. * is called by errfinish.
  1087. */
  1088. void
  1089. EmitErrorReport(void)
  1090. {
  1091. ErrorData *edata = &errordata[errordata_stack_depth];
  1092. MemoryContext oldcontext;
  1093. recursion_depth++;
  1094. CHECK_STACK_DEPTH();
  1095. oldcontext = MemoryContextSwitchTo(ErrorContext);
  1096. /*
  1097. * Call hook before sending message to log. The hook function is allowed
  1098. * to turn off edata->output_to_server, so we must recheck that afterward.
  1099. * Making any other change in the content of edata is not considered
  1100. * supported.
  1101. *
  1102. * Note: the reason why the hook can only turn off output_to_server, and
  1103. * not turn it on, is that it'd be unreliable: we will never get here at
  1104. * all if errstart() deems the message uninteresting. A hook that could
  1105. * make decisions in that direction would have to hook into errstart(),
  1106. * where it would have much less information available. emit_log_hook is
  1107. * intended for custom log filtering and custom log message transmission
  1108. * mechanisms.
  1109. */
  1110. if (edata->output_to_server && emit_log_hook)
  1111. (*emit_log_hook) (edata);
  1112. /* Send to server log, if enabled */
  1113. if (edata->output_to_server)
  1114. send_message_to_server_log(edata);
  1115. /* Send to client, if enabled */
  1116. if (edata->output_to_client)
  1117. send_message_to_frontend(edata);
  1118. MemoryContextSwitchTo(oldcontext);
  1119. recursion_depth--;
  1120. }
  1121. /*
  1122. * CopyErrorData --- obtain a copy of the topmost error stack entry
  1123. *
  1124. * This is only for use in error handler code. The data is copied into the
  1125. * current memory context, so callers should always switch away from
  1126. * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
  1127. */
  1128. ErrorData *
  1129. CopyErrorData(void)
  1130. {
  1131. ErrorData *edata = &errordata[errordata_stack_depth];
  1132. ErrorData *newedata;
  1133. /*
  1134. * we don't increment recursion_depth because out-of-memory here does not
  1135. * indicate a problem within the error subsystem.
  1136. */
  1137. CHECK_STACK_DEPTH();
  1138. Assert(CurrentMemoryContext != ErrorContext);
  1139. /* Copy the struct itself */
  1140. newedata = (ErrorData *) palloc(sizeof(ErrorData));
  1141. memcpy(newedata, edata, sizeof(ErrorData));
  1142. /* Make copies of separately-allocated fields */
  1143. if (newedata->message)
  1144. newedata->message = pstrdup(newedata->message);
  1145. if (newedata->detail)
  1146. newedata->detail = pstrdup(newedata->detail);
  1147. if (newedata->detail_log)
  1148. newedata->detail_log = pstrdup(newedata->detail_log);
  1149. if (newedata->hint)
  1150. newedata->hint = pstrdup(newedata->hint);
  1151. if (newedata->context)
  1152. newedata->context = pstrdup(newedata->context);
  1153. if (newedata->internalquery)
  1154. newedata->internalquery = pstrdup(newedata->internalquery);
  1155. return newedata;
  1156. }
  1157. /*
  1158. * FreeErrorData --- free the structure returned by CopyErrorData.
  1159. *
  1160. * Error handlers should use this in preference to assuming they know all
  1161. * the separately-allocated fields.
  1162. */
  1163. void
  1164. FreeErrorData(ErrorData *edata)
  1165. {
  1166. if (edata->message)
  1167. pfree(edata->message);
  1168. if (edata->detail)
  1169. pfree(edata->detail);
  1170. if (edata->detail_log)
  1171. pfree(edata->detail_log);
  1172. if (edata->hint)
  1173. pfree(edata->hint);
  1174. if (edata->context)
  1175. pfree(edata->context);
  1176. if (edata->internalquery)
  1177. pfree(edata->internalquery);
  1178. pfree(edata);
  1179. }
  1180. /*
  1181. * FlushErrorState --- flush the error state after error recovery
  1182. *
  1183. * This should be called by an error handler after it's done processing
  1184. * the error; or as soon as it's done CopyErrorData, if it intends to
  1185. * do stuff that is likely to provoke another error. You are not "out" of
  1186. * the error subsystem until you have done this.
  1187. */
  1188. void
  1189. FlushErrorState(void)
  1190. {
  1191. /*
  1192. * Reset stack to empty. The only case where it would be more than one
  1193. * deep is if we serviced an error that interrupted construction of
  1194. * another message. We assume control escaped out of that message
  1195. * construction and won't ever go back.
  1196. */
  1197. errordata_stack_depth = -1;
  1198. recursion_depth = 0;
  1199. /* Delete all data in ErrorContext */
  1200. MemoryContextResetAndDeleteChildren(ErrorContext);
  1201. }
  1202. /*
  1203. * ReThrowError --- re-throw a previously copied error
  1204. *
  1205. * A handler can do CopyErrorData/FlushErrorState to get out of the error
  1206. * subsystem, then do some processing, and finally ReThrowError to re-throw
  1207. * the original error. This is slower than just PG_RE_THROW() but should
  1208. * be used if the "some processing" is likely to incur another error.
  1209. */
  1210. void
  1211. ReThrowError(ErrorData *edata)
  1212. {
  1213. ErrorData *newedata;
  1214. Assert(edata->elevel == ERROR);
  1215. /* Push the data back into the error context */
  1216. recursion_depth++;
  1217. MemoryContextSwitchTo(ErrorContext);
  1218. if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
  1219. {
  1220. /*
  1221. * Wups, stack not big enough. We treat this as a PANIC condition
  1222. * because it suggests an infinite loop of errors during error
  1223. * recovery.
  1224. */
  1225. errordata_stack_depth = -1; /* make room on stack */
  1226. ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
  1227. }
  1228. newedata = &errordata[errordata_stack_depth];
  1229. memcpy(newedata, edata, sizeof(ErrorData));
  1230. /* Make copies of separately-allocated fields */
  1231. if (newedata->message)
  1232. newedata->message = pstrdup(newedata->message);
  1233. if (newedata->detail)
  1234. newedata->detail = pstrdup(newedata->detail);
  1235. if (newedata->detail_log)
  1236. newedata->detail_log = pstrdup(newedata->detail_log);
  1237. if (newedata->hint)
  1238. newedata->hint = pstrdup(newedata->hint);
  1239. if (newedata->context)
  1240. newedata->context = pstrdup(newedata->context);
  1241. if (newedata->internalquery)
  1242. newedata->internalquery = pstrdup(newedata->internalquery);
  1243. recursion_depth--;
  1244. PG_RE_THROW();
  1245. }
  1246. /*
  1247. * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
  1248. */
  1249. void
  1250. pg_re_throw(void)
  1251. {
  1252. /* If possible, throw the error to the next outer setjmp handler */
  1253. if (PG_exception_stack != NULL)
  1254. siglongjmp(*PG_exception_stack, 1);
  1255. else
  1256. {
  1257. /*
  1258. * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
  1259. * we have now exited only to discover that there is no outer setjmp
  1260. * handler to pass the error to. Had the error been thrown outside
  1261. * the block to begin with, we'd have promoted the error to FATAL, so
  1262. * the correct behavior is to make it FATAL now; that is, emit it and
  1263. * then call proc_exit.
  1264. */
  1265. ErrorData *edata = &errordata[errordata_stack_depth];
  1266. Assert(errordata_stack_depth >= 0);
  1267. Assert(edata->elevel == ERROR);
  1268. edata->elevel = FATAL;
  1269. /*
  1270. * At least in principle, the increase in severity could have changed
  1271. * where-to-output decisions, so recalculate. This should stay in
  1272. * sync with errstart(), which see for comments.
  1273. */
  1274. if (IsPostmasterEnvironment)
  1275. edata->output_to_server = is_log_level_output(FATAL,
  1276. log_min_messages);
  1277. else
  1278. edata->output_to_server = (FATAL >= log_min_messages);
  1279. if (whereToSendOutput == DestRemote)
  1280. {
  1281. if (ClientAuthInProgress)
  1282. edata->output_to_client = true;
  1283. else
  1284. edata->output_to_client = (FATAL >= client_min_messages);
  1285. }
  1286. /*
  1287. * We can use errfinish() for the rest, but we don't want it to call
  1288. * any error context routines a second time. Since we know we are
  1289. * about to exit, it should be OK to just clear the context stack.
  1290. */
  1291. error_context_stack = NULL;
  1292. errfinish(0);
  1293. }
  1294. /* Doesn't return ... */
  1295. ExceptionalCondition("pg_re_throw tried to return", "FailedAssertion",
  1296. __FILE__, __LINE__);
  1297. }
  1298. /*
  1299. * Initialization of error output file
  1300. */
  1301. void
  1302. DebugFileOpen(void)
  1303. {
  1304. int fd,
  1305. istty;
  1306. if (OutputFileName[0])
  1307. {
  1308. /*
  1309. * A debug-output file name was given.
  1310. *
  1311. * Make sure we can write the file, and find out if it's a tty.
  1312. */
  1313. if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
  1314. 0666)) < 0)
  1315. ereport(FATAL,
  1316. (errcode_for_file_access(),
  1317. errmsg("could not open file \"%s\": %m", OutputFileName)));
  1318. istty = isatty(fd);
  1319. close(fd);
  1320. /*
  1321. * Redirect our stderr to the debug output file.
  1322. */
  1323. if (!freopen(OutputFileName, "a", stderr))
  1324. ereport(FATAL,
  1325. (errcode_for_file_access(),
  1326. errmsg("could not reopen file \"%s\" as stderr: %m",
  1327. OutputFileName)));
  1328. /*
  1329. * If the file is a tty and we're running under the postmaster, try to
  1330. * send stdout there as well (if it isn't a tty then stderr will block
  1331. * out stdout, so we may as well let stdout go wherever it was going
  1332. * before).
  1333. */
  1334. if (istty && IsUnderPostmaster)
  1335. if (!freopen(OutputFileName, "a", stdout))
  1336. ereport(FATAL,
  1337. (errcode_for_file_access(),
  1338. errmsg("could not reopen file \"%s\" as stdout: %m",
  1339. OutputFileName)));
  1340. }
  1341. }
  1342. #ifdef HAVE_SYSLOG
  1343. /*
  1344. * Set or update the parameters for syslog logging
  1345. */
  1346. void
  1347. set_syslog_parameters(const char *ident, int facility)
  1348. {
  1349. /*
  1350. * guc.c is likely to call us repeatedly with same parameters, so don't
  1351. * thrash the syslog connection unnecessarily. Also, we do not re-open
  1352. * the connection until needed, since this routine will get called whether
  1353. * or not Log_destination actually mentions syslog.
  1354. *
  1355. * Note that we make our own copy of the ident string rather than relying
  1356. * on guc.c's. This may be overly paranoid, but it ensures that we cannot
  1357. * accidentally free a string that syslog is still using.
  1358. */
  1359. if (syslog_ident == NULL || strcmp(syslog_ident, ident) != 0 ||
  1360. syslog_facility != facility)
  1361. {
  1362. if (openlog_done)
  1363. {
  1364. closelog();
  1365. openlog_done = false;
  1366. }
  1367. if (syslog_ident)
  1368. free(syslog_ident);
  1369. syslog_ident = strdup(ident);
  1370. /* if the strdup fails, we will cope in write_syslog() */
  1371. syslog_facility = facility;
  1372. }
  1373. }
  1374. /*
  1375. * Write a message line to syslog
  1376. */
  1377. static void
  1378. write_syslog(int level, const char *line)
  1379. {
  1380. static unsigned long seq = 0;
  1381. int len;
  1382. const char *nlpos;
  1383. /* Open syslog connection if not done yet */
  1384. if (!openlog_done)
  1385. {
  1386. openlog(syslog_ident ? syslog_ident : "postgres",
  1387. LOG_PID | LOG_NDELAY | LOG_NOWAIT,
  1388. syslog_facility);
  1389. openlog_done = true;
  1390. }
  1391. /*
  1392. * We add a sequence number to each log message to suppress "same"
  1393. * messages.
  1394. */
  1395. seq++;
  1396. /*
  1397. * Our problem here is that many syslog implementations don't handle long
  1398. * messages in an acceptable manner. While this function doesn't help that
  1399. * fact, it does work around by splitting up messages into smaller pieces.
  1400. *
  1401. * We divide into multiple syslog() calls if message is too long or if the
  1402. * message contains embedded newline(s).
  1403. */
  1404. len = strlen(line);
  1405. nlpos = strchr(line, '\n');
  1406. if (len > PG_SYSLOG_LIMIT || nlpos != NULL)
  1407. {
  1408. int chunk_nr = 0;
  1409. while (len > 0)
  1410. {
  1411. char buf[PG_SYSLOG_LIMIT + 1];
  1412. int buflen;
  1413. int i;
  1414. /* if we start at a newline, move ahead one char */
  1415. if (line[0] == '\n')
  1416. {
  1417. line++;
  1418. len--;
  1419. /* we need to recompute the next newline's position, too */
  1420. nlpos = strchr(line, '\n');
  1421. continue;
  1422. }
  1423. /* copy one line, or as much as will fit, to buf */
  1424. if (nlpos != NULL)
  1425. buflen = nlpos - line;
  1426. else
  1427. buflen = len;
  1428. buflen = Min(buflen, PG_SYSLOG_LIMIT);
  1429. memcpy(buf, line, buflen);
  1430. buf[buflen] = '\0';
  1431. /* trim to multibyte letter boundary */
  1432. buflen = pg_mbcliplen(buf, buflen, buflen);
  1433. if (buflen <= 0)
  1434. return;
  1435. buf[buflen] = '\0';
  1436. /* already word boundary? */
  1437. if (line[buflen] != '\0' &&
  1438. !isspace((unsigned char) line[buflen]))
  1439. {
  1440. /* try to divide at word boundary */
  1441. i = buflen - 1;
  1442. while (i > 0 && !isspace((unsigned char) buf[i]))
  1443. i--;
  1444. if (i > 0) /* else couldn't divide word boundary */
  1445. {
  1446. buflen = i;
  1447. buf[i] = '\0';
  1448. }
  1449. }
  1450. chunk_nr++;
  1451. syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
  1452. line += buflen;
  1453. len -= buflen;
  1454. }
  1455. }
  1456. else
  1457. {
  1458. /* message short enough */
  1459. syslog(level, "[%lu] %s", seq, line);
  1460. }
  1461. }
  1462. #endif /* HAVE_SYSLOG */
  1463. #ifdef WIN32
  1464. /*
  1465. * Write a message line to the windows event log
  1466. */
  1467. static void
  1468. write_eventlog(int level, const char *line, int len)
  1469. {
  1470. WCHAR *utf16;
  1471. int eventlevel = EVENTLOG_ERROR_TYPE;
  1472. static HANDLE evtHandle = INVALID_HANDLE_VALUE;
  1473. if (evtHandle == INVALID_HANDLE_VALUE)
  1474. {
  1475. evtHandle = RegisterEventSource(NULL, event_source ? event_source : "PostgreSQL");
  1476. if (evtHandle == NULL)
  1477. {
  1478. evtHandle = INVALID_HANDLE_VALUE;
  1479. return;
  1480. }
  1481. }
  1482. switch (level)
  1483. {
  1484. case DEBUG5:
  1485. case DEBUG4:
  1486. case DEBUG3:
  1487. case DEBUG2:
  1488. case DEBUG1:
  1489. case LOG:
  1490. case COMMERROR:
  1491. case INFO:
  1492. case NOTICE:
  1493. eventlevel = EVENTLOG_INFORMATION_TYPE;
  1494. break;
  1495. case WARNING:
  1496. eventlevel = EVENTLOG_WARNING_TYPE;
  1497. break;
  1498. case ERROR:
  1499. case FATAL:
  1500. case PANIC:
  1501. default:
  1502. eventlevel = EVENTLOG_ERROR_TYPE;
  1503. break;
  1504. }
  1505. /*
  1506. * Convert message to UTF16 text and write it with ReportEventW, but
  1507. * fall-back into ReportEventA if conversion failed.
  1508. *
  1509. * Also verify that we are not on our way into error recursion trouble due
  1510. * to error messages thrown deep inside pgwin32_toUTF16().
  1511. */
  1512. if (GetDatabaseEncoding() != GetPlatformEncoding() &&
  1513. !in_error_recursion_trouble())
  1514. {
  1515. utf16 = pgwin32_toUTF16(line, len, NULL);
  1516. if (utf16)
  1517. {
  1518. ReportEventW(evtHandle,
  1519. eventlevel,
  1520. 0,
  1521. 0, /* All events are Id 0 */
  1522. NULL,
  1523. 1,
  1524. 0,
  1525. (LPCWSTR *) &utf16,
  1526. NULL);
  1527. pfree(utf16);
  1528. return;
  1529. }
  1530. }
  1531. ReportEventA(evtHandle,
  1532. eventlevel,
  1533. 0,
  1534. 0, /* All events are Id 0 */
  1535. NULL,
  1536. 1,
  1537. 0,
  1538. &line,
  1539. NULL);
  1540. }
  1541. #endif /* WIN32 */
  1542. static void
  1543. write_console(const char *line, int len)
  1544. {
  1545. int rc;
  1546. #ifdef WIN32
  1547. /*
  1548. * WriteConsoleW() will fail if stdout is redirected, so just fall through
  1549. * to writing unconverted to the logfile in thiā€¦

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