doprnt.c 16.4 KB
Newer Older
Joseph Arceneaux's avatar
Joseph Arceneaux committed
1
/* Output like sprintf to a buffer of specified size.
2 3
   Also takes args differently: pass one pointer to the end
   of the format string in addition to the format string itself.
4
   Copyright (C) 1985, 2001-2013 Free Software Foundation, Inc.
Joseph Arceneaux's avatar
Joseph Arceneaux committed
5 6 7

This file is part of GNU Emacs.

8
GNU Emacs is free software: you can redistribute it and/or modify
Joseph Arceneaux's avatar
Joseph Arceneaux committed
9
it under the terms of the GNU General Public License as published by
10 11
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Joseph Arceneaux's avatar
Joseph Arceneaux committed
12 13 14 15 16 17 18

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
19
along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
Joseph Arceneaux's avatar
Joseph Arceneaux committed
20

21 22 23 24 25 26 27 28
/* If you think about replacing this with some similar standard C function of
   the printf family (such as vsnprintf), please note that this function
   supports the following Emacs-specific features:

   . For %c conversions, it produces a string with the multibyte representation
     of the (`int') argument, suitable for display in an Emacs buffer.

   . For %s and %c, when field width is specified (e.g., %25s), it accounts for
Paul Eggert's avatar
Paul Eggert committed
29
     the display width of each character, according to char-width-table.  That
30 31 32 33 34 35 36 37 38 39 40
     is, it does not assume that each character takes one column on display.

   . If the size of the buffer is not enough to produce the formatted string in
     its entirety, it makes sure that truncation does not chop the last
     character in the middle of its multibyte sequence, producing an invalid
     sequence.

   . It accepts a pointer to the end of the format string, so the format string
     could include embedded null characters.

   . It signals an error if the length of the formatted string is about to
Paul Eggert's avatar
Paul Eggert committed
41
     overflow ptrdiff_t or size_t, to avoid producing strings longer than what
42 43 44 45
     Emacs can handle.

   OTOH, this function supports only a small subset of the standard C formatted
   output facilities.  E.g., %u and %ll are not supported, and precision is
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
   ignored %s and %c conversions.  (See below for the detailed documentation of
   what is supported.)  However, this is okay, as this function is supposed to
   be called from `error' and similar functions, and thus does not need to
   support features beyond those in `Fformat', which is used by `error' on the
   Lisp level.  */

/* This function supports the following %-sequences in the `format'
   argument:

   %s means print a string argument.
   %S is silently treated as %s, for loose compatibility with `Fformat'.
   %d means print a `signed int' argument in decimal.
   %o means print an `unsigned int' argument in octal.
   %x means print an `unsigned int' argument in hex.
   %e means print a `double' argument in exponential notation.
   %f means print a `double' argument in decimal-point notation.
   %g means print a `double' argument in exponential notation
      or in decimal-point notation, whichever uses fewer characters.
   %c means print a `signed int' argument as a single character.
   %% means produce a literal % character.

67 68
   A %-sequence may contain optional flag, width, and precision specifiers, and
   a length modifier, as follows:
69

70
     %<flags><width><precision><length>character
71

Paul Eggert's avatar
Paul Eggert committed
72
   where flags is [+ -0], width is [0-9]+, precision is .[0-9]+, and length
73 74 75
   is empty or l or the value of the pD or pI or pMd (sans "d") macros.
   Also, %% in a format stands for a single % in the output.  A % that
   does not introduce a valid %-sequence causes undefined behavior.
76 77

   The + flag character inserts a + before any positive number, while a space
78 79 80 81 82 83 84 85
   inserts a space before any positive number; these flags only affect %d, %o,
   %x, %e, %f, and %g sequences.  The - and 0 flags affect the width specifier,
   as described below.  For signed numerical arguments only, the ` ' (space)
   flag causes the result to be prefixed with a space character if it does not
   start with a sign (+ or -).

   The l (lower-case letter ell) length modifier is a `long' data type
   modifier: it is supported for %d, %o, and %x conversions of integral
Paul Eggert's avatar
Paul Eggert committed
86
   arguments, must immediately precede the conversion specifier, and means that
87
   the respective argument is to be treated as `long int' or `unsigned long
88 89 90 91
   int'.  Similarly, the value of the pD macro means to use ptrdiff_t,
   the value of the pI macro means to use EMACS_INT or EMACS_UINT, the
   value of the pMd etc. macros means to use intmax_t or uintmax_t,
   and the empty length modifier means `int' or `unsigned int'.
92 93 94 95 96 97 98 99 100 101

   The width specifier supplies a lower limit for the length of the printed
   representation.  The padding, if any, normally goes on the left, but it goes
   on the right if the - flag is present.  The padding character is normally a
   space, but (for numerical arguments only) it is 0 if the 0 flag is present.
   The - flag takes precedence over the 0 flag.

   For %e, %f, and %g sequences, the number after the "." in the precision
   specifier says how many decimal places to show; if zero, the decimal point
   itself is omitted.  For %s and %S, the precision specifier is ignored.  */
