mpatch: fix UB integer overflows in discard() (SEC) stable
authorAugie Fackler <augie@google.com>
Mon, 30 Apr 2018 22:20:13 -0400
branchstable
changeset 38193 7f22ef3c0ee7
parent 38192 0b208c13781c
child 38194 59837a16896d
mpatch: fix UB integer overflows in discard() (SEC)
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;