1 /* $OpenBSD: shf.c,v 1.15 2006/04/02 00:48:33 deraadt Exp $ */ 2 3 /*- 4 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2011, 2012 5 * Thorsten Glaser <tg (at) mirbsd.org> 6 * 7 * Provided that these terms and disclaimer and all copyright notices 8 * are retained or reproduced in an accompanying document, permission 9 * is granted to deal in this work without restriction, including un- 10 * limited rights to use, publicly perform, distribute, sell, modify, 11 * merge, give away, or sublicence. 12 * 13 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to 14 * the utmost extent permitted by applicable law, neither express nor 15 * implied; without malicious intent or gross negligence. In no event 16 * may a licensor, author or contributor be held liable for indirect, 17 * direct, other damage, loss, or other issues arising in any way out 18 * of dealing in the work, even if advised of the possibility of such 19 * damage or existence of a defect, except proven that it results out 20 * of said person's immediate fault when using the work as intended. 21 *- 22 * Use %zX instead of %p and floating point isn't supported at all. 23 */ 24 25 #include "sh.h" 26 27 __RCSID("$MirOS: src/bin/mksh/shf.c,v 1.56 2013/01/01 03:32:44 tg Exp $"); 28 29 /* flags to shf_emptybuf() */ 30 #define EB_READSW 0x01 /* about to switch to reading */ 31 #define EB_GROW 0x02 /* grow buffer if necessary (STRING+DYNAMIC) */ 32 33 /* 34 * Replacement stdio routines. Stdio is too flakey on too many machines 35 * to be useful when you have multiple processes using the same underlying 36 * file descriptors. 37 */ 38 39 static int shf_fillbuf(struct shf *); 40 static int shf_emptybuf(struct shf *, int); 41 42 /* 43 * Open a file. First three args are for open(), last arg is flags for 44 * this package. Returns NULL if file could not be opened, or if a dup 45 * fails. 46 */ 47 struct shf * 48 shf_open(const char *name, int oflags, int mode, int sflags) 49 { 50 struct shf *shf; 51 ssize_t bsize = 52 /* at most 512 */ 53 sflags & SHF_UNBUF ? (sflags & SHF_RD ? 1 : 0) : SHF_BSIZE; 54 int fd; 55 56 /* Done before open so if alloca fails, fd won't be lost. */ 57 shf = alloc(sizeof(struct shf) + bsize, ATEMP); 58 shf->areap = ATEMP; 59 shf->buf = (unsigned char *)&shf[1]; 60 shf->bsize = bsize; 61 shf->flags = SHF_ALLOCS; 62 /* Rest filled in by reopen. */ 63 64 fd = open(name, oflags, mode); 65 if (fd < 0) { 66 afree(shf, shf->areap); 67 return (NULL); 68 } 69 if ((sflags & SHF_MAPHI) && fd < FDBASE) { 70 int nfd; 71 72 nfd = fcntl(fd, F_DUPFD, FDBASE); 73 close(fd); 74 if (nfd < 0) { 75 afree(shf, shf->areap); 76 return (NULL); 77 } 78 fd = nfd; 79 } 80 sflags &= ~SHF_ACCMODE; 81 sflags |= (oflags & O_ACCMODE) == O_RDONLY ? SHF_RD : 82 ((oflags & O_ACCMODE) == O_WRONLY ? SHF_WR : SHF_RDWR); 83 84 return (shf_reopen(fd, sflags, shf)); 85 } 86 87 /* helper function for shf_fdopen and shf_reopen */ 88 static void 89 shf_open_hlp(int fd, int *sflagsp, const char *where) 90 { 91 int sflags = *sflagsp; 92 93 /* use fcntl() to figure out correct read/write flags */ 94 if (sflags & SHF_GETFL) { 95 int flags = fcntl(fd, F_GETFL, 0); 96 97 if (flags < 0) 98 /* will get an error on first read/write */ 99 sflags |= SHF_RDWR; 100 else { 101 switch (flags & O_ACCMODE) { 102 case O_RDONLY: 103 sflags |= SHF_RD; 104 break; 105 case O_WRONLY: 106 sflags |= SHF_WR; 107 break; 108 case O_RDWR: 109 sflags |= SHF_RDWR; 110 break; 111 } 112 } 113 *sflagsp = sflags; 114 } 115 116 if (!(sflags & (SHF_RD | SHF_WR))) 117 internal_errorf("%s: %s", where, "missing read/write"); 118 } 119 120 /* Set up the shf structure for a file descriptor. Doesn't fail. */ 121 struct shf * 122 shf_fdopen(int fd, int sflags, struct shf *shf) 123 { 124 ssize_t bsize = 125 /* at most 512 */ 126 sflags & SHF_UNBUF ? (sflags & SHF_RD ? 1 : 0) : SHF_BSIZE; 127 128 shf_open_hlp(fd, &sflags, "shf_fdopen"); 129 if (shf) { 130 if (bsize) { 131 shf->buf = alloc(bsize, ATEMP); 132 sflags |= SHF_ALLOCB; 133 } else 134 shf->buf = NULL; 135 } else { 136 shf = alloc(sizeof(struct shf) + bsize, ATEMP); 137 shf->buf = (unsigned char *)&shf[1]; 138 sflags |= SHF_ALLOCS; 139 } 140 shf->areap = ATEMP; 141 shf->fd = fd; 142 shf->rp = shf->wp = shf->buf; 143 shf->rnleft = 0; 144 shf->rbsize = bsize; 145 shf->wnleft = 0; /* force call to shf_emptybuf() */ 146 shf->wbsize = sflags & SHF_UNBUF ? 0 : bsize; 147 shf->flags = sflags; 148 shf->errnosv = 0; 149 shf->bsize = bsize; 150 if (sflags & SHF_CLEXEC) 151 fcntl(fd, F_SETFD, FD_CLOEXEC); 152 return (shf); 153 } 154 155 /* Set up an existing shf (and buffer) to use the given fd */ 156 struct shf * 157 shf_reopen(int fd, int sflags, struct shf *shf) 158 { 159 ssize_t bsize = 160 /* at most 512 */ 161 sflags & SHF_UNBUF ? (sflags & SHF_RD ? 1 : 0) : SHF_BSIZE; 162 163 shf_open_hlp(fd, &sflags, "shf_reopen"); 164 if (!shf || !shf->buf || shf->bsize < bsize) 165 internal_errorf("%s: %s", "shf_reopen", "bad shf/buf/bsize"); 166 167 /* assumes shf->buf and shf->bsize already set up */ 168 shf->fd = fd; 169 shf->rp = shf->wp = shf->buf; 170 shf->rnleft = 0; 171 shf->rbsize = bsize; 172 shf->wnleft = 0; /* force call to shf_emptybuf() */ 173 shf->wbsize = sflags & SHF_UNBUF ? 0 : bsize; 174 shf->flags = (shf->flags & (SHF_ALLOCS | SHF_ALLOCB)) | sflags; 175 shf->errnosv = 0; 176 if (sflags & SHF_CLEXEC) 177 fcntl(fd, F_SETFD, FD_CLOEXEC); 178 return (shf); 179 } 180 181 /* 182 * Open a string for reading or writing. If reading, bsize is the number 183 * of bytes that can be read. If writing, bsize is the maximum number of 184 * bytes that can be written. If shf is not NULL, it is filled in and 185 * returned, if it is NULL, shf is allocated. If writing and buf is NULL 186 * and SHF_DYNAMIC is set, the buffer is allocated (if bsize > 0, it is 187 * used for the initial size). Doesn't fail. 188 * When writing, a byte is reserved for a trailing NUL - see shf_sclose(). 189 */ 190 struct shf * 191 shf_sopen(char *buf, ssize_t bsize, int sflags, struct shf *shf) 192 { 193 /* can't have a read+write string */ 194 if (!(!(sflags & SHF_RD) ^ !(sflags & SHF_WR))) 195 internal_errorf("%s: flags 0x%X", "shf_sopen", sflags); 196 197 if (!shf) { 198 shf = alloc(sizeof(struct shf), ATEMP); 199 sflags |= SHF_ALLOCS; 200 } 201 shf->areap = ATEMP; 202 if (!buf && (sflags & SHF_WR) && (sflags & SHF_DYNAMIC)) { 203 if (bsize <= 0) 204 bsize = 64; 205 sflags |= SHF_ALLOCB; 206 buf = alloc(bsize, shf->areap); 207 } 208 shf->fd = -1; 209 shf->buf = shf->rp = shf->wp = (unsigned char *)buf; 210 shf->rnleft = bsize; 211 shf->rbsize = bsize; 212 shf->wnleft = bsize - 1; /* space for a '\0' */ 213 shf->wbsize = bsize; 214 shf->flags = sflags | SHF_STRING; 215 shf->errnosv = 0; 216 shf->bsize = bsize; 217 218 return (shf); 219 } 220 221 /* Flush and close file descriptor, free the shf structure */ 222 int 223 shf_close(struct shf *shf) 224 { 225 int ret = 0; 226 227 if (shf->fd >= 0) { 228 ret = shf_flush(shf); 229 if (close(shf->fd) < 0) 230 ret = EOF; 231 } 232 if (shf->flags & SHF_ALLOCS) 233 afree(shf, shf->areap); 234 else if (shf->flags & SHF_ALLOCB) 235 afree(shf->buf, shf->areap); 236 237 return (ret); 238 } 239 240 /* Flush and close file descriptor, don't free file structure */ 241 int 242 shf_fdclose(struct shf *shf) 243 { 244 int ret = 0; 245 246 if (shf->fd >= 0) { 247 ret = shf_flush(shf); 248 if (close(shf->fd) < 0) 249 ret = EOF; 250 shf->rnleft = 0; 251 shf->rp = shf->buf; 252 shf->wnleft = 0; 253 shf->fd = -1; 254 } 255 256 return (ret); 257 } 258 259 /* 260 * Close a string - if it was opened for writing, it is NUL terminated; 261 * returns a pointer to the string and frees shf if it was allocated 262 * (does not free string if it was allocated). 263 */ 264 char * 265 shf_sclose(struct shf *shf) 266 { 267 unsigned char *s = shf->buf; 268 269 /* NUL terminate */ 270 if (shf->flags & SHF_WR) { 271 shf->wnleft++; 272 shf_putc('\0', shf); 273 } 274 if (shf->flags & SHF_ALLOCS) 275 afree(shf, shf->areap); 276 return ((char *)s); 277 } 278 279 /* 280 * Un-read what has been read but not examined, or write what has been 281 * buffered. Returns 0 for success, EOF for (write) error. 282 */ 283 int 284 shf_flush(struct shf *shf) 285 { 286 if (shf->flags & SHF_STRING) 287 return ((shf->flags & SHF_WR) ? EOF : 0); 288 289 if (shf->fd < 0) 290 internal_errorf("%s: %s", "shf_flush", "no fd"); 291 292 if (shf->flags & SHF_ERROR) { 293 errno = shf->errnosv; 294 return (EOF); 295 } 296 297 if (shf->flags & SHF_READING) { 298 shf->flags &= ~(SHF_EOF | SHF_READING); 299 if (shf->rnleft > 0) { 300 lseek(shf->fd, (off_t)-shf->rnleft, SEEK_CUR); 301 shf->rnleft = 0; 302 shf->rp = shf->buf; 303 } 304 return (0); 305 } else if (shf->flags & SHF_WRITING) 306 return (shf_emptybuf(shf, 0)); 307 308 return (0); 309 } 310 311 /* 312 * Write out any buffered data. If currently reading, flushes the read 313 * buffer. Returns 0 for success, EOF for (write) error. 314 */ 315 static int 316 shf_emptybuf(struct shf *shf, int flags) 317 { 318 int ret = 0; 319 320 if (!(shf->flags & SHF_STRING) && shf->fd < 0) 321 internal_errorf("%s: %s", "shf_emptybuf", "no fd"); 322 323 if (shf->flags & SHF_ERROR) { 324 errno = shf->errnosv; 325 return (EOF); 326 } 327 328 if (shf->flags & SHF_READING) { 329 if (flags & EB_READSW) 330 /* doesn't happen */ 331 return (0); 332 ret = shf_flush(shf); 333 shf->flags &= ~SHF_READING; 334 } 335 if (shf->flags & SHF_STRING) { 336 unsigned char *nbuf; 337 338 /* 339 * Note that we assume SHF_ALLOCS is not set if 340 * SHF_ALLOCB is set... (changing the shf pointer could 341 * cause problems) 342 */ 343 if (!(flags & EB_GROW) || !(shf->flags & SHF_DYNAMIC) || 344 !(shf->flags & SHF_ALLOCB)) 345 return (EOF); 346 /* allocate more space for buffer */ 347 nbuf = aresize2(shf->buf, 2, shf->wbsize, shf->areap); 348 shf->rp = nbuf + (shf->rp - shf->buf); 349 shf->wp = nbuf + (shf->wp - shf->buf); 350 shf->rbsize += shf->wbsize; 351 shf->wnleft += shf->wbsize; 352 shf->wbsize <<= 1; 353 shf->buf = nbuf; 354 } else { 355 if (shf->flags & SHF_WRITING) { 356 ssize_t n, ntowrite = shf->wp - shf->buf; 357 unsigned char *buf = shf->buf; 358 359 while (ntowrite > 0) { 360 n = write(shf->fd, buf, ntowrite); 361 if (n < 0) { 362 if (errno == EINTR && 363 !(shf->flags & SHF_INTERRUPT)) 364 continue; 365 shf->flags |= SHF_ERROR; 366 shf->errnosv = errno; 367 shf->wnleft = 0; 368 if (buf != shf->buf) { 369 /* 370 * allow a second flush 371 * to work 372 */ 373 memmove(shf->buf, buf, 374 ntowrite); 375 shf->wp = shf->buf + ntowrite; 376 } 377 return (EOF); 378 } 379 buf += n; 380 ntowrite -= n; 381 } 382 if (flags & EB_READSW) { 383 shf->wp = shf->buf; 384 shf->wnleft = 0; 385 shf->flags &= ~SHF_WRITING; 386 return (0); 387 } 388 } 389 shf->wp = shf->buf; 390 shf->wnleft = shf->wbsize; 391 } 392 shf->flags |= SHF_WRITING; 393 394 return (ret); 395 } 396 397 /* Fill up a read buffer. Returns EOF for a read error, 0 otherwise. */ 398 static int 399 shf_fillbuf(struct shf *shf) 400 { 401 ssize_t n; 402 403 if (shf->flags & SHF_STRING) 404 return (0); 405 406 if (shf->fd < 0) 407 internal_errorf("%s: %s", "shf_fillbuf", "no fd"); 408 409 if (shf->flags & (SHF_EOF | SHF_ERROR)) { 410 if (shf->flags & SHF_ERROR) 411 errno = shf->errnosv; 412 return (EOF); 413 } 414 415 if ((shf->flags & SHF_WRITING) && shf_emptybuf(shf, EB_READSW) == EOF) 416 return (EOF); 417 418 shf->flags |= SHF_READING; 419 420 shf->rp = shf->buf; 421 while (/* CONSTCOND */ 1) { 422 n = blocking_read(shf->fd, (char *)shf->buf, shf->rbsize); 423 if (n < 0 && errno == EINTR && !(shf->flags & SHF_INTERRUPT)) 424 continue; 425 break; 426 } 427 if (n < 0) { 428 shf->flags |= SHF_ERROR; 429 shf->errnosv = errno; 430 shf->rnleft = 0; 431 shf->rp = shf->buf; 432 return (EOF); 433 } 434 if ((shf->rnleft = n) == 0) 435 shf->flags |= SHF_EOF; 436 return (0); 437 } 438 439 /* 440 * Read a buffer from shf. Returns the number of bytes read into buf, if 441 * no bytes were read, returns 0 if end of file was seen, EOF if a read 442 * error occurred. 443 */ 444 ssize_t 445 shf_read(char *buf, ssize_t bsize, struct shf *shf) 446 { 447 ssize_t ncopy, orig_bsize = bsize; 448 449 if (!(shf->flags & SHF_RD)) 450 internal_errorf("%s: flags 0x%X", "shf_read", shf->flags); 451 452 if (bsize <= 0) 453 internal_errorf("%s: %s %zd", "shf_write", "bsize", bsize); 454 455 while (bsize > 0) { 456 if (shf->rnleft == 0 && 457 (shf_fillbuf(shf) == EOF || shf->rnleft == 0)) 458 break; 459 ncopy = shf->rnleft; 460 if (ncopy > bsize) 461 ncopy = bsize; 462 memcpy(buf, shf->rp, ncopy); 463 buf += ncopy; 464 bsize -= ncopy; 465 shf->rp += ncopy; 466 shf->rnleft -= ncopy; 467 } 468 /* Note: fread(3S) returns 0 for errors - this doesn't */ 469 return (orig_bsize == bsize ? (shf_error(shf) ? EOF : 0) : 470 orig_bsize - bsize); 471 } 472 473 /* 474 * Read up to a newline or EOF. The newline is put in buf; buf is always 475 * NUL terminated. Returns NULL on read error or if nothing was read 476 * before end of file, returns a pointer to the NUL byte in buf 477 * otherwise. 478 */ 479 char * 480 shf_getse(char *buf, ssize_t bsize, struct shf *shf) 481 { 482 unsigned char *end; 483 ssize_t ncopy; 484 char *orig_buf = buf; 485 486 if (!(shf->flags & SHF_RD)) 487 internal_errorf("%s: flags 0x%X", "shf_getse", shf->flags); 488 489 if (bsize <= 0) 490 return (NULL); 491 492 /* save room for NUL */ 493 --bsize; 494 do { 495 if (shf->rnleft == 0) { 496 if (shf_fillbuf(shf) == EOF) 497 return (NULL); 498 if (shf->rnleft == 0) { 499 *buf = '\0'; 500 return (buf == orig_buf ? NULL : buf); 501 } 502 } 503 end = (unsigned char *)memchr((char *)shf->rp, '\n', 504 shf->rnleft); 505 ncopy = end ? end - shf->rp + 1 : shf->rnleft; 506 if (ncopy > bsize) 507 ncopy = bsize; 508 memcpy(buf, (char *) shf->rp, ncopy); 509 shf->rp += ncopy; 510 shf->rnleft -= ncopy; 511 buf += ncopy; 512 bsize -= ncopy; 513 } while (!end && bsize); 514 *buf = '\0'; 515 return (buf); 516 } 517 518 /* Returns the char read. Returns EOF for error and end of file. */ 519 int 520 shf_getchar(struct shf *shf) 521 { 522 if (!(shf->flags & SHF_RD)) 523 internal_errorf("%s: flags 0x%X", "shf_getchar", shf->flags); 524 525 if (shf->rnleft == 0 && (shf_fillbuf(shf) == EOF || shf->rnleft == 0)) 526 return (EOF); 527 --shf->rnleft; 528 return (*shf->rp++); 529 } 530 531 /* 532 * Put a character back in the input stream. Returns the character if 533 * successful, EOF if there is no room. 534 */ 535 int 536 shf_ungetc(int c, struct shf *shf) 537 { 538 if (!(shf->flags & SHF_RD)) 539 internal_errorf("%s: flags 0x%X", "shf_ungetc", shf->flags); 540 541 if ((shf->flags & SHF_ERROR) || c == EOF || 542 (shf->rp == shf->buf && shf->rnleft)) 543 return (EOF); 544 545 if ((shf->flags & SHF_WRITING) && shf_emptybuf(shf, EB_READSW) == EOF) 546 return (EOF); 547 548 if (shf->rp == shf->buf) 549 shf->rp = shf->buf + shf->rbsize; 550 if (shf->flags & SHF_STRING) { 551 /* 552 * Can unget what was read, but not something different; 553 * we don't want to modify a string. 554 */ 555 if ((int)(shf->rp[-1]) != c) 556 return (EOF); 557 shf->flags &= ~SHF_EOF; 558 shf->rp--; 559 shf->rnleft++; 560 return (c); 561 } 562 shf->flags &= ~SHF_EOF; 563 *--(shf->rp) = c; 564 shf->rnleft++; 565 return (c); 566 } 567 568 /* 569 * Write a character. Returns the character if successful, EOF if the 570 * char could not be written. 571 */ 572 int 573 shf_putchar(int c, struct shf *shf) 574 { 575 if (!(shf->flags & SHF_WR)) 576 internal_errorf("%s: flags 0x%X", "shf_putchar", shf->flags); 577 578 if (c == EOF) 579 return (EOF); 580 581 if (shf->flags & SHF_UNBUF) { 582 unsigned char cc = (unsigned char)c; 583 ssize_t n; 584 585 if (shf->fd < 0) 586 internal_errorf("%s: %s", "shf_putchar", "no fd"); 587 if (shf->flags & SHF_ERROR) { 588 errno = shf->errnosv; 589 return (EOF); 590 } 591 while ((n = write(shf->fd, &cc, 1)) != 1) 592 if (n < 0) { 593 if (errno == EINTR && 594 !(shf->flags & SHF_INTERRUPT)) 595 continue; 596 shf->flags |= SHF_ERROR; 597 shf->errnosv = errno; 598 return (EOF); 599 } 600 } else { 601 /* Flush deals with strings and sticky errors */ 602 if (shf->wnleft == 0 && shf_emptybuf(shf, EB_GROW) == EOF) 603 return (EOF); 604 shf->wnleft--; 605 *shf->wp++ = c; 606 } 607 608 return (c); 609 } 610 611 /* 612 * Write a string. Returns the length of the string if successful, EOF 613 * if the string could not be written. 614 */ 615 ssize_t 616 shf_puts(const char *s, struct shf *shf) 617 { 618 if (!s) 619 return (EOF); 620 621 return (shf_write(s, strlen(s), shf)); 622 } 623 624 /* Write a buffer. Returns nbytes if successful, EOF if there is an error. */ 625 ssize_t 626 shf_write(const char *buf, ssize_t nbytes, struct shf *shf) 627 { 628 ssize_t n, ncopy, orig_nbytes = nbytes; 629 630 if (!(shf->flags & SHF_WR)) 631 internal_errorf("%s: flags 0x%X", "shf_write", shf->flags); 632 633 if (nbytes < 0) 634 internal_errorf("%s: %s %zd", "shf_write", "nbytes", nbytes); 635 636 /* Don't buffer if buffer is empty and we're writting a large amount. */ 637 if ((ncopy = shf->wnleft) && 638 (shf->wp != shf->buf || nbytes < shf->wnleft)) { 639 if (ncopy > nbytes) 640 ncopy = nbytes; 641 memcpy(shf->wp, buf, ncopy); 642 nbytes -= ncopy; 643 buf += ncopy; 644 shf->wp += ncopy; 645 shf->wnleft -= ncopy; 646 } 647 if (nbytes > 0) { 648 if (shf->flags & SHF_STRING) { 649 /* resize buffer until there's enough space left */ 650 while (nbytes > shf->wnleft) 651 if (shf_emptybuf(shf, EB_GROW) == EOF) 652 return (EOF); 653 /* then write everything into the buffer */ 654 } else { 655 /* flush deals with sticky errors */ 656 if (shf_emptybuf(shf, EB_GROW) == EOF) 657 return (EOF); 658 /* write chunks larger than window size directly */ 659 if (nbytes > shf->wbsize) { 660 ncopy = nbytes; 661 if (shf->wbsize) 662 ncopy -= nbytes % shf->wbsize; 663 nbytes -= ncopy; 664 while (ncopy > 0) { 665 n = write(shf->fd, buf, ncopy); 666 if (n < 0) { 667 if (errno == EINTR && 668 !(shf->flags & SHF_INTERRUPT)) 669 continue; 670 shf->flags |= SHF_ERROR; 671 shf->errnosv = errno; 672 shf->wnleft = 0; 673 /* 674 * Note: fwrite(3) returns 0 675 * for errors - this doesn't 676 */ 677 return (EOF); 678 } 679 buf += n; 680 ncopy -= n; 681 } 682 } 683 /* ... and buffer the rest */ 684 } 685 if (nbytes > 0) { 686 /* write remaining bytes to buffer */ 687 memcpy(shf->wp, buf, nbytes); 688 shf->wp += nbytes; 689 shf->wnleft -= nbytes; 690 } 691 } 692 693 return (orig_nbytes); 694 } 695 696 ssize_t 697 shf_fprintf(struct shf *shf, const char *fmt, ...) 698 { 699 va_list args; 700 ssize_t n; 701 702 va_start(args, fmt); 703 n = shf_vfprintf(shf, fmt, args); 704 va_end(args); 705 706 return (n); 707 } 708 709 ssize_t 710 shf_snprintf(char *buf, ssize_t bsize, const char *fmt, ...) 711 { 712 struct shf shf; 713 va_list args; 714 ssize_t n; 715 716 if (!buf || bsize <= 0) 717 internal_errorf("shf_snprintf: buf %zX, bsize %zd", 718 (size_t)buf, bsize); 719 720 shf_sopen(buf, bsize, SHF_WR, &shf); 721 va_start(args, fmt); 722 n = shf_vfprintf(&shf, fmt, args); 723 va_end(args); 724 /* NUL terminates */ 725 shf_sclose(&shf); 726 return (n); 727 } 728 729 char * 730 shf_smprintf(const char *fmt, ...) 731 { 732 struct shf shf; 733 va_list args; 734 735 shf_sopen(NULL, 0, SHF_WR|SHF_DYNAMIC, &shf); 736 va_start(args, fmt); 737 shf_vfprintf(&shf, fmt, args); 738 va_end(args); 739 /* NUL terminates */ 740 return (shf_sclose(&shf)); 741 } 742 743 #define BUF_SIZE 128 744 745 #define FL_HASH 0x001 /* '#' seen */ 746 #define FL_PLUS 0x002 /* '+' seen */ 747 #define FL_RIGHT 0x004 /* '-' seen */ 748 #define FL_BLANK 0x008 /* ' ' seen */ 749 #define FL_SHORT 0x010 /* 'h' seen */ 750 #define FL_LONG 0x020 /* 'l' seen */ 751 #define FL_ZERO 0x040 /* '0' seen */ 752 #define FL_DOT 0x080 /* '.' seen */ 753 #define FL_UPPER 0x100 /* format character was uppercase */ 754 #define FL_NUMBER 0x200 /* a number was formated %[douxefg] */ 755 #define FL_SIZET 0x400 /* 'z' seen */ 756 #define FM_SIZES 0x430 /* h/l/z mask */ 757 758 ssize_t 759 shf_vfprintf(struct shf *shf, const char *fmt, va_list args) 760 { 761 const char *s; 762 char c, *cp; 763 int tmp = 0, flags; 764 ssize_t field, precision, len; 765 unsigned long lnum; 766 /* %#o produces the longest output */ 767 char numbuf[(8 * sizeof(long) + 2) / 3 + 1 768 #ifdef DEBUG 769 /* a NUL for LLVM/Clang scan-build */ 770 + 1 771 #endif 772 ]; 773 /* this stuff for dealing with the buffer */ 774 ssize_t nwritten = 0; 775 776 #define VA(type) va_arg(args, type) 777 778 if (!fmt) 779 return (0); 780 781 while ((c = *fmt++)) { 782 if (c != '%') { 783 shf_putc(c, shf); 784 nwritten++; 785 continue; 786 } 787 /* 788 * This will accept flags/fields in any order - not just 789 * the order specified in printf(3), but this is the way 790 * _doprnt() seems to work (on BSD and SYSV). The only 791 * restriction is that the format character must come 792 * last :-). 793 */ 794 flags = 0; 795 field = precision = 0; 796 for ( ; (c = *fmt++) ; ) { 797 switch (c) { 798 case '#': 799 flags |= FL_HASH; 800 continue; 801 802 case '+': 803 flags |= FL_PLUS; 804 continue; 805 806 case '-': 807 flags |= FL_RIGHT; 808 continue; 809 810 case ' ': 811 flags |= FL_BLANK; 812 continue; 813 814 case '0': 815 if (!(flags & FL_DOT)) 816 flags |= FL_ZERO; 817 continue; 818 819 case '.': 820 flags |= FL_DOT; 821 precision = 0; 822 continue; 823 824 case '*': 825 tmp = VA(int); 826 if (flags & FL_DOT) 827 precision = tmp; 828 else if ((field = tmp) < 0) { 829 field = -field; 830 flags |= FL_RIGHT; 831 } 832 continue; 833 834 case 'l': 835 flags &= ~FM_SIZES; 836 flags |= FL_LONG; 837 continue; 838 839 case 'h': 840 flags &= ~FM_SIZES; 841 flags |= FL_SHORT; 842 continue; 843 844 case 'z': 845 flags &= ~FM_SIZES; 846 flags |= FL_SIZET; 847 continue; 848 } 849 if (ksh_isdigit(c)) { 850 bool overflowed = false; 851 852 tmp = c - '0'; 853 while (c = *fmt++, ksh_isdigit(c)) { 854 if (notok2mul(2147483647, tmp, 10)) 855 overflowed = true; 856 tmp = tmp * 10 + c - '0'; 857 } 858 --fmt; 859 if (overflowed) 860 tmp = 0; 861 if (flags & FL_DOT) 862 precision = tmp; 863 else 864 field = tmp; 865 continue; 866 } 867 break; 868 } 869 870 if (precision < 0) 871 precision = 0; 872 873 if (!c) 874 /* nasty format */ 875 break; 876 877 if (c >= 'A' && c <= 'Z') { 878 flags |= FL_UPPER; 879 c = ksh_tolower(c); 880 } 881 882 switch (c) { 883 case 'd': 884 case 'i': 885 if (flags & FL_SIZET) 886 lnum = (long)VA(ssize_t); 887 else if (flags & FL_LONG) 888 lnum = VA(long); 889 else if (flags & FL_SHORT) 890 lnum = (long)(short)VA(int); 891 else 892 lnum = (long)VA(int); 893 goto integral; 894 895 case 'o': 896 case 'u': 897 case 'x': 898 if (flags & FL_SIZET) 899 lnum = VA(size_t); 900 else if (flags & FL_LONG) 901 lnum = VA(unsigned long); 902 else if (flags & FL_SHORT) 903 lnum = (unsigned long)(unsigned short)VA(int); 904 else 905 lnum = (unsigned long)VA(unsigned int); 906 907 integral: 908 flags |= FL_NUMBER; 909 cp = numbuf + sizeof(numbuf); 910 #ifdef DEBUG 911 /* 912 * this is necessary so Clang 3.2 realises 913 * utf_skipcols/shf_putc in the output loop 914 * terminate; these values are always ASCII 915 * so an out-of-bounds access cannot happen 916 * but Clang doesn't know that 917 */ 918 *--cp = '\0'; 919 #endif 920 921 switch (c) { 922 case 'd': 923 case 'i': 924 if (0 > (long)lnum) { 925 lnum = -(long)lnum; 926 tmp = 1; 927 } else 928 tmp = 0; 929 /* FALLTHROUGH */ 930 case 'u': 931 do { 932 *--cp = lnum % 10 + '0'; 933 lnum /= 10; 934 } while (lnum); 935 936 if (c != 'u') { 937 if (tmp) 938 *--cp = '-'; 939 else if (flags & FL_PLUS) 940 *--cp = '+'; 941 else if (flags & FL_BLANK) 942 *--cp = ' '; 943 } 944 break; 945 946 case 'o': 947 do { 948 *--cp = (lnum & 0x7) + '0'; 949 lnum >>= 3; 950 } while (lnum); 951 952 if ((flags & FL_HASH) && *cp != '0') 953 *--cp = '0'; 954 break; 955 956 case 'x': { 957 const char *digits = (flags & FL_UPPER) ? 958 digits_uc : digits_lc; 959 do { 960 *--cp = digits[lnum & 0xf]; 961 lnum >>= 4; 962 } while (lnum); 963 964 if (flags & FL_HASH) { 965 *--cp = (flags & FL_UPPER) ? 'X' : 'x'; 966 *--cp = '0'; 967 } 968 } 969 } 970 len = numbuf + sizeof(numbuf) - (s = cp); 971 #ifdef DEBUG 972 /* see above comment for Clang 3.2 */ 973 --len; 974 #endif 975 if (flags & FL_DOT) { 976 if (precision > len) { 977 field = precision; 978 flags |= FL_ZERO; 979 } else 980 /* no loss */ 981 precision = len; 982 } 983 break; 984 985 case 's': 986 if ((s = VA(const char *)) == NULL) 987 s = "(null)"; 988 len = utf_mbswidth(s); 989 break; 990 991 case 'c': 992 flags &= ~FL_DOT; 993 c = (char)(VA(int)); 994 /* FALLTHROUGH */ 995 996 case '%': 997 default: 998 numbuf[0] = c; 999 numbuf[1] = 0; 1000 s = numbuf; 1001 len = 1; 1002 break; 1003 } 1004 1005 /* 1006 * At this point s should point to a string that is to be 1007 * formatted, and len should be the length of the string. 1008 */ 1009 if (!(flags & FL_DOT) || len < precision) 1010 precision = len; 1011 if (field > precision) { 1012 field -= precision; 1013 if (!(flags & FL_RIGHT)) { 1014 field = -field; 1015 /* skip past sign or 0x when padding with 0 */ 1016 if ((flags & FL_ZERO) && (flags & FL_NUMBER)) { 1017 if (*s == '+' || *s == '-' || 1018 *s == ' ') { 1019 shf_putc(*s, shf); 1020 s++; 1021 precision--; 1022 nwritten++; 1023 } else if (*s == '0') { 1024 shf_putc(*s, shf); 1025 s++; 1026 nwritten++; 1027 if (--precision > 0 && 1028 (*s | 0x20) == 'x') { 1029 shf_putc(*s, shf); 1030 s++; 1031 precision--; 1032 nwritten++; 1033 } 1034 } 1035 c = '0'; 1036 } else 1037 c = flags & FL_ZERO ? '0' : ' '; 1038 if (field < 0) { 1039 nwritten += -field; 1040 for ( ; field < 0 ; field++) 1041 shf_putc(c, shf); 1042 } 1043 } else 1044 c = ' '; 1045 } else 1046 field = 0; 1047 1048 if (precision > 0) { 1049 const char *q; 1050 1051 nwritten += precision; 1052 q = utf_skipcols(s, precision); 1053 do { 1054 shf_putc(*s, shf); 1055 } while (++s < q); 1056 } 1057 if (field > 0) { 1058 nwritten += field; 1059 for ( ; field > 0 ; --field) 1060 shf_putc(c, shf); 1061 } 1062 } 1063 1064 return (shf_error(shf) ? EOF : nwritten); 1065 } 1066 1067 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST) 1068 int 1069 shf_getc(struct shf *shf) 1070 { 1071 return (shf_getc_i(shf)); 1072 } 1073 1074 int 1075 shf_putc(int c, struct shf *shf) 1076 { 1077 return (shf_putc_i(c, shf)); 1078 } 1079 #endif 1080 1081 #ifdef DEBUG 1082 const char * 1083 cstrerror(int errnum) 1084 { 1085 #undef strerror 1086 return (strerror(errnum)); 1087 #define strerror dontuse_strerror /* poisoned */ 1088 } 1089 #elif !HAVE_STRERROR 1090 1091 #if HAVE_SYS_ERRLIST 1092 #if !HAVE_SYS_ERRLIST_DECL 1093 extern const int sys_nerr; 1094 extern const char * const sys_errlist[]; 1095 #endif 1096 #endif 1097 1098 const char * 1099 cstrerror(int errnum) 1100 { 1101 /* "Unknown error: " + sign + rough estimate + NUL */ 1102 static char errbuf[15 + 1 + (8 * sizeof(int) + 2) / 3 + 1]; 1103 1104 #if HAVE_SYS_ERRLIST 1105 if (errnum > 0 && errnum < sys_nerr && sys_errlist[errnum]) 1106 return (sys_errlist[errnum]); 1107 #endif 1108 1109 switch (errnum) { 1110 case 0: 1111 return ("Undefined error: 0"); 1112 #ifdef EPERM 1113 case EPERM: 1114 return ("Operation not permitted"); 1115 #endif 1116 #ifdef ENOENT 1117 case ENOENT: 1118 return ("No such file or directory"); 1119 #endif 1120 #ifdef ESRCH 1121 case ESRCH: 1122 return ("No such process"); 1123 #endif 1124 #ifdef E2BIG 1125 case E2BIG: 1126 return ("Argument list too long"); 1127 #endif 1128 #ifdef ENOEXEC 1129 case ENOEXEC: 1130 return ("Exec format error"); 1131 #endif 1132 #ifdef ENOMEM 1133 case ENOMEM: 1134 return ("Cannot allocate memory"); 1135 #endif 1136 #ifdef EACCES 1137 case EACCES: 1138 return ("Permission denied"); 1139 #endif 1140 #ifdef ENOTDIR 1141 case ENOTDIR: 1142 return ("Not a directory"); 1143 #endif 1144 #ifdef EINVAL 1145 case EINVAL: 1146 return ("Invalid argument"); 1147 #endif 1148 #ifdef ELOOP 1149 case ELOOP: 1150 return ("Too many levels of symbolic links"); 1151 #endif 1152 default: 1153 shf_snprintf(errbuf, sizeof(errbuf), 1154 "Unknown error: %d", errnum); 1155 return (errbuf); 1156 } 1157 } 1158 #endif 1159