Joseph Arceneaux's avatar
Joseph Arceneaux committed
102

Richard M. Stallman's avatar
Richard M. Stallman committed
103
#include <config.h>
Joseph Arceneaux's avatar
Joseph Arceneaux committed
104
#include <stdio.h>
105
#include <float.h>
Dave Love's avatar
Dave Love committed
106
#include <unistd.h>
107 108
#include <limits.h>

109 110
#include "lisp.h"

Karl Heuer's avatar
Karl Heuer committed
111 112 113
/* Since we use the macro CHAR_HEAD_P, we have to include this, but
   don't have to include others because CHAR_HEAD_P does not contains
   another macro.  */
114
#include "character.h"
Karl Heuer's avatar
Karl Heuer committed
115

116 117
/* Generate output from a format-spec FORMAT,
   terminated at position FORMAT_END.
118
   (*FORMAT_END is not part of the format, but must exist and be readable.)
119
   Output goes in BUFFER, which has room for BUFSIZE chars.
120 121 122
   BUFSIZE must be positive.  If the output does not fit, truncate it
   to fit and return BUFSIZE - 1; if this truncates a multibyte
   sequence, store '\0' into the sequence's first byte.
123 124
   Returns the number of bytes stored into BUFFER, excluding
   the terminating null byte.  Output is always null-terminated.
Richard M. Stallman's avatar
Richard M. Stallman committed
125 126
   String arguments are passed as C strings.
   Integers are passed as C integers.  */
127

128 129
ptrdiff_t
doprnt (char *buffer, ptrdiff_t bufsize, const char *format,
130
	const char *format_end, va_list ap)
