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