1 /* 2 * Copyright (c) 1989, 1993 3 * The Regents of the University of California. All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. All advertising materials mentioning features or use of this software 14 * must display the following acknowledgement: 15 * This product includes software developed by the University of 16 * California, Berkeley and its contributors. 17 * 4. Neither the name of the University nor the names of its contributors 18 * may be used to endorse or promote products derived from this software 19 * without specific prior written permission. 20 * 21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 */ 33 34 #if !defined(BUILTIN) && !defined(SHELL) 35 #ifndef lint 36 static char const copyright[] = 37 "@(#) Copyright (c) 1989, 1993\n\ 38 The Regents of the University of California. All rights reserved.\n"; 39 #endif /* not lint */ 40 #endif 41 42 #ifndef lint 43 #if 0 44 static char const sccsid[] = "@(#)printf.c 8.1 (Berkeley) 7/20/93"; 45 #endif 46 static const char rcsid[] = 47 "$FreeBSD$"; 48 #endif /* not lint */ 49 50 #include <sys/types.h> 51 52 #include <err.h> 53 #include <errno.h> 54 #include <inttypes.h> 55 #include <limits.h> 56 #include <stdio.h> 57 #include <stdlib.h> 58 #include <string.h> 59 #include <unistd.h> 60 61 #ifdef SHELL 62 #define main printfcmd 63 #include "bltin/bltin.h" 64 #include "memalloc.h" 65 #include "error.h" 66 #else 67 #define warnx1(a, b, c) warnx(a) 68 #define warnx2(a, b, c) warnx(a, b) 69 #define warnx3(a, b, c) warnx(a, b, c) 70 #endif 71 72 #ifndef BUILTIN 73 #include <locale.h> 74 #endif 75 76 #define PF(f, func) do { \ 77 char *b = NULL; \ 78 if (havewidth) \ 79 if (haveprec) \ 80 (void)asprintf(&b, f, fieldwidth, precision, func); \ 81 else \ 82 (void)asprintf(&b, f, fieldwidth, func); \ 83 else if (haveprec) \ 84 (void)asprintf(&b, f, precision, func); \ 85 else \ 86 (void)asprintf(&b, f, func); \ 87 if (b) { \ 88 (void)fputs(b, stdout); \ 89 free(b); \ 90 } \ 91 } while (0) 92 93 static int asciicode(void); 94 static char *printf_doformat(char *, int *); 95 static int escape(char *, int, size_t *); 96 static int getchr(void); 97 static int getfloating(long double *, int); 98 static int getint(int *); 99 static int getnum(intmax_t *, uintmax_t *, int); 100 static const char 101 *getstr(void); 102 static char *mknum(char *, int); 103 static void usage(void); 104 105 static char **gargv; 106 107 int 108 #ifdef BUILTIN 109 progprintf(int argc, char *argv[]) 110 #else 111 main(int argc, char *argv[]) 112 #endif 113 { 114 size_t len; 115 int ch, chopped, end, rval; 116 char *format, *fmt, *start; 117 118 #if !defined(BUILTIN) && !defined(SHELL) 119 (void) setlocale(LC_NUMERIC, ""); 120 #endif 121 #ifdef SHELL 122 optreset = 1; optind = 1; opterr = 0; /* initialize getopt */ 123 #endif 124 while ((ch = getopt(argc, argv, "")) != -1) 125 switch (ch) { 126 case '?': 127 default: 128 usage(); 129 return (1); 130 } 131 argc -= optind; 132 argv += optind; 133 134 if (argc < 1) { 135 usage(); 136 return (1); 137 } 138 139 #ifdef SHELL 140 INTOFF; 141 #endif 142 /* 143 * Basic algorithm is to scan the format string for conversion 144 * specifications -- once one is found, find out if the field 145 * width or precision is a '*'; if it is, gather up value. Note, 146 * format strings are reused as necessary to use up the provided 147 * arguments, arguments of zero/null string are provided to use 148 * up the format string. 149 */ 150 fmt = format = *argv; 151 chopped = escape(fmt, 1, &len); /* backslash interpretation */ 152 rval = end = 0; 153 gargv = ++argv; 154 for (;;) { 155 start = fmt; 156 while (fmt < format + len) { 157 if (fmt[0] == '%') { 158 fwrite(start, 1, fmt - start, stdout); 159 if (fmt[1] == '%') { 160 /* %% prints a % */ 161 putchar('%'); 162 fmt += 2; 163 } else { 164 fmt = printf_doformat(fmt, &rval); 165 if (fmt == NULL) { 166 #ifdef SHELL 167 INTON; 168 #endif 169 return (1); 170 } 171 end = 0; 172 } 173 start = fmt; 174 } else 175 fmt++; 176 } 177 178 if (end == 1) { 179 warnx1("missing format character", NULL, NULL); 180 #ifdef SHELL 181 INTON; 182 #endif 183 return (1); 184 } 185 fwrite(start, 1, fmt - start, stdout); 186 if (chopped || !*gargv) { 187 #ifdef SHELL 188 INTON; 189 #endif 190 return (rval); 191 } 192 /* Restart at the beginning of the format string. */ 193 fmt = format; 194 end = 1; 195 } 196 /* NOTREACHED */ 197 } 198 199 200 static char * 201 printf_doformat(char *start, int *rval) 202 { 203 static const char skip1[] = "#'-+ 0"; 204 static const char skip2[] = "0123456789"; 205 char *fmt; 206 int fieldwidth, haveprec, havewidth, mod_ldbl, precision; 207 char convch, nextch; 208 209 fmt = start + 1; 210 /* skip to field width */ 211 fmt += strspn(fmt, skip1); 212 if (*fmt == '*') { 213 if (getint(&fieldwidth)) 214 return (NULL); 215 havewidth = 1; 216 ++fmt; 217 } else { 218 havewidth = 0; 219 220 /* skip to possible '.', get following precision */ 221 fmt += strspn(fmt, skip2); 222 } 223 if (*fmt == '.') { 224 /* precision present? */ 225 ++fmt; 226 if (*fmt == '*') { 227 if (getint(&precision)) 228 return (NULL); 229 haveprec = 1; 230 ++fmt; 231 } else { 232 haveprec = 0; 233 234 /* skip to conversion char */ 235 fmt += strspn(fmt, skip2); 236 } 237 } else 238 haveprec = 0; 239 if (!*fmt) { 240 warnx1("missing format character", NULL, NULL); 241 return (NULL); 242 } 243 244 /* 245 * Look for a length modifier. POSIX doesn't have these, so 246 * we only support them for floating-point conversions, which 247 * are extensions. This is useful because the L modifier can 248 * be used to gain extra range and precision, while omitting 249 * it is more likely to produce consistent results on different 250 * architectures. This is not so important for integers 251 * because overflow is the only bad thing that can happen to 252 * them, but consider the command printf %a 1.1 253 */ 254 if (*fmt == 'L') { 255 mod_ldbl = 1; 256 fmt++; 257 if (!strchr("aAeEfFgG", *fmt)) { 258 warnx2("bad modifier L for %%%c", *fmt, NULL); 259 return (NULL); 260 } 261 } else { 262 mod_ldbl = 0; 263 } 264 265 convch = *fmt; 266 nextch = *++fmt; 267 *fmt = '\0'; 268 switch (convch) { 269 case 'b': { 270 size_t len; 271 char *p; 272 int getout; 273 274 #ifdef SHELL 275 p = savestr(getstr()); 276 #else 277 p = strdup(getstr()); 278 #endif 279 if (p == NULL) { 280 warnx2("%s", strerror(ENOMEM), NULL); 281 return (NULL); 282 } 283 getout = escape(p, 0, &len); 284 *(fmt - 1) = 's'; 285 PF(start, p); 286 *(fmt - 1) = 'b'; 287 #ifdef SHELL 288 ckfree(p); 289 #else 290 free(p); 291 #endif 292 if (getout) 293 return (fmt); 294 break; 295 } 296 case 'c': { 297 char p; 298 299 p = getchr(); 300 PF(start, p); 301 break; 302 } 303 case 's': { 304 const char *p; 305 306 p = getstr(); 307 PF(start, p); 308 break; 309 } 310 case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': { 311 char *f; 312 intmax_t val; 313 uintmax_t uval; 314 int signedconv; 315 316 signedconv = (convch == 'd' || convch == 'i'); 317 if ((f = mknum(start, convch)) == NULL) 318 return (NULL); 319 if (getnum(&val, &uval, signedconv)) 320 *rval = 1; 321 if (signedconv) 322 PF(f, val); 323 else 324 PF(f, uval); 325 break; 326 } 327 case 'e': case 'E': 328 case 'f': case 'F': 329 case 'g': case 'G': 330 case 'a': case 'A': { 331 long double p; 332 333 if (getfloating(&p, mod_ldbl)) 334 *rval = 1; 335 if (mod_ldbl) 336 PF(start, p); 337 else 338 PF(start, (double)p); 339 break; 340 } 341 default: 342 warnx2("illegal format character %c", convch, NULL); 343 return (NULL); 344 } 345 *fmt = nextch; 346 return (fmt); 347 } 348 349 static char * 350 mknum(char *str, int ch) 351 { 352 static char *copy; 353 static size_t copy_size; 354 char *newcopy; 355 size_t len, newlen; 356 357 len = strlen(str) + 2; 358 if (len > copy_size) { 359 newlen = ((len + 1023) >> 10) << 10; 360 #ifdef SHELL 361 if ((newcopy = ckrealloc(copy, newlen)) == NULL) 362 #else 363 if ((newcopy = realloc(copy, newlen)) == NULL) 364 #endif 365 { 366 warnx2("%s", strerror(ENOMEM), NULL); 367 return (NULL); 368 } 369 copy = newcopy; 370 copy_size = newlen; 371 } 372 373 memmove(copy, str, len - 3); 374 copy[len - 3] = 'j'; 375 copy[len - 2] = ch; 376 copy[len - 1] = '\0'; 377 return (copy); 378 } 379 380 static int 381 escape(char *fmt, int percent, size_t *len) 382 { 383 char *save, *store; 384 int value, c; 385 386 for (save = store = fmt; (c = *fmt); ++fmt, ++store) { 387 if (c != '\\') { 388 *store = c; 389 continue; 390 } 391 switch (*++fmt) { 392 case '\0': /* EOS, user error */ 393 *store = '\\'; 394 *++store = '\0'; 395 *len = store - save; 396 return (0); 397 case '\\': /* backslash */ 398 case '\'': /* single quote */ 399 *store = *fmt; 400 break; 401 case 'a': /* bell/alert */ 402 *store = '\a'; 403 break; 404 case 'b': /* backspace */ 405 *store = '\b'; 406 break; 407 case 'c': 408 *store = '\0'; 409 *len = store - save; 410 return (1); 411 case 'f': /* form-feed */ 412 *store = '\f'; 413 break; 414 case 'n': /* newline */ 415 *store = '\n'; 416 break; 417 case 'r': /* carriage-return */ 418 *store = '\r'; 419 break; 420 case 't': /* horizontal tab */ 421 *store = '\t'; 422 break; 423 case 'v': /* vertical tab */ 424 *store = '\v'; 425 break; 426 /* octal constant */ 427 case '0': case '1': case '2': case '3': 428 case '4': case '5': case '6': case '7': 429 c = (!percent && *fmt == '0') ? 4 : 3; 430 for (value = 0; 431 c-- && *fmt >= '0' && *fmt <= '7'; ++fmt) { 432 value <<= 3; 433 value += *fmt - '0'; 434 } 435 --fmt; 436 if (percent && value == '%') { 437 *store++ = '%'; 438 *store = '%'; 439 } else 440 *store = value; 441 break; 442 default: 443 *store = *fmt; 444 break; 445 } 446 } 447 *store = '\0'; 448 *len = store - save; 449 return (0); 450 } 451 452 static int 453 getchr(void) 454 { 455 if (!*gargv) 456 return ('\0'); 457 return ((int)**gargv++); 458 } 459 460 static const char * 461 getstr(void) 462 { 463 if (!*gargv) 464 return (""); 465 return (*gargv++); 466 } 467 468 static int 469 getint(int *ip) 470 { 471 intmax_t val; 472 uintmax_t uval; 473 int rval; 474 475 if (getnum(&val, &uval, 1)) 476 return (1); 477 rval = 0; 478 if (val < INT_MIN || val > INT_MAX) { 479 warnx3("%s: %s", *gargv, strerror(ERANGE)); 480 rval = 1; 481 } 482 *ip = (int)val; 483 return (rval); 484 } 485 486 static int 487 getnum(intmax_t *ip, uintmax_t *uip, int signedconv) 488 { 489 char *ep; 490 int rval; 491 492 if (!*gargv) { 493 *ip = 0; 494 return (0); 495 } 496 if (**gargv == '"' || **gargv == '\'') { 497 if (signedconv) 498 *ip = asciicode(); 499 else 500 *uip = asciicode(); 501 return (0); 502 } 503 rval = 0; 504 errno = 0; 505 if (signedconv) 506 *ip = strtoimax(*gargv, &ep, 0); 507 else 508 *uip = strtoumax(*gargv, &ep, 0); 509 if (ep == *gargv) { 510 warnx2("%s: expected numeric value", *gargv, NULL); 511 rval = 1; 512 } 513 else if (*ep != '\0') { 514 warnx2("%s: not completely converted", *gargv, NULL); 515 rval = 1; 516 } 517 if (errno == ERANGE) { 518 warnx3("%s: %s", *gargv, strerror(ERANGE)); 519 rval = 1; 520 } 521 ++gargv; 522 return (rval); 523 } 524 525 static int 526 getfloating(long double *dp, int mod_ldbl) 527 { 528 char *ep; 529 int rval; 530 531 if (!*gargv) { 532 *dp = 0.0; 533 return (0); 534 } 535 if (**gargv == '"' || **gargv == '\'') { 536 *dp = asciicode(); 537 return (0); 538 } 539 rval = 0; 540 errno = 0; 541 if (mod_ldbl) 542 *dp = strtold(*gargv, &ep); 543 else 544 *dp = strtod(*gargv, &ep); 545 if (ep == *gargv) { 546 warnx2("%s: expected numeric value", *gargv, NULL); 547 rval = 1; 548 } else if (*ep != '\0') { 549 warnx2("%s: not completely converted", *gargv, NULL); 550 rval = 1; 551 } 552 if (errno == ERANGE) { 553 warnx3("%s: %s", *gargv, strerror(ERANGE)); 554 rval = 1; 555 } 556 ++gargv; 557 return (rval); 558 } 559 560 static int 561 asciicode(void) 562 { 563 int ch; 564 565 ch = **gargv; 566 if (ch == '\'' || ch == '"') 567 ch = (*gargv)[1]; 568 ++gargv; 569 return (ch); 570 } 571 572 static void 573 usage(void) 574 { 575 (void)fprintf(stderr, "usage: printf format [arguments ...]\n"); 576 } 577