PageRenderTime 70ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

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

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