LCOV - code coverage report
Current view: top level - src/port - snprintf.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 418 613 68.2 %
Date: 2025-12-07 18:17:27 Functions: 22 24 91.7 %
Legend: Lines: hit not hit

          Line data    Source code
       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             :  */
     125             : typedef 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 */
     134             : } PrintfTarget;
     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             :  */
     142             : typedef enum
     143             : {
     144             :     ATYPE_NONE = 0,
     145             :     ATYPE_INT,
     146             :     ATYPE_LONG,
     147             :     ATYPE_LONGLONG,
     148             :     ATYPE_DOUBLE,
     149             :     ATYPE_CHARPTR
     150             : } PrintfArgType;
     151             : 
     152             : typedef union
     153             : {
     154             :     int         i;
     155             :     long        l;
     156             :     long long   ll;
     157             :     double      d;
     158             :     char       *cptr;
     159             : } PrintfArgValue;
     160             : 
     161             : 
     162             : static void flushbuffer(PrintfTarget *target);
     163             : static 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             : 
     173             : int
     174    82090104 : pg_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    82090104 :     if (count == 0)
     186             :     {
     187      253790 :         str = onebyte;
     188      253790 :         count = 1;
     189             :     }
     190    82090104 :     target.bufstart = target.bufptr = str;
     191    82090104 :     target.bufend = str + count - 1;
     192    82090104 :     target.stream = NULL;
     193    82090104 :     target.nchars = 0;
     194    82090104 :     target.failed = false;
     195    82090104 :     dopr(&target, fmt, args);
     196    82090106 :     *(target.bufptr) = '\0';
     197   164180212 :     return target.failed ? -1 : (target.bufptr - target.bufstart
     198    82090106 :                                  + target.nchars);
     199             : }
     200             : 
     201             : int
     202    44918262 : pg_snprintf(char *str, size_t count, const char *fmt,...)
     203             : {
     204             :     int         len;
     205             :     va_list     args;
     206             : 
     207    44918262 :     va_start(args, fmt);
     208    44918262 :     len = pg_vsnprintf(str, count, fmt, args);
     209    44918264 :     va_end(args);
     210    44918264 :     return len;
     211             : }
     212             : 
     213             : int
     214    18744854 : pg_vsprintf(char *str, const char *fmt, va_list args)
     215             : {
     216             :     PrintfTarget target;
     217             : 
     218    18744854 :     target.bufstart = target.bufptr = str;
     219    18744854 :     target.bufend = NULL;
     220    18744854 :     target.stream = NULL;
     221    18744854 :     target.nchars = 0;          /* not really used in this case */
     222    18744854 :     target.failed = false;
     223    18744854 :     dopr(&target, fmt, args);
     224    18744844 :     *(target.bufptr) = '\0';
     225    37489688 :     return target.failed ? -1 : (target.bufptr - target.bufstart
     226    18744844 :                                  + target.nchars);
     227             : }
     228             : 
     229             : int
     230    18744850 : pg_sprintf(char *str, const char *fmt,...)
     231             : {
     232             :     int         len;
     233             :     va_list     args;
     234             : 
     235    18744850 :     va_start(args, fmt);
     236    18744850 :     len = pg_vsprintf(str, fmt, args);
     237    18744844 :     va_end(args);
     238    18744844 :     return len;
     239             : }
     240             : 
     241             : int
     242     4632576 : pg_vfprintf(FILE *stream, const char *fmt, va_list args)
     243             : {
     244             :     PrintfTarget target;
     245             :     char        buffer[1024];   /* size is arbitrary */
     246             : 
     247     4632576 :     if (stream == NULL)
     248             :     {
     249           0 :         errno = EINVAL;
     250           0 :         return -1;
     251             :     }
     252     4632576 :     target.bufstart = target.bufptr = buffer;
     253     4632576 :     target.bufend = buffer + sizeof(buffer);    /* use the whole buffer */
     254     4632576 :     target.stream = stream;
     255     4632576 :     target.nchars = 0;
     256     4632576 :     target.failed = false;
     257     4632576 :     dopr(&target, fmt, args);
     258             :     /* dump any remaining buffer contents */
     259     4632576 :     flushbuffer(&target);
     260     4632576 :     return target.failed ? -1 : target.nchars;
     261             : }
     262             : 
     263             : int
     264     2384566 : pg_fprintf(FILE *stream, const char *fmt,...)
     265             : {
     266             :     int         len;
     267             :     va_list     args;
     268             : 
     269     2384566 :     va_start(args, fmt);
     270     2384566 :     len = pg_vfprintf(stream, fmt, args);
     271     2384566 :     va_end(args);
     272     2384566 :     return len;
     273             : }
     274             : 
     275             : int
     276           0 : pg_vprintf(const char *fmt, va_list args)
     277             : {
     278           0 :     return pg_vfprintf(stdout, fmt, args);
     279             : }
     280             : 
     281             : int
     282     2224744 : pg_printf(const char *fmt,...)
     283             : {
     284             :     int         len;
     285             :     va_list     args;
     286             : 
     287     2224744 :     va_start(args, fmt);
     288     2224744 :     len = pg_vfprintf(stdout, fmt, args);
     289     2224744 :     va_end(args);
     290     2224744 :     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             :  */
     297             : static void
     298     4633180 : flushbuffer(PrintfTarget *target)
     299             : {
     300     4633180 :     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     4633180 :     if (!target->failed && nc > 0)
     307             :     {
     308             :         size_t      written;
     309             : 
     310     4366958 :         written = fwrite(target->bufstart, 1, nc, target->stream);
     311     4366958 :         target->nchars += written;
     312     4366958 :         if (written != nc)
     313           0 :             target->failed = true;
     314             :     }
     315     4633180 :     target->bufptr = target->bufstart;
     316     4633180 : }
     317             : 
     318             : 
     319             : static bool find_arguments(const char *format, va_list args,
     320             :                            PrintfArgValue *argvalues);
     321             : static void fmtstr(const char *value, int leftjust, int minlen, int maxwidth,
     322             :                    int pointflag, PrintfTarget *target);
     323             : static void fmtptr(const void *value, PrintfTarget *target);
     324             : static void fmtint(long long value, char type, int forcesign,
     325             :                    int leftjust, int minlen, int zpad, int precision, int pointflag,
     326             :                    PrintfTarget *target);
     327             : static void fmtchar(int value, int leftjust, int minlen, PrintfTarget *target);
     328             : static void fmtfloat(double value, char type, int forcesign,
     329             :                      int leftjust, int minlen, int zpad, int precision, int pointflag,
     330             :                      PrintfTarget *target);
     331             : static void dostr(const char *str, int slen, PrintfTarget *target);
     332             : static void dopr_outch(int c, PrintfTarget *target);
     333             : static void dopr_outchmulti(int c, int slen, PrintfTarget *target);
     334             : static int  adjust_sign(int is_negative, int forcesign, int *signvalue);
     335             : static int  compute_padlen(int minlen, int vallen, int leftjust);
     336             : static void leading_pad(int zpad, int signvalue, int *padlen,
     337             :                         PrintfTarget *target);
     338             : static 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             : 
     358             : static inline const char *
     359             : strchrnul(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             :  */
     372             : static void
     373   105467530 : dopr(PrintfTarget *target, const char *format, va_list args)
     374             : {
     375   105467530 :     int         save_errno = errno;
     376   105467530 :     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   105467530 :     have_dollar = false;
     404             : 
     405   253019652 :     while (*format != '\0')
     406             :     {
     407             :         /* Locate next conversion specifier */
     408   162297328 :         if (*format != '%')
     409             :         {
     410             :             /* Scan to next '%' or end of string */
     411    92095920 :             const char *next_pct = strchrnul(format + 1, '%');
     412             : 
     413             :             /* Dump literal data we just scanned over */
     414    92095920 :             dostr(format, next_pct - format, target);
     415    92095920 :             if (target->failed)
     416           0 :                 break;
     417             : 
     418    92095920 :             if (*next_pct == '\0')
     419    14745196 :                 break;
     420    77350724 :             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   147552132 :         if (first_pct == NULL)
     429   104193060 :             first_pct = format;
     430             : 
     431             :         /* Process conversion spec starting at *format */
     432   147552132 :         format++;
     433             : 
     434             :         /* Fast path for conversion spec that is exactly %s */
     435   147552132 :         if (*format == 's')
     436             :         {
     437    42599540 :             format++;
     438    42599540 :             strvalue = va_arg(args, char *);
     439    42599540 :             if (strvalue == NULL)
     440           8 :                 strvalue = "(null)";
     441    42599540 :             dostr(strvalue, strlen(strvalue), target);
     442    42599540 :             if (target->failed)
     443           0 :                 break;
     444    42599540 :             continue;
     445             :         }
     446             : 
     447   104952592 :         fieldwidth = precision = zpad = leftjust = forcesign = 0;
     448   104952592 :         longflag = longlongflag = pointflag = 0;
     449   104952592 :         fmtpos = accum = 0;
     450   104952592 :         have_star = afterstar = false;
     451    78235342 : nextch2:
     452   183187934 :         ch = *format++;
     453   183187934 :         switch (ch)
     454             :         {
     455     1102196 :             case '-':
     456     1102196 :                 leftjust = 1;
     457     1102196 :                 goto nextch2;
     458         282 :             case '+':
     459         282 :                 forcesign = 1;
     460         282 :                 goto nextch2;
     461    31815456 :             case '0':
     462             :                 /* set zero padding if no nonzero digits yet */
     463    31815456 :                 if (accum == 0 && !pointflag)
     464    31247376 :                     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    66639342 :                 accum = accum * 10 + (ch - '0');
     476    66639342 :                 goto nextch2;
     477      992370 :             case '.':
     478      992370 :                 if (have_star)
     479         968 :                     have_star = false;
     480             :                 else
     481      991402 :                     fieldwidth = accum;
     482      992370 :                 pointflag = 1;
     483      992370 :                 accum = 0;
     484      992370 :                 goto nextch2;
     485     1460682 :             case '*':
     486     1460682 :                 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           0 :                     afterstar = true;
     494             :                 }
     495             :                 else
     496             :                 {
     497             :                     /* fetch and process value now */
     498     1460682 :                     int         starval = va_arg(args, int);
     499             : 
     500     1460682 :                     if (pointflag)
     501             :                     {
     502       61162 :                         precision = starval;
     503       61162 :                         if (precision < 0)
     504             :                         {
     505           0 :                             precision = 0;
     506           0 :                             pointflag = 0;
     507             :                         }
     508             :                     }
     509             :                     else
     510             :                     {
     511     1399520 :                         fieldwidth = starval;
     512     1399520 :                         if (fieldwidth < 0)
     513             :                         {
     514        5646 :                             leftjust = 1;
     515        5646 :                             fieldwidth = -fieldwidth;
     516             :                         }
     517             :                     }
     518             :                 }
     519     1460682 :                 have_star = true;
     520     1460682 :                 accum = 0;
     521     1460682 :                 goto nextch2;
     522           0 :             case '$':
     523             :                 /* First dollar sign? */
     524           0 :                 if (!have_dollar)
     525             :                 {
     526             :                     /* Yup, so examine all conversion specs in format */
     527           0 :                     if (!find_arguments(first_pct, args, argvalues))
     528           4 :                         goto bad_format;
     529           0 :                     have_dollar = true;
     530             :                 }
     531           0 :                 if (afterstar)
     532             :                 {
     533             :                     /* fetch and process star value */
     534           0 :                     int         starval = argvalues[accum].i;
     535             : 
     536           0 :                     if (pointflag)
     537             :                     {
     538           0 :                         precision = starval;
     539           0 :                         if (precision < 0)
     540             :                         {
     541           0 :                             precision = 0;
     542           0 :                             pointflag = 0;
     543             :                         }
     544             :                     }
     545             :                     else
     546             :                     {
     547           0 :                         fieldwidth = starval;
     548           0 :                         if (fieldwidth < 0)
     549             :                         {
     550           0 :                             leftjust = 1;
     551           0 :                             fieldwidth = -fieldwidth;
     552             :                         }
     553             :                     }
     554           0 :                     afterstar = false;
     555             :                 }
     556             :                 else
     557           0 :                     fmtpos = accum;
     558           0 :                 accum = 0;
     559           0 :                 goto nextch2;
     560     7692868 :             case 'l':
     561     7692868 :                 if (longflag)
     562        8832 :                     longlongflag = 1;
     563             :                 else
     564     7684036 :                     longflag = 1;
     565     7692868 :                 goto nextch2;
     566      347518 :             case 'z':
     567             : #if SIZEOF_SIZE_T == SIZEOF_LONG
     568      347518 :                 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      347518 :                 goto nextch2;
     575          88 :             case 'h':
     576             :             case '\'':
     577             :                 /* ignore these */
     578          88 :                 goto nextch2;
     579    41390626 :             case 'd':
     580             :             case 'i':
     581    41390626 :                 if (!have_star)
     582             :                 {
     583    41349514 :                     if (pointflag)
     584           0 :                         precision = accum;
     585             :                     else
     586    41349514 :                         fieldwidth = accum;
     587             :                 }
     588    41390626 :                 if (have_dollar)
     589             :                 {
     590           0 :                     if (longlongflag)
     591           0 :                         numvalue = argvalues[fmtpos].ll;
     592           0 :                     else if (longflag)
     593           0 :                         numvalue = argvalues[fmtpos].l;
     594             :                     else
     595           0 :                         numvalue = argvalues[fmtpos].i;
     596             :                 }
     597             :                 else
     598             :                 {
     599    41390626 :                     if (longlongflag)
     600        8796 :                         numvalue = va_arg(args, long long);
     601    41381830 :                     else if (longflag)
     602     6644438 :                         numvalue = va_arg(args, long);
     603             :                     else
     604    34737392 :                         numvalue = va_arg(args, int);
     605             :                 }
     606    41390626 :                 fmtint(numvalue, ch, forcesign, leftjust, fieldwidth, zpad,
     607             :                        precision, pointflag, target);
     608    41390622 :                 break;
     609    59628754 :             case 'o':
     610             :             case 'u':
     611             :             case 'x':
     612             :             case 'X':
     613    59628754 :                 if (!have_star)
     614             :                 {
     615    59628754 :                     if (pointflag)
     616           0 :                         precision = accum;
     617             :                     else
     618    59628754 :                         fieldwidth = accum;
     619             :                 }
     620    59628754 :                 if (have_dollar)
     621             :                 {
     622           0 :                     if (longlongflag)
     623           0 :                         numvalue = (unsigned long long) argvalues[fmtpos].ll;
     624           0 :                     else if (longflag)
     625           0 :                         numvalue = (unsigned long) argvalues[fmtpos].l;
     626             :                     else
     627           0 :                         numvalue = (unsigned int) argvalues[fmtpos].i;
     628             :                 }
     629             :                 else
     630             :                 {
     631    59628754 :                     if (longlongflag)
     632          36 :                         numvalue = (unsigned long long) va_arg(args, long long);
     633    59628718 :                     else if (longflag)
     634     1378284 :                         numvalue = (unsigned long) va_arg(args, long);
     635             :                     else
     636    58250434 :                         numvalue = (unsigned int) va_arg(args, int);
     637             :                 }
     638    59628754 :                 fmtint(numvalue, ch, forcesign, leftjust, fieldwidth, zpad,
     639             :                        precision, pointflag, target);
     640    59628754 :                 break;
     641       40554 :             case 'c':
     642       40554 :                 if (!have_star)
     643             :                 {
     644       40512 :                     if (pointflag)
     645           0 :                         precision = accum;
     646             :                     else
     647       40512 :                         fieldwidth = accum;
     648             :                 }
     649       40554 :                 if (have_dollar)
     650           0 :                     cvalue = (unsigned char) argvalues[fmtpos].i;
     651             :                 else
     652       40554 :                     cvalue = (unsigned char) va_arg(args, int);
     653       40554 :                 fmtchar(cvalue, leftjust, fieldwidth, target);
     654       40554 :                 break;
     655     1967230 :             case 's':
     656     1967230 :                 if (!have_star)
     657             :                 {
     658      589058 :                     if (pointflag)
     659           0 :                         precision = accum;
     660             :                     else
     661      589058 :                         fieldwidth = accum;
     662             :                 }
     663     1967230 :                 if (have_dollar)
     664           0 :                     strvalue = argvalues[fmtpos].cptr;
     665             :                 else
     666     1967230 :                     strvalue = va_arg(args, char *);
     667             :                 /* If string is NULL, silently substitute "(null)" */
     668     1967230 :                 if (strvalue == NULL)
     669           0 :                     strvalue = "(null)";
     670     1967230 :                 fmtstr(strvalue, leftjust, fieldwidth, precision, pointflag,
     671             :                        target);
     672     1967230 :                 break;
     673         164 :             case 'p':
     674             :                 /* fieldwidth/leftjust are ignored ... */
     675         164 :                 if (have_dollar)
     676           0 :                     strvalue = argvalues[fmtpos].cptr;
     677             :                 else
     678         164 :                     strvalue = va_arg(args, char *);
     679         164 :                 fmtptr((const void *) strvalue, target);
     680         164 :                 break;
     681     1424234 :             case 'e':
     682             :             case 'E':
     683             :             case 'f':
     684             :             case 'g':
     685             :             case 'G':
     686     1424234 :                 if (!have_star)
     687             :                 {
     688     1383846 :                     if (pointflag)
     689      931208 :                         precision = accum;
     690             :                     else
     691      452638 :                         fieldwidth = accum;
     692             :                 }
     693     1424234 :                 if (have_dollar)
     694           0 :                     fvalue = argvalues[fmtpos].d;
     695             :                 else
     696     1424234 :                     fvalue = va_arg(args, double);
     697     1424234 :                 fmtfloat(fvalue, ch, forcesign, leftjust,
     698             :                          fieldwidth, zpad,
     699             :                          precision, pointflag,
     700             :                          target);
     701     1424234 :                 break;
     702         488 :             case 'm':
     703             :                 {
     704             :                     char        errbuf[PG_STRERROR_R_BUFLEN];
     705         488 :                     const char *errm = strerror_r(save_errno,
     706             :                                                   errbuf, sizeof(errbuf));
     707             : 
     708         488 :                     dostr(errm, strlen(errm), target);
     709             :                 }
     710         486 :                 break;
     711      500538 :             case '%':
     712      500538 :                 dopr_outch('%', target);
     713      500538 :                 break;
     714           0 :             default:
     715             : 
     716             :                 /*
     717             :                  * Anything else --- in particular, '\0' indicating end of
     718             :                  * format string --- is bogus.
     719             :                  */
     720           0 :                 goto bad_format;
     721             :         }
     722             : 
     723             :         /* Check for failure after each conversion spec */
     724   104952582 :         if (target->failed)
     725           0 :             break;
     726             :     }
     727             : 
     728   105467520 :     return;
     729             : 
     730           4 : bad_format:
     731           4 :     errno = EINVAL;
     732           4 :     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             :  */
     741             : static bool
     742           0 : find_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           0 :     int         last_dollar = 0;    /* Init to "no dollar arguments known" */
     753           0 :     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           0 :     while (*format != '\0')
     764             :     {
     765             :         /* Locate next conversion specifier */
     766           0 :         if (*format != '%')
     767             :         {
     768             :             /* Unlike dopr, we can just quit if there's no more specifiers */
     769           0 :             format = strchr(format + 1, '%');
     770           0 :             if (format == NULL)
     771           0 :                 break;
     772             :         }
     773             : 
     774             :         /* Process conversion spec starting at *format */
     775           0 :         format++;
     776           0 :         longflag = longlongflag = 0;
     777           0 :         fmtpos = accum = 0;
     778           0 :         afterstar = false;
     779           0 : nextch1:
     780           0 :         ch = *format++;
     781           0 :         switch (ch)
     782             :         {
     783           0 :             case '-':
     784             :             case '+':
     785           0 :                 goto nextch1;
     786           0 :             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           0 :                 accum = accum * 10 + (ch - '0');
     797           0 :                 goto nextch1;
     798           0 :             case '.':
     799           0 :                 accum = 0;
     800           0 :                 goto nextch1;
     801           0 :             case '*':
     802           0 :                 if (afterstar)
     803           0 :                     return false;   /* previous star missing dollar */
     804           0 :                 afterstar = true;
     805           0 :                 accum = 0;
     806           0 :                 goto nextch1;
     807           0 :             case '$':
     808           0 :                 if (accum <= 0 || accum > PG_NL_ARGMAX)
     809           0 :                     return false;
     810           0 :                 if (afterstar)
     811             :                 {
     812           0 :                     if (argtypes[accum] &&
     813           0 :                         argtypes[accum] != ATYPE_INT)
     814           0 :                         return false;
     815           0 :                     argtypes[accum] = ATYPE_INT;
     816           0 :                     last_dollar = Max(last_dollar, accum);
     817           0 :                     afterstar = false;
     818             :                 }
     819             :                 else
     820           0 :                     fmtpos = accum;
     821           0 :                 accum = 0;
     822           0 :                 goto nextch1;
     823           0 :             case 'l':
     824           0 :                 if (longflag)
     825           0 :                     longlongflag = 1;
     826             :                 else
     827           0 :                     longflag = 1;
     828           0 :                 goto nextch1;
     829           0 :             case 'z':
     830             : #if SIZEOF_SIZE_T == SIZEOF_LONG
     831           0 :                 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           0 :                 goto nextch1;
     838           0 :             case 'h':
     839             :             case '\'':
     840             :                 /* ignore these */
     841           0 :                 goto nextch1;
     842           0 :             case 'd':
     843             :             case 'i':
     844             :             case 'o':
     845             :             case 'u':
     846             :             case 'x':
     847             :             case 'X':
     848           0 :                 if (fmtpos)
     849             :                 {
     850             :                     PrintfArgType atype;
     851             : 
     852           0 :                     if (longlongflag)
     853           0 :                         atype = ATYPE_LONGLONG;
     854           0 :                     else if (longflag)
     855           0 :                         atype = ATYPE_LONG;
     856             :                     else
     857           0 :                         atype = ATYPE_INT;
     858           0 :                     if (argtypes[fmtpos] &&
     859           0 :                         argtypes[fmtpos] != atype)
     860           0 :                         return false;
     861           0 :                     argtypes[fmtpos] = atype;
     862           0 :                     last_dollar = Max(last_dollar, fmtpos);
     863             :                 }
     864             :                 else
     865           0 :                     return false;   /* non-dollar conversion spec */
     866           0 :                 break;
     867           0 :             case 'c':
     868           0 :                 if (fmtpos)
     869             :                 {
     870           0 :                     if (argtypes[fmtpos] &&
     871           0 :                         argtypes[fmtpos] != ATYPE_INT)
     872           0 :                         return false;
     873           0 :                     argtypes[fmtpos] = ATYPE_INT;
     874           0 :                     last_dollar = Max(last_dollar, fmtpos);
     875             :                 }
     876             :                 else
     877           0 :                     return false;   /* non-dollar conversion spec */
     878           0 :                 break;
     879           0 :             case 's':
     880             :             case 'p':
     881           0 :                 if (fmtpos)
     882             :                 {
     883           0 :                     if (argtypes[fmtpos] &&
     884           0 :                         argtypes[fmtpos] != ATYPE_CHARPTR)
     885           0 :                         return false;
     886           0 :                     argtypes[fmtpos] = ATYPE_CHARPTR;
     887           0 :                     last_dollar = Max(last_dollar, fmtpos);
     888             :                 }
     889             :                 else
     890           0 :                     return false;   /* non-dollar conversion spec */
     891           0 :                 break;
     892           0 :             case 'e':
     893             :             case 'E':
     894             :             case 'f':
     895             :             case 'g':
     896             :             case 'G':
     897           0 :                 if (fmtpos)
     898             :                 {
     899           0 :                     if (argtypes[fmtpos] &&
     900           0 :                         argtypes[fmtpos] != ATYPE_DOUBLE)
     901           0 :                         return false;
     902           0 :                     argtypes[fmtpos] = ATYPE_DOUBLE;
     903           0 :                     last_dollar = Max(last_dollar, fmtpos);
     904             :                 }
     905             :                 else
     906           0 :                     return false;   /* non-dollar conversion spec */
     907           0 :                 break;
     908           0 :             case 'm':
     909             :             case '%':
     910           0 :                 break;
     911           0 :             default:
     912           0 :                 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           0 :         if (afterstar)
     920           0 :             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           0 :     for (i = 1; i <= last_dollar; i++)
     929             :     {
     930           0 :         switch (argtypes[i])
     931             :         {
     932           0 :             case ATYPE_NONE:
     933           0 :                 return false;
     934           0 :             case ATYPE_INT:
     935           0 :                 argvalues[i].i = va_arg(args, int);
     936           0 :                 break;
     937           0 :             case ATYPE_LONG:
     938           0 :                 argvalues[i].l = va_arg(args, long);
     939           0 :                 break;
     940           0 :             case ATYPE_LONGLONG:
     941           0 :                 argvalues[i].ll = va_arg(args, long long);
     942           0 :                 break;
     943           0 :             case ATYPE_DOUBLE:
     944           0 :                 argvalues[i].d = va_arg(args, double);
     945           0 :                 break;
     946           0 :             case ATYPE_CHARPTR:
     947           0 :                 argvalues[i].cptr = va_arg(args, char *);
     948           0 :                 break;
     949             :         }
     950             :     }
     951             : 
     952           0 :     return true;
     953             : }
     954             : 
     955             : static void
     956     1967230 : fmtstr(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     1967230 :     if (pointflag)
     967       20774 :         vallen = strnlen(value, maxwidth);
     968             :     else
     969     1946456 :         vallen = strlen(value);
     970             : 
     971     1967230 :     padlen = compute_padlen(minlen, vallen, leftjust);
     972             : 
     973     1967230 :     if (padlen > 0)
     974             :     {
     975      591278 :         dopr_outchmulti(' ', padlen, target);
     976      591278 :         padlen = 0;
     977             :     }
     978             : 
     979     1967230 :     dostr(value, vallen, target);
     980             : 
     981     1967230 :     trailing_pad(padlen, target);
     982     1967230 : }
     983             : 
     984             : static void
     985         164 : fmtptr(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         164 :     vallen = snprintf(convert, sizeof(convert), "%p", value);
     992         164 :     if (vallen < 0)
     993           0 :         target->failed = true;
     994             :     else
     995         164 :         dostr(convert, vallen, target);
     996         164 : }
     997             : 
     998             : static void
     999   101019378 : fmtint(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   101019378 :     const char *cvt = "0123456789abcdef";
    1007   101019378 :     int         signvalue = 0;
    1008             :     char        convert[64];
    1009   101019378 :     int         vallen = 0;
    1010             :     int         padlen;         /* amount to pad */
    1011             :     int         zeropad;        /* extra leading zeroes */
    1012             : 
    1013   101019378 :     switch (type)
    1014             :     {
    1015    41390624 :         case 'd':
    1016             :         case 'i':
    1017    41390624 :             base = 10;
    1018    41390624 :             dosign = 1;
    1019    41390624 :             break;
    1020       11184 :         case 'o':
    1021       11184 :             base = 8;
    1022       11184 :             dosign = 0;
    1023       11184 :             break;
    1024    41365158 :         case 'u':
    1025    41365158 :             base = 10;
    1026    41365158 :             dosign = 0;
    1027    41365158 :             break;
    1028       69382 :         case 'x':
    1029       69382 :             base = 16;
    1030       69382 :             dosign = 0;
    1031       69382 :             break;
    1032    18183030 :         case 'X':
    1033    18183030 :             cvt = "0123456789ABCDEF";
    1034    18183030 :             base = 16;
    1035    18183030 :             dosign = 0;
    1036    18183030 :             break;
    1037           0 :         default:
    1038           0 :             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   101019378 :     if (dosign && adjust_sign((value < 0), forcesign, &signvalue))
    1048     3510878 :         uvalue = -(unsigned long long) value;
    1049             :     else
    1050    97508498 :         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   101019376 :     if (value == 0 && pointflag && precision == 0)
    1060           0 :         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   101019376 :         if (base == 10)
    1070             :         {
    1071             :             do
    1072             :             {
    1073   219284406 :                 convert[sizeof(convert) - (++vallen)] = cvt[uvalue % 10];
    1074   219284406 :                 uvalue = uvalue / 10;
    1075   219284406 :             } while (uvalue);
    1076             :         }
    1077    18263596 :         else if (base == 16)
    1078             :         {
    1079             :             do
    1080             :             {
    1081    69064828 :                 convert[sizeof(convert) - (++vallen)] = cvt[uvalue % 16];
    1082    69064828 :                 uvalue = uvalue / 16;
    1083    69064828 :             } while (uvalue);
    1084             :         }
    1085             :         else                    /* base == 8 */
    1086             :         {
    1087             :             do
    1088             :             {
    1089       33552 :                 convert[sizeof(convert) - (++vallen)] = cvt[uvalue % 8];
    1090       33552 :                 uvalue = uvalue / 8;
    1091       33552 :             } while (uvalue);
    1092             :         }
    1093             :     }
    1094             : 
    1095   101019376 :     zeropad = Max(0, precision - vallen);
    1096             : 
    1097   101019376 :     padlen = compute_padlen(minlen, vallen + zeropad, leftjust);
    1098             : 
    1099   101019376 :     leading_pad(zpad, signvalue, &padlen, target);
    1100             : 
    1101   101019378 :     if (zeropad > 0)
    1102           0 :         dopr_outchmulti('0', zeropad, target);
    1103             : 
    1104   101019378 :     dostr(convert + sizeof(convert) - vallen, vallen, target);
    1105             : 
    1106   101019376 :     trailing_pad(padlen, target);
    1107             : }
    1108             : 
    1109             : static void
    1110       40554 : fmtchar(int value, int leftjust, int minlen, PrintfTarget *target)
    1111             : {
    1112             :     int         padlen;         /* amount to pad */
    1113             : 
    1114       40554 :     padlen = compute_padlen(minlen, 1, leftjust);
    1115             : 
    1116       40554 :     if (padlen > 0)
    1117             :     {
    1118          42 :         dopr_outchmulti(' ', padlen, target);
    1119          42 :         padlen = 0;
    1120             :     }
    1121             : 
    1122       40554 :     dopr_outch(value, target);
    1123             : 
    1124       40554 :     trailing_pad(padlen, target);
    1125       40554 : }
    1126             : 
    1127             : static void
    1128     1424234 : fmtfloat(double value, char type, int forcesign, int leftjust,
    1129             :          int minlen, int zpad, int precision, int pointflag,
    1130             :          PrintfTarget *target)
    1131             : {
    1132     1424234 :     int         signvalue = 0;
    1133             :     int         prec;
    1134             :     int         vallen;
    1135             :     char        fmt[8];
    1136             :     char        convert[1024];
    1137     1424234 :     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     1424234 :     if (precision < 0)           /* cover possible overflow of "accum" */
    1158           0 :         precision = 0;
    1159     1424234 :     prec = Min(precision, 350);
    1160             : 
    1161     1424234 :     if (isnan(value))
    1162             :     {
    1163          54 :         strcpy(convert, "NaN");
    1164          54 :         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     2834056 :         if (adjust_sign((value < 0.0 ||
    1178     1409876 :                          (value == 0.0 &&
    1179      572508 :                           memcmp(&value, &dzero, sizeof(double)) != 0)),
    1180             :                         forcesign, &signvalue))
    1181       14304 :             value = -value;
    1182             : 
    1183     1424180 :         if (isinf(value))
    1184             :         {
    1185         114 :             strcpy(convert, "Infinity");
    1186         114 :             vallen = 8;
    1187             :             /* no zero padding, regardless of precision spec */
    1188             :         }
    1189     1424066 :         else if (pointflag)
    1190             :         {
    1191      971452 :             zeropadlen = precision - prec;
    1192      971452 :             fmt[0] = '%';
    1193      971452 :             fmt[1] = '.';
    1194      971452 :             fmt[2] = '*';
    1195      971452 :             fmt[3] = type;
    1196      971452 :             fmt[4] = '\0';
    1197      971452 :             vallen = snprintf(convert, sizeof(convert), fmt, prec, value);
    1198             :         }
    1199             :         else
    1200             :         {
    1201      452614 :             fmt[0] = '%';
    1202      452614 :             fmt[1] = type;
    1203      452614 :             fmt[2] = '\0';
    1204      452614 :             vallen = snprintf(convert, sizeof(convert), fmt, value);
    1205             :         }
    1206     1424180 :         if (vallen < 0)
    1207           0 :             goto fail;
    1208             :     }
    1209             : 
    1210     1424234 :     padlen = compute_padlen(minlen, vallen + zeropadlen, leftjust);
    1211             : 
    1212     1424234 :     leading_pad(zpad, signvalue, &padlen, target);
    1213             : 
    1214     1424234 :     if (zeropadlen > 0)
    1215             :     {
    1216             :         /* If 'e' or 'E' format, inject zeroes before the exponent */
    1217           0 :         char       *epos = strrchr(convert, 'e');
    1218             : 
    1219           0 :         if (!epos)
    1220           0 :             epos = strrchr(convert, 'E');
    1221           0 :         if (epos)
    1222             :         {
    1223             :             /* pad before exponent */
    1224           0 :             dostr(convert, epos - convert, target);
    1225           0 :             dopr_outchmulti('0', zeropadlen, target);
    1226           0 :             dostr(epos, vallen - (epos - convert), target);
    1227             :         }
    1228             :         else
    1229             :         {
    1230             :             /* no exponent, pad after the digits */
    1231           0 :             dostr(convert, vallen, target);
    1232           0 :             dopr_outchmulti('0', zeropadlen, target);
    1233             :         }
    1234             :     }
    1235             :     else
    1236             :     {
    1237             :         /* no zero padding, just emit the number as-is */
    1238     1424234 :         dostr(convert, vallen, target);
    1239             :     }
    1240             : 
    1241     1424234 :     trailing_pad(padlen, target);
    1242     1424234 :     return;
    1243             : 
    1244           0 : fail:
    1245           0 :     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             :  */
    1257             : int
    1258      230294 : pg_strfromd(char *str, size_t count, int precision, double value)
    1259             : {
    1260             :     PrintfTarget target;
    1261      230294 :     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      230294 :     target.bufstart = target.bufptr = str;
    1269      230294 :     target.bufend = str + count - 1;
    1270      230294 :     target.stream = NULL;
    1271      230294 :     target.nchars = 0;
    1272      230294 :     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      230294 :     if (precision < 1)
    1280           0 :         precision = 1;
    1281      230294 :     else if (precision > 32)
    1282           0 :         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      230294 :     if (isnan(value))
    1289             :     {
    1290       12138 :         strcpy(convert, "NaN");
    1291       12138 :         vallen = 3;
    1292             :     }
    1293             :     else
    1294             :     {
    1295             :         static const double dzero = 0.0;
    1296             : 
    1297      218156 :         if (value < 0.0 ||
    1298      185756 :             (value == 0.0 &&
    1299       26878 :              memcmp(&value, &dzero, sizeof(double)) != 0))
    1300             :         {
    1301       32466 :             signvalue = '-';
    1302       32466 :             value = -value;
    1303             :         }
    1304             : 
    1305      218156 :         if (isinf(value))
    1306             :         {
    1307        7116 :             strcpy(convert, "Infinity");
    1308        7116 :             vallen = 8;
    1309             :         }
    1310             :         else
    1311             :         {
    1312      211040 :             fmt[0] = '%';
    1313      211040 :             fmt[1] = '.';
    1314      211040 :             fmt[2] = '*';
    1315      211040 :             fmt[3] = 'g';
    1316      211040 :             fmt[4] = '\0';
    1317      211040 :             vallen = snprintf(convert, sizeof(convert), fmt, precision, value);
    1318      211040 :             if (vallen < 0)
    1319             :             {
    1320           0 :                 target.failed = true;
    1321           0 :                 goto fail;
    1322             :             }
    1323             :         }
    1324             :     }
    1325             : 
    1326      230294 :     if (signvalue)
    1327       32466 :         dopr_outch(signvalue, &target);
    1328             : 
    1329      230294 :     dostr(convert, vallen, &target);
    1330             : 
    1331      230294 : fail:
    1332      230294 :     *(target.bufptr) = '\0';
    1333      460588 :     return target.failed ? -1 : (target.bufptr - target.bufstart
    1334      230294 :                                  + target.nchars);
    1335             : }
    1336             : 
    1337             : 
    1338             : static void
    1339   239337242 : dostr(const char *str, int slen, PrintfTarget *target)
    1340             : {
    1341             :     /* fast path for common case of slen == 1 */
    1342   239337242 :     if (slen == 1)
    1343             :     {
    1344    80138764 :         dopr_outch(*str, target);
    1345    80138764 :         return;
    1346             :     }
    1347             : 
    1348   315282378 :     while (slen > 0)
    1349             :     {
    1350             :         int         avail;
    1351             : 
    1352   156771956 :         if (target->bufend != NULL)
    1353   134874186 :             avail = target->bufend - target->bufptr;
    1354             :         else
    1355    21897770 :             avail = slen;
    1356   156771956 :         if (avail <= 0)
    1357             :         {
    1358             :             /* buffer full, can we dump to stream? */
    1359      688546 :             if (target->stream == NULL)
    1360             :             {
    1361      688056 :                 target->nchars += slen; /* no, lose the data */
    1362      688056 :                 return;
    1363             :             }
    1364         490 :             flushbuffer(target);
    1365         490 :             continue;
    1366             :         }
    1367   156083410 :         avail = Min(avail, slen);
    1368   156083410 :         memmove(target->bufptr, str, avail);
    1369   156083410 :         target->bufptr += avail;
    1370   156083410 :         str += avail;
    1371   156083410 :         slen -= avail;
    1372             :     }
    1373             : }
    1374             : 
    1375             : static void
    1376    92441192 : dopr_outch(int c, PrintfTarget *target)
    1377             : {
    1378    92441192 :     if (target->bufend != NULL && target->bufptr >= target->bufend)
    1379             :     {
    1380             :         /* buffer full, can we dump to stream? */
    1381      200484 :         if (target->stream == NULL)
    1382             :         {
    1383      200484 :             target->nchars++;    /* no, lose the data */
    1384      200484 :             return;
    1385             :         }
    1386           0 :         flushbuffer(target);
    1387             :     }
    1388    92240708 :     *(target->bufptr++) = c;
    1389             : }
    1390             : 
    1391             : static void
    1392    11381366 : dopr_outchmulti(int c, int slen, PrintfTarget *target)
    1393             : {
    1394             :     /* fast path for common case of slen == 1 */
    1395    11381366 :     if (slen == 1)
    1396             :     {
    1397     8203484 :         dopr_outch(c, target);
    1398     8203484 :         return;
    1399             :     }
    1400             : 
    1401     6355822 :     while (slen > 0)
    1402             :     {
    1403             :         int         avail;
    1404             : 
    1405     3178104 :         if (target->bufend != NULL)
    1406     3132554 :             avail = target->bufend - target->bufptr;
    1407             :         else
    1408       45550 :             avail = slen;
    1409     3178104 :         if (avail <= 0)
    1410             :         {
    1411             :             /* buffer full, can we dump to stream? */
    1412         278 :             if (target->stream == NULL)
    1413             :             {
    1414         164 :                 target->nchars += slen; /* no, lose the data */
    1415         164 :                 return;
    1416             :             }
    1417         114 :             flushbuffer(target);
    1418         114 :             continue;
    1419             :         }
    1420     3177826 :         avail = Min(avail, slen);
    1421     3177826 :         memset(target->bufptr, c, avail);
    1422     3177826 :         target->bufptr += avail;
    1423     3177826 :         slen -= avail;
    1424             :     }
    1425             : }
    1426             : 
    1427             : 
    1428             : static int
    1429    42814802 : adjust_sign(int is_negative, int forcesign, int *signvalue)
    1430             : {
    1431    42814802 :     if (is_negative)
    1432             :     {
    1433     3525182 :         *signvalue = '-';
    1434     3525182 :         return true;
    1435             :     }
    1436    39289620 :     else if (forcesign)
    1437         204 :         *signvalue = '+';
    1438    39289620 :     return false;
    1439             : }
    1440             : 
    1441             : 
    1442             : static int
    1443   104451396 : compute_padlen(int minlen, int vallen, int leftjust)
    1444             : {
    1445             :     int         padlen;
    1446             : 
    1447   104451396 :     padlen = minlen - vallen;
    1448   104451396 :     if (padlen < 0)
    1449    69700232 :         padlen = 0;
    1450   104451396 :     if (leftjust)
    1451     1107842 :         padlen = -padlen;
    1452   104451396 :     return padlen;
    1453             : }
    1454             : 
    1455             : 
    1456             : static void
    1457   102443610 : leading_pad(int zpad, int signvalue, int *padlen, PrintfTarget *target)
    1458             : {
    1459             :     int         maxpad;
    1460             : 
    1461   102443610 :     if (*padlen > 0 && zpad)
    1462             :     {
    1463     8498538 :         if (signvalue)
    1464             :         {
    1465         224 :             dopr_outch(signvalue, target);
    1466         224 :             --(*padlen);
    1467         224 :             signvalue = 0;
    1468             :         }
    1469     8498538 :         if (*padlen > 0)
    1470             :         {
    1471     8498520 :             dopr_outchmulti(zpad, *padlen, target);
    1472     8498520 :             *padlen = 0;
    1473             :         }
    1474             :     }
    1475   102443610 :     maxpad = (signvalue != 0);
    1476   102443610 :     if (*padlen > maxpad)
    1477             :     {
    1478     1558560 :         dopr_outchmulti(' ', *padlen - maxpad, target);
    1479     1558560 :         *padlen = maxpad;
    1480             :     }
    1481   102443610 :     if (signvalue)
    1482             :     {
    1483     3525162 :         dopr_outch(signvalue, target);
    1484     3525162 :         if (*padlen > 0)
    1485           0 :             --(*padlen);
    1486     3525162 :         else if (*padlen < 0)
    1487           0 :             ++(*padlen);
    1488             :     }
    1489   102443610 : }
    1490             : 
    1491             : 
    1492             : static void
    1493   104451392 : trailing_pad(int padlen, PrintfTarget *target)
    1494             : {
    1495   104451392 :     if (padlen < 0)
    1496      732966 :         dopr_outchmulti(' ', -padlen, target);
    1497   104451392 : }

Generated by: LCOV version 1.16