Skip to content

Fix assorted correctness bugs found via a code-review sweep - #60

Open
ianjose wants to merge 8 commits into
microsoft:mainfrom
ianjose:fix/correctness-bug-sweep
Open

Fix assorted correctness bugs found via a code-review sweep#60
ianjose wants to merge 8 commits into
microsoft:mainfrom
ianjose:fix/correctness-bug-sweep

Conversation

@ianjose

@ianjose ianjose commented Jul 4, 2026

Copy link
Copy Markdown

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.cxx ErrLGFindFmtVersFromEfv: 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 use INT).
  • ese/rec.cxx ErrRECIMakeKey: an array allocated with new[] was freed with scalar delete; also an && that should be || guarding a rgStartColumns[0] dereference.
  • ese/space.cxx ErrSPCaptureSpaceTreePages: unchecked array allocation + a std::sort off-by-one that left the last element unsorted.
  • ese/dbscan.cxx, ese/dataserializer.*: unique_ptr<T> owning new T[] (scalar delete of an array) -> unique_ptr<T[]>, plus a missing null-check before memcpy.

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.hxx ErrSetUserIoPriority: |= -> = 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 both ErrGetSampleHits implementations.
  • os/string.cxx ErrOSSTRAsciiToUnicodeM: 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/...)

  • 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.

Notes

  • 33 files changed; each change is small and self-contained.
  • Every candidate was verified against surrounding code; suspected-but-intentional patterns were deliberately left unchanged.
  • Validated with editor/language-service diagnostics only (no full build here) - please run through CI.
Microsoft Reviewers: Open in CodeFlow

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.
@microsoft-github-policy-service

Copy link
Copy Markdown
Contributor

@ianjose please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

- 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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants