PageRenderTime 92ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/definex/4707
C | 2979 lines | 1696 code | 397 blank | 886 comment | 317 complexity | b7ef106a34096bc391138ad9b511de79 MD5 | raw file
Possible License(s): AGPL-3.0
  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 this case.
  1550. *
  1551. * Since we palloc the structure required for conversion, also fall
  1552. * through to writing unconverted if we have not yet set up
  1553. * CurrentMemoryContext.
  1554. */
  1555. if (GetDatabaseEncoding() != GetPlatformEncoding() &&
  1556. !in_error_recursion_trouble() &&
  1557. !redirection_done &&
  1558. CurrentMemoryContext != NULL)
  1559. {
  1560. WCHAR *utf16;
  1561. int utf16len;
  1562. utf16 = pgwin32_toUTF16(line, len, &utf16len);
  1563. if (utf16 != NULL)
  1564. {
  1565. HANDLE stdHandle;
  1566. DWORD written;
  1567. stdHandle = GetStdHandle(STD_ERROR_HANDLE);
  1568. if (WriteConsoleW(stdHandle, utf16, utf16len, &written, NULL))
  1569. {
  1570. pfree(utf16);
  1571. return;
  1572. }
  1573. /*
  1574. * In case WriteConsoleW() failed, fall back to writing the
  1575. * message unconverted.
  1576. */
  1577. pfree(utf16);
  1578. }
  1579. }
  1580. #else
  1581. /*
  1582. * Conversion on non-win32 platforms is not implemented yet. It requires
  1583. * non-throw version of pg_do_encoding_conversion(), that converts
  1584. * unconvertable characters to '?' without errors.
  1585. */
  1586. #endif
  1587. /*
  1588. * We ignore any error from write() here. We have no useful way to report
  1589. * it ... certainly whining on stderr isn't likely to be productive.
  1590. */
  1591. rc = write(fileno(stderr), line, len);
  1592. (void) rc;
  1593. }
  1594. /*
  1595. * setup formatted_log_time, for consistent times between CSV and regular logs
  1596. */
  1597. static void
  1598. setup_formatted_log_time(void)
  1599. {
  1600. struct timeval tv;
  1601. pg_time_t stamp_time;
  1602. char msbuf[8];
  1603. gettimeofday(&tv, NULL);
  1604. stamp_time = (pg_time_t) tv.tv_sec;
  1605. /*
  1606. * Note: we expect that guc.c will ensure that log_timezone is set up (at
  1607. * least with a minimal GMT value) before Log_line_prefix can become
  1608. * nonempty or CSV mode can be selected.
  1609. */
  1610. pg_strftime(formatted_log_time, FORMATTED_TS_LEN,
  1611. /* leave room for milliseconds... */
  1612. "%Y-%m-%d %H:%M:%S %Z",
  1613. pg_localtime(&stamp_time, log_timezone));
  1614. /* 'paste' milliseconds into place... */
  1615. sprintf(msbuf, ".%03d", (int) (tv.tv_usec / 1000));
  1616. strncpy(formatted_log_time + 19, msbuf, 4);
  1617. }
  1618. /*
  1619. * setup formatted_start_time
  1620. */
  1621. static void
  1622. setup_formatted_start_time(void)
  1623. {
  1624. pg_time_t stamp_time = (pg_time_t) MyStartTime;
  1625. /*
  1626. * Note: we expect that guc.c will ensure that log_timezone is set up (at
  1627. * least with a minimal GMT value) before Log_line_prefix can become
  1628. * nonempty or CSV mode can be selected.
  1629. */
  1630. pg_strftime(formatted_start_time, FORMATTED_TS_LEN,
  1631. "%Y-%m-%d %H:%M:%S %Z",
  1632. pg_localtime(&stamp_time, log_timezone));
  1633. }
  1634. /*
  1635. * Format tag info for log lines; append to the provided buffer.
  1636. */
  1637. static void
  1638. log_line_prefix(StringInfo buf, ErrorData *edata)
  1639. {
  1640. /* static counter for line numbers */
  1641. static long log_line_number = 0;
  1642. /* has counter been reset in current process? */
  1643. static int log_my_pid = 0;
  1644. int format_len;
  1645. int i;
  1646. /*
  1647. * This is one of the few places where we'd rather not inherit a static
  1648. * variable's value from the postmaster. But since we will, reset it when
  1649. * MyProcPid changes. MyStartTime also changes when MyProcPid does, so
  1650. * reset the formatted start timestamp too.
  1651. */
  1652. if (log_my_pid != MyProcPid)
  1653. {
  1654. log_line_number = 0;
  1655. log_my_pid = MyProcPid;
  1656. formatted_start_time[0] = '\0';
  1657. }
  1658. log_line_number++;
  1659. if (Log_line_prefix == NULL)
  1660. return; /* in case guc hasn't run yet */
  1661. format_len = strlen(Log_line_prefix);
  1662. for (i = 0; i < format_len; i++)
  1663. {
  1664. if (Log_line_prefix[i] != '%')
  1665. {
  1666. /* literal char, just copy */
  1667. appendStringInfoChar(buf, Log_line_prefix[i]);
  1668. continue;
  1669. }
  1670. /* go to char after '%' */
  1671. i++;
  1672. if (i >= format_len)
  1673. break; /* format error - ignore it */
  1674. /* process the option */
  1675. switch (Log_line_prefix[i])
  1676. {
  1677. case 'a':
  1678. if (MyProcPort)
  1679. {
  1680. const char *appname = application_name;
  1681. if (appname == NULL || *appname == '\0')
  1682. appname = _("[unknown]");
  1683. appendStringInfoString(buf, appname);
  1684. }
  1685. break;
  1686. case 'u':
  1687. if (MyProcPort)
  1688. {
  1689. const char *username = MyProcPort->user_name;
  1690. if (username == NULL || *username == '\0')
  1691. username = _("[unknown]");
  1692. appendStringInfoString(buf, username);
  1693. }
  1694. break;
  1695. case 'd':
  1696. if (MyProcPort)
  1697. {
  1698. const char *dbname = MyProcPort->database_name;
  1699. if (dbname == NULL || *dbname == '\0')
  1700. dbname = _("[unknown]");
  1701. appendStringInfoString(buf, dbname);
  1702. }
  1703. break;
  1704. case 'c':
  1705. appendStringInfo(buf, "%lx.%x", (long) (MyStartTime), MyProcPid);
  1706. break;
  1707. case 'p':
  1708. appendStringInfo(buf, "%d", MyProcPid);
  1709. break;
  1710. case 'l':
  1711. appendStringInfo(buf, "%ld", log_line_number);
  1712. break;
  1713. case 'm':
  1714. setup_formatted_log_time();
  1715. appendStringInfoString(buf, formatted_log_time);
  1716. break;
  1717. case 't':
  1718. {
  1719. pg_time_t stamp_time = (pg_time_t) time(NULL);
  1720. char strfbuf[128];
  1721. pg_strftime(strfbuf, sizeof(strfbuf),
  1722. "%Y-%m-%d %H:%M:%S %Z",
  1723. pg_localtime(&stamp_time, log_timezone));
  1724. appendStringInfoString(buf, strfbuf);
  1725. }
  1726. break;
  1727. case 's':
  1728. if (formatted_start_time[0] == '\0')
  1729. setup_formatted_start_time();
  1730. appendStringInfoString(buf, formatted_start_time);
  1731. break;
  1732. case 'i':
  1733. if (MyProcPort)
  1734. {
  1735. const char *psdisp;
  1736. int displen;
  1737. psdisp = get_ps_display(&displen);
  1738. appendBinaryStringInfo(buf, psdisp, displen);
  1739. }
  1740. break;
  1741. case 'r':
  1742. if (MyProcPort && MyProcPort->remote_host)
  1743. {
  1744. appendStringInfoString(buf, MyProcPort->remote_host);
  1745. if (MyProcPort->remote_port &&
  1746. MyProcPort->remote_port[0] != '\0')
  1747. appendStringInfo(buf, "(%s)",
  1748. MyProcPort->remote_port);
  1749. }
  1750. break;
  1751. case 'h':
  1752. if (MyProcPort && MyProcPort->remote_host)
  1753. appendStringInfoString(buf, MyProcPort->remote_host);
  1754. break;
  1755. case 'q':
  1756. /* in postmaster and friends, stop if %q is seen */
  1757. /* in a backend, just ignore */
  1758. if (MyProcPort == NULL)
  1759. i = format_len;
  1760. break;
  1761. case 'v':
  1762. /* keep VXID format in sync with lockfuncs.c */
  1763. if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
  1764. appendStringInfo(buf, "%d/%u",
  1765. MyProc->backendId, MyProc->lxid);
  1766. break;
  1767. case 'x':
  1768. appendStringInfo(buf, "%u", GetTopTransactionIdIfAny());
  1769. break;
  1770. case 'e':
  1771. appendStringInfoString(buf, unpack_sql_state(edata->sqlerrcode));
  1772. break;
  1773. case '%':
  1774. appendStringInfoChar(buf, '%');
  1775. break;
  1776. default:
  1777. /* format error - ignore it */
  1778. break;
  1779. }
  1780. }
  1781. }
  1782. /*
  1783. * append a CSV'd version of a string to a StringInfo
  1784. * We use the PostgreSQL defaults for CSV, i.e. quote = escape = '"'
  1785. * If it's NULL, append nothing.
  1786. */
  1787. static inline void
  1788. appendCSVLiteral(StringInfo buf, const char *data)
  1789. {
  1790. const char *p = data;
  1791. char c;
  1792. /* avoid confusing an empty string with NULL */
  1793. if (p == NULL)
  1794. return;
  1795. appendStringInfoCharMacro(buf, '"');
  1796. while ((c = *p++) != '\0')
  1797. {
  1798. if (c == '"')
  1799. appendStringInfoCharMacro(buf, '"');
  1800. appendStringInfoCharMacro(buf, c);
  1801. }
  1802. appendStringInfoCharMacro(buf, '"');
  1803. }
  1804. /*
  1805. * Constructs the error message, depending on the Errordata it gets, in a CSV
  1806. * format which is described in doc/src/sgml/config.sgml.
  1807. */
  1808. static void
  1809. write_csvlog(ErrorData *edata)
  1810. {
  1811. StringInfoData buf;
  1812. bool print_stmt = false;
  1813. /* static counter for line numbers */
  1814. static long log_line_number = 0;
  1815. /* has counter been reset in current process? */
  1816. static int log_my_pid = 0;
  1817. /*
  1818. * This is one of the few places where we'd rather not inherit a static
  1819. * variable's value from the postmaster. But since we will, reset it when
  1820. * MyProcPid changes.
  1821. */
  1822. if (log_my_pid != MyProcPid)
  1823. {
  1824. log_line_number = 0;
  1825. log_my_pid = MyProcPid;
  1826. formatted_start_time[0] = '\0';
  1827. }
  1828. log_line_number++;
  1829. initStringInfo(&buf);
  1830. /*
  1831. * timestamp with milliseconds
  1832. *
  1833. * Check if the timestamp is already calculated for the syslog message,
  1834. * and use it if so. Otherwise, get the current timestamp. This is done
  1835. * to put same timestamp in both syslog and csvlog messages.
  1836. */
  1837. if (formatted_log_time[0] == '\0')
  1838. setup_formatted_log_time();
  1839. appendStringInfoString(&buf, formatted_log_time);
  1840. appendStringInfoChar(&buf, ',');
  1841. /* username */
  1842. if (MyProcPort)
  1843. appendCSVLiteral(&buf, MyProcPort->user_name);
  1844. appendStringInfoChar(&buf, ',');
  1845. /* database name */
  1846. if (MyProcPort)
  1847. appendCSVLiteral(&buf, MyProcPort->database_name);
  1848. appendStringInfoChar(&buf, ',');
  1849. /* Process id */
  1850. if (MyProcPid != 0)
  1851. appendStringInfo(&buf, "%d", MyProcPid);
  1852. appendStringInfoChar(&buf, ',');
  1853. /* Remote host and port */
  1854. if (MyProcPort && MyProcPort->remote_host)
  1855. {
  1856. appendStringInfoChar(&buf, '"');
  1857. appendStringInfoString(&buf, MyProcPort->remote_host);
  1858. if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
  1859. {
  1860. appendStringInfoChar(&buf, ':');
  1861. appendStringInfoString(&buf, MyProcPort->remote_port);
  1862. }
  1863. appendStringInfoChar(&buf, '"');
  1864. }
  1865. appendStringInfoChar(&buf, ',');
  1866. /* session id */
  1867. appendStringInfo(&buf, "%lx.%x", (long) MyStartTime, MyProcPid);
  1868. appendStringInfoChar(&buf, ',');
  1869. /* Line number */
  1870. appendStringInfo(&buf, "%ld", log_line_number);
  1871. appendStringInfoChar(&buf, ',');
  1872. /* PS display */
  1873. if (MyProcPort)
  1874. {
  1875. StringInfoData msgbuf;
  1876. const char *psdisp;
  1877. int displen;
  1878. initStringInfo(&msgbuf);
  1879. psdisp = get_ps_display(&displen);
  1880. appendBinaryStringInfo(&msgbuf, psdisp, displen);
  1881. appendCSVLiteral(&buf, msgbuf.data);
  1882. pfree(msgbuf.data);
  1883. }
  1884. appendStringInfoChar(&buf, ',');
  1885. /* session start timestamp */
  1886. if (formatted_start_time[0] == '\0')
  1887. setup_formatted_start_time();
  1888. appendStringInfoString(&buf, formatted_start_time);
  1889. appendStringInfoChar(&buf, ',');
  1890. /* Virtual transaction id */
  1891. /* keep VXID format in sync with lockfuncs.c */
  1892. if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
  1893. appendStringInfo(&buf, "%d/%u", MyProc->backendId, MyProc->lxid);
  1894. appendStringInfoChar(&buf, ',');
  1895. /* Transaction id */
  1896. appendStringInfo(&buf, "%u", GetTopTransactionIdIfAny());
  1897. appendStringInfoChar(&buf, ',');
  1898. /* Error severity */
  1899. appendStringInfoString(&buf, error_severity(edata->elevel));
  1900. appendStringInfoChar(&buf, ',');
  1901. /* SQL state code */
  1902. appendStringInfoString(&buf, unpack_sql_state(edata->sqlerrcode));
  1903. appendStringInfoChar(&buf, ',');
  1904. /* errmessage */
  1905. appendCSVLiteral(&buf, edata->message);
  1906. appendStringInfoChar(&buf, ',');
  1907. /* errdetail or errdetail_log */
  1908. if (edata->detail_log)
  1909. appendCSVLiteral(&buf, edata->detail_log);
  1910. else
  1911. appendCSVLiteral(&buf, edata->detail);
  1912. appendStringInfoChar(&buf, ',');
  1913. /* errhint */
  1914. appendCSVLiteral(&buf, edata->hint);
  1915. appendStringInfoChar(&buf, ',');
  1916. /* internal query */
  1917. appendCSVLiteral(&buf, edata->internalquery);
  1918. appendStringInfoChar(&buf, ',');
  1919. /* if printed internal query, print internal pos too */
  1920. if (edata->internalpos > 0 && edata->internalquery != NULL)
  1921. appendStringInfo(&buf, "%d", edata->internalpos);
  1922. appendStringInfoChar(&buf, ',');
  1923. /* errcontext */
  1924. appendCSVLiteral(&buf, edata->context);
  1925. appendStringInfoChar(&buf, ',');
  1926. /* user query --- only reported if not disabled by the caller */
  1927. if (is_log_level_output(edata->elevel, log_min_error_statement) &&
  1928. debug_query_string != NULL &&
  1929. !edata->hide_stmt)
  1930. print_stmt = true;
  1931. if (print_stmt)
  1932. appendCSVLiteral(&buf, debug_query_string);
  1933. appendStringInfoChar(&buf, ',');
  1934. if (print_stmt && edata->cursorpos > 0)
  1935. appendStringInfo(&buf, "%d", edata->cursorpos);
  1936. appendStringInfoChar(&buf, ',');
  1937. /* file error location */
  1938. if (Log_error_verbosity >= PGERROR_VERBOSE)
  1939. {
  1940. StringInfoData msgbuf;
  1941. initStringInfo(&msgbuf);
  1942. if (edata->funcname && edata->filename)
  1943. appendStringInfo(&msgbuf, "%s, %s:%d",
  1944. edata->funcname, edata->filename,
  1945. edata->lineno);
  1946. else if (edata->filename)
  1947. appendStringInfo(&msgbuf, "%s:%d",
  1948. edata->filename, edata->lineno);
  1949. appendCSVLiteral(&buf, msgbuf.data);
  1950. pfree(msgbuf.data);
  1951. }
  1952. appendStringInfoChar(&buf, ',');
  1953. /* application name */
  1954. if (application_name)
  1955. appendCSVLiteral(&buf, application_name);
  1956. appendStringInfoChar(&buf, '\n');
  1957. /* If in the syslogger process, try to write messages direct to file */
  1958. if (am_syslogger)
  1959. write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
  1960. else
  1961. write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
  1962. pfree(buf.data);
  1963. }
  1964. /*
  1965. * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
  1966. * static buffer.
  1967. */
  1968. char *
  1969. unpack_sql_state(int sql_state)
  1970. {
  1971. static char buf[12];
  1972. int i;
  1973. for (i = 0; i < 5; i++)
  1974. {
  1975. buf[i] = PGUNSIXBIT(sql_state);
  1976. sql_state >>= 6;
  1977. }
  1978. buf[i] = '\0';
  1979. return buf;
  1980. }
  1981. /*
  1982. * Write error report to server's log
  1983. */
  1984. static void
  1985. send_message_to_server_log(ErrorData *edata)
  1986. {
  1987. StringInfoData buf;
  1988. initStringInfo(&buf);
  1989. formatted_log_time[0] = '\0';
  1990. log_line_prefix(&buf, edata);
  1991. appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
  1992. if (Log_error_verbosity >= PGERROR_VERBOSE)
  1993. appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
  1994. if (edata->message)
  1995. append_with_tabs(&buf, edata->message);
  1996. else
  1997. append_with_tabs(&buf, _("missing error text"));
  1998. if (edata->cursorpos > 0)
  1999. appendStringInfo(&buf, _(" at character %d"),
  2000. edata->cursorpos);
  2001. else if (edata->internalpos > 0)
  2002. appendStringInfo(&buf, _(" at character %d"),
  2003. edata->internalpos);
  2004. appendStringInfoChar(&buf, '\n');
  2005. if (Log_error_verbosity >= PGERROR_DEFAULT)
  2006. {
  2007. if (edata->detail_log)
  2008. {
  2009. log_line_prefix(&buf, edata);
  2010. appendStringInfoString(&buf, _("DETAIL: "));
  2011. append_with_tabs(&buf, edata->detail_log);
  2012. appendStringInfoChar(&buf, '\n');
  2013. }
  2014. else if (edata->detail)
  2015. {
  2016. log_line_prefix(&buf, edata);
  2017. appendStringInfoString(&buf, _("DETAIL: "));
  2018. append_with_tabs(&buf, edata->detail);
  2019. appendStringInfoChar(&buf, '\n');
  2020. }
  2021. if (edata->hint)
  2022. {
  2023. log_line_prefix(&buf, edata);
  2024. appendStringInfoString(&buf, _("HINT: "));
  2025. append_with_tabs(&buf, edata->hint);
  2026. appendStringInfoChar(&buf, '\n');
  2027. }
  2028. if (edata->internalquery)
  2029. {
  2030. log_line_prefix(&buf, edata);
  2031. appendStringInfoString(&buf, _("QUERY: "));
  2032. append_with_tabs(&buf, edata->internalquery);
  2033. appendStringInfoChar(&buf, '\n');
  2034. }
  2035. if (edata->context)
  2036. {
  2037. log_line_prefix(&buf, edata);
  2038. appendStringInfoString(&buf, _("CONTEXT: "));
  2039. append_with_tabs(&buf, edata->context);
  2040. appendStringInfoChar(&buf, '\n');
  2041. }
  2042. if (Log_error_verbosity >= PGERROR_VERBOSE)
  2043. {
  2044. /* assume no newlines in funcname or filename... */
  2045. if (edata->funcname && edata->filename)
  2046. {
  2047. log_line_prefix(&buf, edata);
  2048. appendStringInfo(&buf, _("LOCATION: %s, %s:%d\n"),
  2049. edata->funcname, edata->filename,
  2050. edata->lineno);
  2051. }
  2052. else if (edata->filename)
  2053. {
  2054. log_line_prefix(&buf, edata);
  2055. appendStringInfo(&buf, _("LOCATION: %s:%d\n"),
  2056. edata->filename, edata->lineno);
  2057. }
  2058. }
  2059. }
  2060. /*
  2061. * If the user wants the query that generated this error logged, do it.
  2062. */
  2063. if (is_log_level_output(edata->elevel, log_min_error_statement) &&
  2064. debug_query_string != NULL &&
  2065. !edata->hide_stmt)
  2066. {
  2067. log_line_prefix(&buf, edata);
  2068. appendStringInfoString(&buf, _("STATEMENT: "));
  2069. append_with_tabs(&buf, debug_query_string);
  2070. appendStringInfoChar(&buf, '\n');
  2071. }
  2072. #ifdef HAVE_SYSLOG
  2073. /* Write to syslog, if enabled */
  2074. if (Log_destination & LOG_DESTINATION_SYSLOG)
  2075. {
  2076. int syslog_level;
  2077. switch (edata->elevel)
  2078. {
  2079. case DEBUG5:
  2080. case DEBUG4:
  2081. case DEBUG3:
  2082. case DEBUG2:
  2083. case DEBUG1:
  2084. syslog_level = LOG_DEBUG;
  2085. break;
  2086. case LOG:
  2087. case COMMERROR:
  2088. case INFO:
  2089. syslog_level = LOG_INFO;
  2090. break;
  2091. case NOTICE:
  2092. case WARNING:
  2093. syslog_level = LOG_NOTICE;
  2094. break;
  2095. case ERROR:
  2096. syslog_level = LOG_WARNING;
  2097. break;
  2098. case FATAL:
  2099. syslog_level = LOG_ERR;
  2100. break;
  2101. case PANIC:
  2102. default:
  2103. syslog_level = LOG_CRIT;
  2104. break;
  2105. }
  2106. write_syslog(syslog_level, buf.data);
  2107. }
  2108. #endif /* HAVE_SYSLOG */
  2109. #ifdef WIN32
  2110. /* Write to eventlog, if enabled */
  2111. if (Log_destination & LOG_DESTINATION_EVENTLOG)
  2112. {
  2113. write_eventlog(edata->elevel, buf.data, buf.len);
  2114. }
  2115. #endif /* WIN32 */
  2116. /* Write to stderr, if enabled */
  2117. if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == DestDebug)
  2118. {
  2119. /*
  2120. * Use the chunking protocol if we know the syslogger should be
  2121. * catching stderr output, and we are not ourselves the syslogger.
  2122. * Otherwise, just do a vanilla write to stderr.
  2123. */
  2124. if (redirection_done && !am_syslogger)
  2125. write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_STDERR);
  2126. #ifdef WIN32
  2127. /*
  2128. * In a win32 service environment, there is no usable stderr. Capture
  2129. * anything going there and write it to the eventlog instead.
  2130. *
  2131. * If stderr redirection is active, it was OK to write to stderr above
  2132. * because that's really a pipe to the syslogger process.
  2133. */
  2134. else if (pgwin32_is_service())
  2135. write_eventlog(edata->elevel, buf.data, buf.len);
  2136. #endif
  2137. else
  2138. write_console(buf.data, buf.len);
  2139. }
  2140. /* If in the syslogger process, try to write messages direct to file */
  2141. if (am_syslogger)
  2142. write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_STDERR);
  2143. /* Write to CSV log if enabled */
  2144. if (Log_destination & LOG_DESTINATION_CSVLOG)
  2145. {
  2146. if (redirection_done || am_syslogger)
  2147. {
  2148. /*
  2149. * send CSV data if it's safe to do so (syslogger doesn't need the
  2150. * pipe). First get back the space in the message buffer.
  2151. */
  2152. pfree(buf.data);
  2153. write_csvlog(edata);
  2154. }
  2155. else
  2156. {
  2157. /*
  2158. * syslogger not up (yet), so just dump the message to stderr,
  2159. * unless we already did so above.
  2160. */
  2161. if (!(Log_destination & LOG_DESTINATION_STDERR) &&
  2162. whereToSendOutput != DestDebug)
  2163. write_console(buf.data, buf.len);
  2164. pfree(buf.data);
  2165. }
  2166. }
  2167. else
  2168. {
  2169. pfree(buf.data);
  2170. }
  2171. }
  2172. /*
  2173. * Send data to the syslogger using the chunked protocol
  2174. *
  2175. * Note: when there are multiple backends writing into the syslogger pipe,
  2176. * it's critical that each write go into the pipe indivisibly, and not
  2177. * get interleaved with data from other processes. Fortunately, the POSIX
  2178. * spec requires that writes to pipes be atomic so long as they are not
  2179. * more than PIPE_BUF bytes long. So we divide long messages into chunks
  2180. * that are no more than that length, and send one chunk per write() call.
  2181. * The collector process knows how to reassemble the chunks.
  2182. *
  2183. * Because of the atomic write requirement, there are only two possible
  2184. * results from write() here: -1 for failure, or the requested number of
  2185. * bytes. There is not really anything we can do about a failure; retry would
  2186. * probably be an infinite loop, and we can't even report the error usefully.
  2187. * (There is noplace else we could send it!) So we might as well just ignore
  2188. * the result from write(). However, on some platforms you get a compiler
  2189. * warning from ignoring write()'s result, so do a little dance with casting
  2190. * rc to void to shut up the compiler.
  2191. */
  2192. static void
  2193. write_pipe_chunks(char *data, int len, int dest)
  2194. {
  2195. PipeProtoChunk p;
  2196. int fd = fileno(stderr);
  2197. int rc;
  2198. Assert(len > 0);
  2199. p.proto.nuls[0] = p.proto.nuls[1] = '\0';
  2200. p.proto.pid = MyProcPid;
  2201. /* write all but the last chunk */
  2202. while (len > PIPE_MAX_PAYLOAD)
  2203. {
  2204. p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'F' : 'f');
  2205. p.proto.len = PIPE_MAX_PAYLOAD;
  2206. memcpy(p.proto.data, data, PIPE_MAX_PAYLOAD);
  2207. rc = write(fd, &p, PIPE_HEADER_SIZE + PIPE_MAX_PAYLOAD);
  2208. (void) rc;
  2209. data += PIPE_MAX_PAYLOAD;
  2210. len -= PIPE_MAX_PAYLOAD;
  2211. }
  2212. /* write the last chunk */
  2213. p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'T' : 't');
  2214. p.proto.len = len;
  2215. memcpy(p.proto.data, data, len);
  2216. rc = write(fd, &p, PIPE_HEADER_SIZE + len);
  2217. (void) rc;
  2218. }
  2219. /*
  2220. * Append a text string to the error report being built for the client.
  2221. *
  2222. * This is ordinarily identical to pq_sendstring(), but if we are in
  2223. * error recursion trouble we skip encoding conversion, because of the
  2224. * possibility that the problem is a failure in the encoding conversion
  2225. * subsystem itself. Code elsewhere should ensure that the passed-in
  2226. * strings will be plain 7-bit ASCII, and thus not in need of conversion,
  2227. * in such cases. (In particular, we disable localization of error messages
  2228. * to help ensure that's true.)
  2229. */
  2230. static void
  2231. err_sendstring(StringInfo buf, const char *str)
  2232. {
  2233. if (in_error_recursion_trouble())
  2234. pq_send_ascii_string(buf, str);
  2235. else
  2236. pq_sendstring(buf, str);
  2237. }
  2238. /*
  2239. * Write error report to client
  2240. */
  2241. static void
  2242. send_message_to_frontend(ErrorData *edata)
  2243. {
  2244. StringInfoData msgbuf;
  2245. /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
  2246. pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
  2247. if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
  2248. {
  2249. /* New style with separate fields */
  2250. char tbuf[12];
  2251. int ssval;
  2252. int i;
  2253. pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
  2254. err_sendstring(&msgbuf, error_severity(edata->elevel));
  2255. /* unpack MAKE_SQLSTATE code */
  2256. ssval = edata->sqlerrcode;
  2257. for (i = 0; i < 5; i++)
  2258. {
  2259. tbuf[i] = PGUNSIXBIT(ssval);
  2260. ssval >>= 6;
  2261. }
  2262. tbuf[i] = '\0';
  2263. pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
  2264. err_sendstring(&msgbuf, tbuf);
  2265. /* M field is required per protocol, so always send something */
  2266. pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
  2267. if (edata->message)
  2268. err_sendstring(&msgbuf, edata->message);
  2269. else
  2270. err_sendstring(&msgbuf, _("missing error text"));
  2271. if (edata->detail)
  2272. {
  2273. pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
  2274. err_sendstring(&msgbuf, edata->detail);
  2275. }
  2276. /* detail_log is intentionally not used here */
  2277. if (edata->hint)
  2278. {
  2279. pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
  2280. err_sendstring(&msgbuf, edata->hint);
  2281. }
  2282. if (edata->context)
  2283. {
  2284. pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
  2285. err_sendstring(&msgbuf, edata->context);
  2286. }
  2287. if (edata->cursorpos > 0)
  2288. {
  2289. snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
  2290. pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
  2291. err_sendstring(&msgbuf, tbuf);
  2292. }
  2293. if (edata->internalpos > 0)
  2294. {
  2295. snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
  2296. pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
  2297. err_sendstring(&msgbuf, tbuf);
  2298. }
  2299. if (edata->internalquery)
  2300. {
  2301. pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
  2302. err_sendstring(&msgbuf, edata->internalquery);
  2303. }
  2304. if (edata->filename)
  2305. {
  2306. pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
  2307. err_sendstring(&msgbuf, edata->filename);
  2308. }
  2309. if (edata->lineno > 0)
  2310. {
  2311. snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
  2312. pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
  2313. err_sendstring(&msgbuf, tbuf);
  2314. }
  2315. if (edata->funcname)
  2316. {
  2317. pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
  2318. err_sendstring(&msgbuf, edata->funcname);
  2319. }
  2320. pq_sendbyte(&msgbuf, '\0'); /* terminator */
  2321. }
  2322. else
  2323. {
  2324. /* Old style --- gin up a backwards-compatible message */
  2325. StringInfoData buf;
  2326. initStringInfo(&buf);
  2327. appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
  2328. if (edata->show_funcname && edata->funcname)
  2329. appendStringInfo(&buf, "%s: ", edata->funcname);
  2330. if (edata->message)
  2331. appendStringInfoString(&buf, edata->message);
  2332. else
  2333. appendStringInfoString(&buf, _("missing error text"));
  2334. if (edata->cursorpos > 0)
  2335. appendStringInfo(&buf, _(" at character %d"),
  2336. edata->cursorpos);
  2337. else if (edata->internalpos > 0)
  2338. appendStringInfo(&buf, _(" at character %d"),
  2339. edata->internalpos);
  2340. appendStringInfoChar(&buf, '\n');
  2341. err_sendstring(&msgbuf, buf.data);
  2342. pfree(buf.data);
  2343. }
  2344. pq_endmessage(&msgbuf);
  2345. /*
  2346. * This flush is normally not necessary, since postgres.c will flush out
  2347. * waiting data when control returns to the main loop. But it seems best
  2348. * to leave it here, so that the client has some clue what happened if the
  2349. * backend dies before getting back to the main loop ... error/notice
  2350. * messages should not be a performance-critical path anyway, so an extra
  2351. * flush won't hurt much ...
  2352. */
  2353. pq_flush();
  2354. }
  2355. /*
  2356. * Support routines for formatting error messages.
  2357. */
  2358. /*
  2359. * expand_fmt_string --- process special format codes in a format string
  2360. *
  2361. * We must replace %m with the appropriate strerror string, since vsnprintf
  2362. * won't know what to do with it.
  2363. *
  2364. * The result is a palloc'd string.
  2365. */
  2366. static char *
  2367. expand_fmt_string(const char *fmt, ErrorData *edata)
  2368. {
  2369. StringInfoData buf;
  2370. const char *cp;
  2371. initStringInfo(&buf);
  2372. for (cp = fmt; *cp; cp++)
  2373. {
  2374. if (cp[0] == '%' && cp[1] != '\0')
  2375. {
  2376. cp++;
  2377. if (*cp == 'm')
  2378. {
  2379. /*
  2380. * Replace %m by system error string. If there are any %'s in
  2381. * the string, we'd better double them so that vsnprintf won't
  2382. * misinterpret.
  2383. */
  2384. const char *cp2;
  2385. cp2 = useful_strerror(edata->saved_errno);
  2386. for (; *cp2; cp2++)
  2387. {
  2388. if (*cp2 == '%')
  2389. appendStringInfoCharMacro(&buf, '%');
  2390. appendStringInfoCharMacro(&buf, *cp2);
  2391. }
  2392. }
  2393. else
  2394. {
  2395. /* copy % and next char --- this avoids trouble with %%m */
  2396. appendStringInfoCharMacro(&buf, '%');
  2397. appendStringInfoCharMacro(&buf, *cp);
  2398. }
  2399. }
  2400. else
  2401. appendStringInfoCharMacro(&buf, *cp);
  2402. }
  2403. return buf.data;
  2404. }
  2405. /*
  2406. * A slightly cleaned-up version of strerror()
  2407. */
  2408. static const char *
  2409. useful_strerror(int errnum)
  2410. {
  2411. /* this buffer is only used if errno has a bogus value */
  2412. static char errorstr_buf[48];
  2413. const char *str;
  2414. #ifdef WIN32
  2415. /* Winsock error code range, per WinError.h */
  2416. if (errnum >= 10000 && errnum <= 11999)
  2417. return pgwin32_socket_strerror(errnum);
  2418. #endif
  2419. str = strerror(errnum);
  2420. /*
  2421. * Some strerror()s return an empty string for out-of-range errno. This is
  2422. * ANSI C spec compliant, but not exactly useful.
  2423. */
  2424. if (str == NULL || *str == '\0')
  2425. {
  2426. snprintf(errorstr_buf, sizeof(errorstr_buf),
  2427. /*------
  2428. translator: This string will be truncated at 47
  2429. characters expanded. */
  2430. _("operating system error %d"), errnum);
  2431. str = errorstr_buf;
  2432. }
  2433. return str;
  2434. }
  2435. /*
  2436. * error_severity --- get localized string representing elevel
  2437. */
  2438. static const char *
  2439. error_severity(int elevel)
  2440. {
  2441. const char *prefix;
  2442. switch (elevel)
  2443. {
  2444. case DEBUG1:
  2445. case DEBUG2:
  2446. case DEBUG3:
  2447. case DEBUG4:
  2448. case DEBUG5:
  2449. prefix = _("DEBUG");
  2450. break;
  2451. case LOG:
  2452. case COMMERROR:
  2453. prefix = _("LOG");
  2454. break;
  2455. case INFO:
  2456. prefix = _("INFO");
  2457. break;
  2458. case NOTICE:
  2459. prefix = _("NOTICE");
  2460. break;
  2461. case WARNING:
  2462. prefix = _("WARNING");
  2463. break;
  2464. case ERROR:
  2465. prefix = _("ERROR");
  2466. break;
  2467. case FATAL:
  2468. prefix = _("FATAL");
  2469. break;
  2470. case PANIC:
  2471. prefix = _("PANIC");
  2472. break;
  2473. default:
  2474. prefix = "???";
  2475. break;
  2476. }
  2477. return prefix;
  2478. }
  2479. /*
  2480. * append_with_tabs
  2481. *
  2482. * Append the string to the StringInfo buffer, inserting a tab after any
  2483. * newline.
  2484. */
  2485. static void
  2486. append_with_tabs(StringInfo buf, const char *str)
  2487. {
  2488. char ch;
  2489. while ((ch = *str++) != '\0')
  2490. {
  2491. appendStringInfoCharMacro(buf, ch);
  2492. if (ch == '\n')
  2493. appendStringInfoCharMacro(buf, '\t');
  2494. }
  2495. }
  2496. /*
  2497. * Write errors to stderr (or by equal means when stderr is
  2498. * not available). Used before ereport/elog can be used
  2499. * safely (memory context, GUC load etc)
  2500. */
  2501. void
  2502. write_stderr(const char *fmt,...)
  2503. {
  2504. va_list ap;
  2505. #ifdef WIN32
  2506. char errbuf[2048]; /* Arbitrary size? */
  2507. #endif
  2508. fmt = _(fmt);
  2509. va_start(ap, fmt);
  2510. #ifndef WIN32
  2511. /* On Unix, we just fprintf to stderr */
  2512. vfprintf(stderr, fmt, ap);
  2513. fflush(stderr);
  2514. #else
  2515. vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
  2516. /*
  2517. * On Win32, we print to stderr if running on a console, or write to
  2518. * eventlog if running as a service
  2519. */
  2520. if (pgwin32_is_service()) /* Running as a service */
  2521. {
  2522. write_eventlog(ERROR, errbuf, strlen(errbuf));
  2523. }
  2524. else
  2525. {
  2526. /* Not running as service, write to stderr */
  2527. write_console(errbuf, strlen(errbuf));
  2528. fflush(stderr);
  2529. }
  2530. #endif
  2531. va_end(ap);
  2532. }
  2533. /*
  2534. * is_log_level_output -- is elevel logically >= log_min_level?
  2535. *
  2536. * We use this for tests that should consider LOG to sort out-of-order,
  2537. * between ERROR and FATAL. Generally this is the right thing for testing
  2538. * whether a message should go to the postmaster log, whereas a simple >=
  2539. * test is correct for testing whether the message should go to the client.
  2540. */
  2541. static bool
  2542. is_log_level_output(int elevel, int log_min_level)
  2543. {
  2544. if (elevel == LOG || elevel == COMMERROR)
  2545. {
  2546. if (log_min_level == LOG || log_min_level <= ERROR)
  2547. return true;
  2548. }
  2549. else if (log_min_level == LOG)
  2550. {
  2551. /* elevel != LOG */
  2552. if (elevel >= FATAL)
  2553. return true;
  2554. }
  2555. /* Neither is LOG */
  2556. else if (elevel >= log_min_level)
  2557. return true;
  2558. return false;
  2559. }
  2560. /*
  2561. * Adjust the level of a recovery-related message per trace_recovery_messages.
  2562. *
  2563. * The argument is the default log level of the message, eg, DEBUG2. (This
  2564. * should only be applied to DEBUGn log messages, otherwise it's a no-op.)
  2565. * If the level is >= trace_recovery_messages, we return LOG, causing the
  2566. * message to be logged unconditionally (for most settings of
  2567. * log_min_messages). Otherwise, we return the argument unchanged.
  2568. * The message will then be shown based on the setting of log_min_messages.
  2569. *
  2570. * Intention is to keep this for at least the whole of the 9.0 production
  2571. * release, so we can more easily diagnose production problems in the field.
  2572. * It should go away eventually, though, because it's an ugly and
  2573. * hard-to-explain kluge.
  2574. */
  2575. int
  2576. trace_recovery(int trace_level)
  2577. {
  2578. if (trace_level < LOG &&
  2579. trace_level >= trace_recovery_messages)
  2580. return LOG;
  2581. return trace_level;
  2582. }