From d8dfeec019e053ffc3c8205378c24a7023856a0d Mon Sep 17 00:00:00 2001 From: George Rimar Date: Fri, 2 Sep 2016 08:44:46 +0000 Subject: [PATCH] [Support] - Fix possible crash in match() of llvm::Regex. Crash was possible if match() method was called on object that was moved or object created with empty constructor. Testcases updated. DIfferential revision: https://reviews.llvm.org/D24123 llvm-svn: 280473 --- llvm/include/llvm/Support/Regex.h | 6 +----- llvm/lib/Support/Regex.cpp | 10 ++++++++++ llvm/unittests/Support/RegexTest.cpp | 9 +++++++++ 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/llvm/include/llvm/Support/Regex.h b/llvm/include/llvm/Support/Regex.h index afabaaf..83db803 100644 --- a/llvm/include/llvm/Support/Regex.h +++ b/llvm/include/llvm/Support/Regex.h @@ -52,11 +52,7 @@ namespace llvm { std::swap(error, regex.error); return *this; } - Regex(Regex &®ex) { - preg = regex.preg; - error = regex.error; - regex.preg = nullptr; - } + Regex(Regex &®ex); ~Regex(); /// isValid - returns the error encountered during regex compilation, or diff --git a/llvm/lib/Support/Regex.cpp b/llvm/lib/Support/Regex.cpp index 35641f3..68ba79e 100644 --- a/llvm/lib/Support/Regex.cpp +++ b/llvm/lib/Support/Regex.cpp @@ -34,6 +34,13 @@ Regex::Regex(StringRef regex, unsigned Flags) { error = llvm_regcomp(preg, regex.data(), flags|REG_PEND); } +Regex::Regex(Regex &®ex) { + preg = regex.preg; + error = regex.error; + regex.preg = nullptr; + regex.error = REG_BADPAT; +} + Regex::~Regex() { if (preg) { llvm_regfree(preg); @@ -59,6 +66,9 @@ unsigned Regex::getNumMatches() const { } bool Regex::match(StringRef String, SmallVectorImpl *Matches){ + if (error) + return false; + unsigned nmatch = Matches ? preg->re_nsub+1 : 0; // pmatch needs to have at least one element. diff --git a/llvm/unittests/Support/RegexTest.cpp b/llvm/unittests/Support/RegexTest.cpp index 7b61a03..5e3ce39 100644 --- a/llvm/unittests/Support/RegexTest.cpp +++ b/llvm/unittests/Support/RegexTest.cpp @@ -151,6 +151,8 @@ TEST_F(RegexTest, MoveAssign) { Regex r2("abc"); r2 = std::move(r1); EXPECT_TRUE(r2.match("916")); + std::string Error; + EXPECT_FALSE(r1.isValid(Error)); } TEST_F(RegexTest, NoArgConstructor) { @@ -162,4 +164,11 @@ TEST_F(RegexTest, NoArgConstructor) { EXPECT_TRUE(r1.isValid(Error)); } +TEST_F(RegexTest, MatchInvalid) { + Regex r1; + std::string Error; + EXPECT_FALSE(r1.isValid(Error)); + EXPECT_FALSE(r1.match("X")); +} + } -- 2.7.4