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);
236 len = pg_vsprintf(str, fmt, args);
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);
288 len = pg_vfprintf(stdout, fmt, args);
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, but since adopted by some other
342 * platforms), it's a good bit faster than the equivalent manual loop.
343 * Use it if possible, and if it doesn't exist, use this replacement.
344 *
345 * Note: glibc declares this as returning "char *", but that would require
346 * casting away const internally, so we don't follow that detail.
347 *
348 * Note: macOS has this too as of Sequoia 15.4, but it's hidden behind
349 * a deployment-target check that causes compile errors if the deployment
350 * target isn't high enough. So !HAVE_DECL_STRCHRNUL may mean "yes it's
351 * declared, but it doesn't compile". To avoid failing in that scenario,
352 * use a macro to avoid matching <string.h>'s name.
353 */
354#if !HAVE_DECL_STRCHRNUL
355
356#define strchrnul pg_strchrnul
357
358static inline const char *
359strchrnul(const char *s, int c)
360{
361 while (*s != '\0' && *s != c)
362 s++;
363 return s;
364}
365
366#endif /* !HAVE_DECL_STRCHRNUL */
367
368
369/*
370 * dopr(): the guts of *printf for all cases.
371 */
372static void
373dopr(PrintfTarget *target, const char *format, va_list args)
374{
375 int save_errno = errno;
376 const char *first_pct = NULL;
377 int ch;
378 bool have_dollar;
379 bool have_star;
380 bool afterstar;
381 int accum;
382 int longlongflag;
383 int longflag;
384 int pointflag;
385 int leftjust;
386 int fieldwidth;
387 int precision;
388 int zpad;
389 int forcesign;
390 int fmtpos;
391 int cvalue;
392 long long numvalue;
393 double fvalue;
394 const char *strvalue;
395 PrintfArgValue argvalues[PG_NL_ARGMAX + 1];
396
397 /*
398 * Initially, we suppose the format string does not use %n$. The first
399 * time we come to a conversion spec that has that, we'll call
400 * find_arguments() to check for consistent use of %n$ and fill the
401 * argvalues array with the argument values in the correct order.
402 */
403 have_dollar = false;
404
405 while (*format != '\0')
406 {
407 /* Locate next conversion specifier */
408 if (*format != '%')
409 {
410 /* Scan to next '%' or end of string */
411 const char *next_pct = strchrnul(format + 1, '%');
412
413 /* Dump literal data we just scanned over */
414 dostr(format, next_pct - format, target);
415 if (target->failed)
416 break;
417
418 if (*next_pct == '\0')
419 break;
420 format = next_pct;
421 }
422
423 /*
424 * Remember start of first conversion spec; if we find %n$, then it's
425 * sufficient for find_arguments() to start here, without rescanning
426 * earlier literal text.
427 */
428 if (first_pct == NULL)
429 first_pct = format;
430
431 /* Process conversion spec starting at *format */
432 format++;
433
434 /* Fast path for conversion spec that is exactly %s */
435 if (*format == 's')
436 {
437 format++;
438 strvalue = va_arg(args, char *);
439 if (strvalue == NULL)
440 strvalue = "(null)";
441 dostr(strvalue, strlen(strvalue), target);
442 if (target->failed)
443 break;
444 continue;
445 }
446
447 fieldwidth = precision = zpad = leftjust = forcesign = 0;
448 longflag = longlongflag = pointflag = 0;
449 fmtpos = accum = 0;
450 have_star = afterstar = false;
451nextch2:
452 ch = *format++;
453 switch (ch)
454 {
455 case '-':
456 leftjust = 1;
457 goto nextch2;
458 case '+':
459 forcesign = 1;
460 goto nextch2;
461 case '0':
462 /* set zero padding if no nonzero digits yet */
463 if (accum == 0 && !pointflag)
464 zpad = '0';
465 /* FALL THRU */
466 case '1':
467 case '2':
468 case '3':
469 case '4':
470 case '5':
471 case '6':
472 case '7':
473 case '8':
474 case '9':
475 accum = accum * 10 + (ch - '0');
476 goto nextch2;
477 case '.':
478 if (have_star)
479 have_star = false;
480 else
481 fieldwidth = accum;
482 pointflag = 1;
483 accum = 0;
484 goto nextch2;
485 case '*':
486 if (have_dollar)
487 {
488 /*
489 * We'll process value after reading n$. Note it's OK to
490 * assume have_dollar is set correctly, because in a valid
491 * format string the initial % must have had n$ if * does.
492 */
493 afterstar = true;
494 }
495 else
496 {
497 /* fetch and process value now */
498 int starval = va_arg(args, int);
499
500 if (pointflag)
501 {
502 precision = starval;
503 if (precision < 0)
504 {
505 precision = 0;
506 pointflag = 0;
507 }
508 }
509 else
510 {
511 fieldwidth = starval;
512 if (fieldwidth < 0)
513 {
514 leftjust = 1;
515 fieldwidth = -fieldwidth;
516 }
517 }
518 }
519 have_star = true;
520 accum = 0;
521 goto nextch2;
522 case '$':
523 /* First dollar sign? */
524 if (!have_dollar)
525 {
526 /* Yup, so examine all conversion specs in format */
527 if (!find_arguments(first_pct, args, argvalues))
528 goto bad_format;
529 have_dollar = true;
530 }
531 if (afterstar)
532 {
533 /* fetch and process star value */
534 int starval = argvalues[accum].i;
535
536 if (pointflag)
537 {
538 precision = starval;
539 if (precision < 0)
540 {
541 precision = 0;
542 pointflag = 0;
543 }
544 }
545 else
546 {
547 fieldwidth = starval;
548 if (fieldwidth < 0)
549 {
550 leftjust = 1;
551 fieldwidth = -fieldwidth;
552 }
553 }
554 afterstar = false;
555 }
556 else
557 fmtpos = accum;
558 accum = 0;
559 goto nextch2;
560 case 'l':
561 if (longflag)
562 longlongflag = 1;
563 else
564 longflag = 1;
565 goto nextch2;
566 case 'z':
567#if SIZEOF_SIZE_T == SIZEOF_LONG
568 longflag = 1;
569#elif SIZEOF_SIZE_T == SIZEOF_LONG_LONG
570 longlongflag = 1;
571#else
572#error "cannot find integer type of the same size as size_t"
573#endif
574 goto nextch2;
575 case 'h':
576 case '\'':
577 /* ignore these */
578 goto nextch2;
579 case 'd':
580 case 'i':
581 if (!have_star)
582 {
583 if (pointflag)
584 precision = accum;
585 else
586 fieldwidth = accum;
587 }
588 if (have_dollar)
589 {
590 if (longlongflag)
591 numvalue = argvalues[fmtpos].ll;
592 else if (longflag)
593 numvalue = argvalues[fmtpos].l;
594 else
595 numvalue = argvalues[fmtpos].i;
596 }
597 else
598 {
599 if (longlongflag)
600 numvalue = va_arg(args, long long);
601 else if (longflag)
602 numvalue = va_arg(args, long);
603 else
604 numvalue = va_arg(args, int);
605 }
606 fmtint(numvalue, ch, forcesign, leftjust, fieldwidth, zpad,
607 precision, pointflag, target);
608 break;
609 case 'o':
610 case 'u':
611 case 'x':
612 case 'X':
613 if (!have_star)
614 {
615 if (pointflag)
616 precision = accum;
617 else
618 fieldwidth = accum;
619 }
620 if (have_dollar)
621 {
622 if (longlongflag)
623 numvalue = (unsigned long long) argvalues[fmtpos].ll;
624 else if (longflag)
625 numvalue = (unsigned long) argvalues[fmtpos].l;
626 else
627 numvalue = (unsigned int) argvalues[fmtpos].i;
628 }
629 else
630 {
631 if (longlongflag)
632 numvalue = (unsigned long long) va_arg(args, long long);
633 else if (longflag)
634 numvalue = (unsigned long) va_arg(args, long);
635 else
636 numvalue = (unsigned int) va_arg(args, int);
637 }
638 fmtint(numvalue, ch, forcesign, leftjust, fieldwidth, zpad,
639 precision, pointflag, target);
640 break;
641 case 'c':
642 if (!have_star)
643 {
644 if (pointflag)
645 precision = accum;
646 else
647 fieldwidth = accum;
648 }
649 if (have_dollar)
650 cvalue = (unsigned char) argvalues[fmtpos].i;
651 else
652 cvalue = (unsigned char) va_arg(args, int);
653 fmtchar(cvalue, leftjust, fieldwidth, target);
654 break;
655 case 's':
656 if (!have_star)
657 {
658 if (pointflag)
659 precision = accum;
660 else
661 fieldwidth = accum;
662 }
663 if (have_dollar)
664 strvalue = argvalues[fmtpos].cptr;
665 else
666 strvalue = va_arg(args, char *);
667 /* If string is NULL, silently substitute "(null)" */
668 if (strvalue == NULL)
669 strvalue = "(null)";
670 fmtstr(strvalue, leftjust, fieldwidth, precision, pointflag,
671 target);
672 break;
673 case 'p':
674 /* fieldwidth/leftjust are ignored ... */
675 if (have_dollar)
676 strvalue = argvalues[fmtpos].cptr;
677 else
678 strvalue = va_arg(args, char *);
679 fmtptr((const void *) strvalue, target);
680 break;
681 case 'e':
682 case 'E':
683 case 'f':
684 case 'g':
685 case 'G':
686 if (!have_star)
687 {
688 if (pointflag)
689 precision = accum;
690 else
691 fieldwidth = accum;
692 }
693 if (have_dollar)
694 fvalue = argvalues[fmtpos].d;
695 else
696 fvalue = va_arg(args, double);
697 fmtfloat(fvalue, ch, forcesign, leftjust,
698 fieldwidth, zpad,
699 precision, pointflag,
700 target);
701 break;
702 case 'm':
703 {
704 char errbuf[PG_STRERROR_R_BUFLEN];
705 const char *errm = strerror_r(save_errno,
706 errbuf, sizeof(errbuf));
707
708 dostr(errm, strlen(errm), target);
709 }
710 break;
711 case '%':
712 dopr_outch('%', target);
713 break;
714 default:
715
716 /*
717 * Anything else --- in particular, '\0' indicating end of
718 * format string --- is bogus.
719 */
720 goto bad_format;
721 }
722
723 /* Check for failure after each conversion spec */
724 if (target->failed)
725 break;
726 }
727
728 return;
729
730bad_format:
731 errno = EINVAL;
732 target->failed = true;
733}
734
735/*
736 * find_arguments(): sort out the arguments for a format spec with %n$
737 *
738 * If format is valid, return true and fill argvalues[i] with the value
739 * for the conversion spec that has %i$ or *i$. Else return false.
740 */
741static bool
742find_arguments(const char *format, va_list args,
743 PrintfArgValue *argvalues)
744{
745 int ch;
746 bool afterstar;
747 int accum;
748 int longlongflag;
749 int longflag;
750 int fmtpos;
751 int i;
752 int last_dollar = 0; /* Init to "no dollar arguments known" */
753 PrintfArgType argtypes[PG_NL_ARGMAX + 1] = {0};
754
755 /*
756 * This loop must accept the same format strings as the one in dopr().
757 * However, we don't need to analyze them to the same level of detail.
758 *
759 * Since we're only called if there's a dollar-type spec somewhere, we can
760 * fail immediately if we find a non-dollar spec. Per the C99 standard,
761 * all argument references in the format string must be one or the other.
762 */
763 while (*format != '\0')
764 {
765 /* Locate next conversion specifier */
766 if (*format != '%')
767 {
768 /* Unlike dopr, we can just quit if there's no more specifiers */
769 format = strchr(format + 1, '%');
770 if (format == NULL)
771 break;
772 }
773
774 /* Process conversion spec starting at *format */
775 format++;
776 longflag = longlongflag = 0;
777 fmtpos = accum = 0;
778 afterstar = false;
779nextch1:
780 ch = *format++;
781 switch (ch)
782 {
783 case '-':
784 case '+':
785 goto nextch1;
786 case '0':
787 case '1':
788 case '2':
789 case '3':
790 case '4':
791 case '5':
792 case '6':
793 case '7':
794 case '8':
795 case '9':
796 accum = accum * 10 + (ch - '0');
797 goto nextch1;
798 case '.':
799 accum = 0;
800 goto nextch1;
801 case '*':
802 if (afterstar)
803 return false; /* previous star missing dollar */
804 afterstar = true;
805 accum = 0;
806 goto nextch1;
807 case '$':
808 if (accum <= 0 || accum > PG_NL_ARGMAX)
809 return false;
810 if (afterstar)
811 {
812 if (argtypes[accum] &&
813 argtypes[accum] != ATYPE_INT)
814 return false;
815 argtypes[accum] = ATYPE_INT;
816 last_dollar = Max(last_dollar, accum);
817 afterstar = false;
818 }
819 else
820 fmtpos = accum;
821 accum = 0;
822 goto nextch1;
823 case 'l':
824 if (longflag)
825 longlongflag = 1;
826 else
827 longflag = 1;
828 goto nextch1;
829 case 'z':
830#if SIZEOF_SIZE_T == SIZEOF_LONG
831 longflag = 1;
832#elif SIZEOF_SIZE_T == SIZEOF_LONG_LONG
833 longlongflag = 1;
834#else
835#error "cannot find integer type of the same size as size_t"
836#endif
837 goto nextch1;
838 case 'h':
839 case '\'':
840 /* ignore these */
841 goto nextch1;
842 case 'd':
843 case 'i':
844 case 'o':
845 case 'u':
846 case 'x':
847 case 'X':
848 if (fmtpos)
849 {
850 PrintfArgType atype;
851
852 if (longlongflag)
853 atype = ATYPE_LONGLONG;
854 else if (longflag)
855 atype = ATYPE_LONG;
856 else
857 atype = ATYPE_INT;
858 if (argtypes[fmtpos] &&
859 argtypes[fmtpos] != atype)
860 return false;
861 argtypes[fmtpos] = atype;
862 last_dollar = Max(last_dollar, fmtpos);
863 }
864 else
865 return false; /* non-dollar conversion spec */
866 break;
867 case 'c':
868 if (fmtpos)
869 {
870 if (argtypes[fmtpos] &&
871 argtypes[fmtpos] != ATYPE_INT)
872 return false;
873 argtypes[fmtpos] = ATYPE_INT;
874 last_dollar = Max(last_dollar, fmtpos);
875 }
876 else
877 return false; /* non-dollar conversion spec */
878 break;
879 case 's':
880 case 'p':
881 if (fmtpos)
882 {
883 if (argtypes[fmtpos] &&
884 argtypes[fmtpos] != ATYPE_CHARPTR)
885 return false;
886 argtypes[fmtpos] = ATYPE_CHARPTR;
887 last_dollar = Max(last_dollar, fmtpos);
888 }
889 else
890 return false; /* non-dollar conversion spec */
891 break;
892 case 'e':
893 case 'E':
894 case 'f':
895 case 'g':
896 case 'G':
897 if (fmtpos)
898 {
899 if (argtypes[fmtpos] &&
900 argtypes[fmtpos] != ATYPE_DOUBLE)
901 return false;
902 argtypes[fmtpos] = ATYPE_DOUBLE;
903 last_dollar = Max(last_dollar, fmtpos);
904 }
905 else
906 return false; /* non-dollar conversion spec */
907 break;
908 case 'm':
909 case '%':
910 break;
911 default:
912 return false; /* bogus format string */
913 }
914
915 /*
916 * If we finish the spec with afterstar still set, there's a
917 * non-dollar star in there.
918 */
919 if (afterstar)
920 return false; /* non-dollar conversion spec */
921 }
922
923 /*
924 * Format appears valid so far, so collect the arguments in physical
925 * order. (Since we rejected any non-dollar specs that would have
926 * collected arguments, we know that dopr() hasn't collected any yet.)
927 */
928 for (i = 1; i <= last_dollar; i++)
929 {
930 switch (argtypes[i])
931 {
932 case ATYPE_NONE:
933 return false;
934 case ATYPE_INT:
935 argvalues[i].i = va_arg(args, int);
936 break;
937 case ATYPE_LONG:
938 argvalues[i].l = va_arg(args, long);
939 break;
940 case ATYPE_LONGLONG:
941 argvalues[i].ll = va_arg(args, long long);
942 break;
943 case ATYPE_DOUBLE:
944 argvalues[i].d = va_arg(args, double);
945 break;
946 case ATYPE_CHARPTR:
947 argvalues[i].cptr = va_arg(args, char *);
948 break;
949 }
950 }
951
952 return true;
953}
954
955static void
956fmtstr(const char *value, int leftjust, int minlen, int maxwidth,
957 int pointflag, PrintfTarget *target)
958{
959 int padlen,
960 vallen; /* amount to pad */
961
962 /*
963 * If a maxwidth (precision) is specified, we must not fetch more bytes
964 * than that.
965 */
966 if (pointflag)
967 vallen = strnlen(value, maxwidth);
968 else
969 vallen = strlen(value);
970
971 padlen = compute_padlen(minlen, vallen, leftjust);
972
973 if (padlen > 0)
974 {
975 dopr_outchmulti(' ', padlen, target);
976 padlen = 0;
977 }
978
979 dostr(value, vallen, target);
980
981 trailing_pad(padlen, target);
982}
983
984static void
985fmtptr(const void *value, PrintfTarget *target)
986{
987 int vallen;
988 char convert[64];
989
990 /* we rely on regular C library's snprintf to do the basic conversion */
991 vallen = snprintf(convert, sizeof(convert), "%p", value);
992 if (vallen < 0)
993 target->failed = true;
994 else
995 dostr(convert, vallen, target);
996}
997
998static void
999fmtint(long long value, char type, int forcesign, int leftjust,
1000 int minlen, int zpad, int precision, int pointflag,
1001 PrintfTarget *target)
1002{
1003 unsigned long long uvalue;
1004 int base;
1005 int dosign;
1006 const char *cvt = "0123456789abcdef";
1007 int signvalue = 0;
1008 char convert[64];
1009 int vallen = 0;
1010 int padlen; /* amount to pad */
1011 int zeropad; /* extra leading zeroes */
1012
1013 switch (type)
1014 {
1015 case 'd':
1016 case 'i':
1017 base = 10;
1018 dosign = 1;
1019 break;
1020 case 'o':
1021 base = 8;
1022 dosign = 0;
1023 break;
1024 case 'u':
1025 base = 10;
1026 dosign = 0;
1027 break;
1028 case 'x':
1029 base = 16;
1030 dosign = 0;
1031 break;
1032 case 'X':
1033 cvt = "0123456789ABCDEF";
1034 base = 16;
1035 dosign = 0;
1036 break;
1037 default:
1038 return; /* keep compiler quiet */
1039 }
1040
1041 /* disable MSVC warning about applying unary minus to an unsigned value */
1042#ifdef _MSC_VER
1043#pragma warning(push)
1044#pragma warning(disable: 4146)
1045#endif
1046 /* Handle +/- */
1047 if (dosign && adjust_sign((value < 0), forcesign, &signvalue))
1048 uvalue = -(unsigned long long) value;
1049 else
1050 uvalue = (unsigned long long) value;
1051#ifdef _MSC_VER
1052#pragma warning(pop)
1053#endif
1054
1055 /*
1056 * SUS: the result of converting 0 with an explicit precision of 0 is no
1057 * characters
1058 */
1059 if (value == 0 && pointflag && precision == 0)
1060 vallen = 0;
1061 else
1062 {
1063 /*
1064 * Convert integer to string. We special-case each of the possible
1065 * base values so as to avoid general-purpose divisions. On most
1066 * machines, division by a fixed constant can be done much more
1067 * cheaply than a general divide.
1068 */
1069 if (base == 10)
1070 {
1071 do
1072 {
1073 convert[sizeof(convert) - (++vallen)] = cvt[uvalue % 10];
1074 uvalue = uvalue / 10;
1075 } while (uvalue);
1076 }
1077 else if (base == 16)
1078 {
1079 do
1080 {
1081 convert[sizeof(convert) - (++vallen)] = cvt[uvalue % 16];
1082 uvalue = uvalue / 16;
1083 } while (uvalue);
1084 }
1085 else /* base == 8 */
1086 {
1087 do
1088 {
1089 convert[sizeof(convert) - (++vallen)] = cvt[uvalue % 8];
1090 uvalue = uvalue / 8;
1091 } while (uvalue);
1092 }
1093 }
1094
1095 zeropad = Max(0, precision - vallen);
1096
1097 padlen = compute_padlen(minlen, vallen + zeropad, leftjust);
1098
1099 leading_pad(zpad, signvalue, &padlen, target);
1100
1101 if (zeropad > 0)
1102 dopr_outchmulti('0', zeropad, target);
1103
1104 dostr(convert + sizeof(convert) - vallen, vallen, target);
1105
1106 trailing_pad(padlen, target);
1107}
1108
1109static void
1110fmtchar(int value, int leftjust, int minlen, PrintfTarget *target)
1111{
1112 int padlen; /* amount to pad */
1113
1114 padlen = compute_padlen(minlen, 1, leftjust);
1115
1116 if (padlen > 0)
1117 {
1118 dopr_outchmulti(' ', padlen, target);
1119 padlen = 0;
1120 }
1121
1122 dopr_outch(value, target);
1123
1124 trailing_pad(padlen, target);
1125}
1126
1127static void
1128fmtfloat(double value, char type, int forcesign, int leftjust,
1129 int minlen, int zpad, int precision, int pointflag,
1130 PrintfTarget *target)
1131{
1132 int signvalue = 0;
1133 int prec;
1134 int vallen;
1135 char fmt[8];
1136 char convert[1024];
1137 int zeropadlen = 0; /* amount to pad with zeroes */
1138 int padlen; /* amount to pad with spaces */
1139
1140 /*
1141 * We rely on the regular C library's snprintf to do the basic conversion,
1142 * then handle padding considerations here.
1143 *
1144 * The dynamic range of "double" is about 1E+-308 for IEEE math, and not
1145 * too wildly more than that with other hardware. In "f" format, snprintf
1146 * could therefore generate at most 308 characters to the left of the
1147 * decimal point; while we need to allow the precision to get as high as
1148 * 308+17 to ensure that we don't truncate significant digits from very
1149 * small values. To handle both these extremes, we use a buffer of 1024
1150 * bytes and limit requested precision to 350 digits; this should prevent
1151 * buffer overrun even with non-IEEE math. If the original precision
1152 * request was more than 350, separately pad with zeroes.
1153 *
1154 * We handle infinities and NaNs specially to ensure platform-independent
1155 * output.
1156 */
1157 if (precision < 0) /* cover possible overflow of "accum" */
1158 precision = 0;
1159 prec = Min(precision, 350);
1160
1161 if (isnan(value))
1162 {
1163 strcpy(convert, "NaN");
1164 vallen = 3;
1165 /* no zero padding, regardless of precision spec */
1166 }
1167 else
1168 {
1169 /*
1170 * Handle sign (NaNs have no sign, so we don't do this in the case
1171 * above). "value < 0.0" will not be true for IEEE minus zero, so we
1172 * detect that by looking for the case where value equals 0.0
1173 * according to == but not according to memcmp.
1174 */
1175 static const double dzero = 0.0;
1176
1177 if (adjust_sign((value < 0.0 ||
1178 (value == 0.0 &&
1179 memcmp(&value, &dzero, sizeof(double)) != 0)),
1180 forcesign, &signvalue))
1181 value = -value;
1182
1183 if (isinf(value))
1184 {
1185 strcpy(convert, "Infinity");
1186 vallen = 8;
1187 /* no zero padding, regardless of precision spec */
1188 }
1189 else if (pointflag)
1190 {
1191 zeropadlen = precision - prec;
1192 fmt[0] = '%';
1193 fmt[1] = '.';
1194 fmt[2] = '*';
1195 fmt[3] = type;
1196 fmt[4] = '\0';
1197 vallen = snprintf(convert, sizeof(convert), fmt, prec, value);
1198 }
1199 else
1200 {
1201 fmt[0] = '%';
1202 fmt[1] = type;
1203 fmt[2] = '\0';
1204 vallen = snprintf(convert, sizeof(convert), fmt, value);
1205 }
1206 if (vallen < 0)
1207 goto fail;
1208 }
1209
1210 padlen = compute_padlen(minlen, vallen + zeropadlen, leftjust);
1211
1212 leading_pad(zpad, signvalue, &padlen, target);
1213
1214 if (zeropadlen > 0)
1215 {
1216 /* If 'e' or 'E' format, inject zeroes before the exponent */
1217 char *epos = strrchr(convert, 'e');
1218
1219 if (!epos)
1220 epos = strrchr(convert, 'E');
1221 if (epos)
1222 {
1223 /* pad before exponent */
1224 dostr(convert, epos - convert, target);
1225 dopr_outchmulti('0', zeropadlen, target);
1226 dostr(epos, vallen - (epos - convert), target);
1227 }
1228 else
1229 {
1230 /* no exponent, pad after the digits */
1231 dostr(convert, vallen, target);
1232 dopr_outchmulti('0', zeropadlen, target);
1233 }
1234 }
1235 else
1236 {
1237 /* no zero padding, just emit the number as-is */
1238 dostr(convert, vallen, target);
1239 }
1240
1241 trailing_pad(padlen, target);
1242 return;
1243
1244fail:
1245 target->failed = true;
1246}
1247
1248/*
1249 * Nonstandard entry point to print a double value efficiently.
1250 *
1251 * This is approximately equivalent to strfromd(), but has an API more
1252 * adapted to what float8out() wants. The behavior is like snprintf()
1253 * with a format of "%.ng", where n is the specified precision.
1254 * However, the target buffer must be nonempty (i.e. count > 0), and
1255 * the precision is silently bounded to a sane range.
1256 */
1257int
1258pg_strfromd(char *str, size_t count, int precision, double value)
1259{
1260 PrintfTarget target;
1261 int signvalue = 0;
1262 int vallen;
1263 char fmt[8];
1264 char convert[64];
1265
1266 /* Set up the target like pg_snprintf, but require nonempty buffer */
1267 Assert(count > 0);
1268 target.bufstart = target.bufptr = str;
1269 target.bufend = str + count - 1;
1270 target.stream = NULL;
1271 target.nchars = 0;
1272 target.failed = false;
1273
1274 /*
1275 * We bound precision to a reasonable range; the combination of this and
1276 * the knowledge that we're using "g" format without padding allows the
1277 * convert[] buffer to be reasonably small.
1278 */
1279 if (precision < 1)
1280 precision = 1;
1281 else if (precision > 32)
1282 precision = 32;
1283
1284 /*
1285 * The rest is just an inlined version of the fmtfloat() logic above,
1286 * simplified using the knowledge that no padding is wanted.
1287 */
1288 if (isnan(value))
1289 {
1290 strcpy(convert, "NaN");
1291 vallen = 3;
1292 }
1293 else
1294 {
1295 static const double dzero = 0.0;
1296
1297 if (value < 0.0 ||
1298 (value == 0.0 &&
1299 memcmp(&value, &dzero, sizeof(double)) != 0))
1300 {
1301 signvalue = '-';
1302 value = -value;
1303 }
1304
1305 if (isinf(value))
1306 {
1307 strcpy(convert, "Infinity");
1308 vallen = 8;
1309 }
1310 else
1311 {
1312 fmt[0] = '%';
1313 fmt[1] = '.';
1314 fmt[2] = '*';
1315 fmt[3] = 'g';
1316 fmt[4] = '\0';
1317 vallen = snprintf(convert, sizeof(convert), fmt, precision, value);
1318 if (vallen < 0)
1319 {
1320 target.failed = true;
1321 goto fail;
1322 }
1323 }
1324 }
1325
1326 if (signvalue)
1327 dopr_outch(signvalue, &target);
1328
1329 dostr(convert, vallen, &target);
1330
1331fail:
1332 *(target.bufptr) = '\0';
1333 return target.failed ? -1 : (target.bufptr - target.bufstart
1334 + target.nchars);
1335}
1336
1337
1338static void
1339dostr(const char *str, int slen, PrintfTarget *target)
1340{
1341 /* fast path for common case of slen == 1 */
1342 if (slen == 1)
1343 {
1344 dopr_outch(*str, target);
1345 return;
1346 }
1347
1348 while (slen > 0)
1349 {
1350 int avail;
1351
1352 if (target->bufend != NULL)
1353 avail = target->bufend - target->bufptr;
1354 else
1355 avail = slen;
1356 if (avail <= 0)
1357 {
1358 /* buffer full, can we dump to stream? */
1359 if (target->stream == NULL)
1360 {
1361 target->nchars += slen; /* no, lose the data */
1362 return;
1363 }
1364 flushbuffer(target);
1365 continue;
1366 }
1367 avail = Min(avail, slen);
1368 memmove(target->bufptr, str, avail);
1369 target->bufptr += avail;
1370 str += avail;
1371 slen -= avail;
1372 }
1373}
1374
1375static void
1377{
1378 if (target->bufend != NULL && target->bufptr >= target->bufend)
1379 {
1380 /* buffer full, can we dump to stream? */
1381 if (target->stream == NULL)
1382 {
1383 target->nchars++; /* no, lose the data */
1384 return;
1385 }
1386 flushbuffer(target);
1387 }
1388 *(target->bufptr++) = c;
1389}
1390
1391static void
1392dopr_outchmulti(int c, int slen, PrintfTarget *target)
1393{
1394 /* fast path for common case of slen == 1 */
1395 if (slen == 1)
1396 {
1397 dopr_outch(c, target);
1398 return;
1399 }
1400
1401 while (slen > 0)
1402 {
1403 int avail;
1404
1405 if (target->bufend != NULL)
1406 avail = target->bufend - target->bufptr;
1407 else
1408 avail = slen;
1409 if (avail <= 0)
1410 {
1411 /* buffer full, can we dump to stream? */
1412 if (target->stream == NULL)
1413 {
1414 target->nchars += slen; /* no, lose the data */
1415 return;
1416 }
1417 flushbuffer(target);
1418 continue;
1419 }
1420 avail = Min(avail, slen);
1421 memset(target->bufptr, c, avail);
1422 target->bufptr += avail;
1423 slen -= avail;
1424 }
1425}
1426
1427
1428static int
1429adjust_sign(int is_negative, int forcesign, int *signvalue)
1430{
1431 if (is_negative)
1432 {
1433 *signvalue = '-';
1434 return true;
1435 }
1436 else if (forcesign)
1437 *signvalue = '+';
1438 return false;
1439}
1440
1441
1442static int
1443compute_padlen(int minlen, int vallen, int leftjust)
1444{
1445 int padlen;
1446
1447 padlen = minlen - vallen;
1448 if (padlen < 0)
1449 padlen = 0;
1450 if (leftjust)
1451 padlen = -padlen;
1452 return padlen;
1453}
1454
1455
1456static void
1457leading_pad(int zpad, int signvalue, int *padlen, PrintfTarget *target)
1458{
1459 int maxpad;
1460
1461 if (*padlen > 0 && zpad)
1462 {
1463 if (signvalue)
1464 {
1465 dopr_outch(signvalue, target);
1466 --(*padlen);
1467 signvalue = 0;
1468 }
1469 if (*padlen > 0)
1470 {
1471 dopr_outchmulti(zpad, *padlen, target);
1472 *padlen = 0;
1473 }
1474 }
1475 maxpad = (signvalue != 0);
1476 if (*padlen > maxpad)
1477 {
1478 dopr_outchmulti(' ', *padlen - maxpad, target);
1479 *padlen = maxpad;
1480 }
1481 if (signvalue)
1482 {
1483 dopr_outch(signvalue, target);
1484 if (*padlen > 0)
1485 --(*padlen);
1486 else if (*padlen < 0)
1487 ++(*padlen);
1488 }
1489}
1490
1491
1492static void
1493trailing_pad(int padlen, PrintfTarget *target)
1494{
1495 if (padlen < 0)
1496 dopr_outchmulti(' ', -padlen, target);
1497}
#define Min(x, y)
Definition: c.h:1008
#define Max(x, y)
Definition: c.h:1002
Assert(PointerIsAligned(start, uint64))
const char * str
static struct @171 value
int i
Definition: isn.c:77
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:1339
static void dopr_outch(int c, PrintfTarget *target)
Definition: snprintf.c:1376
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:999
static void leading_pad(int zpad, int signvalue, int *padlen, PrintfTarget *target)
Definition: snprintf.c:1457
int pg_strfromd(char *str, size_t count, int precision, double value)
Definition: snprintf.c:1258
static void fmtptr(const void *value, PrintfTarget *target)
Definition: snprintf.c:985
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:1110
static void fmtstr(const char *value, int leftjust, int minlen, int maxwidth, int pointflag, PrintfTarget *target)
Definition: snprintf.c:956
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
#define strchrnul
Definition: snprintf.c:356
static int compute_padlen(int minlen, int vallen, int leftjust)
Definition: snprintf.c:1443
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:1493
static void fmtfloat(double value, char type, int forcesign, int leftjust, int minlen, int zpad, int precision, int pointflag, PrintfTarget *target)
Definition: snprintf.c:1128
int pg_sprintf(char *str, const char *fmt,...)
Definition: snprintf.c:230
static bool find_arguments(const char *format, va_list args, PrintfArgValue *argvalues)
Definition: snprintf.c:742
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:373
static void dopr_outchmulti(int c, int slen, PrintfTarget *target)
Definition: snprintf.c:1392
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:1429
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