Skip to content

Commit 9d387eb

Browse files
committed
fix: panic in linear myers algorithm
In `linearSpaceMyersRecWithIndices`, the suffix-scanning loop: ```go for suffix < n-prefix && a[aEnd-1-suffix] == b[bEnd-1-suffix] { ``` bounds the scan against n-prefix (a's remaining length after prefix) but not against m-prefix (b's remaining length). With the fuzzer's input a="\n\n\n\n\n\n\n\n\n0" → 10 lines, b="0" → 1 line: n=10, m=1, prefix=0 suffix=0: a[9]="0" == b[0]="0" → true, suffix becomes 1 suffix=1: tries b[1-1-1] = b[-1] → index out of range panic Signed-off-by: Andrey Smirnov <andrey.smirnov@siderolabs.com>
1 parent a1f8b87 commit 9d387eb

1 file changed

Lines changed: 18 additions & 2 deletions

File tree

diff/myers/myers.go

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ func linearSpaceMyersRecWithIndices(a, b []string, aStart, aEnd, bStart, bEnd, d
207207

208208
// Check for common prefix/suffix to reduce problem size
209209
prefix := 0
210-
for prefix < n && a[aStart+prefix] == b[bStart+prefix] {
210+
for prefix < n && prefix < m && a[aStart+prefix] == b[bStart+prefix] {
211211
prefix++
212212
}
213213

@@ -217,7 +217,7 @@ func linearSpaceMyersRecWithIndices(a, b []string, aStart, aEnd, bStart, bEnd, d
217217
}
218218

219219
suffix := 0
220-
for suffix < n-prefix && a[aEnd-1-suffix] == b[bEnd-1-suffix] {
220+
for suffix < n-prefix && suffix < m-prefix && a[aEnd-1-suffix] == b[bEnd-1-suffix] {
221221
suffix++
222222
}
223223

@@ -418,7 +418,15 @@ func findMiddleSnake(a, b []string, aStart, aEnd, bStart, bEnd int) snake { //re
418418
x = vf[idx]
419419
}
420420

421+
// Clamp to valid grid boundaries: x must be in [0, n], y = x-k must be in [0, m].
422+
// vf[k-1]+1 can exceed n when that diagonal already reached the end of a.
423+
if x > n {
424+
x = n
425+
}
421426
y := x - k // Calculate y based on x and diagonal k
427+
if y < 0 || y > m {
428+
continue
429+
}
422430

423431
// Store the starting point of the potential snake for this (d, k)
424432
startX := x
@@ -480,7 +488,15 @@ func findMiddleSnake(a, b []string, aStart, aEnd, bStart, bEnd int) snake { //re
480488
continue
481489
}
482490

491+
// Clamp to valid grid boundaries: x must be in [0, n], y = x-k must be in [0, m].
492+
// vr[k+1]-1 can go negative when that diagonal already reached the start.
493+
if x < 0 {
494+
x = 0
495+
}
483496
y := x - k
497+
if y < 0 || y > m {
498+
continue
499+
}
484500

485501
endX := x
486502
endY := y

0 commit comments

Comments
 (0)