[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Xen-devel] [PATCH] Convert hvmloader sprintf() into snprintf()



> -----Original Message-----
> From: David Vrabel
> Sent: 29 November 2011 13:57
> To: Paul Durrant
> Cc: xen-devel@xxxxxxxxxxxxxxxxxxx
> Subject: Re: [Xen-devel] [PATCH] Convert hvmloader sprintf() into
> snprintf()
> 
[snip]
> > +static void __copy(void *arg, char c)
> >  {
> > -    **buf = c;
> > -    (*buf)++;
> > +    struct __copy_context *ctxt = arg;
> > +
> > +    ctxt->emitted++;
> > +
> > +    if (ctxt->remaining == 0)
> > +        return;
> > +
> > +    *(ctxt->ptr++) = c;
> > +    --ctxt->remaining;
> >  }
> >
> > -int sprintf(char *buf, const char *fmt, ...)
> > +int snprintf(char *buf, size_t size, const char *fmt, ...)
> >  {
> >      va_list ap;
> > +    struct __copy_context ctxt;
> > +
> > +    ctxt.ptr = buf;
> > +    ctxt.emitted = 0;
> > +    ctxt.remaining = size;
> >
> >      va_start(ap, fmt);
> > -    _doprint(__copy, &buf, fmt, ap);
> > +    _doprint(__copy, &ctxt, fmt, ap);
> >      va_end(ap);
> >
> > -    *buf = '\0';
> > -    return 0;
> > +    if (ctxt.remaining != 0)
> > +        *ctxt.ptr = '\0';
> > +
> > +    return ctxt.emitted;
> >  }
> 
> This doesn't return the correct value according the C99.  From the
> snprintf() man page:
> 
> "The functions snprintf() and vsnprintf() do not write  more  than
> size  bytes  (including  the trailing '\0').  If the output was
> truncated due  to this limit then the return value is the number  of
> characters  (not  including the trailing '\0') which would have been
> written to the final  string if enough space had been available.
> Thus,  a  return  value  of  size  or  more  means  that  the output
> was truncated."
> 

Actually, reading the code again, it is correct isn't it? ctxt.emitted is 
bumped for every character emitted by _doprint() regardless of whether it makes 
it into the buffer or not so in an overflow case the value returned will be the 
number of characters which would have been written not including the nul 
terminator.

  Paul

_______________________________________________
Xen-devel mailing list
Xen-devel@xxxxxxxxxxxxxxxxxxx
http://lists.xensource.com/xen-devel


 


Rackspace

Lists.xenproject.org is hosted with RackSpace, monitoring our
servers 24x7x365 and backed by RackSpace's Fanatical Support®.