[Python-Dev] Re: [Patches] add string precisions to PyErr_Format calls

Greg Stein gstein@lyra.org
Tue, 11 Apr 2000 16:28:01 -0700 (PDT)


On Tue, 11 Apr 2000, Andrew M. Kuchling wrote:
> Greg Stein writes:
> >Wouldn't it be best to simply fix PyErr_Format so that we don't have to
> >continue to worry about buffer overruns?
> 
> A while ago I suggested using nsprintf() in PyErr_Format, but that
> means stealing the implementation from Apache for those platforms
> where libc doesn't include nsprintf().  Haven't done it yet...

Seems like it would be cake to write one that took *only* the %d and %s
(unadorned) modifiers. We wouldn't need anything else, would we?

[ ... grep'ing the source ... ]

I see the following format codes which would need to change:

%.###s  -- switch to %s
%i      -- switch to %d
%c      -- hrm. probably need to support this  (in stringobject.c)
%x      -- maybe switch to %d?                 (in stringobject.c)

The last two are used once, both in stringobject.c. I could see a case for
revising that call use just %s and %d.

One pass to count the length, alloc, then one pass to fill in. The second
pass could actually be handled by vsprintf() since we know the buffer is
large enough.

The only tricky part would be determining the max length for %d. For a
32-bit value, it is 10 digits; for 64-bit value, it is 20 digits. I'd say
allocate room for 20 digits regardless of platform and be done with it.

Maybe support %%, but I didn't see that anywhere. Somebody could add
support when the need arises.

Last problem: backwards compat for third-party modules using PyErr_Format.
IMO, leave PyErr_Format for them (they're already responsible for buffer
overruns (or not) since PyErr_Format isn't helping them). The new one
would be PyErr_SafeFormat. Recommend the Safe version, deprecate the
unsafe one.

Cheers,
-g

-- 
Greg Stein, http://www.lyra.org/