Fix UAF when iterator outlives DB during shutdown #1297
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 #1292
Problem
Iterators created by
DBImpl::NewInternalIteratorregister a cleanup callback that may execute after the owningDBImplinstance has been destroyed. The cleanup path previously relied on a mutex whose lifetime was tied to theDBImplobject. If the DB was destroyed before all iterators were released (for example, during shutdown races in multi-threaded environments), iterator destruction could access freed memory, resulting in a use-after-free and segmentation fault in release builds.Fix
This change introduces a minimal internal lifetime indirection so that iterator cleanup no longer depends on a mutex that may already have been destroyed. The mutex lifetime is safely extended for the duration of iterator cleanup, preventing access to freed memory. The fix is internal-only, does not modify the public API, and preserves existing semantics for correct usage.
Behavior Change
Before: Destroying a DB before its iterators could result in a segmentation fault or ASAN-reported heap-use-after-free during iterator cleanup.
After: This change removes undefined behavior during iterator cleanup; incorrect shutdown order may still trigger existing internal assertions, consistent with documented usage requirements.
Correct usage (destroying iterators before the DB) is unaffected.
Testing
The issue was validated using a minimal external reproducer that consistently triggered a crash on the current
mainbranch and no longer does so after this change. The shutdown-order race involved is difficult to cover deterministically in the existing test framework, so no new internal test was added.Notes