PageRenderTime 48ms CodeModel.GetById 7ms RepoModel.GetById 0ms app.codeStats 0ms

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

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