]> granicus.if.org Git - postgresql/blob - src/backend/utils/error/elog.c
Per discussion earlier today, here is a fix that lets ereport() on win32
[postgresql] / src / backend / utils / error / elog.c
1 /*-------------------------------------------------------------------------
2  *
3  * elog.c
4  *        error logging and reporting
5  *
6  * Some notes about recursion and errors during error processing:
7  *
8  * We need to be robust about recursive-error scenarios --- for example,
9  * if we run out of memory, it's important to be able to report that fact.
10  * There are a number of considerations that go into this.
11  *
12  * First, distinguish between re-entrant use and actual recursion.      It
13  * is possible for an error or warning message to be emitted while the
14  * parameters for an error message are being computed.  In this case
15  * errstart has been called for the outer message, and some field values
16  * may have already been saved, but we are not actually recursing.      We handle
17  * this by providing a (small) stack of ErrorData records.      The inner message
18  * can be computed and sent without disturbing the state of the outer message.
19  * (If the inner message is actually an error, this isn't very interesting
20  * because control won't come back to the outer message generator ... but
21  * if the inner message is only debug or log data, this is critical.)
22  *
23  * Second, actual recursion will occur if an error is reported by one of
24  * the elog.c routines or something they call.  By far the most probable
25  * scenario of this sort is "out of memory"; and it's also the nastiest
26  * to handle because we'd likely also run out of memory while trying to
27  * report this error!  Our escape hatch for this condition is to force any
28  * such messages up to ERROR level if they aren't already (so that we will
29  * not need to return to the outer elog.c call), and to reset the ErrorContext
30  * to empty before trying to process the inner message.  Since ErrorContext
31  * is guaranteed to have at least 8K of space in it (see mcxt.c), we should
32  * be able to process an "out of memory" message successfully.
33  *
34  *
35  * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
36  * Portions Copyright (c) 1994, Regents of the University of California
37  *
38  *
39  * IDENTIFICATION
40  *        $PostgreSQL: pgsql/src/backend/utils/error/elog.c,v 1.135 2004/04/22 03:51:09 momjian Exp $
41  *
42  *-------------------------------------------------------------------------
43  */
44 #include "postgres.h"
45
46 #include <time.h>
47 #include <fcntl.h>
48 #include <errno.h>
49 #include <unistd.h>
50 #include <signal.h>
51 #include <sys/time.h>
52 #include <ctype.h>
53 #ifdef HAVE_SYSLOG
54 #include <syslog.h>
55 #endif
56
57 #include "libpq/libpq.h"
58 #include "libpq/pqformat.h"
59 #include "mb/pg_wchar.h"
60 #include "miscadmin.h"
61 #include "storage/ipc.h"
62 #include "tcop/tcopprot.h"
63 #include "utils/memutils.h"
64 #include "utils/guc.h"
65
66
67 /* Global variables */
68 ErrorContextCallback *error_context_stack = NULL;
69
70 /* GUC parameters */
71 PGErrorVerbosity Log_error_verbosity = PGERROR_VERBOSE;
72 char       *Log_line_prefix = NULL; /* format for extra log line info */
73 unsigned int Log_destination;
74
75 bool in_fatal_exit = false;
76
77 #ifdef HAVE_SYSLOG
78 char       *Syslog_facility;    /* openlog() parameters */
79 char       *Syslog_ident;
80
81 static void write_syslog(int level, const char *line);
82 #endif
83 #ifdef WIN32
84 static void write_eventlog(int level, const char *line);
85 #endif
86
87 /*
88  * ErrorData holds the data accumulated during any one ereport() cycle.
89  * Any non-NULL pointers must point to palloc'd data in ErrorContext.
90  * (The const pointers are an exception; we assume they point at non-freeable
91  * constant strings.)
92  */
93
94 typedef struct ErrorData
95 {
96         int                     elevel;                 /* error level */
97         bool            output_to_server;               /* will report to server log? */
98         bool            output_to_client;               /* will report to client? */
99         bool            show_funcname;  /* true to force funcname inclusion */
100         const char *filename;           /* __FILE__ of ereport() call */
101         int                     lineno;                 /* __LINE__ of ereport() call */
102         const char *funcname;           /* __func__ of ereport() call */
103         int                     sqlerrcode;             /* encoded ERRSTATE */
104         char       *message;            /* primary error message */
105         char       *detail;                     /* detail error message */
106         char       *hint;                       /* hint message */
107         char       *context;            /* context message */
108         int                     cursorpos;              /* cursor index into query string */
109         int                     internalpos;    /* cursor index into internalquery */
110         char       *internalquery;      /* text of internally-generated query */
111         int                     saved_errno;    /* errno at entry */
112 } ErrorData;
113
114 /* We provide a small stack of ErrorData records for re-entrant cases */
115 #define ERRORDATA_STACK_SIZE  5
116
117 static ErrorData errordata[ERRORDATA_STACK_SIZE];
118
119 static int      errordata_stack_depth = -1; /* index of topmost active frame */
120
121 static int      recursion_depth = 0;    /* to detect actual recursion */
122
123
124 /* Macro for checking errordata_stack_depth is reasonable */
125 #define CHECK_STACK_DEPTH() \
126         do { \
127                 if (errordata_stack_depth < 0) \
128                 { \
129                         errordata_stack_depth = -1; \
130                         ereport(ERROR, (errmsg_internal("errstart was not called"))); \
131                 } \
132         } while (0)
133
134
135 static void log_line_prefix(StringInfo buf);
136 static void send_message_to_server_log(ErrorData *edata);
137 static void send_message_to_frontend(ErrorData *edata);
138 static char *expand_fmt_string(const char *fmt, ErrorData *edata);
139 static const char *useful_strerror(int errnum);
140 static const char *error_severity(int elevel);
141 static void append_with_tabs(StringInfo buf, const char *str);
142
143
144 /*
145  * errstart --- begin an error-reporting cycle
146  *
147  * Create a stack entry and store the given parameters in it.  Subsequently,
148  * errmsg() and perhaps other routines will be called to further populate
149  * the stack entry.  Finally, errfinish() will be called to actually process
150  * the error report.
151  *
152  * Returns TRUE in normal case.  Returns FALSE to short-circuit the error
153  * report (if it's a warning or lower and not to be reported anywhere).
154  */
155 bool
156 errstart(int elevel, const char *filename, int lineno,
157                  const char *funcname)
158 {
159         ErrorData  *edata;
160         bool            output_to_server = false;
161         bool            output_to_client = false;
162
163         /*
164          * First decide whether we need to process this report at all; if it's
165          * warning or less and not enabled for logging, just return FALSE
166          * without starting up any error logging machinery.
167          */
168
169         /*
170          * Convert initialization errors into fatal errors. This is probably
171          * redundant, because Warn_restart_ready won't be set anyway.
172          */
173         if (elevel == ERROR && IsInitProcessingMode())
174                 elevel = FATAL;
175
176         /*
177          * If we are inside a critical section, all errors become PANIC
178          * errors.      See miscadmin.h.
179          */
180         if (elevel >= ERROR)
181         {
182                 if (CritSectionCount > 0)
183                         elevel = PANIC;
184         }
185
186         /* Determine whether message is enabled for server log output */
187         if (IsPostmasterEnvironment)
188         {
189                 /* Complicated because LOG is sorted out-of-order for this purpose */
190                 if (elevel == LOG || elevel == COMMERROR)
191                 {
192                         if (log_min_messages == LOG)
193                                 output_to_server = true;
194                         else if (log_min_messages < FATAL)
195                                 output_to_server = true;
196                 }
197                 else
198                 {
199                         /* elevel != LOG */
200                         if (log_min_messages == LOG)
201                         {
202                                 if (elevel >= FATAL)
203                                         output_to_server = true;
204                         }
205                         /* Neither is LOG */
206                         else if (elevel >= log_min_messages)
207                                 output_to_server = true;
208                 }
209         }
210         else
211         {
212                 /* In bootstrap/standalone case, do not sort LOG out-of-order */
213                 output_to_server = (elevel >= log_min_messages);
214         }
215
216         /* Determine whether message is enabled for client output */
217         if (whereToSendOutput == Remote && elevel != COMMERROR)
218         {
219                 /*
220                  * client_min_messages is honored only after we complete the
221                  * authentication handshake.  This is required both for security
222                  * reasons and because many clients can't handle NOTICE messages
223                  * during authentication.
224                  */
225                 if (ClientAuthInProgress)
226                         output_to_client = (elevel >= ERROR);
227                 else
228                         output_to_client = (elevel >= client_min_messages ||
229                                                                 elevel == INFO);
230         }
231
232         /* Skip processing effort if non-error message will not be output */
233         if (elevel < ERROR && !output_to_server && !output_to_client)
234                 return false;
235
236         /*
237          * Okay, crank up a stack entry to store the info in.
238          */
239
240         if (recursion_depth++ > 0)
241         {
242                 /*
243                  * Ooops, error during error processing.  Clear ErrorContext and
244                  * force level up to ERROR or greater, as discussed at top of
245                  * file.  Adjust output decisions too.
246                  */
247                 MemoryContextReset(ErrorContext);
248                 output_to_server = true;
249                 if (whereToSendOutput == Remote && elevel != COMMERROR)
250                         output_to_client = true;
251                 elevel = Max(elevel, ERROR);
252
253                 /*
254                  * If we recurse more than once, the problem might be something
255                  * broken in a context traceback routine.  Abandon them too.
256                  */
257                 if (recursion_depth > 2)
258                         error_context_stack = NULL;
259         }
260         if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
261         {
262                 /* Wups, stack not big enough */
263                 int                     i;
264
265                 elevel = Max(elevel, ERROR);
266
267                 /*
268                  * Don't forget any FATAL/PANIC status on the stack (see comments
269                  * in errfinish)
270                  */
271                 for (i = 0; i < errordata_stack_depth; i++)
272                         elevel = Max(elevel, errordata[i].elevel);
273                 /* Clear the stack and try again */
274                 errordata_stack_depth = -1;
275                 ereport(elevel, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
276         }
277
278         /* Initialize data for this error frame */
279         edata = &errordata[errordata_stack_depth];
280         MemSet(edata, 0, sizeof(ErrorData));
281         edata->elevel = elevel;
282         edata->output_to_server = output_to_server;
283         edata->output_to_client = output_to_client;
284         edata->filename = filename;
285         edata->lineno = lineno;
286         edata->funcname = funcname;
287         /* Select default errcode based on elevel */
288         if (elevel >= ERROR)
289                 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
290         else if (elevel == WARNING)
291                 edata->sqlerrcode = ERRCODE_WARNING;
292         else
293                 edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
294         /* errno is saved here so that error parameter eval can't change it */
295         edata->saved_errno = errno;
296
297         recursion_depth--;
298         return true;
299 }
300
301 /*
302  * errfinish --- end an error-reporting cycle
303  *
304  * Produce the appropriate error report(s) and pop the error stack.
305  *
306  * If elevel is ERROR or worse, control does not return to the caller.
307  * See elog.h for the error level definitions.
308  */
309 void
310 errfinish(int dummy,...)
311 {
312         ErrorData  *edata = &errordata[errordata_stack_depth];
313         int                     elevel = edata->elevel;
314         MemoryContext oldcontext;
315         ErrorContextCallback *econtext;
316
317         recursion_depth++;
318         CHECK_STACK_DEPTH();
319
320         /*
321          * Do processing in ErrorContext, which we hope has enough reserved
322          * space to report an error.
323          */
324         oldcontext = MemoryContextSwitchTo(ErrorContext);
325
326         /*
327          * Call any context callback functions.  Errors occurring in callback
328          * functions will be treated as recursive errors --- this ensures we
329          * will avoid infinite recursion (see errstart).
330          */
331         for (econtext = error_context_stack;
332                  econtext != NULL;
333                  econtext = econtext->previous)
334                 (*econtext->callback) (econtext->arg);
335
336         /* Send to server log, if enabled */
337         if (edata->output_to_server)
338                 send_message_to_server_log(edata);
339
340         /*
341          * Abort any old-style COPY OUT in progress when an error is detected.
342          * This hack is necessary because of poor design of old-style copy
343          * protocol.  Note we must do this even if client is fool enough to
344          * have set client_min_messages above ERROR, so don't look at
345          * output_to_client.
346          */
347         if (elevel >= ERROR && whereToSendOutput == Remote)
348                 pq_endcopyout(true);
349
350         /* Send to client, if enabled */
351         if (edata->output_to_client)
352                 send_message_to_frontend(edata);
353
354         /* Now free up subsidiary data attached to stack entry, and release it */
355         if (edata->message)
356                 pfree(edata->message);
357         if (edata->detail)
358                 pfree(edata->detail);
359         if (edata->hint)
360                 pfree(edata->hint);
361         if (edata->context)
362                 pfree(edata->context);
363         if (edata->internalquery)
364                 pfree(edata->internalquery);
365
366         MemoryContextSwitchTo(oldcontext);
367
368         errordata_stack_depth--;
369         recursion_depth--;
370
371         /*
372          * If the error level is ERROR or more, we are not going to return to
373          * caller; therefore, if there is any stacked error already in
374          * progress it will be lost.  This is more or less okay, except we do
375          * not want to have a FATAL or PANIC error downgraded because the
376          * reporting process was interrupted by a lower-grade error.  So check
377          * the stack and make sure we panic if panic is warranted.
378          */
379         if (elevel >= ERROR)
380         {
381                 int                     i;
382
383                 for (i = 0; i <= errordata_stack_depth; i++)
384                         elevel = Max(elevel, errordata[i].elevel);
385
386                 /*
387                  * Also, be sure to reset the stack to empty.  We do not clear
388                  * ErrorContext here, though; PostgresMain does that later on.
389                  */
390                 errordata_stack_depth = -1;
391                 recursion_depth = 0;
392                 error_context_stack = NULL;
393         }
394
395         /*
396          * Perform error recovery action as specified by elevel.
397          */
398         if (elevel == ERROR || elevel == FATAL)
399         {
400                 /* Prevent immediate interrupt while entering error recovery */
401                 ImmediateInterruptOK = false;
402
403                 /*
404                  * If we just reported a startup failure, the client will
405                  * disconnect on receiving it, so don't send any more to the
406                  * client.
407                  */
408                 if (!Warn_restart_ready && whereToSendOutput == Remote)
409                         whereToSendOutput = None;
410
411                 /*
412                  * For a FATAL error, we let proc_exit clean up and exit.
413                  *
414                  * There are several other cases in which we treat ERROR as FATAL and
415                  * go directly to proc_exit:
416                  *
417                  * 1. ExitOnAnyError mode switch is set (initdb uses this).
418                  *
419                  * 2. we have not yet entered the main backend loop (ie, we are in
420                  * the postmaster or in backend startup); we have noplace to
421                  * recover.
422                  *
423                  * 3. the error occurred after proc_exit has begun to run.      (It's
424                  * proc_exit's responsibility to see that this doesn't turn into
425                  * infinite recursion!)
426                  *
427                  * In the last case, we exit with nonzero exit code to indicate that
428                  * something's pretty wrong.  We also want to exit with nonzero
429                  * exit code if not running under the postmaster (for example, if
430                  * we are being run from the initdb script, we'd better return an
431                  * error status).
432                  */
433                 if (elevel == FATAL ||
434                         ExitOnAnyError ||
435                         !Warn_restart_ready ||
436                         proc_exit_inprogress)
437                 {
438                         /*
439                          * fflush here is just to improve the odds that we get to see
440                          * the error message, in case things are so hosed that
441                          * proc_exit crashes.  Any other code you might be tempted to
442                          * add here should probably be in an on_proc_exit callback
443                          * instead.
444                          */
445                         fflush(stdout);
446                         fflush(stderr);
447
448                         if (in_fatal_exit)
449                                 ereport(PANIC, (errmsg("fatal error during fatal exit, giving up")));
450
451                         /* not safe to longjump */
452                         if (!Warn_restart_ready || proc_exit_inprogress)
453                                 proc_exit(proc_exit_inprogress || !IsUnderPostmaster);
454
455                         /* We will exit the backend by simulating a client EOF */
456                         in_fatal_exit = true;
457                 }
458
459                 /*
460                  * Guard against infinite loop from errors during error recovery.
461                  */
462                 if (InError)
463                         ereport(PANIC, (errmsg("error during error recovery, giving up")));
464                 InError = true;
465
466                 /*
467                  * Otherwise we can return to the main loop in postgres.c.
468                  */
469                 siglongjmp(Warn_restart, 1);
470         }
471
472         if (elevel >= PANIC)
473         {
474                 /*
475                  * Serious crash time. Postmaster will observe nonzero process
476                  * exit status and kill the other backends too.
477                  *
478                  * XXX: what if we are *in* the postmaster?  abort() won't kill our
479                  * children...
480                  */
481                 ImmediateInterruptOK = false;
482                 fflush(stdout);
483                 fflush(stderr);
484                 abort();
485         }
486
487         /* We reach here if elevel <= WARNING. OK to return to caller. */
488 }
489
490
491 /*
492  * errcode --- add SQLSTATE error code to the current error
493  *
494  * The code is expected to be represented as per MAKE_SQLSTATE().
495  */
496 int
497 errcode(int sqlerrcode)
498 {
499         ErrorData  *edata = &errordata[errordata_stack_depth];
500
501         /* we don't bother incrementing recursion_depth */
502         CHECK_STACK_DEPTH();
503
504         edata->sqlerrcode = sqlerrcode;
505
506         return 0;                                       /* return value does not matter */
507 }
508
509
510 /*
511  * errcode_for_file_access --- add SQLSTATE error code to the current error
512  *
513  * The SQLSTATE code is chosen based on the saved errno value.  We assume
514  * that the failing operation was some type of disk file access.
515  *
516  * NOTE: the primary error message string should generally include %m
517  * when this is used.
518  */
519 int
520 errcode_for_file_access(void)
521 {
522         ErrorData  *edata = &errordata[errordata_stack_depth];
523
524         /* we don't bother incrementing recursion_depth */
525         CHECK_STACK_DEPTH();
526
527         switch (edata->saved_errno)
528         {
529                         /* Permission-denied failures */
530                 case EPERM:                             /* Not super-user */
531                 case EACCES:                    /* Permission denied */
532 #ifdef EROFS
533                 case EROFS:                             /* Read only file system */
534 #endif
535                         edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
536                         break;
537
538                         /* File not found */
539                 case ENOENT:                    /* No such file or directory */
540                         edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
541                         break;
542
543                         /* Duplicate file */
544                 case EEXIST:                    /* File exists */
545                         edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
546                         break;
547
548                         /* Wrong object type or state */
549                 case ENOTDIR:                   /* Not a directory */
550                 case EISDIR:                    /* Is a directory */
551 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
552                 case ENOTEMPTY:                 /* Directory not empty */
553 #endif
554                         edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
555                         break;
556
557                         /* Insufficient resources */
558                 case ENOSPC:                    /* No space left on device */
559                         edata->sqlerrcode = ERRCODE_DISK_FULL;
560                         break;
561
562                 case ENFILE:                    /* File table overflow */
563                 case EMFILE:                    /* Too many open files */
564                         edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
565                         break;
566
567                         /* Hardware failure */
568                 case EIO:                               /* I/O error */
569                         edata->sqlerrcode = ERRCODE_IO_ERROR;
570                         break;
571
572                         /* All else is classified as internal errors */
573                 default:
574                         edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
575                         break;
576         }
577
578         return 0;                                       /* return value does not matter */
579 }
580
581 /*
582  * errcode_for_socket_access --- add SQLSTATE error code to the current error
583  *
584  * The SQLSTATE code is chosen based on the saved errno value.  We assume
585  * that the failing operation was some type of socket access.
586  *
587  * NOTE: the primary error message string should generally include %m
588  * when this is used.
589  */
590 int
591 errcode_for_socket_access(void)
592 {
593         ErrorData  *edata = &errordata[errordata_stack_depth];
594
595         /* we don't bother incrementing recursion_depth */
596         CHECK_STACK_DEPTH();
597
598         switch (edata->saved_errno)
599         {
600                         /* Loss of connection */
601                 case EPIPE:
602 #ifdef ECONNRESET
603                 case ECONNRESET:
604 #endif
605                         edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
606                         break;
607
608                         /* All else is classified as internal errors */
609                 default:
610                         edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
611                         break;
612         }
613
614         return 0;                                       /* return value does not matter */
615 }
616
617
618 /*
619  * This macro handles expansion of a format string and associated parameters;
620  * it's common code for errmsg(), errdetail(), etc.  Must be called inside
621  * a routine that is declared like "const char *fmt, ..." and has an edata
622  * pointer set up.      The message is assigned to edata->targetfield, or
623  * appended to it if appendval is true.
624  *
625  * Note: we pstrdup the buffer rather than just transferring its storage
626  * to the edata field because the buffer might be considerably larger than
627  * really necessary.
628  */
629 #define EVALUATE_MESSAGE(targetfield, appendval)  \
630         { \
631                 char               *fmtbuf; \
632                 StringInfoData  buf; \
633                 /* Internationalize the error format string */ \
634                 fmt = gettext(fmt); \
635                 /* Expand %m in format string */ \
636                 fmtbuf = expand_fmt_string(fmt, edata); \
637                 initStringInfo(&buf); \
638                 if ((appendval) && edata->targetfield) \
639                         appendStringInfo(&buf, "%s\n", edata->targetfield); \
640                 /* Generate actual output --- have to use appendStringInfoVA */ \
641                 for (;;) \
642                 { \
643                         va_list         args; \
644                         bool            success; \
645                         va_start(args, fmt); \
646                         success = appendStringInfoVA(&buf, fmtbuf, args); \
647                         va_end(args); \
648                         if (success) \
649                                 break; \
650                         enlargeStringInfo(&buf, buf.maxlen); \
651                 } \
652                 /* Done with expanded fmt */ \
653                 pfree(fmtbuf); \
654                 /* Save the completed message into the stack item */ \
655                 if (edata->targetfield) \
656                         pfree(edata->targetfield); \
657                 edata->targetfield = pstrdup(buf.data); \
658                 pfree(buf.data); \
659         }
660
661
662 /*
663  * errmsg --- add a primary error message text to the current error
664  *
665  * In addition to the usual %-escapes recognized by printf, "%m" in
666  * fmt is replaced by the error message for the caller's value of errno.
667  *
668  * Note: no newline is needed at the end of the fmt string, since
669  * ereport will provide one for the output methods that need it.
670  */
671 int
672 errmsg(const char *fmt,...)
673 {
674         ErrorData  *edata = &errordata[errordata_stack_depth];
675         MemoryContext oldcontext;
676
677         recursion_depth++;
678         CHECK_STACK_DEPTH();
679         oldcontext = MemoryContextSwitchTo(ErrorContext);
680
681         EVALUATE_MESSAGE(message, false);
682
683         MemoryContextSwitchTo(oldcontext);
684         recursion_depth--;
685         return 0;                                       /* return value does not matter */
686 }
687
688
689 /*
690  * errmsg_internal --- add a primary error message text to the current error
691  *
692  * This is exactly like errmsg() except that strings passed to errmsg_internal
693  * are customarily left out of the internationalization message dictionary.
694  * This should be used for "can't happen" cases that are probably not worth
695  * spending translation effort on.
696  */
697 int
698 errmsg_internal(const char *fmt,...)
699 {
700         ErrorData  *edata = &errordata[errordata_stack_depth];
701         MemoryContext oldcontext;
702
703         recursion_depth++;
704         CHECK_STACK_DEPTH();
705         oldcontext = MemoryContextSwitchTo(ErrorContext);
706
707         EVALUATE_MESSAGE(message, false);
708
709         MemoryContextSwitchTo(oldcontext);
710         recursion_depth--;
711         return 0;                                       /* return value does not matter */
712 }
713
714
715 /*
716  * errdetail --- add a detail error message text to the current error
717  */
718 int
719 errdetail(const char *fmt,...)
720 {
721         ErrorData  *edata = &errordata[errordata_stack_depth];
722         MemoryContext oldcontext;
723
724         recursion_depth++;
725         CHECK_STACK_DEPTH();
726         oldcontext = MemoryContextSwitchTo(ErrorContext);
727
728         EVALUATE_MESSAGE(detail, false);
729
730         MemoryContextSwitchTo(oldcontext);
731         recursion_depth--;
732         return 0;                                       /* return value does not matter */
733 }
734
735
736 /*
737  * errhint --- add a hint error message text to the current error
738  */
739 int
740 errhint(const char *fmt,...)
741 {
742         ErrorData  *edata = &errordata[errordata_stack_depth];
743         MemoryContext oldcontext;
744
745         recursion_depth++;
746         CHECK_STACK_DEPTH();
747         oldcontext = MemoryContextSwitchTo(ErrorContext);
748
749         EVALUATE_MESSAGE(hint, false);
750
751         MemoryContextSwitchTo(oldcontext);
752         recursion_depth--;
753         return 0;                                       /* return value does not matter */
754 }
755
756
757 /*
758  * errcontext --- add a context error message text to the current error
759  *
760  * Unlike other cases, multiple calls are allowed to build up a stack of
761  * context information.  We assume earlier calls represent more-closely-nested
762  * states.
763  */
764 int
765 errcontext(const char *fmt,...)
766 {
767         ErrorData  *edata = &errordata[errordata_stack_depth];
768         MemoryContext oldcontext;
769
770         recursion_depth++;
771         CHECK_STACK_DEPTH();
772         oldcontext = MemoryContextSwitchTo(ErrorContext);
773
774         EVALUATE_MESSAGE(context, true);
775
776         MemoryContextSwitchTo(oldcontext);
777         recursion_depth--;
778         return 0;                                       /* return value does not matter */
779 }
780
781
782 /*
783  * errfunction --- add reporting function name to the current error
784  *
785  * This is used when backwards compatibility demands that the function
786  * name appear in messages sent to old-protocol clients.  Note that the
787  * passed string is expected to be a non-freeable constant string.
788  */
789 int
790 errfunction(const char *funcname)
791 {
792         ErrorData  *edata = &errordata[errordata_stack_depth];
793
794         /* we don't bother incrementing recursion_depth */
795         CHECK_STACK_DEPTH();
796
797         edata->funcname = funcname;
798         edata->show_funcname = true;
799
800         return 0;                                       /* return value does not matter */
801 }
802
803 /*
804  * errposition --- add cursor position to the current error
805  */
806 int
807 errposition(int cursorpos)
808 {
809         ErrorData  *edata = &errordata[errordata_stack_depth];
810
811         /* we don't bother incrementing recursion_depth */
812         CHECK_STACK_DEPTH();
813
814         edata->cursorpos = cursorpos;
815
816         return 0;                                       /* return value does not matter */
817 }
818
819 /*
820  * internalerrposition --- add internal cursor position to the current error
821  */
822 int
823 internalerrposition(int cursorpos)
824 {
825         ErrorData  *edata = &errordata[errordata_stack_depth];
826
827         /* we don't bother incrementing recursion_depth */
828         CHECK_STACK_DEPTH();
829
830         edata->internalpos = cursorpos;
831
832         return 0;                                       /* return value does not matter */
833 }
834
835 /*
836  * internalerrquery --- add internal query text to the current error
837  *
838  * Can also pass NULL to drop the internal query text entry.  This case
839  * is intended for use in error callback subroutines that are editorializing
840  * on the layout of the error report.
841  */
842 int
843 internalerrquery(const char *query)
844 {
845         ErrorData  *edata = &errordata[errordata_stack_depth];
846
847         /* we don't bother incrementing recursion_depth */
848         CHECK_STACK_DEPTH();
849
850         if (edata->internalquery)
851         {
852                 pfree(edata->internalquery);
853                 edata->internalquery = NULL;
854         }
855
856         if (query)
857                 edata->internalquery = MemoryContextStrdup(ErrorContext, query);
858
859         return 0;                                       /* return value does not matter */
860 }
861
862 /*
863  * geterrposition --- return the currently set error position (0 if none)
864  *
865  * This is only intended for use in error callback subroutines, since there
866  * is no other place outside elog.c where the concept is meaningful.
867  */
868 int
869 geterrposition(void)
870 {
871         ErrorData  *edata = &errordata[errordata_stack_depth];
872
873         /* we don't bother incrementing recursion_depth */
874         CHECK_STACK_DEPTH();
875
876         return edata->cursorpos;
877 }
878
879 /*
880  * getinternalerrposition --- same for internal error position
881  *
882  * This is only intended for use in error callback subroutines, since there
883  * is no other place outside elog.c where the concept is meaningful.
884  */
885 int
886 getinternalerrposition(void)
887 {
888         ErrorData  *edata = &errordata[errordata_stack_depth];
889
890         /* we don't bother incrementing recursion_depth */
891         CHECK_STACK_DEPTH();
892
893         return edata->internalpos;
894 }
895
896
897 /*
898  * elog_finish --- finish up for old-style API
899  *
900  * The elog() macro already called errstart, but with ERROR rather than
901  * the true elevel.
902  */
903 void
904 elog_finish(int elevel, const char *fmt,...)
905 {
906         ErrorData  *edata = &errordata[errordata_stack_depth];
907         MemoryContext oldcontext;
908
909         CHECK_STACK_DEPTH();
910
911         /*
912          * We need to redo errstart() because the elog macro had to call it
913          * with bogus elevel.
914          */
915         errordata_stack_depth--;
916         errno = edata->saved_errno;
917         if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname))
918                 return;                                 /* nothing to do */
919
920         /*
921          * Format error message just like errmsg().
922          */
923         recursion_depth++;
924         oldcontext = MemoryContextSwitchTo(ErrorContext);
925
926         EVALUATE_MESSAGE(message, false);
927
928         MemoryContextSwitchTo(oldcontext);
929         recursion_depth--;
930
931         /*
932          * And let errfinish() finish up.
933          */
934         errfinish(0);
935 }
936
937
938 /*
939  * Initialization of error output file
940  */
941 void
942 DebugFileOpen(void)
943 {
944         int                     fd,
945                                 istty;
946
947         if (OutputFileName[0])
948         {
949                 /*
950                  * A debug-output file name was given.
951                  *
952                  * Make sure we can write the file, and find out if it's a tty.
953                  */
954                 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
955                                            0666)) < 0)
956                         ereport(FATAL,
957                                         (errcode_for_file_access(),
958                                    errmsg("could not open file \"%s\": %m", OutputFileName)));
959                 istty = isatty(fd);
960                 close(fd);
961
962                 /*
963                  * Redirect our stderr to the debug output file.
964                  */
965                 if (!freopen(OutputFileName, "a", stderr))
966                         ereport(FATAL,
967                                         (errcode_for_file_access(),
968                                          errmsg("could not reopen file \"%s\" as stderr: %m",
969                                                         OutputFileName)));
970
971                 /*
972                  * If the file is a tty and we're running under the postmaster,
973                  * try to send stdout there as well (if it isn't a tty then stderr
974                  * will block out stdout, so we may as well let stdout go wherever
975                  * it was going before).
976                  */
977                 if (istty && IsUnderPostmaster)
978                         if (!freopen(OutputFileName, "a", stdout))
979                                 ereport(FATAL,
980                                                 (errcode_for_file_access(),
981                                                  errmsg("could not reopen file \"%s\" as stdout: %m",
982                                                                 OutputFileName)));
983         }
984 }
985
986
987
988 #ifdef HAVE_SYSLOG
989
990 #ifndef PG_SYSLOG_LIMIT
991 #define PG_SYSLOG_LIMIT 128
992 #endif
993
994 /*
995  * Write a message line to syslog if the syslog option is set.
996  *
997  * Our problem here is that many syslog implementations don't handle
998  * long messages in an acceptable manner. While this function doesn't
999  * help that fact, it does work around by splitting up messages into
1000  * smaller pieces.
1001  */
1002 static void
1003 write_syslog(int level, const char *line)
1004 {
1005         static bool openlog_done = false;
1006         static unsigned long seq = 0;
1007         static int      syslog_fac = LOG_LOCAL0;
1008
1009         int                     len = strlen(line);
1010
1011         if (!openlog_done)
1012         {
1013                 if (strcasecmp(Syslog_facility, "LOCAL0") == 0)
1014                         syslog_fac = LOG_LOCAL0;
1015                 if (strcasecmp(Syslog_facility, "LOCAL1") == 0)
1016                         syslog_fac = LOG_LOCAL1;
1017                 if (strcasecmp(Syslog_facility, "LOCAL2") == 0)
1018                         syslog_fac = LOG_LOCAL2;
1019                 if (strcasecmp(Syslog_facility, "LOCAL3") == 0)
1020                         syslog_fac = LOG_LOCAL3;
1021                 if (strcasecmp(Syslog_facility, "LOCAL4") == 0)
1022                         syslog_fac = LOG_LOCAL4;
1023                 if (strcasecmp(Syslog_facility, "LOCAL5") == 0)
1024                         syslog_fac = LOG_LOCAL5;
1025                 if (strcasecmp(Syslog_facility, "LOCAL6") == 0)
1026                         syslog_fac = LOG_LOCAL6;
1027                 if (strcasecmp(Syslog_facility, "LOCAL7") == 0)
1028                         syslog_fac = LOG_LOCAL7;
1029                 openlog(Syslog_ident, LOG_PID | LOG_NDELAY, syslog_fac);
1030                 openlog_done = true;
1031         }
1032
1033         /*
1034          * We add a sequence number to each log message to suppress "same"
1035          * messages.
1036          */
1037         seq++;
1038
1039         /* divide into multiple syslog() calls if message is too long */
1040         /* or if the message contains embedded NewLine(s) '\n' */
1041         if (len > PG_SYSLOG_LIMIT || strchr(line, '\n') != NULL)
1042         {
1043                 int                     chunk_nr = 0;
1044
1045                 while (len > 0)
1046                 {
1047                         char            buf[PG_SYSLOG_LIMIT + 1];
1048                         int                     buflen;
1049                         int                     i;
1050
1051                         /* if we start at a newline, move ahead one char */
1052                         if (line[0] == '\n')
1053                         {
1054                                 line++;
1055                                 len--;
1056                                 continue;
1057                         }
1058
1059                         strncpy(buf, line, PG_SYSLOG_LIMIT);
1060                         buf[PG_SYSLOG_LIMIT] = '\0';
1061                         if (strchr(buf, '\n') != NULL)
1062                                 *strchr(buf, '\n') = '\0';
1063
1064                         buflen = strlen(buf);
1065
1066                         /* trim to multibyte letter boundary */
1067                         buflen = pg_mbcliplen(buf, buflen, buflen);
1068                         if (buflen <= 0)
1069                                 return;
1070                         buf[buflen] = '\0';
1071
1072                         /* already word boundary? */
1073                         if (!isspace((unsigned char) line[buflen]) &&
1074                                 line[buflen] != '\0')
1075                         {
1076                                 /* try to divide at word boundary */
1077                                 i = buflen - 1;
1078                                 while (i > 0 && !isspace((unsigned char) buf[i]))
1079                                         i--;
1080
1081                                 if (i > 0)              /* else couldn't divide word boundary */
1082                                 {
1083                                         buflen = i;
1084                                         buf[i] = '\0';
1085                                 }
1086                         }
1087
1088                         chunk_nr++;
1089
1090                         syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1091                         line += buflen;
1092                         len -= buflen;
1093                 }
1094         }
1095         else
1096         {
1097                 /* message short enough */
1098                 syslog(level, "[%lu] %s", seq, line);
1099         }
1100 }
1101 #endif   /* HAVE_SYSLOG */
1102 #ifdef WIN32
1103 /*
1104  * Write a message line to the windows event log
1105  */
1106 static void
1107 write_eventlog(int level, const char *line)
1108 {
1109         static HANDLE evtHandle = INVALID_HANDLE_VALUE;
1110         
1111         if (evtHandle == INVALID_HANDLE_VALUE) {
1112                 evtHandle = RegisterEventSource(NULL,"PostgreSQL");
1113                 if (evtHandle == NULL) {
1114                         evtHandle = INVALID_HANDLE_VALUE;
1115                         return;
1116                 }
1117         }
1118
1119         ReportEvent(evtHandle,
1120                                 level,
1121                                 0,
1122                                 0, /* All events are Id 0 */
1123                                 NULL,
1124                                 1,
1125                                 0,
1126                                 &line,
1127                                 NULL);
1128 }
1129 #endif /* WIN32*/
1130
1131 /*
1132  * Format tag info for log lines; append to the provided buffer.
1133  */
1134 static void
1135 log_line_prefix(StringInfo buf)
1136 {
1137         /* static counter for line numbers */
1138         static long log_line_number = 0;
1139         /* has counter been reset in current process? */
1140         static int      log_my_pid = 0;
1141
1142         int format_len;
1143         int i;
1144
1145         /*
1146          * This is one of the few places where we'd rather not inherit a
1147          * static variable's value from the postmaster.  But since we will,
1148          * reset it when MyProcPid changes.
1149          */
1150         if (log_my_pid != MyProcPid)
1151         {
1152                 log_line_number = 0;
1153                 log_my_pid = MyProcPid;
1154         }
1155         log_line_number++;
1156
1157         if (Log_line_prefix == NULL)
1158                 return;                                 /* in case guc hasn't run yet */
1159
1160         format_len = strlen(Log_line_prefix);
1161
1162         for (i = 0; i < format_len; i++)
1163         {
1164                 if (Log_line_prefix[i] != '%')
1165                 {
1166                         /* literal char, just copy */
1167                         appendStringInfoChar(buf, Log_line_prefix[i]);
1168                         continue;
1169                 }
1170                 /* go to char after '%' */
1171                 i++;
1172                 if (i >= format_len)
1173                 {
1174                         /* format error - ignore it */
1175                         break;
1176                 }
1177
1178                 /* process the option */
1179                 switch (Log_line_prefix[i])
1180                 {
1181                         case 'u':
1182                                 if (MyProcPort)
1183                                 {
1184                                         const char *username = MyProcPort->user_name;
1185
1186                                         if (username == NULL || *username == '\0')
1187                                                 username = gettext("[unknown]");
1188                                         appendStringInfo(buf, "%s", username);
1189                                 }
1190                                 break;
1191                         case 'd': 
1192                                 if (MyProcPort)
1193                                 {
1194                                         const char *dbname = MyProcPort->database_name;
1195
1196                                         if (dbname == NULL || *dbname == '\0')
1197                                                 dbname = gettext("[unknown]");
1198                                         appendStringInfo(buf, "%s", dbname);
1199                                 }
1200                                 break;
1201                         case 'c':
1202                                 if (MyProcPort)
1203                                 {
1204                                         appendStringInfo(buf, "%lx.%lx",
1205                                                                          (long)(MyProcPort->session_start.tv_sec),
1206                                                                          (long)MyProcPid);
1207                                 }
1208                                 break;
1209                         case 'p':
1210                                 appendStringInfo(buf, "%ld", (long)MyProcPid);
1211                                 break;
1212                         case 'l':
1213                                 appendStringInfo(buf, "%ld", log_line_number);
1214                                 break;
1215                         case 't':
1216                                 {
1217                                         time_t stamp_time = time(NULL);
1218                                         char strfbuf[128];
1219
1220                                         strftime(strfbuf, sizeof(strfbuf), "%Y-%m-%d %H:%M:%S %Z",
1221                                                          localtime(&stamp_time));
1222                                         appendStringInfoString(buf, strfbuf);
1223                                 }
1224                                 break;
1225                         case 's':
1226                                 if (MyProcPort)
1227                                 {
1228                                         time_t stamp_time = MyProcPort->session_start.tv_sec;
1229                                         char strfbuf[128];
1230
1231                                         strftime(strfbuf, sizeof(strfbuf), "%Y-%m-%d %H:%M:%S %Z",
1232                                                          localtime(&stamp_time));
1233                                         appendStringInfoString(buf, strfbuf);
1234                                 }
1235                                 break;
1236                         case 'i':
1237                                 if (MyProcPort)
1238                                 {
1239                                         appendStringInfo(buf, "%s", MyProcPort->commandTag);
1240                                 }
1241                                 break;
1242                         case 'r':
1243                                 if (MyProcPort)
1244                                 {
1245                                         appendStringInfo(buf, "%s", MyProcPort->remote_host);
1246                                         if (strlen(MyProcPort->remote_port) > 0)
1247                                                 appendStringInfo(buf, "(%s)",
1248                                                                                  MyProcPort->remote_port);
1249                                 }
1250                                 break;
1251                         case 'x': 
1252                                 /* in postmaster and friends, stop if %x is seen */
1253                                 /* in a backend, just ignore */
1254                                 if (MyProcPort == NULL)
1255                                         i = format_len;
1256                                 break;
1257                         case '%': 
1258                                 appendStringInfoChar(buf, '%');
1259                                 break;
1260                         default:
1261                                 /* format error - ignore it */
1262                                 break;
1263                 }
1264         }
1265 }
1266
1267
1268 /*
1269  * Write error report to server's log
1270  */
1271 static void
1272 send_message_to_server_log(ErrorData *edata)
1273 {
1274         StringInfoData buf;
1275
1276         initStringInfo(&buf);
1277
1278         log_line_prefix(&buf);
1279         appendStringInfo(&buf, "%s:  ", error_severity(edata->elevel));
1280
1281         if (Log_error_verbosity >= PGERROR_VERBOSE)
1282         {
1283                 /* unpack MAKE_SQLSTATE code */
1284                 char            tbuf[12];
1285                 int                     ssval;
1286                 int                     i;
1287
1288                 ssval = edata->sqlerrcode;
1289                 for (i = 0; i < 5; i++)
1290                 {
1291                         tbuf[i] = PGUNSIXBIT(ssval);
1292                         ssval >>= 6;
1293                 }
1294                 tbuf[i] = '\0';
1295                 appendStringInfo(&buf, "%s: ", tbuf);
1296         }
1297
1298         if (edata->message)
1299                 append_with_tabs(&buf, edata->message);
1300         else
1301                 append_with_tabs(&buf, gettext("missing error text"));
1302
1303         if (edata->cursorpos > 0)
1304                 appendStringInfo(&buf, gettext(" at character %d"),
1305                                                  edata->cursorpos);
1306         else if (edata->internalpos > 0)
1307                 appendStringInfo(&buf, gettext(" at character %d"),
1308                                                  edata->internalpos);
1309
1310         appendStringInfoChar(&buf, '\n');
1311
1312         if (Log_error_verbosity >= PGERROR_DEFAULT)
1313         {
1314                 if (edata->detail)
1315                 {
1316                         log_line_prefix(&buf);
1317                         appendStringInfoString(&buf, gettext("DETAIL:  "));
1318                         append_with_tabs(&buf, edata->detail);
1319                         appendStringInfoChar(&buf, '\n');
1320                 }
1321                 if (edata->hint)
1322                 {
1323                         log_line_prefix(&buf);
1324                         appendStringInfoString(&buf, gettext("HINT:  "));
1325                         append_with_tabs(&buf, edata->hint);
1326                         appendStringInfoChar(&buf, '\n');
1327                 }
1328                 if (edata->internalquery)
1329                 {
1330                         log_line_prefix(&buf);
1331                         appendStringInfoString(&buf, gettext("QUERY:  "));
1332                         append_with_tabs(&buf, edata->internalquery);
1333                         appendStringInfoChar(&buf, '\n');
1334                 }
1335                 if (edata->context)
1336                 {
1337                         log_line_prefix(&buf);
1338                         appendStringInfoString(&buf, gettext("CONTEXT:  "));
1339                         append_with_tabs(&buf, edata->context);
1340                         appendStringInfoChar(&buf, '\n');
1341                 }
1342                 if (Log_error_verbosity >= PGERROR_VERBOSE)
1343                 {
1344                         /* assume no newlines in funcname or filename... */
1345                         if (edata->funcname && edata->filename)
1346                         {
1347                                 log_line_prefix(&buf);
1348                                 appendStringInfo(&buf, gettext("LOCATION:  %s, %s:%d\n"),
1349                                                                  edata->funcname, edata->filename,
1350                                                                  edata->lineno);
1351                         }
1352                         else if (edata->filename)
1353                         {
1354                                 log_line_prefix(&buf);
1355                                 appendStringInfo(&buf, gettext("LOCATION:  %s:%d\n"),
1356                                                                  edata->filename, edata->lineno);
1357                         }
1358                 }
1359         }
1360
1361         /*
1362          * If the user wants the query that generated this error logged, do it.
1363          */
1364         if (edata->elevel >= log_min_error_statement && debug_query_string != NULL)
1365         {
1366                 log_line_prefix(&buf);
1367                 appendStringInfoString(&buf, gettext("STATEMENT:  "));
1368                 append_with_tabs(&buf, debug_query_string);
1369                 appendStringInfoChar(&buf, '\n');
1370         }
1371
1372
1373 #ifdef HAVE_SYSLOG
1374         /* Write to syslog, if enabled */
1375         if (Log_destination & LOG_DESTINATION_SYSLOG)
1376         {
1377                 int                     syslog_level;
1378
1379                 switch (edata->elevel)
1380                 {
1381                         case DEBUG5:
1382                         case DEBUG4:
1383                         case DEBUG3:
1384                         case DEBUG2:
1385                         case DEBUG1:
1386                                 syslog_level = LOG_DEBUG;
1387                                 break;
1388                         case LOG:
1389                         case COMMERROR:
1390                         case INFO:
1391                                 syslog_level = LOG_INFO;
1392                                 break;
1393                         case NOTICE:
1394                         case WARNING:
1395                                 syslog_level = LOG_NOTICE;
1396                                 break;
1397                         case ERROR:
1398                                 syslog_level = LOG_WARNING;
1399                                 break;
1400                         case FATAL:
1401                                 syslog_level = LOG_ERR;
1402                                 break;
1403                         case PANIC:
1404                         default:
1405                                 syslog_level = LOG_CRIT;
1406                                 break;
1407                 }
1408
1409                 write_syslog(syslog_level, buf.data);
1410         }
1411 #endif   /* HAVE_SYSLOG */
1412 #ifdef WIN32
1413         if (Log_destination & LOG_DESTINATION_EVENTLOG)
1414         {
1415                 int eventlog_level;
1416                 switch (edata->elevel) 
1417                 {
1418                         case DEBUG5:
1419                         case DEBUG4:
1420                         case DEBUG3:
1421                         case DEBUG2:
1422                         case DEBUG1:
1423                         case LOG:
1424                         case COMMERROR:
1425                         case INFO:
1426                         case NOTICE:
1427                                 eventlog_level = EVENTLOG_INFORMATION_TYPE;
1428                                 break;
1429                         case WARNING:
1430                                 eventlog_level = EVENTLOG_WARNING_TYPE;
1431                                 break;
1432                         case ERROR:
1433                         case FATAL:
1434                         case PANIC:
1435                         default:
1436                                 eventlog_level = EVENTLOG_ERROR_TYPE;
1437                                 break;
1438                 }
1439                 write_eventlog(eventlog_level, buf.data);
1440         }
1441 #endif   /* WIN32 */
1442         /* Write to stderr, if enabled */
1443         if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == Debug)
1444         {
1445                 fprintf(stderr, "%s", buf.data);
1446         }
1447
1448         pfree(buf.data);
1449 }
1450
1451
1452 /*
1453  * Write error report to client
1454  */
1455 static void
1456 send_message_to_frontend(ErrorData *edata)
1457 {
1458         StringInfoData msgbuf;
1459
1460         /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
1461         pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
1462
1463         if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
1464         {
1465                 /* New style with separate fields */
1466                 char            tbuf[12];
1467                 int                     ssval;
1468                 int                     i;
1469
1470                 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
1471                 pq_sendstring(&msgbuf, error_severity(edata->elevel));
1472
1473                 /* unpack MAKE_SQLSTATE code */
1474                 ssval = edata->sqlerrcode;
1475                 for (i = 0; i < 5; i++)
1476                 {
1477                         tbuf[i] = PGUNSIXBIT(ssval);
1478                         ssval >>= 6;
1479                 }
1480                 tbuf[i] = '\0';
1481
1482                 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
1483                 pq_sendstring(&msgbuf, tbuf);
1484
1485                 /* M field is required per protocol, so always send something */
1486                 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
1487                 if (edata->message)
1488                         pq_sendstring(&msgbuf, edata->message);
1489                 else
1490                         pq_sendstring(&msgbuf, gettext("missing error text"));
1491
1492                 if (edata->detail)
1493                 {
1494                         pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
1495                         pq_sendstring(&msgbuf, edata->detail);
1496                 }
1497
1498                 if (edata->hint)
1499                 {
1500                         pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
1501                         pq_sendstring(&msgbuf, edata->hint);
1502                 }
1503
1504                 if (edata->context)
1505                 {
1506                         pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
1507                         pq_sendstring(&msgbuf, edata->context);
1508                 }
1509
1510                 if (edata->cursorpos > 0)
1511                 {
1512                         snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
1513                         pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
1514                         pq_sendstring(&msgbuf, tbuf);
1515                 }
1516
1517                 if (edata->internalpos > 0)
1518                 {
1519                         snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
1520                         pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
1521                         pq_sendstring(&msgbuf, tbuf);
1522                 }
1523
1524                 if (edata->internalquery)
1525                 {
1526                         pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
1527                         pq_sendstring(&msgbuf, edata->internalquery);
1528                 }
1529
1530                 if (edata->filename)
1531                 {
1532                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
1533                         pq_sendstring(&msgbuf, edata->filename);
1534                 }
1535
1536                 if (edata->lineno > 0)
1537                 {
1538                         snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
1539                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
1540                         pq_sendstring(&msgbuf, tbuf);
1541                 }
1542
1543                 if (edata->funcname)
1544                 {
1545                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
1546                         pq_sendstring(&msgbuf, edata->funcname);
1547                 }
1548
1549                 pq_sendbyte(&msgbuf, '\0');             /* terminator */
1550         }
1551         else
1552         {
1553                 /* Old style --- gin up a backwards-compatible message */
1554                 StringInfoData buf;
1555
1556                 initStringInfo(&buf);
1557
1558                 appendStringInfo(&buf, "%s:  ", error_severity(edata->elevel));
1559
1560                 if (edata->show_funcname && edata->funcname)
1561                         appendStringInfo(&buf, "%s: ", edata->funcname);
1562
1563                 if (edata->message)
1564                         appendStringInfoString(&buf, edata->message);
1565                 else
1566                         appendStringInfoString(&buf, gettext("missing error text"));
1567
1568                 if (edata->cursorpos > 0)
1569                         appendStringInfo(&buf, gettext(" at character %d"),
1570                                                          edata->cursorpos);
1571                 else if (edata->internalpos > 0)
1572                         appendStringInfo(&buf, gettext(" at character %d"),
1573                                                          edata->internalpos);
1574
1575                 appendStringInfoChar(&buf, '\n');
1576
1577                 pq_sendstring(&msgbuf, buf.data);
1578
1579                 pfree(buf.data);
1580         }
1581
1582         pq_endmessage(&msgbuf);
1583
1584         /*
1585          * This flush is normally not necessary, since postgres.c will flush
1586          * out waiting data when control returns to the main loop. But it
1587          * seems best to leave it here, so that the client has some clue what
1588          * happened if the backend dies before getting back to the main loop
1589          * ... error/notice messages should not be a performance-critical path
1590          * anyway, so an extra flush won't hurt much ...
1591          */
1592         pq_flush();
1593 }
1594
1595
1596 /*
1597  * Support routines for formatting error messages.
1598  */
1599
1600
1601 /*
1602  * expand_fmt_string --- process special format codes in a format string
1603  *
1604  * We must replace %m with the appropriate strerror string, since vsnprintf
1605  * won't know what to do with it.
1606  *
1607  * The result is a palloc'd string.
1608  */
1609 static char *
1610 expand_fmt_string(const char *fmt, ErrorData *edata)
1611 {
1612         StringInfoData buf;
1613         const char *cp;
1614
1615         initStringInfo(&buf);
1616
1617         for (cp = fmt; *cp; cp++)
1618         {
1619                 if (cp[0] == '%' && cp[1] != '\0')
1620                 {
1621                         cp++;
1622                         if (*cp == 'm')
1623                         {
1624                                 /*
1625                                  * Replace %m by system error string.  If there are any
1626                                  * %'s in the string, we'd better double them so that
1627                                  * vsnprintf won't misinterpret.
1628                                  */
1629                                 const char *cp2;
1630
1631                                 cp2 = useful_strerror(edata->saved_errno);
1632                                 for (; *cp2; cp2++)
1633                                 {
1634                                         if (*cp2 == '%')
1635                                                 appendStringInfoCharMacro(&buf, '%');
1636                                         appendStringInfoCharMacro(&buf, *cp2);
1637                                 }
1638                         }
1639                         else
1640                         {
1641                                 /* copy % and next char --- this avoids trouble with %%m */
1642                                 appendStringInfoCharMacro(&buf, '%');
1643                                 appendStringInfoCharMacro(&buf, *cp);
1644                         }
1645                 }
1646                 else
1647                         appendStringInfoCharMacro(&buf, *cp);
1648         }
1649
1650         return buf.data;
1651 }
1652
1653
1654 /*
1655  * A slightly cleaned-up version of strerror()
1656  */
1657 static const char *
1658 useful_strerror(int errnum)
1659 {
1660         /* this buffer is only used if errno has a bogus value */
1661         static char errorstr_buf[48];
1662         const char *str;
1663
1664 #ifdef WIN32
1665         /* Winsock error code range, per WinError.h */
1666         if (errnum >= 10000 && errnum <= 11999)
1667                 return pgwin32_socket_strerror(errnum);
1668 #endif
1669         str = strerror(errnum);
1670
1671         /*
1672          * Some strerror()s return an empty string for out-of-range errno.
1673          * This is ANSI C spec compliant, but not exactly useful.
1674          */
1675         if (str == NULL || *str == '\0')
1676         {
1677                 /*
1678                  * translator: This string will be truncated at 47 characters
1679                  * expanded.
1680                  */
1681                 snprintf(errorstr_buf, sizeof(errorstr_buf),
1682                                  gettext("operating system error %d"), errnum);
1683                 str = errorstr_buf;
1684         }
1685
1686         return str;
1687 }
1688
1689
1690 /*
1691  * error_severity --- get localized string representing elevel
1692  */
1693 static const char *
1694 error_severity(int elevel)
1695 {
1696         const char *prefix;
1697
1698         switch (elevel)
1699         {
1700                 case DEBUG1:
1701                 case DEBUG2:
1702                 case DEBUG3:
1703                 case DEBUG4:
1704                 case DEBUG5:
1705                         prefix = gettext("DEBUG");
1706                         break;
1707                 case LOG:
1708                 case COMMERROR:
1709                         prefix = gettext("LOG");
1710                         break;
1711                 case INFO:
1712                         prefix = gettext("INFO");
1713                         break;
1714                 case NOTICE:
1715                         prefix = gettext("NOTICE");
1716                         break;
1717                 case WARNING:
1718                         prefix = gettext("WARNING");
1719                         break;
1720                 case ERROR:
1721                         prefix = gettext("ERROR");
1722                         break;
1723                 case FATAL:
1724                         prefix = gettext("FATAL");
1725                         break;
1726                 case PANIC:
1727                         prefix = gettext("PANIC");
1728                         break;
1729                 default:
1730                         prefix = "???";
1731                         break;
1732         }
1733
1734         return prefix;
1735 }
1736
1737
1738 /*
1739  *      append_with_tabs
1740  *
1741  *      Append the string to the StringInfo buffer, inserting a tab after any
1742  *      newline.
1743  */
1744 static void
1745 append_with_tabs(StringInfo buf, const char *str)
1746 {
1747         char    ch;
1748
1749         while ((ch = *str++) != '\0')
1750         {
1751                 appendStringInfoCharMacro(buf, ch);
1752                 if (ch == '\n')
1753                         appendStringInfoCharMacro(buf, '\t');
1754         }
1755 }