changeset 38193:7f22ef3c0ee7 stable

mpatch: fix UB integer overflows in discard() (SEC)
author Augie Fackler <augie@google.com>
date Mon, 30 Apr 2018 22:20:13 -0400
parents 0b208c13781c
children 59837a16896d
files mercurial/mpatch.c
diffstat 1 files changed, 28 insertions(+), 4 deletions(-) [+]
line wrap: on
line diff
--- 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;