Skip to content

Commit df481b9

Browse files
committed
Merge branch 'rs/apply-fuzzy-match-fix' into maint
A fix for an ancient bug in "git apply --ignore-space-change" codepath. * rs/apply-fuzzy-match-fix: apply: avoid out-of-bounds access in fuzzy_matchlines()
2 parents b51df7d + 6ce15ce commit df481b9

File tree

1 file changed

+20
-39
lines changed

1 file changed

+20
-39
lines changed

apply.c

Lines changed: 20 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -305,52 +305,33 @@ static uint32_t hash_line(const char *cp, size_t len)
305305
static int fuzzy_matchlines(const char *s1, size_t n1,
306306
const char *s2, size_t n2)
307307
{
308-
const char *last1 = s1 + n1 - 1;
309-
const char *last2 = s2 + n2 - 1;
310-
int result = 0;
308+
const char *end1 = s1 + n1;
309+
const char *end2 = s2 + n2;
311310

312311
/* ignore line endings */
313-
while ((*last1 == '\r') || (*last1 == '\n'))
314-
last1--;
315-
while ((*last2 == '\r') || (*last2 == '\n'))
316-
last2--;
317-
318-
/* skip leading whitespaces, if both begin with whitespace */
319-
if (s1 <= last1 && s2 <= last2 && isspace(*s1) && isspace(*s2)) {
320-
while (isspace(*s1) && (s1 <= last1))
321-
s1++;
322-
while (isspace(*s2) && (s2 <= last2))
323-
s2++;
324-
}
325-
/* early return if both lines are empty */
326-
if ((s1 > last1) && (s2 > last2))
327-
return 1;
328-
while (!result) {
329-
result = *s1++ - *s2++;
330-
/*
331-
* Skip whitespace inside. We check for whitespace on
332-
* both buffers because we don't want "a b" to match
333-
* "ab"
334-
*/
335-
if (isspace(*s1) && isspace(*s2)) {
336-
while (isspace(*s1) && s1 <= last1)
312+
while (s1 < end1 && (end1[-1] == '\r' || end1[-1] == '\n'))
313+
end1--;
314+
while (s2 < end2 && (end2[-1] == '\r' || end2[-1] == '\n'))
315+
end2--;
316+
317+
while (s1 < end1 && s2 < end2) {
318+
if (isspace(*s1)) {
319+
/*
320+
* Skip whitespace. We check on both buffers
321+
* because we don't want "a b" to match "ab".
322+
*/
323+
if (!isspace(*s2))
324+
return 0;
325+
while (s1 < end1 && isspace(*s1))
337326
s1++;
338-
while (isspace(*s2) && s2 <= last2)
327+
while (s2 < end2 && isspace(*s2))
339328
s2++;
340-
}
341-
/*
342-
* If we reached the end on one side only,
343-
* lines don't match
344-
*/
345-
if (
346-
((s2 > last2) && (s1 <= last1)) ||
347-
((s1 > last1) && (s2 <= last2)))
329+
} else if (*s1++ != *s2++)
348330
return 0;
349-
if ((s1 > last1) && (s2 > last2))
350-
break;
351331
}
352332

353-
return !result;
333+
/* If we reached the end on one side only, lines don't match. */
334+
return s1 == end1 && s2 == end2;
354335
}
355336

356337
static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)

0 commit comments

Comments
 (0)