RFR(xs): 8076475: Misuses of strncpy/strncat

Thomas Stüfe thomas.stuefe at gmail.com
Thu Apr 9 13:36:27 UTC 2015


Hi Kim,

On Thu, Apr 9, 2015 at 3:13 PM, Kim Barrett <kim.barrett at oracle.com> wrote:

> On Apr 8, 2015, at 8:40 AM, Dmitry Samersoff <dmitry.samersoff at oracle.com>
> wrote:
> >
> > To make this code nice-looking it's better to add:
> >
> > if (strlen(libname) >  sizeof(newlib->name)) {
> > //  Bail out with debug message
> > ...
> > }
> > strcpy(newlib->name, libname);
> >
> > rather than use snprintf here.
>
> Just happened to see this going by in my email stream…
>
> There’s a problem with that suggestion:  strlen can run off the end if not
> NUL terminated.
> This can crash if, for example, unmapped memory is hit before a NUL is
> encountered.
> This is the sort of thing the strnlen function exists for.  Not sure how
> portably available
> that function is though - glibc requires feature test macros to enable it.
>
>
Good point.

I just checked and strnlen() is POSIX.1-2008 - hopefully supported on all
our platforms.
http://pubs.opengroup.org/onlinepubs/9699919799/functions/strlen.html

I'd still rather keep my snprintf() here - for my taste it is less verbose
and easier to understand
and would also protect us from non-terminated strings.

But if I adopt Dimitrys proposal above, I'll use strnlen().

..Thomas


More information about the hotspot-runtime-dev mailing list