From 1e750858d0a3fa31bf9e591cb065dcb031677a9b Mon Sep 17 00:00:00 2001 From: Thomas Van Lenten Date: Fri, 2 Oct 2020 09:46:13 -0400 Subject: Fix issue found via asan Don't try to use more bytes then there are in the string. --- Foundation/GTMRegex.m | 8 ++++++-- Foundation/GTMRegexTest.m | 9 +++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/Foundation/GTMRegex.m b/Foundation/GTMRegex.m index 38077be..3d6f96f 100644 --- a/Foundation/GTMRegex.m +++ b/Foundation/GTMRegex.m @@ -652,11 +652,15 @@ static NSString *const kReplacementPattern = } - (NSString *)description { - return [NSString stringWithFormat:@"%@<%p> { regex=\"%@\", allSegments=%s, string=\"%.20s...\" }", + // `[utf8StrBuf_ bytes]` won't be null terminated, must manually ensure we + // don't ask for more bytes then there are. + NSUInteger len = (int)[utf8StrBuf_ length]; + return [NSString stringWithFormat:@"%@<%p> { regex=\"%@\", allSegments=%s, string=\"%.*s%s\" }", [self class], self, regex_, (allSegments_ ? "YES" : "NO"), - [utf8StrBuf_ bytes]]; + (int)(MIN(len, 20)), [utf8StrBuf_ bytes], + (len > 20 ? "..." : "")]; } @end diff --git a/Foundation/GTMRegexTest.m b/Foundation/GTMRegexTest.m index 75f5aad..d43b731 100644 --- a/Foundation/GTMRegexTest.m +++ b/Foundation/GTMRegexTest.m @@ -885,6 +885,15 @@ XCTAssertNotNil(seg); XCTAssertGreaterThan([[seg description] length], (NSUInteger)10, @"failed to get a reasonable description for regex string segment"); + + // Truncation on the input string (and handling sort lengths) + enumerator = [regex segmentEnumeratorForString:@"aaabbbccc"]; + XCTAssertNotNil(enumerator); + XCTAssertTrue([[enumerator description] hasSuffix:@", string=\"aaabbbccc\" }"]); + enumerator = [regex segmentEnumeratorForString:@"aaabbbcccdddeeefffggghhh"]; + XCTAssertNotNil(enumerator); + XCTAssertTrue([[enumerator description] hasSuffix:@", string=\"aaabbbcccdddeeefffgg...\" }"]); + // regex w/ other options regex = [GTMRegex regexWithPattern:@"a+" options:(kGTMRegexOptionIgnoreCase | kGTMRegexOptionSupressNewlineSupport)]; -- cgit v1.2.3