This is the mail archive of the gdb-patches@sourceware.org mailing list for the GDB project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: [commit] printcmd.c, print_scalar_formatted, use strncpy.


On Wednesday 02 March 2011 23:56:16, Michael Snyder wrote:
> Pedro Alves wrote:
> > On Wednesday 02 March 2011 23:00:23, Michael Snyder wrote:
> >>   2011-03-02  Michael Snyder  <msnyder@vmware.com>
> >>
> >>         * printcmd.c (print_scalar_formatted): Use strncpy for safety.

> >> -       strcpy (buf, cp);
> >> +       strncpy (buf, cp, sizeof (bits));
> >>         fputs_filtered (buf, stream);

> > We've been through this recently...  This is not safe.
> > 
> 
> I'm slow today -- how is it not safe?
> 
> (note that sizeof (bits) is smaller than sizeof (buff)).

In that case the change is useless.

In the case you're thinking strncpy is safer
(to prevent overflow), it does _not_ add the terminating
null byte to the destination.  See its linux man page, please.

If the change hadn't been useless for the reason above,
you'd've shifted the problem elsewhere, not made things safer,
because if the safety net had been hit, the fputs_filtered
in the next line would do undefined things, like for example
crash, when trying to print a not null-terminated BUF.

strncpy was _not_ designed as a safe version of strcpy.
It was designed to be used on fixed length fields
in things like databases, where if you don't null terminate
the destination, it's okay, because _users_ of the data
in the buffer know how to handle that.

Here <http://www.lysator.liu.se/c/rat/d11.html>:

"4.11.2.4  The strncpy function

 strncpy was initially introduced into the C library to deal with
 fixed-length name fields in structures such as directory entries.
 Such fields are not used in the same way as strings: the trailing
 null is unnecessary for a maximum-length field, and setting
 trailing bytes for shorter names to null assures efficient
 field-wise comparisons.  strncpy is not by origin a ``bounded
 strcpy,'' and the Committee has preferred to recognize existing
 practice rather than alter the function to better suit it to such use."

So, to recap, simply s/strcpy/strncpy/ is not any safer.

-- 
Pedro Alves


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]