• Kees Cook's avatar
    string: Introduce strtomem() and strtomem_pad() · dfbafa70
    Kees Cook authored
    One of the "legitimate" uses of strncpy() is copying a NUL-terminated
    string into a fixed-size non-NUL-terminated character array. To avoid
    the weaknesses and ambiguity of intent when using strncpy(), provide
    replacement functions that explicitly distinguish between trailing
    padding and not, and require the destination buffer size be discoverable
    by the compiler.
    
    For example:
    
    struct obj {
    	int foo;
    	char small[4] __nonstring;
    	char big[8] __nonstring;
    	int bar;
    };
    
    struct obj p;
    
    /* This will truncate to 4 chars with no trailing NUL */
    strncpy(p.small, "hello", sizeof(p.small));
    /* p.small contains 'h', 'e', 'l', 'l' */
    
    /* This will NUL pad to 8 chars. */
    strncpy(p.big, "hello", sizeof(p.big));
    /* p.big contains 'h', 'e', 'l', 'l', 'o', '\0', '\0', '\0' */
    
    When the "__nonstring" attributes are missing, the intent of the
    programmer becomes ambiguous for whether the lack of a trailing NUL
    in the p.small copy is a bug. Additionally, it's not clear whether
    the trailing padding in the p.big copy is _needed_. Both cases
    become unambiguous with:
    
    strtomem(p.small, "hello");
    strtomem_pad(p.big, "hello", 0);
    
    See also https://github.com/KSPP/linux/issues/90
    
    Expand the memcpy KUnit tests to include these functions.
    
    Cc: Wolfram Sang <wsa+renesas@sang-engineering.com>
    Cc: Nick Desaulniers <ndesaulniers@google.com>
    Cc: Geert Uytterhoeven <geert@linux-m68k.org>
    Cc: Guenter Roeck <linux@roeck-us.net>
    Signed-off-by: default avatarKees Cook <keescook@chromium.org>
    dfbafa70
deprecated.rst 15.4 KB