Fix assorted correctness bugs found via a code-review sweep - #60
Open
ianjose wants to merge 8 commits into
Open
Conversation
A collection of small, independent correctness fixes across the engine, OS layer, and unit tests. Each is a localized defect (memory safety, wrong operator/variable, resource leak, or ineffective test) with no intended behavior change beyond the fix. Engine (dev/ese/src): - rec.cxx: delete[] for the array allocated in ErrRECIMakeKey; fix an && that should be || in ErrIsamIPrereadIndexRanges (guards rgStartColumns[0] when cStartColumns == 0). - space.cxx: null-check the PGNO array alloc and fix a std::sort off-by-one (cpgno-1 -> cpgno) in ErrSPCaptureSpaceTreePages. - dbscan.cxx / dataserializer.cxx / inc/dataserializer.hxx: unique_ptr<T> owning new T[] -> unique_ptr<T[]>; add a missing null-check before memcpy. - sysver.cxx: signed loop counter in ErrLGFindFmtVersFromEfv (a ULONG counter with i >= 0 never terminates and reads out of bounds). - revertsnapshot.cxx / rbsdump.cxx: null-check several allocations, fix a leak on an ErrAddPage path, bound an on-disk length before use. - _log/logwrite.cxx, _log/rstmap.cxx, inc/ccsr.hxx: == vs = in asserts; use the inner loop index in FRstmapCheckDuplicateSignature. - inc/pib.hxx: ErrSetUserIoPriority assigns (=) instead of OR-accumulating the QOS priority so it can be lowered again. Published header: - published/inc/stat.hxx: off-by-one (> 1 -> > 0) in the monotonicity guard of both ErrGetSampleHits implementations. OS layer / misc: - os/string.cxx: advance past the NUL in the ErrOSSTRAsciiToUnicodeM multi-string loop (only the first substring was converted). - os/norm.cxx: free the buffer on the GetLocaleInfo failure path. - os/task.cxx: use the captured thread-node count during teardown. - os/edbg.cxx: free szNewNote on the OOM cleanup path. - os/blockcache/_hashedlrukcachechunk.hxx: operator-precedence fix. - sync/sync.cxx: use the correct perf-data pointer in the term path. - noncore/eseshadow/*.cxx: null-check WcsDupNew results; correct _countof buffer argument. noncore/interop/jetinterop.cpp: avoid leaking a heap MJET_TABLEID. _xpress9/Xpress9DecLz77.c: fix a misplaced SET_ERROR arg. Tests: - Correct wrong-variable/tautological assertions, a sizeof(pointer), an out-of-bounds read, a missing return on a detected inconsistency, a placement-new buffer mismatch, and a wildcard suffix-match fix.
Contributor
|
@ianjose please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.
Contributor License AgreementContribution License AgreementThis Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
|
- sysinit.cxx: fix PagePatching (PRL) resource leak on instance-init failure. PagePatching::ErrPRLInit had no cleanup in the ErrINSTInit unwind, and ErrINSTTerm early-returns on fSTInitNotDone, so a failed init after PRL init leaked PRL. Added a TermPRL unwind label and routed ErrSCBInit failure to it (reverse-init order). - revertsnapshot.cxx: ErrRemoveRBSAfterRevert loop bound used m_lRBSMaxGenToApply instead of m_lRBSMinGenToApply, deleting only the newest RBS generation and leaving applied generations on disk after a revert. - dbutil.cxx: pgnonext/pgnoprev/pageflags DBCC commands passed NULL as strtoul endptr for the 2nd argument then checked a stale pchEnd, so trailing-garbage validation was dead. Pass &pchEnd. - compression.cxx: ErrCompressLz4_ reported *pcbDataCompressedActual to the perf counter before it was assigned (use-before-set). - lv.cxx: ErrRECGetLVSize used the table cursor's key size (pfucb) instead of the LV cursor's (pfucbLV) for per-chunk overhead accounting. - cat.cxx, info.cxx, kvpstore.cxx: correct wrong-variable / assignment-in-Assert validation asserts (FidFixedLast, fidTaggedFirst, ==).
- fldenum.cxx: validate column-reference size before reading versioned fields (fixes OOB read on truncated caller-supplied reference); free per-column-value buffers each iteration in primary-index streaming (fixes multi-value leak). - fldmod.cxx: propagate JET_errDatabaseCorrupted from ErrCbBurstVarDefaults via out-param instead of returning a negative ERR through a ULONG count. - lv.cxx: free decompressed buffer on LV-corruption return paths. - old.cxx: read full TDelta width for escrow finalize check (64-bit value with zero low-32 no longer misread as zero). - daedef.hxx: FID::operator+= returns FID&; correct CbMapSize bitmap-size computation; fix LOGTIME range comments.
fldext.cxx: - UlRECICountTaggedColumnInstances: return 0 (not an ERR) on the record-corruption path, since the function returns a ULONG instance count. - ErrRECIRetrieveFromIndex: CallR -> Call in the tuple sub-loop so an error frees the RESKEY key buffer via HandleError (previously leaked). - ErrIsamRetrieveColumn: guard the *pcbActual writes with if(pcbActual) in the PageNumber/CopyIntrinsic early-exit paths (NULL-deref). - ErrRECRetrieveColumns: use the per-column iterator pretcolT (not base pretcol) for JET_bitRetrievePhysicalSize validation. - ErrRECIBuildTaggedColumnList: set fDefaultValue based on whether the value came from the default-values iterator (was hard-coded fFalse). fcreate.cxx: - ErrFILEIBatchCreateIndex: use the loop iterator pidxcreateT (not base pidxcreate) for the space-hints copy (potential NULL-deref) and the debug-only forced write. - ErrIsamCreateIndex: use pindexcreateT in the one-by-one loop body (multi-index create was broken in MINIMAL_FUNCTIONALITY builds). jetapi.cxx: - CAutoINDEXCREATE3To3_T::Result: advance the client write-back pointer unconditionally so it stays in sync with the loop index when indexes are immutable. - Batch wide-char JetCreateIndex (1W/2W/3W): copy each per-index engine result back into the converter before Result(), and add the missing 3W write-back branch to CAutoIDXCREATE3::Result, so per-index .err is reported. rec.cxx: - ErrRECSetCursorFilter: reject filter cb > JET_cbColumnMost before the 32-bit buffer-size accumulation, preventing an integer overflow that could under-allocate the buffer and cause a heap overflow.
cat.cxx / fileopen.cxx (stack buffer overflows on a corrupt catalog): - ErrCATGetNextRootObject: bound the persisted fidMSO_Name length before copying into the fixed szObjectNameT[] stack buffer (retail JET_errCatalogCorrupted check, matching the other name readers) instead of an Assert-only guard. - ErrIDBSetIdxSeg / ErrIDBSetIdxSegFromOldFormat: reject cidxseg > _countof(rgidxseg) before the conversion loop, so a corrupt KeyFldIDs/ConditionalColumns catalog column length cannot overflow the local IDXSEG rgidxseg[JET_ccolKeyMost] stack array. repair.cxx (integrity-checker corruption handling): - BTSTATS histograms: bound persisted key/suffix/prefix lengths to cbKeyAlloc before using them as array indices (6 sites), preventing a heap out-of-bounds write during eseutil /g or /p on a corrupt database. - ErrREPAIRInsertCatalogRecordIntoTempTable: cap the SetColumn length to the bytes actually copied (CopyIntoBuffer truncates), avoiding a stack over-read on an over-long corrupt catalog key. space.cxx (space-dump path leaks): - ErrSPIAddExtentInfo: reallocate into a temporary so an OOM leaves the caller''s array pointer intact (was nulled, leaking the old buffer). - ErrSPGetExtentInfo: free the extent array in HandleError on failure (ownership only transfers to the caller on success). dbscan.cxx: - CDBMScanFollower ctor: initialize m_pscanobsPerfmon and m_cFollowerSkipsPrePass.
logredo.cxx (crash-recovery redo of persisted, possibly-corrupt log records): - ErrReplacePageImageHeaderTrailer: reject a page-move record whose persisted header/trailer sizes exceed the page buffer, before RebuildPageImageHeaderTrailer overruns the buffer and underflows its memset size (size_t) to ~SIZE_MAX. - Root-page-move SetExternalHeader redo: validate the persisted length equals sizeof(SPACE_HEADER) before copying into the fixed sphNew (the normal SetExternalHeader redo already validates; this path did not). - Split/merge redo: bound the persisted parent-key and prefix lengths to the RESBOOKMARK buffer capacity before copying, matching the assert bt.cxx makes on the same copies. (le_cbKeyParent / le_cbPrefixSplitOld / le_cbPrefixSplitNew / le_cbKeyParentSep are USHORT and were guarded only by > 0.) All use JET_errLogFileCorrupt / JET_errLogCorrupted, matching sibling redo sites. flushmap.cxx: - ErrOpenFlushMap: clamp the flush-map data-page count derived from the (untrusted) persisted .jfm file size to CfmpgGetRequiredFmDataPageCount_(pgnoSysMax), so a crafted over-large file cannot overflow the 32-bit descriptor-capacity arithmetic in ErrAllocateDescriptorsCapacity_ (which otherwise under-commits the descriptor table and later dereferences a NULL descriptor).
logread.cxx (parses untrusted on-disk log files/headers): - ErrVerifyHeader: validate the persisted log-file-header sector size and header span (le_cbSec / le_csecHeader) before advancing past them; a crafted header could otherwise underflow the remaining-byte count (DWORD) and make ErrVerifyLogSegments walk past the buffer (OOB read), or hang when le_cbSec==0. - Log-record reader: treat a zero-size record (e.g. an obsolete/unknown in-range lrtyp for which CbLGSizeOfRec returns 0) as corruption, instead of failing to advance and looping forever. dir.cxx: - ErrDIRIIRefresh: when a secondary index is current, release the secondary-index cursor's page latch if ErrDIRGotoBookmark fails (e.g. OOM), instead of leaking it (the cursor is distinct from the base cursor and was left latched by ErrBTDown). comp.cxx: - ErrCMPCopyTable: guard against a corrupt space tree that reports AvailExt == OwnExt, which made cpgUsed 0 and divided by zero in the progress-meter computation.
…read node.cxx: - ErrNDISetExternalHeader: bound the trailing external-header field copy to the 32-byte stack buffer before UtilMemCpy, matching the retail JET_errInvalidBufferSize guards its two sibling copies already have. cbPostcedingStoredFields derives from the persisted external-header size and could overflow the buffer (large size) or underflow to ~SIZE_MAX (a corrupt flag byte walking the source cursor past the tag) -- the prior AssertRTL is a no-op in retail builds. backup.cxx: - ErrBKIPrepareDirectory (incremental atomic backup): append the "old" subdirectory onto the base backup path (OSStrCbAppendW) instead of overwriting it with a bare "old" (OSStrCbCopyW). The length check sums both lengths and the full-backup branch appends, so a copy sent the incremental backup to a CWD-relative directory. cpage.cxx: - CPAGE::DumpHeader: stop the external-header-size accumulation loop at noderfMax-1 so it cannot read one element past g_rgcbExternalHeaderSize on a page with a corrupt flag byte (diagnostic path).
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.
Summary
A set of small, independent correctness fixes found while reviewing the engine, OS layer, published headers, and unit tests. Each change is a localized defect (memory safety, a wrong operator/variable, a resource leak on an error path, or an ineffective test) with no intended behavior change beyond the fix. They are grouped here for convenience; please take whichever subset you like and I can split into smaller PRs on request.
Highlights
Memory safety / crashes
ese/sysver.cxxErrLGFindFmtVersFromEfv:for ( ULONG i = ...; i >= 0; i-- )never terminates for an unsigned counter and reads out of bounds on the not-found path (two sibling loops already useINT).ese/rec.cxxErrRECIMakeKey: an array allocated withnew[]was freed with scalardelete; also an&&that should be||guarding argStartColumns[0]dereference.ese/space.cxxErrSPCaptureSpaceTreePages: unchecked array allocation + astd::sortoff-by-one that left the last element unsorted.ese/dbscan.cxx,ese/dataserializer.*:unique_ptr<T>owningnew T[](scalar delete of an array) ->unique_ptr<T[]>, plus a missing null-check beforememcpy.Resource leaks / error paths
ese/revertsnapshot.cxx,ese/rbsdump.cxx,os/norm.cxx,os/edbg.cxx,noncore/eseshadow/*,noncore/interop/jetinterop.cpp,os/task.cxx.Logic
inc/pib.hxxErrSetUserIoPriority:|=->=so the QOS IO priority can be lowered again across calls.published/inc/stat.hxx: off-by-one (> 1->> 0) in the monotonicity guard of bothErrGetSampleHitsimplementations.os/string.cxxErrOSSTRAsciiToUnicodeM: advance past the NUL so multi-strings beyond the first substring are converted._log/logwrite.cxx,inc/ccsr.hxx:=->==in asserts;_log/rstmap.cxx: use the inner-loop index;os/blockcache/_hashedlrukcachechunk.hxx: operator precedence;sync/sync.cxx: correct perf-data pointer in term;_xpress9/Xpress9DecLz77.c: misplaced SET_ERROR arg.Tests (
ese/*_test.cxx,test/ese/...)sizeof(pointer), an out-of-bounds read, a missingreturnon a detected inconsistency, a placement-new buffer mismatch, and a wildcard suffix-match fix.Notes
Microsoft Reviewers: Open in CodeFlow