microsoft / microsoft/vs-threading
Add a thread validation rule for usage of GetObjectForIUnknown
Nobody has claimed this yet.
- Dominant language
- C#
- Stars
- 1k
- Forks
- 160
- Avg merge
- 1d 12h
- Merged PRs (30d)
- 28
Description
We run into a bug recently when we clean up code for other thread validation rules. Basically, add SwitchToUIThread to ensure code to use thread bound COM object on the UI thread.
However, this leads into exceptions like:
System.Runtime.InteropServices.COMException (0x8001010E): The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
That happens when a method takes an IntPtr parameter, and need convert it to COM object by calling GetObjectForIUnknown, which must happen on the calling thread. Adding SwitchToUIThread accidently pushes some of those calls to the UI thread, and potentially access a marshalled object on a wrong thread.
It appears this mistake has already been in a few other places in the codebase, and by updating code with existing threading rule, it may lead more mistakes in the future. (And hard to detect until a specific usage pops up.)
It would be worth to add a validation rule when the method has both switching thread calls & GetObjectForIUnknown. It is more difficult if the method switches thread, and passes the IntPtr to another method.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reading the existing thread validation rules and the usages of SwitchToUIThread and GetObjectForIUnknown. Define validation for methods that switch threads before calling GetObjectForIUnknown, including the stated harder case where an IntPtr is passed to another method; done means those unsafe usages are detected without introducing false positives.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- devtools, tooling
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100