[PATCH] D26646: Avoid calling std::memcmp with nullptr

Vitaly Buka via llvm-commits llvm-commits at lists.llvm.org
Mon Nov 14 15:51:56 PST 2016


vitalybuka created this revision.
vitalybuka added reviewers: ruiu, zturner.
vitalybuka added a subscriber: llvm-commits.

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.


https://reviews.llvm.org/D26646

Files:
  include/llvm/ADT/StringSwitch.h


Index: include/llvm/ADT/StringSwitch.h
===================================================================
--- include/llvm/ADT/StringSwitch.h
+++ include/llvm/ADT/StringSwitch.h
@@ -72,28 +72,34 @@
   template<unsigned N>
   LLVM_ATTRIBUTE_ALWAYS_INLINE
   StringSwitch& Case(const char (&S)[N], const T& Value) {
+    assert(N);
+    assert(S[N-1] == '\0');
     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;
   }
 
   template<unsigned N>
   LLVM_ATTRIBUTE_ALWAYS_INLINE
   StringSwitch& EndsWith(const char (&S)[N], const T &Value) {
+    assert(N);
+    assert(S[N-1] == '\0');
     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;
   }
 
   template<unsigned N>
   LLVM_ATTRIBUTE_ALWAYS_INLINE
   StringSwitch& StartsWith(const char (&S)[N], const T &Value) {
+    assert(N);
+    assert(S[N-1] == '\0');
     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;


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D26646.77903.patch
Type: text/x-patch
Size: 1353 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20161114/91b3153b/attachment.bin>


More information about the llvm-commits mailing list