[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <20260203173939.3c5939c7@pumpkin>
Date: Tue, 3 Feb 2026 17:39:39 +0000
From: David Laight <david.laight.linux@...il.com>
To: Willy Tarreau <w@....eu>, Thomas Weißschuh
<linux@...ssschuh.net>, linux-kernel@...r.kernel.org, Cheng Li
<lechain@...il.com>
Subject: Re: [PATCH next 00/12] tools/nolibc: Enhance printf()
On Tue, 3 Feb 2026 10:29:48 +0000
david.laight.linux@...il.com wrote:
> From: David Laight <david.laight.linux@...il.com>
>
> Update printf() so that it handles almost all the non-fp formats.
> In particular:
> - Left alignment.
> - Zero padding.
> - Field precision.
> - Variable field width and precision.
> - Width modifiers q, L, t and z.
> - Conversion specifiers i and X (X generates lower case).
> About the only thing that is missing is octal.
>
> The tests are updated to match.
>
> There is a slight increase in code size, but it is minimalised
> by the the heavy use of bit-pattern matches.
I failed to add 'next' to the last two patches, but I don't expect anything
to actually happen until after the next merge window.
If the patch to change all the number->ascii function is committed I'll
add the trivial patch to support octal.
For reference this is the final version:
/* printf(). Supports most of the normal integer and string formats.
* - %[#0-+ ][width|*[.precision|*]][{l,t,z,ll,L,j,q}]{d,i,u,c,x,X,p,s,m,%}
* - %% generates a single %
* - %m outputs strerror(errno).
* - # only affects %x and prepends 0x to non-zero values.
* - %o (octal) isn't supported.
* - %X outputs a..f the same as %x.
* - No support for wide characters.
* - invalid formats are copied to the output buffer.
*/
typedef int (*__nolibc_printf_cb)(void *state, const char *buf, size_t size);
#define __PF_FLAG(c) (1u << ((c) & 0x1f))
static __attribute__((unused, format(printf, 3, 0)))
int __nolibc_printf(__nolibc_printf_cb cb, void *state, const char *fmt, va_list args)
{
char c;
int len, written, width, precision;
unsigned int flags, c_flag;
char tmpbuf[32 + 24];
const char *outstr;
written = 0;
while (1) {
outstr = fmt;
c = *fmt++;
if (!c)
break;
width = 0;
flags = 0;
if (c != '%') {
while (*fmt && *fmt != '%')
fmt++;
len = fmt - outstr;
} else {
/* we're in a format sequence */
c = *fmt++;
/* Flag characters */
for (; c >= 0x20 && c <= 0x3f; c = *fmt++) {
if ((__PF_FLAG(c) & (__PF_FLAG('-') | __PF_FLAG(' ') | __PF_FLAG('+') |
__PF_FLAG('#') | __PF_FLAG('0'))) == 0)
break;
flags |= __PF_FLAG(c);
}
/* width and precision */
for (;; c = *fmt++) {
if (c == '*') {
precision = va_arg(args, unsigned int);
c = *fmt++;
} else {
for (precision = 0; c >= '0' && c <= '9'; c = *fmt++)
precision = precision * 10 + (c - '0');
}
if (flags & __PF_FLAG('.'))
break;
width = precision;
if (c != '.') {
/* Default precision for strings */
precision = INT_MAX;
break;
}
flags |= __PF_FLAG('.');
}
/* Length modifiers are lower case except 'L' which is the same a 'q' */
if ((c >= 'a' && c <= 'z') || (c == 'L' && (c = 'q'))) {
if (__PF_FLAG(c) & (__PF_FLAG('l') | __PF_FLAG('t') | __PF_FLAG('z') |
__PF_FLAG('j') | __PF_FLAG('q'))) {
if (c == 'l' && fmt[0] == 'l') {
fmt++;
c = 'q';
}
/* These all miss "# -0+" */
flags |= __PF_FLAG(c);
c = *fmt++;
}
}
/* Conversion specifiers are lower case except 'X' treated as 'x' */
if (!((c >= 'a' && c <= 'z') || (c == 'X' && (c = 'x'))))
goto bad_conversion_specifier;
/* Numeric and pointer conversion specifiers.
* We need to check for "%p" or "%#x" later, merging here gives better code.
* But '#' collides with 'c' so shift right.
*/
c_flag = __PF_FLAG(c) | (flags & __PF_FLAG('#')) >> 1;
if (c_flag & (__PF_FLAG('c') | __PF_FLAG('d') | __PF_FLAG('i') | __PF_FLAG('u') |
__PF_FLAG('x') | __PF_FLAG('p') | __PF_FLAG('s'))) {
unsigned long long v;
long long signed_v;
char *out = tmpbuf + 32;
int sign = 0;
/* Annoying 'p' === '0' so mask from flags */
if ((c_flag | (flags & ~__PF_FLAG('p'))) &
(__PF_FLAG('p') | __PF_FLAG('s') | __PF_FLAG('l') | __PF_FLAG('t') | __PF_FLAG('z'))) {
v = va_arg(args, unsigned long);
signed_v = (long)v;
} else if (flags & (__PF_FLAG('j') | __PF_FLAG('q'))) {
v = va_arg(args, unsigned long long);
signed_v = v;
} else {
v = va_arg(args, unsigned int);
signed_v = (int)v;
}
if (c_flag & __PF_FLAG('c')) {
tmpbuf[0] = v;
len = 1;
outstr = tmpbuf;
goto do_output;
}
if (c_flag & __PF_FLAG('s')) {
if (!v) {
outstr = "(null)";
/* Match glibc, nothing output if precision too small */
len = precision >= 6 ? 6 : 0;
goto do_output;
}
outstr = (void *)v;
do_strnlen_output:
len = strnlen(outstr, precision);
goto do_output;
}
if (c_flag & (__PF_FLAG('d') | __PF_FLAG('i'))) {
if (signed_v < 0) {
sign = '-';
v = -(signed_v + 1);
v++;
} else if (flags & __PF_FLAG('+')) {
sign = '+';
} else if (flags & __PF_FLAG(' ')) {
sign = ' ';
}
}
if (v == 0) {
/* There are special rules for zero. */
if (c_flag & __PF_FLAG('p')) {
/* match glibc, precision is ignored */
outstr = "(nil)";
len = 5;
goto do_output;
}
if (!precision) {
/* Explicit %nn.0d, no digits output */
len = 0;
goto prepend_sign;
}
/* "#x" should output "0" not "0x0" */
*out = '0';
len = 1;
} else {
if (c_flag & (__PF_FLAG('d') | __PF_FLAG('i') | __PF_FLAG('u'))) {
len = u64toa_r(v, out);
} else {
len = u64toh_r(v, out);
if (c_flag & (__PF_FLAG('p') | __PF_FLAG('#' - 1)))
sign = 'x' | '0' << 8;
}
}
/* Add zero padding */
if (flags & (__PF_FLAG('0') | __PF_FLAG('.'))) {
if (!(flags & __PF_FLAG('.'))) {
if (flags & __PF_FLAG('-'))
/* Left justify overrides zero pad */
goto prepend_sign;
/* Zero pad to field width less sign */
precision = width;
if (sign) {
precision--;
if (sign >= 256)
precision--;
}
}
if (precision > 30)
/* Don't run off the start of tmpbuf[] */
precision = 30;
for (; len < precision; len++) {
/* Stop gcc generating horrid code and memset().
* This is OPTIMIZER_HIDE_VAR() from compiler.h.
*/
__asm__ volatile("" : "=r"(len) : "0"(len));
*--out = '0';
}
}
prepend_sign:
for (; sign; sign >>= 8) {
len++;
*--out = sign;
}
outstr = out;
}
else if (c == 'm') {
#ifdef NOLIBC_IGNORE_ERRNO
outstr = "unknown error";
len = __builtin_strlen(outstr);
#else
outstr = strerror(errno);
goto do_strnlen_output;
#endif /* NOLIBC_IGNORE_ERRNO */
} else {
bad_conversion_specifier:
if (c != '%')
/* Invalid format, output the format string */
fmt = outstr + 1;
/* %% is documented as a 'conversion specifier'.
* Any flags, precision or length modifier are ignored.
*/
outstr = fmt - 1;
len = 1;
width = 0;
}
}
do_output:
written += len;
/* An OPTIMIZER_HIDE_VAR() seems to stop gcc back-merging this
* code into one of the conditionals above.
*/
__asm__ volatile("" : "=r"(len) : "0"(len));
/* Output 'left pad', 'value' then 'right pad'. */
flags &= __PF_FLAG('-');
width -= len;
if (flags && cb(state, outstr, len) != 0)
return -1;
while (width > 0) {
int pad_len = ((width - 1) & 15) + 1;
width -= pad_len;
written += pad_len;
if (cb(state, " ", pad_len) != 0)
return -1;
}
if (!flags && cb(state, outstr, len) != 0)
return -1;
}
if (cb(state, NULL, 0) != 0)
return -1;
return written;
}
#undef _PF_FLAG
struct __nolibc_fprintf_cb_state {
FILE *stream;
unsigned int buf_offset;
char buf[128];
};
static int __nolibc_fprintf_cb(void *v_state, const char *buf, size_t size)
{
struct __nolibc_fprintf_cb_state *state = v_state;
unsigned int off = state->buf_offset;
if (off + size > sizeof(state->buf) || buf == NULL) {
state->buf_offset = 0;
if (off && _fwrite(state->buf, off, state->stream))
return -1;
if (size > sizeof(state->buf))
return _fwrite(buf, size, state->stream);
off = 0;
}
if (size) {
state->buf_offset = off + size;
memcpy(state->buf + off, buf, size);
}
return 0;
}
static __attribute__((unused, format(printf, 2, 0)))
int vfprintf(FILE *stream, const char *fmt, va_list args)
{
struct __nolibc_fprintf_cb_state state;
state.stream = stream;
state.buf_offset = 0;
return __nolibc_printf(__nolibc_fprintf_cb, &state, fmt, args);
}
struct __nolibc_sprintf_cb_state {
char *buf;
size_t size;
};
static int __nolibc_sprintf_cb(void *v_state, const char *buf, size_t size)
{
struct __nolibc_sprintf_cb_state *state = v_state;
char *tgt;
if (size >= state->size) {
if (state->size <= 1)
return 0;
size = state->size - 1;
}
tgt = state->buf;
if (size) {
state->size -= size;
state->buf = tgt + size;
memcpy(tgt, buf, size);
} else {
*tgt = '\0';
}
return 0;
}
static __attribute__((unused, format(printf, 3, 0)))
int vsnprintf(char *buf, size_t size, const char *fmt, va_list args)
{
struct __nolibc_sprintf_cb_state state = { .buf = buf, .size = size };
return __nolibc_printf(__nolibc_sprintf_cb, &state, fmt, args);
}
Powered by blists - more mailing lists