[MPlayer-dev-eng] [PATCH 2/4] String handling audit/cleanup take 2

Rich Felker dalias at aerifal.cx
Fri Mar 9 03:17:04 CET 2007


On Thu, Mar 08, 2007 at 03:17:57PM -0500, Rich Felker wrote:
> On Thu, Mar 08, 2007 at 12:17:55PM +0100, Reimar Döffinger wrote:
> > Hello,
> > On Thu, Mar 08, 2007 at 12:02:11PM +0100, Reimar D?ffinger wrote:
> > [...]
> > > So, and to be productive I was thinking of something like that (I did
> > > not think long about it, so bear with any bugs/stupidity and ignore the
> > > stupid names):
> > > add a
> > > mpsnprintf that behaves like snprintf except that it aborts when the
> > > string does not fit
> > > BUFPRINTF macro for static arrays that does mpsnprintf(buf, sizeof(buf), ...)
> > 
> > Forgot: and something similar to asprintf, this should simplify quite a
> > bit of code.
> 
> OK here's some code..

I heard that some snprintf implementations maybe be broken (not
C99/POSIX compliant) and not return the length needed, so here's a
nasty workaround to point out how dumb they are. :))))))))

int vasprintf(char **s, const char *fmt, va_list ap)
{
	int len;
	va_list ap2;

#ifdef SNPRINTF_IS_BROKEN
	FILE *devnull = fopen("/dev/null", "wb");
	if (!devnull) return -1;
#endif

	va_copy(ap2, ap);
#ifdef SNPRINTF_IS_BROKEN
	len = vfprintf(devnull, fmt, ap2);
	fclose(devnull);
#else
	len = vsnprintf(NULL, 0, fmt, ap2);
#endif
	va_end(ap2);
	if (len >= 0) {
		if (!(*s = malloc((size_t)len+1)))
			return -1;
		vsnprintf(*s, (size_t)len+1, fmt, ap);
	}
	return len;
}

No idea if this is needed or not; hopefully someone can look it up.
Also, are there broken versions of the printf family of functions
which can overflow the returned length? My implementation is very safe
and fails to print more than INT_MAX characters (since C and POSIX
specify that they must return the number of characters printed and the
return value is an int, IMO is violates the spec to print more
characters than can be counted by an int), but I don't know if there
are other implementations which just let the count overflow, with the
naturally disastrous results.

Perhaps it's not even our job to work around such broken crap. I'd
rather tell people with broken systems that implement
security-critical functions in incorrect, insecure ways to whine to
their vendors to fix them, or drop the lame vendors and switch to an
OS where security is taken seriously, but I don't know what others'
opinions will be.

BTW, we probably already assume elsewhere that snprintf works mostly
correctly. I'm just not sure what assumptions we make and don't make.
If we want to support such insanely broken systems it might be better
to implement a fallback snprintf on top of fprintf+tmpfile. :)

Rich



More information about the MPlayer-dev-eng mailing list