Re: [PATCH v2] tile: avoid errors from truncating long strings in mpipe gxio

From: Randy Dunlap
Date: Mon Aug 11 2014 - 17:30:16 EST


On 08/11/14 13:43, Rickard Strandqvist wrote:
> 2014-08-07 8:43 GMT+02:00 Randy Dunlap <rdunlap@xxxxxxxxxxxxx>:
>> On 08/06/14 11:16, Chris Metcalf wrote:
>>> Using strncpy() will just silently truncate long strings; we should
>>> instead return an appropriate error. Using strlcpy() would suffer from
>>> the same problem. Instead, use strnlen()+memcpy(), and add an
>>> error-checking step to make sure the lengths are reasonable.
>>>
>>> I called the convenience wrapper strscpy(), and a case could be made for
>>> making it more generic (possibly with a better name), but that seems
>>> outside the scope of this initial commit.
>>
>> Well, having looked at the function before I read this comment, my first
>> thought was that it should be added to lib/string.c for general
>> availability.
>>
>>>
>>> Signed-off-by: Chris Metcalf <cmetcalf@xxxxxxxxxx>
>>> ---
>>> v2: use strnlen instead of strlen
>>>
>>> arch/tile/gxio/mpipe.c | 30 +++++++++++++++++++++++++-----
>>> 1 file changed, 25 insertions(+), 5 deletions(-)
>>>
>>> diff --git a/arch/tile/gxio/mpipe.c b/arch/tile/gxio/mpipe.c
>>> index 5301a9ffbae1..27a56be8d583 100644
>>> --- a/arch/tile/gxio/mpipe.c
>>> +++ b/arch/tile/gxio/mpipe.c
>>> @@ -29,6 +29,25 @@
>>> /* HACK: Avoid pointless "shadow" warnings. */
>>> #define link link_shadow
>>>
>>> +/*
>>> + * Use this routine to avoid copying too-long strings. Unlike strncpy
>>> + * or strlcpy, we don't enable programmers who don't check return codes;
>>> + * partially-copied strings can be problematic. The routine returns
>>> + * the total number of bytes copied (including the trailing NUL) or
>>> + * zero if the buffer wasn't big enough.
>>> + */
>>> +static size_t strscpy(char *dest, const char *src, size_t size)
>>> +{
>>> + size_t ret = strnlen(src, size) + 1;
>>> + if (ret > size) {
>>> + if (size)
>>> + dest[0] = '\0';
>>> + return 0;
>>> + }
>>> + memcpy(dest, src, ret);
>>> + return ret;
>>> +}
>>
>> --
>> ~Randy
>
>
> Hi
>
> Sounds like a great idea!
>
> Do it Chris! Randy?

Yeah, I don't have a better name for it, but I do think
that it's the right thing to do.

Thanks,

--
~Randy
--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/