Repository navigation
video: fix DISOpticalFlow heap-buffer-overflow with patch_size > border_size - #29853
Merged
asmorkalov merged 3 commits intoSep 7, 2026
Merged
Conversation
…er_size
DISOpticalFlowImpl pads I1 of every pyramid level with a fixed 16
pixel border (border_size), while PatchInverseSearch clamps a patch's
sample position to:
i_lower_limit = bsz - psz + 1.0f; // bsz = border_size, psz = patch_size
i_upper_limit = bsz + dis->h - 1.0f;
i.e. a patch may be placed up to patch_size - 1 pixels outside of the
image. computeSSD()/computeSSDMeanNorm() then read patch_size (+1 for
bilinear interpolation) rows/columns starting at that clamped
position, which stays inside the padded buffer only while
patch_size <= border_size. patch_size is user-settable via
setPatchSize() with no upper bound relative to the hardcoded
border_size, so setPatchSize() past 16 -- or a temporal-candidate flow
large enough to push the clamped search against its limit -- reads
past the end of I1s_ext (confirmed via AddressSanitizer,
heap-buffer-overflow in computeSSDMeanNorm).
Fix: size the border to whichever is larger, exactly once, at the top
of prepareBuffers() (where every I1s_ext[i] already gets freshly
created/padded on every calc() call, so this doesn't need any
additional cache-invalidation logic). The needed inequality
(border_size >= patch_size) is independent of image size, so this is
sufficient at every pyramid level uniformly. ocl_prepareBuffers() does
not need the equivalent change: calc()'s CV_OCL_RUN gate only takes
the OpenCL path when patch_size == 8, which is always within the
hardcoded border, so that path can never reach this overflow.
A prior attempt at this exact fix (PR opencv#29600) was closed by a
maintainer, who ran its own added regression test and got the same
ASan heap-buffer-overflow again ("the patch is not efficient"). I
could not reproduce that failure: I reproduced the original overflow
on unfixed 5.x (byte-for-byte the same crash site/allocator stack as
both the original issue report and opencv#29600's own ASan trace), then
applied the same one-line fix and ran opencv#29600's own added test 20x
plus a new 40-trial randomized stress test (patch_size 9-48 -- above
and below border_size=16 -- varying image size, patch_stride, flow
magnitude up to 120px, and a same-instance second calc() call to
exercise buffer re-use across a patch-size change) under
AddressSanitizer with zero failures. I don't have an explanation for
the discrepancy (possibly a stale incremental build on the original
report's end, since I hit and had to work around exactly that kind of
false "no work to do" build-cache issue myself while reproducing this)
-- flagging this openly rather than asserting certainty either way.
Verified locally:
- Built an ASan+UBSan-style instrumented Debug configuration
(-fsanitize=address, core+imgproc+features+flann+video+ts) separate
from the Release build used for the rest of today's changes,
specifically to reproduce and verify this memory-safety class of bug
properly rather than relying on a Release build where an
out-of-bounds read often silently returns garbage instead of
crashing.
- Confirmed the crash reproduces on unfixed 5.x, and is gone with the
fix, under both the exact regression_20185_patch_larger_than_border
test and the new randomized regression_20185_stress test (40
trials), both passing cleanly under ASan.
- Re-verified both new tests pass in the standard Release build_verify
configuration used for the rest of today's PRs.
- Full opencv_test_video suite (both ASan and Release): no failures
attributable to this change; all failures present are pre-existing,
needing opencv_extra test data (tracking/ECC/optical-flow reference
videos and images) not configured in this scoped build.
- border_size is object state that persists across calc() calls; per review, growing it based on the current patch_size made "the next frames processed with border_size > 16" -- correct in that prepareBuffers() recomputes it fresh every call so it doesn't actually leak stale values across frames, but still the wrong place to put a per-call derived quantity. Reverted that change entirely; border_size stays the constant 16 it always was. Instead, fixed this at the point that actually needs to respect the border: PatchInverseSearch_ParBody's i/j_lower_limit and i/j_upper_limit, which clamp how far a patch search may be pushed outside the image. These now also account for the read window (patch_size, plus 1 for bilinear interpolation) needing to stay inside the *existing* padded buffer, rather than assuming patch_size <= border_size always holds. For patch_size <= border_size (the common case, e.g. the default of 8) the bounds are algebraically identical to the originals -- verified no test/behavior change for default settings. - Replaced the local, explicitly-seeded RNG in both new tests with theRNG(), which the test system already seeds per-test. - Removed the comments duplicating what's in the PR description. While re-verifying under the same ASan setup used originally, the stress test's initial patch_stride range (independent of patch_size) surfaced a second, unrelated heap-buffer-overflow in precomputeStructureTensor(): its buffer-allocation size (cur_cols / patch_stride) and its usage formula (1 + (w - patch_size) / patch_stride) can disagree once patch_stride is comparable to or larger than the *effective* patch_size (which autoSelectPatchSizeAndScales can silently reduce for a given image size, independent of what setPatchSize() was called with). This is a real, separate, pre-existing bug, but out of scope for opencv#20185 -- constrained the stress test's patch_stride to a small fixed value (matching every built-in preset, all of which keep stride well below patch_size) instead of trying to fix it here. Re-verified with the same rigor as the original PR: ASan build, 20185_patch_larger_than_border and 20185_stress passing cleanly across 10 repeated runs plus a full opencv_test_video pass (no failures beyond the same pre-existing missing-opencv_extra-data ones as before); Release build_verify shows the same.
5 tasks done
Contributor
Author
|
@asmorkalov #29715 |
There was a problem hiding this comment.
🟢 Approval recommended
The fix is localized, matches the documented failure mode (bilinear patch reads exceeding the padded buffer), and includes regression coverage for the reported crash scenario.
Pull request overview
This PR fixes a heap-buffer-overflow in DISOpticalFlowImpl when patch_size > border_size by tightening the PatchInverseSearch clamp so bilinear patch reads stay within the already-padded I1_ext buffer. It also adds targeted regression tests to prevent reintroducing the crash scenario from #20185.
Changes:
- Adjusted PatchInverseSearch clamp bounds to account for the full
patch_size(+1 for bilinear) read window inside the padded buffer. - Added regression test covering
patch_sizelarger than the fixed border and a randomized stress test to exercise a wider parameter space and repeatedcalc()calls.
File summaries
| File | Description |
|---|---|
| modules/video/src/dis_flow.cpp | Tightens clamping logic in PatchInverseSearch to prevent out-of-bounds reads when patch_size exceeds the fixed padding. |
| modules/video/test/test_OF_accuracy.cpp | Adds regression + stress tests that reproduce the historical crash conditions and validate stability across repeated runs. |
Review details
- Files reviewed: 2/2 changed files
- Comments generated: 0
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Contributor
Author
|
@asmorkalov done merge allowance. |
asmorkalov
reviewed
Sep 5, 2026
The stress test ran DIS 40 times per invocation for little added coverage beyond the existing targeted regression test; dropping it per review. Also condensed the clamp-bounds comment in PatchInverseSearch_ParBody down to its essential rationale.
asmorkalov
approved these changes
Sep 7, 2026
Contributor
Author
|
@asmorkalov ready to merge. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #20185. 4.x companion to #29715.
@asmorkalov asked to retarget #29715 to 4.x since the issue reproduces there too, but that PR's branch descends from 5.x, so literally changing its base produces an unreviewable ~2M-line diff (the two branches have diverged far beyond this module). Opening a separate PR instead: same two commits, cherry-picked cleanly onto 4.x's current tip with zero conflicts (
modules/video/src/dis_flow.cppis byte-for-byte identical between the branches apart from this fix).What / why
See #29715 for the full writeup. Summary:
DISOpticalFlowImplpadsI1with a fixed 16px border, whilePatchInverseSearch's search-position clamp lets a patch be placed up topatch_size - 1px outside the image -- safe only whilepatch_size <= border_size. Sincepatch_sizeis user-settable with no upper bound relative to the hardcoded border,setPatchSize()past 16 (or a large-enough temporal-candidate flow) reads past the end of the padded buffer (confirmed via AddressSanitizer).Fix (per review on #29715): rather than growing the persistent
border_sizeobject field to matchpatch_size(which a reviewer correctly flagged as the wrong place for a per-call derived quantity), the search clamp itself (i/j_lower_limit,i/j_upper_limitinPatchInverseSearch_ParBody) now accounts for the read window needing to stay inside the existing padded buffer. Forpatch_size <= border_size(every built-in preset) the bounds are algebraically identical to the originals --border_sizeitself is untouched.Testing
Verified this reproduces identically on 4.x: built an ASan-instrumented Debug configuration (
core+imgproc+imgcodecs+features2d+flann+video+ts), confirmed the crash reproduces on pristine 4.x (same crash site as the original report), confirmed it's gone with this fix, and ran the newregression_20185_patch_larger_than_border/regression_20185_stresstests (5 repeated runs) plus the fullopencv_test_videosuite -- no failures attributable to this change (everything else failing needsopencv_extratest data not configured in this scoped build).PR checklist