================================================
FILE: CNAME
================================================
wtrace.net
================================================
FILE: Gemfile
================================================
source "https://rubygems.org"
# Hello! This is where you manage which Jekyll version is used to run.
# When you want to use a different version, change it below, save the
# file and run `bundle install`. Run Jekyll with `bundle exec`, like so:
#
# bundle exec jekyll serve
#
# This will help ensure the proper Jekyll version is running.
# Happy Jekylling!
# gem "jekyll", "~> 4.2.0"
# This is the default theme for new Jekyll sites. You may change this to anything you like.
gem "minima", "~> 2.5"
# gem "jekyll-theme-cayman", "~> 0.2.0"
# If you want to use GitHub Pages, remove the "gem "jekyll"" above and
# uncomment the line below. To upgrade, run `bundle update github-pages`.
gem "github-pages", group: :jekyll_plugins
# If you have any plugins, put them here!
group :jekyll_plugins do
gem "jekyll-feed", "~> 0.12"
end
# Windows and JRuby does not include zoneinfo files, so bundle the tzinfo-data gem
# and associated library.
platforms :mingw, :x64_mingw, :mswin, :jruby do
gem "tzinfo", "~> 1.2"
gem "tzinfo-data"
end
# Performance-booster for watching directories on Windows
gem "wdm", "~> 0.1.1", :platforms => [:mingw, :x64_mingw, :mswin]
gem "webrick", "~> 1.7"
gem "json", "~> 2.7"
================================================
FILE: LICENSE
================================================
Attribution 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution 4.0 International Public License ("Public License"). To the
extent this Public License may be interpreted as a contract, You are
granted the Licensed Rights in consideration of Your acceptance of
these terms and conditions, and the Licensor grants You such rights in
consideration of benefits the Licensor receives from making the
Licensed Material available under these terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
d. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
e. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
f. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
g. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
h. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
i. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
j. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
k. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part; and
b. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
4. If You Share Adapted Material You produce, the Adapter's
License You apply must not prevent recipients of the Adapted
Material from complying with this Public License.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.
================================================
FILE: README.md
================================================
Debug Recipes
=============
It is a repository of my field notes collected while debugging various .NET application problems on Windows (mainly) and Linux. They do not contain much theory but rather describe tools and scripts with some usage examples.
:floppy_disk: Old and no longer updated recipes are in the [archived branch](https://github.com/lowleveldesign/debug-recipes/tree/archive).
The recipes are available in the guides folder and at **[wtrace.net](https://wtrace.net/guides)** (probably the best way to view them).
## Troubleshooting guides
- [Diagnosing .NET applications](guides/diagnosing-dotnet-apps.md)
- [Diagnosing native Windows applications](guides/diagnosing-native-windows-apps.md)
- [COM troubleshooting](guides/com-troubleshooting)
## Tools usage guides
- [WinDbg usage guide](guides/windbg.md)
- [Event Tracing for Windows (ETW)](guides/etw.md)
- [Using withdll and detours to trace Win API calls](guides/using-withdll-and-detours-to-trace-winapi.md)
- [Windows Performance Counters](guides/windows-performance-counters.md)
- [Network tracing tools](guides/network-tracing-tools.md)
================================================
FILE: _config.yml
================================================
title: wtrace.net
email: contact@wtrace.net
description: >- # this means to ignore newlines until "baseurl:"
Tools and materials for software and system troubleshooting
baseurl: "" # the subpath of your site, e.g. /blog
url: "https://wtrace.net" # the base hostname & protocol for your site, e.g. http://example.com
youtube_username: "@lowleveldesign"
github_username: lowleveldesign
permalink: pretty
defaults:
-
scope:
path: ""
type: "posts"
values:
permalink: /:year/:month/:day/:title
# Build settings
theme: minima
plugins:
- jekyll-feed
- jekyll-seo-tag
- jekyll-redirect-from
- jekyll-sitemap
- jemoji
header_pages:
- guides.md
- tools.md
- about.md
================================================
FILE: _includes/footer.html
================================================
================================================
FILE: _includes/head.html
================================================
{%- seo -%}
{%- feed_meta -%}
{%- if jekyll.environment == 'production' and site.google_analytics -%}
{%- include google-analytics.html -%}
{%- endif -%}
================================================
FILE: _layouts/home.html
================================================
---
---
{%- include head.html -%}
{%- include header.html -%}
================================================
FILE: about.md
================================================
---
layout: page
title: About
---
I am **Sebastian Solnica**, a software engineer with more than 15 years of experience. My primary interests are debugging, profiling, and application security. I created this website to share tools and resources that can help you in your diagnostic endeavors.
I also provide consulting services for troubleshooting .NET applications. If you would like to discuss consulting or contact me for any other reason, please use [the contact form on my blog](https://lowleveldesign.org/about/) or email me at contact@wtrace.net.
Credits: this site uses modified icons from the feather set.
================================================
FILE: articles.md
================================================
---
layout: page
title: Articles
redirect_to: /guides
---
================================================
FILE: assets/main.scss
================================================
---
# Only the main Sass file needs front matter (the dashes are enough)
---
$brand-color: #CA4E07;
$credits-color: #707070;
@import "minima";
body {
background-color: #f6f6ef;
}
pre, code {
background: transparent;
}
.highlighter-rouge .highlight {
background: #f9f9f9;
}
.highlight .c {
color: #6c6c62;
}
.post-title {
@include relative-font-size(2.2);
letter-spacing: -1px;
line-height: 1;
@include media-query($on-laptop) {
@include relative-font-size(2.0);
}
}
.post-content {
table {
table-layout: fixed;
}
table th {
text-align: center;
}
table td {
vertical-align: top;
}
h2, h3 {
margin: 15px 0 15px 0;
}
}
.site-title {
@include relative-font-size(1.4);
font-weight: 700;
line-height: $base-line-height * $base-font-size * 2.25;
letter-spacing: -1px;
margin-bottom: 0;
float: left;
text-transform: uppercase;
&, &:visited {
color: $brand-color;
}
}
.site-nav {
.page-link {
text-transform: uppercase;
font-weight: 600;
}
}
.feature-image {
background-color: black;
background-repeat: no-repeat;
margin-bottom: 10px;
padding-top: 50px;
height: 300px;
.wrapper {
color: #ffffff;
h1 {
font-size: 4rem;
font-weight: 900;
margin-bottom: 0px
}
p {
font-size: 1.2rem;
}
}
}
p.credits {
color: $credits-color;
padding-top: 10px;
margin-top: 10px;
}
================================================
FILE: assets/other/EtwMetadata.ps1.txt
================================================
$ErrorActionPreference = "Stop"
$MetadataFolder = "$env:LOCALAPPDATA\MyEtwMetadata\ById"
$MetadataSearchByNameFolder = "$env:LOCALAPPDATA\MyEtwMetadata\ByName"
if (-not (Test-Path $MetadataFolder)) {
New-Item -ItemType Directory -Path $MetadataFolder | Out-Null
}
if (-not (Test-Path $MetadataSearchByNameFolder)) {
New-Item -ItemType Directory -Path $MetadataSearchByNameFolder | Out-Null
}
function _SanitizeFileName {
param ([Parameter(Mandatory = $true)]$FileName)
[System.IO.Path]::GetInvalidFileNameChars() | ForEach-Object -Process {
$FileName = $FileName.Replace($_, [char]'_')
}
$FileName
}
Write-Output "Initializing ETW providers metadata... "
wevtutil.exe ep | ForEach-Object -Process {
$ProviderName = $_
Write-Debug $ProviderName
$xml = $(wevtutil.exe gp /f:xml "$_" 2>$null)
if ($LASTEXITCODE -eq 0 -and $xml) {
$metadata = [xml]$xml
$metadata.Save($(Join-Path -Path $MetadataFolder -ChildPath "$($metadata.provider.guid).xml"));
$metadata.provider.guid | Out-File $(
Join-Path -Path $MetadataSearchByNameFolder -ChildPath "$(_SanitizeFileName $ProviderName).txt")
}
else {
Write-Warning "Invalid metadata for '$ProviderName'"
}
}
function _ResolveKeywords {
param (
[Parameter(Mandatory = $true)]$Metadata,
[Parameter(Mandatory = $true)][ulong]$Keywords
)
if ($Metadata.provider.keywords) {
$Metadata.provider.keywords.keyword | ForEach-Object -Process {
$MaskValue = [ulong]::Parse($_.mask.TrimStart(@('0', 'x', 'X')), [System.Globalization.NumberStyles]::HexNumber)
if ($Keywords -band $MaskValue) {
[PSCustomObject]@{
Name = $_.name
Value = $MaskValue
}
}
}
}
}
# ** EXPORTS **
function Get-EtwProvidersFromWprProfile {
param (
[Parameter(Mandatory = $true)][string]$WprProfilePath
)
if (-not (Test-Path $MetadataFolder)) {
Write-Error "No metadata found - please run Initialize-EtwProvidersMetadata first."
}
function ParseProvider([Parameter(ValueFromPipeline = $true, Mandatory = $true)]$ProviderData) {
begin {}
process {
$MetadataPath = (Join-Path -Path $MetadataFolder -ChildPath "$($ProviderData.Name).xml")
if (-not (Test-Path $MetadataPath)) {
Write-Warning "No metadata found for provider '$($ProviderData.Name)'"
return
}
Write-Debug "Parsing provider '$($ProviderData.Name))'"
$Metadata = [xml](Get-Content $MetadataPath)
[ulong]$Keywords = 0
if ($ProviderData.Keywords) {
$ProviderData.Keywords.Keyword.Value | ForEach-Object -Process {
$Keywords = $Keywords -bor ([ulong]::Parse($_.TrimStart(@('0', 'x', 'X')), [System.Globalization.NumberStyles]::HexNumber)) }
}
else {
$Keywords = [ulong]::MaxValue
}
[ulong]$CaptureOnSaveKeywords = 0
if ($ProviderData.CaptureOnSaveKeywords) {
$ProviderData.CaptureStateOnSave.Keyword.Value | ForEach-Object -Process {
$CaptureOnSaveKeywords = $CaptureOnSaveKeywords -bor ([ulong]::Parse($_.TrimStart(@('0', 'x', 'X')), [System.Globalization.NumberStyles]::HexNumber)) }
}
[PSCustomObject]@{
Id = $ProviderData.Name
Name = $Metadata.provider.name
Keywords = _ResolveKeywords $Metadata $Keywords
CaptureOnSaveKeywords = _ResolveKeywords $Metadata $CaptureOnSaveKeywords
}
}
end {}
}
$xml = [xml](Get-Content $WprProfilePath)
$xml.WindowsPerformanceRecorder.Profiles.EventProvider | ParseProvider
}
function Get-EtwProviderMetadata {
param([Parameter(ValueFromPipeline = $true, Mandatory = $true)]$ProviderName)
$ProviderId = $ProviderName
$Path = $(Join-Path -Path $MetadataSearchByNameFolder -ChildPath "$(_SanitizeFileName $ProviderName).txt")
if (Test-Path $Path) {
$ProviderId = Get-Content $Path
}
$MetadataPath = (Join-Path -Path $MetadataFolder -ChildPath "$ProviderId.xml")
if (-not (Test-Path $MetadataPath)) {
Write-Error "No metadata found for provider '$($ProviderId)'"
}
$Metadata = [xml](Get-Content $MetadataPath)
[PSCustomObject]@{
Id = $ProviderId
Name = $Metadata.provider.name
Keywords = _ResolveKeywords $Metadata $([ulong]::MaxValue)
}
}
================================================
FILE: assets/other/WTComTrace.wprp
================================================
================================================
FILE: assets/other/winapi-user32.ps1.txt
================================================
$ErrorActionPreference = "Stop"
Add-Type -TypeDefinition @"
using System;
public enum GWL_EXSTYLE : int {
WS_EX_DLGMODALFRAME = 0x00000001,
WS_EX_NOPARENTNOTIFY = 0x00000004,
WS_EX_TOPMOST = 0x00000008,
WS_EX_ACCEPTFILES = 0x00000010,
WS_EX_TRANSPARENT = 0x00000020,
WS_EX_MDICHILD = 0x00000040,
WS_EX_TOOLWINDOW = 0x00000080,
WS_EX_WINDOWEDGE = 0x00000100,
WS_EX_CLIENTEDGE = 0x00000200,
WS_EX_CONTEXTHELP = 0x00000400,
WS_EX_RIGHT = 0x00001000,
WS_EX_LEFT = 0x00000000,
WS_EX_RTLREADING = 0x00002000,
WS_EX_LTRREADING = 0x00000000,
WS_EX_LEFTSCROLLBAR = 0x00004000,
WS_EX_RIGHTSCROLLBAR = 0x00000000,
WS_EX_CONTROLPARENT = 0x00010000,
WS_EX_STATICEDGE = 0x00020000,
WS_EX_APPWINDOW = 0x00040000,
WS_EX_LAYERED = 0x00080000,
WS_EX_NOINHERITLAYOUT = 0x00100000,
WS_EX_NOREDIRECTIONBITMAP = 0x00200000,
WS_EX_LAYOUTRTL = 0x00400000,
WS_EX_COMPOSITED = 0x02000000,
WS_EX_NOACTIVATE = 0x08000000
}
public enum GWL_STYLE : int {
WS_OVERLAPPED = 0x00000000,
WS_POPUP = unchecked((int)0x80000000),
WS_CHILD = 0x40000000,
WS_MINIMIZE = 0x20000000,
WS_VISIBLE = 0x10000000,
WS_DISABLED = 0x08000000,
WS_CLIPSIBLINGS = 0x04000000,
WS_CLIPCHILDREN = 0x02000000,
WS_MAXIMIZE = 0x01000000,
WS_CAPTION = 0x00C00000,
WS_BORDER = 0x00800000,
WS_DLGFRAME = 0x00400000,
WS_VSCROLL = 0x00200000,
WS_HSCROLL = 0x00100000,
WS_SYSMENU = 0x00080000,
WS_THICKFRAME = 0x00040000,
// WS_GROUP = 0x00020000,
// WS_TABSTOP = 0x00010000,
WS_MINIMIZEBOX = 0x00020000,
WS_MAXIMIZEBOX = 0x00010000,
// WS_TILED = WS_OVERLAPPED,
// WS_ICONIC = WS_MINIMIZE,
// WS_SIZEBOX = WS_THICKFRAME
}
public enum SWP : uint {
SWP_NOSIZE = 0x0001,
SWP_NOMOVE = 0x0002,
SWP_NOZORDER = 0x0004,
SWP_NOREDRAW = 0x0008,
SWP_NOACTIVATE = 0x0010,
SWP_FRAMECHANGED = 0x0020,
SWP_SHOWWINDOW = 0x0040,
SWP_HIDEWINDOW = 0x0080,
SWP_NOCOPYBITS = 0x0100,
SWP_NOOWNERZORDER = 0x0200,
SWP_NOSENDCHANGING = 0x0400,
// SWP_DRAWFRAME = SWP_FRAMECHANGED,
// SWP_NOREPOSITION = SWP_NOOWNERZORDER,
SWP_DEFERERASE = 0x2000,
SWP_ASYNCWINDOWPOS = 0x4000
}
"@
================================================
FILE: assets/other/windbg-install.ps1.txt
================================================
# script created by @Izybkr (https://github.com/microsoftfeedback/WinDbg-Feedback/issues/19#issuecomment-1513926394) with my minor updates to make it work with latest WinDbg releases):
param(
$OutDir = ".",
[ValidateSet("x64", "x86", "arm64")]
$Arch = "x64"
)
if (!(Test-Path $OutDir)) {
$null = mkdir $OutDir
}
$ErrorActionPreference = "Stop"
if ($PSVersionTable.PSVersion.Major -le 5) {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# This is a workaround to get better performance on older versions of PowerShell
$ProgressPreference = 'SilentlyContinue'
}
# Download the appinstaller to find the current uri for the msixbundle
Invoke-WebRequest https://aka.ms/windbg/download -OutFile $OutDir\windbg.appinstaller
# Download the msixbundle
$msixBundleUri = ([xml](Get-Content $OutDir\windbg.appinstaller)).AppInstaller.MainBundle.Uri
# Download the msixbundle (but name as zip for older versions of Expand-Archive
Invoke-WebRequest $msixBundleUri -OutFile $OutDir\windbg.zip
# Extract the 3 msix files (plus other files)
Expand-Archive -DestinationPath $OutDir\UnzippedBundle $OutDir\windbg.zip
# Expand the build you want - also renaming the msix to zip for Windows PowerShell
$fileName = switch ($Arch) {
"x64" { "windbg_win-x64" }
"x86" { "windbg_win-x86" }
"arm64" { "windbg_win-arm64" }
}
# Rename msix (for older versions of Expand-Archive) and extract the debugger
Rename-Item "$OutDir\UnzippedBundle\$fileName.msix" "$fileName.zip"
Expand-Archive -DestinationPath "$OutDir\windbg" "$OutDir\UnzippedBundle\$fileName.zip"
Remove-Item -Recurse -Force "$OutDir\UnzippedBundle"
Remove-Item -Force "$OutDir\windbg.appinstaller"
Remove-Item -Force "$OutDir\windbg.zip"
# Now you can run:
& $OutDir\windbg\DbgX.Shell.exe
================================================
FILE: browserconfig.xml
================================================
#da532c
================================================
FILE: guides/com-troubleshooting.md
================================================
---
layout: page
title: COM troubleshooting
date: 2023-04-07 08:00:00 +0200
redirect_from:
- /articles/com-troubleshooting/
- /articles/com-troubleshooting
---
{% raw %}
**Table of contents:**
- [Quick introduction to COM](#quick-introduction-to-com)
- [COM metadata](#com-metadata)
- [Troubleshooting COM in WinDbg](#troubleshooting-com-in-windbg)
- [Monitoring COM objects in a process](#monitoring-com-objects-in-a-process)
- [Tracing COM methods](#tracing-com-methods)
- [Stopping the COM monitor](#stopping-the-com-monitor)
- [Observing COM interactions outside WinDbg](#observing-com-interactions-outside-windbg)
- [Windows Performance Recorder \(wpr.exe\)](#windows-performance-recorder-wprexe)
- [Process Monitor](#process-monitor)
- [wtrace](#wtrace)
- [Troubleshooting .NET COM interop](#troubleshooting-net-com-interop)
- [Links](#links)
Quick introduction to COM
-------------------------
In COM, everything is about interfaces. In old times, when various compiler vendors were fighting over whose "standard" was better, the only reliable way to call C++ class methods contained in third-party libraries was to use virtual tables. As its name suggests virtual table is a table, to be precise, a table of addresses (pointers). The "virtual" adjective relates to the fact that our table's addresses point to virtual methods. If you're familiar with object programming (you plan to debug COM, so you should!), you probably thought of inheritance and abstract classes. And that's correct! The abstract class is how we implement interfaces in C++ (to be more precise [an abstract class with pure virtual methods](https://en.cppreference.com/w/cpp/language/abstract_class)). Now, COM is all about passing pointers to those various virtual tables which happen to have GUID identifiers. The most important interface (parent of all interfaces) is `IUnknown`. Every COM interface must inherit from this interface. Why? For two reasons: to manage the object lifetime and to access all the other interfaces that our object may implement (or, in other words, to find all virtual tables our object is aware of). As this interface is so important, let's have a quick look at its definition:
```cpp
struct __declspec(uuid("00000000-0000-0000-C000-000000000046"))) IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) = 0;
virtual ULONG STDMETHODCALLTYPE AddRef( void) = 0;
virtual ULONG STDMETHODCALLTYPE Release( void) = 0;
};
```
Guess which methods are responsible for lifetime management and which are for interface querying. OK, so we know the declaration, but to debug COM, we need to understand how COM objects are laid out in the memory. Let's have a look at a sample Probe class (the snippet comes from [my Protoss COM example repository](https://github.com/lowleveldesign/protoss-com-example)):
```cpp
struct __declspec(uuid("59644217-3e52-4202-ba49-f473590cc61a")) IGameObject : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE get_Name(BSTR* name) = 0;
virtual HRESULT STDMETHODCALLTYPE get_Minerals(LONG* minerals) = 0;
virtual HRESULT STDMETHODCALLTYPE get_BuildTime(LONG* buildtime) = 0;
};
struct __declspec(uuid("246A22D5-CF02-44B2-BF09-AAB95A34E0CF")) IProbe : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE ConstructBuilding(BSTR building_name, IUnknown * *ppUnk) = 0;
};
class __declspec(uuid("EFF8970E-C50F-45E0-9284-291CE5A6F771")) Probe final : public IProbe, public IGameObject
{
ULONG ref_count;
/* ... implementation .... */
}
```
If we instantiate (more on that later) the Probe class, its layout in the memory will look as follows:
```
0:000> dps 0xfb2f58 L4
00fb2f58 72367744 protoss!Probe::`vftable'
00fb2f5c 7236775c protoss!Probe::`vftable'
00fb2f60 00000001
00fb2f64 fdfdfdfd
0:000> dps 72367744 L4 * IProbe interface
72367744 72341bb3 protoss!ILT+2990(?QueryInterfaceProbeUAGJABU_GUIDPAPAXZ)
72367748 72341ba9 protoss!ILT+2980(?AddRefProbeUAGKXZ)
7236774c 723411ae protoss!ILT+425(?ReleaseProbeUAGKXZ)
72367750 723414d3 protoss!ILT+1230(?ConstructBuildingProbeUAGJPA_WPAPAUIUnknownZ)
0:000> dps 7236775c L6 * IGameUnit interface
7236775c 72341e3d protoss!ILT+3640(?QueryInterfaceProbeW3AGJABU_GUIDPAPAXZ)
72367760 723416fe protoss!ILT+1785(?AddRefProbeW3AGKXZ)
72367764 72341096 protoss!ILT+145(?ReleaseProbeW3AGKXZ)
72367768 723415f0 protoss!ILT+1515(?get_NameProbeUAGJPAPA_WZ)
7236776c 723419d8 protoss!ILT+2515(?get_MineralsProbeUAGJPAJZ)
72367770 72341e1a protoss!ILT+3605(?get_BuildTimeProbeUAGJPAJZ)
```
Notice the pointers at the beginning of the object memory. As you can see in the snippet, those pointers reference arrays of function pointers or, as you remember, virtual tables. Each virtual table represents a COM interface, like `IProbe` or `IGameObject` in our case.
Let's now briefly discuss the creation of COM objects. We usually start by calling one of the well-known Co-functions to create a COM object. Often, it's either `CoCreateInstance` or `CoGetClassObject`. Those functions perform actions defined in the COM registration (either in a manifest file or in the registry). In the most common (and most straightforward scenario), they load a dll and run the exported `DllGetClassObject` function:
```cpp
HRESULT DllGetClassObject([in] REFCLSID rclsid, [in] REFIID riid, [out] LPVOID *ppv);
```
On a successful return, the `*ppv` value should point to an address of the virtual table representing a COM interface with the IID equal to `riid`. And this address will be a part of memory belonging to a COM object of the type identified by the `rclsid`.
People often say that COM is complicated. As you just saw, COM fundamentals are clear and straightforward. However, its various implementations might cause a headache. For example, there are myriads of methods in OLE and ActiveX interfaces created to make it possible to drag/drop things between windows, use the clipboard, or embed one control in another. Remember, though, that all those crazy interfaces still need to implement `IUnknown`. And that's the advantage we can take as troubleshooters. It's easy to track new instance creations, interface queries, and interface method calls (often even with their names). That may give us enough insights to debug a problem successfully.
### COM metadata
COM metadata, saved in type libraries, provides definitions of COM classes and COM interfaces. Thanks to it, we can decode method names and their argument values without debugging symbols. The tool we usually use to view the type libraries installed in the system is [OleView](https://learn.microsoft.com/en-us/windows/win32/com/ole-com-object-viewer), part of the Windows SDK. OleView has some open-source alternatives, such as [.NET OLE/COM viewer](https://github.com/tyranid/oleviewdotnet) or [OleWoo](https://github.com/leibnitz27/olewoo). [Comon](https://github.com/lowleveldesign/comon) also provides the **!cometa** command, which allows you to use COM metadata without leaving WinDbg. Before the debugging session, it is worth taking a moment to build the cometa database with the **!cometa index** command. The database resides in a temporary folder. It's an SQLite database, so you may copy it between machines. Other comon commands will use the cometa database to resolve class and interface IDs to meaningful names.
You may also do some basic queries against the database with the **!cometa showc** and **!cometa showi** commands, for example:
```
0:000> !cometa showi {59644217-3E52-4202-BA49-F473590CC61A}
Found: {59644217-3E52-4202-BA49-F473590CC61A} (IGameObject)
Methods:
- [0] HRESULT QueryInterface(void* this, GUID* riid, void** ppvObject)
- [1] ULONG AddRef(void* this)
- [2] ULONG Release(void* this)
- [3] HRESULT get_Name(void* this, BSTR* Name)
- [4] HRESULT get_Minerals(void* this, long* Minerals)
- [5] HRESULT get_BuildTime(void* this, long* BuildTime)
Registered VTables for IID:
- Module: protoss, CLSID: {EFF8970E-C50F-45E0-9284-291CE5A6F771} (Probe), VTable offset: 0x3775c
- Module: protoss, CLSID: {F5353C58-CFD9-4204-8D92-D274C7578B53} (Nexus), VTable offset: 0x37710
```
Troubleshooting COM in WinDbg
-----------------------------
### Monitoring COM objects in a process
There are various ways in which COM objects can be created. When a given function creates a COM object, you will see a `void **` as one of its arguments. After a successful call, this pointer will point to a new COM object. Let's check how we can trace such a creation. We will use breakpoints to monitor calls to the `CoCreateInstance(REFCLSID rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID *ppv)` function. We are interested in the class (`rclsid`) and interface (`riid`) values, and the address of the created COM object (`*ppv`). When debugging a 64-bit process, our breakpoint command might look as follows:
```
bp combase!CoCreateInstance ".echo ==== combase!CoCreateInstance ====; dps @rsp L8; dx *(combase!GUID*)@rcx; dx *(combase!GUID*)@r9; .printf /D \"==> obj addr: %p\", poi(@rsp+28);.echo; bp /1 @$ra; g"
```
The `bp /1 @$ra` part creates a one-time breakpoint at a function return address. This second breakpoint will stop the process execution and allow us to examine the results of the function call. At this time, the `rax` register will show the return code (should be `0` for a successful call), and the created COM object (and also the interface virtual) will be at the previously printed object address. For the sake of completeness, let me show you the 32-bit version of this breakpoint:
```
bp combase!CoCreateInstance ".echo ==== combase!CoCreateInstance ====; dps @esp L8; dx **(combase!GUID **)(@esp + 4); dx **(combase!GUID **)(@esp + 0x10); .printf /D \"==> obj addr: %p\", poi(@esp+14);.echo; bp /1 @$ra; g"
```
Creating such breakpoints for various COM functions might be a mundane task, especially when we consider that our only point in doing so is to save the addresses of the virtual tables. **Fortunately, [comon](https://github.com/lowleveldesign/comon) might be of help here**. In-process COM creation usually ends in a call to the `DllGetClassObject` function exported by the DLL implementing a given COM object. After **attaching to a process** (**!comon attach**), comon creates breakpoints on all such functions and checks the results of their executions. It also breaks when a process calls `CoRegisterClassObject`, a function called by out-of-process COM servers to register the COM objects they host.
After you attach comon to a debugged process, you should see various log messages showing COM object creations, for example:
```
0:000> !comon attach
COM monitor enabled for the current process.
0:000> g
...
[comon] 0:000 [protoss!DllGetClassObject] CLSID: {EFF8970E-C50F-45E0-9284-291CE5A6F771} (Protoss Probe), IID: {00000001-0000-0000-C000-000000000046} (IClassFactory) -> SUCCESS (0x0)
[comon] 0:000 [IClassFactory::CreateInstance] CLSID: {EFF8970E-C50F-45E0-9284-291CE5A6F771} (Protoss Probe), IID: {246A22D5-CF02-44B2-BF09-AAB95A34E0CF} (IProbe) -> SUCCESS (0x0)
[comon] 0:000 [IUnknown::QueryInterface] CLSID: {EFF8970E-C50F-45E0-9284-291CE5A6F771} (Protoss Probe), IID: {59644217-3E52-4202-BA49-F473590CC61A} (IGameObject) -> SUCCESS (0x0)
[comon] 0:000 [protoss!DllGetClassObject] CLSID: {F5353C58-CFD9-4204-8D92-D274C7578B53} (Protoss Nexus), IID: {00000001-0000-0000-C000-000000000046} (IClassFactory) -> SUCCESS (0x0)
[comon] 0:000 [IClassFactory::CreateInstance] CLSID: {F5353C58-CFD9-4204-8D92-D274C7578B53} (Protoss Nexus), IID: {C5F45CBC-4439-418C-A9F9-05AC67525E43} (INexus) -> SUCCESS (0x0)
[comon] 0:000 [IUnknown::QueryInterface] CLSID: {F5353C58-CFD9-4204-8D92-D274C7578B53} (Protoss Nexus), IID: {59644217-3E52-4202-BA49-F473590CC61A} (IGameObject) -> SUCCESS (0x0)
...
```
The `QueryInterface` calls will show up only for the first time; it won't be reported if we have the virtual table for a given interface already registered in the cometa database. To check the COM objects registered in a given session, run the **!comon status** command, for example:
```
0:000> !comon status
COM monitor is RUNNING
COM types recorded for the current process:
CLSID: {F5353C58-CFD9-4204-8D92-D274C7578B53} (Nexus)
IID: {C5F45CBC-4439-418C-A9F9-05AC67525E43} (INexus), address: 0x723676f8
IID: {00000001-0000-0000-C000-000000000046} (N/A), address: 0x7236694c
IID: {59644217-3E52-4202-BA49-F473590CC61A} (IGameObject), address: 0x72367710
CLSID: {EFF8970E-C50F-45E0-9284-291CE5A6F771} (Probe)
IID: {00000001-0000-0000-C000-000000000046} (N/A), address: 0x72366968
IID: {59644217-3E52-4202-BA49-F473590CC61A} (IGameObject), address: 0x7236775c
IID: {246A22D5-CF02-44B2-BF09-AAB95A34E0CF} (IProbe), address: 0x72367744
```
The `cometa` queries show now also return information about the registered virtual tables:
```
0:000> !cometa showc {F5353C58-CFD9-4204-8D92-D274C7578B53}
Found: {F5353C58-CFD9-4204-8D92-D274C7578B53} (Nexus)
Registered VTables for CLSID:
- module: protoss, IID: {00000001-0000-0000-C000-000000000046} (N/A), VTable offset: 0x3694c
- module: protoss, IID: {59644217-3E52-4202-BA49-F473590CC61A} (IGameObject), VTable offset: 0x37710
- module: protoss, IID: {C5F45CBC-4439-418C-A9F9-05AC67525E43} (INexus), VTable offset: 0x376f8
```
### Tracing COM methods
When we know the interface virtual table address, nothing can stop us from creating breakpoints on interface methods :) I will first show you how to do that manually and later present how [comon](https://github.com/lowleveldesign/comon) may help.
The first step is to find the offset of our method in the interface definition. Let's stick to the Protoss COM example and let's create a breakpoint on the `get_Minerals` method/property from the `IGameObject` interface:
```
0:000> !cometa showi {59644217-3E52-4202-BA49-F473590CC61A}
Found: {59644217-3E52-4202-BA49-F473590CC61A} (IGameObject)
Methods:
- [0] HRESULT QueryInterface(void* this, GUID* riid, void** ppvObject)
- [1] ULONG AddRef(void* this)
- [2] ULONG Release(void* this)
- [3] HRESULT get_Name(void* this, BSTR* Name)
- [4] HRESULT get_Minerals(void* this, long* Minerals)
- [5] HRESULT get_BuildTime(void* this, long* BuildTime)
Registered VTables for IID:
- Module: protoss, CLSID: {EFF8970E-C50F-45E0-9284-291CE5A6F771} (Probe), VTable offset: 0x3775c
- Module: protoss, CLSID: {F5353C58-CFD9-4204-8D92-D274C7578B53} (Nexus), VTable offset: 0x37710
```
We can see that its ordinal number is four, and two virtual tables are registered for our interface (two classes implementing it). Let's focus on the `Probe` class. To set a breakpoint method, we can use the `bp` command:
```
bp poi(protoss + 0x3775c + 4 * $ptrsize)
```
Similarly, if we would like to set breakpoints on all the `IGameObject` methods, we might use a loop:
```
.for (r $t0 = 0; @$t0 < 6; r $t0 = @$t0 + 1) { bp poi(protoss + 0x3775c + @$t0 * @$ptrsize) }
```
Instead of setting breakpoints manually, you may use the **!cobp** command from the comon extension. It also creates a breakpoint (you will see it if you run the bl command), but on hit, comon will decode the method parameters (for the supported types). It will also automatically create a one-time breakpoint on the method return address, displaying the return code and method out parameter values. The optional parameter lets you decide if you'd like to stop when cobreakpoint is hit. An example output might look as follows:
```
0:000> !cobp --always {EFF8970E-C50F-45E0-9284-291CE5A6F771} {59644217-3E52-4202-BA49-F473590CC61A} get_Name
[comon] Breakpoint 18 (address 0x723415f0) created / updated
0:000> g
[comon breakpoint] IGameObject::get_Name (iid: {59644217-3E52-4202-BA49-F473590CC61A}, clsid: {EFF8970E-C50F-45E0-9284-291CE5A6F771})
Parameters:
- this: 0xfb2f5c (void*)
- Name: 0x81fc1c (BSTR*) [out]
0:000> dps 0081fc1c L1
0081fc1c 00000000
0:000> g
[comon breakpoint] IGameObject::get_Name (iid: {59644217-3E52-4202-BA49-F473590CC61A}, clsid: {EFF8970E-C50F-45E0-9284-291CE5A6F771}) return
Result: 0x0 (HRESULT)
Out parameters:
- Name: 0x81fc1c (BSTR*)
0:000> du 00f9c6ac
00f9c6ac "Probe"
```
If comon can't decode a given parameter, you may use the **dx** command with combase.dll symbols (one of the rare Microsoft DLLs that comes with private symbols), for example: `dx -r2 (combase!DISPPARAMS *)(*(void **)(@esp+0x18))` or `dx -r1 ((combase!tagVARIANT[3])0x31ec1f0)`.
### Stopping the COM monitor
Run the **!comon detach** command to stop the COM monitor. This command will remove all the comon breakpoints and debugging session data, but you can still examine COM metadata with the cometa command.
Observing COM interactions outside WinDbg
-----------------------------------------
Sometimes we only need basic information about COM interactions, such as which objects are used and how they are launched. While WinDbg can be overkill for such scenarios, there are several simpler tools we can use to collect this additional information.
### Windows Performance Recorder (wpr.exe)
Let's begin with wpr.exe, a powerful tool that's likely already installed on your system. WPR requires profile files to configure tracing sessions. For basic COM event collection, you can use [the ComTrace.wprp profile](https://raw.githubusercontent.com/microsoft/winget-cli/refs/heads/master/tools/COMTrace/ComTrace.wprp) from [the winget-cli repository](https://github.com/microsoft/winget-cli). I've also created an enhanced profile, adding providers found in the [TSS scripts](https://learn.microsoft.com/en-us/troubleshoot/windows-client/windows-tss/introduction-to-troubleshootingscript-toolset-tss), which you can download **[here](/assets/other/WTComTrace.wprp)**. You can use those profiles either solely or in combination with other profiles, as shown in the examples below.
```shell
# Collect only COM events
wpr.exe -start .\WTComTrace.wprp -filemode
# Run COM apps ...
# Stop the trace when done
wpr -stop C:\temp\comtrace.etl
# Collect COM events with CPU sampling
wpr.exe -start CPU -start .\WTComTrace.wprp -filemode
# Run COM apps ...
# Stop the trace when done
wpr -stop C:\temp\comtrace.etl
```
Some providers are the [legacy WPP providers](https://learn.microsoft.com/en-us/windows-hardware/drivers/devtest/wpp-software-tracing), which require TMF files to read the collected events. Fortunately, the PDB file for compbase.dll contains the required TMF data and we can decode those events. To view the collected data, open the ETL file in **[Windows Performance Analyzer (WPA)](https://learn.microsoft.com/en-us/windows-hardware/test/wpt/windows-performance-analyzer)**. Remember to load symbols first (check [the Windows configuration guide](guides/configuring-windows-for-effective-troubleshooting/#configuring-debug-symbols) how to configure symbols globally in the system), then navigate to the **Generic Events** category and open the **WPP Trace** view.
### Process Monitor
In **[Process Monitor](https://learn.microsoft.com/en-us/sysinternals/downloads/procmon)**, we can include Registry and Process events and events where Path contains `\CLSID\` or `\AppID` strings or ends with `.dll`, as in the image below:

The collected events should tell us which COM objects the application initiated and in which way. For example, if procmon shows a DLL path read from the `InprocServer32` and then we see this dll loaded, we may assume that the application created a given COM object (the event call stack may be an additional proof). If the COM server runs in a standalone process or a remote machine, other keys will be queried. We may then check the Process Tree or Network events for more details. [COM registry keys official documentation](https://learn.microsoft.com/en-us/windows/win32/com/com-registry-keys) is thorough, so please consult it to learn more.
### wtrace
In **[wtrace](https://github.com/lowleveldesign/wtrace)**, we need to pick the proper handlers and define filters. An example command line might look as follows:
```shell
wtrace --handlers registry,process,rpc -f 'path ~ \CLSID\' -f 'path ~ \AppID\' -f 'path ~ rpc' -f 'pname = ProtossComClient'
```
As you can see, wtrace may additionally show information about RPC (Remote Procedure Call) events.
Troubleshooting .NET COM interop
--------------------------------
A native COM object must be wrapped into a Runtime Callable Wrapper (RCW) to be accessible to managed code. RCW binds a managed object (for example, `System.__Com`) and a native COM class instance. COM Callable Wrappers (CCW) work in the opposite direction - thanks to them, we may expose .NET objects to the COM world. Interestingly, the object interop usage is saved in the object's SyncBlock. Therefore, it should not come as a surprise that the **!syncblk** command from [the SOS extension](https://learn.microsoft.com/en-us/dotnet/core/diagnostics/sos-debugging-extension) presents information about RCWs and CCWs:
```
0:011> !syncblk
Index SyncBlock MonitorHeld Recursion Owning Thread Info SyncBlock Owner
-----------------------------
Total 5
CCW 1
RCW 0
ComClassFactory 0
Free 3
```
When we add the **-all** parameter, **!syncblk** will list information about the created SyncBlocks with their corresponding objects, for example:
```
0:007> !syncblk -all
Index SyncBlock MonitorHeld Recursion Owning Thread Info SyncBlock Owner
1 07FF8F54 0 0 00000000 none 030deb48 System.__ComObject
2 07FF8F20 0 0 00000000 none 030deb3c EventTesting
3 00000000 0 0 00000000 none 0 Free
4 00000000 0 0 00000000 none 0 Free
5 00000000 0 0 00000000 none 0 Free
-----------------------------
Total 5
CCW 1
RCW 0
ComClassFactory 0
Free 3
```
Now, we can dump information about managed objects using the **!dumpobj** command, for example:
```
0:006> !dumpobj 030deb3c
Name: EventTesting
MethodTable: 08301668
EEClass: 082f7110
CCW: 0833ffe0
Tracked Type: false
Size: 12(0xc) bytes
File: c:\repos\testing-com-events\bin\NETServer.dll
Fields:
MT Field Offset Type VT Attr Value Name
0830db50 4000003 4 ...ng+OnEventHandler 0 instance 00000000 onEvent```
```
The good news is that the **!dumpobj** command also checks if a given object has a SyncBlock assigned and dumps information from it. In this case, it's the address of CCW. We may get more details about it by using the **!dumpccw** command:
```
0:011> !dumpccw 08060000
Managed object: 02e6cf88
Outer IUnknown: 00000000
Ref count: 0
Flags:
RefCounted Handle: 00D714F8 (WEAK)
COM interface pointers:
IP MT Type
08060010 080315b0 Server.Contract.IEventTesting
```
Notice here that there is only one interface implemented by the managed object and the CCW is no longer in use by the native code (Ref count equals 0). Below is an example of a CCW representing a Windows Forms ActiveX control which is still alive and implements more interfaces:
```
0:014> !dumpccw 0a23fde0
Managed object: 04ee6984
Outer IUnknown: 00000000
Ref count: 7
Flags:
RefCounted Handle: 04C716D8 (STRONG)
COM interface pointers:
IP MT Type
0A23FDF8 09fbbb04 Interop+Ole32+IOleControl
0A23FDC8 09fbbc4c Interop+Ole32+IOleObject
0A23FDCC 09fbbd34 Interop+Ole32+IOleInPlaceObject
0A23FDD0 09fbbde4 Interop+Ole32+IOleInPlaceActiveObject
0A23FDA8 09fbbfa0 Interop+Ole32+IViewObject2
0A23FDB0 09fbc09c Interop+Ole32+IPersistStreamInit
0A23FD4C 09f6485c BullsEyeControlLib.IBullsEye
```
If you would like to dump information about all objects associated with SyncBlocks, you may use the following WinDbg script:
```
.foreach /pS 7 /ps 7 (addr { !syncblk -all }) { !do addr }
```
And to extract only the RCW or CCW addresses, we could use the **!grep** command from the [awesome Andrew Richard's PDE extension](https://onedrive.live.com/?authkey=%21AJeSzeiu8SQ7T4w&id=DAE128BD454CF957%217152&cid=DAE128BD454CF957):
```
0:014> .load PDE.dll
0:014> !grep RCW: .foreach /pS 7 /ps 7 (addr { !syncblk -all }) { !do addr }
RCW: 08086d30
0:014> !grep CCW: .foreach /pS 7 /ps 7 (addr { !syncblk -all }) { !do addr }
CCW: 08060000
```
To keep COM objects alive in the managed memory, .NET Runtime creates handles for them. Those are either strong or ref-counted handles and we may list them with the **!gchandles** command, for example:
```
0:011> !gchandles -type refcounted
Handle Type Object Size Data Type
00D714F8 RefCounted 02e6cf88 12 0 EventTesting
Statistics:
MT Count TotalSize Class Name
08031668 1 12 EventTesting
Total 1 objects
0:014> !gchandles -type strong
Handle Type Object Size Data Type
04C711B4 Strong 030deb48 12 System.__ComObject
...
Statistics:
MT Count TotalSize Class Name
04ebbf00 1 12 System.__ComObject
...
Total 19 objects
```
Of course, in those lists we will find the objects we already saw in the **!syncblk** output, so it's just another way to find them. It may be useful when tracking, for example, GC leaks.
Finally, to find who is keeping our managed object alive, we could use the **!gcroot** command. And it's quite easy to find the GC roots for a particular type with the following script:
```
.foreach (addr { !DumpHeap -short -type System.__ComObject }) { !gcroot addr }
```
Links
-----
- ["Essential COM"](https://archive.org/details/essentialcom00boxd) by Don Box
- ["Inside OLE"](https://github.com/kraigb/InsideOLE) by Kraig Brockschmidt (Kraig published the whole book with source code on GitHub!)
- ["Inside COM+ Base Services"](https://thrysoee.dk/InsideCOM+/) by Guy Eddon and Henry Eddon
- ["COM and .NET interoperability"](https://link.springer.com/book/10.1007/978-1-4302-0824-2) and [source code](https://github.com/Apress/com-.net-interoperability) by Andrew Troelsen
- [".NET and COM: The Complete Interoperability Guide"](https://books.google.pl/books/about/NET_and_COM.html?id=x2OIPSyFLBcC) by Adam Nathan
- [COM+ revisited](https://lowleveldesign.wordpress.com/2022/01/17/com-revisited/) by me :)
- [Calling Local Windows RPC Servers from .NET](https://googleprojectzero.blogspot.com/2019/12/calling-local-windows-rpc-servers-from.html) by James Forshaw
{% endraw %}
================================================
FILE: guides/configuring-linux-for-effective-troubleshooting.md
================================================
---
layout: page
title: Configuring Linux for effective troubleshooting
date: 2025-12-26 08:00:00 +0200
---
**Table of contents:**
- [Configuring debug symbols](#configuring-debug-symbols)
Configuring debug symbols
-------------------------
These days many debugging tools can fetch debug symbols from debuginfod servers. The [official project page](https://sourceware.org/elfutils/Debuginfod.html) lists the URLs you should use for each supported distribution. For example, in my Arch Linux, the `DEBUGINFOD_URLS` environment variable is set to `https://debuginfod.archlinux.org` by the `/etc/profile.d/debuginfod.sh` script (a part of the libelf package).
If you want this variable to be preserved when running commands with sudo, you can add a rule such as the following to a file in `/etc/sudoers.d/` (e.g., `/etc/sudoers.d/debuginfod`):
```
Defaults env_keep += "DEBUGINFOD_URLS"
```
================================================
FILE: guides/configuring-windows-for-effective-troubleshooting.md
================================================
---
layout: page
title: Configuring Windows for effective troubleshooting
date: 2023-10-11 08:00:00 +0200
---
**Table of contents:**
- [Configuring debug symbols](#configuring-debug-symbols)
- [Replacing Task Manager with System Informer](#replacing-task-manager-with-system-informer)
- [Installing and configuring Sysinternals Suite](#installing-and-configuring-sysinternals-suite)
- [Configuring post-mortem debugging](#configuring-post-mortem-debugging)
## Configuring debug symbols
Staring at raw hex numbers is not very helpful for troubleshooting. Therefore, it's essential to take the time to properly configure debug symbols on our system. One effective method is to set the **\_NT\_SYMBOL\_PATH** environment variable. Most troubleshooting tools read its value and utilize the specified symbol stores. I usually configure it to point only to the official Microsoft symbol server, resulting in the following value for the \_NT\_SYMBOL\_PATH variable on my system: `SRV*C:\symbols\dbg*https://msdl.microsoft.com/download/symbols`. Here, `C:\symbols` serves as a cache folder for storing downloaded symbols. I also use `C:\symbols\dbg` if I need to index PDB files for my applications. For further information about the \_NT\_SYMBOL\_PATH variable, refer to [the official documentation](https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/symbol-path).
The symbol path variable is one essential component required for successful symbol resolution. Another critical aspect is the version of **dbghelp.dll** that can work with symbol servers. Unfortunately, the version preinstalled with Windows lacks this feature. To overcome this issue, you can install the **Debugging Tools for Windows** from the [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/). Make sure to install both the x86 and x64 versions to enable debugging of both 32- and 64-bit applications. Once installed, certain tools (e.g., Symbol Informer) will automatically select the appropriate dbghelp.dll version, while others will require some configuration, as we'll explore in later sections.
## Replacing Task Manager with System Informer
My long time favorite tool to observe system and processes running on it, is [System Informer](https://www.systeminformer.com/), formerly known as Process Hacker. It has so many great features that deserves a guide on its own. The process tree, which shows the process creation and termination events, is much more readable than the flat process list in Task Manager or Resource Monitor. Moreover, System Informer lets you manage services and drivers, and view live network connections. Therefore, I highly recommend to open the Options dialog and replace Task Manager with it. System Informer does not have an option to set the dbghelp.dll path in its settings, but it will detect it if you have Debugging Tools for Windows installed. So please install them to have Windows stacks correctly resolved.
If you have reasons not to use System Informer, you can try [Process Explorer](https://learn.microsoft.com/en-us/sysinternals/downloads/process-explorer). It does not have as many functionalities as System Informer, but it is still a powerful system monitor.
## Installing and configuring Sysinternals Suite
[Sysinternals tools](https://learn.microsoft.com/en-us/sysinternals/) help me diagnose and fix various issues on Windows systems. Most often I use [Process Monitor](https://learn.microsoft.com/en-us/sysinternals/downloads/procmon) to capture and analyze system events, and sometimes that's the only tool I need to solve the problem! Other Sysinternals tools that I frequently use are [DebugView](https://learn.microsoft.com/en-us/sysinternals/downloads/debugview), [ProcDump](https://learn.microsoft.com/en-us/sysinternals/downloads/procdump), and [LiveKd](https://learn.microsoft.com/en-us/sysinternals/downloads/livekd). You can get the entire suite or individual tools from the [SysInternals website](https://learn.microsoft.com/en-us/sysinternals/downloads/) or from [live.sysinternals.com](https://live.sysinternals.com). However, these methods require manual updates when new versions are available. A more convenient way to keep the tools up to date is to install them from [Microsoft Store](https://www.microsoft.com/store/apps/9p7knl5rwt25).
To get the most out of Process Monitor and Process Explorer, you need to set up symbol resolution correctly. The default settings do not use the Microsoft symbol store, so you need to adjust them in the options or import the registry keys shown below (after installing Debugging Tools for Windows):
```
[HKEY_CURRENT_USER\Software\Sysinternals\Process Explorer]
"DbgHelpPath"="C:\\Program Files (x86)\\Windows Kits\\10\\Debuggers\\x64\\dbghelp.dll"
"SymbolPath"="SRV*C:\\symbols\\dbg*http://msdl.microsoft.com/download/symbols"
[HKEY_CURRENT_USER\Software\Sysinternals\Process Monitor]
"DbgHelpPath"="C:\\Program Files (x86)\\Windows Kits\\10\\Debuggers\\x64\\dbghelp.dll"
"SymbolPath"="SRV*C:\\symbols\\dbg*http://msdl.microsoft.com/download/symbols"
```
## Configuring post-mortem debugging
We all experience application failures from time to time. When it happens, Windows collectes some data about a crash and saves it to the event log. It usually lacks details required to fully understand the root cause of an issue. Fortunately, we have options to replace this scarse report with, for example, a memory dump. One way to accomplish that is by configuring **Windows Error Reporting** . The commands below will enable minidump collection to a C:\Dumps folder on a process failure:
```shell
reg.exe add "HKLM\Software\Microsoft\Windows\Windows Error Reporting\LocalDumps" /v DumpType /t REG_DWORD /d 1 /f
reg.exe add "HKLM\Software\Microsoft\Windows\Windows Error Reporting\LocalDumps" /v DumpFolder /t REG_EXPAND_SZ /d C:\dumps /f
```
The available settings are listed and explained in the [WER documentation](https://learn.microsoft.com/en-us/windows/win32/wer/collecting-user-mode-dumps). Note, that by creating a subkey with an application name (for example, `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps\test.exe`), you may customize WER settings per individual applications.
[ProcDump](https://learn.microsoft.com/en-us/sysinternals/downloads/procdump) is an alternative to WER. You could install it as an [automatic debugger](https://learn.microsoft.com/en-us/windows/win32/debug/configuring-automatic-debugging), which Windows will run whenever a critical error occurs in an application. Example install command (-u to uninstall):
```shell
procdump -i C:\Dumps
```
These dumps can take up a lot of disk space over time, so you should either delete the old files periodically, or set up a task scheduler job that does it for you.
================================================
FILE: guides/diagnosing-dotnet-apps.md
================================================
---
layout: page
title: Diagnosing .NET applications
date: 2024-01-01 08:00:00 +0200
---
{% raw %}
:point_right: I also authored the **[.NET Diagnostics Expert](https://diagnosticsexpert.com/?utm_source=debugrecipes&utm_medium=banner&utm_campaign=general) course**, available at Dotnetos :hot_pepper: Academy. Apart from the theory, it contains lots of demos and troubleshooting guidelines. Check it out if you're interested in learning .NET troubleshooting. :point_left:
**Table of contents:**
- [General .NET debugging tips](#general-net-debugging-tips)
- [Loading the SOS extension into WinDbg](#loading-the-sos-extension-into-windbg)
- [Manually loading symbol files for .NET Core](#manually-loading-symbol-files-for-net-core)
- [Disabling JIT optimization](#disabling-jit-optimization)
- [Decoding managed stacks in Sysinternals](#decoding-managed-stacks-in-sysinternals)
- [Check runtime version](#check-runtime-version)
- [Debugging/tracing a containerized .NET application \(Docker\)](#debuggingtracing-a-containerized-net-application-docker)
- [Diagnosing exceptions or erroneous behavior](#diagnosing-exceptions-or-erroneous-behavior)
- [Using Time Travel Debugging \(TTD\)](#using-time-travel-debugging-ttd)
- [Collecting a memory dump](#collecting-a-memory-dump)
- [Analysing exception information](#analysing-exception-information)
- [Diagnosing hangs](#diagnosing-hangs)
- [Listing threads call stacks](#listing-threads-call-stacks)
- [Finding locks in managed code](#finding-locks-in-managed-code)
- [Diagnosing waits or high CPU usage](#diagnosing-waits-or-high-cpu-usage)
- [Diagnosing managed memory leaks](#diagnosing-managed-memory-leaks)
- [Collecting memory snapshots](#collecting-memory-snapshots)
- [Analyzing collected snapshots](#analyzing-collected-snapshots)
- [Diagnosing issues with assembly loading](#diagnosing-issues-with-assembly-loading)
- [Troubleshooting loading with EventPipes/ETW \(.NET\)](#troubleshooting-loading-with-eventpipesetw-net)
- [Troubleshooting loading using ETW \(.NET Framework\)](#troubleshooting-loading-using-etw-net-framework)
- [Troubleshooting loading using Fusion log \(.NET Framework\)](#troubleshooting-loading-using-fusion-log-net-framework)
- [GAC \(.NET Framework\)](#gac-net-framework)
- [Find assembly in cache](#find-assembly-in-cache)
- [Uninstall assembly from cache](#uninstall-assembly-from-cache)
- [Diagnosing network connectivity issues](#diagnosing-network-connectivity-issues)
- [.NET Core](#net-core)
- [.NET Framework](#net-framework)
- [ASP.NET Core](#aspnet-core)
- [Collecting ASP.NET Core logs](#collecting-aspnet-core-logs)
- [ILogger logs](#ilogger-logs)
- [DiagnosticSource logs](#diagnosticsource-logs)
- [Collecting ASP.NET Core performance counters](#collecting-aspnet-core-performance-counters)
- [ASP.NET \(.NET Framework\)](#aspnet-net-framework)
- [Examining ASP.NET process memory \(and dumps\)](#examining-aspnet-process-memory-and-dumps)
- [Profiling ASP.NET](#profiling-aspnet)
- [Application instrumentation](#application-instrumentation)
- [ASP.NET ETW providers](#aspnet-etw-providers)
- [Collect events using the Perfecto tool](#collect-events-using-the-perfecto-tool)
- [Collect events using FREB](#collect-events-using-freb)
## General .NET debugging tips
### Loading the SOS extension into WinDbg
When debugging a **.NET Framework application**, WinDbgX should automatically find a correct version of the SOS.dll. If it fails to do so and your .NET Framework version matches the one of the target app, use the following command:
```
.loadby sos mscorwks (.NET 2.0/3.5)
.loadby sos clr (.NET 4.0+)
```
For **.NET Core**, you need to download and install the **dotnet-sos** tool. The install command informs how to load SOS into WinDbg, for example:
```
> dotnet tool install -g dotnet-sos
...
> dotnet sos install
...
Execute '.load C:\Users\me\.dotnet\sos\sos.dll' to load SOS in your Windows debugger.
Cleaning up...
SOS install succeeded
```
SOS commands sometimes get overriden by other extensions help files. In such case, use **!sos.help \[cmd\]** command, for example, `!sos.help !savemodule`.
### Manually loading symbol files for .NET Core
I noticed that sometimes Microsoft public symbol servers do not have .NET Core dlls symbols. That does not allow WinDbg to decode native .NET stacks. Fortunately, we may solve this problem by precaching symbol files using the [dotnet-symbol](https://github.com/dotnet/symstore/tree/master/src/dotnet-symbol) tool. Assuming we set our `_NT_SYMBOL_PATH` to `SRV*C:\symbols\dbg*https://msdl.microsoft.com/download/symbols`, we need to run dotnet-symbol with the **--cache-directory** parameter pointing to our symbol cache folder (for example, `C:\symbols\dbg`):
```
dotnet-symbol --recurse-subdirectories --cache-directory c:\symbols\dbg -o C:\temp\toremove "C:\Program Files\dotnet\shared\Microsoft.NETCore.App\3.0.0\*"
```
We may later remove the `C:\temp\toremove` folder as all PDB files are indexed in the cache directory. The output folder contains both DLL and PDB files, takes lots of space, and is often not required.
### Disabling JIT optimization
For **.NET Core**, set the **COMPlus_JITMinOptsx** environment variable:
```
export COMPlus_JITMinOpts=1
```
For **.NET Framework**, you need to create an ini file. The ini file must have the same name as the executable with only extension changed to ini, eg. my.ini file will work with my.exe application.
```
[.NET Framework Debugging Control]
GenerateTrackingInfo=1
AllowOptimize=0
```
### Decoding managed stacks in Sysinternals
As of version 16.22 version, **Process Explorer** understands managed stacks and should display them correctly when you double click on a thread in a process.
**Process Monitor**, unfortunately, lacks this feature. Pure managed modules will appear as `` in the call stack view. However, we may fix the problem for the ngened assemblies. First, you need to generate a .pdb file for the ngened assembly, for example, `ngen createPDB c:\Windows\assembly\NativeImages_v4.0.30319_64\mscorlib\e2c5db271896923f5450a77229fb2077\mscorlib.ni.dll c:\symbols\private`. Then make sure you have this path in your `_NT_SYMBOL_PATH` variable, for example, `C:\symbols\private;SRV*C:\symbols\dbg*http://msdl.microsoft.com/download/symbols`. If procmon still does not resolve the symbols, go to Options - Configure Symbols and reload the dbghelp.dll. I observe this issue in version 3.50.
### Check runtime version
For .NET Framework 2.0, you could check the version of mscorwks in the file properties or, if in debugger, using lmmv. For .NET Framework 4.x, you need to check clr.dll (or the Release value under the `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full` key) and find it in the [Microsoft Docs](https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/versions-and-dependencies).
In .NET Core, we could run **dotnet --list-runtimes** command to list the available runtimes.
### Debugging/tracing a containerized .NET application (Docker)
With the introduction of EventPipes in .NET Core 2.1, the easiest approach is to create a shared `/tmp` volume and use a sidecar diagnostics container. A sample Dockerfile.netdiag may look as follows:
```
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS base
RUN apt-get update && apt-get install -y lldb; \
dotnet tool install -g dotnet-symbol; \
dotnet tool install -g dotnet-sos; \
/root/.dotnet/tools/dotnet-sos install
RUN dotnet tool install -g dotnet-counters; \
dotnet tool install -g dotnet-trace; \
dotnet tool install -g dotnet-dump; \
dotnet tool install -g dotnet-gcdump; \
echo 'export PATH="$PATH:/root/.dotnet/tools"' >> /root/.bashrc
ENTRYPOINT ["/bin/bash"]
```
You may use it to create a .NET diagnostics Docker image, for example:
```
$ docker build -t netdiag -f .\Dockerfile.netdiag .
```
Then, create a `/tmp` volume and mount it into your .NET application container, for example:
```
$ docker volume create dotnet-tmp
$ docker run --rm --name helloserver --mount "source=dotnet-tmp,target=/tmp" -p 13000:13000 helloserver 13000
```
And you are ready to run the diagnostics container and diagnose the remote application:
```
$ docker run --rm -it --mount "source=dotnet-tmp,target=/tmp" --pid=container:helloserver netdiag
root@d4bfaa3a9322:/# dotnet-trace ps
1 dotnet /usr/share/dotnet/dotnet
```
If you only want to trace the application with **dotnet-trace**, consider using a shorter Dockerfile.nettrace file:
```
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS base
RUN dotnet tool install -g dotnet-trace
ENTRYPOINT ["/root/.dotnet/tools/dotnet-trace", "collect", "-n", "dotnet", "-o", "/work/trace.nettrace", "@/work/input.rsp"]
```
where input.rsp:
```
--providers Microsoft-Windows-DotNETRuntime:0x14C14FCCBD:4,Microsoft-DotNETCore-SampleProfiler:0xF00000000000:4
```
The nettrace container will automatically start the tracing session enabling the providers from the input.rsp file. It also assumes the destination process name is dotnet:
```
$ docker build -t nettrace -f .\Dockerfile.nettrace .
$ docker run --rm --pid=container:helloserver --mount "source=dotnet-tmp,target=/tmp" -v "$pwd/:/work" -it nettrace
Provider Name Keywords Level Enabled By
Microsoft-Windows-DotNETRuntime 0x00000014C14FCCBD Informational(4) --providers
Microsoft-DotNETCore-SampleProfiler 0x0000F00000000000 Informational(4) --providers
Process : /usr/share/dotnet/dotnet
Output File : /work/trace.nettrace
[00:00:00:02] Recording trace 261.502 (KB)
Press or to exit...11 (KB)
Stopping the trace. This may take up to minutes depending on the application being traced.
```
## Diagnosing exceptions or erroneous behavior
### Using Time Travel Debugging (TTD)
Time Travel Debugging is an excellent way of troubleshooting errors and exceptions. We can step through the code causing the problems at our own pace. I describe TTD in [a WinDbg guide](/guides/windbg). It is my preferred way of debugging issues in applications and I highly recommend giving it a try.
### Collecting a memory dump
**[dotnet-dump](https://docs.microsoft.com/en-us/dotnet/core/diagnostics/dotnet-dump)** is one of the .NET diagnostics CLI tools. You may download it using curl or wget, for example: `curl -JLO https://aka.ms/dotnet-dump/win-x64`.
To create a full memory dump, run one of the commands:
```
dotnet-dump collect -p
dotnet-dump collect -n
```
You may create a heap-only memory dump by adding the **--type=Heap** option.
Createdump shares the location with the coreclr library, for example, for .NET 5: `/usr/share/dotnet/shared/Microsoft.NETCore.App/5.0.3/createdump` or `c:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.3\createdump.exe`.
To create a full memory dump, run **createdump --full {process-id}**. With no options provided, it creates a memory dump with heap memory, which equals to **createdump --withheap {pid}**.
The .NET application may run **createdump** automatically on crash. We configure this feature through [environment variables](https://learn.microsoft.com/en-us/dotnet/core/diagnostics/collect-dumps-crash), for example:
```shell
# enable a memory dump creation on crash
set DOTNET_DbgEnableMiniDump=1
# when crashing, create a heap (2) memory dump, (4) for full memory dump
set DOTNET_DbgMiniDumpType=2
```
Apart from the .NET tools described above, you may create memory dumps with tools described in [the guide dedicated to diagnosing native Windows applications](diagnosing-native-windows-apps). As those tools usually do not understand .NET memory layout, I recommend creating full memory dumps to have all the necessary metadata for later analysis.
### Analysing exception information
First make sure with the **!Threads** command (SOS) that your current thread is the one with the exception context:
```
0:000> !Threads
ThreadCount: 2
UnstartedThread: 0
BackgroundThread: 1
PendingThread: 0
DeadThread: 0
Hosted Runtime: no
ID OSID ThreadOBJ State GC Mode GC Alloc Context Domain Count Apt Exception
0 1 1ec8 000000000055adf0 2a020 Preemptive 0000000002253560:0000000002253FD0 00000000004fb970 0 Ukn System.ArgumentException 0000000002253438
5 2 1c74 00000000005851a0 2b220 Preemptive 0000000000000000:0000000000000000 00000000004fb970 0 Ukn (Finalizer)
```
In the snippet above we can see that the exception was thrown on the thread no. 0 and this is our currently selected thread (in case it's not, we would use **\~0s** command) so we may use the **!PrintException** command from SOS (alias **!pe**), for example:
```
0:000> !pe
Exception object: 0000000002253438
Exception type: System.ArgumentException
Message: v should not be null
InnerException:
StackTrace (generated):
StackTraceString:
HResult: 80070057
```
To see the full managed call stack, use the **!CLRStack** command. By default, the debugger will stop on an unhandled exception. If you want to stop at the moment when an exception is thrown (first-chance exception), run the **sxe clr** command at the beginning of the debugging session.
## Diagnosing hangs
We usually start the analysis by looking at the threads running in a process. The call stacks help us identify blocked threads. We can use TTD, thread-time trace, or memory dumps to learn about what threads are doing. In the follow-up sections, I will describe how to find lock objects and relations between threads in memory dumps.
### Listing threads call stacks
To list native stacks for all the threads in **WinDbg**, run: **~\*k** or **~\*e!dumpstack**. If you are interested only in managed stacks, you may use the **~\*e!clrstack** SOS command. The **dotnet-dump**'s **analyze** command provides a super useful parallel stacks command:
```
> dotnet dump analyze test.dmp
> pstacks
________________________________________________
~~~~ 5cd8
1 System.Threading.Monitor.Enter(Object, Boolean ByRef)
1 deadlock.Program.Lock2()
~~~~ 3e58
1 System.Threading.Monitor.Enter(Object, Boolean ByRef)
1 deadlock.Program.Lock1()
2 System.Threading.Tasks.Task.InnerInvoke()
...
2 System.Threading.ThreadPoolWorkQueue.Dispatch()
2 System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
```
In **LLDB**, we may show native call stacks for all the threads with the **bt all** command. Unfortunately, if we want to use !dumpstack or !clrstack commands, we need to manually switch between threads with the thread select command.
### Finding locks in managed code
You may examine thin locks using **!DumpHeap -thinlocks**. To find all sync blocks, use the **!SyncBlk -all** command.
On .NET Framework, you may also use the **!dlk** command from the SOSEX extension. It is pretty good in detecting deadlocks, for example:
```
0:007> .load sosex
0:007> !dlk
Examining SyncBlocks...
Scanning for ReaderWriterLock(Slim) instances...
Scanning for holders of ReaderWriterLock locks...
Scanning for holders of ReaderWriterLockSlim locks...
Examining CriticalSections...
Scanning for threads waiting on SyncBlocks...
Scanning for threads waiting on ReaderWriterLock locks...
Scanning for threads waiting on ReaderWriterLocksSlim locks...
*** WARNING: Unable to verify checksum for C:\WINDOWS\assembly\NativeImages_v4.0.30319_32\System\3a4f0a84904c4b568b6621b30306261c\System.ni.dll
*** WARNING: Unable to verify checksum for C:\WINDOWS\assembly\NativeImages_v4.0.30319_32\System.Transactions\ebef418f08844f99287024d1790a62a4\System.Transactions.ni.dll
Scanning for threads waiting on CriticalSections...
*DEADLOCK DETECTED*
CLR thread 0x1 holds the lock on SyncBlock 011e59b0 OBJ:02e93410[System.Object]
...and is waiting on CriticalSection 01216a58
CLR thread 0x3 holds CriticalSection 01216a58
...and is waiting for the lock on SyncBlock 011e59b0 OBJ:02e93410[System.Object]
CLR Thread 0x1 is waiting at clr!CrstBase::SpinEnter+0x92
CLR Thread 0x3 is waiting at System.Threading.Monitor.Enter(System.Object, Boolean ByRef)(+0x17 Native)
```
When debugging locks in code that is using tasks it is often necessary to examine execution contexts assigned to the running threads. I prepared a simple script which lists threads with their execution contexts. You only need (as in previous script) to find the MT of the Thread class in your appdomain, e.g.
```
0:036> !Name2EE mscorlib.dll System.Threading.Thread
Module: 72551000
Assembly: mscorlib.dll
Token: 020001d1
MethodTable: 72954960
EEClass: 725bc0c4
Name: System.Threading.Thread
```
And then paste it in the scripts below:
x86 version:
```
.foreach ($addr {!DumpHeap -short -mt }) { .printf /D "Thread: %i; Execution context: %p\n", poi(${$addr}+28), poi(${$addr}+8), poi(${$addr}+8) }
```
x64 version:
```
.foreach ($addr {!DumpHeap -short -mt }) { .printf /D "Thread: %i; Execution context: %p\n", poi(${$addr}+4c), poi(${$addr}+10), poi(${$addr}+10) }
```
Notice that the thread number from the output is a managed thread id and to map it to the windbg thread number you need to use the !Threads command.
## Diagnosing waits or high CPU usage
Dotnet-trace allows us to enable the runtime CPU sampling provider (**Microsoft-DotNETCore-SampleProfiler**). However, using it might impact application performance as it internally calls **ThreadSuspend::SuspendEE** to suspend managed code execution while collecting the samples. Although it is a sampling profiler, it is a bit special. It runs on a separate thread and collects stacks of all the managed threads, even the waiting ones. This behavior resembles the thread time profiler. Probably that's the reason why PerfView shows us the **Thread Time** view when opening the .nettrace file.
Sample collect examples:
```bash
dotnet-trace collect --profile cpu-sampling -p 12345
dotnet-trace collect --profile cpu-sampling -- myapp.exe
```
Dotnet-trace does not automatically enable DiagnosticSource or TPL providers. Therefore, if we want to see activities in PerfView, we need to turn them on manually, for example:
```bash
dotnet-trace collect --profile cpu-sampling --providers "Microsoft-Diagnostics-DiagnosticSource:0xFFFFFFFFFFFFF7FF:4:FilterAndPayloadSpecs=HttpHandlerDiagnosticListener/System.Net.Http.Request@Activity2Start:Request.RequestUri\nHttpHandlerDiagnosticListener/System.Net.Http.Response@Activity2Stop:Response.StatusCode,System.Threading.Tasks.TplEventSource:1FF:5" -n testapp
```
For diagnosing CPU problems in .NET applications running on Windows, we may also rely on ETW (Event Tracing for Windows). In [a guide dedicated to diagnosing native applications](diagnosing-native-windows-apps), I describe how to collect and analyze ETW traces.
On Linux, we additionally have the [perfcollect](https://docs.microsoft.com/en-us/dotnet/core/diagnostics/trace-perfcollect-lttng) script. It is the easiest way to use Linux Kernel perf_events for diagnosing .NET apps. In my tests, however, I found that quite often, it did not correctly resolve .NET stacks.
To collect CPU samples with perfcollect, use the **perfcollect collect** command. To also enable the Thread Time events, add the **-threadtime** option. If only possible, I would recommend opening the traces (even the ones from Linux) in PerfView. But if it's impossible, try the **view** command of the perfcollect script, for example:
```bash
perfcollect view sqrt.trace.zip -graphtype caller
```
Using the **-graphtype** option, we may switch from the top-down view (`caller`) to the bottom-up view (`callee`).
## Diagnosing managed memory leaks
### Collecting memory snapshots
If we are interested only in GC Heaps, we may create the GC Heap snapshot using **PerfView**:
perfview heapsnapshot
In GUI, we may use the menu option: **Memory -> Take Heap Snapshot**.
For .NET Core applications, we have a CLI tool: **dotnet-gcdump**, which you may get from the https://aka.ms/dotnet-gcdump/runtime-id URL, for example, https://aka.ms/dotnet-gcdump/linux-x64. And to collect the GC dump we need to run one of the commands:
```
dotnet-gcdump -p
dotnet-gcdump -n
```
Sometimes managed heap is not enough to diagnose the memory leak. In such situations, we need to create a memory dump, as described in [a guide dedicated to diagnosing native applications](diagnosing-native-windows-apps).
### Analyzing collected snapshots
**PerfView** can open GC Heap snapshots and dumps. If you only have a memory dump, you may convert a memory dump file to a PerfView snapshot using **PerfView HeapSnapshotFromProcessDump ProcessDumpFile {DataFile}** or using the GUI options **Memory -> Take Heap Snapshot from Dump**.
I would like to bring your attention to an excellent diffing option available for heap snapshots. Imagine you made two heap snapshots of the leaking process:
- first named LeakingProcess.gcdump
- second (taken a minute later) named LeakingProcess.1.gcdump
You may now run PerfView, open two collected snapshots, switch to the LeakingProcess.1.gcdump and under the Diff menu you should see an option to diff this snapshot with the baseline:

After you choose it, a new window will pop up with a tree of objects which have changed between the snapshots. Of course, if you have more snapshots you can generate diffs between them all. A really powerful feature!
**WinDbg** allows you to analyze the full memory dumps. **Make sure that bitness of the dump matches bitness of the debugger.** Then load the SOS extension and identify objects which use most of the memory using **!DumpHeap -stat**. Later, analyze the references using the **!GCRoot** command.
Other SOS commands for analyzing the managed heap include:
```
!EEHeap [-gc] [-loader]
!HeapStat [-inclUnrooted | -iu]
!DumpHeap [-stat]
[-strings]
[-short]
[-min ]
[-max ]
[-live]
[-dead]
[-thinlock]
[-startAtLowerBound]
[-mt ]
[-type ]
[start [end]]
!ObjSize [