/** * @file printf.c * @brief The `printf` builtin and the backslash-escape writer shared with * `echo` and `print`. */ #include #include #include #include #include #include #include #include "exec.h" /** * @brief Write a string, interpreting backslash escapes. * * In echo style (`echo`, `print`, and printf's `%b`) an octal escape is * `\0ooo` and `\c` stops all output. In format style an octal escape is * `\ooo`. * * @param o The output. * @param s The string. * @param echo_style Which rules apply. * @return false if `\c` was seen: the caller prints nothing more. */ bool out_escaped(output *o, const char *s, bool echo_style) { for (; *s; s++) { if (*s != '\\') { out_putc(o, *s); continue; } s++; switch (*s) { case 'a': out_putc(o, '\a'); break; case 'b': out_putc(o, '\b'); break; case 'f': out_putc(o, '\f'); break; case 'n': out_putc(o, '\n'); break; case 'r': out_putc(o, '\r'); break; case 't': out_putc(o, '\t'); break; case 'v': out_putc(o, '\v'); break; case '\\': out_putc(o, '\\'); break; case '\0': out_putc(o, '\\'); return true; case 'c': if (echo_style) return false; out_puts(o, "\\c"); break; default: if (*s >= '0' && *s <= '7') { /* * \ddd in a format. \0ddd (and, as other shells allow, * \ddd) in a %b argument or for echo. The digits 0-9 are * contiguous in every C character set. */ unsigned v = 0; int digits = echo_style && *s == '0' ? 4 : 3; for (int i = 0; i < digits && *s >= '0' && *s <= '7'; i++) v = v * 8 + (unsigned)(*s++ - '0'); s--; out_putc(o, (char)v); } else { out_putc(o, '\\'); out_putc(o, *s); } break; } } return true; } /** * @brief State of one printf: the arguments not yet used and the exit status. */ typedef struct printf_state { char **args; int status; } printf_state; /** * @brief Take the next argument, or an empty string when they have run out. */ static const char *next_arg(printf_state *pf) { return *pf->args ? *pf->args++ : nullptr; } /** * @brief Take the next argument as an integer. * * A leading quote means "the code of the next character". A bad number is * reported and makes the exit status 1, but printing continues. */ static intmax_t arg_int(printf_state *pf, bool is_unsigned) { const char *s = next_arg(pf); if (!s) return 0; if (*s == '\'' || *s == '"') return (unsigned char)s[1]; char *end; errno = 0; intmax_t v = is_unsigned ? (intmax_t)strtoumax(s, &end, 0) : strtoimax(s, &end, 0); if (end == s || *end) { sh_warn("printf: %s: expected numeric value", s); pf->status = 1; } else if (errno == ERANGE) { sh_warn("printf: %s: out of range", s); pf->status = 1; } return v; } /** * @brief Take the next argument as a floating-point number. */ static double arg_double(printf_state *pf) { const char *s = next_arg(pf); if (!s) return 0; if (*s == '\'' || *s == '"') return (unsigned char)s[1]; char *end; errno = 0; double v = strtod(s, &end); if (end == s || *end) { sh_warn("printf: %s: expected numeric value", s); pf->status = 1; } else if (errno == ERANGE && (v == HUGE_VAL || v == -HUGE_VAL)) { sh_warn("printf: %s: out of range", s); pf->status = 1; } return v; } /** * @brief Copy a width or precision into a conversion specification. * @param pf printf state (a `*` takes its value from the next argument). * @param f Position in the format. * @param spec Specification being built. * @param n Receives the new length of `spec`. * @param dot Length of `spec` before the '.' that starts this precision, * or 0 when this is the width. * @return Position in the format after the number. */ static const char *copy_number(printf_state *pf, const char *f, char *spec, size_t *n, size_t dot) { if (*f == '*') { intmax_t v = arg_int(pf, false); /* * C99: a negative precision is as if the precision were omitted, * so drop the '.' as well; a negative width is a '-' flag, which * snprintf() reads from the "%*d" this writes. */ if (dot && v < 0) *n = dot; else *n += (size_t)snprintf(spec + *n, 24, "%jd", v); return f + 1; } int digits = 0; while (isdigit((unsigned char)*f)) { if (digits++ < 9) spec[(*n)++] = *f; f++; } return f; } /** * @brief Handle one conversion. * @param pf printf state. * @param f Points just after the `%`. * @return Position of the conversion character, or nullptr to stop (an * error, or `\c` in a `%b` argument). */ static const char *convert(printf_state *pf, const char *f) { char spec[64]; size_t n = 0; int nflags = 0; spec[n++] = '%'; while (*f && strchr("-+ #0", *f)) { if (nflags++ < 5) spec[n++] = *f; f++; } f = copy_number(pf, f, spec, &n, 0); if (*f == '.') { size_t dot = n; spec[n++] = '.'; f = copy_number(pf, f + 1, spec, &n, dot); } switch (*f) { case 'd': case 'i': spec[n++] = 'j'; spec[n++] = 'd'; spec[n] = '\0'; out_printf(&out1, spec, arg_int(pf, false)); break; case 'u': case 'o': case 'x': case 'X': spec[n++] = 'j'; spec[n++] = *f; spec[n] = '\0'; out_printf(&out1, spec, (uintmax_t)arg_int(pf, true)); break; case 'e': case 'E': case 'f': case 'F': case 'g': case 'G': spec[n++] = *f; spec[n] = '\0'; out_printf(&out1, spec, arg_double(pf)); break; case 'c': { const char *s = next_arg(pf); spec[n++] = 'c'; spec[n] = '\0'; if (s && *s) out_printf(&out1, spec, *s); else /* "%c" of an empty or missing argument is a NUL (dash, bash) */ out_write(&out1, "", 1); break; } case 's': { const char *s = next_arg(pf); if (n == 1) { /* a bare "%s": there is nothing to pad or truncate */ out_puts(&out1, s ? s : ""); break; } spec[n++] = 's'; spec[n] = '\0'; out_printf(&out1, spec, s ? s : ""); break; } case 'b': { const char *s = next_arg(pf); output mem = {.fd = OUT_MEM}; bool more = out_escaped(&mem, s ? s : "", true); if (n == 1) { out_write(&out1, mem.buf, mem.len); } else { out_putc(&mem, '\0'); spec[n++] = 's'; spec[n] = '\0'; out_printf(&out1, spec, mem.buf); } free(mem.buf); if (!more) return nullptr; break; } default: sh_warn("printf: %%%c: invalid directive", *f ? *f : ' '); pf->status = 1; return nullptr; } return f; } /** * @brief The `printf` builtin. * * The format is reused until the arguments are exhausted, as POSIX * requires. * * @return 0, or 1 if an argument could not be converted. */ int builtin_printf(int argc, char **argv) { int i = 1; if (i < argc && !strcmp(argv[i], "--")) i++; if (i >= argc) { sh_warn("printf: usage: printf format [argument ...]"); return 2; } const char *fmt = argv[i]; printf_state pf = {.args = argv + i + 1}; /* The format is reused until the arguments run out. */ for (;;) { char **before = pf.args; for (const char *f = fmt; *f; f++) { if (*f == '\\') { char esc[6] = {'\\'}; size_t len = 1; /* Take one escape: \X or up to three octal digits. */ if (f[1] >= '0' && f[1] <= '7') { while (len < 4 && f[len] >= '0' && f[len] <= '7') { esc[len] = f[len]; len++; } } else if (f[1]) { esc[len] = f[len]; len++; } out_escaped(&out1, esc, false); f += len - 1; } else if (*f != '%') { out_putc(&out1, *f); } else if (f[1] == '%') { out_putc(&out1, '%'); f++; } else { f = convert(&pf, f + 1); if (!f) return pf.status; } } if (pf.args == before || !*pf.args) break; } return pf.status; }