summaryrefslogtreecommitdiffhomepage
path: root/src/printf.c
blob: 511e1852c56778beba21ad1144d0c2684382aedc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/**
 * @file printf.c
 * @brief The `printf` builtin and the backslash-escape writer shared with
 * `echo` and `print`.
 */
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#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;
}