Joseph Arceneaux's avatar
Joseph Arceneaux committed
131
{
132 133
  const char *fmt = format;	/* Pointer into format string.  */
  char *bufptr = buffer;	/* Pointer into output buffer.  */
134

135
  /* Use this for sprintf unless we need something really big.  */
136
  char tembuf[DBL_MAX_10_EXP + 100];
137

138
  /* Size of sprintf_buffer.  */
139
  ptrdiff_t size_allocated = sizeof (tembuf);
140

141 142
  /* Buffer to use for sprintf.  Either tembuf or same as BIG_BUFFER.  */
  char *sprintf_buffer = tembuf;
143

144
  /* Buffer we have got with malloc.  */
145
  char *big_buffer = NULL;
146

147
  ptrdiff_t tem = -1;
148
  char *string;
149 150
  char fixed_buffer[20];	/* Default buffer for small formatting. */
  char *fmtcpy;
Joseph Arceneaux's avatar
Joseph Arceneaux committed
151
  int minlen;
152
  char charbuf[MAX_MULTIBYTE_LENGTH + 1];	/* Used for %c.  */
153
  USE_SAFE_ALLOCA;
Joseph Arceneaux's avatar
Joseph Arceneaux committed
154 155 156 157

  if (format_end == 0)
    format_end = format + strlen (format);

158 159 160
  fmtcpy = (format_end - format < sizeof (fixed_buffer) - 1
	    ? fixed_buffer
	    : SAFE_ALLOCA (format_end - format + 1));
161

Joseph Arceneaux's avatar
Joseph Arceneaux committed
162
  bufsize--;
163 164

  /* Loop until end of format string or buffer full. */
165
  while (fmt < format_end && bufsize > 0)
Joseph Arceneaux's avatar
Joseph Arceneaux committed
166 167 168
    {
      if (*fmt == '%')	/* Check for a '%' character */
	{
169
	  ptrdiff_t size_bound = 0;
170
	  ptrdiff_t width;  /* Columns occupied by STRING on display.  */
171 172 173 174 175 176 177 178 179 180 181
	  enum {
	    pDlen = sizeof pD - 1,
	    pIlen = sizeof pI - 1,
	    pMlen = sizeof pMd - 2
	  };
	  enum {
	    no_modifier, long_modifier, pD_modifier, pI_modifier, pM_modifier
	  } length_modifier = no_modifier;
	  static char const modifier_len[] = { 0, 1, pDlen, pIlen, pMlen };
	  int maxmlen = max (max (1, pDlen), max (pIlen, pMlen));
	  int mlen;
182

Joseph Arceneaux's avatar
Joseph Arceneaux committed
183
	  fmt++;
Jim Blandy's avatar
Jim Blandy committed
184
	  /* Copy this one %-spec into fmtcpy.  */
185
	  string = fmtcpy;
Joseph Arceneaux's avatar
Joseph Arceneaux committed
186
	  *string++ = '%';
187
	  while (fmt < format_end)
Joseph Arceneaux's avatar
Joseph Arceneaux committed
188 189
	    {
	      *string++ = *fmt;
190 191 192 193 194 195
	      if ('0' <= *fmt && *fmt <= '9')
		{
		  /* Get an idea of how much space we might need.
		     This might be a field width or a precision; e.g.
		     %1.1000f and %1000.1f both might need 1000+ bytes.
		     Parse the width or precision, checking for overflow.  */
196
		  ptrdiff_t n = *fmt - '0';
197
		  while (fmt + 1 < format_end
198
			 && '0' <= fmt[1] && fmt[1] <= '9')
199
		    {
200
		      /* Avoid ptrdiff_t, size_t, and int overflow, as
Paul Eggert's avatar
Paul Eggert committed
201 202 203 204
			 many sprintfs mishandle widths greater than INT_MAX.
			 This test is simple but slightly conservative: e.g.,
			 (INT_MAX - INT_MAX % 10) is reported as an overflow
			 even when it's not.  */
205
		      if (n >= min (INT_MAX, min (PTRDIFF_MAX, SIZE_MAX)) / 10)
206
			error ("Format width or precision too large");
Andreas Schwab's avatar
Andreas Schwab committed
207
		      n = n * 10 + fmt[1] - '0';
208 209 210 211 212 213
		      *string++ = *++fmt;
		    }

		  if (size_bound < n)
		    size_bound = n;
		}
214 215
	      else if (! (*fmt == '-' || *fmt == ' ' || *fmt == '.'
			  || *fmt == '+'))
Joseph Arceneaux's avatar
Joseph Arceneaux committed
216 217 218
		break;
	      fmt++;
	    }
219

220 221 222
	  /* Check for the length modifiers in textual length order, so
	     that longer modifiers override shorter ones.  */
	  for (mlen = 1; mlen <= maxmlen; mlen++)
223
	    {
224 225 226 227 228 229 230 231 232 233
	      if (format_end - fmt < mlen)
		break;
	      if (mlen == 1 && *fmt == 'l')
		length_modifier = long_modifier;
	      if (mlen == pDlen && memcmp (fmt, pD, pDlen) == 0)
		length_modifier = pD_modifier;
	      if (mlen == pIlen && memcmp (fmt, pI, pIlen) == 0)
		length_modifier = pI_modifier;
	      if (mlen == pMlen && memcmp (fmt, pMd, pMlen) == 0)
		length_modifier = pM_modifier;
234
	    }
235 236 237 238 239

	  mlen = modifier_len[length_modifier];
	  memcpy (string, fmt + 1, mlen);
	  string += mlen;
	  fmt += mlen;
Joseph Arceneaux's avatar
Joseph Arceneaux committed
240
	  *string = 0;
241

242 243
	  /* Make the size bound large enough to handle floating point formats
	     with large numbers.  */
244
	  if (size_bound > min (PTRDIFF_MAX, SIZE_MAX) - DBL_MAX_10_EXP - 50)
245
	    error ("Format width or precision too large");
246
	  size_bound += DBL_MAX_10_EXP + 50;
247

248 249 250 251
	  /* Make sure we have that much.  */
	  if (size_bound > size_allocated)
	    {
	      if (big_buffer)
252
		xfree (big_buffer);
Dmitry Antipov's avatar
Dmitry Antipov committed
253
	      big_buffer = xmalloc (size_bound);
254 255 256
	      sprintf_buffer = big_buffer;
	      size_allocated = size_bound;
	    }
Joseph Arceneaux's avatar
Joseph Arceneaux committed
257 258 259 260
	  minlen = 0;
	  switch (*fmt++)
	    {
	    default:
261
	      error ("Invalid format operation %s", fmtcpy);
Joseph Arceneaux's avatar
Joseph Arceneaux committed
262 263

/*	    case 'b': */
264
	    case 'l':
Joseph Arceneaux's avatar
Joseph Arceneaux committed
265
	    case 'd':
266 267 268
	      switch (length_modifier)
		{
		case no_modifier:
269
		  {
270
		    int v = va_arg (ap, int);
271
		    tem = sprintf (sprintf_buffer, fmtcpy, v);
272
		  }
273 274
		  break;
		case long_modifier:
275
		  {
276
		    long v = va_arg (ap, long);
277
		    tem = sprintf (sprintf_buffer, fmtcpy, v);
278
		  }
279 280 281
		  break;
		case pD_modifier:
		signed_pD_modifier:
282
		  {
283
		    ptrdiff_t v = va_arg (ap, ptrdiff_t);
284
		    tem = sprintf (sprintf_buffer, fmtcpy, v);
285
		  }
286 287 288 289
		  break;
		case pI_modifier:
		  {
		    EMACS_INT v = va_arg (ap, EMACS_INT);
290
		    tem = sprintf (sprintf_buffer, fmtcpy, v);
291 292 293 294 295
		  }
		  break;
		case pM_modifier:
		  {
		    intmax_t v = va_arg (ap, intmax_t);
296
		    tem = sprintf (sprintf_buffer, fmtcpy, v);
297 298 299 300 301 302
		  }
		  break;
		}
	      /* Now copy into final output, truncating as necessary.  */
	      string = sprintf_buffer;
	      goto doit;
303

Joseph Arceneaux's avatar
Joseph Arceneaux committed
304 305
	    case 'o':
	    case 'x':
306 307 308
	      switch (length_modifier)
		{
		case no_modifier:
309
		  {
310
		    unsigned v = va_arg (ap, unsigned);
311
		    tem = sprintf (sprintf_buffer, fmtcpy, v);
312
		  }
313 314
		  break;
		case long_modifier:
315
		  {
316
		    unsigned long v = va_arg (ap, unsigned long);
317
		    tem = sprintf (sprintf_buffer, fmtcpy, v);
318
		  }
319 320 321 322
		  break;
		case pD_modifier:
		  goto signed_pD_modifier;
		case pI_modifier:
323
		  {
324
		    EMACS_UINT v = va_arg (ap, EMACS_UINT);
325
		    tem = sprintf (sprintf_buffer, fmtcpy, v);
326
		  }
327 328 329 330
		  break;
		case pM_modifier:
		  {
		    uintmax_t v = va_arg (ap, uintmax_t);
331
		    tem = sprintf (sprintf_buffer, fmtcpy, v);
332 333 334 335 336 337
		  }
		  break;
		}
	      /* Now copy into final output, truncating as necessary.  */
	      string = sprintf_buffer;
	      goto doit;
Joseph Arceneaux's avatar
Joseph Arceneaux committed
338

339 340 341 342
	    case 'f':
	    case 'e':
	    case 'g':
	      {
Juanma Barranquero's avatar
Juanma Barranquero committed
343
		double d = va_arg (ap, double);
344
		tem = sprintf (sprintf_buffer, fmtcpy, d);
345
		/* Now copy into final output, truncating as necessary.  */
346
		string = sprintf_buffer;
347 348 349
		goto doit;
	      }

Joseph Arceneaux's avatar
Joseph Arceneaux committed
350 351 352 353 354
	    case 'S':
	      string[-1] = 's';
	    case 's':
	      if (fmtcpy[1] != 's')
		minlen = atoi (&fmtcpy[1]);
355
	      string = va_arg (ap, char *);
356
	      tem = strlen (string);
357
	      if (STRING_BYTES_BOUND < tem)
358
		error ("String for %%s or %%S format is too long");
Karl Heuer's avatar
Karl Heuer committed
359
	      width = strwidth (string, tem);
Richard M. Stallman's avatar
Richard M. Stallman committed
360 361
	      goto doit1;

Joseph Arceneaux's avatar
Joseph Arceneaux committed
362 363
	      /* Copy string into final output, truncating if no room.  */
	    doit:
364
	      eassert (0 <= tem);
Karl Heuer's avatar
Karl Heuer committed
365
	      /* Coming here means STRING contains ASCII only.  */
366
	      if (STRING_BYTES_BOUND < tem)
367 368
		error ("Format width or precision too large");
	      width = tem;
369
	    doit1:
Karl Heuer's avatar
Karl Heuer committed
370 371 372 373
	      /* We have already calculated:
		 TEM -- length of STRING,
		 WIDTH -- columns occupied by STRING when displayed, and
		 MINLEN -- minimum columns of the output.  */
Joseph Arceneaux's avatar
Joseph Arceneaux committed
374 375
	      if (minlen > 0)
		{
Karl Heuer's avatar
Karl Heuer committed
376
		  while (minlen > width && bufsize > 0)
Joseph Arceneaux's avatar
Joseph Arceneaux committed
377 378 379 380 381 382 383 384
		    {
		      *bufptr++ = ' ';
		      bufsize--;
		      minlen--;
		    }
		  minlen = 0;
		}
	      if (tem > bufsize)
Karl Heuer's avatar
Karl Heuer committed
385 386 387
		{
		  /* Truncate the string at character boundary.  */
		  tem = bufsize;
388 389 390 391 392 393 394 395 396 397 398 399 400
		  do
		    {
		      tem--;
		      if (CHAR_HEAD_P (string[tem]))
			{
			  if (BYTES_BY_CHAR_HEAD (string[tem]) <= bufsize - tem)
			    tem = bufsize;
			  break;
			}
		    }
		  while (tem != 0);

		  memcpy (bufptr, string, tem);
401 402 403 404 405 406 407
		  bufptr[tem] = 0;
		  /* Trigger exit from the loop, but make sure we
		     return to the caller a value which will indicate
		     that the buffer was too small.  */
		  bufptr += bufsize;
		  bufsize = 0;
		  continue;
Karl Heuer's avatar
Karl Heuer committed
408
		}
409
	      memcpy (bufptr, string, tem);
Joseph Arceneaux's avatar
Joseph Arceneaux committed
410 411 412 413
	      bufptr += tem;
	      bufsize -= tem;
	      if (minlen < 0)
		{
Karl Heuer's avatar
Karl Heuer committed
414
		  while (minlen < - width && bufsize > 0)
Joseph Arceneaux's avatar
Joseph Arceneaux committed
415 416 417 418 419 420 421 422 423 424
		    {
		      *bufptr++ = ' ';
		      bufsize--;
		      minlen++;
		    }
		  minlen = 0;
		}
	      continue;

	    case 'c':
425
	      {
Juanma Barranquero's avatar
Juanma Barranquero committed
426
		int chr = va_arg (ap, int);
427
		tem = CHAR_STRING (chr, (unsigned char *) charbuf);
428 429 430 431 432 433 434
		string = charbuf;
		string[tem] = 0;
		width = strwidth (string, tem);
		if (fmtcpy[1] != 'c')
		  minlen = atoi (&fmtcpy[1]);
		goto doit1;
	      }
Joseph Arceneaux's avatar
Joseph Arceneaux committed
435 436 437 438 439

	    case '%':
	      fmt--;    /* Drop thru and this % will be treated as normal */
	    }
	}
Karl Heuer's avatar
Karl Heuer committed
440 441 442 443 444 445 446

      {
	/* Just some character; Copy it if the whole multi-byte form
	   fit in the buffer.  */
	char *save_bufptr = bufptr;

	do { *bufptr++ = *fmt++; }
447
	while (fmt < format_end && --bufsize > 0 && !CHAR_HEAD_P (*fmt));
448
	if (!CHAR_HEAD_P (*fmt))
Karl Heuer's avatar
Karl Heuer committed
449
	  {
450 451 452
	    /* Truncate, but return value that will signal to caller
	       that the buffer was too small.  */
	    *save_bufptr = 0;
Karl Heuer's avatar
Karl Heuer committed
453 454 455
	    break;
	  }
      }
Joseph Arceneaux's avatar
Joseph Arceneaux committed
456 457
    };

458
  /* If we had to malloc something, free it.  */
459
  xfree (big_buffer);
460

461
  *bufptr = 0;		/* Make sure our string ends with a '\0' */
462 463

  SAFE_FREE ();
Joseph Arceneaux's avatar
Joseph Arceneaux committed
464 465
  return bufptr - buffer;
}
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484

