doprnt.c 13.8 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-2011  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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
/* 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
     the diplay width of each character, according to char-width-table.  That
     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
     overflow MOST_POSITIVE_FIXNUM, to avoid producing strings longer than what
     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 ll.  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
Paul Eggert's avatar
Paul Eggert committed
88
   int'.  Similarly, ll (two letter ells) means to use `long long int' or
Paul Eggert's avatar
Paul Eggert committed
89 90
   `unsigned long long int'; this can be used only on hosts that have
   these two types.  The empty length modifier means to use `int' or
Paul Eggert's avatar
Paul Eggert committed
91 92
   `unsigned int'.  EMACS_INT arguments should use the pI macro, which
   expands to whatever length modifier is needed for the target host.
93 94 95 96 97 98 99 100 101 102

   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
103

Richard M. Stallman's avatar
Richard M. Stallman committed
104
#include <config.h>
Joseph Arceneaux's avatar
Joseph Arceneaux committed
105 106
#include <stdio.h>
#include <ctype.h>
107
#include <setjmp.h>
Joseph Arceneaux's avatar
Joseph Arceneaux committed
108

109
#ifdef STDC_HEADERS
110 111 112
#include <float.h>
#endif

Dave Love's avatar
Dave Love committed
113 114
#include <unistd.h>

115 116
#include <limits.h>

117 118
#include "lisp.h"

Karl Heuer's avatar
Karl Heuer committed
119 120 121
/* 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.  */
122
#include "character.h"
Karl Heuer's avatar
Karl Heuer committed
123

124 125 126 127
#ifndef SIZE_MAX
# define SIZE_MAX ((size_t) -1)
#endif

128 129 130 131
#ifndef DBL_MAX_10_EXP
#define DBL_MAX_10_EXP 308 /* IEEE double */
#endif

132 133
/* Generate output from a format-spec FORMAT,
   terminated at position FORMAT_END.
134
   (*FORMAT_END is not part of the format, but must exist and be readable.)
135
   Output goes in BUFFER, which has room for BUFSIZE chars.
136 137 138
   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.
139 140
   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
141 142
   String arguments are passed as C strings.
   Integers are passed as C integers.  */
143

144 145
size_t
doprnt (char *buffer, register size_t bufsize, const char *format,
146
	const char *format_end, va_list ap)
