Skip to content

Fix bugs in the shared Clipboard code for WPF #11401 and #11402. - #14257

Merged
JeremyKuhne merged 1 commit into
dotnet:mainfrom
JeremyKuhne:clip10fix
Jan 31, 2026
Merged

JeremyKuhne merged 1 commit into
dotnet:mainfrom
JeremyKuhne:clip10fix

Conversation

@JeremyKuhne

@JeremyKuhne JeremyKuhne commented Jan 30, 2026 •

Copy link
Copy Markdown
Member

Refactor ReadUtf8StringFromHGLOBAL for safer null-termination and error handling. Prevent double-release of IStream in TryGetIStreamData. Return null instead of corrupted data when GetData fails. Add comprehensive unit tests and new test mocks for edge cases. Update NativeMethods.txt with CLIPBRD_E_CANT_OPEN. Fixes issues #11401 and #11402 in the WPF repo (which also apply to WinForms as the code is shared now).

Microsoft Reviewers: Open in CodeFlow

Refactor ReadUtf8StringFromHGLOBAL for safer null-termination and error handling. Prevent double-release of IStream in TryGetIStreamData. Return null instead of corrupted data when GetData fails. Add comprehensive unit tests and new test mocks for edge cases. Update NativeMethods.txt with CLIPBRD_E_CANT_OPEN. Fixes issues dotnet#11401 and dotnet#11402 in the WPF repo (which also apply to WinForms as the code is shared now).
@JeremyKuhne
JeremyKuhne requested a review from a team as a code owner January 30, 2026 22:08
@JeremyKuhne
JeremyKuhne requested review from Copilot and removed request for a team January 30, 2026 22:08
@github-actions github-actions Bot added the area-Clipboard Issues related to Clipboard label Jan 30, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR improves clipboard and OLE data handling with a focus on safety, correctness, and comprehensive testing. The changes address issues found in WPF that also apply to WinForms due to shared code, specifically fixing potential crashes from double-releasing IStream COM objects and preventing corrupted data from being returned when clipboard operations fail.

Changes:

  • Refactored ReadUtf8StringFromHGLOBAL to safely handle null-termination by searching for the null terminator instead of assuming size-1
  • Fixed double-release bug in TryGetIStreamData by removing ComScope wrapper since ReleaseStgMedium already releases the stream
  • Added early failure check in TryGetHGLOBALData to return null instead of reading potentially uninitialized memory when GetData fails
  • Added comprehensive unit tests covering edge cases for UTF-8 string reading, IStream handling, and GetData failure scenarios
  • Added CLIPBRD_E_CANT_OPEN constant to NativeMethods.txt for clipboard contention error handling

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
src/System.Private.Windows.Core/src/System/Private/Windows/Ole/Composition.NativeToManagedAdapter.cs Core fixes: safer UTF-8 string reading, IStream double-release fix, GetData failure handling, and List-based file collection
src/System.Private.Windows.Core/tests/System.Private.Windows.Core.Tests/System/Private/Windows/Ole/NativeToManagedAdapterTests.cs Comprehensive unit tests for UTF-8 string handling, IStream ref counting, and GetData failure scenarios
src/System.Private.Windows.Core/tests/System.Private.Windows.Core.Tests/System/Private/Windows/Ole/IStreamNativeDataObject.cs Test mock for IStream-based data object to verify proper COM lifetime management
src/System.Private.Windows.Core/tests/System.Private.Windows.Core.Tests/System/Private/Windows/Ole/FailingGetDataNativeDataObject.cs Test mock simulating clipboard contention race condition between QueryGetData and GetData
src/System.Private.Windows.Core/src/NativeMethods.txt Added CLIPBRD_E_CANT_OPEN constant for clipboard error handling

@codecov

codecov Bot commented Jan 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.00000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 77.18798%. Comparing base (333771d) to head (e0e858a).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@                 Coverage Diff                 @@
##                main      #14257         +/-   ##
===================================================
+ Coverage   77.17929%   77.18798%   +0.00869%     
===================================================
  Files           3279        3279                 
  Lines         645129      645138          +9     
  Branches       47728       47730          +2     