/* Format to an unbounded buffer BUF.  This is like sprintf, except it
   is not limited to returning an 'int' so it doesn't have a silly 2
   GiB limit on typical 64-bit hosts.  However, it is limited to the
   Emacs-style formats that doprnt supports.

   Return the number of bytes put into BUF, excluding the terminating
   '\0'.  */
ptrdiff_t
esprintf (char *buf, char const *format, ...)
{
  ptrdiff_t nbytes;
  va_list ap;
  va_start (ap, format);
  nbytes = doprnt (buf, TYPE_MAXIMUM (ptrdiff_t), format, 0, ap);
  va_end (ap);
  return nbytes;
}

Paul Eggert's avatar
Paul Eggert committed
485 486
#if defined HAVE_X_WINDOWS && defined USE_X_TOOLKIT

487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
/* Format to buffer *BUF of positive size *BUFSIZE, reallocating *BUF
   and updating *BUFSIZE if the buffer is too small, and otherwise
   behaving line esprintf.  When reallocating, free *BUF unless it is
   equal to NONHEAPBUF, and if BUFSIZE_MAX is nonnegative then signal
   memory exhaustion instead of growing the buffer size past
   BUFSIZE_MAX.  */
ptrdiff_t
exprintf (char **buf, ptrdiff_t *bufsize,
	  char const *nonheapbuf, ptrdiff_t bufsize_max,
	  char const *format, ...)
{
  ptrdiff_t nbytes;
  va_list ap;
  va_start (ap, format);
  nbytes = evxprintf (buf, bufsize, nonheapbuf, bufsize_max, format, ap);
  va_end (ap);
  return nbytes;
}

Paul Eggert's avatar
Paul Eggert committed
506 507
#endif

508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
/* Act like exprintf, except take a va_list.  */
ptrdiff_t
evxprintf (char **buf, ptrdiff_t *bufsize,
	   char const *nonheapbuf, ptrdiff_t bufsize_max,
	   char const *format, va_list ap)
{
  for (;;)
    {
      ptrdiff_t nbytes;
      va_list ap_copy;
      va_copy (ap_copy, ap);
      nbytes = doprnt (*buf, *bufsize, format, 0, ap_copy);
      va_end (ap_copy);
      if (nbytes < *bufsize - 1)
	return nbytes;
      if (*buf != nonheapbuf)
524 525 526 527
	{
	  xfree (*buf);
	  *buf = NULL;
	}
528 529 530
      *buf = xpalloc (NULL, bufsize, 1, bufsize_max, 1);
    }
}