Joseph Arceneaux's avatar
Joseph Arceneaux committed
147
{
148
  const char *fmt = format;	/* Pointer into format string */
Joseph Arceneaux's avatar
Joseph Arceneaux committed
149
  register char *bufptr = buffer; /* Pointer into output buffer.. */
150

151
  /* Use this for sprintf unless we need something really big.  */
152
  char tembuf[DBL_MAX_10_EXP + 100];
153

154
  /* Size of sprintf_buffer.  */
155
  size_t size_allocated = sizeof (tembuf);
156

157 158
  /* Buffer to use for sprintf.  Either tembuf or same as BIG_BUFFER.  */
  char *sprintf_buffer = tembuf;
159

160
  /* Buffer we have got with malloc.  */
161
  char *big_buffer = NULL;
162

163
  register size_t tem;
164
  char *string;
165 166
  char fixed_buffer[20];	/* Default buffer for small formatting. */
  char *fmtcpy;
Joseph Arceneaux's avatar
Joseph Arceneaux committed
167
  int minlen;
168
  char charbuf[MAX_MULTIBYTE_LENGTH + 1];	/* Used for %c.  */
169
  USE_SAFE_ALLOCA;
Joseph Arceneaux's avatar
Joseph Arceneaux committed
170 171 172 173

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

174 175 176
  if ((format_end - format + 1) < sizeof (fixed_buffer))
    fmtcpy = fixed_buffer;
  else
177
    SAFE_ALLOCA (fmtcpy, char *, format_end - format + 1);
178

Joseph Arceneaux's avatar
Joseph Arceneaux committed
179
  bufsize--;
180 181

  /* Loop until end of format string or buffer full. */
182
  while (fmt < format_end && bufsize > 0)
Joseph Arceneaux's avatar
Joseph Arceneaux committed
183 184 185
    {
      if (*fmt == '%')	/* Check for a '%' character */
	{
186 187 188
	  size_t size_bound = 0;
	  EMACS_INT width;  /* Columns occupied by STRING on display.  */
	  int long_flag = 0;
189

Joseph Arceneaux's avatar
Joseph Arceneaux committed
190
	  fmt++;
Jim Blandy's avatar
Jim Blandy committed
191
	  /* Copy this one %-spec into fmtcpy.  */
192
	  string = fmtcpy;
Joseph Arceneaux's avatar
Joseph Arceneaux committed
193
	  *string++ = '%';
194
	  while (fmt < format_end)
Joseph Arceneaux's avatar
Joseph Arceneaux committed
195 196
	    {
	      *string++ = *fmt;
197 198 199 200 201 202
	      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.  */
203
		  size_t n = *fmt - '0';
204 205
		  while (fmt < format_end
			 && '0' <= fmt[1] && fmt[1] <= '9')
206
		    {
Paul Eggert's avatar
Paul Eggert committed
207 208 209 210 211
		      /* Avoid size_t overflow.  Avoid int overflow too, as
			 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.  */
212
		      if (n >= min (INT_MAX, SIZE_MAX) / 10)
213
			error ("Format width or precision too large");
Andreas Schwab's avatar
Andreas Schwab committed
214
		      n = n * 10 + fmt[1] - '0';
215 216 217 218 219 220
		      *string++ = *++fmt;
		    }

		  if (size_bound < n)
		    size_bound = n;
		}
221
	      else if (*fmt == '-' || *fmt == ' ' || *fmt == '.' || *fmt == '+')
222
		;
223 224
	      else if (*fmt == 'l')
		{
225
		  long_flag = 1 + (fmt + 1 < format_end && fmt[1] == 'l');
Paul Eggert's avatar
Paul Eggert committed
226
		  fmt += long_flag;
227
		  break;
228
		}
229
	      else
Joseph Arceneaux's avatar
Joseph Arceneaux committed
230 231 232
		break;
	      fmt++;
	    }
233 234
	  if (fmt > format_end)
	    fmt = format_end;
Joseph Arceneaux's avatar
Joseph Arceneaux committed
235
	  *string = 0;
236

237 238
	  /* Make the size bound large enough to handle floating point formats
	     with large numbers.  */
239
	  if (size_bound > SIZE_MAX - DBL_MAX_10_EXP - 50)
240
	    error ("Format width or precision too large");
241
	  size_bound += DBL_MAX_10_EXP + 50;
242

243 244 245 246
	  /* Make sure we have that much.  */
	  if (size_bound > size_allocated)
	    {
	      if (big_buffer)
247 248
		xfree (big_buffer);
	      big_buffer = (char *) xmalloc (size_bound);
249 250 251
	      sprintf_buffer = big_buffer;
	      size_allocated = size_bound;
	    }
Joseph Arceneaux's avatar
Joseph Arceneaux committed
252 253 254 255
	  minlen = 0;
	  switch (*fmt++)
	    {
	    default:
256
	      error ("Invalid format operation %%%s%c",
257
		     "ll" + 2 - long_flag, fmt[-1]);
Joseph Arceneaux's avatar
Joseph Arceneaux committed
258 259

/*	    case 'b': */
260
	    case 'l':
Joseph Arceneaux's avatar
Joseph Arceneaux committed
261
	    case 'd':
262 263 264 265
	      {
		int i;
		long l;

266 267 268 269 270 271
		if (1 < long_flag)
		  {
#ifdef HAVE_LONG_LONG_INT
		    long long ll = va_arg (ap, long long);
		    sprintf (sprintf_buffer, fmtcpy, ll);
#else
272
		    error ("Invalid format operation %%ll%c", fmt[-1]);
273 274 275
#endif
		  }
		else if (long_flag)
276 277 278 279 280 281 282 283 284 285 286 287 288 289
		  {
		    l = va_arg(ap, long);
		    sprintf (sprintf_buffer, fmtcpy, l);
		  }
		else
		  {
		    i = va_arg(ap, int);
		    sprintf (sprintf_buffer, fmtcpy, i);
		  }
		/* Now copy into final output, truncating as necessary.  */
		string = sprintf_buffer;
		goto doit;
	      }

Joseph Arceneaux's avatar
Joseph Arceneaux committed
290 291
	    case 'o':
	    case 'x':
292 293 294 295
	      {
		unsigned u;
		unsigned long ul;

296 297 298 299 300 301
		if (1 < long_flag)
		  {
#ifdef HAVE_UNSIGNED_LONG_LONG_INT
		    unsigned long long ull = va_arg (ap, unsigned long long);
		    sprintf (sprintf_buffer, fmtcpy, ull);
#else
302
		    error ("Invalid format operation %%ll%c", fmt[-1]);
303 304 305
#endif
		  }
		else if (long_flag)
306 307 308 309 310 311 312 313 314 315 316 317 318
		  {
		    ul = va_arg(ap, unsigned long);
		    sprintf (sprintf_buffer, fmtcpy, ul);
		  }
		else
		  {
		    u = va_arg(ap, unsigned);
		    sprintf (sprintf_buffer, fmtcpy, u);
		  }
		/* Now copy into final output, truncating as necessary.  */
		string = sprintf_buffer;
		goto doit;
	      }
Joseph Arceneaux's avatar
Joseph Arceneaux committed
319

320 321 322 323
	    case 'f':
	    case 'e':
	    case 'g':
	      {
324 325
		double d = va_arg(ap, double);
		sprintf (sprintf_buffer, fmtcpy, d);
326
		/* Now copy into final output, truncating as necessary.  */
327
		string = sprintf_buffer;
328 329 330
		goto doit;
	      }

Joseph Arceneaux's avatar
Joseph Arceneaux committed
331 332 333 334 335
	    case 'S':
	      string[-1] = 's';
	    case 's':
	      if (fmtcpy[1] != 's')
		minlen = atoi (&fmtcpy[1]);
336
	      string = va_arg (ap, char *);
337
	      tem = strlen (string);
338 339
	      if (tem > MOST_POSITIVE_FIXNUM)
		error ("String for %%s or %%S format is too long");
Karl Heuer's avatar
Karl Heuer committed
340
	      width = strwidth (string, tem);
Richard M. Stallman's avatar
Richard M. Stallman committed
341 342
	      goto doit1;

Joseph Arceneaux's avatar
Joseph Arceneaux committed
343 344
	      /* Copy string into final output, truncating if no room.  */
	    doit:
Karl Heuer's avatar
Karl Heuer committed
345
	      /* Coming here means STRING contains ASCII only.  */
346 347 348 349
	      tem = strlen (string);
	      if (tem > MOST_POSITIVE_FIXNUM)
		error ("Format width or precision too large");
	      width = tem;
350
	    doit1:
Karl Heuer's avatar
Karl Heuer committed
351 352 353 354
	      /* 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
355 356
	      if (minlen > 0)
		{
Karl Heuer's avatar
Karl Heuer committed
357
		  while (minlen > width && bufsize > 0)
Joseph Arceneaux's avatar
Joseph Arceneaux committed
358 359 360 361 362 363 364 365
		    {
		      *bufptr++ = ' ';
		      bufsize--;
		      minlen--;
		    }
		  minlen = 0;
		}
	      if (tem > bufsize)
Karl Heuer's avatar
Karl Heuer committed
366 367 368
		{
		  /* Truncate the string at character boundary.  */
		  tem = bufsize;
369
		  while (!CHAR_HEAD_P (string[tem - 1])) tem--;
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
		  /* If the multibyte sequence of this character is
		     too long for the space we have left in the
		     buffer, truncate before it.  */
		  if (tem > 0
		      && BYTES_BY_CHAR_HEAD (string[tem - 1]) > bufsize)
		    tem--;
		  if (tem > 0)
		    memcpy (bufptr, string, tem);
		  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
385 386
		}
	      else
387
		memcpy (bufptr, string, tem);
Joseph Arceneaux's avatar
Joseph Arceneaux committed
388 389 390 391
	      bufptr += tem;
	      bufsize -= tem;
	      if (minlen < 0)
		{
Karl Heuer's avatar
Karl Heuer committed
392
		  while (minlen < - width && bufsize > 0)
Joseph Arceneaux's avatar
Joseph Arceneaux committed
393 394 395 396 397 398 399 400 401 402
		    {
		      *bufptr++ = ' ';
		      bufsize--;
		      minlen++;
		    }
		  minlen = 0;
		}
	      continue;

	    case 'c':
403
	      {
404 405
		int chr = va_arg(ap, int);
		tem = CHAR_STRING (chr, (unsigned char *) charbuf);
406 407 408 409 410 411 412
		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
413 414 415 416 417

	    case '%':
	      fmt--;    /* Drop thru and this % will be treated as normal */
	    }
	}
Karl Heuer's avatar
Karl Heuer committed
418 419 420 421 422 423 424

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

	do { *bufptr++ = *fmt++; }
425
	while (fmt < format_end && --bufsize > 0 && !CHAR_HEAD_P (*fmt));
426
	if (!CHAR_HEAD_P (*fmt))
Karl Heuer's avatar
Karl Heuer committed
427
	  {
428 429 430
	    /* 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
431 432 433
	    break;
	  }
      }
Joseph Arceneaux's avatar
Joseph Arceneaux committed
434 435
    };

436
  /* If we had to malloc something, free it.  */
437
  xfree (big_buffer);
438

439
  *bufptr = 0;		/* Make sure our string ends with a '\0' */
440 441

  SAFE_FREE ();
Joseph Arceneaux's avatar
Joseph Arceneaux committed
442 443
  return bufptr - buffer;
}