===================================================
+ Hits          497906      497969         +63     
+ Misses        143540      143481         -59     
- Partials        3683        3688          +5     
Flag Coverage Δ
Debug 77.18798% <85.00000%> (+0.00869%) ⬆️
integration 18.99238% <15.00000%> (+0.01055%) ⬆️
production 52.07223% <85.00000%> (+0.02026%) ⬆️
test 97.40479% <ø> (ø)
unit 49.53356% <85.00000%> (+0.04294%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Shyam-Gupta

Copy link
Copy Markdown
Member

Looks good.

@JeremyKuhne
JeremyKuhne merged commit 233aa40 into dotnet:main Jan 31, 2026
15 checks passed
@rampaa

rampaa commented Jan 31, 2026

Copy link
Copy Markdown

Does this PR need to be tagged with servicing-consider or something similar in order it to be serviced back to .NET 10?

@JeremyKuhne

Copy link
Copy Markdown
Member Author

@rampaa: @Shyam-Gupta is going to determine how to manage this through the servicing process. It might be manual, separate PRs for each aspect of it.

@KlausLoeffelmann

Copy link
Copy Markdown
Member

@JeremyKuhne, can you briefly explain what the main purpose of this PR was?
It is primarily a bug fix, is that correct?

If it is a bug fix, is there any particular reason not to call it a bug fix?
You wrote

This PR improves clipboard and OLE data handling with a focus on safety, correctness, and comprehensive testing.

And you also wrote later

Fixes issues #14308 and #14322 in the WPF repo (which also apply to WinForms as the code is shared now).

My question is: What does this PR do in addition to fixing the bugs, which would qualify for "improving clipboard and OLE data handling with a focus on safety, correctness, and comprehensive testing" which would go beyond correcting the respective mentioned bugs and adding unit test which would be added primarily in the context of the corrected bugs.

Further, for my own education:
When you write, it fixes the 2 referenced bugs in WPF, but the PR is changing files in the WinForms code base - how is the source code shared mechanically?

If we fix or change something in these respected code files here in the WinForms repo code base, is it then automatically affecting the codebase in WPF (by some automatic replicating mechanism), or do the files need to be replicated (like, copied over) to WPF?

This is not urgent - I just need this for future reference.
I will also have Copilot assemble what kind of documentation status we have around this, and if it thinks we should add respective docs so folks would better know about the dependency between WPF and WinForms in this area - that is not a problem - because I will then trigger it to kick a PR for writing the docs with including a risk assessment off (meaning raising awareness that changing the one in WinForms means changing and potentially regressing the other).

@Shyam-Gupta, @merriemcgaw FYI.

Thanks!

@KlausLoeffelmann

Copy link
Copy Markdown
Member

After consulting with copilot, I followed the advice and had it created 2 new issues and one PR with the docs.

@Shyam-Gupta and @JeremyKuhne:
Could you take a quick look as to the correctness of its approaches/conclusions, and provide feedback about kicking of the 2nd pr, which would add info about the shared nature of the clipboard code to the source files?

@JeremyKuhne, should there are already respective docs or comments in the source, and both Copilot and I should have missed them, could you please point me to them? In that case, I would quickly have copilot amend that info, and have it taken those for all the created items into account.

Thanks!

@KlausLoeffelmann KlausLoeffelmann changed the title Improve clipboard/OLE data handling and test coverage Fix bugs in the shared Clipboard code for WPF #11401 and #11402. Feb 17, 2026
@rampaa

rampaa commented Feb 21, 2026

Copy link
Copy Markdown

@Shyam-Gupta Will there be no backport for the other regression we are experiencing #14322?

@Shyam-Gupta

Copy link
Copy Markdown
Member

@Shyam-Gupta Will there be no backport for the other regression we are experiencing #14322?

I am still investigating that issue on priority, and the plan is to backport it once we have the fix. In our internal testing, we found that the changes in this PR do not address that issue.

Shyam-Gupta added a commit that referenced this pull request Mar 8, 2026
…data from clipboard (#14296)

Fixes #14308

**Description/Customer Impact:** In WPF GitHub repo, a customer reported
that after upgrading to .NET 10, a WPF application intermittently
crashes with an unhandled native CFG violation exception: `Indirect call
guard check detected invalid control transfer`

The crash occurs inside `Clipboard.ContainsText(...)` API when it is
called in response to `WM_CLIPBOARDUPDATE` message. The same code path
worked reliably in previous .NET versions.

**Regression**: Since .NET 9, WinForms and WPF have started using shared
Clipboard code which is owned by WinForms. This change modified the
clipboard logic substantially for both the UI stacks as compared to .NET
8 and previous versions.

**Risk of this change:** Low. The change only avoids using ComScope
which was double freeing the memory pointer. In all other places in the
code, ComScope is not in use for STGMEDIUM. So there is prior art for
this fix.
Although we couldn't repro the issue internally, CTI team did extensive
internal testing with the changes in this PR and didn't find any new
issue.

**Issue**: #14308

**main branch commit**: #14257

**Root cause**: Due to use of ComScope , the STGMEDIUM was getting
released twice - once by ComScope and once in the finally block. It was
causing intermittent CFG exception.

**Fix**: Don't use ComScope in this case.

**Note**: We checked other use cases of STGMEDIUM in the repo and
confirmed that ComScope is not being used for them.

###### Microsoft Reviewers: [Open in
CodeFlow](https://microsoft.github.io/open-pr/?codeflow=https://github.com/dotnet/winforms/pull/14296)
@github-actions github-actions Bot locked and limited conversation to collaborators Mar 26, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-Clipboard Issues related to Clipboard

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants