[llvm] r286910 - Avoid calling std::memcmp with nullptr

Vitaly Buka via llvm-commits llvm-commits at lists.llvm.org
Mon Nov 14 16:01:40 PST 2016


Author: vitalybuka
Date: Mon Nov 14 18:01:40 2016
New Revision: 286910

URL: http://llvm.org/viewvc/llvm-project?rev=286910&view=rev
Log:
Avoid calling std::memcmp with nullptr

Summary:
UBSAN complains that this is undefined behavior.

We can assume that empty substring (N==1) always satisfy conditions. So
std::memcmp will be called only only for N > 1 and Str.size() > 0.

Reviewers: ruiu, zturner

Subscribers: llvm-commits

Differential Revision: https://reviews.llvm.org/D26646

Modified:
    llvm/trunk/include/llvm/ADT/StringSwitch.h

Modified: llvm/trunk/include/llvm/ADT/StringSwitch.h
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/ADT/StringSwitch.h?rev=286910&r1=286909&r2=286910&view=diff
==============================================================================
--- llvm/trunk/include/llvm/ADT/StringSwitch.h (original)
+++ llvm/trunk/include/llvm/ADT/StringSwitch.h Mon Nov 14 18:01:40 2016
@@ -72,8 +72,9 @@ public:
   template<unsigned N>
   LLVM_ATTRIBUTE_ALWAYS_INLINE
   StringSwitch& Case(const char (&S)[N], const T& Value) {
+    assert(N);
     if (!Result && N-1 == Str.size() &&
-        (std::memcmp(S, Str.data(), N-1) == 0)) {
+        (N == 1 || std::memcmp(S, Str.data(), N-1) == 0)) {
       Result = &Value;
     }
     return *this;
@@ -82,8 +83,9 @@ public:
   template<unsigned N>
   LLVM_ATTRIBUTE_ALWAYS_INLINE
   StringSwitch& EndsWith(const char (&S)[N], const T &Value) {
+    assert(N);
     if (!Result && Str.size() >= N-1 &&
-        std::memcmp(S, Str.data() + Str.size() + 1 - N, N-1) == 0) {
+        (N == 1 || std::memcmp(S, Str.data() + Str.size() + 1 - N, N-1) == 0)) {
       Result = &Value;
     }
     return *this;
@@ -92,8 +94,9 @@ public:
   template<unsigned N>
   LLVM_ATTRIBUTE_ALWAYS_INLINE
   StringSwitch& StartsWith(const char (&S)[N], const T &Value) {
+    assert(N);
     if (!Result && Str.size() >= N-1 &&
-        std::memcmp(S, Str.data(), N-1) == 0) {
+        (N == 1 || std::memcmp(S, Str.data(), N-1) == 0)) {
       Result = &Value;
     }
     return *this;




More information about the llvm-commits mailing list