mpatch: fix UB in int overflows in gather() (SEC) stable
authorAugie Fackler <augie@google.com>
Mon, 30 Apr 2018 22:15:11 -0400
branchstable
changeset 38192 0b208c13781c
parent 38191 b8b253aec953
child 38193 7f22ef3c0ee7
mpatch: fix UB in int overflows in gather() (SEC)
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;