Re: [PATCH 3/3] tools/nolibc: add support for asprintf()

From: David Laight

Date: Tue Apr 07 2026 - 06:47:20 EST


On Sun, 5 Apr 2026 17:39:22 +0200
Thomas Weißschuh <linux@xxxxxxxxxxxxxx> wrote:

> On 2026-04-04 16:34:59+0100, David Laight wrote:
> > On Wed, 01 Apr 2026 17:07:29 +0200
> > Thomas Weißschuh <linux@xxxxxxxxxxxxxx> wrote:
> >
> > > Add support for dynamically allocating formatted strings through
> > > asprintf() and vasprintf().
> > >
> > > Signed-off-by: Thomas Weißschuh <linux@xxxxxxxxxxxxxx>
> > > ---
> > > tools/include/nolibc/stdio.h | 50 ++++++++++++++++++++++++++++
> > > tools/testing/selftests/nolibc/nolibc-test.c | 24 +++++++++++++
> > > 2 files changed, 74 insertions(+)
> > >
> > > diff --git a/tools/include/nolibc/stdio.h b/tools/include/nolibc/stdio.h
> > > index 8f7e1948a651..1c9287b558f0 100644
> > > --- a/tools/include/nolibc/stdio.h
> > > +++ b/tools/include/nolibc/stdio.h
> > > @@ -787,6 +787,56 @@ int sprintf(char *buf, const char *fmt, ...)
> > > return ret;
> > > }
> > >
> > > +static __attribute__((unused, format(printf, 2, 0)))
> > > +int __nolibc_vasprintf(char **strp, const char *fmt, va_list args1, va_list args2)
> > > +{
> > > + char *buf;
> > > + int len;
> > > +
> > > + len = vsnprintf(NULL, 0, fmt, args1);
> > > + if (len < 0)
> > > + return -1;
> >
> > vsnprintf() can never fail.
>
> The one in nolibc not, according to the specification it could.
> So to be on the safe side, also against future changes in nolibc
> I'd like to keep the check.
> The asnprintf()/malloc() implementation will make any performance
> considerations moot anyways.

While a -1 return value from vsnprintf() would indicate a failure,
there are no conditions where that can happen.

The man page (and I think posix/sus) has a common page with fprintf()
and the only error is:
If an output error is encountered, a negative value is returned.
which can't happen for the 's' variants.

In particular there is nothing at all about invalid formats.
Perhaps just a comment that says it can't fail.

David