PageRenderTime 114ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://bitbucket.org/mhellegers/pghaikuport
C | 3001 lines | 1704 code | 401 blank | 896 comment | 317 complexity | 7cffc7a3537c53797b55fd5ec9be50f5 MD5 | raw file
Possible License(s): AGPL-3.0
  1. /*-------------------------------------------------------------------------
  2. *
  3. * elog.c
  4. * error logging and reporting
  5. *
  6. * Because of the extremely high rate at which log messages can be generated,
  7. * we need to be mindful of the performance cost of obtaining any information
  8. * that may be logged. Also, it's important to keep in mind that this code may
  9. * get called from within an aborted transaction, in which case operations
  10. * such as syscache lookups are unsafe.
  11. *
  12. * Some notes about recursion and errors during error processing:
  13. *
  14. * We need to be robust about recursive-error scenarios --- for example,
  15. * if we run out of memory, it's important to be able to report that fact.
  16. * There are a number of considerations that go into this.
  17. *
  18. * First, distinguish between re-entrant use and actual recursion. It
  19. * is possible for an error or warning message to be emitted while the
  20. * parameters for an error message are being computed. In this case
  21. * errstart has been called for the outer message, and some field values
  22. * may have already been saved, but we are not actually recursing. We handle
  23. * this by providing a (small) stack of ErrorData records. The inner message
  24. * can be computed and sent without disturbing the state of the outer message.
  25. * (If the inner message is actually an error, this isn't very interesting
  26. * because control won't come back to the outer message generator ... but
  27. * if the inner message is only debug or log data, this is critical.)
  28. *
  29. * Second, actual recursion will occur if an error is reported by one of
  30. * the elog.c routines or something they call. By far the most probable
  31. * scenario of this sort is "out of memory"; and it's also the nastiest
  32. * to handle because we'd likely also run out of memory while trying to
  33. * report this error! Our escape hatch for this case is to reset the
  34. * ErrorContext to empty before trying to process the inner error. Since
  35. * ErrorContext is guaranteed to have at least 8K of space in it (see mcxt.c),
  36. * we should be able to process an "out of memory" message successfully.
  37. * Since we lose the prior error state due to the reset, we won't be able
  38. * to return to processing the original error, but we wouldn't have anyway.
  39. * (NOTE: the escape hatch is not used for recursive situations where the
  40. * inner message is of less than ERROR severity; in that case we just
  41. * try to process it and return normally. Usually this will work, but if
  42. * it ends up in infinite recursion, we will PANIC due to error stack
  43. * overflow.)
  44. *
  45. *
  46. * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
  47. * Portions Copyright (c) 1994, Regents of the University of California
  48. *
  49. *
  50. * IDENTIFICATION
  51. * src/backend/utils/error/elog.c
  52. *
  53. *-------------------------------------------------------------------------
  54. */
  55. #include "postgres.h"
  56. #include <fcntl.h>
  57. #include <time.h>
  58. #include <unistd.h>
  59. #include <signal.h>
  60. #include <ctype.h>
  61. #ifdef HAVE_SYSLOG
  62. #include <syslog.h>
  63. #endif
  64. #include "access/transam.h"
  65. #include "access/xact.h"
  66. #include "libpq/libpq.h"
  67. #include "libpq/pqformat.h"
  68. #include "mb/pg_wchar.h"
  69. #include "miscadmin.h"
  70. #include "postmaster/postmaster.h"
  71. #include "postmaster/syslogger.h"
  72. #include "storage/ipc.h"
  73. #include "storage/proc.h"
  74. #include "tcop/tcopprot.h"
  75. #include "utils/guc.h"
  76. #include "utils/memutils.h"
  77. #include "utils/ps_status.h"
  78. #undef _
  79. #define _(x) err_gettext(x)
  80. static const char *
  81. err_gettext(const char *str)
  82. /* This extension allows gcc to check the format string for consistency with
  83. the supplied arguments. */
  84. __attribute__((format_arg(1)));
  85. /* Global variables */
  86. ErrorContextCallback *error_context_stack = NULL;
  87. sigjmp_buf *PG_exception_stack = NULL;
  88. extern bool redirection_done;
  89. /*
  90. * Hook for intercepting messages before they are sent to the server log.
  91. * Note that the hook will not get called for messages that are suppressed
  92. * by log_min_messages. Also note that logging hooks implemented in preload
  93. * libraries will miss any log messages that are generated before the
  94. * library is loaded.
  95. */
  96. emit_log_hook_type emit_log_hook = NULL;
  97. /* GUC parameters */
  98. int Log_error_verbosity = PGERROR_VERBOSE;
  99. char *Log_line_prefix = NULL; /* format for extra log line info */
  100. int Log_destination = LOG_DESTINATION_STDERR;
  101. #ifdef HAVE_SYSLOG
  102. /*
  103. * Max string length to send to syslog(). Note that this doesn't count the
  104. * sequence-number prefix we add, and of course it doesn't count the prefix
  105. * added by syslog itself. Solaris and sysklogd truncate the final message
  106. * at 1024 bytes, so this value leaves 124 bytes for those prefixes. (Most
  107. * other syslog implementations seem to have limits of 2KB or so.)
  108. */
  109. #ifndef PG_SYSLOG_LIMIT
  110. #define PG_SYSLOG_LIMIT 900
  111. #endif
  112. static bool openlog_done = false;
  113. static char *syslog_ident = NULL;
  114. static int syslog_facility = LOG_LOCAL0;
  115. static void write_syslog(int level, const char *line);
  116. #endif
  117. static void write_console(const char *line, int len);
  118. #ifdef WIN32
  119. extern char *event_source;
  120. static void write_eventlog(int level, const char *line, int len);
  121. #endif
  122. /* We provide a small stack of ErrorData records for re-entrant cases */
  123. #define ERRORDATA_STACK_SIZE 5
  124. static ErrorData errordata[ERRORDATA_STACK_SIZE];
  125. static int errordata_stack_depth = -1; /* index of topmost active frame */
  126. static int recursion_depth = 0; /* to detect actual recursion */
  127. /* buffers for formatted timestamps that might be used by both
  128. * log_line_prefix and csv logs.
  129. */
  130. #define FORMATTED_TS_LEN 128
  131. static char formatted_start_time[FORMATTED_TS_LEN];
  132. static char formatted_log_time[FORMATTED_TS_LEN];
  133. /* Macro for checking errordata_stack_depth is reasonable */
  134. #define CHECK_STACK_DEPTH() \
  135. do { \
  136. if (errordata_stack_depth < 0) \
  137. { \
  138. errordata_stack_depth = -1; \
  139. ereport(ERROR, (errmsg_internal("errstart was not called"))); \
  140. } \
  141. } while (0)
  142. static void log_line_prefix(StringInfo buf, ErrorData *edata);
  143. static void send_message_to_server_log(ErrorData *edata);
  144. static void send_message_to_frontend(ErrorData *edata);
  145. static char *expand_fmt_string(const char *fmt, ErrorData *edata);
  146. static const char *useful_strerror(int errnum);
  147. static const char *error_severity(int elevel);
  148. static void append_with_tabs(StringInfo buf, const char *str);
  149. static bool is_log_level_output(int elevel, int log_min_level);
  150. static void write_pipe_chunks(char *data, int len, int dest);
  151. static void write_csvlog(ErrorData *edata);
  152. static void setup_formatted_log_time(void);
  153. static void setup_formatted_start_time(void);
  154. /*
  155. * in_error_recursion_trouble --- are we at risk of infinite error recursion?
  156. *
  157. * This function exists to provide common control of various fallback steps
  158. * that we take if we think we are facing infinite error recursion. See the
  159. * callers for details.
  160. */
  161. bool
  162. in_error_recursion_trouble(void)
  163. {
  164. /* Pull the plug if recurse more than once */
  165. return (recursion_depth > 2);
  166. }
  167. /*
  168. * One of those fallback steps is to stop trying to localize the error
  169. * message, since there's a significant probability that that's exactly
  170. * what's causing the recursion.
  171. */
  172. static inline const char *
  173. err_gettext(const char *str)
  174. {
  175. #ifdef ENABLE_NLS
  176. if (in_error_recursion_trouble())
  177. return str;
  178. else
  179. return gettext(str);
  180. #else
  181. return str;
  182. #endif
  183. }
  184. /*
  185. * errstart --- begin an error-reporting cycle
  186. *
  187. * Create a stack entry and store the given parameters in it. Subsequently,
  188. * errmsg() and perhaps other routines will be called to further populate
  189. * the stack entry. Finally, errfinish() will be called to actually process
  190. * the error report.
  191. *
  192. * Returns TRUE in normal case. Returns FALSE to short-circuit the error
  193. * report (if it's a warning or lower and not to be reported anywhere).
  194. */
  195. bool
  196. errstart(int elevel, const char *filename, int lineno,
  197. const char *funcname, const char *domain)
  198. {
  199. ErrorData *edata;
  200. bool output_to_server;
  201. bool output_to_client = false;
  202. int i;
  203. /*
  204. * Check some cases in which we want to promote an error into a more
  205. * severe error. None of this logic applies for non-error messages.
  206. */
  207. if (elevel >= ERROR)
  208. {
  209. /*
  210. * If we are inside a critical section, all errors become PANIC
  211. * errors. See miscadmin.h.
  212. */
  213. if (CritSectionCount > 0)
  214. elevel = PANIC;
  215. /*
  216. * Check reasons for treating ERROR as FATAL:
  217. *
  218. * 1. we have no handler to pass the error to (implies we are in the
  219. * postmaster or in backend startup).
  220. *
  221. * 2. ExitOnAnyError mode switch is set (initdb uses this).
  222. *
  223. * 3. the error occurred after proc_exit has begun to run. (It's
  224. * proc_exit's responsibility to see that this doesn't turn into
  225. * infinite recursion!)
  226. */
  227. if (elevel == ERROR)
  228. {
  229. if (PG_exception_stack == NULL ||
  230. ExitOnAnyError ||
  231. proc_exit_inprogress)
  232. elevel = FATAL;
  233. }
  234. /*
  235. * If the error level is ERROR or more, errfinish is not going to
  236. * return to caller; therefore, if there is any stacked error already
  237. * in progress it will be lost. This is more or less okay, except we
  238. * do not want to have a FATAL or PANIC error downgraded because the
  239. * reporting process was interrupted by a lower-grade error. So check
  240. * the stack and make sure we panic if panic is warranted.
  241. */
  242. for (i = 0; i <= errordata_stack_depth; i++)
  243. elevel = Max(elevel, errordata[i].elevel);
  244. }
  245. /*
  246. * Now decide whether we need to process this report at all; if it's
  247. * warning or less and not enabled for logging, just return FALSE without
  248. * starting up any error logging machinery.
  249. */
  250. /* Determine whether message is enabled for server log output */
  251. if (IsPostmasterEnvironment)
  252. output_to_server = is_log_level_output(elevel, log_min_messages);
  253. else
  254. /* In bootstrap/standalone case, do not sort LOG out-of-order */
  255. output_to_server = (elevel >= log_min_messages);
  256. /* Determine whether message is enabled for client output */
  257. if (whereToSendOutput == DestRemote && elevel != COMMERROR)
  258. {
  259. /*
  260. * client_min_messages is honored only after we complete the
  261. * authentication handshake. This is required both for security
  262. * reasons and because many clients can't handle NOTICE messages
  263. * during authentication.
  264. */
  265. if (ClientAuthInProgress)
  266. output_to_client = (elevel >= ERROR);
  267. else
  268. output_to_client = (elevel >= client_min_messages ||
  269. elevel == INFO);
  270. }
  271. /* Skip processing effort if non-error message will not be output */
  272. if (elevel < ERROR && !output_to_server && !output_to_client)
  273. return false;
  274. /*
  275. * Okay, crank up a stack entry to store the info in.
  276. */
  277. if (recursion_depth++ > 0 && elevel >= ERROR)
  278. {
  279. /*
  280. * Ooops, error during error processing. Clear ErrorContext as
  281. * discussed at top of file. We will not return to the original
  282. * error's reporter or handler, so we don't need it.
  283. */
  284. MemoryContextReset(ErrorContext);
  285. /*
  286. * Infinite error recursion might be due to something broken in a
  287. * context traceback routine. Abandon them too. We also abandon
  288. * attempting to print the error statement (which, if long, could
  289. * itself be the source of the recursive failure).
  290. */
  291. if (in_error_recursion_trouble())
  292. {
  293. error_context_stack = NULL;
  294. debug_query_string = NULL;
  295. }
  296. }
  297. if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
  298. {
  299. /*
  300. * Wups, stack not big enough. We treat this as a PANIC condition
  301. * because it suggests an infinite loop of errors during error
  302. * recovery.
  303. */
  304. errordata_stack_depth = -1; /* make room on stack */
  305. ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
  306. }
  307. /* Initialize data for this error frame */
  308. edata = &errordata[errordata_stack_depth];
  309. MemSet(edata, 0, sizeof(ErrorData));
  310. edata->elevel = elevel;
  311. edata->output_to_server = output_to_server;
  312. edata->output_to_client = output_to_client;
  313. if (filename)
  314. {
  315. const char *slash;
  316. /* keep only base name, useful especially for vpath builds */
  317. slash = strrchr(filename, '/');
  318. if (slash)
  319. filename = slash + 1;
  320. }
  321. edata->filename = filename;
  322. edata->lineno = lineno;
  323. edata->funcname = funcname;
  324. /* the default text domain is the backend's */
  325. edata->domain = domain ? domain : PG_TEXTDOMAIN("postgres");
  326. /* Select default errcode based on elevel */
  327. if (elevel >= ERROR)
  328. edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
  329. else if (elevel == WARNING)
  330. edata->sqlerrcode = ERRCODE_WARNING;
  331. else
  332. edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
  333. /* errno is saved here so that error parameter eval can't change it */
  334. edata->saved_errno = errno;
  335. recursion_depth--;
  336. return true;
  337. }
  338. /*
  339. * errfinish --- end an error-reporting cycle
  340. *
  341. * Produce the appropriate error report(s) and pop the error stack.
  342. *
  343. * If elevel is ERROR or worse, control does not return to the caller.
  344. * See elog.h for the error level definitions.
  345. */
  346. void
  347. errfinish(int dummy,...)
  348. {
  349. ErrorData *edata = &errordata[errordata_stack_depth];
  350. int elevel = edata->elevel;
  351. MemoryContext oldcontext;
  352. ErrorContextCallback *econtext;
  353. recursion_depth++;
  354. CHECK_STACK_DEPTH();
  355. /*
  356. * Do processing in ErrorContext, which we hope has enough reserved space
  357. * to report an error.
  358. */
  359. oldcontext = MemoryContextSwitchTo(ErrorContext);
  360. /*
  361. * Call any context callback functions. Errors occurring in callback
  362. * functions will be treated as recursive errors --- this ensures we will
  363. * avoid infinite recursion (see errstart).
  364. */
  365. for (econtext = error_context_stack;
  366. econtext != NULL;
  367. econtext = econtext->previous)
  368. (*econtext->callback) (econtext->arg);
  369. /*
  370. * If ERROR (not more nor less) we pass it off to the current handler.
  371. * Printing it and popping the stack is the responsibility of the handler.
  372. */
  373. if (elevel == ERROR)
  374. {
  375. /*
  376. * We do some minimal cleanup before longjmp'ing so that handlers can
  377. * execute in a reasonably sane state.
  378. */
  379. /* This is just in case the error came while waiting for input */
  380. ImmediateInterruptOK = false;
  381. /*
  382. * Reset InterruptHoldoffCount in case we ereport'd from inside an
  383. * interrupt holdoff section. (We assume here that no handler will
  384. * itself be inside a holdoff section. If necessary, such a handler
  385. * could save and restore InterruptHoldoffCount for itself, but this
  386. * should make life easier for most.)
  387. */
  388. InterruptHoldoffCount = 0;
  389. CritSectionCount = 0; /* should be unnecessary, but... */
  390. /*
  391. * Note that we leave CurrentMemoryContext set to ErrorContext. The
  392. * handler should reset it to something else soon.
  393. */
  394. recursion_depth--;
  395. PG_RE_THROW();
  396. }
  397. /*
  398. * If we are doing FATAL or PANIC, abort any old-style COPY OUT in
  399. * progress, so that we can report the message before dying. (Without
  400. * this, pq_putmessage will refuse to send the message at all, which is
  401. * what we want for NOTICE messages, but not for fatal exits.) This hack
  402. * is necessary because of poor design of old-style copy protocol. Note
  403. * we must do this even if client is fool enough to have set
  404. * client_min_messages above FATAL, so don't look at output_to_client.
  405. */
  406. if (elevel >= FATAL && whereToSendOutput == DestRemote)
  407. pq_endcopyout(true);
  408. /* Emit the message to the right places */
  409. EmitErrorReport();
  410. /* Now free up subsidiary data attached to stack entry, and release it */
  411. if (edata->message)
  412. pfree(edata->message);
  413. if (edata->detail)
  414. pfree(edata->detail);
  415. if (edata->detail_log)
  416. pfree(edata->detail_log);
  417. if (edata->hint)
  418. pfree(edata->hint);
  419. if (edata->context)
  420. pfree(edata->context);
  421. if (edata->internalquery)
  422. pfree(edata->internalquery);
  423. errordata_stack_depth--;
  424. /* Exit error-handling context */
  425. MemoryContextSwitchTo(oldcontext);
  426. recursion_depth--;
  427. /*
  428. * Perform error recovery action as specified by elevel.
  429. */
  430. if (elevel == FATAL)
  431. {
  432. /*
  433. * For a FATAL error, we let proc_exit clean up and exit.
  434. */
  435. ImmediateInterruptOK = false;
  436. /*
  437. * If we just reported a startup failure, the client will disconnect
  438. * on receiving it, so don't send any more to the client.
  439. */
  440. if (PG_exception_stack == NULL && whereToSendOutput == DestRemote)
  441. whereToSendOutput = DestNone;
  442. /*
  443. * fflush here is just to improve the odds that we get to see the
  444. * error message, in case things are so hosed that proc_exit crashes.
  445. * Any other code you might be tempted to add here should probably be
  446. * in an on_proc_exit or on_shmem_exit callback instead.
  447. */
  448. fflush(stdout);
  449. fflush(stderr);
  450. /*
  451. * Do normal process-exit cleanup, then return exit code 1 to indicate
  452. * FATAL termination. The postmaster may or may not consider this
  453. * worthy of panic, depending on which subprocess returns it.
  454. */
  455. proc_exit(1);
  456. }
  457. if (elevel >= PANIC)
  458. {
  459. /*
  460. * Serious crash time. Postmaster will observe SIGABRT process exit
  461. * status and kill the other backends too.
  462. *
  463. * XXX: what if we are *in* the postmaster? abort() won't kill our
  464. * children...
  465. */
  466. ImmediateInterruptOK = false;
  467. fflush(stdout);
  468. fflush(stderr);
  469. abort();
  470. }
  471. /*
  472. * We reach here if elevel <= WARNING. OK to return to caller.
  473. *
  474. * But check for cancel/die interrupt first --- this is so that the user
  475. * can stop a query emitting tons of notice or warning messages, even if
  476. * it's in a loop that otherwise fails to check for interrupts.
  477. */
  478. CHECK_FOR_INTERRUPTS();
  479. }
  480. /*
  481. * errcode --- add SQLSTATE error code to the current error
  482. *
  483. * The code is expected to be represented as per MAKE_SQLSTATE().
  484. */
  485. int
  486. errcode(int sqlerrcode)
  487. {
  488. ErrorData *edata = &errordata[errordata_stack_depth];
  489. /* we don't bother incrementing recursion_depth */
  490. CHECK_STACK_DEPTH();
  491. edata->sqlerrcode = sqlerrcode;
  492. return 0; /* return value does not matter */
  493. }
  494. /*
  495. * errcode_for_file_access --- add SQLSTATE error code to the current error
  496. *
  497. * The SQLSTATE code is chosen based on the saved errno value. We assume
  498. * that the failing operation was some type of disk file access.
  499. *
  500. * NOTE: the primary error message string should generally include %m
  501. * when this is used.
  502. */
  503. int
  504. errcode_for_file_access(void)
  505. {
  506. ErrorData *edata = &errordata[errordata_stack_depth];
  507. /* we don't bother incrementing recursion_depth */
  508. CHECK_STACK_DEPTH();
  509. switch (edata->saved_errno)
  510. {
  511. /* Permission-denied failures */
  512. case EPERM: /* Not super-user */
  513. case EACCES: /* Permission denied */
  514. #ifdef EROFS
  515. case EROFS: /* Read only file system */
  516. #endif
  517. edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
  518. break;
  519. /* File not found */
  520. case ENOENT: /* No such file or directory */
  521. edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
  522. break;
  523. /* Duplicate file */
  524. case EEXIST: /* File exists */
  525. edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
  526. break;
  527. /* Wrong object type or state */
  528. case ENOTDIR: /* Not a directory */
  529. case EISDIR: /* Is a directory */
  530. #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
  531. case ENOTEMPTY: /* Directory not empty */
  532. #endif
  533. edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
  534. break;
  535. /* Insufficient resources */
  536. case ENOSPC: /* No space left on device */
  537. edata->sqlerrcode = ERRCODE_DISK_FULL;
  538. break;
  539. case ENFILE: /* File table overflow */
  540. case EMFILE: /* Too many open files */
  541. edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
  542. break;
  543. /* Hardware failure */
  544. case EIO: /* I/O error */
  545. edata->sqlerrcode = ERRCODE_IO_ERROR;
  546. break;
  547. /* All else is classified as internal errors */
  548. default:
  549. edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
  550. break;
  551. }
  552. return 0; /* return value does not matter */
  553. }
  554. /*
  555. * errcode_for_socket_access --- add SQLSTATE error code to the current error
  556. *
  557. * The SQLSTATE code is chosen based on the saved errno value. We assume
  558. * that the failing operation was some type of socket access.
  559. *
  560. * NOTE: the primary error message string should generally include %m
  561. * when this is used.
  562. */
  563. int
  564. errcode_for_socket_access(void)
  565. {
  566. ErrorData *edata = &errordata[errordata_stack_depth];
  567. /* we don't bother incrementing recursion_depth */
  568. CHECK_STACK_DEPTH();
  569. switch (edata->saved_errno)
  570. {
  571. /* Loss of connection */
  572. case EPIPE:
  573. #ifdef ECONNRESET
  574. case ECONNRESET:
  575. #endif
  576. edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
  577. break;
  578. /* All else is classified as internal errors */
  579. default:
  580. edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
  581. break;
  582. }
  583. return 0; /* return value does not matter */
  584. }
  585. /*
  586. * This macro handles expansion of a format string and associated parameters;
  587. * it's common code for errmsg(), errdetail(), etc. Must be called inside
  588. * a routine that is declared like "const char *fmt, ..." and has an edata
  589. * pointer set up. The message is assigned to edata->targetfield, or
  590. * appended to it if appendval is true. The message is subject to translation
  591. * if translateit is true.
  592. *
  593. * Note: we pstrdup the buffer rather than just transferring its storage
  594. * to the edata field because the buffer might be considerably larger than
  595. * really necessary.
  596. */
  597. #define EVALUATE_MESSAGE(domain, targetfield, appendval, translateit) \
  598. { \
  599. char *fmtbuf; \
  600. StringInfoData buf; \
  601. /* Internationalize the error format string */ \
  602. if (translateit && !in_error_recursion_trouble()) \
  603. fmt = dgettext((domain), fmt); \
  604. /* Expand %m in format string */ \
  605. fmtbuf = expand_fmt_string(fmt, edata); \
  606. initStringInfo(&buf); \
  607. if ((appendval) && edata->targetfield) { \
  608. appendStringInfoString(&buf, edata->targetfield); \
  609. appendStringInfoChar(&buf, '\n'); \
  610. } \
  611. /* Generate actual output --- have to use appendStringInfoVA */ \
  612. for (;;) \
  613. { \
  614. va_list args; \
  615. bool success; \
  616. va_start(args, fmt); \
  617. success = appendStringInfoVA(&buf, fmtbuf, args); \
  618. va_end(args); \
  619. if (success) \
  620. break; \
  621. enlargeStringInfo(&buf, buf.maxlen); \
  622. } \
  623. /* Done with expanded fmt */ \
  624. pfree(fmtbuf); \
  625. /* Save the completed message into the stack item */ \
  626. if (edata->targetfield) \
  627. pfree(edata->targetfield); \
  628. edata->targetfield = pstrdup(buf.data); \
  629. pfree(buf.data); \
  630. }
  631. /*
  632. * Same as above, except for pluralized error messages. The calling routine
  633. * must be declared like "const char *fmt_singular, const char *fmt_plural,
  634. * unsigned long n, ...". Translation is assumed always wanted.
  635. */
  636. #define EVALUATE_MESSAGE_PLURAL(domain, targetfield, appendval) \
  637. { \
  638. const char *fmt; \
  639. char *fmtbuf; \
  640. StringInfoData buf; \
  641. /* Internationalize the error format string */ \
  642. if (!in_error_recursion_trouble()) \
  643. fmt = dngettext((domain), fmt_singular, fmt_plural, n); \
  644. else \
  645. fmt = (n == 1 ? fmt_singular : fmt_plural); \
  646. /* Expand %m in format string */ \
  647. fmtbuf = expand_fmt_string(fmt, edata); \
  648. initStringInfo(&buf); \
  649. if ((appendval) && edata->targetfield) { \
  650. appendStringInfoString(&buf, edata->targetfield); \
  651. appendStringInfoChar(&buf, '\n'); \
  652. } \
  653. /* Generate actual output --- have to use appendStringInfoVA */ \
  654. for (;;) \
  655. { \
  656. va_list args; \
  657. bool success; \
  658. va_start(args, n); \
  659. success = appendStringInfoVA(&buf, fmtbuf, args); \
  660. va_end(args); \
  661. if (success) \
  662. break; \
  663. enlargeStringInfo(&buf, buf.maxlen); \
  664. } \
  665. /* Done with expanded fmt */ \
  666. pfree(fmtbuf); \
  667. /* Save the completed message into the stack item */ \
  668. if (edata->targetfield) \
  669. pfree(edata->targetfield); \
  670. edata->targetfield = pstrdup(buf.data); \
  671. pfree(buf.data); \
  672. }
  673. /*
  674. * errmsg --- add a primary error message text to the current error
  675. *
  676. * In addition to the usual %-escapes recognized by printf, "%m" in
  677. * fmt is replaced by the error message for the caller's value of errno.
  678. *
  679. * Note: no newline is needed at the end of the fmt string, since
  680. * ereport will provide one for the output methods that need it.
  681. */
  682. int
  683. errmsg(const char *fmt,...)
  684. {
  685. ErrorData *edata = &errordata[errordata_stack_depth];
  686. MemoryContext oldcontext;
  687. recursion_depth++;
  688. CHECK_STACK_DEPTH();
  689. oldcontext = MemoryContextSwitchTo(ErrorContext);
  690. EVALUATE_MESSAGE(edata->domain, message, false, true);
  691. MemoryContextSwitchTo(oldcontext);
  692. recursion_depth--;
  693. return 0; /* return value does not matter */
  694. }
  695. /*
  696. * errmsg_internal --- add a primary error message text to the current error
  697. *
  698. * This is exactly like errmsg() except that strings passed to errmsg_internal
  699. * are not translated, and are customarily left out of the
  700. * internationalization message dictionary. This should be used for "can't
  701. * happen" cases that are probably not worth spending translation effort on.
  702. * We also use this for certain cases where we *must* not try to translate
  703. * the message because the translation would fail and result in infinite
  704. * error recursion.
  705. */
  706. int
  707. errmsg_internal(const char *fmt,...)
  708. {
  709. ErrorData *edata = &errordata[errordata_stack_depth];
  710. MemoryContext oldcontext;
  711. recursion_depth++;
  712. CHECK_STACK_DEPTH();
  713. oldcontext = MemoryContextSwitchTo(ErrorContext);
  714. EVALUATE_MESSAGE(edata->domain, message, false, false);
  715. MemoryContextSwitchTo(oldcontext);
  716. recursion_depth--;
  717. return 0; /* return value does not matter */
  718. }
  719. /*
  720. * errmsg_plural --- add a primary error message text to the current error,
  721. * with support for pluralization of the message text
  722. */
  723. int
  724. errmsg_plural(const char *fmt_singular, const char *fmt_plural,
  725. unsigned long n,...)
  726. {
  727. ErrorData *edata = &errordata[errordata_stack_depth];
  728. MemoryContext oldcontext;
  729. recursion_depth++;
  730. CHECK_STACK_DEPTH();
  731. oldcontext = MemoryContextSwitchTo(ErrorContext);
  732. EVALUATE_MESSAGE_PLURAL(edata->domain, message, false);
  733. MemoryContextSwitchTo(oldcontext);
  734. recursion_depth--;
  735. return 0; /* return value does not matter */
  736. }
  737. /*
  738. * errdetail --- add a detail error message text to the current error
  739. */
  740. int
  741. errdetail(const char *fmt,...)
  742. {
  743. ErrorData *edata = &errordata[errordata_stack_depth];
  744. MemoryContext oldcontext;
  745. recursion_depth++;
  746. CHECK_STACK_DEPTH();
  747. oldcontext = MemoryContextSwitchTo(ErrorContext);
  748. EVALUATE_MESSAGE(edata->domain, detail, false, true);
  749. MemoryContextSwitchTo(oldcontext);
  750. recursion_depth--;
  751. return 0; /* return value does not matter */
  752. }
  753. /*
  754. * errdetail_internal --- add a detail error message text to the current error
  755. *
  756. * This is exactly like errdetail() except that strings passed to
  757. * errdetail_internal are not translated, and are customarily left out of the
  758. * internationalization message dictionary. This should be used for detail
  759. * messages that seem not worth translating for one reason or another
  760. * (typically, that they don't seem to be useful to average users).
  761. */
  762. int
  763. errdetail_internal(const char *fmt,...)
  764. {
  765. ErrorData *edata = &errordata[errordata_stack_depth];
  766. MemoryContext oldcontext;
  767. recursion_depth++;
  768. CHECK_STACK_DEPTH();
  769. oldcontext = MemoryContextSwitchTo(ErrorContext);
  770. EVALUATE_MESSAGE(edata->domain, detail, false, false);
  771. MemoryContextSwitchTo(oldcontext);
  772. recursion_depth--;
  773. return 0; /* return value does not matter */
  774. }
  775. /*
  776. * errdetail_log --- add a detail_log error message text to the current error
  777. */
  778. int
  779. errdetail_log(const char *fmt,...)
  780. {
  781. ErrorData *edata = &errordata[errordata_stack_depth];
  782. MemoryContext oldcontext;
  783. recursion_depth++;
  784. CHECK_STACK_DEPTH();
  785. oldcontext = MemoryContextSwitchTo(ErrorContext);
  786. EVALUATE_MESSAGE(edata->domain, detail_log, false, true);
  787. MemoryContextSwitchTo(oldcontext);
  788. recursion_depth--;
  789. return 0; /* return value does not matter */
  790. }
  791. /*
  792. * errdetail_plural --- add a detail error message text to the current error,
  793. * with support for pluralization of the message text
  794. */
  795. int
  796. errdetail_plural(const char *fmt_singular, const char *fmt_plural,
  797. unsigned long n,...)
  798. {
  799. ErrorData *edata = &errordata[errordata_stack_depth];
  800. MemoryContext oldcontext;
  801. recursion_depth++;
  802. CHECK_STACK_DEPTH();
  803. oldcontext = MemoryContextSwitchTo(ErrorContext);
  804. EVALUATE_MESSAGE_PLURAL(edata->domain, detail, false);
  805. MemoryContextSwitchTo(oldcontext);
  806. recursion_depth--;
  807. return 0; /* return value does not matter */
  808. }
  809. /*
  810. * errhint --- add a hint error message text to the current error
  811. */
  812. int
  813. errhint(const char *fmt,...)
  814. {
  815. ErrorData *edata = &errordata[errordata_stack_depth];
  816. MemoryContext oldcontext;
  817. recursion_depth++;
  818. CHECK_STACK_DEPTH();
  819. oldcontext = MemoryContextSwitchTo(ErrorContext);
  820. EVALUATE_MESSAGE(edata->domain, hint, false, true);
  821. MemoryContextSwitchTo(oldcontext);
  822. recursion_depth--;
  823. return 0; /* return value does not matter */
  824. }
  825. /*
  826. * errcontext_msg --- add a context error message text to the current error
  827. *
  828. * Unlike other cases, multiple calls are allowed to build up a stack of
  829. * context information. We assume earlier calls represent more-closely-nested
  830. * states.
  831. */
  832. int
  833. errcontext_msg(const char *fmt,...)
  834. {
  835. ErrorData *edata = &errordata[errordata_stack_depth];
  836. MemoryContext oldcontext;
  837. recursion_depth++;
  838. CHECK_STACK_DEPTH();
  839. oldcontext = MemoryContextSwitchTo(ErrorContext);
  840. EVALUATE_MESSAGE(edata->context_domain, context, true, true);
  841. MemoryContextSwitchTo(oldcontext);
  842. recursion_depth--;
  843. return 0; /* return value does not matter */
  844. }
  845. /*
  846. * set_errcontext_domain --- set message domain to be used by errcontext()
  847. *
  848. * errcontext_msg() can be called from a different module than the original
  849. * ereport(), so we cannot use the message domain passed in errstart() to
  850. * translate it. Instead, each errcontext_msg() call should be preceded by
  851. * a set_errcontext_domain() call to specify the domain. This is usually
  852. * done transparently by the errcontext() macro.
  853. */
  854. int
  855. set_errcontext_domain(const char *domain)
  856. {
  857. ErrorData *edata = &errordata[errordata_stack_depth];
  858. /* we don't bother incrementing recursion_depth */
  859. CHECK_STACK_DEPTH();
  860. edata->context_domain = domain;
  861. return 0; /* return value does not matter */
  862. }
  863. /*
  864. * errhidestmt --- optionally suppress STATEMENT: field of log entry
  865. *
  866. * This should be called if the message text already includes the statement.
  867. */
  868. int
  869. errhidestmt(bool hide_stmt)
  870. {
  871. ErrorData *edata = &errordata[errordata_stack_depth];
  872. /* we don't bother incrementing recursion_depth */
  873. CHECK_STACK_DEPTH();
  874. edata->hide_stmt = hide_stmt;
  875. return 0; /* return value does not matter */
  876. }
  877. /*
  878. * errfunction --- add reporting function name to the current error
  879. *
  880. * This is used when backwards compatibility demands that the function
  881. * name appear in messages sent to old-protocol clients. Note that the
  882. * passed string is expected to be a non-freeable constant string.
  883. */
  884. int
  885. errfunction(const char *funcname)
  886. {
  887. ErrorData *edata = &errordata[errordata_stack_depth];
  888. /* we don't bother incrementing recursion_depth */
  889. CHECK_STACK_DEPTH();
  890. edata->funcname = funcname;
  891. edata->show_funcname = true;
  892. return 0; /* return value does not matter */
  893. }
  894. /*
  895. * errposition --- add cursor position to the current error
  896. */
  897. int
  898. errposition(int cursorpos)
  899. {
  900. ErrorData *edata = &errordata[errordata_stack_depth];
  901. /* we don't bother incrementing recursion_depth */
  902. CHECK_STACK_DEPTH();
  903. edata->cursorpos = cursorpos;
  904. return 0; /* return value does not matter */
  905. }
  906. /*
  907. * internalerrposition --- add internal cursor position to the current error
  908. */
  909. int
  910. internalerrposition(int cursorpos)
  911. {
  912. ErrorData *edata = &errordata[errordata_stack_depth];
  913. /* we don't bother incrementing recursion_depth */
  914. CHECK_STACK_DEPTH();
  915. edata->internalpos = cursorpos;
  916. return 0; /* return value does not matter */
  917. }
  918. /*
  919. * internalerrquery --- add internal query text to the current error
  920. *
  921. * Can also pass NULL to drop the internal query text entry. This case
  922. * is intended for use in error callback subroutines that are editorializing
  923. * on the layout of the error report.
  924. */
  925. int
  926. internalerrquery(const char *query)
  927. {
  928. ErrorData *edata = &errordata[errordata_stack_depth];
  929. /* we don't bother incrementing recursion_depth */
  930. CHECK_STACK_DEPTH();
  931. if (edata->internalquery)
  932. {
  933. pfree(edata->internalquery);
  934. edata->internalquery = NULL;
  935. }
  936. if (query)
  937. edata->internalquery = MemoryContextStrdup(ErrorContext, query);
  938. return 0; /* return value does not matter */
  939. }
  940. /*
  941. * geterrcode --- return the currently set SQLSTATE error code
  942. *
  943. * This is only intended for use in error callback subroutines, since there
  944. * is no other place outside elog.c where the concept is meaningful.
  945. */
  946. int
  947. geterrcode(void)
  948. {
  949. ErrorData *edata = &errordata[errordata_stack_depth];
  950. /* we don't bother incrementing recursion_depth */
  951. CHECK_STACK_DEPTH();
  952. return edata->sqlerrcode;
  953. }
  954. /*
  955. * geterrposition --- return the currently set error position (0 if none)
  956. *
  957. * This is only intended for use in error callback subroutines, since there
  958. * is no other place outside elog.c where the concept is meaningful.
  959. */
  960. int
  961. geterrposition(void)
  962. {
  963. ErrorData *edata = &errordata[errordata_stack_depth];
  964. /* we don't bother incrementing recursion_depth */
  965. CHECK_STACK_DEPTH();
  966. return edata->cursorpos;
  967. }
  968. /*
  969. * getinternalerrposition --- same for internal error position
  970. *
  971. * This is only intended for use in error callback subroutines, since there
  972. * is no other place outside elog.c where the concept is meaningful.
  973. */
  974. int
  975. getinternalerrposition(void)
  976. {
  977. ErrorData *edata = &errordata[errordata_stack_depth];
  978. /* we don't bother incrementing recursion_depth */
  979. CHECK_STACK_DEPTH();
  980. return edata->internalpos;
  981. }
  982. /*
  983. * elog_start --- startup for old-style API
  984. *
  985. * All that we do here is stash the hidden filename/lineno/funcname
  986. * arguments into a stack entry.
  987. *
  988. * We need this to be separate from elog_finish because there's no other
  989. * portable way to deal with inserting extra arguments into the elog call.
  990. * (If macros with variable numbers of arguments were portable, it'd be
  991. * easy, but they aren't.)
  992. */
  993. void
  994. elog_start(const char *filename, int lineno, const char *funcname)
  995. {
  996. ErrorData *edata;
  997. if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
  998. {
  999. /*
  1000. * Wups, stack not big enough. We treat this as a PANIC condition
  1001. * because it suggests an infinite loop of errors during error
  1002. * recovery. Note that the message is intentionally not localized,
  1003. * else failure to convert it to client encoding could cause further
  1004. * recursion.
  1005. */
  1006. errordata_stack_depth = -1; /* make room on stack */
  1007. ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
  1008. }
  1009. edata = &errordata[errordata_stack_depth];
  1010. if (filename)
  1011. {
  1012. const char *slash;
  1013. /* keep only base name, useful especially for vpath builds */
  1014. slash = strrchr(filename, '/');
  1015. if (slash)
  1016. filename = slash + 1;
  1017. }
  1018. edata->filename = filename;
  1019. edata->lineno = lineno;
  1020. edata->funcname = funcname;
  1021. /* errno is saved now so that error parameter eval can't change it */
  1022. edata->saved_errno = errno;
  1023. }
  1024. /*
  1025. * elog_finish --- finish up for old-style API
  1026. */
  1027. void
  1028. elog_finish(int elevel, const char *fmt,...)
  1029. {
  1030. ErrorData *edata = &errordata[errordata_stack_depth];
  1031. MemoryContext oldcontext;
  1032. CHECK_STACK_DEPTH();
  1033. /*
  1034. * Do errstart() to see if we actually want to report the message.
  1035. */
  1036. errordata_stack_depth--;
  1037. errno = edata->saved_errno;
  1038. if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname, NULL))
  1039. return; /* nothing to do */
  1040. /*
  1041. * Format error message just like errmsg_internal().
  1042. */
  1043. recursion_depth++;
  1044. oldcontext = MemoryContextSwitchTo(ErrorContext);
  1045. EVALUATE_MESSAGE(edata->domain, message, false, false);
  1046. MemoryContextSwitchTo(oldcontext);
  1047. recursion_depth--;
  1048. /*
  1049. * And let errfinish() finish up.
  1050. */
  1051. errfinish(0);
  1052. }
  1053. /*
  1054. * Functions to allow construction of error message strings separately from
  1055. * the ereport() call itself.
  1056. *
  1057. * The expected calling convention is
  1058. *
  1059. * pre_format_elog_string(errno, domain), var = format_elog_string(format,...)
  1060. *
  1061. * which can be hidden behind a macro such as GUC_check_errdetail(). We
  1062. * assume that any functions called in the arguments of format_elog_string()
  1063. * cannot result in re-entrant use of these functions --- otherwise the wrong
  1064. * text domain might be used, or the wrong errno substituted for %m. This is
  1065. * okay for the current usage with GUC check hooks, but might need further
  1066. * effort someday.
  1067. *
  1068. * The result of format_elog_string() is stored in ErrorContext, and will
  1069. * therefore survive until FlushErrorState() is called.
  1070. */
  1071. static int save_format_errnumber;
  1072. static const char *save_format_domain;
  1073. void
  1074. pre_format_elog_string(int errnumber, const char *domain)
  1075. {
  1076. /* Save errno before evaluation of argument functions can change it */
  1077. save_format_errnumber = errnumber;
  1078. /* Save caller's text domain */
  1079. save_format_domain = domain;
  1080. }
  1081. char *
  1082. format_elog_string(const char *fmt,...)
  1083. {
  1084. ErrorData errdata;
  1085. ErrorData *edata;
  1086. MemoryContext oldcontext;
  1087. /* Initialize a mostly-dummy error frame */
  1088. edata = &errdata;
  1089. MemSet(edata, 0, sizeof(ErrorData));
  1090. /* the default text domain is the backend's */
  1091. edata->domain = save_format_domain ? save_format_domain : PG_TEXTDOMAIN("postgres");
  1092. /* set the errno to be used to interpret %m */
  1093. edata->saved_errno = save_format_errnumber;
  1094. oldcontext = MemoryContextSwitchTo(ErrorContext);
  1095. EVALUATE_MESSAGE(edata->domain, message, false, true);
  1096. MemoryContextSwitchTo(oldcontext);
  1097. return edata->message;
  1098. }
  1099. /*
  1100. * Actual output of the top-of-stack error message
  1101. *
  1102. * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
  1103. * if the error is caught by somebody). For all other severity levels this
  1104. * is called by errfinish.
  1105. */
  1106. void
  1107. EmitErrorReport(void)
  1108. {
  1109. ErrorData *edata = &errordata[errordata_stack_depth];
  1110. MemoryContext oldcontext;
  1111. recursion_depth++;
  1112. CHECK_STACK_DEPTH();
  1113. oldcontext = MemoryContextSwitchTo(ErrorContext);
  1114. /*
  1115. * Call hook before sending message to log. The hook function is allowed
  1116. * to turn off edata->output_to_server, so we must recheck that afterward.
  1117. * Making any other change in the content of edata is not considered
  1118. * supported.
  1119. *
  1120. * Note: the reason why the hook can only turn off output_to_server, and
  1121. * not turn it on, is that it'd be unreliable: we will never get here at
  1122. * all if errstart() deems the message uninteresting. A hook that could
  1123. * make decisions in that direction would have to hook into errstart(),
  1124. * where it would have much less information available. emit_log_hook is
  1125. * intended for custom log filtering and custom log message transmission
  1126. * mechanisms.
  1127. */
  1128. if (edata->output_to_server && emit_log_hook)
  1129. (*emit_log_hook) (edata);
  1130. /* Send to server log, if enabled */
  1131. if (edata->output_to_server)
  1132. send_message_to_server_log(edata);
  1133. /* Send to client, if enabled */
  1134. if (edata->output_to_client)
  1135. send_message_to_frontend(edata);
  1136. MemoryContextSwitchTo(oldcontext);
  1137. recursion_depth--;
  1138. }
  1139. /*
  1140. * CopyErrorData --- obtain a copy of the topmost error stack entry
  1141. *
  1142. * This is only for use in error handler code. The data is copied into the
  1143. * current memory context, so callers should always switch away from
  1144. * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
  1145. */
  1146. ErrorData *
  1147. CopyErrorData(void)
  1148. {
  1149. ErrorData *edata = &errordata[errordata_stack_depth];
  1150. ErrorData *newedata;
  1151. /*
  1152. * we don't increment recursion_depth because out-of-memory here does not
  1153. * indicate a problem within the error subsystem.
  1154. */
  1155. CHECK_STACK_DEPTH();
  1156. Assert(CurrentMemoryContext != ErrorContext);
  1157. /* Copy the struct itself */
  1158. newedata = (ErrorData *) palloc(sizeof(ErrorData));
  1159. memcpy(newedata, edata, sizeof(ErrorData));
  1160. /* Make copies of separately-allocated fields */
  1161. if (newedata->message)
  1162. newedata->message = pstrdup(newedata->message);
  1163. if (newedata->detail)
  1164. newedata->detail = pstrdup(newedata->detail);
  1165. if (newedata->detail_log)
  1166. newedata->detail_log = pstrdup(newedata->detail_log);
  1167. if (newedata->hint)
  1168. newedata->hint = pstrdup(newedata->hint);
  1169. if (newedata->context)
  1170. newedata->context = pstrdup(newedata->context);
  1171. if (newedata->internalquery)
  1172. newedata->internalquery = pstrdup(newedata->internalquery);
  1173. return newedata;
  1174. }
  1175. /*
  1176. * FreeErrorData --- free the structure returned by CopyErrorData.
  1177. *
  1178. * Error handlers should use this in preference to assuming they know all
  1179. * the separately-allocated fields.
  1180. */
  1181. void
  1182. FreeErrorData(ErrorData *edata)
  1183. {
  1184. if (edata->message)
  1185. pfree(edata->message);
  1186. if (edata->detail)
  1187. pfree(edata->detail);
  1188. if (edata->detail_log)
  1189. pfree(edata->detail_log);
  1190. if (edata->hint)
  1191. pfree(edata->hint);
  1192. if (edata->context)
  1193. pfree(edata->context);
  1194. if (edata->internalquery)
  1195. pfree(edata->internalquery);
  1196. pfree(edata);
  1197. }
  1198. /*
  1199. * FlushErrorState --- flush the error state after error recovery
  1200. *
  1201. * This should be called by an error handler after it's done processing
  1202. * the error; or as soon as it's done CopyErrorData, if it intends to
  1203. * do stuff that is likely to provoke another error. You are not "out" of
  1204. * the error subsystem until you have done this.
  1205. */
  1206. void
  1207. FlushErrorState(void)
  1208. {
  1209. /*
  1210. * Reset stack to empty. The only case where it would be more than one
  1211. * deep is if we serviced an error that interrupted construction of
  1212. * another message. We assume control escaped out of that message
  1213. * construction and won't ever go back.
  1214. */
  1215. errordata_stack_depth = -1;
  1216. recursion_depth = 0;
  1217. /* Delete all data in ErrorContext */
  1218. MemoryContextResetAndDeleteChildren(ErrorContext);
  1219. }
  1220. /*
  1221. * ReThrowError --- re-throw a previously copied error
  1222. *
  1223. * A handler can do CopyErrorData/FlushErrorState to get out of the error
  1224. * subsystem, then do some processing, and finally ReThrowError to re-throw
  1225. * the original error. This is slower than just PG_RE_THROW() but should
  1226. * be used if the "some processing" is likely to incur another error.
  1227. */
  1228. void
  1229. ReThrowError(ErrorData *edata)
  1230. {
  1231. ErrorData *newedata;
  1232. Assert(edata->elevel == ERROR);
  1233. /* Push the data back into the error context */
  1234. recursion_depth++;
  1235. MemoryContextSwitchTo(ErrorContext);
  1236. if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
  1237. {
  1238. /*
  1239. * Wups, stack not big enough. We treat this as a PANIC condition
  1240. * because it suggests an infinite loop of errors during error
  1241. * recovery.
  1242. */
  1243. errordata_stack_depth = -1; /* make room on stack */
  1244. ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
  1245. }
  1246. newedata = &errordata[errordata_stack_depth];
  1247. memcpy(newedata, edata, sizeof(ErrorData));
  1248. /* Make copies of separately-allocated fields */
  1249. if (newedata->message)
  1250. newedata->message = pstrdup(newedata->message);
  1251. if (newedata->detail)
  1252. newedata->detail = pstrdup(newedata->detail);
  1253. if (newedata->detail_log)
  1254. newedata->detail_log = pstrdup(newedata->detail_log);
  1255. if (newedata->hint)
  1256. newedata->hint = pstrdup(newedata->hint);
  1257. if (newedata->context)
  1258. newedata->context = pstrdup(newedata->context);
  1259. if (newedata->internalquery)
  1260. newedata->internalquery = pstrdup(newedata->internalquery);
  1261. recursion_depth--;
  1262. PG_RE_THROW();
  1263. }
  1264. /*
  1265. * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
  1266. */
  1267. void
  1268. pg_re_throw(void)
  1269. {
  1270. /* If possible, throw the error to the next outer setjmp handler */
  1271. if (PG_exception_stack != NULL)
  1272. siglongjmp(*PG_exception_stack, 1);
  1273. else
  1274. {
  1275. /*
  1276. * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
  1277. * we have now exited only to discover that there is no outer setjmp
  1278. * handler to pass the error to. Had the error been thrown outside
  1279. * the block to begin with, we'd have promoted the error to FATAL, so
  1280. * the correct behavior is to make it FATAL now; that is, emit it and
  1281. * then call proc_exit.
  1282. */
  1283. ErrorData *edata = &errordata[errordata_stack_depth];
  1284. Assert(errordata_stack_depth >= 0);
  1285. Assert(edata->elevel == ERROR);
  1286. edata->elevel = FATAL;
  1287. /*
  1288. * At least in principle, the increase in severity could have changed
  1289. * where-to-output decisions, so recalculate. This should stay in
  1290. * sync with errstart(), which see for comments.
  1291. */
  1292. if (IsPostmasterEnvironment)
  1293. edata->output_to_server = is_log_level_output(FATAL,
  1294. log_min_messages);
  1295. else
  1296. edata->output_to_server = (FATAL >= log_min_messages);
  1297. if (whereToSendOutput == DestRemote)
  1298. {
  1299. if (ClientAuthInProgress)
  1300. edata->output_to_client = true;
  1301. else
  1302. edata->output_to_client = (FATAL >= client_min_messages);
  1303. }
  1304. /*
  1305. * We can use errfinish() for the rest, but we don't want it to call
  1306. * any error context routines a second time. Since we know we are
  1307. * about to exit, it should be OK to just clear the context stack.
  1308. */
  1309. error_context_stack = NULL;
  1310. errfinish(0);
  1311. }
  1312. /* Doesn't return ... */
  1313. ExceptionalCondition("pg_re_throw tried to return", "FailedAssertion",
  1314. __FILE__, __LINE__);
  1315. }
  1316. /*
  1317. * Initialization of error output file
  1318. */
  1319. void
  1320. DebugFileOpen(void)
  1321. {
  1322. int fd,
  1323. istty;
  1324. if (OutputFileName[0])
  1325. {
  1326. /*
  1327. * A debug-output file name was given.
  1328. *
  1329. * Make sure we can write the file, and find out if it's a tty.
  1330. */
  1331. if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
  1332. 0666)) < 0)
  1333. ereport(FATAL,
  1334. (errcode_for_file_access(),
  1335. errmsg("could not open file \"%s\": %m", OutputFileName)));
  1336. istty = isatty(fd);
  1337. close(fd);
  1338. /*
  1339. * Redirect our stderr to the debug output file.
  1340. */
  1341. if (!freopen(OutputFileName, "a", stderr))
  1342. ereport(FATAL,
  1343. (errcode_for_file_access(),
  1344. errmsg("could not reopen file \"%s\" as stderr: %m",
  1345. OutputFileName)));
  1346. /*
  1347. * If the file is a tty and we're running under the postmaster, try to
  1348. * send stdout there as well (if it isn't a tty then stderr will block
  1349. * out stdout, so we may as well let stdout go wherever it was going
  1350. * before).
  1351. */
  1352. if (istty && IsUnderPostmaster)
  1353. if (!freopen(OutputFileName, "a", stdout))
  1354. ereport(FATAL,
  1355. (errcode_for_file_access(),
  1356. errmsg("could not reopen file \"%s\" as stdout: %m",
  1357. OutputFileName)));
  1358. }
  1359. }
  1360. #ifdef HAVE_SYSLOG
  1361. /*
  1362. * Set or update the parameters for syslog logging
  1363. */
  1364. void
  1365. set_syslog_parameters(const char *ident, int facility)
  1366. {
  1367. /*
  1368. * guc.c is likely to call us repeatedly with same parameters, so don't
  1369. * thrash the syslog connection unnecessarily. Also, we do not re-open
  1370. * the connection until needed, since this routine will get called whether
  1371. * or not Log_destination actually mentions syslog.
  1372. *
  1373. * Note that we make our own copy of the ident string rather than relying
  1374. * on guc.c's. This may be overly paranoid, but it ensures that we cannot
  1375. * accidentally free a string that syslog is still using.
  1376. */
  1377. if (syslog_ident == NULL || strcmp(syslog_ident, ident) != 0 ||
  1378. syslog_facility != facility)
  1379. {
  1380. if (openlog_done)
  1381. {
  1382. closelog();
  1383. openlog_done = false;
  1384. }
  1385. if (syslog_ident)
  1386. free(syslog_ident);
  1387. syslog_ident = strdup(ident);
  1388. /* if the strdup fails, we will cope in write_syslog() */
  1389. syslog_facility = facility;
  1390. }
  1391. }
  1392. /*
  1393. * Write a message line to syslog
  1394. */
  1395. static void
  1396. write_syslog(int level, const char *line)
  1397. {
  1398. static unsigned long seq = 0;
  1399. int len;
  1400. const char *nlpos;
  1401. /* Open syslog connection if not done yet */
  1402. if (!openlog_done)
  1403. {
  1404. openlog(syslog_ident ? syslog_ident : "postgres",
  1405. LOG_PID | LOG_NDELAY | LOG_NOWAIT,
  1406. syslog_facility);
  1407. openlog_done = true;
  1408. }
  1409. /*
  1410. * We add a sequence number to each log message to suppress "same"
  1411. * messages.
  1412. */
  1413. seq++;
  1414. /*
  1415. * Our problem here is that many syslog implementations don't handle long
  1416. * messages in an acceptable manner. While this function doesn't help that
  1417. * fact, it does work around by splitting up messages into smaller pieces.
  1418. *
  1419. * We divide into multiple syslog() calls if message is too long or if the
  1420. * message contains embedded newline(s).
  1421. */
  1422. len = strlen(line);
  1423. nlpos = strchr(line, '\n');
  1424. if (len > PG_SYSLOG_LIMIT || nlpos != NULL)
  1425. {
  1426. int chunk_nr = 0;
  1427. while (len > 0)
  1428. {
  1429. char buf[PG_SYSLOG_LIMIT + 1];
  1430. int buflen;
  1431. int i;
  1432. /* if we start at a newline, move ahead one char */
  1433. if (line[0] == '\n')
  1434. {
  1435. line++;
  1436. len--;
  1437. /* we need to recompute the next newline's position, too */
  1438. nlpos = strchr(line, '\n');
  1439. continue;
  1440. }
  1441. /* copy one line, or as much as will fit, to buf */
  1442. if (nlpos != NULL)
  1443. buflen = nlpos - line;
  1444. else
  1445. buflen = len;
  1446. buflen = Min(buflen, PG_SYSLOG_LIMIT);
  1447. memcpy(buf, line, buflen);
  1448. buf[buflen] = '\0';
  1449. /* trim to multibyte letter boundary */
  1450. buflen = pg_mbcliplen(buf, buflen, buflen);
  1451. if (buflen <= 0)
  1452. return;
  1453. buf[buflen] = '\0';
  1454. /* already word boundary? */
  1455. if (line[buflen] != '\0' &&
  1456. !isspace((unsigned char) line[buflen]))
  1457. {
  1458. /* try to divide at word boundary */
  1459. i = buflen - 1;
  1460. while (i > 0 && !isspace((unsigned char) buf[i]))
  1461. i--;
  1462. if (i > 0) /* else couldn't divide word boundary */
  1463. {
  1464. buflen = i;
  1465. buf[i] = '\0';
  1466. }
  1467. }
  1468. chunk_nr++;
  1469. syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
  1470. line += buflen;
  1471. len -= buflen;
  1472. }
  1473. }
  1474. else
  1475. {
  1476. /* message short enough */
  1477. syslog(level, "[%lu] %s", seq, line);
  1478. }
  1479. }
  1480. #endif /* HAVE_SYSLOG */
  1481. #ifdef WIN32
  1482. /*
  1483. * Write a message line to the windows event log
  1484. */
  1485. static void
  1486. write_eventlog(int level, const char *line, int len)
  1487. {
  1488. WCHAR *utf16;
  1489. int eventlevel = EVENTLOG_ERROR_TYPE;
  1490. static HANDLE evtHandle = INVALID_HANDLE_VALUE;
  1491. if (evtHandle == INVALID_HANDLE_VALUE)
  1492. {
  1493. evtHandle = RegisterEventSource(NULL, event_source ? event_source : "PostgreSQL");
  1494. if (evtHandle == NULL)
  1495. {
  1496. evtHandle = INVALID_HANDLE_VALUE;
  1497. return;
  1498. }
  1499. }
  1500. switch (level)
  1501. {
  1502. case DEBUG5:
  1503. case DEBUG4:
  1504. case DEBUG3:
  1505. case DEBUG2:
  1506. case DEBUG1:
  1507. case LOG:
  1508. case COMMERROR:
  1509. case INFO:
  1510. case NOTICE:
  1511. eventlevel = EVENTLOG_INFORMATION_TYPE;
  1512. break;
  1513. case WARNING:
  1514. eventlevel = EVENTLOG_WARNING_TYPE;
  1515. break;
  1516. case ERROR:
  1517. case FATAL:
  1518. case PANIC:
  1519. default:
  1520. eventlevel = EVENTLOG_ERROR_TYPE;
  1521. break;
  1522. }
  1523. /*
  1524. * Convert message to UTF16 text and write it with ReportEventW, but
  1525. * fall-back into ReportEventA if conversion failed.
  1526. *
  1527. * Also verify that we are not on our way into error recursion trouble due
  1528. * to error messages thrown deep inside pgwin32_toUTF16().
  1529. */
  1530. if (GetDatabaseEncoding() != GetPlatformEncoding() &&
  1531. !in_error_recursion_trouble())
  1532. {
  1533. utf16 = pgwin32_toUTF16(line, len, NULL);
  1534. if (utf16)
  1535. {
  1536. ReportEventW(evtHandle,
  1537. eventlevel,
  1538. 0,
  1539. 0, /* All events are Id 0 */
  1540. NULL,
  1541. 1,
  1542. 0,
  1543. (LPCWSTR *) &utf16,
  1544. NULL);
  1545. pfree(utf16);
  1546. return;
  1547. }
  1548. }
  1549. ReportEventA(evtHandle,
  1550. eventlevel,
  1551. 0,
  1552. 0, /* All events are Id 0 */
  1553. NULL,
  1554. 1,
  1555. 0,
  1556. &line,
  1557. NULL);
  1558. }
  1559. #endif /* WIN32 */
  1560. static void
  1561. write_console(const char *line, int len)
  1562. {
  1563. int rc;
  1564. #ifdef WIN32
  1565. /*
  1566. * WriteConsoleW() will fail if stdout is redirected, so just fall through
  1567. * to writing unconverted to the logfile in this case.
  1568. *
  1569. * Since we palloc the structure required for conversion, also fall
  1570. * through to writing unconverted if we have not yet set up
  1571. * CurrentMemoryContext.
  1572. */
  1573. if (GetDatabaseEncoding() != GetPlatformEncoding() &&
  1574. !in_error_recursion_trouble() &&
  1575. !redirection_done &&
  1576. CurrentMemoryContext != NULL)
  1577. {
  1578. WCHAR *utf16;
  1579. int utf16len;
  1580. utf16 = pgwin32_toUTF16(line, len, &utf16len);
  1581. if (utf16 != NULL)
  1582. {
  1583. HANDLE stdHandle;
  1584. DWORD written;
  1585. stdHandle = GetStdHandle(STD_ERROR_HANDLE);
  1586. if (WriteConsoleW(stdHandle, utf16, utf16len, &written, NULL))
  1587. {
  1588. pfree(utf16);
  1589. return;
  1590. }
  1591. /*
  1592. * In case WriteConsoleW() failed, fall back to writing the
  1593. * message unconverted.
  1594. */
  1595. pfree(utf16);
  1596. }
  1597. }
  1598. #else
  1599. /*
  1600. * Conversion on non-win32 platforms is not implemented yet. It requires
  1601. * non-throw version of pg_do_encoding_conversion(), that converts
  1602. * unconvertable characters to '?' without errors.
  1603. */
  1604. #endif
  1605. /*
  1606. * We ignore any error from write() here. We have no useful way to report
  1607. * it ... certainly whining on stderr isn't likely to be productive.
  1608. */
  1609. rc = write(fileno(stderr), line, len);
  1610. (void) rc;
  1611. }
  1612. /*
  1613. * setup formatted_log_time, for consistent times between CSV and regular logs
  1614. */
  1615. static void
  1616. setup_formatted_log_time(void)
  1617. {
  1618. struct timeval tv;
  1619. pg_time_t stamp_time;
  1620. char msbuf[8];
  1621. gettimeofday(&tv, NULL);
  1622. stamp_time = (pg_time_t) tv.tv_sec;
  1623. /*
  1624. * Note: we expect that guc.c will ensure that log_timezone is set up (at
  1625. * least with a minimal GMT value) before Log_line_prefix can become
  1626. * nonempty or CSV mode can be selected.
  1627. */
  1628. pg_strftime(formatted_log_time, FORMATTED_TS_LEN,
  1629. /* leave room for milliseconds... */
  1630. "%Y-%m-%d %H:%M:%S %Z",
  1631. pg_localtime(&stamp_time, log_timezone));
  1632. /* 'paste' milliseconds into place... */
  1633. sprintf(msbuf, ".%03d", (int) (tv.tv_usec / 1000));
  1634. strncpy(formatted_log_time + 19, msbuf, 4);
  1635. }
  1636. /*
  1637. * setup formatted_start_time
  1638. */
  1639. static void
  1640. setup_formatted_start_time(void)
  1641. {
  1642. pg_time_t stamp_time = (pg_time_t) MyStartTime;
  1643. /*
  1644. * Note: we expect that guc.c will ensure that log_timezone is set up (at
  1645. * least with a minimal GMT value) before Log_line_prefix can become
  1646. * nonempty or CSV mode can be selected.
  1647. */
  1648. pg_strftime(formatted_start_time, FORMATTED_TS_LEN,
  1649. "%Y-%m-%d %H:%M:%S %Z",
  1650. pg_localtime(&stamp_time, log_timezone));
  1651. }
  1652. /*
  1653. * Format tag info for log lines; append to the provided buffer.
  1654. */
  1655. static void
  1656. log_line_prefix(StringInfo buf, ErrorData *edata)
  1657. {
  1658. /* static counter for line numbers */
  1659. static long log_line_number = 0;
  1660. /* has counter been reset in current process? */
  1661. static int log_my_pid = 0;
  1662. int format_len;
  1663. int i;
  1664. /*
  1665. * This is one of the few places where we'd rather not inherit a static
  1666. * variable's value from the postmaster. But since we will, reset it when
  1667. * MyProcPid changes. MyStartTime also changes when MyProcPid does, so
  1668. * reset the formatted start timestamp too.
  1669. */
  1670. if (log_my_pid != MyProcPid)
  1671. {
  1672. log_line_number = 0;
  1673. log_my_pid = MyProcPid;
  1674. formatted_start_time[0] = '\0';
  1675. }
  1676. log_line_number++;
  1677. if (Log_line_prefix == NULL)
  1678. return; /* in case guc hasn't run yet */
  1679. format_len = strlen(Log_line_prefix);
  1680. for (i = 0; i < format_len; i++)
  1681. {
  1682. if (Log_line_prefix[i] != '%')
  1683. {
  1684. /* literal char, just copy */
  1685. appendStringInfoChar(buf, Log_line_prefix[i]);
  1686. continue;
  1687. }
  1688. /* go to char after '%' */
  1689. i++;
  1690. if (i >= format_len)
  1691. break; /* format error - ignore it */
  1692. /* process the option */
  1693. switch (Log_line_prefix[i])
  1694. {
  1695. case 'a':
  1696. if (MyProcPort)
  1697. {
  1698. const char *appname = application_name;
  1699. if (appname == NULL || *appname == '\0')
  1700. appname = _("[unknown]");
  1701. appendStringInfoString(buf, appname);
  1702. }
  1703. break;
  1704. case 'u':
  1705. if (MyProcPort)
  1706. {
  1707. const char *username = MyProcPort->user_name;
  1708. if (username == NULL || *username == '\0')
  1709. username = _("[unknown]");
  1710. appendStringInfoString(buf, username);
  1711. }
  1712. break;
  1713. case 'd':
  1714. if (MyProcPort)
  1715. {
  1716. const char *dbname = MyProcPort->database_name;
  1717. if (dbname == NULL || *dbname == '\0')
  1718. dbname = _("[unknown]");
  1719. appendStringInfoString(buf, dbname);
  1720. }
  1721. break;
  1722. case 'c':
  1723. appendStringInfo(buf, "%lx.%04x", (long) (MyStartTime), MyProcPid);
  1724. break;
  1725. case 'p':
  1726. appendStringInfo(buf, "%d", MyProcPid);
  1727. break;
  1728. case 'l':
  1729. appendStringInfo(buf, "%ld", log_line_number);
  1730. break;
  1731. case 'm':
  1732. setup_formatted_log_time();
  1733. appendStringInfoString(buf, formatted_log_time);
  1734. break;
  1735. case 't':
  1736. {
  1737. pg_time_t stamp_time = (pg_time_t) time(NULL);
  1738. char strfbuf[128];
  1739. pg_strftime(strfbuf, sizeof(strfbuf),
  1740. "%Y-%m-%d %H:%M:%S %Z",
  1741. pg_localtime(&stamp_time, log_timezone));
  1742. appendStringInfoString(buf, strfbuf);
  1743. }
  1744. break;
  1745. case 's':
  1746. if (formatted_start_time[0] == '\0')
  1747. setup_formatted_start_time();
  1748. appendStringInfoString(buf, formatted_start_time);
  1749. break;
  1750. case 'i':
  1751. if (MyProcPort)
  1752. {
  1753. const char *psdisp;
  1754. int displen;
  1755. psdisp = get_ps_display(&displen);
  1756. appendBinaryStringInfo(buf, psdisp, displen);
  1757. }
  1758. break;
  1759. case 'r':
  1760. if (MyProcPort && MyProcPort->remote_host)
  1761. {
  1762. appendStringInfoString(buf, MyProcPort->remote_host);
  1763. if (MyProcPort->remote_port &&
  1764. MyProcPort->remote_port[0] != '\0')
  1765. appendStringInfo(buf, "(%s)",
  1766. MyProcPort->remote_port);
  1767. }
  1768. break;
  1769. case 'h':
  1770. if (MyProcPort && MyProcPort->remote_host)
  1771. appendStringInfoString(buf, MyProcPort->remote_host);
  1772. break;
  1773. case 'q':
  1774. /* in postmaster and friends, stop if %q is seen */
  1775. /* in a backend, just ignore */
  1776. if (MyProcPort == NULL)
  1777. i = format_len;
  1778. break;
  1779. case 'v':
  1780. /* keep VXID format in sync with lockfuncs.c */
  1781. if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
  1782. appendStringInfo(buf, "%d/%u",
  1783. MyProc->backendId, MyProc->lxid);
  1784. break;
  1785. case 'x':
  1786. appendStringInfo(buf, "%u", GetTopTransactionIdIfAny());
  1787. break;
  1788. case 'e':
  1789. appendStringInfoString(buf, unpack_sql_state(edata->sqlerrcode));
  1790. break;
  1791. case '%':
  1792. appendStringInfoChar(buf, '%');
  1793. break;
  1794. default:
  1795. /* format error - ignore it */
  1796. break;
  1797. }
  1798. }
  1799. }
  1800. /*
  1801. * append a CSV'd version of a string to a StringInfo
  1802. * We use the PostgreSQL defaults for CSV, i.e. quote = escape = '"'
  1803. * If it's NULL, append nothing.
  1804. */
  1805. static inline void
  1806. appendCSVLiteral(StringInfo buf, const char *data)
  1807. {
  1808. const char *p = data;
  1809. char c;
  1810. /* avoid confusing an empty string with NULL */
  1811. if (p == NULL)
  1812. return;
  1813. appendStringInfoCharMacro(buf, '"');
  1814. while ((c = *p++) != '\0')
  1815. {
  1816. if (c == '"')
  1817. appendStringInfoCharMacro(buf, '"');
  1818. appendStringInfoCharMacro(buf, c);
  1819. }
  1820. appendStringInfoCharMacro(buf, '"');
  1821. }
  1822. /*
  1823. * Constructs the error message, depending on the Errordata it gets, in a CSV
  1824. * format which is described in doc/src/sgml/config.sgml.
  1825. */
  1826. static void
  1827. write_csvlog(ErrorData *edata)
  1828. {
  1829. StringInfoData buf;
  1830. bool print_stmt = false;
  1831. /* static counter for line numbers */
  1832. static long log_line_number = 0;
  1833. /* has counter been reset in current process? */
  1834. static int log_my_pid = 0;
  1835. /*
  1836. * This is one of the few places where we'd rather not inherit a static
  1837. * variable's value from the postmaster. But since we will, reset it when
  1838. * MyProcPid changes.
  1839. */
  1840. if (log_my_pid != MyProcPid)
  1841. {
  1842. log_line_number = 0;
  1843. log_my_pid = MyProcPid;
  1844. formatted_start_time[0] = '\0';
  1845. }
  1846. log_line_number++;
  1847. initStringInfo(&buf);
  1848. /*
  1849. * timestamp with milliseconds
  1850. *
  1851. * Check if the timestamp is already calculated for the syslog message,
  1852. * and use it if so. Otherwise, get the current timestamp. This is done
  1853. * to put same timestamp in both syslog and csvlog messages.
  1854. */
  1855. if (formatted_log_time[0] == '\0')
  1856. setup_formatted_log_time();
  1857. appendStringInfoString(&buf, formatted_log_time);
  1858. appendStringInfoChar(&buf, ',');
  1859. /* username */
  1860. if (MyProcPort)
  1861. appendCSVLiteral(&buf, MyProcPort->user_name);
  1862. appendStringInfoChar(&buf, ',');
  1863. /* database name */
  1864. if (MyProcPort)
  1865. appendCSVLiteral(&buf, MyProcPort->database_name);
  1866. appendStringInfoChar(&buf, ',');
  1867. /* Process id */
  1868. if (MyProcPid != 0)
  1869. appendStringInfo(&buf, "%d", MyProcPid);
  1870. appendStringInfoChar(&buf, ',');
  1871. /* Remote host and port */
  1872. if (MyProcPort && MyProcPort->remote_host)
  1873. {
  1874. appendStringInfoChar(&buf, '"');
  1875. appendStringInfoString(&buf, MyProcPort->remote_host);
  1876. if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
  1877. {
  1878. appendStringInfoChar(&buf, ':');
  1879. appendStringInfoString(&buf, MyProcPort->remote_port);
  1880. }
  1881. appendStringInfoChar(&buf, '"');
  1882. }
  1883. appendStringInfoChar(&buf, ',');
  1884. /* session id */
  1885. appendStringInfo(&buf, "%lx.%04x", (long) MyStartTime, MyProcPid);
  1886. appendStringInfoChar(&buf, ',');
  1887. /* Line number */
  1888. appendStringInfo(&buf, "%ld", log_line_number);
  1889. appendStringInfoChar(&buf, ',');
  1890. /* PS display */
  1891. if (MyProcPort)
  1892. {
  1893. StringInfoData msgbuf;
  1894. const char *psdisp;
  1895. int displen;
  1896. initStringInfo(&msgbuf);
  1897. psdisp = get_ps_display(&displen);
  1898. appendBinaryStringInfo(&msgbuf, psdisp, displen);
  1899. appendCSVLiteral(&buf, msgbuf.data);
  1900. pfree(msgbuf.data);
  1901. }
  1902. appendStringInfoChar(&buf, ',');
  1903. /* session start timestamp */
  1904. if (formatted_start_time[0] == '\0')
  1905. setup_formatted_start_time();
  1906. appendStringInfoString(&buf, formatted_start_time);
  1907. appendStringInfoChar(&buf, ',');
  1908. /* Virtual transaction id */
  1909. /* keep VXID format in sync with lockfuncs.c */
  1910. if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
  1911. appendStringInfo(&buf, "%d/%u", MyProc->backendId, MyProc->lxid);
  1912. appendStringInfoChar(&buf, ',');
  1913. /* Transaction id */
  1914. appendStringInfo(&buf, "%u", GetTopTransactionIdIfAny());
  1915. appendStringInfoChar(&buf, ',');
  1916. /* Error severity */
  1917. appendStringInfoString(&buf, error_severity(edata->elevel));
  1918. appendStringInfoChar(&buf, ',');
  1919. /* SQL state code */
  1920. appendStringInfoString(&buf, unpack_sql_state(edata->sqlerrcode));
  1921. appendStringInfoChar(&buf, ',');
  1922. /* errmessage */
  1923. appendCSVLiteral(&buf, edata->message);
  1924. appendStringInfoChar(&buf, ',');
  1925. /* errdetail or errdetail_log */
  1926. if (edata->detail_log)
  1927. appendCSVLiteral(&buf, edata->detail_log);
  1928. else
  1929. appendCSVLiteral(&buf, edata->detail);
  1930. appendStringInfoChar(&buf, ',');
  1931. /* errhint */
  1932. appendCSVLiteral(&buf, edata->hint);
  1933. appendStringInfoChar(&buf, ',');
  1934. /* internal query */
  1935. appendCSVLiteral(&buf, edata->internalquery);
  1936. appendStringInfoChar(&buf, ',');
  1937. /* if printed internal query, print internal pos too */
  1938. if (edata->internalpos > 0 && edata->internalquery != NULL)
  1939. appendStringInfo(&buf, "%d", edata->internalpos);
  1940. appendStringInfoChar(&buf, ',');
  1941. /* errcontext */
  1942. appendCSVLiteral(&buf, edata->context);
  1943. appendStringInfoChar(&buf, ',');
  1944. /* user query --- only reported if not disabled by the caller */
  1945. if (is_log_level_output(edata->elevel, log_min_error_statement) &&
  1946. debug_query_string != NULL &&
  1947. !edata->hide_stmt)
  1948. print_stmt = true;
  1949. if (print_stmt)
  1950. appendCSVLiteral(&buf, debug_query_string);
  1951. appendStringInfoChar(&buf, ',');
  1952. if (print_stmt && edata->cursorpos > 0)
  1953. appendStringInfo(&buf, "%d", edata->cursorpos);
  1954. appendStringInfoChar(&buf, ',');
  1955. /* file error location */
  1956. if (Log_error_verbosity >= PGERROR_VERBOSE)
  1957. {
  1958. StringInfoData msgbuf;
  1959. initStringInfo(&msgbuf);
  1960. if (edata->funcname && edata->filename)
  1961. appendStringInfo(&msgbuf, "%s, %s:%d",
  1962. edata->funcname, edata->filename,
  1963. edata->lineno);
  1964. else if (edata->filename)
  1965. appendStringInfo(&msgbuf, "%s:%d",
  1966. edata->filename, edata->lineno);
  1967. appendCSVLiteral(&buf, msgbuf.data);
  1968. pfree(msgbuf.data);
  1969. }
  1970. appendStringInfoChar(&buf, ',');
  1971. /* application name */
  1972. if (application_name)
  1973. appendCSVLiteral(&buf, application_name);
  1974. appendStringInfoChar(&buf, '\n');
  1975. /* If in the syslogger process, try to write messages direct to file */
  1976. if (am_syslogger)
  1977. write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
  1978. else
  1979. write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
  1980. pfree(buf.data);
  1981. }
  1982. /*
  1983. * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
  1984. * static buffer.
  1985. */
  1986. char *
  1987. unpack_sql_state(int sql_state)
  1988. {
  1989. static char buf[12];
  1990. int i;
  1991. for (i = 0; i < 5; i++)
  1992. {
  1993. buf[i] = PGUNSIXBIT(sql_state);
  1994. sql_state >>= 6;
  1995. }
  1996. buf[i] = '\0';
  1997. return buf;
  1998. }
  1999. /*
  2000. * Write error report to server's log
  2001. */
  2002. static void
  2003. send_message_to_server_log(ErrorData *edata)
  2004. {
  2005. StringInfoData buf;
  2006. initStringInfo(&buf);
  2007. formatted_log_time[0] = '\0';
  2008. log_line_prefix(&buf, edata);
  2009. appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
  2010. if (Log_error_verbosity >= PGERROR_VERBOSE)
  2011. appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
  2012. if (edata->message)
  2013. append_with_tabs(&buf, edata->message);
  2014. else
  2015. append_with_tabs(&buf, _("missing error text"));
  2016. if (edata->cursorpos > 0)
  2017. appendStringInfo(&buf, _(" at character %d"),
  2018. edata->cursorpos);
  2019. else if (edata->internalpos > 0)
  2020. appendStringInfo(&buf, _(" at character %d"),
  2021. edata->internalpos);
  2022. appendStringInfoChar(&buf, '\n');
  2023. if (Log_error_verbosity >= PGERROR_DEFAULT)
  2024. {
  2025. if (edata->detail_log)
  2026. {
  2027. log_line_prefix(&buf, edata);
  2028. appendStringInfoString(&buf, _("DETAIL: "));
  2029. append_with_tabs(&buf, edata->detail_log);
  2030. appendStringInfoChar(&buf, '\n');
  2031. }
  2032. else if (edata->detail)
  2033. {
  2034. log_line_prefix(&buf, edata);
  2035. appendStringInfoString(&buf, _("DETAIL: "));
  2036. append_with_tabs(&buf, edata->detail);
  2037. appendStringInfoChar(&buf, '\n');
  2038. }
  2039. if (edata->hint)
  2040. {
  2041. log_line_prefix(&buf, edata);
  2042. appendStringInfoString(&buf, _("HINT: "));
  2043. append_with_tabs(&buf, edata->hint);
  2044. appendStringInfoChar(&buf, '\n');
  2045. }
  2046. if (edata->internalquery)
  2047. {
  2048. log_line_prefix(&buf, edata);
  2049. appendStringInfoString(&buf, _("QUERY: "));
  2050. append_with_tabs(&buf, edata->internalquery);
  2051. appendStringInfoChar(&buf, '\n');
  2052. }
  2053. if (edata->context)
  2054. {
  2055. log_line_prefix(&buf, edata);
  2056. appendStringInfoString(&buf, _("CONTEXT: "));
  2057. append_with_tabs(&buf, edata->context);
  2058. appendStringInfoChar(&buf, '\n');
  2059. }
  2060. if (Log_error_verbosity >= PGERROR_VERBOSE)
  2061. {
  2062. /* assume no newlines in funcname or filename... */
  2063. if (edata->funcname && edata->filename)
  2064. {
  2065. log_line_prefix(&buf, edata);
  2066. appendStringInfo(&buf, _("LOCATION: %s, %s:%d\n"),
  2067. edata->funcname, edata->filename,
  2068. edata->lineno);
  2069. }
  2070. else if (edata->filename)
  2071. {
  2072. log_line_prefix(&buf, edata);
  2073. appendStringInfo(&buf, _("LOCATION: %s:%d\n"),
  2074. edata->filename, edata->lineno);
  2075. }
  2076. }
  2077. }
  2078. /*
  2079. * If the user wants the query that generated this error logged, do it.
  2080. */
  2081. if (is_log_level_output(edata->elevel, log_min_error_statement) &&
  2082. debug_query_string != NULL &&
  2083. !edata->hide_stmt)
  2084. {
  2085. log_line_prefix(&buf, edata);
  2086. appendStringInfoString(&buf, _("STATEMENT: "));
  2087. append_with_tabs(&buf, debug_query_string);
  2088. appendStringInfoChar(&buf, '\n');
  2089. }
  2090. #ifdef HAVE_SYSLOG
  2091. /* Write to syslog, if enabled */
  2092. if (Log_destination & LOG_DESTINATION_SYSLOG)
  2093. {
  2094. int syslog_level;
  2095. switch (edata->elevel)
  2096. {
  2097. case DEBUG5:
  2098. case DEBUG4:
  2099. case DEBUG3:
  2100. case DEBUG2:
  2101. case DEBUG1:
  2102. syslog_level = LOG_DEBUG;
  2103. break;
  2104. case LOG:
  2105. case COMMERROR:
  2106. case INFO:
  2107. syslog_level = LOG_INFO;
  2108. break;
  2109. case NOTICE:
  2110. case WARNING:
  2111. syslog_level = LOG_NOTICE;
  2112. break;
  2113. case ERROR:
  2114. syslog_level = LOG_WARNING;
  2115. break;
  2116. case FATAL:
  2117. syslog_level = LOG_ERR;
  2118. break;
  2119. case PANIC:
  2120. default:
  2121. syslog_level = LOG_CRIT;
  2122. break;
  2123. }
  2124. write_syslog(syslog_level, buf.data);
  2125. }
  2126. #endif /* HAVE_SYSLOG */
  2127. #ifdef WIN32
  2128. /* Write to eventlog, if enabled */
  2129. if (Log_destination & LOG_DESTINATION_EVENTLOG)
  2130. {
  2131. write_eventlog(edata->elevel, buf.data, buf.len);
  2132. }
  2133. #endif /* WIN32 */
  2134. /* Write to stderr, if enabled */
  2135. if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == DestDebug)
  2136. {
  2137. /*
  2138. * Use the chunking protocol if we know the syslogger should be
  2139. * catching stderr output, and we are not ourselves the syslogger.
  2140. * Otherwise, just do a vanilla write to stderr.
  2141. */
  2142. if (redirection_done && !am_syslogger)
  2143. write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_STDERR);
  2144. #ifdef WIN32
  2145. /*
  2146. * In a win32 service environment, there is no usable stderr. Capture
  2147. * anything going there and write it to the eventlog instead.
  2148. *
  2149. * If stderr redirection is active, it was OK to write to stderr above
  2150. * because that's really a pipe to the syslogger process.
  2151. */
  2152. else if (pgwin32_is_service())
  2153. write_eventlog(edata->elevel, buf.data, buf.len);
  2154. #endif
  2155. else
  2156. write_console(buf.data, buf.len);
  2157. }
  2158. /* If in the syslogger process, try to write messages direct to file */
  2159. if (am_syslogger)
  2160. write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_STDERR);
  2161. /* Write to CSV log if enabled */
  2162. if (Log_destination & LOG_DESTINATION_CSVLOG)
  2163. {
  2164. if (redirection_done || am_syslogger)
  2165. {
  2166. /*
  2167. * send CSV data if it's safe to do so (syslogger doesn't need the
  2168. * pipe). First get back the space in the message buffer.
  2169. */
  2170. pfree(buf.data);
  2171. write_csvlog(edata);
  2172. }
  2173. else
  2174. {
  2175. /*
  2176. * syslogger not up (yet), so just dump the message to stderr,
  2177. * unless we already did so above.
  2178. */
  2179. if (!(Log_destination & LOG_DESTINATION_STDERR) &&
  2180. whereToSendOutput != DestDebug)
  2181. write_console(buf.data, buf.len);
  2182. pfree(buf.data);
  2183. }
  2184. }
  2185. else
  2186. {
  2187. pfree(buf.data);
  2188. }
  2189. }
  2190. /*
  2191. * Send data to the syslogger using the chunked protocol
  2192. *
  2193. * Note: when there are multiple backends writing into the syslogger pipe,
  2194. * it's critical that each write go into the pipe indivisibly, and not
  2195. * get interleaved with data from other processes. Fortunately, the POSIX
  2196. * spec requires that writes to pipes be atomic so long as they are not
  2197. * more than PIPE_BUF bytes long. So we divide long messages into chunks
  2198. * that are no more than that length, and send one chunk per write() call.
  2199. * The collector process knows how to reassemble the chunks.
  2200. *
  2201. * Because of the atomic write requirement, there are only two possible
  2202. * results from write() here: -1 for failure, or the requested number of
  2203. * bytes. There is not really anything we can do about a failure; retry would
  2204. * probably be an infinite loop, and we can't even report the error usefully.
  2205. * (There is noplace else we could send it!) So we might as well just ignore
  2206. * the result from write(). However, on some platforms you get a compiler
  2207. * warning from ignoring write()'s result, so do a little dance with casting
  2208. * rc to void to shut up the compiler.
  2209. */
  2210. static void
  2211. write_pipe_chunks(char *data, int len, int dest)
  2212. {
  2213. PipeProtoChunk p;
  2214. int fd = fileno(stderr);
  2215. int rc;
  2216. Assert(len > 0);
  2217. p.proto.nuls[0] = p.proto.nuls[1] = '\0';
  2218. p.proto.pid = MyProcPid;
  2219. /* write all but the last chunk */
  2220. while (len > PIPE_MAX_PAYLOAD)
  2221. {
  2222. p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'F' : 'f');
  2223. p.proto.len = PIPE_MAX_PAYLOAD;
  2224. memcpy(p.proto.data, data, PIPE_MAX_PAYLOAD);
  2225. rc = write(fd, &p, PIPE_HEADER_SIZE + PIPE_MAX_PAYLOAD);
  2226. (void) rc;
  2227. data += PIPE_MAX_PAYLOAD;
  2228. len -= PIPE_MAX_PAYLOAD;
  2229. }
  2230. /* write the last chunk */
  2231. p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'T' : 't');
  2232. p.proto.len = len;
  2233. memcpy(p.proto.data, data, len);
  2234. rc = write(fd, &p, PIPE_HEADER_SIZE + len);
  2235. (void) rc;
  2236. }
  2237. /*
  2238. * Append a text string to the error report being built for the client.
  2239. *
  2240. * This is ordinarily identical to pq_sendstring(), but if we are in
  2241. * error recursion trouble we skip encoding conversion, because of the
  2242. * possibility that the problem is a failure in the encoding conversion
  2243. * subsystem itself. Code elsewhere should ensure that the passed-in
  2244. * strings will be plain 7-bit ASCII, and thus not in need of conversion,
  2245. * in such cases. (In particular, we disable localization of error messages
  2246. * to help ensure that's true.)
  2247. */
  2248. static void
  2249. err_sendstring(StringInfo buf, const char *str)
  2250. {
  2251. if (in_error_recursion_trouble())
  2252. pq_send_ascii_string(buf, str);
  2253. else
  2254. pq_sendstring(buf, str);
  2255. }
  2256. /*
  2257. * Write error report to client
  2258. */
  2259. static void
  2260. send_message_to_frontend(ErrorData *edata)
  2261. {
  2262. StringInfoData msgbuf;
  2263. /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
  2264. pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
  2265. if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
  2266. {
  2267. /* New style with separate fields */
  2268. char tbuf[12];
  2269. int ssval;
  2270. int i;
  2271. pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
  2272. err_sendstring(&msgbuf, error_severity(edata->elevel));
  2273. /* unpack MAKE_SQLSTATE code */
  2274. ssval = edata->sqlerrcode;
  2275. for (i = 0; i < 5; i++)
  2276. {
  2277. tbuf[i] = PGUNSIXBIT(ssval);
  2278. ssval >>= 6;
  2279. }
  2280. tbuf[i] = '\0';
  2281. pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
  2282. err_sendstring(&msgbuf, tbuf);
  2283. /* M field is required per protocol, so always send something */
  2284. pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
  2285. if (edata->message)
  2286. err_sendstring(&msgbuf, edata->message);
  2287. else
  2288. err_sendstring(&msgbuf, _("missing error text"));
  2289. if (edata->detail)
  2290. {
  2291. pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
  2292. err_sendstring(&msgbuf, edata->detail);
  2293. }
  2294. /* detail_log is intentionally not used here */
  2295. if (edata->hint)
  2296. {
  2297. pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
  2298. err_sendstring(&msgbuf, edata->hint);
  2299. }
  2300. if (edata->context)
  2301. {
  2302. pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
  2303. err_sendstring(&msgbuf, edata->context);
  2304. }
  2305. if (edata->cursorpos > 0)
  2306. {
  2307. snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
  2308. pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
  2309. err_sendstring(&msgbuf, tbuf);
  2310. }
  2311. if (edata->internalpos > 0)
  2312. {
  2313. snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
  2314. pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
  2315. err_sendstring(&msgbuf, tbuf);
  2316. }
  2317. if (edata->internalquery)
  2318. {
  2319. pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
  2320. err_sendstring(&msgbuf, edata->internalquery);
  2321. }
  2322. if (edata->filename)
  2323. {
  2324. pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
  2325. err_sendstring(&msgbuf, edata->filename);
  2326. }
  2327. if (edata->lineno > 0)
  2328. {
  2329. snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
  2330. pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
  2331. err_sendstring(&msgbuf, tbuf);
  2332. }
  2333. if (edata->funcname)
  2334. {
  2335. pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
  2336. err_sendstring(&msgbuf, edata->funcname);
  2337. }
  2338. pq_sendbyte(&msgbuf, '\0'); /* terminator */
  2339. }
  2340. else
  2341. {
  2342. /* Old style --- gin up a backwards-compatible message */
  2343. StringInfoData buf;
  2344. initStringInfo(&buf);
  2345. appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
  2346. if (edata->show_funcname && edata->funcname)
  2347. appendStringInfo(&buf, "%s: ", edata->funcname);
  2348. if (edata->message)
  2349. appendStringInfoString(&buf, edata->message);
  2350. else
  2351. appendStringInfoString(&buf, _("missing error text"));
  2352. if (edata->cursorpos > 0)
  2353. appendStringInfo(&buf, _(" at character %d"),
  2354. edata->cursorpos);
  2355. else if (edata->internalpos > 0)
  2356. appendStringInfo(&buf, _(" at character %d"),
  2357. edata->internalpos);
  2358. appendStringInfoChar(&buf, '\n');
  2359. err_sendstring(&msgbuf, buf.data);
  2360. pfree(buf.data);
  2361. }
  2362. pq_endmessage(&msgbuf);
  2363. /*
  2364. * This flush is normally not necessary, since postgres.c will flush out
  2365. * waiting data when control returns to the main loop. But it seems best
  2366. * to leave it here, so that the client has some clue what happened if the
  2367. * backend dies before getting back to the main loop ... error/notice
  2368. * messages should not be a performance-critical path anyway, so an extra
  2369. * flush won't hurt much ...
  2370. */
  2371. pq_flush();
  2372. }
  2373. /*
  2374. * Support routines for formatting error messages.
  2375. */
  2376. /*
  2377. * expand_fmt_string --- process special format codes in a format string
  2378. *
  2379. * We must replace %m with the appropriate strerror string, since vsnprintf
  2380. * won't know what to do with it.
  2381. *
  2382. * The result is a palloc'd string.
  2383. */
  2384. static char *
  2385. expand_fmt_string(const char *fmt, ErrorData *edata)
  2386. {
  2387. StringInfoData buf;
  2388. const char *cp;
  2389. initStringInfo(&buf);
  2390. for (cp = fmt; *cp; cp++)
  2391. {
  2392. if (cp[0] == '%' && cp[1] != '\0')
  2393. {
  2394. cp++;
  2395. if (*cp == 'm')
  2396. {
  2397. /*
  2398. * Replace %m by system error string. If there are any %'s in
  2399. * the string, we'd better double them so that vsnprintf won't
  2400. * misinterpret.
  2401. */
  2402. const char *cp2;
  2403. cp2 = useful_strerror(edata->saved_errno);
  2404. for (; *cp2; cp2++)
  2405. {
  2406. if (*cp2 == '%')
  2407. appendStringInfoCharMacro(&buf, '%');
  2408. appendStringInfoCharMacro(&buf, *cp2);
  2409. }
  2410. }
  2411. else
  2412. {
  2413. /* copy % and next char --- this avoids trouble with %%m */
  2414. appendStringInfoCharMacro(&buf, '%');
  2415. appendStringInfoCharMacro(&buf, *cp);
  2416. }
  2417. }
  2418. else
  2419. appendStringInfoCharMacro(&buf, *cp);
  2420. }
  2421. return buf.data;
  2422. }
  2423. /*
  2424. * A slightly cleaned-up version of strerror()
  2425. */
  2426. static const char *
  2427. useful_strerror(int errnum)
  2428. {
  2429. /* this buffer is only used if errno has a bogus value */
  2430. static char errorstr_buf[48];
  2431. const char *str;
  2432. #ifdef WIN32
  2433. /* Winsock error code range, per WinError.h */
  2434. if (errnum >= 10000 && errnum <= 11999)
  2435. return pgwin32_socket_strerror(errnum);
  2436. #endif
  2437. str = strerror(errnum);
  2438. /*
  2439. * Some strerror()s return an empty string for out-of-range errno. This is
  2440. * ANSI C spec compliant, but not exactly useful.
  2441. */
  2442. if (str == NULL || *str == '\0')
  2443. {
  2444. snprintf(errorstr_buf, sizeof(errorstr_buf),
  2445. /*------
  2446. translator: This string will be truncated at 47
  2447. characters expanded. */
  2448. _("operating system error %d"), errnum);
  2449. str = errorstr_buf;
  2450. }
  2451. return str;
  2452. }
  2453. /*
  2454. * error_severity --- get localized string representing elevel
  2455. */
  2456. static const char *
  2457. error_severity(int elevel)
  2458. {
  2459. const char *prefix;
  2460. switch (elevel)
  2461. {
  2462. case DEBUG1:
  2463. case DEBUG2:
  2464. case DEBUG3:
  2465. case DEBUG4:
  2466. case DEBUG5:
  2467. prefix = _("DEBUG");
  2468. break;
  2469. case LOG:
  2470. case COMMERROR:
  2471. prefix = _("LOG");
  2472. break;
  2473. case INFO:
  2474. prefix = _("INFO");
  2475. break;
  2476. case NOTICE:
  2477. prefix = _("NOTICE");
  2478. break;
  2479. case WARNING:
  2480. prefix = _("WARNING");
  2481. break;
  2482. case ERROR:
  2483. prefix = _("ERROR");
  2484. break;
  2485. case FATAL:
  2486. prefix = _("FATAL");
  2487. break;
  2488. case PANIC:
  2489. prefix = _("PANIC");
  2490. break;
  2491. default:
  2492. prefix = "???";
  2493. break;
  2494. }
  2495. return prefix;
  2496. }
  2497. /*
  2498. * append_with_tabs
  2499. *
  2500. * Append the string to the StringInfo buffer, inserting a tab after any
  2501. * newline.
  2502. */
  2503. static void
  2504. append_with_tabs(StringInfo buf, const char *str)
  2505. {
  2506. char ch;
  2507. while ((ch = *str++) != '\0')
  2508. {
  2509. appendStringInfoCharMacro(buf, ch);
  2510. if (ch == '\n')
  2511. appendStringInfoCharMacro(buf, '\t');
  2512. }
  2513. }
  2514. /*
  2515. * Write errors to stderr (or by equal means when stderr is
  2516. * not available). Used before ereport/elog can be used
  2517. * safely (memory context, GUC load etc)
  2518. */
  2519. void
  2520. write_stderr(const char *fmt,...)
  2521. {
  2522. va_list ap;
  2523. #ifdef WIN32
  2524. char errbuf[2048]; /* Arbitrary size? */
  2525. #endif
  2526. fmt = _(fmt);
  2527. va_start(ap, fmt);
  2528. #ifndef WIN32
  2529. /* On Unix, we just fprintf to stderr */
  2530. vfprintf(stderr, fmt, ap);
  2531. fflush(stderr);
  2532. #else
  2533. vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
  2534. /*
  2535. * On Win32, we print to stderr if running on a console, or write to
  2536. * eventlog if running as a service
  2537. */
  2538. if (pgwin32_is_service()) /* Running as a service */
  2539. {
  2540. write_eventlog(ERROR, errbuf, strlen(errbuf));
  2541. }
  2542. else
  2543. {
  2544. /* Not running as service, write to stderr */
  2545. write_console(errbuf, strlen(errbuf));
  2546. fflush(stderr);
  2547. }
  2548. #endif
  2549. va_end(ap);
  2550. }
  2551. /*
  2552. * is_log_level_output -- is elevel logically >= log_min_level?
  2553. *
  2554. * We use this for tests that should consider LOG to sort out-of-order,
  2555. * between ERROR and FATAL. Generally this is the right thing for testing
  2556. * whether a message should go to the postmaster log, whereas a simple >=
  2557. * test is correct for testing whether the message should go to the client.
  2558. */
  2559. static bool
  2560. is_log_level_output(int elevel, int log_min_level)
  2561. {
  2562. if (elevel == LOG || elevel == COMMERROR)
  2563. {
  2564. if (log_min_level == LOG || log_min_level <= ERROR)
  2565. return true;
  2566. }
  2567. else if (log_min_level == LOG)
  2568. {
  2569. /* elevel != LOG */
  2570. if (elevel >= FATAL)
  2571. return true;
  2572. }
  2573. /* Neither is LOG */
  2574. else if (elevel >= log_min_level)
  2575. return true;
  2576. return false;
  2577. }
  2578. /*
  2579. * Adjust the level of a recovery-related message per trace_recovery_messages.
  2580. *
  2581. * The argument is the default log level of the message, eg, DEBUG2. (This
  2582. * should only be applied to DEBUGn log messages, otherwise it's a no-op.)
  2583. * If the level is >= trace_recovery_messages, we return LOG, causing the
  2584. * message to be logged unconditionally (for most settings of
  2585. * log_min_messages). Otherwise, we return the argument unchanged.
  2586. * The message will then be shown based on the setting of log_min_messages.
  2587. *
  2588. * Intention is to keep this for at least the whole of the 9.0 production
  2589. * release, so we can more easily diagnose production problems in the field.
  2590. * It should go away eventually, though, because it's an ugly and
  2591. * hard-to-explain kluge.
  2592. */
  2593. int
  2594. trace_recovery(int trace_level)
  2595. {
  2596. if (trace_level < LOG &&
  2597. trace_level >= trace_recovery_messages)
  2598. return LOG;
  2599. return trace_level;
  2600. }