PostgreSQL Source Code git master
snprintf.c
Go to the documentation of this file.
1/*
2 * Copyright (c) 1983, 1995, 1996 Eric P. Allman
3 * Copyright (c) 1988, 1993
4 * The Regents of the University of California. All rights reserved.
5 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 *
31 * src/port/snprintf.c
32 */
33
34#include "c.h"
35
36#include <math.h>
37
38/*
39 * We used to use the platform's NL_ARGMAX here, but that's a bad idea,
40 * first because the point of this module is to remove platform dependencies
41 * not perpetuate them, and second because some platforms use ridiculously
42 * large values, leading to excessive stack consumption in dopr().
43 */
44#define PG_NL_ARGMAX 31
45
46
47/*
48 * SNPRINTF, VSNPRINTF and friends
49 *
50 * These versions have been grabbed off the net. They have been
51 * cleaned up to compile properly and support for most of the C99
52 * specification has been added. Remaining unimplemented features are:
53 *
54 * 1. No locale support: the radix character is always '.' and the '
55 * (single quote) format flag is ignored.
56 *
57 * 2. No support for the "%n" format specification.
58 *
59 * 3. No support for wide characters ("lc" and "ls" formats).
60 *
61 * 4. No support for "long double" ("Lf" and related formats).
62 *
63 * 5. Space and '#' flags are not implemented.
64 *
65 * In addition, we support some extensions over C99:
66 *
67 * 1. Argument order control through "%n$" and "*n$", as required by POSIX.
68 *
69 * 2. "%m" expands to the value of strerror(errno), where errno is the
70 * value that variable had at the start of the call. This is a glibc
71 * extension, but a very useful one.
72 *
73 *
74 * Historically the result values of sprintf/snprintf varied across platforms.
75 * This implementation now follows the C99 standard:
76 *
77 * 1. -1 is returned if an error is detected in the format string, or if
78 * a write to the target stream fails (as reported by fwrite). Note that
79 * overrunning snprintf's target buffer is *not* an error.
80 *
81 * 2. For successful writes to streams, the actual number of bytes written
82 * to the stream is returned.
83 *
84 * 3. For successful sprintf/snprintf, the number of bytes that would have
85 * been written to an infinite-size buffer (excluding the trailing '\0')
86 * is returned. snprintf will truncate its output to fit in the buffer
87 * (ensuring a trailing '\0' unless count == 0), but this is not reflected
88 * in the function result.
89 *
90 * snprintf buffer overrun can be detected by checking for function result
91 * greater than or equal to the supplied count.
92 */
93
94/**************************************************************
95 * Original:
96 * Patrick Powell Tue Apr 11 09:48:21 PDT 1995
97 * A bombproof version of doprnt (dopr) included.
98 * Sigh. This sort of thing is always nasty do deal with. Note that
99 * the version here does not include floating point. (now it does ... tgl)
100 **************************************************************/
101
102/* Prevent recursion */
103#undef vsnprintf
104#undef snprintf
105#undef vsprintf
106#undef sprintf
107#undef vfprintf
108#undef fprintf
109#undef vprintf
110#undef printf
111
112/*
113 * Info about where the formatted output is going.
114 *
115 * dopr and subroutines will not write at/past bufend, but snprintf
116 * reserves one byte, ensuring it may place the trailing '\0' there.
117 *
118 * In snprintf, we use nchars to count the number of bytes dropped on the
119 * floor due to buffer overrun. The correct result of snprintf is thus
120 * (bufptr - bufstart) + nchars. (This isn't as inconsistent as it might
121 * seem: nchars is the number of emitted bytes that are not in the buffer now,
122 * either because we sent them to the stream or because we couldn't fit them
123 * into the buffer to begin with.)
124 */
125typedef struct
126{
127 char *bufptr; /* next buffer output position */
128 char *bufstart; /* first buffer element */
129 char *bufend; /* last+1 buffer element, or NULL */
130 /* bufend == NULL is for sprintf, where we assume buf is big enough */
131 FILE *stream; /* eventual output destination, or NULL */
132 int nchars; /* # chars sent to stream, or dropped */
133 bool failed; /* call is a failure; errno is set */
135
136/*
137 * Info about the type and value of a formatting parameter. Note that we
138 * don't currently support "long double", "wint_t", or "wchar_t *" data,
139 * nor the '%n' formatting code; else we'd need more types. Also, at this
140 * level we need not worry about signed vs unsigned values.
141 */
142typedef enum
143{
151
152typedef union
153{
154 int i;
155 long l;
156 long long ll;
157 double d;
158 char *cptr;
160
161
162static void flushbuffer(PrintfTarget *target);
163static void dopr(PrintfTarget *target, const char *format, va_list args);
164
165
166/*
167 * Externally visible entry points.
168 *
169 * All of these are just wrappers around dopr(). Note it's essential that
170 * they not change the value of "errno" before reaching dopr().
171 */
172
173int
174pg_vsnprintf(char *str, size_t count, const char *fmt, va_list args)
175{
176 PrintfTarget target;
177 char onebyte[1];
178
179 /*
180 * C99 allows the case str == NULL when count == 0. Rather than
181 * special-casing this situation further down, we substitute a one-byte
182 * local buffer. Callers cannot tell, since the function result doesn't
183 * depend on count.
184 */
185 if (count == 0)
186 {
187 str = onebyte;
188 count = 1;
189 }
190 target.bufstart = target.bufptr = str;
191 target.bufend = str + count - 1;
192 target.stream = NULL;
193 target.nchars = 0;
194 target.failed = false;
195 dopr(&target, fmt, args);
196 *(target.bufptr) = '\0';
197 return target.failed ? -1 : (target.bufptr - target.bufstart
198 + target.nchars);
199}
200
201int
202pg_snprintf(char *str, size_t count, const char *fmt,...)
203{
204 int len;
205 va_list args;
206
207 va_start(args, fmt);
208 len = pg_vsnprintf(str, count, fmt, args);
209 va_end(args);
210 return len;
211}
212
213int
214pg_vsprintf(char *str, const char *fmt, va_list args)
215{
216 PrintfTarget target;
217
218 target.bufstart = target.bufptr = str;
219 target.bufend = NULL;
220 target.stream = NULL;
221 target.nchars = 0; /* not really used in this case */
222 target.failed = false;
223 dopr(&target, fmt, args);
224 *(target.bufptr) = '\0';
225 return target.failed ? -1 : (target.bufptr - target.bufstart
226 + target.nchars);
227}
228
229int
230pg_sprintf(char *str, const char *fmt,...)
231{
232 int len;
233 va_list args;
234
235 va_start(args, fmt);
237 va_end(args);
238 return len;
239}
240
241int
242pg_vfprintf(FILE *stream, const char *fmt, va_list args)
243{
244 PrintfTarget target;
245 char buffer[1024]; /* size is arbitrary */
246
247 if (stream == NULL)
248 {
249 errno = EINVAL;
250 return -1;
251 }
252 target.bufstart = target.bufptr = buffer;
253 target.bufend = buffer + sizeof(buffer); /* use the whole buffer */
254 target.stream = stream;
255 target.nchars = 0;
256 target.failed = false;
257 dopr(&target, fmt, args);
258 /* dump any remaining buffer contents */
259 flushbuffer(&target);
260 return target.failed ? -1 : target.nchars;
261}
262
263int
264pg_fprintf(FILE *stream, const char *fmt,...)
265{
266 int len;
267 va_list args;
268
269 va_start(args, fmt);
270 len = pg_vfprintf(stream, fmt, args);
271 va_end(args);
272 return len;
273}
274
275int
276pg_vprintf(const char *fmt, va_list args)
277{
278 return pg_vfprintf(stdout, fmt, args);
279}
280
281int
282pg_printf(const char *fmt,...)
283{
284 int len;
285 va_list args;
286
287 va_start(args, fmt);
289 va_end(args);
290 return len;
291}
292
293/*
294 * Attempt to write the entire buffer to target->stream; discard the entire
295 * buffer in any case. Call this only when target->stream is defined.
296 */
297static void
299{
300 size_t nc = target->bufptr - target->bufstart;
301
302 /*
303 * Don't write anything if we already failed; this is to ensure we
304 * preserve the original failure's errno.
305 */
306 if (!target->failed && nc > 0)
307 {
308 size_t written;
309
310 written = fwrite(target->bufstart, 1, nc, target->stream);
311 target->nchars += written;
312 if (written != nc)
313 target->failed = true;
314 }
315 target->bufptr = target->bufstart;
316}
317
318
319static bool find_arguments(const char *format, va_list args,
320 PrintfArgValue *argvalues);
321static void fmtstr(const char *value, int leftjust, int minlen, int maxwidth,
322 int pointflag, PrintfTarget *target);
323static void fmtptr(const void *value, PrintfTarget *target);
324static void fmtint(long long value, char type, int forcesign,
325 int leftjust, int minlen, int zpad, int precision, int pointflag,
326 PrintfTarget *target);
327static void fmtchar(int value, int leftjust, int minlen, PrintfTarget *target);
328static void fmtfloat(double value, char type, int forcesign,
329 int leftjust, int minlen, int zpad, int precision, int pointflag,
330 PrintfTarget *target);
331static void dostr(const char *str, int slen, PrintfTarget *target);
332static void dopr_outch(int c, PrintfTarget *target);
333static void dopr_outchmulti(int c, int slen, PrintfTarget *target);
334static int adjust_sign(int is_negative, int forcesign, int *signvalue);
335static int compute_padlen(int minlen, int vallen, int leftjust);
336static void leading_pad(int zpad, int signvalue, int *padlen,
337 PrintfTarget *target);
338static void trailing_pad(int padlen, PrintfTarget *target);
339
340/*
341 * If strchrnul exists (it's a glibc-ism), it's a good bit faster than the
342 * equivalent manual loop. If it doesn't exist, provide a replacement.
343 *
344 * Note: glibc declares this as returning "char *", but that would require
345 * casting away const internally, so we don't follow that detail.
346 */
347#ifndef HAVE_STRCHRNUL
348
349static inline const char *
350strchrnul(const char *s, int c)
351{
352 while (*s != '\0' && *s != c)
353 s++;
354 return s;
355}
356
357#else
358
359/*
360 * glibc's <string.h> declares strchrnul only if _GNU_SOURCE is defined.
361 * While we typically use that on glibc platforms, configure will set
362 * HAVE_STRCHRNUL whether it's used or not. Fill in the missing declaration
363 * so that this file will compile cleanly with or without _GNU_SOURCE.
364 */
365#ifndef _GNU_SOURCE
366extern char *strchrnul(const char *s, int c);
367#endif
368
369#endif /* HAVE_STRCHRNUL */
370
371
372/*
373 * dopr(): the guts of *printf for all cases.
374 */
375static void
376dopr(PrintfTarget *target, const char *format, va_list args)
377{
378 int save_errno = errno;
379 const char *first_pct = NULL;
380 int ch;
381 bool have_dollar;
382 bool have_star;
383 bool afterstar;
384 int accum;
385 int longlongflag;
386 int longflag;
387 int pointflag;
388 int leftjust;
389 int fieldwidth;
390 int precision;
391 int zpad;
392 int forcesign;
393 int fmtpos;
394 int cvalue;
395 long long numvalue;
396 double fvalue;
397 const char *strvalue;
398 PrintfArgValue argvalues[PG_NL_ARGMAX + 1];
399
400 /*
401 * Initially, we suppose the format string does not use %n$. The first
402 * time we come to a conversion spec that has that, we'll call
403 * find_arguments() to check for consistent use of %n$ and fill the
404 * argvalues array with the argument values in the correct order.
405 */
406 have_dollar = false;
407
408 while (*format != '\0')
409 {
410 /* Locate next conversion specifier */
411 if (*format != '%')
412 {
413 /* Scan to next '%' or end of string */
414 const char *next_pct = strchrnul(format + 1, '%');
415
416 /* Dump literal data we just scanned over */
417 dostr(format, next_pct - format, target);
418 if (target->failed)
419 break;
420
421 if (*next_pct == '\0')
422 break;
423 format = next_pct;
424 }
425
426 /*
427 * Remember start of first conversion spec; if we find %n$, then it's
428 * sufficient for find_arguments() to start here, without rescanning
429 * earlier literal text.
430 */
431 if (first_pct == NULL)
432 first_pct = format;
433
434 /* Process conversion spec starting at *format */
435 format++;
436
437 /* Fast path for conversion spec that is exactly %s */
438 if (*format == 's')
439 {
440 format++;
441 strvalue = va_arg(args, char *);
442 if (strvalue == NULL)
443 strvalue = "(null)";
444 dostr(strvalue, strlen(strvalue), target);
445 if (target->failed)
446 break;
447 continue;
448 }
449
450 fieldwidth = precision = zpad = leftjust = forcesign = 0;
451 longflag = longlongflag = pointflag = 0;
452 fmtpos = accum = 0;
453 have_star = afterstar = false;
454nextch2:
455 ch = *format++;
456 switch (ch)
457 {
458 case '-':
459 leftjust = 1;
460 goto nextch2;
461 case '+':
462 forcesign = 1;
463 goto nextch2;
464 case '0':
465 /* set zero padding if no nonzero digits yet */
466 if (accum == 0 && !pointflag)
467 zpad = '0';
468 /* FALL THRU */
469 case '1':
470 case '2':
471 case '3':
472 case '4':
473 case '5':
474 case '6':
475 case '7':
476 case '8':
477 case '9':
478 accum = accum * 10 + (ch - '0');
479 goto nextch2;
480 case '.':
481 if (have_star)
482 have_star = false;
483 else
484 fieldwidth = accum;
485 pointflag = 1;
486 accum = 0;
487 goto nextch2;
488 case '*':
489 if (have_dollar)
490 {
491 /*
492 * We'll process value after reading n$. Note it's OK to
493 * assume have_dollar is set correctly, because in a valid
494 * format string the initial % must have had n$ if * does.
495 */
496 afterstar = true;
497 }
498 else
499 {
500 /* fetch and process value now */
501 int starval = va_arg(args, int);
502
503 if (pointflag)
504 {
505 precision = starval;
506 if (precision < 0)
507 {
508 precision = 0;
509 pointflag = 0;
510 }
511 }
512 else
513 {
514 fieldwidth = starval;
515 if (fieldwidth < 0)
516 {
517 leftjust = 1;
518 fieldwidth = -fieldwidth;
519 }
520 }
521 }
522 have_star = true;
523 accum = 0;
524 goto nextch2;
525 case '$':
526 /* First dollar sign? */
527 if (!have_dollar)
528 {
529 /* Yup, so examine all conversion specs in format */
530 if (!find_arguments(first_pct, args, argvalues))
531 goto bad_format;
532 have_dollar = true;
533 }
534 if (afterstar)
535 {
536 /* fetch and process star value */
537 int starval = argvalues[accum].i;
538
539 if (pointflag)
540 {
541 precision = starval;
542 if (precision < 0)
543 {
544 precision = 0;
545 pointflag = 0;
546 }
547 }
548 else
549 {
550 fieldwidth = starval;
551 if (fieldwidth < 0)
552 {
553 leftjust = 1;
554 fieldwidth = -fieldwidth;
555 }
556 }
557 afterstar = false;
558 }
559 else
560 fmtpos = accum;
561 accum = 0;
562 goto nextch2;
563#ifdef WIN32
564 case 'I':
565 /* Windows PRI*{32,64,PTR} size */
566 if (format[0] == '3' && format[1] == '2')
567 format += 2;
568 else if (format[0] == '6' && format[1] == '4')
569 {
570 format += 2;
571 longlongflag = 1;
572 }
573 else
574 {
575#if SIZEOF_VOID_P == SIZEOF_LONG
576 longflag = 1;
577#elif SIZEOF_VOID_P == SIZEOF_LONG_LONG
578 longlongflag = 1;
579#else
580#error "cannot find integer type of the same size as intptr_t"
581#endif
582 }
583 goto nextch2;
584#endif
585 case 'l':
586 if (longflag)
587 longlongflag = 1;
588 else
589 longflag = 1;
590 goto nextch2;
591 case 'z':
592#if SIZEOF_SIZE_T == SIZEOF_LONG
593 longflag = 1;
594#elif SIZEOF_SIZE_T == SIZEOF_LONG_LONG
595 longlongflag = 1;
596#else
597#error "cannot find integer type of the same size as size_t"
598#endif
599 goto nextch2;
600 case 'h':
601 case '\'':
602 /* ignore these */
603 goto nextch2;
604 case 'd':
605 case 'i':
606 if (!have_star)
607 {
608 if (pointflag)
609 precision = accum;
610 else
611 fieldwidth = accum;
612 }
613 if (have_dollar)
614 {
615 if (longlongflag)
616 numvalue = argvalues[fmtpos].ll;
617 else if (longflag)
618 numvalue = argvalues[fmtpos].l;
619 else
620 numvalue = argvalues[fmtpos].i;
621 }
622 else
623 {
624 if (longlongflag)
625 numvalue = va_arg(args, long long);
626 else if (longflag)
627 numvalue = va_arg(args, long);
628 else
629 numvalue = va_arg(args, int);
630 }
631 fmtint(numvalue, ch, forcesign, leftjust, fieldwidth, zpad,
632 precision, pointflag, target);
633 break;
634 case 'o':
635 case 'u':
636 case 'x':
637 case 'X':
638 if (!have_star)
639 {
640 if (pointflag)
641 precision = accum;
642 else
643 fieldwidth = accum;
644 }
645 if (have_dollar)
646 {
647 if (longlongflag)
648 numvalue = (unsigned long long) argvalues[fmtpos].ll;
649 else if (longflag)
650 numvalue = (unsigned long) argvalues[fmtpos].l;
651 else
652 numvalue = (unsigned int) argvalues[fmtpos].i;
653 }
654 else
655 {
656 if (longlongflag)
657 numvalue = (unsigned long long) va_arg(args, long long);
658 else if (longflag)
659 numvalue = (unsigned long) va_arg(args, long);
660 else
661 numvalue = (unsigned int) va_arg(args, int);
662 }
663 fmtint(numvalue, ch, forcesign, leftjust, fieldwidth, zpad,
664 precision, pointflag, target);
665 break;
666 case 'c':
667 if (!have_star)
668 {
669 if (pointflag)
670 precision = accum;
671 else
672 fieldwidth = accum;
673 }
674 if (have_dollar)
675 cvalue = (unsigned char) argvalues[fmtpos].i;
676 else
677 cvalue = (unsigned char) va_arg(args, int);
678 fmtchar(cvalue, leftjust, fieldwidth, target);
679 break;
680 case 's':
681 if (!have_star)
682 {
683 if (pointflag)
684 precision = accum;
685 else
686 fieldwidth = accum;
687 }
688 if (have_dollar)
689 strvalue = argvalues[fmtpos].cptr;
690 else
691 strvalue = va_arg(args, char *);
692 /* If string is NULL, silently substitute "(null)" */
693 if (strvalue == NULL)
694 strvalue = "(null)";
695 fmtstr(strvalue, leftjust, fieldwidth, precision, pointflag,
696 target);
697 break;
698 case 'p':
699 /* fieldwidth/leftjust are ignored ... */
700 if (have_dollar)
701 strvalue = argvalues[fmtpos].cptr;
702 else
703 strvalue = va_arg(args, char *);
704 fmtptr((const void *) strvalue, target);
705 break;
706 case 'e':
707 case 'E':
708 case 'f':
709 case 'g':
710 case 'G':
711 if (!have_star)
712 {
713 if (pointflag)
714 precision = accum;
715 else
716 fieldwidth = accum;
717 }
718 if (have_dollar)
719 fvalue = argvalues[fmtpos].d;
720 else
721 fvalue = va_arg(args, double);
722 fmtfloat(fvalue, ch, forcesign, leftjust,
723 fieldwidth, zpad,
724 precision, pointflag,
725 target);
726 break;
727 case 'm':
728 {
729 char errbuf[PG_STRERROR_R_BUFLEN];
730 const char *errm = strerror_r(save_errno,
731 errbuf, sizeof(errbuf));
732
733 dostr(errm, strlen(errm), target);
734 }
735 break;
736 case '%':
737 dopr_outch('%', target);
738 break;
739 default:
740
741 /*
742 * Anything else --- in particular, '\0' indicating end of
743 * format string --- is bogus.
744 */
745 goto bad_format;
746 }
747
748 /* Check for failure after each conversion spec */
749 if (target->failed)
750 break;
751 }
752
753 return;
754
755bad_format:
756 errno = EINVAL;
757 target->failed = true;
758}
759
760/*
761 * find_arguments(): sort out the arguments for a format spec with %n$
762 *
763 * If format is valid, return true and fill argvalues[i] with the value
764 * for the conversion spec that has %i$ or *i$. Else return false.
765 */
766static bool
767find_arguments(const char *format, va_list args,
768 PrintfArgValue *argvalues)
769{
770 int ch;
771 bool afterstar;
772 int accum;
773 int longlongflag;
774 int longflag;
775 int fmtpos;
776 int i;
777 int last_dollar = 0; /* Init to "no dollar arguments known" */
778 PrintfArgType argtypes[PG_NL_ARGMAX + 1] = {0};
779
780 /*
781 * This loop must accept the same format strings as the one in dopr().
782 * However, we don't need to analyze them to the same level of detail.
783 *
784 * Since we're only called if there's a dollar-type spec somewhere, we can
785 * fail immediately if we find a non-dollar spec. Per the C99 standard,
786 * all argument references in the format string must be one or the other.
787 */
788 while (*format != '\0')
789 {
790 /* Locate next conversion specifier */
791 if (*format != '%')
792 {
793 /* Unlike dopr, we can just quit if there's no more specifiers */
794 format = strchr(format + 1, '%');
795 if (format == NULL)
796 break;
797 }
798
799 /* Process conversion spec starting at *format */
800 format++;
801 longflag = longlongflag = 0;
802 fmtpos = accum = 0;
803 afterstar = false;
804nextch1:
805 ch = *format++;
806 switch (ch)
807 {
808 case '-':
809 case '+':
810 goto nextch1;
811 case '0':
812 case '1':
813 case '2':
814 case '3':
815 case '4':
816 case '5':
817 case '6':
818 case '7':
819 case '8':
820 case '9':
821 accum = accum * 10 + (ch - '0');
822 goto nextch1;
823 case '.':
824 accum = 0;
825 goto nextch1;
826 case '*':
827 if (afterstar)
828 return false; /* previous star missing dollar */
829 afterstar = true;
830 accum = 0;
831 goto nextch1;
832 case '$':
833 if (accum <= 0 || accum > PG_NL_ARGMAX)
834 return false;
835 if (afterstar)
836 {
837 if (argtypes[accum] &&
838 argtypes[accum] != ATYPE_INT)
839 return false;
840 argtypes[accum] = ATYPE_INT;
841 last_dollar = Max(last_dollar, accum);
842 afterstar = false;
843 }
844 else
845 fmtpos = accum;
846 accum = 0;
847 goto nextch1;
848#ifdef WIN32
849 case 'I':
850 /* Windows PRI*{32,64,PTR} size */
851 if (format[0] == '3' && format[1] == '2')
852 format += 2;
853 else if (format[0] == '6' && format[1] == '4')
854 {
855 format += 2;
856 longlongflag = 1;
857 }
858 else
859 {
860#if SIZEOF_VOID_P == SIZEOF_LONG
861 longflag = 1;
862#elif SIZEOF_VOID_P == SIZEOF_LONG_LONG
863 longlongflag = 1;
864#else
865#error "cannot find integer type of the same size as intptr_t"
866#endif
867 }
868 goto nextch1;
869#endif
870 case 'l':
871 if (longflag)
872 longlongflag = 1;
873 else
874 longflag = 1;
875 goto nextch1;
876 case 'z':
877#if SIZEOF_SIZE_T == SIZEOF_LONG
878 longflag = 1;
879#elif SIZEOF_SIZE_T == SIZEOF_LONG_LONG
880 longlongflag = 1;
881#else
882#error "cannot find integer type of the same size as size_t"
883#endif
884 goto nextch1;
885 case 'h':
886 case '\'':
887 /* ignore these */
888 goto nextch1;
889 case 'd':
890 case 'i':
891 case 'o':
892 case 'u':
893 case 'x':
894 case 'X':
895 if (fmtpos)
896 {
897 PrintfArgType atype;
898
899 if (longlongflag)
900 atype = ATYPE_LONGLONG;
901 else if (longflag)
902 atype = ATYPE_LONG;
903 else
904 atype = ATYPE_INT;
905 if (argtypes[fmtpos] &&
906 argtypes[fmtpos] != atype)
907 return false;
908 argtypes[fmtpos] = atype;
909 last_dollar = Max(last_dollar, fmtpos);
910 }
911 else
912 return false; /* non-dollar conversion spec */
913 break;
914 case 'c':
915 if (fmtpos)
916 {
917 if (argtypes[fmtpos] &&
918 argtypes[fmtpos] != ATYPE_INT)
919 return false;
920 argtypes[fmtpos] = ATYPE_INT;
921 last_dollar = Max(last_dollar, fmtpos);
922 }
923 else
924 return false; /* non-dollar conversion spec */
925 break;
926 case 's':
927 case 'p':
928 if (fmtpos)
929 {
930 if (argtypes[fmtpos] &&
931 argtypes[fmtpos] != ATYPE_CHARPTR)
932 return false;
933 argtypes[fmtpos] = ATYPE_CHARPTR;
934 last_dollar = Max(last_dollar, fmtpos);
935 }
936 else
937 return false; /* non-dollar conversion spec */
938 break;
939 case 'e':
940 case 'E':
941 case 'f':
942 case 'g':
943 case 'G':
944 if (fmtpos)
945 {
946 if (argtypes[fmtpos] &&
947 argtypes[fmtpos] != ATYPE_DOUBLE)
948 return false;
949 argtypes[fmtpos] = ATYPE_DOUBLE;
950 last_dollar = Max(last_dollar, fmtpos);
951 }
952 else
953 return false; /* non-dollar conversion spec */
954 break;
955 case 'm':
956 case '%':
957 break;
958 default:
959 return false; /* bogus format string */
960 }
961
962 /*
963 * If we finish the spec with afterstar still set, there's a
964 * non-dollar star in there.
965 */
966 if (afterstar)
967 return false; /* non-dollar conversion spec */
968 }
969
970 /*
971 * Format appears valid so far, so collect the arguments in physical
972 * order. (Since we rejected any non-dollar specs that would have
973 * collected arguments, we know that dopr() hasn't collected any yet.)
974 */
975 for (i = 1; i <= last_dollar; i++)
976 {
977 switch (argtypes[i])
978 {
979 case ATYPE_NONE:
980 return false;
981 case ATYPE_INT:
982 argvalues[i].i = va_arg(args, int);
983 break;
984 case ATYPE_LONG:
985 argvalues[i].l = va_arg(args, long);
986 break;
987 case ATYPE_LONGLONG:
988 argvalues[i].ll = va_arg(args, long long);
989 break;
990 case ATYPE_DOUBLE:
991 argvalues[i].d = va_arg(args, double);
992 break;
993 case ATYPE_CHARPTR:
994 argvalues[i].cptr = va_arg(args, char *);
995 break;
996 }
997 }
998
999 return true;
1000}
1001
1002static void
1003fmtstr(const char *value, int leftjust, int minlen, int maxwidth,
1004 int pointflag, PrintfTarget *target)
1005{
1006 int padlen,
1007 vallen; /* amount to pad */
1008
1009 /*
1010 * If a maxwidth (precision) is specified, we must not fetch more bytes
1011 * than that.
1012 */
1013 if (pointflag)
1014 vallen = strnlen(value, maxwidth);
1015 else
1016 vallen = strlen(value);
1017
1018 padlen = compute_padlen(minlen, vallen, leftjust);
1019
1020 if (padlen > 0)
1021 {
1022 dopr_outchmulti(' ', padlen, target);
1023 padlen = 0;
1024 }
1025
1026 dostr(value, vallen, target);
1027
1028 trailing_pad(padlen, target);
1029}
1030
1031static void
1032fmtptr(const void *value, PrintfTarget *target)
1033{
1034 int vallen;
1035 char convert[64];
1036
1037 /* we rely on regular C library's snprintf to do the basic conversion */
1038 vallen = snprintf(convert, sizeof(convert), "%p", value);
1039 if (vallen < 0)
1040 target->failed = true;
1041 else
1042 dostr(convert, vallen, target);
1043}
1044
1045static void
1046fmtint(long long value, char type, int forcesign, int leftjust,
1047 int minlen, int zpad, int precision, int pointflag,
1048 PrintfTarget *target)
1049{
1050 unsigned long long uvalue;
1051 int base;
1052 int dosign;
1053 const char *cvt = "0123456789abcdef";
1054 int signvalue = 0;
1055 char convert[64];
1056 int vallen = 0;
1057 int padlen; /* amount to pad */
1058 int zeropad; /* extra leading zeroes */
1059
1060 switch (type)
1061 {
1062 case 'd':
1063 case 'i':
1064 base = 10;
1065 dosign = 1;
1066 break;
1067 case 'o':
1068 base = 8;
1069 dosign = 0;
1070 break;
1071 case 'u':
1072 base = 10;
1073 dosign = 0;
1074 break;
1075 case 'x':
1076 base = 16;
1077 dosign = 0;
1078 break;
1079 case 'X':
1080 cvt = "0123456789ABCDEF";
1081 base = 16;
1082 dosign = 0;
1083 break;
1084 default:
1085 return; /* keep compiler quiet */
1086 }
1087
1088 /* disable MSVC warning about applying unary minus to an unsigned value */
1089#ifdef _MSC_VER
1090#pragma warning(push)
1091#pragma warning(disable: 4146)
1092#endif
1093 /* Handle +/- */
1094 if (dosign && adjust_sign((value < 0), forcesign, &signvalue))
1095 uvalue = -(unsigned long long) value;
1096 else
1097 uvalue = (unsigned long long) value;
1098#ifdef _MSC_VER
1099#pragma warning(pop)
1100#endif
1101
1102 /*
1103 * SUS: the result of converting 0 with an explicit precision of 0 is no
1104 * characters
1105 */
1106 if (value == 0 && pointflag && precision == 0)
1107 vallen = 0;
1108 else
1109 {
1110 /*
1111 * Convert integer to string. We special-case each of the possible
1112 * base values so as to avoid general-purpose divisions. On most
1113 * machines, division by a fixed constant can be done much more
1114 * cheaply than a general divide.
1115 */
1116 if (base == 10)
1117 {
1118 do
1119 {
1120 convert[sizeof(convert) - (++vallen)] = cvt[uvalue % 10];
1121 uvalue = uvalue / 10;
1122 } while (uvalue);
1123 }
1124 else if (base == 16)
1125 {
1126 do
1127 {
1128 convert[sizeof(convert) - (++vallen)] = cvt[uvalue % 16];
1129 uvalue = uvalue / 16;
1130 } while (uvalue);
1131 }
1132 else /* base == 8 */
1133 {
1134 do
1135 {
1136 convert[sizeof(convert) - (++vallen)] = cvt[uvalue % 8];
1137 uvalue = uvalue / 8;
1138 } while (uvalue);
1139 }
1140 }
1141
1142 zeropad = Max(0, precision - vallen);
1143
1144 padlen = compute_padlen(minlen, vallen + zeropad, leftjust);
1145
1146 leading_pad(zpad, signvalue, &padlen, target);
1147
1148 if (zeropad > 0)
1149 dopr_outchmulti('0', zeropad, target);
1150
1151 dostr(convert + sizeof(convert) - vallen, vallen, target);
1152
1153 trailing_pad(padlen, target);
1154}
1155
1156static void
1157fmtchar(int value, int leftjust, int minlen, PrintfTarget *target)
1158{
1159 int padlen; /* amount to pad */
1160
1161 padlen = compute_padlen(minlen, 1, leftjust);
1162
1163 if (padlen > 0)
1164 {
1165 dopr_outchmulti(' ', padlen, target);
1166 padlen = 0;
1167 }
1168
1169 dopr_outch(value, target);
1170
1171 trailing_pad(padlen, target);
1172}
1173
1174static void
1175fmtfloat(double value, char type, int forcesign, int leftjust,
1176 int minlen, int zpad, int precision, int pointflag,
1177 PrintfTarget *target)
1178{
1179 int signvalue = 0;
1180 int prec;
1181 int vallen;
1182 char fmt[8];
1183 char convert[1024];
1184 int zeropadlen = 0; /* amount to pad with zeroes */
1185 int padlen; /* amount to pad with spaces */
1186
1187 /*
1188 * We rely on the regular C library's snprintf to do the basic conversion,
1189 * then handle padding considerations here.
1190 *
1191 * The dynamic range of "double" is about 1E+-308 for IEEE math, and not
1192 * too wildly more than that with other hardware. In "f" format, snprintf
1193 * could therefore generate at most 308 characters to the left of the
1194 * decimal point; while we need to allow the precision to get as high as
1195 * 308+17 to ensure that we don't truncate significant digits from very
1196 * small values. To handle both these extremes, we use a buffer of 1024
1197 * bytes and limit requested precision to 350 digits; this should prevent
1198 * buffer overrun even with non-IEEE math. If the original precision
1199 * request was more than 350, separately pad with zeroes.
1200 *
1201 * We handle infinities and NaNs specially to ensure platform-independent
1202 * output.
1203 */
1204 if (precision < 0) /* cover possible overflow of "accum" */
1205 precision = 0;
1206 prec = Min(precision, 350);
1207
1208 if (isnan(value))
1209 {
1210 strcpy(convert, "NaN");
1211 vallen = 3;
1212 /* no zero padding, regardless of precision spec */
1213 }
1214 else
1215 {
1216 /*
1217 * Handle sign (NaNs have no sign, so we don't do this in the case
1218 * above). "value < 0.0" will not be true for IEEE minus zero, so we
1219 * detect that by looking for the case where value equals 0.0
1220 * according to == but not according to memcmp.
1221 */
1222 static const double dzero = 0.0;
1223
1224 if (adjust_sign((value < 0.0 ||
1225 (value == 0.0 &&
1226 memcmp(&value, &dzero, sizeof(double)) != 0)),
1227 forcesign, &signvalue))
1228 value = -value;
1229
1230 if (isinf(value))
1231 {
1232 strcpy(convert, "Infinity");
1233 vallen = 8;
1234 /* no zero padding, regardless of precision spec */
1235 }
1236 else if (pointflag)
1237 {
1238 zeropadlen = precision - prec;
1239 fmt[0] = '%';
1240 fmt[1] = '.';
1241 fmt[2] = '*';
1242 fmt[3] = type;
1243 fmt[4] = '\0';
1244 vallen = snprintf(convert, sizeof(convert), fmt, prec, value);
1245 }
1246 else
1247 {
1248 fmt[0] = '%';
1249 fmt[1] = type;
1250 fmt[2] = '\0';
1251 vallen = snprintf(convert, sizeof(convert), fmt, value);
1252 }
1253 if (vallen < 0)
1254 goto fail;
1255
1256 /*
1257 * Windows, alone among our supported platforms, likes to emit
1258 * three-digit exponent fields even when two digits would do. Hack
1259 * such results to look like the way everyone else does it.
1260 */
1261#ifdef WIN32
1262 if (vallen >= 6 &&
1263 convert[vallen - 5] == 'e' &&
1264 convert[vallen - 3] == '0')
1265 {
1266 convert[vallen - 3] = convert[vallen - 2];
1267 convert[vallen - 2] = convert[vallen - 1];
1268 vallen--;
1269 }
1270#endif
1271 }
1272
1273 padlen = compute_padlen(minlen, vallen + zeropadlen, leftjust);
1274
1275 leading_pad(zpad, signvalue, &padlen, target);
1276
1277 if (zeropadlen > 0)
1278 {
1279 /* If 'e' or 'E' format, inject zeroes before the exponent */
1280 char *epos = strrchr(convert, 'e');
1281
1282 if (!epos)
1283 epos = strrchr(convert, 'E');
1284 if (epos)
1285 {
1286 /* pad before exponent */
1287 dostr(convert, epos - convert, target);
1288 dopr_outchmulti('0', zeropadlen, target);
1289 dostr(epos, vallen - (epos - convert), target);
1290 }
1291 else
1292 {
1293 /* no exponent, pad after the digits */
1294 dostr(convert, vallen, target);
1295 dopr_outchmulti('0', zeropadlen, target);
1296 }
1297 }
1298 else
1299 {
1300 /* no zero padding, just emit the number as-is */
1301 dostr(convert, vallen, target);
1302 }
1303
1304 trailing_pad(padlen, target);
1305 return;
1306
1307fail:
1308 target->failed = true;
1309}
1310
1311/*
1312 * Nonstandard entry point to print a double value efficiently.
1313 *
1314 * This is approximately equivalent to strfromd(), but has an API more
1315 * adapted to what float8out() wants. The behavior is like snprintf()
1316 * with a format of "%.ng", where n is the specified precision.
1317 * However, the target buffer must be nonempty (i.e. count > 0), and
1318 * the precision is silently bounded to a sane range.
1319 */
1320int
1321pg_strfromd(char *str, size_t count, int precision, double value)
1322{
1323 PrintfTarget target;
1324 int signvalue = 0;
1325 int vallen;
1326 char fmt[8];
1327 char convert[64];
1328
1329 /* Set up the target like pg_snprintf, but require nonempty buffer */
1330 Assert(count > 0);
1331 target.bufstart = target.bufptr = str;
1332 target.bufend = str + count - 1;
1333 target.stream = NULL;
1334 target.nchars = 0;
1335 target.failed = false;
1336
1337 /*
1338 * We bound precision to a reasonable range; the combination of this and
1339 * the knowledge that we're using "g" format without padding allows the
1340 * convert[] buffer to be reasonably small.
1341 */
1342 if (precision < 1)
1343 precision = 1;
1344 else if (precision > 32)
1345 precision = 32;
1346
1347 /*
1348 * The rest is just an inlined version of the fmtfloat() logic above,
1349 * simplified using the knowledge that no padding is wanted.
1350 */
1351 if (isnan(value))
1352 {
1353 strcpy(convert, "NaN");
1354 vallen = 3;
1355 }
1356 else
1357 {
1358 static const double dzero = 0.0;
1359
1360 if (value < 0.0 ||
1361 (value == 0.0 &&
1362 memcmp(&value, &dzero, sizeof(double)) != 0))
1363 {
1364 signvalue = '-';
1365 value = -value;
1366 }
1367
1368 if (isinf(value))
1369 {
1370 strcpy(convert, "Infinity");
1371 vallen = 8;
1372 }
1373 else
1374 {
1375 fmt[0] = '%';
1376 fmt[1] = '.';
1377 fmt[2] = '*';
1378 fmt[3] = 'g';
1379 fmt[4] = '\0';
1380 vallen = snprintf(convert, sizeof(convert), fmt, precision, value);
1381 if (vallen < 0)
1382 {
1383 target.failed = true;
1384 goto fail;
1385 }
1386
1387#ifdef WIN32
1388 if (vallen >= 6 &&
1389 convert[vallen - 5] == 'e' &&
1390 convert[vallen - 3] == '0')
1391 {
1392 convert[vallen - 3] = convert[vallen - 2];
1393 convert[vallen - 2] = convert[vallen - 1];
1394 vallen--;
1395 }
1396#endif
1397 }
1398 }
1399
1400 if (signvalue)
1401 dopr_outch(signvalue, &target);
1402
1403 dostr(convert, vallen, &target);
1404
1405fail:
1406 *(target.bufptr) = '\0';
1407 return target.failed ? -1 : (target.bufptr - target.bufstart
1408 + target.nchars);
1409}
1410
1411
1412static void
1413dostr(const char *str, int slen, PrintfTarget *target)
1414{
1415 /* fast path for common case of slen == 1 */
1416 if (slen == 1)
1417 {
1418 dopr_outch(*str, target);
1419 return;
1420 }
1421
1422 while (slen > 0)
1423 {
1424 int avail;
1425
1426 if (target->bufend != NULL)
1427 avail = target->bufend - target->bufptr;
1428 else
1429 avail = slen;
1430 if (avail <= 0)
1431 {
1432 /* buffer full, can we dump to stream? */
1433 if (target->stream == NULL)
1434 {
1435 target->nchars += slen; /* no, lose the data */
1436 return;
1437 }
1438 flushbuffer(target);
1439 continue;
1440 }
1441 avail = Min(avail, slen);
1442 memmove(target->bufptr, str, avail);
1443 target->bufptr += avail;
1444 str += avail;
1445 slen -= avail;
1446 }
1447}
1448
1449static void
1451{
1452 if (target->bufend != NULL && target->bufptr >= target->bufend)
1453 {
1454 /* buffer full, can we dump to stream? */
1455 if (target->stream == NULL)
1456 {
1457 target->nchars++; /* no, lose the data */
1458 return;
1459 }
1460 flushbuffer(target);
1461 }
1462 *(target->bufptr++) = c;
1463}
1464
1465static void
1466dopr_outchmulti(int c, int slen, PrintfTarget *target)
1467{
1468 /* fast path for common case of slen == 1 */
1469 if (slen == 1)
1470 {
1471 dopr_outch(c, target);
1472 return;
1473 }
1474
1475 while (slen > 0)
1476 {
1477 int avail;
1478
1479 if (target->bufend != NULL)
1480 avail = target->bufend - target->bufptr;
1481 else
1482 avail = slen;
1483 if (avail <= 0)
1484 {
1485 /* buffer full, can we dump to stream? */
1486 if (target->stream == NULL)
1487 {
1488 target->nchars += slen; /* no, lose the data */
1489 return;
1490 }
1491 flushbuffer(target);
1492 continue;
1493 }
1494 avail = Min(avail, slen);
1495 memset(target->bufptr, c, avail);
1496 target->bufptr += avail;
1497 slen -= avail;
1498 }
1499}
1500
1501
1502static int
1503adjust_sign(int is_negative, int forcesign, int *signvalue)
1504{
1505 if (is_negative)
1506 {
1507 *signvalue = '-';
1508 return true;
1509 }
1510 else if (forcesign)
1511 *signvalue = '+';
1512 return false;
1513}
1514
1515
1516static int
1517compute_padlen(int minlen, int vallen, int leftjust)
1518{
1519 int padlen;
1520
1521 padlen = minlen - vallen;
1522 if (padlen < 0)
1523 padlen = 0;
1524 if (leftjust)
1525 padlen = -padlen;
1526 return padlen;
1527}
1528
1529
1530static void
1531leading_pad(int zpad, int signvalue, int *padlen, PrintfTarget *target)
1532{
1533 int maxpad;
1534
1535 if (*padlen > 0 && zpad)
1536 {
1537 if (signvalue)
1538 {
1539 dopr_outch(signvalue, target);
1540 --(*padlen);
1541 signvalue = 0;
1542 }
1543 if (*padlen > 0)
1544 {
1545 dopr_outchmulti(zpad, *padlen, target);
1546 *padlen = 0;
1547 }
1548 }
1549 maxpad = (signvalue != 0);
1550 if (*padlen > maxpad)
1551 {
1552 dopr_outchmulti(' ', *padlen - maxpad, target);
1553 *padlen = maxpad;
1554 }
1555 if (signvalue)
1556 {
1557 dopr_outch(signvalue, target);
1558 if (*padlen > 0)
1559 --(*padlen);
1560 else if (*padlen < 0)
1561 ++(*padlen);
1562 }
1563}
1564
1565
1566static void
1567trailing_pad(int padlen, PrintfTarget *target)
1568{
1569 if (padlen < 0)
1570 dopr_outchmulti(' ', -padlen, target);
1571}
#define Min(x, y)
Definition: c.h:961
#define Max(x, y)
Definition: c.h:955
#define Assert(condition)
Definition: c.h:815
const char * str
static struct @162 value
int i
Definition: isn.c:72
static void const char * fmt
va_end(args)
va_start(args, fmt)
static char format
const void size_t len
#define PG_STRERROR_R_BUFLEN
Definition: port.h:257
#define snprintf
Definition: port.h:239
#define strerror_r
Definition: port.h:256
size_t strnlen(const char *str, size_t maxlen)
Definition: strnlen.c:26
char * c
static void dostr(const char *str, int slen, PrintfTarget *target)
Definition: snprintf.c:1413
static void dopr_outch(int c, PrintfTarget *target)
Definition: snprintf.c:1450
static void fmtint(long long value, char type, int forcesign, int leftjust, int minlen, int zpad, int precision, int pointflag, PrintfTarget *target)
Definition: snprintf.c:1046
static void leading_pad(int zpad, int signvalue, int *padlen, PrintfTarget *target)
Definition: snprintf.c:1531
int pg_strfromd(char *str, size_t count, int precision, double value)
Definition: snprintf.c:1321
static void fmtptr(const void *value, PrintfTarget *target)
Definition: snprintf.c:1032
static void flushbuffer(PrintfTarget *target)
Definition: snprintf.c:298
int pg_printf(const char *fmt,...)
Definition: snprintf.c:282
static void fmtchar(int value, int leftjust, int minlen, PrintfTarget *target)
Definition: snprintf.c:1157
static void fmtstr(const char *value, int leftjust, int minlen, int maxwidth, int pointflag, PrintfTarget *target)
Definition: snprintf.c:1003
int pg_vprintf(const char *fmt, va_list args)
Definition: snprintf.c:276
int pg_snprintf(char *str, size_t count, const char *fmt,...)
Definition: snprintf.c:202
static int compute_padlen(int minlen, int vallen, int leftjust)
Definition: snprintf.c:1517
int pg_vsnprintf(char *str, size_t count, const char *fmt, va_list args)
Definition: snprintf.c:174
#define PG_NL_ARGMAX
Definition: snprintf.c:44
static void trailing_pad(int padlen, PrintfTarget *target)
Definition: snprintf.c:1567
static void fmtfloat(double value, char type, int forcesign, int leftjust, int minlen, int zpad, int precision, int pointflag, PrintfTarget *target)
Definition: snprintf.c:1175
int pg_sprintf(char *str, const char *fmt,...)
Definition: snprintf.c:230
static const char * strchrnul(const char *s, int c)
Definition: snprintf.c:350
static bool find_arguments(const char *format, va_list args, PrintfArgValue *argvalues)
Definition: snprintf.c:767
int pg_vsprintf(char *str, const char *fmt, va_list args)
Definition: snprintf.c:214
static void dopr(PrintfTarget *target, const char *format, va_list args)
Definition: snprintf.c:376
static void dopr_outchmulti(int c, int slen, PrintfTarget *target)
Definition: snprintf.c:1466
int pg_fprintf(FILE *stream, const char *fmt,...)
Definition: snprintf.c:264
PrintfArgType
Definition: snprintf.c:143
@ ATYPE_LONGLONG
Definition: snprintf.c:147
@ ATYPE_INT
Definition: snprintf.c:145
@ ATYPE_LONG
Definition: snprintf.c:146
@ ATYPE_CHARPTR
Definition: snprintf.c:149
@ ATYPE_NONE
Definition: snprintf.c:144
@ ATYPE_DOUBLE
Definition: snprintf.c:148
int pg_vfprintf(FILE *stream, const char *fmt, va_list args)
Definition: snprintf.c:242
static int adjust_sign(int is_negative, int forcesign, int *signvalue)
Definition: snprintf.c:1503
bool failed
Definition: snprintf.c:133
char * bufstart
Definition: snprintf.c:128
char * bufend
Definition: snprintf.c:129
char * bufptr
Definition: snprintf.c:127
FILE * stream
Definition: snprintf.c:131
long long ll
Definition: snprintf.c:156
char * cptr
Definition: snprintf.c:158
const char * type
static void convert(const int32 val, char *const buf)
Definition: zic.c:1992