File hg-mpatch-fix06.patch of Package mercurial.11235

# HG changeset patch
# User Augie Fackler <augie@google.com>
# Date 1525140911 14400
# Node ID 0b208c13781c18deae8fddb1dd63677f61fd64b5
# Parent  b8b253aec9538b2614295f6ba4ecefe335ad8bf5
mpatch: fix UB in int overflows in gather() (SEC)

diff -r b8b253aec953 -r 0b208c13781c mercurial/mpatch.c
--- a/mercurial/mpatch.c	Thu May 03 12:54:20 2018 -0400
+++ b/mercurial/mpatch.c	Mon Apr 30 22:15:11 2018 -0400
@@ -109,17 +109,36 @@
 	int postend, c, l;
 
 	while (s != src->tail) {
-		if (s->start + offset >= cut)
+		int soffset = s->start;
+		if (!safeadd(offset, &soffset))
+			break; /* add would overflow, oh well */
+		if (soffset >= cut)
 			break; /* we've gone far enough */
 
-		postend = offset + s->start + s->len;
+		postend = offset;
+		if (!safeadd(s->start, &postend) ||
+		    !safeadd(s->len, &postend)) {
+			break;
+		}
 		if (postend <= cut) {
 			/* save this hunk */
-			offset += s->start + s->len - s->end;
+			int tmp = s->start;
+			if (!safesub(s->end, &tmp)) {
+				break;
+			}
+			if (!safeadd(s->len, &tmp)) {
+				break;
+			}
+			if (!safeadd(tmp, &offset)) {
+				break; /* add would overflow, oh well */
+			}
 			*d++ = *s++;
 		} else {
 			/* break up this hunk */
-			c = cut - offset;
+			c = cut;
+			if (!safesub(offset, &c)) {
+				break;
+			}
 			if (s->end < c)
 				c = s->end;
 			l = cut - offset - s->start;