VirtualBox

source: kBuild/trunk/src/kmk/kmkbuiltin/printf.c@ 3387

Last change on this file since 3387 was 3215, checked in by bird, 6 years ago

kmk_ln, kmk_mkdir, kmk_mv, kmk_printf: changed to use getopt_r and got rid of remaining static buffers.

  • Property svn:eol-style set to native
File size: 23.3 KB
Line 
1/* $NetBSD: printf.c,v 1.31 2005/03/22 23:55:46 dsl Exp $ */
2
3/*
4 * Copyright (c) 1989, 1993
5 * The Regents of the University of California. All rights reserved.
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
32/*#include <sys/cdefs.h>
33#ifndef lint
34#if !defined(BUILTIN) && !defined(SHELL)
35__COPYRIGHT("@(#) Copyright (c) 1989, 1993\n\
36 The Regents of the University of California. All rights reserved.\n");
37#endif
38#endif
39
40#ifndef lint
41#if 0
42static char sccsid[] = "@(#)printf.c 8.2 (Berkeley) 3/22/95";
43#else
44__RCSID("$NetBSD: printf.c,v 1.31 2005/03/22 23:55:46 dsl Exp $");
45#endif
46#endif*/ /* not lint */
47
48
49/*********************************************************************************************************************************
50* Header Files *
51*********************************************************************************************************************************/
52#define FAKES_NO_GETOPT_H /* bird */
53#if !defined(KMK_BUILTIN_STANDALONE) && !defined(BUILTIN) && !defined(SHELL)
54# include "../makeint.h"
55# include "../filedef.h"
56# include "../variable.h"
57#else
58# include "config.h"
59#endif
60#include <sys/types.h>
61
62#include <ctype.h>
63#include "err.h"
64#include <errno.h>
65#include <inttypes.h>
66#include <limits.h>
67#include <locale.h>
68#include <stdarg.h>
69#include <stdio.h>
70#include <stdlib.h>
71#include <string.h>
72#include <unistd.h>
73#include "getopt_r.h"
74#ifdef __sun__
75# include "solfakes.h"
76#endif
77#ifdef _MSC_VER
78# include "mscfakes.h"
79#endif
80
81#include "../kmkbuiltin.h"
82
83#ifdef KBUILD_OS_WINDOWS
84/* This is a trick to speed up console output on windows. */
85# include "console.h"
86# undef fwrite
87# define fwrite maybe_con_fwrite
88#endif
89
90#if 0
91#ifdef BUILTIN /* csh builtin */
92#define kmk_builtin_printf progprintf
93#endif
94
95#ifdef SHELL /* sh (aka ash) builtin */
96#define kmk_builtin_printf printfcmd
97#include "../../bin/sh/bltin/bltin.h"
98#endif /* SHELL */
99#endif
100
101
102/*********************************************************************************************************************************
103* Defined Constants And Macros *
104*********************************************************************************************************************************/
105#if 0 /*def __GNUC__ - bird: gcc complains about non-ISO-standard escape. */
106#define ESCAPE '\e'
107#else
108#define ESCAPE 033
109#endif
110
111#define PF(f, func) { \
112 if (fieldwidth != -1) { \
113 if (precision != -1) \
114 (void)wrap_printf(pThis, f, fieldwidth, precision, func); \
115 else \
116 (void)wrap_printf(pThis, f, fieldwidth, func); \
117 } else if (precision != -1) \
118 (void)wrap_printf(pThis, f, precision, func); \
119 else \
120 (void)wrap_printf(pThis, f, func); \
121}
122
123#define APF(cpp, f, func) { \
124 if (fieldwidth != -1) { \
125 if (precision != -1) \
126 (void)asprintf(cpp, f, fieldwidth, precision, func); \
127 else \
128 (void)asprintf(cpp, f, fieldwidth, func); \
129 } else if (precision != -1) \
130 (void)asprintf(cpp, f, precision, func); \
131 else \
132 (void)asprintf(cpp, f, func); \
133}
134
135
136/*********************************************************************************************************************************
137* Structures and Typedefs *
138*********************************************************************************************************************************/
139typedef struct PRINTFINSTANCE
140{
141 PKMKBUILTINCTX pCtx;
142 /* former globals */
143 size_t b_length;
144 char *b_fmt;
145 int rval;
146 char **gargv;
147#ifndef KMK_BUILTIN_STANDALONE
148 char *g_o;
149#endif
150 /* former function level statics in common_printf(); both need freeing. */
151 char *a, *t;
152
153 /* former function level statics in conv_expand(); needs freeing. */
154 char *conv_str;
155
156 /* Buffer the output because windows doesn't do line buffering of stdout. */
157 size_t g_cchBuf;
158 char g_achBuf[256];
159} PRINTFINSTANCE;
160typedef PRINTFINSTANCE *PPRINTFINSTANCE;
161
162
163/*********************************************************************************************************************************
164* Global Variables *
165*********************************************************************************************************************************/
166static struct option long_options[] =
167{
168 { "help", no_argument, 0, 261 },
169 { "version", no_argument, 0, 262 },
170 { 0, 0, 0, 0 },
171};
172
173
174/*********************************************************************************************************************************
175* Internal Functions *
176*********************************************************************************************************************************/
177static int common_printf(PPRINTFINSTANCE pThis, char *argv[], PKMKBUILTINCTX pCtx);
178static int common_printf_inner(PPRINTFINSTANCE pThis, char *argv[]);
179static void conv_escape_str(PPRINTFINSTANCE, char *, void (*)(PPRINTFINSTANCE, int));
180static char *conv_escape(PPRINTFINSTANCE, char *, char *);
181static const char *conv_expand(PPRINTFINSTANCE, const char *);
182static int getchr(PPRINTFINSTANCE);
183static double getdouble(PPRINTFINSTANCE);
184static int getwidth(PPRINTFINSTANCE);
185static intmax_t getintmax(PPRINTFINSTANCE);
186static uintmax_t getuintmax(PPRINTFINSTANCE);
187static char *getstr(PPRINTFINSTANCE);
188static char *mklong(PPRINTFINSTANCE, const char *, int, char[64]);
189static void check_conversion(PPRINTFINSTANCE, const char *, const char *);
190static int usage(PKMKBUILTINCTX, int);
191
192static int flush_buffer(PPRINTFINSTANCE);
193static void b_count(PPRINTFINSTANCE, int);
194static void b_output(PPRINTFINSTANCE, int);
195static int wrap_putchar(PPRINTFINSTANCE, int ch);
196static int wrap_printf(PPRINTFINSTANCE, const char *, ...);
197
198
199
200int kmk_builtin_printf(int argc, char **argv, char **envp, PKMKBUILTINCTX pCtx)
201{
202 PRINTFINSTANCE This;
203 struct getopt_state_r gos;
204 int ch;
205
206 getopt_initialize_r(&gos, argc, argv, "", long_options, envp, pCtx);
207 while ((ch = getopt_long_r(&gos, NULL)) != -1) {
208 switch (ch) {
209 case 261:
210 usage(pCtx, 0);
211 return 0;
212 case 262:
213 return kbuild_version(argv[0]);
214 case '?':
215 default:
216 return usage(pCtx, 1);
217 }
218 }
219 argc -= gos.optind;
220 argv += gos.optind;
221
222 if (argc < 1)
223 return usage(pCtx, 1);
224
225#ifndef KMK_BUILTIN_STANDALONE
226 This.g_o = NULL;
227#endif
228 return common_printf(&This, argv, pCtx);
229}
230
231#ifdef KMK_BUILTIN_STANDALONE
232int main(int argc, char **argv, char **envp)
233{
234 KMKBUILTINCTX Ctx = { "kmk_printf", NULL };
235 setlocale(LC_ALL, "");
236 return kmk_builtin_printf(argc, argv, envp, &Ctx);
237}
238#else /* KMK_BUILTIN_STANDALONE */
239/* entry point used by function.c $(printf ..,..). */
240char *kmk_builtin_func_printf(char *o, char **argv, const char *funcname)
241{
242 PRINTFINSTANCE This;
243 int rc;
244 int argc;
245
246 for (argc = 0; argv[argc] != NULL; argc++)
247 /* nothing */;
248 if (argc == 0)
249 fatal(NILF, strlen(funcname) + INTSTR_LENGTH, _("$(%s): no format string\n"), funcname);
250
251 This.g_o = o;
252 rc = common_printf(&This, argv, NULL);
253 o = This.g_o;
254
255 if (rc != 0)
256 fatal(NILF, strlen(funcname) + INTSTR_LENGTH, _("$(%s): failure rc=%d\n"), funcname, rc);
257 return o;
258}
259#endif /* KMK_BUILTIN_STANDALONE */
260
261static int common_printf(PPRINTFINSTANCE pThis, char *argv[], PKMKBUILTINCTX pCtx)
262{
263 int rc;
264
265 /* Init all but g_o. */
266 pThis->pCtx = pCtx;
267 pThis->b_length = 0;
268 pThis->b_fmt = NULL;
269 pThis->rval = 0;
270 pThis->gargv = NULL;
271 pThis->g_cchBuf = 0;
272 pThis->a = NULL;
273 pThis->t = NULL;
274 pThis->conv_str = NULL;
275
276 rc = common_printf_inner(pThis, argv);
277
278 /* Cleanup allocations. */
279 if (pThis->a) {
280 free(pThis->a);
281 pThis->a = NULL;
282 }
283 if (pThis->t) {
284 free(pThis->t);
285 pThis->t = NULL;
286 }
287 if (pThis->conv_str) {
288 free(pThis->conv_str);
289 pThis->conv_str = NULL;
290 }
291 return rc;
292}
293
294static int common_printf_inner(PPRINTFINSTANCE pThis, char *argv[])
295{
296 char *fmt, *start;
297 int fieldwidth, precision;
298 char nextch;
299 char *format;
300 int ch;
301 char longbuf[64];
302
303 format = *argv;
304 pThis->gargv = ++argv;
305
306#define SKIP1 "#-+ 0"
307#define SKIP2 "*0123456789"
308 do {
309 /*
310 * Basic algorithm is to scan the format string for conversion
311 * specifications -- once one is found, find out if the field
312 * width or precision is a '*'; if it is, gather up value.
313 * Note, format strings are reused as necessary to use up the
314 * provided arguments, arguments of zero/null string are
315 * provided to use up the format string.
316 */
317
318 /* find next format specification */
319 for (fmt = format; (ch = *fmt++) != '\0';) {
320 if (ch == '\\') {
321 char c_ch;
322 fmt = conv_escape(pThis, fmt, &c_ch);
323 wrap_putchar(pThis, c_ch);
324 continue;
325 }
326 if (ch != '%' || (*fmt == '%' && ++fmt)) {
327 (void)wrap_putchar(pThis, ch);
328 continue;
329 }
330
331 /* Ok - we've found a format specification,
332 Save its address for a later printf(). */
333 start = fmt - 1;
334
335 /* skip to field width */
336 fmt += strspn(fmt, SKIP1);
337 fieldwidth = *fmt == '*' ? getwidth(pThis) : -1;
338
339 /* skip to possible '.', get following precision */
340 fmt += strspn(fmt, SKIP2);
341 if (*fmt == '.')
342 ++fmt;
343 precision = *fmt == '*' ? getwidth(pThis) : -1;
344
345 fmt += strspn(fmt, SKIP2);
346
347 ch = *fmt;
348 if (!ch) {
349 flush_buffer(pThis);
350 warnx(pThis->pCtx, "missing format character");
351 return (1);
352 }
353 /* null terminate format string to we can use it
354 as an argument to printf. */
355 nextch = fmt[1];
356 fmt[1] = 0;
357 switch (ch) {
358
359 case 'B': {
360 const char *p = conv_expand(pThis, getstr(pThis));
361 *fmt = 's';
362 PF(start, p);
363 break;
364 }
365 case 'b': {
366 /* There has to be a better way to do this,
367 * but the string we generate might have
368 * embedded nulls. */
369 char *cp = getstr(pThis);
370 /* Free on entry in case shell longjumped out */
371 if (pThis->a != NULL) {
372 free(pThis->a);
373 pThis->a = NULL;
374 }
375 if (pThis->t != NULL) {
376 free(pThis->t);
377 pThis->t = NULL;
378 }
379 /* Count number of bytes we want to output */
380 pThis->b_length = 0;
381 conv_escape_str(pThis, cp, b_count);
382 pThis->t = malloc(pThis->b_length + 1);
383 if (pThis->t == NULL)
384 break;
385 memset(pThis->t, 'x', pThis->b_length);
386 pThis->t[pThis->b_length] = 0;
387 /* Get printf to calculate the lengths */
388 *fmt = 's';
389 APF(&pThis->a, start, pThis->t);
390 pThis->b_fmt = pThis->a;
391 /* Output leading spaces and data bytes */
392 conv_escape_str(pThis, cp, b_output);
393 /* Add any trailing spaces */
394 wrap_printf(pThis, "%s", pThis->b_fmt);
395 break;
396 }
397 case 'c': {
398 char p = getchr(pThis);
399 PF(start, p);
400 break;
401 }
402 case 's': {
403 char *p = getstr(pThis);
404 PF(start, p);
405 break;
406 }
407 case 'd':
408 case 'i': {
409 intmax_t p = getintmax(pThis);
410 char *f = mklong(pThis, start, ch, longbuf);
411 PF(f, p);
412 break;
413 }
414 case 'o':
415 case 'u':
416 case 'x':
417 case 'X': {
418 uintmax_t p = getuintmax(pThis);
419 char *f = mklong(pThis, start, ch, longbuf);
420 PF(f, p);
421 break;
422 }
423 case 'e':
424 case 'E':
425 case 'f':
426 case 'g':
427 case 'G': {
428 double p = getdouble(pThis);
429 PF(start, p);
430 break;
431 }
432 default:
433 flush_buffer(pThis);
434 warnx(pThis->pCtx, "%s: invalid directive", start);
435 return 1;
436 }
437 *fmt++ = ch;
438 *fmt = nextch;
439 /* escape if a \c was encountered */
440 if (pThis->rval & 0x100) {
441 flush_buffer(pThis);
442 return pThis->rval & ~0x100;
443 }
444 }
445 } while (pThis->gargv != argv && *pThis->gargv);
446
447 flush_buffer(pThis);
448 return pThis->rval;
449}
450
451
452/* helper functions for conv_escape_str */
453
454static void
455/*ARGSUSED*/
456b_count(PPRINTFINSTANCE pThis, int ch)
457{
458 pThis->b_length++;
459 (void)ch;
460}
461
462/* Output one converted character for every 'x' in the 'format' */
463
464static void
465b_output(PPRINTFINSTANCE pThis, int ch)
466{
467 for (;;) {
468 switch (*pThis->b_fmt++) {
469 case 0:
470 pThis->b_fmt--;
471 return;
472 case ' ':
473 wrap_putchar(pThis, ' ');
474 break;
475 default:
476 wrap_putchar(pThis, ch);
477 return;
478 }
479 }
480}
481
482static int wrap_putchar(PPRINTFINSTANCE pThis, int ch)
483{
484#ifndef KMK_BUILTIN_STANDALONE
485 if (pThis->g_o) {
486 char sz[2];
487 sz[0] = ch; sz[1] = '\0';
488 pThis->g_o = variable_buffer_output(pThis->g_o, sz, 1);
489 }
490 else
491#endif
492 /* Buffered output. */
493 if (pThis->g_cchBuf + 1 < sizeof(pThis->g_achBuf)) {
494 pThis->g_achBuf[pThis->g_cchBuf++] = ch;
495 } else {
496 int rc = flush_buffer(pThis);
497 pThis->g_achBuf[pThis->g_cchBuf++] = ch;
498 if (rc)
499 return -1;
500 }
501 return 0;
502}
503
504static int wrap_printf(PPRINTFINSTANCE pThis, const char * fmt, ...)
505{
506 ssize_t cchRet;
507 va_list va;
508 char *pszTmp;
509
510 va_start(va, fmt);
511 cchRet = vasprintf(&pszTmp, fmt, va);
512 va_end(va);
513 if (cchRet >= 0) {
514#ifndef KMK_BUILTIN_STANDALONE
515 if (pThis->g_o) {
516 pThis->g_o = variable_buffer_output(pThis->g_o, pszTmp, cchRet);
517 } else
518#endif
519 {
520 if (cchRet + pThis->g_cchBuf <= sizeof(pThis->g_achBuf)) {
521 /* We've got space in the buffer. */
522 memcpy(&pThis->g_achBuf[pThis->g_cchBuf], pszTmp, cchRet);
523 pThis->g_cchBuf += cchRet;
524 } else {
525 /* Try write out complete lines. */
526 const char *pszLeft = pszTmp;
527 ssize_t cchLeft = cchRet;
528
529 while (cchLeft > 0) {
530 const char *pchNewLine = strchr(pszLeft, '\n');
531 ssize_t cchLine = pchNewLine ? pchNewLine - pszLeft + 1 : cchLeft;
532 if (pThis->g_cchBuf + cchLine <= sizeof(pThis->g_achBuf)) {
533 memcpy(&pThis->g_achBuf[pThis->g_cchBuf], pszLeft, cchLine);
534 pThis->g_cchBuf += cchLine;
535 } else {
536 if (flush_buffer(pThis) < 0) {
537 return -1;
538 }
539#ifndef KMK_BUILTIN_STANDALONE
540 if (output_write_text(pThis->pCtx->pOut, 0,pszLeft, cchLine) < 1)
541#else
542 if (fwrite(pszLeft, cchLine, 1, stdout) < 1)
543#endif
544
545 return -1;
546 }
547 pszLeft += cchLine;
548 cchLeft -= cchLine;
549 }
550 }
551 }
552 free(pszTmp);
553 }
554 return (int)cchRet;
555}
556
557/**
558 * Flushes the g_abBuf/g_cchBuf.
559 */
560static int flush_buffer(PPRINTFINSTANCE pThis)
561{
562 ssize_t cchToWrite = pThis->g_cchBuf;
563 if (cchToWrite > 0) {
564#ifndef KMK_BUILTIN_STANDALONE
565 ssize_t cchWritten = output_write_text(pThis->pCtx->pOut, 0, pThis->g_achBuf, cchToWrite);
566#else
567 ssize_t cchWritten = fwrite(pThis->g_achBuf, 1, cchToWrite, stdout);
568#endif
569 pThis->g_cchBuf = 0;
570 if (cchWritten >= cchToWrite) {
571 /* likely */
572 } else {
573 ssize_t off = cchWritten;
574 if (cchWritten >= 0) {
575 off = cchWritten;
576 } else if (errno == EINTR) {
577 cchWritten = 0;
578 } else {
579 return -1;
580 }
581
582 while (off < cchToWrite) {
583#ifndef KMK_BUILTIN_STANDALONE
584 cchWritten = output_write_text(pThis->pCtx->pOut, 0, &pThis->g_achBuf[off], cchToWrite - off);
585#else
586 cchWritten = fwrite(&pThis->g_achBuf[off], 1, cchToWrite - off, stdout);
587#endif
588 if (cchWritten > 0) {
589 off += cchWritten;
590 } else if (errno == EINTR) {
591 /* nothing */
592 } else {
593 return -1;
594 }
595 }
596 }
597 }
598 return 0;
599}
600
601
602
603/*
604 * Print SysV echo(1) style escape string
605 * Halts processing string if a \c escape is encountered.
606 */
607static void
608conv_escape_str(PPRINTFINSTANCE pThis, char *str, void (*do_putchar)(PPRINTFINSTANCE, int))
609{
610 int value;
611 int ch;
612 char c;
613
614 while ((ch = *str++) != '\0') {
615 if (ch != '\\') {
616 do_putchar(pThis, ch);
617 continue;
618 }
619
620 ch = *str++;
621 if (ch == 'c') {
622 /* \c as in SYSV echo - abort all processing.... */
623 pThis->rval |= 0x100;
624 break;
625 }
626
627 /*
628 * %b string octal constants are not like those in C.
629 * They start with a \0, and are followed by 0, 1, 2,
630 * or 3 octal digits.
631 */
632 if (ch == '0') {
633 int octnum = 0, i;
634 for (i = 0; i < 3; i++) {
635 if (!isdigit((unsigned char)*str) || *str > '7')
636 break;
637 octnum = (octnum << 3) | (*str++ - '0');
638 }
639 do_putchar(pThis, octnum);
640 continue;
641 }
642
643 /* \[M][^|-]C as defined by vis(3) */
644 if (ch == 'M' && *str == '-') {
645 do_putchar(pThis, 0200 | str[1]);
646 str += 2;
647 continue;
648 }
649 if (ch == 'M' && *str == '^') {
650 str++;
651 value = 0200;
652 ch = '^';
653 } else
654 value = 0;
655 if (ch == '^') {
656 ch = *str++;
657 if (ch == '?')
658 value |= 0177;
659 else
660 value |= ch & 037;
661 do_putchar(pThis, value);
662 continue;
663 }
664
665 /* Finally test for sequences valid in the format string */
666 str = conv_escape(pThis, str - 1, &c);
667 do_putchar(pThis, c);
668 }
669}
670
671/*
672 * Print "standard" escape characters
673 */
674static char *
675conv_escape(PPRINTFINSTANCE pThis, char *str, char *conv_ch)
676{
677 int value;
678 int ch;
679 char num_buf[4], *num_end;
680
681 ch = *str++;
682
683 switch (ch) {
684 case '0': case '1': case '2': case '3':
685 case '4': case '5': case '6': case '7':
686 num_buf[0] = ch;
687 ch = str[0];
688 num_buf[1] = ch;
689 num_buf[2] = ch ? str[1] : 0;
690 num_buf[3] = 0;
691 value = strtoul(num_buf, &num_end, 8);
692 str += num_end - (num_buf + 1);
693 break;
694
695 case 'x':
696 /* Hexadecimal character constants are not required to be
697 supported (by SuS v1) because there is no consistent
698 way to detect the end of the constant.
699 Supporting 2 byte constants is a compromise. */
700 ch = str[0];
701 num_buf[0] = ch;
702 num_buf[1] = ch ? str[1] : 0;
703 num_buf[2] = 0;
704 value = strtoul(num_buf, &num_end, 16);
705 str += num_end - num_buf;
706 break;
707
708 case '\\': value = '\\'; break; /* backslash */
709 case '\'': value = '\''; break; /* single quote */
710 case '"': value = '"'; break; /* double quote */
711 case 'a': value = '\a'; break; /* alert */
712 case 'b': value = '\b'; break; /* backspace */
713 case 'e': value = ESCAPE; break; /* escape */
714 case 'f': value = '\f'; break; /* form-feed */
715 case 'n': value = '\n'; break; /* newline */
716 case 'r': value = '\r'; break; /* carriage-return */
717 case 't': value = '\t'; break; /* tab */
718 case 'v': value = '\v'; break; /* vertical-tab */
719
720 default:
721 warnx(pThis->pCtx, "unknown escape sequence `\\%c'", ch);
722 pThis->rval = 1;
723 value = ch;
724 break;
725 }
726
727 *conv_ch = value;
728 return str;
729}
730
731/* expand a string so that everything is printable */
732
733static const char *
734conv_expand(PPRINTFINSTANCE pThis, const char *str)
735{
736 static const char no_memory[] = "<no memory>";
737 char *cp;
738 int ch;
739
740 if (pThis->conv_str)
741 free(pThis->conv_str);
742 /* get a buffer that is definitely large enough.... */
743 pThis->conv_str = cp = malloc(4 * strlen(str) + 1);
744 if (!cp)
745 return no_memory;
746
747 while ((ch = *(const unsigned char *)str++) != '\0') {
748 switch (ch) {
749 /* Use C escapes for expected control characters */
750 case '\\': ch = '\\'; break; /* backslash */
751 case '\'': ch = '\''; break; /* single quote */
752 case '"': ch = '"'; break; /* double quote */
753 case '\a': ch = 'a'; break; /* alert */
754 case '\b': ch = 'b'; break; /* backspace */
755 case ESCAPE: ch = 'e'; break; /* escape */
756 case '\f': ch = 'f'; break; /* form-feed */
757 case '\n': ch = 'n'; break; /* newline */
758 case '\r': ch = 'r'; break; /* carriage-return */
759 case '\t': ch = 't'; break; /* tab */
760 case '\v': ch = 'v'; break; /* vertical-tab */
761 default:
762 /* Copy anything printable */
763 if (isprint(ch)) {
764 *cp++ = ch;
765 continue;
766 }
767 /* Use vis(3) encodings for the rest */
768 *cp++ = '\\';
769 if (ch & 0200) {
770 *cp++ = 'M';
771 ch &= ~0200;
772 }
773 if (ch == 0177) {
774 *cp++ = '^';
775 *cp++ = '?';
776 continue;
777 }
778 if (ch < 040) {
779 *cp++ = '^';
780 *cp++ = ch | 0100;
781 continue;
782 }
783 *cp++ = '-';
784 *cp++ = ch;
785 continue;
786 }
787 *cp++ = '\\';
788 *cp++ = ch;
789 }
790
791 *cp = 0;
792 return pThis->conv_str;
793}
794
795static char *
796mklong(PPRINTFINSTANCE pThis, const char *str, int ch, char copy[64])
797{
798 size_t len;
799
800 len = strlen(str) - 1;
801 if (len > 64 - 5) {
802 warnx(pThis->pCtx, "format %s too complex\n", str);
803 len = 4;
804 }
805 (void)memmove(copy, str, len);
806#ifndef _MSC_VER
807 copy[len++] = 'j';
808#else
809 copy[len++] = 'I';
810 copy[len++] = '6';
811 copy[len++] = '4';
812#endif
813 copy[len++] = ch;
814 copy[len] = '\0';
815 return copy;
816}
817
818static int
819getchr(PPRINTFINSTANCE pThis)
820{
821 if (!*pThis->gargv)
822 return 0;
823 return (int)**pThis->gargv++;
824}
825
826static char *
827getstr(PPRINTFINSTANCE pThis)
828{
829 static char empty[] = "";
830 if (!*pThis->gargv)
831 return empty;
832 return *pThis->gargv++;
833}
834
835static int
836getwidth(PPRINTFINSTANCE pThis)
837{
838 long val;
839 char *s, *ep;
840
841 s = *pThis->gargv;
842 if (!s)
843 return (0);
844 pThis->gargv++;
845
846 errno = 0;
847 val = strtoul(s, &ep, 0);
848 check_conversion(pThis, s, ep);
849
850 /* Arbitrarily 'restrict' field widths to 1Mbyte */
851 if (val < 0 || val > 1 << 20) {
852 warnx(pThis->pCtx, "%s: invalid field width", s);
853 return 0;
854 }
855
856 return val;
857}
858
859static intmax_t
860getintmax(PPRINTFINSTANCE pThis)
861{
862 intmax_t val;
863 char *cp, *ep;
864
865 cp = *pThis->gargv;
866 if (cp == NULL)
867 return 0;
868 pThis->gargv++;
869
870 if (*cp == '\"' || *cp == '\'')
871 return *(cp+1);
872
873 errno = 0;
874 val = strtoimax(cp, &ep, 0);
875 check_conversion(pThis, cp, ep);
876 return val;
877}
878
879static uintmax_t
880getuintmax(PPRINTFINSTANCE pThis)
881{
882 uintmax_t val;
883 char *cp, *ep;
884
885 cp = *pThis->gargv;
886 if (cp == NULL)
887 return 0;
888 pThis->gargv++;
889
890 if (*cp == '\"' || *cp == '\'')
891 return *(cp + 1);
892
893 /* strtoumax won't error -ve values */
894 while (isspace(*(unsigned char *)cp))
895 cp++;
896 if (*cp == '-') {
897 warnx(pThis->pCtx, "%s: expected positive numeric value", cp);
898 pThis->rval = 1;
899 return 0;
900 }
901
902 errno = 0;
903 val = strtoumax(cp, &ep, 0);
904 check_conversion(pThis, cp, ep);
905 return val;
906}
907
908static double
909getdouble(PPRINTFINSTANCE pThis)
910{
911 double val;
912 char *ep;
913 char *s;
914
915 s = *pThis->gargv;
916 if (!s)
917 return (0.0);
918 pThis->gargv++;
919
920 if (*s == '\"' || *s == '\'')
921 return (double) s[1];
922
923 errno = 0;
924 val = strtod(s, &ep);
925 check_conversion(pThis, s, ep);
926 return val;
927}
928
929static void
930check_conversion(PPRINTFINSTANCE pThis, const char *s, const char *ep)
931{
932 if (*ep) {
933 if (ep == s)
934 warnx(pThis->pCtx, "%s: expected numeric value", s);
935 else
936 warnx(pThis->pCtx, "%s: not completely converted", s);
937 pThis->rval = 1;
938 } else if (errno == ERANGE) {
939 warnx(pThis->pCtx, "%s: %s", s, strerror(ERANGE));
940 pThis->rval = 1;
941 }
942}
943
944static int
945usage(PKMKBUILTINCTX pCtx, int fIsErr)
946{
947 kmk_builtin_ctx_printf(pCtx, fIsErr,
948 "usage: %s format [arg ...]\n"
949 " or: %s --help\n"
950 " or: %s --version\n",
951 pCtx->pszProgName, pCtx->pszProgName, pCtx->pszProgName);
952 return 1;
953}
954
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use