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

# HG changeset patch
# User Augie Fackler <augie@google.com>
# Date 1525141213 14400
# Node ID 7f22ef3c0ee721da8a568613dff48a7051fad8d7
# Parent  0b208c13781c18deae8fddb1dd63677f61fd64b5
mpatch: fix UB integer overflows in discard() (SEC)

diff -r 0b208c13781c -r 7f22ef3c0ee7 mercurial/mpatch.c
--- a/mercurial/mpatch.c	Mon Apr 30 22:15:11 2018 -0400
+++ b/mercurial/mpatch.c	Mon Apr 30 22:20:13 2018 -0400
@@ -172,15 +172,39 @@
 	int postend, c, l;
 
 	while (s != src->tail) {
-		if (s->start + offset >= cut)
+		int cmpcut = s->start;
+		if (!safeadd(offset, &cmpcut)) {
+			break;
+		}
+		if (cmpcut >= cut)
 			break;
 
-		postend = offset + s->start + s->len;
+		postend = offset;
+		if (!safeadd(s->start, &postend)) {
+			break;
+		}
+		if (!safeadd(s->len, &postend)) {
+			break;
+		}
 		if (postend <= cut) {
-			offset += s->start + s->len - s->end;
+			/* do the subtraction first to avoid UB integer overflow
+			 */
+			int tmp = s->start;
+			if (!safesub(s->end, &tmp)) {
+				break;
+			}
+			if (!safeadd(s->len, &tmp)) {
+				break;
+			}
+			if (!safeadd(tmp, &offset)) {
+				break;
+			}
 			s++;
 		} else {
-			c = cut - offset;
+			c = cut;
+			if (!safesub(offset, &c)) {
+				break;
+			}
 			if (s->end < c)
 				c = s->end;
 			l = cut - offset - s->start;