OSDN Git Service

Avoid a UB pointer overflow in the ArrayRef unit test
authorVedant Kumar <vsk@apple.com>
Wed, 31 May 2017 21:47:52 +0000 (21:47 +0000)
committerVedant Kumar <vsk@apple.com>
Wed, 31 May 2017 21:47:52 +0000 (21:47 +0000)
The intent of the test is to check that array lengths greater than
UINT_MAX work properly. Change the test to stress that scenario, without
triggering pointer overflow UB.

Caught by a WIP pointer overflow checker in clang.

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

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@304353 91177308-0d34-0410-b5e6-96231b3b80d8

unittests/ADT/ArrayRefTest.cpp

index 65b4cbc..4694ff1 100644 (file)
@@ -11,6 +11,7 @@
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/raw_ostream.h"
 #include "gtest/gtest.h"
+#include <limits>
 #include <vector>
 using namespace llvm;
 
@@ -80,15 +81,25 @@ TEST(ArrayRefTest, AllocatorCopy) {
   EXPECT_NE(makeArrayRef(Array3Src).data(), Array3Copy.data());
 }
 
+TEST(ArrayRefTest, SizeTSizedOperations) {
+  ArrayRef<char> AR(nullptr, std::numeric_limits<ptrdiff_t>::max());
+
+  // Check that drop_back accepts size_t-sized numbers.
+  EXPECT_EQ(1U, AR.drop_back(AR.size() - 1).size());
+
+  // Check that drop_front accepts size_t-sized numbers.
+  EXPECT_EQ(1U, AR.drop_front(AR.size() - 1).size());
+
+  // Check that slice accepts size_t-sized numbers.
+  EXPECT_EQ(1U, AR.slice(AR.size() - 1).size());
+  EXPECT_EQ(AR.size() - 1, AR.slice(1, AR.size() - 1).size());
+}
+
 TEST(ArrayRefTest, DropBack) {
   static const int TheNumbers[] = {4, 8, 15, 16, 23, 42};
   ArrayRef<int> AR1(TheNumbers);
   ArrayRef<int> AR2(TheNumbers, AR1.size() - 1);
   EXPECT_TRUE(AR1.drop_back().equals(AR2));
-
-  // Check that drop_back accepts size_t-sized numbers.
-  ArrayRef<char> AR3((const char *)0x10000, SIZE_MAX - 0x10000);
-  EXPECT_EQ(1U, AR3.drop_back(AR3.size() - 1).size());
 }
 
 TEST(ArrayRefTest, DropFront) {
@@ -96,10 +107,6 @@ TEST(ArrayRefTest, DropFront) {
   ArrayRef<int> AR1(TheNumbers);
   ArrayRef<int> AR2(&TheNumbers[2], AR1.size() - 2);
   EXPECT_TRUE(AR1.drop_front(2).equals(AR2));
-
-  // Check that drop_front accepts size_t-sized numbers.
-  ArrayRef<char> AR3((const char *)0x10000, SIZE_MAX - 0x10000);
-  EXPECT_EQ(1U, AR3.drop_front(AR3.size() - 1).size());
 }
 
 TEST(ArrayRefTest, DropWhile) {
@@ -187,13 +194,6 @@ TEST(ArrayRefTest, EmptyEquals) {
   EXPECT_TRUE(ArrayRef<unsigned>() == ArrayRef<unsigned>());
 }
 
-TEST(ArrayRefTest, Slice) {
-  // Check that slice accepts size_t-sized numbers.
-  ArrayRef<char> AR((const char *)0x10000, SIZE_MAX - 0x10000);
-  EXPECT_EQ(1U, AR.slice(AR.size() - 1).size());
-  EXPECT_EQ(AR.size() - 1, AR.slice(1, AR.size() - 1).size());
-}
-
 TEST(ArrayRefTest, ConstConvert) {
   int buf[4];
   for (int i = 0; i < 4; ++i)