--- 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;