Re: [PATCH] perf: Incorrect use of snprintf results in SEGV

Ingo Molnar
2012-03-07T20:37:52Z

* Peter Seebach <peter.seebach@windriver.com> wrote:

> On Tue, 6 Mar 2012 22:09:04 -0300
> Arnaldo Carvalho de Melo <acme@redhat.com> wrote:
>
> > Or what kind of such pipe the people who designed snprintf
> > were using
> > :-(
>
> I wasn't there for the original 4.4BSD implementation, but I
> was on the ISO committee when we adopted it, and I regret to
> say, while the food was lovely, the hosting organization
> didn't offer us any drugs at all. But I can explain the
> rationale of the choice.

;-)

> If snprintf returns the size it needed, and you know the size
> you gave it, you have a choice of what to do, and you have all
> the information you need to make an informed choice.
>
> If it returns the amount it wrote, or possibly an error
> indicator (such as -1) when out of space, you *don't* have the
> information you need to make an informed choice, and one
> possible choice ("reallocate with the right amount") is not
> available to you. We had also seen other functions which made
> that implementation choice, and consistently, people disliked
> them more.

You are missing two important aspects:

1) Dynamic reallocation on snprintf() failure is an utterly rare
thing - it is used in less than 1% of snprintf() invocations.
(Yes, I just checked a couple of codebases.)

We *DONT* want to make APIs more fragile just to accomodate a
rare, esoteric usecase! Doing that you are introducing very
real bugs in very real code. You are hurting the 99% for the
sake of the 1%, and needlessly so:

2) It's not even true that should some code want to
dynamically allocate the 'required' number of bytes is not
available. Some oddball side API could be added for that 1%:

size_needed = snprintf_size(...);

So this API could have been designed right but it was messed up
out of concern for an insane 1% case - FAIL.

This is a case study for how insane semantics are created ...

Thanks,

Ingo