Re: Reasons not to like asprintf - Mailing list pgsql-hackers

From Tom Lane
Subject Re: Reasons not to like asprintf
Date
Msg-id 24648.1382466032@sss.pgh.pa.us
Whole thread Raw
In response to Re: Reasons not to like asprintf  (Stephen Frost <sfrost@snowman.net>)
Responses Re: Reasons not to like asprintf  (Stephen Frost <sfrost@snowman.net>)
List pgsql-hackers
Stephen Frost <sfrost@snowman.net> writes:
> Sounds reasonable, and I haven't got a better name, but I'm trying to
> figure out why psprintf hasn't got the same issues which you mention in
> your other thread (eg: depending on vsnprintf to return the "would-be"
> result size).

It does, though not directly in psprintf but rather in the underlying
vasprintf implementation.  (Although psprintf is exposed to the problem
that it can't tell out-of-memory from format errors.)

What I'm on about in this thread is the API used by all the call sites,
not the underlying implementation issues.  As long as we're okay with
"exit or elog on any error", I think we should just have the widely-used
functions returning a buffer pointer.  Underneath that, we need some work
so that we can print more-specific error messages, but that will not be
of concern to the callers.

It's possibly debatable whether exit-on-error is okay or not.  I think
it is though, because none of our frontend code is prepared to do anything
except go belly-up on out-of-memory, while in the backend case it's only
elog(ERROR) anyway.  The other possible class of failures is format string
or encoding errors, but those seem to reduce to the same cases: I can't
envision that frontend code would have any useful recovery strategies.
I'd like the printed error message to distinguish these cases, but I don't
think the callers need to care.

> I'm also a bit nervous that we only check vsnprintf()
> success in Assert-enabled builds in psprintf, though I suppose that's
> all we're doing in appendStringInfo too.

Actually, appendStringInfo treats result < 0 as a buffer overrun report;
if the failure is persistent because it's really a format/encoding
problem, it'll loop till it runs out of memory, and then report the error
as that.  The trouble here is that in pre-C99 implementations of
vsnprintf, return code < 0 might mean either buffer overrun or a
format/encoding problem.  We can't do too much about this unless we are
prepared to move our goalposts about portability assumptions.  (Hmm ...
current POSIX requires *printf to set errno on error, so maybe we could
look at errno?)
        regards, tom lane



pgsql-hackers by date:

Previous
From: Jeff Janes
Date:
Subject: Re: Add min and max execute statement time in pg_stat_statement
Next
From: Andres Freund
Date:
Subject: Re: Failure while inserting parent tuple to B-tree is not fun