[llvm-bugs] [Bug 32357] New: -O1 replaces strncmp with strcmp even if one param is not null-terminated

via llvm-bugs llvm-bugs at lists.llvm.org
Mon Mar 20 16:30:36 PDT 2017


https://bugs.llvm.org/show_bug.cgi?id=32357

            Bug ID: 32357
           Summary: -O1 replaces strncmp with strcmp even if one param is
                    not null-terminated
           Product: new-bugs
           Version: unspecified
          Hardware: PC
                OS: Linux
            Status: NEW
          Severity: enhancement
          Priority: P
         Component: new bugs
          Assignee: unassignedbugs at nondot.org
          Reporter: kcc at google.com
                CC: llvm-bugs at lists.llvm.org, richard-llvm at metafoo.co.uk

% cat z.c
#include <string.h>
char magic[8];
int foo() { return strncmp(magic, "1234567", 8); }

% clang -S -o -  z.c -O0 | grep 'str.*cmp'
        callq   strncmp
% clang -S -o -  z.c -O1 | grep 'str.*cmp'
        jmp     strcmp                  # TAILCALL

Richard says: 

It's a bug. 

C11 7.1.1: "A string is a contiguous sequence of characters terminated by and
including the first null character. [...] A pointer to a string is a pointer to
its initial (lowest addressed) character."

C11 7.24.4.2: "The strcmp function compares the string pointed to by s1 to the
string pointed to by s2."

C11 7.24.4.4: "The strncmp function compares not more than n characters
(characters that follow a null character are not compared) from the array
pointed to by s1 to the array pointed to by s2."

Note that strcmp requires its arguments to be pointers to strings, but strncmp
only requires them to be pointers to arrays. Calling strcmp with pointers that
do not point to strings (presumably) results in undefined behavior. In the
above program, there is no guarantee that "magic" is a pointer to a string, so
it is not correct to convert the strncmp call to a strcmp call.

A hostile-but-valid strcmp implementation could first apply strlen to both of
its arguments. (And a clever implementation could probably get some performance
advantage by scanning ahead looking for a nul in the next, say, 16 bytes, and
then doing a 16-byte-at-a-time comparison.)

-- 
You are receiving this mail because:
You are on the CC list for the bug.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-bugs/attachments/20170320/f00479ac/attachment.html>


More information about the llvm-bugs mailing list