[
  {
    "path": ".gitignore",
    "content": "_site\n.sass-cache\n.jekyll-cache\n.jekyll-metadata\nvendor\ndraft_*\n"
  },
  {
    "path": "404.html",
    "content": "---\npermalink: /404.html\nlayout: default\n---\n\n<style type=\"text/css\" media=\"screen\">\n  .container {\n    margin: 10px auto;\n    max-width: 600px;\n    text-align: center;\n  }\n  h1 {\n    margin: 30px 0;\n    font-size: 4em;\n    line-height: 1;\n    letter-spacing: -1px;\n  }\n</style>\n\n<div class=\"container\">\n  <h1>404</h1>\n\n  <p><strong>Page not found :(</strong></p>\n  <p>The requested page could not be found.</p>\n</div>\n"
  },
  {
    "path": "CNAME",
    "content": "wtrace.net"
  },
  {
    "path": "Gemfile",
    "content": "source \"https://rubygems.org\"\n# Hello! This is where you manage which Jekyll version is used to run.\n# When you want to use a different version, change it below, save the\n# file and run `bundle install`. Run Jekyll with `bundle exec`, like so:\n#\n#     bundle exec jekyll serve\n#\n# This will help ensure the proper Jekyll version is running.\n# Happy Jekylling!\n# gem \"jekyll\", \"~> 4.2.0\"\n# This is the default theme for new Jekyll sites. You may change this to anything you like.\ngem \"minima\", \"~> 2.5\"\n# gem \"jekyll-theme-cayman\", \"~> 0.2.0\"\n# If you want to use GitHub Pages, remove the \"gem \"jekyll\"\" above and\n# uncomment the line below. To upgrade, run `bundle update github-pages`.\ngem \"github-pages\", group: :jekyll_plugins\n# If you have any plugins, put them here!\ngroup :jekyll_plugins do\n  gem \"jekyll-feed\", \"~> 0.12\"\nend\n\n# Windows and JRuby does not include zoneinfo files, so bundle the tzinfo-data gem\n# and associated library.\nplatforms :mingw, :x64_mingw, :mswin, :jruby do\n  gem \"tzinfo\", \"~> 1.2\"\n  gem \"tzinfo-data\"\nend\n\n# Performance-booster for watching directories on Windows\ngem \"wdm\", \"~> 0.1.1\", :platforms => [:mingw, :x64_mingw, :mswin]\n\ngem \"webrick\", \"~> 1.7\"\n\ngem \"json\", \"~> 2.7\"\n"
  },
  {
    "path": "LICENSE",
    "content": "Attribution 4.0 International\n\n=======================================================================\n\nCreative Commons Corporation (\"Creative Commons\") is not a law firm and\ndoes not provide legal services or legal advice. Distribution of\nCreative Commons public licenses does not create a lawyer-client or\nother relationship. Creative Commons makes its licenses and related\ninformation available on an \"as-is\" basis. Creative Commons gives no\nwarranties regarding its licenses, any material licensed under their\nterms and conditions, or any related information. Creative Commons\ndisclaims all liability for damages resulting from their use to the\nfullest extent possible.\n\nUsing Creative Commons Public Licenses\n\nCreative Commons public licenses provide a standard set of terms and\nconditions that creators and other rights holders may use to share\noriginal works of authorship and other material subject to copyright\nand certain other rights specified in the public license below. The\nfollowing considerations are for informational purposes only, are not\nexhaustive, and do not form part of our licenses.\n\n     Considerations for licensors: Our public licenses are\n     intended for use by those authorized to give the public\n     permission to use material in ways otherwise restricted by\n     copyright and certain other rights. Our licenses are\n     irrevocable. Licensors should read and understand the terms\n     and conditions of the license they choose before applying it.\n     Licensors should also secure all rights necessary before\n     applying our licenses so that the public can reuse the\n     material as expected. Licensors should clearly mark any\n     material not subject to the license. This includes other CC-\n     licensed material, or material used under an exception or\n     limitation to copyright. More considerations for licensors:\n    wiki.creativecommons.org/Considerations_for_licensors\n\n     Considerations for the public: By using one of our public\n     licenses, a licensor grants the public permission to use the\n     licensed material under specified terms and conditions. If\n     the licensor's permission is not necessary for any reason--for\n     example, because of any applicable exception or limitation to\n     copyright--then that use is not regulated by the license. Our\n     licenses grant only permissions under copyright and certain\n     other rights that a licensor has authority to grant. Use of\n     the licensed material may still be restricted for other\n     reasons, including because others have copyright or other\n     rights in the material. A licensor may make special requests,\n     such as asking that all changes be marked or described.\n     Although not required by our licenses, you are encouraged to\n     respect those requests where reasonable. More considerations\n     for the public:\n    wiki.creativecommons.org/Considerations_for_licensees\n\n=======================================================================\n\nCreative Commons Attribution 4.0 International Public License\n\nBy exercising the Licensed Rights (defined below), You accept and agree\nto be bound by the terms and conditions of this Creative Commons\nAttribution 4.0 International Public License (\"Public License\"). To the\nextent this Public License may be interpreted as a contract, You are\ngranted the Licensed Rights in consideration of Your acceptance of\nthese terms and conditions, and the Licensor grants You such rights in\nconsideration of benefits the Licensor receives from making the\nLicensed Material available under these terms and conditions.\n\n\nSection 1 -- Definitions.\n\n  a. Adapted Material means material subject to Copyright and Similar\n     Rights that is derived from or based upon the Licensed Material\n     and in which the Licensed Material is translated, altered,\n     arranged, transformed, or otherwise modified in a manner requiring\n     permission under the Copyright and Similar Rights held by the\n     Licensor. For purposes of this Public License, where the Licensed\n     Material is a musical work, performance, or sound recording,\n     Adapted Material is always produced where the Licensed Material is\n     synched in timed relation with a moving image.\n\n  b. Adapter's License means the license You apply to Your Copyright\n     and Similar Rights in Your contributions to Adapted Material in\n     accordance with the terms and conditions of this Public License.\n\n  c. Copyright and Similar Rights means copyright and/or similar rights\n     closely related to copyright including, without limitation,\n     performance, broadcast, sound recording, and Sui Generis Database\n     Rights, without regard to how the rights are labeled or\n     categorized. For purposes of this Public License, the rights\n     specified in Section 2(b)(1)-(2) are not Copyright and Similar\n     Rights.\n\n  d. Effective Technological Measures means those measures that, in the\n     absence of proper authority, may not be circumvented under laws\n     fulfilling obligations under Article 11 of the WIPO Copyright\n     Treaty adopted on December 20, 1996, and/or similar international\n     agreements.\n\n  e. Exceptions and Limitations means fair use, fair dealing, and/or\n     any other exception or limitation to Copyright and Similar Rights\n     that applies to Your use of the Licensed Material.\n\n  f. Licensed Material means the artistic or literary work, database,\n     or other material to which the Licensor applied this Public\n     License.\n\n  g. Licensed Rights means the rights granted to You subject to the\n     terms and conditions of this Public License, which are limited to\n     all Copyright and Similar Rights that apply to Your use of the\n     Licensed Material and that the Licensor has authority to license.\n\n  h. Licensor means the individual(s) or entity(ies) granting rights\n     under this Public License.\n\n  i. Share means to provide material to the public by any means or\n     process that requires permission under the Licensed Rights, such\n     as reproduction, public display, public performance, distribution,\n     dissemination, communication, or importation, and to make material\n     available to the public including in ways that members of the\n     public may access the material from a place and at a time\n     individually chosen by them.\n\n  j. Sui Generis Database Rights means rights other than copyright\n     resulting from Directive 96/9/EC of the European Parliament and of\n     the Council of 11 March 1996 on the legal protection of databases,\n     as amended and/or succeeded, as well as other essentially\n     equivalent rights anywhere in the world.\n\n  k. You means the individual or entity exercising the Licensed Rights\n     under this Public License. Your has a corresponding meaning.\n\n\nSection 2 -- Scope.\n\n  a. License grant.\n\n       1. Subject to the terms and conditions of this Public License,\n          the Licensor hereby grants You a worldwide, royalty-free,\n          non-sublicensable, non-exclusive, irrevocable license to\n          exercise the Licensed Rights in the Licensed Material to:\n\n            a. reproduce and Share the Licensed Material, in whole or\n               in part; and\n\n            b. produce, reproduce, and Share Adapted Material.\n\n       2. Exceptions and Limitations. For the avoidance of doubt, where\n          Exceptions and Limitations apply to Your use, this Public\n          License does not apply, and You do not need to comply with\n          its terms and conditions.\n\n       3. Term. The term of this Public License is specified in Section\n          6(a).\n\n       4. Media and formats; technical modifications allowed. The\n          Licensor authorizes You to exercise the Licensed Rights in\n          all media and formats whether now known or hereafter created,\n          and to make technical modifications necessary to do so. The\n          Licensor waives and/or agrees not to assert any right or\n          authority to forbid You from making technical modifications\n          necessary to exercise the Licensed Rights, including\n          technical modifications necessary to circumvent Effective\n          Technological Measures. For purposes of this Public License,\n          simply making modifications authorized by this Section 2(a)\n          (4) never produces Adapted Material.\n\n       5. Downstream recipients.\n\n            a. Offer from the Licensor -- Licensed Material. Every\n               recipient of the Licensed Material automatically\n               receives an offer from the Licensor to exercise the\n               Licensed Rights under the terms and conditions of this\n               Public License.\n\n            b. No downstream restrictions. You may not offer or impose\n               any additional or different terms or conditions on, or\n               apply any Effective Technological Measures to, the\n               Licensed Material if doing so restricts exercise of the\n               Licensed Rights by any recipient of the Licensed\n               Material.\n\n       6. No endorsement. Nothing in this Public License constitutes or\n          may be construed as permission to assert or imply that You\n          are, or that Your use of the Licensed Material is, connected\n          with, or sponsored, endorsed, or granted official status by,\n          the Licensor or others designated to receive attribution as\n          provided in Section 3(a)(1)(A)(i).\n\n  b. Other rights.\n\n       1. Moral rights, such as the right of integrity, are not\n          licensed under this Public License, nor are publicity,\n          privacy, and/or other similar personality rights; however, to\n          the extent possible, the Licensor waives and/or agrees not to\n          assert any such rights held by the Licensor to the limited\n          extent necessary to allow You to exercise the Licensed\n          Rights, but not otherwise.\n\n       2. Patent and trademark rights are not licensed under this\n          Public License.\n\n       3. To the extent possible, the Licensor waives any right to\n          collect royalties from You for the exercise of the Licensed\n          Rights, whether directly or through a collecting society\n          under any voluntary or waivable statutory or compulsory\n          licensing scheme. In all other cases the Licensor expressly\n          reserves any right to collect such royalties.\n\n\nSection 3 -- License Conditions.\n\nYour exercise of the Licensed Rights is expressly made subject to the\nfollowing conditions.\n\n  a. Attribution.\n\n       1. If You Share the Licensed Material (including in modified\n          form), You must:\n\n            a. retain the following if it is supplied by the Licensor\n               with the Licensed Material:\n\n                 i. identification of the creator(s) of the Licensed\n                    Material and any others designated to receive\n                    attribution, in any reasonable manner requested by\n                    the Licensor (including by pseudonym if\n                    designated);\n\n                ii. a copyright notice;\n\n               iii. a notice that refers to this Public License;\n\n                iv. a notice that refers to the disclaimer of\n                    warranties;\n\n                 v. a URI or hyperlink to the Licensed Material to the\n                    extent reasonably practicable;\n\n            b. indicate if You modified the Licensed Material and\n               retain an indication of any previous modifications; and\n\n            c. indicate the Licensed Material is licensed under this\n               Public License, and include the text of, or the URI or\n               hyperlink to, this Public License.\n\n       2. You may satisfy the conditions in Section 3(a)(1) in any\n          reasonable manner based on the medium, means, and context in\n          which You Share the Licensed Material. For example, it may be\n          reasonable to satisfy the conditions by providing a URI or\n          hyperlink to a resource that includes the required\n          information.\n\n       3. If requested by the Licensor, You must remove any of the\n          information required by Section 3(a)(1)(A) to the extent\n          reasonably practicable.\n\n       4. If You Share Adapted Material You produce, the Adapter's\n          License You apply must not prevent recipients of the Adapted\n          Material from complying with this Public License.\n\n\nSection 4 -- Sui Generis Database Rights.\n\nWhere the Licensed Rights include Sui Generis Database Rights that\napply to Your use of the Licensed Material:\n\n  a. for the avoidance of doubt, Section 2(a)(1) grants You the right\n     to extract, reuse, reproduce, and Share all or a substantial\n     portion of the contents of the database;\n\n  b. if You include all or a substantial portion of the database\n     contents in a database in which You have Sui Generis Database\n     Rights, then the database in which You have Sui Generis Database\n     Rights (but not its individual contents) is Adapted Material; and\n\n  c. You must comply with the conditions in Section 3(a) if You Share\n     all or a substantial portion of the contents of the database.\n\nFor the avoidance of doubt, this Section 4 supplements and does not\nreplace Your obligations under this Public License where the Licensed\nRights include other Copyright and Similar Rights.\n\n\nSection 5 -- Disclaimer of Warranties and Limitation of Liability.\n\n  a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE\n     EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS\n     AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF\n     ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,\n     IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,\n     WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR\n     PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,\n     ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT\n     KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT\n     ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.\n\n  b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE\n     TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,\n     NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,\n     INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,\n     COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR\n     USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN\n     ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR\n     DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR\n     IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.\n\n  c. The disclaimer of warranties and limitation of liability provided\n     above shall be interpreted in a manner that, to the extent\n     possible, most closely approximates an absolute disclaimer and\n     waiver of all liability.\n\n\nSection 6 -- Term and Termination.\n\n  a. This Public License applies for the term of the Copyright and\n     Similar Rights licensed here. However, if You fail to comply with\n     this Public License, then Your rights under this Public License\n     terminate automatically.\n\n  b. Where Your right to use the Licensed Material has terminated under\n     Section 6(a), it reinstates:\n\n       1. automatically as of the date the violation is cured, provided\n          it is cured within 30 days of Your discovery of the\n          violation; or\n\n       2. upon express reinstatement by the Licensor.\n\n     For the avoidance of doubt, this Section 6(b) does not affect any\n     right the Licensor may have to seek remedies for Your violations\n     of this Public License.\n\n  c. For the avoidance of doubt, the Licensor may also offer the\n     Licensed Material under separate terms or conditions or stop\n     distributing the Licensed Material at any time; however, doing so\n     will not terminate this Public License.\n\n  d. Sections 1, 5, 6, 7, and 8 survive termination of this Public\n     License.\n\n\nSection 7 -- Other Terms and Conditions.\n\n  a. The Licensor shall not be bound by any additional or different\n     terms or conditions communicated by You unless expressly agreed.\n\n  b. Any arrangements, understandings, or agreements regarding the\n     Licensed Material not stated herein are separate from and\n     independent of the terms and conditions of this Public License.\n\n\nSection 8 -- Interpretation.\n\n  a. For the avoidance of doubt, this Public License does not, and\n     shall not be interpreted to, reduce, limit, restrict, or impose\n     conditions on any use of the Licensed Material that could lawfully\n     be made without permission under this Public License.\n\n  b. To the extent possible, if any provision of this Public License is\n     deemed unenforceable, it shall be automatically reformed to the\n     minimum extent necessary to make it enforceable. If the provision\n     cannot be reformed, it shall be severed from this Public License\n     without affecting the enforceability of the remaining terms and\n     conditions.\n\n  c. No term or condition of this Public License will be waived and no\n     failure to comply consented to unless expressly agreed to by the\n     Licensor.\n\n  d. Nothing in this Public License constitutes or may be interpreted\n     as a limitation upon, or waiver of, any privileges and immunities\n     that apply to the Licensor or You, including from the legal\n     processes of any jurisdiction or authority.\n\n\n=======================================================================\n\nCreative Commons is not a party to its public\nlicenses. Notwithstanding, Creative Commons may elect to apply one of\nits public licenses to material it publishes and in those instances\nwill be considered the “Licensor.” The text of the Creative Commons\npublic licenses is dedicated to the public domain under the CC0 Public\nDomain Dedication. Except for the limited purpose of indicating that\nmaterial is shared under a Creative Commons public license or as\notherwise permitted by the Creative Commons policies published at\ncreativecommons.org/policies, Creative Commons does not authorize the\nuse of the trademark \"Creative Commons\" or any other trademark or logo\nof Creative Commons without its prior written consent including,\nwithout limitation, in connection with any unauthorized modifications\nto any of its public licenses or any other arrangements,\nunderstandings, or agreements concerning use of licensed material. For\nthe avoidance of doubt, this paragraph does not form part of the\npublic licenses.\n\nCreative Commons may be contacted at creativecommons.org.\n\n"
  },
  {
    "path": "README.md",
    "content": "\nDebug Recipes\n=============\n\nIt 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.\n\n:floppy_disk: Old and no longer updated recipes are in the [archived branch](https://github.com/lowleveldesign/debug-recipes/tree/archive).\n\nThe recipes are available in the guides folder and at **[wtrace.net](https://wtrace.net/guides)** (probably the best way to view them).\n\n## Troubleshooting guides\n\n- [Diagnosing .NET applications](guides/diagnosing-dotnet-apps.md)\n- [Diagnosing native Windows applications](guides/diagnosing-native-windows-apps.md)\n- [COM troubleshooting](guides/com-troubleshooting)\n\n## Tools usage guides\n\n- [WinDbg usage guide](guides/windbg.md)\n- [Event Tracing for Windows (ETW)](guides/etw.md)\n- [Using withdll and detours to trace Win API calls](guides/using-withdll-and-detours-to-trace-winapi.md)\n- [Windows Performance Counters](guides/windows-performance-counters.md)\n- [Network tracing tools](guides/network-tracing-tools.md)\n"
  },
  {
    "path": "_config.yml",
    "content": "title: wtrace.net\nemail: contact@wtrace.net\ndescription: >- # this means to ignore newlines until \"baseurl:\"\n  Tools and materials for software and system troubleshooting \nbaseurl: \"\" # the subpath of your site, e.g. /blog\nurl: \"https://wtrace.net\" # the base hostname & protocol for your site, e.g. http://example.com\n\nyoutube_username: \"@lowleveldesign\"\ngithub_username:  lowleveldesign\n\npermalink: pretty\n\ndefaults:\n  - \n    scope:\n      path: \"\"\n      type: \"posts\"\n    values:\n      permalink: /:year/:month/:day/:title\n\n# Build settings\ntheme: minima\nplugins:\n  - jekyll-feed\n  - jekyll-seo-tag\n  - jekyll-redirect-from\n  - jekyll-sitemap\n  - jemoji\n\nheader_pages:\n  - guides.md\n  - tools.md\n  - about.md\n"
  },
  {
    "path": "_includes/footer.html",
    "content": "<footer class=\"site-footer h-card\">\n  <data class=\"u-url\" href=\"{{ \"/\" | relative_url }}\"></data>\n\n  <div class=\"wrapper\">\n    <div class=\"footer-col-wrapper\">\n      <div class=\"footer-col footer-col-1\">\n        <p>\n          &copy; {{ site.time | date: \"%Y\" }} {{ site.title | escape }}\n        </p>\n        <p>{{- site.description | escape -}}</p>\n      </div>\n\n      <div class=\"footer-col footer-col-2\">\n        <ul class=\"contact-list\">\n        </ul>\n      </div>\n\n      <div class=\"footer-col footer-col-3\">\n        {%- include social.html -%}\n      </div>\n    </div>\n  </div>\n\n</footer>\n"
  },
  {
    "path": "_includes/head.html",
    "content": "\n<head>\n  <meta charset=\"utf-8\">\n  <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\n  <link rel=\"apple-touch-icon\" sizes=\"180x180\" href=\"/apple-touch-icon.png\">\n  <link rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"/favicon-32x32.png\">\n  <link rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"/favicon-16x16.png\">\n  <link rel=\"manifest\" href=\"/site.webmanifest\">\n  <link rel=\"mask-icon\" href=\"/safari-pinned-tab.svg\" color=\"#5bbad5\">\n  <meta name=\"msapplication-TileColor\" content=\"#da532c\">\n  <meta name=\"theme-color\" content=\"#ffffff\">\n\n  {%- seo -%}\n  <link rel=\"stylesheet\" href=\"{{ \"/assets/main.css\" | relative_url }}\">\n  {%- feed_meta -%}\n  {%- if jekyll.environment == 'production' and site.google_analytics -%}\n    {%- include google-analytics.html -%}\n  {%- endif -%}\n</head>\n"
  },
  {
    "path": "_layouts/home.html",
    "content": "---\n---\n<!DOCTYPE html>\n<html lang=\"{{ page.lang | default: site.lang | default: \"en\" }}\">\n\n  {%- include head.html -%}\n\n  <body>\n\n    {%- include header.html -%}\n\n    <div class=\"home\">\n      {%- if page.title -%}\n      <div class=\"feature-image\"{% if page.feature_image %} style=\"background-image: url({{ page.feature_image }})\"{% endif %}>\n        <div class=\"wrapper\">\n          <h1 class=\"page-heading\">{{ page.title }}</h1>\n          {% if page.description %}\n          <p>{{ page.description }}</p>\n          {% endif %}\n        </div>\n      </div>\n      {%- endif -%}\n\n      <main class=\"page-content\" aria-label=\"Content\">\n        <div class=\"wrapper\">\n          {{ content }}\n        </div>\n      </main>\n\n    </div>\n\n    {%- include footer.html -%}\n\n  </body>\n\n</html>\n"
  },
  {
    "path": "_layouts/posts.html",
    "content": "---\nlayout: default\n---\n\n<div class=\"home\">\n  {%- if page.title -%}\n    <h1 class=\"page-heading\">{{ page.title }}</h1>\n  {%- endif -%}\n\n  {%- if site.posts.size > 0 -%}\n    <ul class=\"post-list\">\n      {%- for post in site.posts -%}\n      <li>\n        {%- assign date_format = site.minima.date_format | default: \"%b %-d, %Y\" -%}\n        <span class=\"post-meta\">{{ post.date | date: date_format }}</span>\n        <h3>\n          <a class=\"post-link\" href=\"{{ post.url | relative_url }}\">\n            {{ post.title | escape }}\n          </a>\n        </h3>\n        {{ post.excerpt }}\n      </li>\n      {%- endfor -%}\n    </ul>\n  {%- endif -%}\n\n</div>"
  },
  {
    "path": "about.md",
    "content": "---\nlayout: page\ntitle: About\n---\n\nI 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. \n\nI 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.\n\n<p class=\"credits\">\n<em><strong>Credits:</strong> this site uses modified icons from the <a href=\"https://github.com/feathericons/feather\">feather set</a>.</em>\n</p>\n\n<p class=\"credits\">\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by/4.0/88x31.png\"></a><br>The published guides are licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\">Creative Commons Attribution 4.0 International License</a>.\n</p>"
  },
  {
    "path": "articles.md",
    "content": "---\nlayout: page\ntitle: Articles\nredirect_to: /guides\n---\n"
  },
  {
    "path": "assets/main.scss",
    "content": "---\n# Only the main Sass file needs front matter (the dashes are enough)\n---\n\n$brand-color: #CA4E07;\n$credits-color: #707070;\n\n@import \"minima\";\n\nbody {\n  background-color: #f6f6ef;\n}\n\npre, code {\n  background: transparent;\n}\n\n.highlighter-rouge .highlight {\n  background: #f9f9f9;\n}\n\n.highlight .c {\n  color: #6c6c62;\n}\n\n.post-title {\n  @include relative-font-size(2.2);\n  letter-spacing: -1px;\n  line-height: 1;\n\n  @include media-query($on-laptop) {\n    @include relative-font-size(2.0);\n  }\n}\n\n.post-content {\n  table {\n    table-layout: fixed;\n  }\n\n  table th {\n    text-align: center;\n  }\n\n  table td {\n    vertical-align: top;\n  }\n\n  h2, h3 {\n    margin: 15px 0 15px 0;\n  }\n}\n\n.site-title {\n  @include relative-font-size(1.4);\n  font-weight: 700;\n  line-height: $base-line-height * $base-font-size * 2.25;\n  letter-spacing: -1px;\n  margin-bottom: 0;\n  float: left;\n  text-transform: uppercase;\n\n  &, &:visited {\n    color: $brand-color;\n  }\n}\n\n.site-nav {\n  .page-link {\n    text-transform: uppercase;\n    font-weight: 600;\n  }\n}\n\n.feature-image {\n  background-color: black;\n  background-repeat: no-repeat;\n  margin-bottom: 10px;\n  padding-top: 50px;\n  height: 300px;\n\n  .wrapper {\n    color: #ffffff;\n\n    h1 {\n      font-size: 4rem;\n      font-weight: 900;\n      margin-bottom: 0px\n    }\n\n    p {\n      font-size: 1.2rem;\n    }\n  }\n}\n\np.credits {\n  color: $credits-color;\n  padding-top: 10px;\n  margin-top: 10px;\n}\n"
  },
  {
    "path": "assets/other/EtwMetadata.ps1.txt",
    "content": "\r\n$ErrorActionPreference = \"Stop\"\r\n\r\n$MetadataFolder = \"$env:LOCALAPPDATA\\MyEtwMetadata\\ById\"\r\n$MetadataSearchByNameFolder = \"$env:LOCALAPPDATA\\MyEtwMetadata\\ByName\"\r\n\r\n\r\nif (-not (Test-Path $MetadataFolder)) {\r\n    New-Item -ItemType Directory -Path $MetadataFolder | Out-Null\r\n}\r\n\r\nif (-not (Test-Path $MetadataSearchByNameFolder)) {\r\n    New-Item -ItemType Directory -Path $MetadataSearchByNameFolder | Out-Null\r\n}\r\n\r\nfunction _SanitizeFileName {\r\n    param ([Parameter(Mandatory = $true)]$FileName)\r\n\r\n    [System.IO.Path]::GetInvalidFileNameChars() | ForEach-Object -Process {\r\n        $FileName = $FileName.Replace($_, [char]'_')\r\n    }\r\n    $FileName\r\n}\r\n\r\nWrite-Output \"Initializing ETW providers metadata... \"\r\nwevtutil.exe ep | ForEach-Object -Process {\r\n    $ProviderName = $_\r\n    Write-Debug $ProviderName\r\n    $xml = $(wevtutil.exe gp /f:xml \"$_\" 2>$null)\r\n    if ($LASTEXITCODE -eq 0 -and $xml) {\r\n        $metadata = [xml]$xml\r\n        $metadata.Save($(Join-Path -Path $MetadataFolder -ChildPath \"$($metadata.provider.guid).xml\"));\r\n        $metadata.provider.guid | Out-File $(\r\n            Join-Path -Path $MetadataSearchByNameFolder -ChildPath \"$(_SanitizeFileName $ProviderName).txt\")\r\n    }\r\n    else {\r\n        Write-Warning \"Invalid metadata for '$ProviderName'\"\r\n    }\r\n}\r\n\r\nfunction _ResolveKeywords {\r\n    param (\r\n        [Parameter(Mandatory = $true)]$Metadata,\r\n        [Parameter(Mandatory = $true)][ulong]$Keywords\r\n    )\r\n\r\n    if ($Metadata.provider.keywords) {\r\n        $Metadata.provider.keywords.keyword | ForEach-Object -Process {\r\n            $MaskValue = [ulong]::Parse($_.mask.TrimStart(@('0', 'x', 'X')), [System.Globalization.NumberStyles]::HexNumber)\r\n            if ($Keywords -band $MaskValue) {\r\n                [PSCustomObject]@{\r\n                    Name  = $_.name\r\n                    Value = $MaskValue\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n# ** EXPORTS **\r\n\r\nfunction Get-EtwProvidersFromWprProfile {\r\n    param (\r\n        [Parameter(Mandatory = $true)][string]$WprProfilePath\r\n    )\r\n\r\n    if (-not (Test-Path $MetadataFolder)) {\r\n        Write-Error \"No metadata found - please run Initialize-EtwProvidersMetadata first.\"\r\n    }\r\n\r\n    function ParseProvider([Parameter(ValueFromPipeline = $true, Mandatory = $true)]$ProviderData) {\r\n        begin {}\r\n        process {\r\n            $MetadataPath = (Join-Path -Path $MetadataFolder -ChildPath \"$($ProviderData.Name).xml\")\r\n            if (-not (Test-Path $MetadataPath)) {\r\n                Write-Warning \"No metadata found for provider '$($ProviderData.Name)'\"\r\n                return\r\n            }\r\n\r\n            Write-Debug \"Parsing provider '$($ProviderData.Name))'\"\r\n            $Metadata = [xml](Get-Content $MetadataPath)\r\n\r\n            [ulong]$Keywords = 0\r\n            if ($ProviderData.Keywords) {\r\n                $ProviderData.Keywords.Keyword.Value | ForEach-Object -Process {\r\n                    $Keywords = $Keywords -bor ([ulong]::Parse($_.TrimStart(@('0', 'x', 'X')), [System.Globalization.NumberStyles]::HexNumber)) }\r\n            }\r\n            else {\r\n                $Keywords = [ulong]::MaxValue\r\n            }\r\n\r\n            [ulong]$CaptureOnSaveKeywords = 0\r\n            if ($ProviderData.CaptureOnSaveKeywords) {\r\n                $ProviderData.CaptureStateOnSave.Keyword.Value | ForEach-Object -Process {\r\n                    $CaptureOnSaveKeywords = $CaptureOnSaveKeywords -bor ([ulong]::Parse($_.TrimStart(@('0', 'x', 'X')), [System.Globalization.NumberStyles]::HexNumber)) }\r\n            }\r\n\r\n            [PSCustomObject]@{\r\n                Id                    = $ProviderData.Name\r\n                Name                  = $Metadata.provider.name\r\n                Keywords              = _ResolveKeywords $Metadata $Keywords\r\n                CaptureOnSaveKeywords = _ResolveKeywords $Metadata $CaptureOnSaveKeywords\r\n            }\r\n        }\r\n        end {}\r\n    }\r\n    \r\n    $xml = [xml](Get-Content $WprProfilePath)\r\n\r\n    $xml.WindowsPerformanceRecorder.Profiles.EventProvider | ParseProvider\r\n}\r\n\r\nfunction Get-EtwProviderMetadata {\r\n    param([Parameter(ValueFromPipeline = $true, Mandatory = $true)]$ProviderName)\r\n\r\n    $ProviderId = $ProviderName\r\n    $Path = $(Join-Path -Path $MetadataSearchByNameFolder -ChildPath \"$(_SanitizeFileName $ProviderName).txt\")\r\n    if (Test-Path $Path) {\r\n        $ProviderId = Get-Content $Path\r\n    }\r\n\r\n    $MetadataPath = (Join-Path -Path $MetadataFolder -ChildPath \"$ProviderId.xml\")\r\n    if (-not (Test-Path $MetadataPath)) {\r\n        Write-Error \"No metadata found for provider '$($ProviderId)'\"\r\n    }\r\n\r\n    $Metadata = [xml](Get-Content $MetadataPath)\r\n\r\n    [PSCustomObject]@{\r\n        Id       = $ProviderId\r\n        Name     = $Metadata.provider.name\r\n        Keywords = _ResolveKeywords $Metadata $([ulong]::MaxValue)\r\n    }\r\n}\r\n"
  },
  {
    "path": "assets/other/WTComTrace.wprp",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<WindowsPerformanceRecorder Version=\"1.0\" Author=\"Sebastian Solnica (https://wtrace.net)\" Comments=\"Profile based on TSS scripts by Microsoft\">\r\n  <Profiles>\r\n    <SystemCollector Id=\"SystemCollector\" Name=\"NT Kernel Logger\">\r\n      <BufferSize Value=\"1024\"/>\r\n      <Buffers Value=\"32\"/>\r\n    </SystemCollector>\r\n    \r\n    <EventCollector Id=\"EventCollector_MicrosoftWindowsCOMTrace\" Name=\"MicrosoftWindowsCOMTraceCollector\">\r\n      <BufferSize Value=\"1024\" />\r\n      <Buffers Value=\"32\" />\r\n    </EventCollector>\r\n    \r\n    <SystemProvider Id=\"SystemProviderBasic\">\r\n      <Keywords>\r\n        <Keyword Value=\"ProcessThread\" />\r\n        <Keyword Value=\"Loader\" />\r\n        <Keyword Value=\"Registry\" />\r\n      </Keywords>\r\n    </SystemProvider>\r\n    \r\n    <EventProvider Id=\"EventProvider_CombaseTraceLoggingProvider\" Name=\"1AFF6089-E863-4D36-BDFD-3581F07440BE\" NonPagedMemory=\"true\"></EventProvider>\r\n    <EventProvider Id=\"EventProvider_COMSVCS-COMPlus\" Name=\"B46FA1AD-B22D-4362-B072-9F5BA07B046D\" NonPagedMemory=\"true\"></EventProvider>\r\n    <EventProvider Id=\"EventProvider_COMADMIN-COMPlus\" Name=\"A0C4702B-51F7-4ea9-9C74-E39952C694B8\" NonPagedMemory=\"true\"></EventProvider>\r\n    <EventProvider Id=\"EventProvider_COMPlus-Services\" Name=\"53201895-60E8-4fb0-9643-3F80762D658F\" NonPagedMemory=\"true\"></EventProvider>\r\n    <EventProvider Id=\"EventProvider_MicrosoftWindowsComBaseWpp\" Name=\"bda92ae8-9f11-4d49-ba1d-a4c2abca692e\" NonPagedMemory=\"true\"></EventProvider>\r\n    <EventProvider Id=\"EventProvider_MicrosoftWindowsDcomScmWpp\" Name=\"9474a749-a98d-4f52-9f45-5b20247e4f01\" NonPagedMemory=\"true\"></EventProvider>\r\n    <EventProvider Id=\"EventProvider_Microsoft-Windows-COM\" Name=\"d4263c98-310c-4d97-ba39-b55354f08584\" NonPagedMemory=\"true\"></EventProvider>\r\n    <EventProvider Id=\"EventProvider_Microsoft-Windows-Complus\" Name=\"0f177893-4a9c-4709-b921-f432d67f43d5\" NonPagedMemory=\"true\"></EventProvider>\r\n    <EventProvider Id=\"EventProvider_Microsoft-Windows-DistributedCOM\" Name=\"1B562E86-B7AA-4131-BADC-B6F3A001407E\" NonPagedMemory=\"true\"></EventProvider>\r\n    <EventProvider Id=\"EventProvider_CLBCATQ\" Name=\"097d1686-4038-46be-b551-10fda0387165\" NonPagedMemory=\"true\"></EventProvider>\r\n    <EventProvider Id=\"EventProvider_Microsoft-Windows-COMRuntime\" Name=\"bf406804-6afa-46e7-8a48-6c357e1d6d61\" NonPagedMemory=\"true\"></EventProvider>\r\n    <EventProvider Id=\"EventProvider_Microsoft-Windows-WinRT-Error\" Name=\"A86F8471-C31D-4FBC-A035-665D06047B03\" NonPagedMemory=\"true\"></EventProvider>\r\n    <EventProvider Id=\"EventProvider_Microsoft-Windows-WinTypes-Perf\" Name=\"7913ac64-a5cd-40cd-b096-4e8c4028eaab\" NonPagedMemory=\"true\"></EventProvider>\r\n    <EventProvider Id=\"EventProvider_Microsoft-Windows-WinRtClassActivation\" Name=\"f0558438-f56a-5987-47da-040ca757ef05\" NonPagedMemory=\"true\"></EventProvider>\r\n    <EventProvider Id=\"EventProvider_Microsoft-Windows-RPC\" Name=\"6AD52B32-D609-4BE9-AE07-CE8DAE937E39\" NonPagedMemory=\"true\"></EventProvider>\r\n    <EventProvider Id=\"EventProvider_Microsoft-Windows-RPCSS\" Name=\"d8975f88-7ddb-4ed0-91bf-3adf48c48e0c\" NonPagedMemory=\"true\"></EventProvider>\r\n    <EventProvider Id=\"EventProvider_Microsoft-Windows-RPC-Events\" Name=\"F4AED7C7-A898-4627-B053-44A7CAA12FCD\" NonPagedMemory=\"true\"></EventProvider>\r\n    <EventProvider Id=\"EventProvider_Microsoft-Windows-RPC-Proxy-LBS\" Name=\"272A979B-34B5-48EC-94F5-7225A59C85A0\" NonPagedMemory=\"true\"></EventProvider>\r\n    <EventProvider Id=\"EventProvider_Microsoft-Windows-RPC-Proxy\" Name=\"879b2576-39d1-4c0f-80a4-cc086e02548c\" NonPagedMemory=\"true\"></EventProvider>\r\n    <EventProvider Id=\"EventProvider_Microsoft-Windows-RPC-LBS\" Name=\"536caa1f-798d-4cdb-a987-05f79a9f457e\" NonPagedMemory=\"true\"></EventProvider>\r\n    \r\n    <Profile Id=\"COMTrace.Verbose.File\" Name=\"COMTrace\" Description=\"COM events trace\" LoggingMode=\"File\" DetailLevel=\"Verbose\">\r\n      <Collectors>\r\n        <SystemCollectorId Value=\"SystemCollector\">\r\n          <SystemProviderId Value=\"SystemProviderBasic\"/>\r\n        </SystemCollectorId>\r\n        <EventCollectorId Value=\"EventCollector_MicrosoftWindowsCOMTrace\">\r\n          <EventProviders>\r\n            <EventProviderId Value=\"EventProvider_CombaseTraceLoggingProvider\" />\r\n            <EventProviderId Value=\"EventProvider_COMSVCS-COMPlus\" />\r\n            <EventProviderId Value=\"EventProvider_COMADMIN-COMPlus\" />\r\n            <EventProviderId Value=\"EventProvider_COMPlus-Services\" />\r\n            <EventProviderId Value=\"EventProvider_MicrosoftWindowsComBaseWpp\" />\r\n            <EventProviderId Value=\"EventProvider_MicrosoftWindowsDcomScmWpp\" />\r\n            <EventProviderId Value=\"EventProvider_Microsoft-Windows-COM\" />\r\n            <EventProviderId Value=\"EventProvider_Microsoft-Windows-Complus\" />\r\n            <EventProviderId Value=\"EventProvider_Microsoft-Windows-DistributedCOM\" />\r\n            <EventProviderId Value=\"EventProvider_CLBCATQ\" />\r\n            <EventProviderId Value=\"EventProvider_Microsoft-Windows-COMRuntime\" />\r\n            <EventProviderId Value=\"EventProvider_Microsoft-Windows-WinRT-Error\" />\r\n            <EventProviderId Value=\"EventProvider_Microsoft-Windows-WinTypes-Perf\" />\r\n            <EventProviderId Value=\"EventProvider_Microsoft-Windows-WinRtClassActivation\" />\r\n            <EventProviderId Value=\"EventProvider_Microsoft-Windows-RPC\" />\r\n            <EventProviderId Value=\"EventProvider_Microsoft-Windows-RPCSS\" />\r\n            <EventProviderId Value=\"EventProvider_Microsoft-Windows-RPC-Events\" />\r\n            <EventProviderId Value=\"EventProvider_Microsoft-Windows-RPC-Proxy-LBS\" />\r\n            <EventProviderId Value=\"EventProvider_Microsoft-Windows-RPC-Proxy\" />\r\n            <EventProviderId Value=\"EventProvider_Microsoft-Windows-RPC-LBS\" />\r\n          </EventProviders>\r\n        </EventCollectorId>\r\n      </Collectors>\r\n\r\n      <TraceMergeProperties>\r\n        <TraceMergeProperty Id=\"BaseVerboseTraceMergeProperties\" Name=\"BaseTraceMergeProperties\">\r\n          <DeletePreMergedTraceFiles Value=\"true\" />\r\n          <FileCompression Value=\"false\" />\r\n          <InjectOnly Value=\"false\" />\r\n          <SkipMerge Value=\"false\" />\r\n          <CustomEvents>\r\n            <CustomEvent Value=\"ImageId\" />\r\n            <CustomEvent Value=\"BuildInfo\" />\r\n            <CustomEvent Value=\"VolumeMapping\" />\r\n            <CustomEvent Value=\"EventMetadata\" />\r\n            <CustomEvent Value=\"PerfTrackMetadata\" />\r\n            <CustomEvent Value=\"WinSAT\" />\r\n            <CustomEvent Value=\"NetworkInterface\" />\r\n          </CustomEvents>\r\n        </TraceMergeProperty>\r\n      </TraceMergeProperties>\r\n    </Profile>\r\n    \r\n  </Profiles>\r\n</WindowsPerformanceRecorder>\r\n"
  },
  {
    "path": "assets/other/winapi-user32.ps1.txt",
    "content": "$ErrorActionPreference = \"Stop\"\r\n\r\nAdd-Type -TypeDefinition @\"\r\n    using System;\r\n    public enum GWL_EXSTYLE : int {\r\n        WS_EX_DLGMODALFRAME = 0x00000001,\r\n        WS_EX_NOPARENTNOTIFY = 0x00000004,\r\n        WS_EX_TOPMOST = 0x00000008,\r\n        WS_EX_ACCEPTFILES = 0x00000010,\r\n        WS_EX_TRANSPARENT = 0x00000020,\r\n        WS_EX_MDICHILD = 0x00000040,\r\n        WS_EX_TOOLWINDOW = 0x00000080,\r\n        WS_EX_WINDOWEDGE = 0x00000100,\r\n        WS_EX_CLIENTEDGE = 0x00000200,\r\n        WS_EX_CONTEXTHELP = 0x00000400,\r\n        WS_EX_RIGHT = 0x00001000,\r\n        WS_EX_LEFT = 0x00000000,\r\n        WS_EX_RTLREADING = 0x00002000,\r\n        WS_EX_LTRREADING = 0x00000000,\r\n        WS_EX_LEFTSCROLLBAR = 0x00004000,\r\n        WS_EX_RIGHTSCROLLBAR = 0x00000000,\r\n        WS_EX_CONTROLPARENT = 0x00010000,\r\n        WS_EX_STATICEDGE = 0x00020000,\r\n        WS_EX_APPWINDOW = 0x00040000,\r\n        WS_EX_LAYERED = 0x00080000,\r\n        WS_EX_NOINHERITLAYOUT = 0x00100000,\r\n        WS_EX_NOREDIRECTIONBITMAP = 0x00200000,\r\n        WS_EX_LAYOUTRTL = 0x00400000,\r\n        WS_EX_COMPOSITED = 0x02000000,\r\n        WS_EX_NOACTIVATE = 0x08000000\r\n    }\r\n\r\n    public enum GWL_STYLE : int {\r\n        WS_OVERLAPPED = 0x00000000,\r\n        WS_POPUP = unchecked((int)0x80000000),\r\n        WS_CHILD = 0x40000000,\r\n        WS_MINIMIZE = 0x20000000,\r\n        WS_VISIBLE = 0x10000000,\r\n        WS_DISABLED = 0x08000000,\r\n        WS_CLIPSIBLINGS = 0x04000000,\r\n        WS_CLIPCHILDREN = 0x02000000,\r\n        WS_MAXIMIZE = 0x01000000,\r\n        WS_CAPTION = 0x00C00000,\r\n        WS_BORDER = 0x00800000,\r\n        WS_DLGFRAME = 0x00400000,\r\n        WS_VSCROLL = 0x00200000,\r\n        WS_HSCROLL = 0x00100000,\r\n        WS_SYSMENU = 0x00080000,\r\n        WS_THICKFRAME = 0x00040000,\r\n        // WS_GROUP = 0x00020000,\r\n        // WS_TABSTOP = 0x00010000,\r\n        WS_MINIMIZEBOX = 0x00020000,\r\n        WS_MAXIMIZEBOX = 0x00010000,\r\n        // WS_TILED = WS_OVERLAPPED,\r\n        // WS_ICONIC = WS_MINIMIZE,\r\n        // WS_SIZEBOX = WS_THICKFRAME\r\n    }\r\n\r\n    public enum SWP : uint {\r\n        SWP_NOSIZE = 0x0001,\r\n        SWP_NOMOVE = 0x0002,\r\n        SWP_NOZORDER = 0x0004,\r\n        SWP_NOREDRAW = 0x0008,\r\n        SWP_NOACTIVATE = 0x0010,\r\n        SWP_FRAMECHANGED = 0x0020,\r\n        SWP_SHOWWINDOW = 0x0040,\r\n        SWP_HIDEWINDOW = 0x0080,\r\n        SWP_NOCOPYBITS = 0x0100,\r\n        SWP_NOOWNERZORDER = 0x0200,\r\n        SWP_NOSENDCHANGING = 0x0400,\r\n        // SWP_DRAWFRAME = SWP_FRAMECHANGED,\r\n        // SWP_NOREPOSITION = SWP_NOOWNERZORDER,\r\n        SWP_DEFERERASE = 0x2000,\r\n        SWP_ASYNCWINDOWPOS = 0x4000\r\n    }\r\n\"@\r\n"
  },
  {
    "path": "assets/other/windbg-install.ps1.txt",
    "content": "# 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):\n\nparam(\n    $OutDir = \".\",\n    [ValidateSet(\"x64\", \"x86\", \"arm64\")]\n    $Arch = \"x64\"\n)\n\nif (!(Test-Path $OutDir)) {\n    $null = mkdir $OutDir\n}\n\n$ErrorActionPreference = \"Stop\"\n\nif ($PSVersionTable.PSVersion.Major -le 5) {\n    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12\n\n    # This is a workaround to get better performance on older versions of PowerShell\n    $ProgressPreference = 'SilentlyContinue'\n}\n\n# Download the appinstaller to find the current uri for the msixbundle\nInvoke-WebRequest https://aka.ms/windbg/download -OutFile $OutDir\\windbg.appinstaller\n\n# Download the msixbundle\n$msixBundleUri = ([xml](Get-Content $OutDir\\windbg.appinstaller)).AppInstaller.MainBundle.Uri\n\n# Download the msixbundle (but name as zip for older versions of Expand-Archive\nInvoke-WebRequest $msixBundleUri -OutFile $OutDir\\windbg.zip\n\n# Extract the 3 msix files (plus other files)\nExpand-Archive -DestinationPath $OutDir\\UnzippedBundle $OutDir\\windbg.zip\n\n# Expand the build you want - also renaming the msix to zip for Windows PowerShell\n$fileName = switch ($Arch) {\n    \"x64\" { \"windbg_win-x64\" }\n    \"x86\" { \"windbg_win-x86\" }\n    \"arm64\" { \"windbg_win-arm64\" }\n}\n\n# Rename msix (for older versions of Expand-Archive) and extract the debugger\nRename-Item \"$OutDir\\UnzippedBundle\\$fileName.msix\" \"$fileName.zip\"\nExpand-Archive -DestinationPath \"$OutDir\\windbg\" \"$OutDir\\UnzippedBundle\\$fileName.zip\"\n\nRemove-Item -Recurse -Force \"$OutDir\\UnzippedBundle\"\nRemove-Item -Force \"$OutDir\\windbg.appinstaller\"\nRemove-Item -Force \"$OutDir\\windbg.zip\"\n\n# Now you can run:\n& $OutDir\\windbg\\DbgX.Shell.exe\n"
  },
  {
    "path": "browserconfig.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<browserconfig>\n    <msapplication>\n        <tile>\n            <square150x150logo src=\"/mstile-150x150.png\"/>\n            <TileColor>#da532c</TileColor>\n        </tile>\n    </msapplication>\n</browserconfig>\n"
  },
  {
    "path": "guides/com-troubleshooting.md",
    "content": "---\r\nlayout: page\r\ntitle: COM troubleshooting\r\ndate: 2023-04-07 08:00:00 +0200\r\nredirect_from:\r\n    - /articles/com-troubleshooting/\r\n    - /articles/com-troubleshooting\r\n---\r\n\r\n{% raw %}\r\n\r\n**Table of contents:**\r\n\r\n<!-- MarkdownTOC -->\r\n\r\n- [Quick introduction to COM](#quick-introduction-to-com)\r\n    - [COM metadata](#com-metadata)\r\n- [Troubleshooting COM in WinDbg](#troubleshooting-com-in-windbg)\r\n    - [Monitoring COM objects in a process](#monitoring-com-objects-in-a-process)\r\n    - [Tracing COM methods](#tracing-com-methods)\r\n    - [Stopping the COM monitor](#stopping-the-com-monitor)\r\n- [Observing COM interactions outside WinDbg](#observing-com-interactions-outside-windbg)\r\n    - [Windows Performance Recorder \\(wpr.exe\\)](#windows-performance-recorder-wprexe)\r\n    - [Process Monitor](#process-monitor)\r\n    - [wtrace](#wtrace)\r\n- [Troubleshooting .NET COM interop](#troubleshooting-net-com-interop)\r\n- [Links](#links)\r\n\r\n<!-- /MarkdownTOC -->\r\n\r\nQuick introduction to COM\r\n-------------------------\r\n\r\nIn 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:\r\n\r\n```cpp\r\nstruct __declspec(uuid(\"00000000-0000-0000-C000-000000000046\"))) IUnknown\r\n{\r\npublic:\r\n    virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) = 0;\r\n    virtual ULONG STDMETHODCALLTYPE AddRef( void) = 0;\r\n    virtual ULONG STDMETHODCALLTYPE Release( void) = 0;\r\n};\r\n```\r\n\r\nGuess 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)):\r\n\r\n```cpp\r\nstruct __declspec(uuid(\"59644217-3e52-4202-ba49-f473590cc61a\")) IGameObject : public IUnknown\r\n{\r\npublic:\r\n    virtual HRESULT STDMETHODCALLTYPE get_Name(BSTR* name) = 0;\r\n    virtual HRESULT STDMETHODCALLTYPE get_Minerals(LONG* minerals) = 0;\r\n    virtual HRESULT STDMETHODCALLTYPE get_BuildTime(LONG* buildtime) = 0;\r\n};\r\n\r\nstruct __declspec(uuid(\"246A22D5-CF02-44B2-BF09-AAB95A34E0CF\")) IProbe : public IUnknown\r\n{\r\npublic:\r\n    virtual HRESULT STDMETHODCALLTYPE ConstructBuilding(BSTR building_name, IUnknown * *ppUnk) = 0;\r\n};\r\n\r\nclass __declspec(uuid(\"EFF8970E-C50F-45E0-9284-291CE5A6F771\")) Probe final : public IProbe, public IGameObject\r\n{ \r\n    ULONG ref_count;\r\n    /* ... implementation ....  */\r\n}\r\n```\r\n\r\nIf we instantiate (more on that later) the Probe class, its layout in the memory will look as follows:\r\n\r\n```\r\n0:000> dps 0xfb2f58 L4\r\n00fb2f58  72367744 protoss!Probe::`vftable'\r\n00fb2f5c  7236775c protoss!Probe::`vftable'\r\n00fb2f60  00000001\r\n00fb2f64  fdfdfdfd\r\n\r\n0:000> dps 72367744 L4 * IProbe interface\r\n72367744  72341bb3 protoss!ILT+2990(?QueryInterfaceProbeUAGJABU_GUIDPAPAXZ)\r\n72367748  72341ba9 protoss!ILT+2980(?AddRefProbeUAGKXZ)\r\n7236774c  723411ae protoss!ILT+425(?ReleaseProbeUAGKXZ)\r\n72367750  723414d3 protoss!ILT+1230(?ConstructBuildingProbeUAGJPA_WPAPAUIUnknownZ)\r\n\r\n0:000> dps 7236775c L6 * IGameUnit interface\r\n7236775c  72341e3d protoss!ILT+3640(?QueryInterfaceProbeW3AGJABU_GUIDPAPAXZ)\r\n72367760  723416fe protoss!ILT+1785(?AddRefProbeW3AGKXZ)\r\n72367764  72341096 protoss!ILT+145(?ReleaseProbeW3AGKXZ)\r\n72367768  723415f0 protoss!ILT+1515(?get_NameProbeUAGJPAPA_WZ)\r\n7236776c  723419d8 protoss!ILT+2515(?get_MineralsProbeUAGJPAJZ)\r\n72367770  72341e1a protoss!ILT+3605(?get_BuildTimeProbeUAGJPAJZ)\r\n```\r\n\r\nNotice 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. \r\n\r\nLet'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:\r\n\r\n```cpp\r\nHRESULT DllGetClassObject([in] REFCLSID rclsid, [in] REFIID riid, [out] LPVOID *ppv);\r\n```\r\n\r\nOn 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`.\r\n\r\nPeople 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.\r\n\r\n### COM metadata\r\n\r\nCOM 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.\r\n\r\nYou may also do some basic queries against the database with the **!cometa showc** and **!cometa showi** commands, for example:\r\n\r\n```\r\n0:000> !cometa showi {59644217-3E52-4202-BA49-F473590CC61A}\r\nFound: {59644217-3E52-4202-BA49-F473590CC61A} (IGameObject)\r\n\r\nMethods:\r\n- [0] HRESULT QueryInterface(void* this, GUID* riid, void** ppvObject)\r\n- [1] ULONG AddRef(void* this)\r\n- [2] ULONG Release(void* this)\r\n- [3] HRESULT get_Name(void* this, BSTR* Name)\r\n- [4] HRESULT get_Minerals(void* this, long* Minerals)\r\n- [5] HRESULT get_BuildTime(void* this, long* BuildTime)\r\n\r\nRegistered VTables for IID:\r\n- Module: protoss, CLSID: {EFF8970E-C50F-45E0-9284-291CE5A6F771} (Probe), VTable offset: 0x3775c\r\n- Module: protoss, CLSID: {F5353C58-CFD9-4204-8D92-D274C7578B53} (Nexus), VTable offset: 0x37710\r\n```\r\n\r\nTroubleshooting COM in WinDbg\r\n-----------------------------\r\n\r\n### Monitoring COM objects in a process\r\n\r\nThere 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:\r\n\r\n```\r\nbp 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\"\r\n```\r\n\r\nThe `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:\r\n\r\n```\r\nbp 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\"\r\n```\r\n\r\nCreating 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.\r\n\r\nAfter you attach comon to a debugged process, you should see various log messages showing COM object creations, for example:\r\n\r\n```\r\n0:000> !comon attach\r\nCOM monitor enabled for the current process.\r\n0:000> g\r\n...\r\n[comon] 0:000 [protoss!DllGetClassObject] CLSID: {EFF8970E-C50F-45E0-9284-291CE5A6F771} (Protoss Probe), IID: {00000001-0000-0000-C000-000000000046} (IClassFactory) -> SUCCESS (0x0)\r\n[comon] 0:000 [IClassFactory::CreateInstance] CLSID: {EFF8970E-C50F-45E0-9284-291CE5A6F771} (Protoss Probe), IID: {246A22D5-CF02-44B2-BF09-AAB95A34E0CF} (IProbe) -> SUCCESS (0x0)\r\n[comon] 0:000 [IUnknown::QueryInterface] CLSID: {EFF8970E-C50F-45E0-9284-291CE5A6F771} (Protoss Probe), IID: {59644217-3E52-4202-BA49-F473590CC61A} (IGameObject) -> SUCCESS (0x0)\r\n[comon] 0:000 [protoss!DllGetClassObject] CLSID: {F5353C58-CFD9-4204-8D92-D274C7578B53} (Protoss Nexus), IID: {00000001-0000-0000-C000-000000000046} (IClassFactory) -> SUCCESS (0x0)\r\n[comon] 0:000 [IClassFactory::CreateInstance] CLSID: {F5353C58-CFD9-4204-8D92-D274C7578B53} (Protoss Nexus), IID: {C5F45CBC-4439-418C-A9F9-05AC67525E43} (INexus) -> SUCCESS (0x0)\r\n[comon] 0:000 [IUnknown::QueryInterface] CLSID: {F5353C58-CFD9-4204-8D92-D274C7578B53} (Protoss Nexus), IID: {59644217-3E52-4202-BA49-F473590CC61A} (IGameObject) -> SUCCESS (0x0)\r\n...\r\n```\r\n\r\nThe `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:\r\n\r\n```\r\n0:000> !comon status\r\nCOM monitor is RUNNING\r\n\r\nCOM types recorded for the current process:\r\n\r\nCLSID: {F5353C58-CFD9-4204-8D92-D274C7578B53} (Nexus)\r\n  IID: {C5F45CBC-4439-418C-A9F9-05AC67525E43} (INexus), address: 0x723676f8\r\n  IID: {00000001-0000-0000-C000-000000000046} (N/A), address: 0x7236694c\r\n  IID: {59644217-3E52-4202-BA49-F473590CC61A} (IGameObject), address: 0x72367710\r\n\r\nCLSID: {EFF8970E-C50F-45E0-9284-291CE5A6F771} (Probe)\r\n  IID: {00000001-0000-0000-C000-000000000046} (N/A), address: 0x72366968\r\n  IID: {59644217-3E52-4202-BA49-F473590CC61A} (IGameObject), address: 0x7236775c\r\n  IID: {246A22D5-CF02-44B2-BF09-AAB95A34E0CF} (IProbe), address: 0x72367744\r\n```\r\n\r\nThe `cometa` queries show now also return information about the registered virtual tables:\r\n\r\n```\r\n0:000> !cometa showc {F5353C58-CFD9-4204-8D92-D274C7578B53}\r\nFound: {F5353C58-CFD9-4204-8D92-D274C7578B53} (Nexus)\r\n\r\nRegistered VTables for CLSID:\r\n- module: protoss, IID: {00000001-0000-0000-C000-000000000046} (N/A), VTable offset: 0x3694c\r\n- module: protoss, IID: {59644217-3E52-4202-BA49-F473590CC61A} (IGameObject), VTable offset: 0x37710\r\n- module: protoss, IID: {C5F45CBC-4439-418C-A9F9-05AC67525E43} (INexus), VTable offset: 0x376f8\r\n```\r\n\r\n### Tracing COM methods\r\n\r\nWhen 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.\r\n\r\nThe 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:\r\n\r\n```\r\n0:000> !cometa showi {59644217-3E52-4202-BA49-F473590CC61A}\r\nFound: {59644217-3E52-4202-BA49-F473590CC61A} (IGameObject)\r\n\r\nMethods:\r\n- [0] HRESULT QueryInterface(void* this, GUID* riid, void** ppvObject)\r\n- [1] ULONG AddRef(void* this)\r\n- [2] ULONG Release(void* this)\r\n- [3] HRESULT get_Name(void* this, BSTR* Name)\r\n- [4] HRESULT get_Minerals(void* this, long* Minerals)\r\n- [5] HRESULT get_BuildTime(void* this, long* BuildTime)\r\n\r\nRegistered VTables for IID:\r\n- Module: protoss, CLSID: {EFF8970E-C50F-45E0-9284-291CE5A6F771} (Probe), VTable offset: 0x3775c\r\n- Module: protoss, CLSID: {F5353C58-CFD9-4204-8D92-D274C7578B53} (Nexus), VTable offset: 0x37710\r\n```\r\n\r\nWe 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:\r\n\r\n```\r\nbp poi(protoss + 0x3775c + 4 * $ptrsize)\r\n```\r\n\r\nSimilarly, if we would like to set breakpoints on all the `IGameObject` methods, we might use a loop:\r\n\r\n```\r\n.for (r $t0 = 0; @$t0 < 6; r $t0 = @$t0 + 1) { bp poi(protoss + 0x3775c + @$t0 * @$ptrsize) }\r\n```\r\n\r\nInstead 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:\r\n\r\n```\r\n0:000> !cobp --always {EFF8970E-C50F-45E0-9284-291CE5A6F771} {59644217-3E52-4202-BA49-F473590CC61A} get_Name\r\n[comon] Breakpoint 18 (address 0x723415f0) created / updated\r\n0:000> g\r\n[comon breakpoint] IGameObject::get_Name (iid: {59644217-3E52-4202-BA49-F473590CC61A}, clsid: {EFF8970E-C50F-45E0-9284-291CE5A6F771})\r\n\r\nParameters:\r\n- this: 0xfb2f5c (void*)\r\n- Name: 0x81fc1c (BSTR*) [out]\r\n\r\n0:000> dps 0081fc1c L1\r\n0081fc1c  00000000\r\n0:000> g\r\n[comon breakpoint] IGameObject::get_Name (iid: {59644217-3E52-4202-BA49-F473590CC61A}, clsid: {EFF8970E-C50F-45E0-9284-291CE5A6F771}) return\r\nResult: 0x0 (HRESULT)\r\n\r\nOut parameters:\r\n- Name: 0x81fc1c (BSTR*)\r\n\r\n0:000> du 00f9c6ac\r\n00f9c6ac  \"Probe\"\r\n```\r\n\r\nIf 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)`.\r\n\r\n### Stopping the COM monitor\r\n\r\nRun 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.\r\n\r\nObserving COM interactions outside WinDbg\r\n-----------------------------------------\r\n\r\nSometimes 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.\r\n\r\n### Windows Performance Recorder (wpr.exe)\r\n\r\nLet'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.\r\n\r\n```shell\r\n# Collect only COM events\r\nwpr.exe -start .\\WTComTrace.wprp -filemode\r\n# Run COM apps ...\r\n# Stop the trace when done\r\nwpr -stop C:\\temp\\comtrace.etl\r\n\r\n# Collect COM events with CPU sampling\r\nwpr.exe -start CPU -start .\\WTComTrace.wprp -filemode\r\n# Run COM apps ...\r\n# Stop the trace when done\r\nwpr -stop C:\\temp\\comtrace.etl\r\n```\r\n\r\nSome 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.\r\n\r\n### Process Monitor\r\n\r\nIn **[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:\r\n\r\n![](/assets/img/procmon-filters.png)\r\n\r\nThe 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.\r\n\r\n### wtrace\r\n\r\nIn **[wtrace](https://github.com/lowleveldesign/wtrace)**, we need to pick the proper handlers and define filters. An example command line might look as follows:\r\n\r\n```shell\r\nwtrace --handlers registry,process,rpc -f 'path ~ \\CLSID\\' -f 'path ~ \\AppID\\' -f 'path ~ rpc' -f 'pname = ProtossComClient'\r\n```\r\n\r\nAs you can see, wtrace may additionally show information about RPC (Remote Procedure Call) events.\r\n\r\nTroubleshooting .NET COM interop\r\n--------------------------------\r\n\r\nA 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:\r\n\r\n```\r\n0:011> !syncblk\r\nIndex SyncBlock MonitorHeld Recursion Owning Thread Info  SyncBlock Owner\r\n-----------------------------\r\nTotal           5\r\nCCW             1\r\nRCW             0\r\nComClassFactory 0\r\nFree            3\r\n```\r\n\r\nWhen we add the **-all** parameter, **!syncblk** will list information about the created SyncBlocks with their corresponding objects, for example:\r\n\r\n```\r\n0:007> !syncblk -all\r\nIndex SyncBlock MonitorHeld Recursion Owning Thread Info  SyncBlock Owner\r\n    1 07FF8F54            0         0 00000000     none    030deb48 System.__ComObject\r\n    2 07FF8F20            0         0 00000000     none    030deb3c EventTesting\r\n    3 00000000            0         0 00000000     none           0 Free\r\n    4 00000000            0         0 00000000     none           0 Free\r\n    5 00000000            0         0 00000000     none           0 Free\r\n-----------------------------\r\nTotal           5\r\nCCW             1\r\nRCW             0\r\nComClassFactory 0\r\nFree            3\r\n```\r\n\r\nNow, we can dump information about managed objects using the **!dumpobj** command, for example:\r\n\r\n```\r\n0:006> !dumpobj 030deb3c\r\nName:        EventTesting\r\nMethodTable: 08301668\r\nEEClass:     082f7110\r\nCCW:         0833ffe0\r\nTracked Type: false\r\nSize:        12(0xc) bytes\r\nFile:        c:\\repos\\testing-com-events\\bin\\NETServer.dll\r\nFields:\r\n      MT    Field   Offset                 Type VT     Attr    Value Name\r\n0830db50  4000003        4 ...ng+OnEventHandler  0 instance 00000000 onEvent```\r\n```\r\n\r\nThe 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:\r\n\r\n```\r\n0:011> !dumpccw 08060000\r\nManaged object:    02e6cf88\r\nOuter IUnknown:    00000000\r\nRef count:         0\r\nFlags:             \r\nRefCounted Handle: 00D714F8 (WEAK)\r\nCOM interface pointers:\r\n      IP       MT Type\r\n08060010 080315b0 Server.Contract.IEventTesting\r\n```\r\n\r\nNotice 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:\r\n\r\n```\r\n0:014> !dumpccw 0a23fde0\r\nManaged object:    04ee6984\r\nOuter IUnknown:    00000000\r\nRef count:         7\r\nFlags:             \r\nRefCounted Handle: 04C716D8 (STRONG)\r\nCOM interface pointers:\r\n      IP       MT Type\r\n0A23FDF8 09fbbb04 Interop+Ole32+IOleControl\r\n0A23FDC8 09fbbc4c Interop+Ole32+IOleObject\r\n0A23FDCC 09fbbd34 Interop+Ole32+IOleInPlaceObject\r\n0A23FDD0 09fbbde4 Interop+Ole32+IOleInPlaceActiveObject\r\n0A23FDA8 09fbbfa0 Interop+Ole32+IViewObject2\r\n0A23FDB0 09fbc09c Interop+Ole32+IPersistStreamInit\r\n0A23FD4C 09f6485c BullsEyeControlLib.IBullsEye\r\n```\r\n\r\nIf you would like to dump information about all objects associated with SyncBlocks, you may use the following WinDbg script:\r\n\r\n```\r\n.foreach /pS 7 /ps 7 (addr { !syncblk -all }) { !do addr }\r\n```\r\n\r\nAnd 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):\r\n\r\n```\r\n0:014> .load PDE.dll\r\n0:014> !grep RCW: .foreach /pS 7 /ps 7 (addr { !syncblk -all }) { !do addr }\r\nRCW:         08086d30\r\n0:014> !grep CCW: .foreach /pS 7 /ps 7 (addr { !syncblk -all }) { !do addr }\r\nCCW:         08060000\r\n```\r\n\r\nTo 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:\r\n\r\n```\r\n0:011> !gchandles -type refcounted\r\n  Handle Type          Object     Size     Data Type\r\n00D714F8 RefCounted  02e6cf88       12        0 EventTesting\r\n\r\nStatistics:\r\n      MT    Count    TotalSize Class Name\r\n08031668        1           12 EventTesting\r\nTotal 1 objects\r\n\r\n0:014> !gchandles -type strong\r\n  Handle Type          Object     Size     Data Type\r\n04C711B4 Strong      030deb48       12          System.__ComObject\r\n...\r\n\r\nStatistics:\r\n      MT    Count    TotalSize Class Name\r\n04ebbf00        1           12 System.__ComObject\r\n...\r\nTotal 19 objects\r\n```\r\n\r\nOf 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.\r\n\r\nFinally, 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:\r\n\r\n```\r\n.foreach (addr { !DumpHeap -short -type System.__ComObject }) { !gcroot addr }\r\n```\r\n\r\nLinks\r\n-----\r\n\r\n- [\"Essential COM\"](https://archive.org/details/essentialcom00boxd) by Don Box\r\n- [\"Inside OLE\"](https://github.com/kraigb/InsideOLE) by Kraig Brockschmidt (Kraig published the whole book with source code on GitHub!)\r\n- [\"Inside COM+ Base Services\"](https://thrysoee.dk/InsideCOM+/) by Guy Eddon and Henry Eddon\r\n- [\"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\r\n- [\".NET and COM: The Complete Interoperability Guide\"](https://books.google.pl/books/about/NET_and_COM.html?id=x2OIPSyFLBcC) by Adam Nathan\r\n- [COM+ revisited](https://lowleveldesign.wordpress.com/2022/01/17/com-revisited/) by me :)\r\n- [Calling Local Windows RPC Servers from .NET](https://googleprojectzero.blogspot.com/2019/12/calling-local-windows-rpc-servers-from.html) by James Forshaw\r\n\r\n{% endraw %}"
  },
  {
    "path": "guides/configuring-linux-for-effective-troubleshooting.md",
    "content": "---\r\nlayout: page\r\ntitle: Configuring Linux for effective troubleshooting\r\ndate: 2025-12-26 08:00:00 +0200\r\n---\r\n\r\n**Table of contents:**\r\n\r\n<!-- MarkdownTOC -->\r\n\r\n- [Configuring debug symbols](#configuring-debug-symbols)\r\n\r\n<!-- /MarkdownTOC -->\r\n\r\nConfiguring debug symbols\r\n-------------------------\r\n\r\nThese 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).\r\n\r\nIf 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`):\r\n\r\n```\r\nDefaults env_keep += \"DEBUGINFOD_URLS\"\r\n```\r\n"
  },
  {
    "path": "guides/configuring-windows-for-effective-troubleshooting.md",
    "content": "---\r\nlayout: page\r\ntitle: Configuring Windows for effective troubleshooting\r\ndate: 2023-10-11 08:00:00 +0200\r\n---\r\n\r\n**Table of contents:**\r\n\r\n<!-- MarkdownTOC -->\r\n\r\n- [Configuring debug symbols](#configuring-debug-symbols)\r\n- [Replacing Task Manager with System Informer](#replacing-task-manager-with-system-informer)\r\n- [Installing and configuring Sysinternals Suite](#installing-and-configuring-sysinternals-suite)\r\n- [Configuring post-mortem debugging](#configuring-post-mortem-debugging)\r\n\r\n<!-- /MarkdownTOC -->\r\n\r\n## Configuring debug symbols\r\n\r\nStaring 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).\r\n\r\nThe 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.\r\n\r\n## Replacing Task Manager with System Informer\r\n\r\nMy 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.\r\n\r\nIf 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.\r\n\r\n## Installing and configuring Sysinternals Suite\r\n\r\n[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).\r\n\r\nTo 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):\r\n\r\n```\r\n[HKEY_CURRENT_USER\\Software\\Sysinternals\\Process Explorer]\r\n\"DbgHelpPath\"=\"C:\\\\Program Files (x86)\\\\Windows Kits\\\\10\\\\Debuggers\\\\x64\\\\dbghelp.dll\"\r\n\"SymbolPath\"=\"SRV*C:\\\\symbols\\\\dbg*http://msdl.microsoft.com/download/symbols\"\r\n\r\n[HKEY_CURRENT_USER\\Software\\Sysinternals\\Process Monitor]\r\n\"DbgHelpPath\"=\"C:\\\\Program Files (x86)\\\\Windows Kits\\\\10\\\\Debuggers\\\\x64\\\\dbghelp.dll\"\r\n\"SymbolPath\"=\"SRV*C:\\\\symbols\\\\dbg*http://msdl.microsoft.com/download/symbols\"\r\n```\r\n\r\n## Configuring post-mortem debugging\r\n\r\nWe 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:\r\n\r\n```shell\r\nreg.exe add \"HKLM\\Software\\Microsoft\\Windows\\Windows Error Reporting\\LocalDumps\" /v DumpType /t REG_DWORD /d 1 /f\r\nreg.exe add \"HKLM\\Software\\Microsoft\\Windows\\Windows Error Reporting\\LocalDumps\" /v DumpFolder /t REG_EXPAND_SZ /d C:\\dumps /f\r\n```\r\n\r\nThe 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.\r\n\r\n[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):\r\n\r\n```shell\r\nprocdump -i C:\\Dumps\r\n```\r\n\r\nThese 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.\r\n"
  },
  {
    "path": "guides/diagnosing-dotnet-apps.md",
    "content": "---\nlayout: page\ntitle: Diagnosing .NET applications\ndate: 2024-01-01 08:00:00 +0200\n---\n\n{% raw %}\n\n: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:\n\n**Table of contents:**\n\n<!-- MarkdownTOC -->\n\n- [General .NET debugging tips](#general-net-debugging-tips)\n    - [Loading the SOS extension into WinDbg](#loading-the-sos-extension-into-windbg)\n    - [Manually loading symbol files for .NET Core](#manually-loading-symbol-files-for-net-core)\n    - [Disabling JIT optimization](#disabling-jit-optimization)\n    - [Decoding managed stacks in Sysinternals](#decoding-managed-stacks-in-sysinternals)\n    - [Check runtime version](#check-runtime-version)\n    - [Debugging/tracing a containerized .NET application \\(Docker\\)](#debuggingtracing-a-containerized-net-application-docker)\n- [Diagnosing exceptions or erroneous behavior](#diagnosing-exceptions-or-erroneous-behavior)\n    - [Using Time Travel Debugging \\(TTD\\)](#using-time-travel-debugging-ttd)\n    - [Collecting a memory dump](#collecting-a-memory-dump)\n    - [Analysing exception information](#analysing-exception-information)\n- [Diagnosing hangs](#diagnosing-hangs)\n    - [Listing threads call stacks](#listing-threads-call-stacks)\n    - [Finding locks in managed code](#finding-locks-in-managed-code)\n- [Diagnosing waits or high CPU usage](#diagnosing-waits-or-high-cpu-usage)\n- [Diagnosing managed memory leaks](#diagnosing-managed-memory-leaks)\n    - [Collecting memory snapshots](#collecting-memory-snapshots)\n    - [Analyzing collected snapshots](#analyzing-collected-snapshots)\n- [Diagnosing issues with assembly loading](#diagnosing-issues-with-assembly-loading)\n    - [Troubleshooting loading with EventPipes/ETW \\(.NET\\)](#troubleshooting-loading-with-eventpipesetw-net)\n    - [Troubleshooting loading using ETW \\(.NET Framework\\)](#troubleshooting-loading-using-etw-net-framework)\n    - [Troubleshooting loading using Fusion log \\(.NET Framework\\)](#troubleshooting-loading-using-fusion-log-net-framework)\n    - [GAC \\(.NET Framework\\)](#gac-net-framework)\n        - [Find assembly in cache](#find-assembly-in-cache)\n        - [Uninstall assembly from cache](#uninstall-assembly-from-cache)\n- [Diagnosing network connectivity issues](#diagnosing-network-connectivity-issues)\n    - [.NET Core](#net-core)\n    - [.NET Framework](#net-framework)\n- [ASP.NET Core](#aspnet-core)\n    - [Collecting ASP.NET Core logs](#collecting-aspnet-core-logs)\n        - [ILogger logs](#ilogger-logs)\n        - [DiagnosticSource logs](#diagnosticsource-logs)\n    - [Collecting ASP.NET Core performance counters](#collecting-aspnet-core-performance-counters)\n- [ASP.NET \\(.NET Framework\\)](#aspnet-net-framework)\n    - [Examining ASP.NET process memory \\(and dumps\\)](#examining-aspnet-process-memory-and-dumps)\n    - [Profiling ASP.NET](#profiling-aspnet)\n    - [Application instrumentation](#application-instrumentation)\n    - [ASP.NET ETW providers](#aspnet-etw-providers)\n    - [Collect events using the Perfecto tool](#collect-events-using-the-perfecto-tool)\n    - [Collect events using FREB](#collect-events-using-freb)\n\n<!-- /MarkdownTOC -->\n\n## General .NET debugging tips\n\n### Loading the SOS extension into WinDbg\n\nWhen 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:\n\n```\n.loadby sos mscorwks (.NET 2.0/3.5)\n.loadby sos clr      (.NET 4.0+)\n```\n\nFor **.NET Core**, you need to download and install the **dotnet-sos** tool. The install command informs how to load SOS into WinDbg, for example:\n\n```\n> dotnet tool install -g dotnet-sos\n...\n> dotnet sos install\n...\nExecute '.load C:\\Users\\me\\.dotnet\\sos\\sos.dll' to load SOS in your Windows debugger.\nCleaning up...\nSOS install succeeded\n```\n\nSOS commands sometimes get overriden by other extensions help files. In such case, use **!sos.help \\[cmd\\]** command, for example, `!sos.help !savemodule`.\n\n### Manually loading symbol files for .NET Core\n\nI 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`):\n\n```\ndotnet-symbol --recurse-subdirectories --cache-directory c:\\symbols\\dbg -o C:\\temp\\toremove \"C:\\Program Files\\dotnet\\shared\\Microsoft.NETCore.App\\3.0.0\\*\"\n```\n\nWe 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.\n\n### Disabling JIT optimization\n\nFor **.NET Core**, set the **COMPlus_JITMinOptsx** environment variable:\n\n```\nexport COMPlus_JITMinOpts=1\n```\n\nFor **.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.\n\n```\n[.NET Framework Debugging Control]\nGenerateTrackingInfo=1\nAllowOptimize=0\n```\n\n### Decoding managed stacks in Sysinternals\n\nAs 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.\n\n**Process Monitor**, unfortunately, lacks this feature. Pure managed modules will appear as `<unknown>` 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.\n\n### Check runtime version\n\nFor .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).\n\nIn .NET Core, we could run **dotnet --list-runtimes** command to list the available runtimes.\n\n### Debugging/tracing a containerized .NET application (Docker)\n\nWith 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:\n\n```\nFROM mcr.microsoft.com/dotnet/sdk:5.0 AS base\n\nRUN apt-get update && apt-get install -y lldb; \\\n    dotnet tool install -g dotnet-symbol; \\\n    dotnet tool install -g dotnet-sos; \\\n    /root/.dotnet/tools/dotnet-sos install\n\nRUN dotnet tool install -g dotnet-counters; \\\n  dotnet tool install -g dotnet-trace; \\\n  dotnet tool install -g dotnet-dump; \\\n  dotnet tool install -g dotnet-gcdump; \\\n  echo 'export PATH=\"$PATH:/root/.dotnet/tools\"' >> /root/.bashrc\n\nENTRYPOINT [\"/bin/bash\"]\n```\n\nYou may use it to create a .NET diagnostics Docker image, for example:\n\n```\n$ docker build -t netdiag -f .\\Dockerfile.netdiag .\n```\n\nThen, create a `/tmp` volume and mount it into your .NET application container, for example:\n\n```\n$ docker volume create dotnet-tmp\n\n$ docker run --rm --name helloserver --mount \"source=dotnet-tmp,target=/tmp\" -p 13000:13000 helloserver 13000\n```\n\nAnd you are ready to run the diagnostics container and diagnose the remote application:\n\n```\n$ docker run --rm -it --mount \"source=dotnet-tmp,target=/tmp\" --pid=container:helloserver netdiag\n\nroot@d4bfaa3a9322:/# dotnet-trace ps\n         1 dotnet     /usr/share/dotnet/dotnet \n```\n\nIf you only want to trace the application with **dotnet-trace**, consider using a shorter Dockerfile.nettrace file:\n\n```\nFROM mcr.microsoft.com/dotnet/sdk:5.0 AS base\n\nRUN dotnet tool install -g dotnet-trace\n\nENTRYPOINT [\"/root/.dotnet/tools/dotnet-trace\", \"collect\", \"-n\", \"dotnet\", \"-o\", \"/work/trace.nettrace\", \"@/work/input.rsp\"]\n```\n\nwhere input.rsp:\n\n```\n--providers Microsoft-Windows-DotNETRuntime:0x14C14FCCBD:4,Microsoft-DotNETCore-SampleProfiler:0xF00000000000:4\n```\n\nThe 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:\n\n```\n$ docker build -t nettrace -f .\\Dockerfile.nettrace .\n\n$ docker run --rm --pid=container:helloserver --mount \"source=dotnet-tmp,target=/tmp\" -v \"$pwd/:/work\" -it nettrace\n\nProvider Name                           Keywords            Level               Enabled By\nMicrosoft-Windows-DotNETRuntime         0x00000014C14FCCBD  Informational(4)    --providers\nMicrosoft-DotNETCore-SampleProfiler     0x0000F00000000000  Informational(4)    --providers\n\nProcess        : /usr/share/dotnet/dotnet\nOutput File    : /work/trace.nettrace\n[00:00:00:02]   Recording trace 261.502  (KB)\nPress <Enter> or <Ctrl+C> to exit...11   (KB)\nStopping the trace. This may take up to minutes depending on the application being traced.\n```\n\n## Diagnosing exceptions or erroneous behavior\n\n### Using Time Travel Debugging (TTD)\n\nTime 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.\n\n### Collecting a memory dump\n\n**[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`.\n\nTo create a full memory dump, run one of the commands:\n\n```\ndotnet-dump collect -p <process-id>\ndotnet-dump collect -n <process-name>\n```\n\nYou may create a heap-only memory dump by adding the **--type=Heap** option.\n\nCreatedump 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`.\n\nTo 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}**.\n\nThe .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:\n\n```shell\n# enable a memory dump creation on crash\nset DOTNET_DbgEnableMiniDump=1\n# when crashing, create a heap (2) memory dump, (4) for full memory dump\nset DOTNET_DbgMiniDumpType=2\n```\n\nApart 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.\n\n### Analysing exception information\n\nFirst make sure with the **!Threads** command (SOS) that your current thread is the one with the exception context:\n\n```\n0:000> !Threads\nThreadCount:      2\nUnstartedThread:  0\nBackgroundThread: 1\nPendingThread:    0\nDeadThread:       0\nHosted Runtime:   no\n\nID OSID ThreadOBJ           State GC Mode     GC Alloc Context                  Domain           Count Apt Exception\n0    1 1ec8 000000000055adf0    2a020 Preemptive  0000000002253560:0000000002253FD0 00000000004fb970 0     Ukn System.ArgumentException 0000000002253438\n5    2 1c74 00000000005851a0    2b220 Preemptive  0000000000000000:0000000000000000 00000000004fb970 0     Ukn (Finalizer)\n```\n\nIn 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:\n\n```\n0:000> !pe\nException object: 0000000002253438\nException type:   System.ArgumentException\nMessage:          v should not be null\nInnerException:   <none>\nStackTrace (generated):\n<none>\nStackTraceString: <none>\nHResult: 80070057\n```\n\nTo 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.\n\n## Diagnosing hangs\n\nWe 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.\n\n### Listing threads call stacks\n\nTo 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:\n\n```\n> dotnet dump analyze test.dmp\n> pstacks\n________________________________________________\n    ~~~~ 5cd8\n       1 System.Threading.Monitor.Enter(Object, Boolean ByRef)\n       1 deadlock.Program.Lock2()\n    ~~~~ 3e58\n       1 System.Threading.Monitor.Enter(Object, Boolean ByRef)\n       1 deadlock.Program.Lock1()\n  2 System.Threading.Tasks.Task.InnerInvoke()\n  ...\n  2 System.Threading.ThreadPoolWorkQueue.Dispatch()\n  2 System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()\n```\n\nIn **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.\n\n### Finding locks in managed code\n\nYou may examine thin locks using **!DumpHeap -thinlocks**.  To find all sync blocks, use the **!SyncBlk -all** command.\n\nOn .NET Framework, you may also use the **!dlk** command from the SOSEX extension. It is pretty good in detecting deadlocks, for example:\n\n```\n0:007> .load sosex\n0:007> !dlk\nExamining SyncBlocks...\nScanning for ReaderWriterLock(Slim) instances...\nScanning for holders of ReaderWriterLock locks...\nScanning for holders of ReaderWriterLockSlim locks...\nExamining CriticalSections...\nScanning for threads waiting on SyncBlocks...\nScanning for threads waiting on ReaderWriterLock locks...\nScanning for threads waiting on ReaderWriterLocksSlim locks...\n*** WARNING: Unable to verify checksum for C:\\WINDOWS\\assembly\\NativeImages_v4.0.30319_32\\System\\3a4f0a84904c4b568b6621b30306261c\\System.ni.dll\n*** WARNING: Unable to verify checksum for C:\\WINDOWS\\assembly\\NativeImages_v4.0.30319_32\\System.Transactions\\ebef418f08844f99287024d1790a62a4\\System.Transactions.ni.dll\nScanning for threads waiting on CriticalSections...\n*DEADLOCK DETECTED*\nCLR thread 0x1 holds the lock on SyncBlock 011e59b0 OBJ:02e93410[System.Object]\n...and is waiting on CriticalSection 01216a58\nCLR thread 0x3 holds CriticalSection 01216a58\n...and is waiting for the lock on SyncBlock 011e59b0 OBJ:02e93410[System.Object]\nCLR Thread 0x1 is waiting at clr!CrstBase::SpinEnter+0x92\nCLR Thread 0x3 is waiting at System.Threading.Monitor.Enter(System.Object, Boolean ByRef)(+0x17 Native)\n```\n\nWhen 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.\n\n```\n0:036> !Name2EE mscorlib.dll System.Threading.Thread\nModule:      72551000\nAssembly:    mscorlib.dll\nToken:       020001d1\nMethodTable: 72954960\nEEClass:     725bc0c4\nName:        System.Threading.Thread\n```\n\nAnd then paste it in the scripts below:\n\nx86 version:\n\n```\n.foreach ($addr {!DumpHeap -short -mt <METHODTABLE> }) { .printf /D \"Thread: %i; Execution context: <link cmd=\\\"!do %p\\\">%p</link>\\n\", poi(${$addr}+28), poi(${$addr}+8), poi(${$addr}+8) }\n```\n\nx64 version:\n\n```\n.foreach ($addr {!DumpHeap -short -mt <METHODTABLE> }) { .printf /D \"Thread: %i; Execution context: <link cmd=\\\"!do %p\\\">%p</link>\\n\", poi(${$addr}+4c), poi(${$addr}+10), poi(${$addr}+10) }\n```\n\nNotice 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.\n\n## Diagnosing waits or high CPU usage\n\nDotnet-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.\n\nSample collect examples:\n\n```bash\ndotnet-trace collect --profile cpu-sampling -p 12345\ndotnet-trace collect --profile cpu-sampling -- myapp.exe\n```\n\nDotnet-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:\n\n```bash\ndotnet-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\n```\n\nFor 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.\n\nOn 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.\n\nTo 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:\n\n```bash\nperfcollect view sqrt.trace.zip -graphtype caller\n```\n\nUsing the **-graphtype** option, we may switch from the top-down view (`caller`) to the bottom-up view (`callee`).\n\n## Diagnosing managed memory leaks\n\n### Collecting memory snapshots\n\nIf we are interested only in GC Heaps, we may create the GC Heap snapshot using **PerfView**:\n\n    perfview heapsnapshot <pid|name>\n\nIn GUI, we may use the menu option: **Memory -&gt; Take Heap Snapshot**.\n\nFor .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:\n\n```\ndotnet-gcdump -p <process-id>\ndotnet-gcdump -n <process-name>\n```\n\nSometimes 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). \n\n### Analyzing collected snapshots\n\n**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 -&gt; Take Heap Snapshot from Dump**.\n\nI 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:\n\n- first named LeakingProcess.gcdump\n- second (taken a minute later) named LeakingProcess.1.gcdump\n\nYou 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:\n\n![diff option under the menu](/assets/img/perfview-snapshots-diff.png)\n\nAfter 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!\n\n**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.\n\nOther SOS commands for analyzing the managed heap include:\n\n```\n!EEHeap [-gc] [-loader]\n!HeapStat [-inclUnrooted | -iu]\n\n!DumpHeap [-stat]\n          [-strings]\n          [-short]\n          [-min <size>]\n          [-max <size>]\n          [-live]\n          [-dead]\n          [-thinlock]\n          [-startAtLowerBound]\n          [-mt <MethodTable address>]\n          [-type <partial type name>]\n          [start [end]]\n\n!ObjSize [<Object address>]\n!GCRoot [-nostacks] <Object address>\n!DumpObject <address> | !DumpArray <address> | !DumpVC <mt> <address>\n```\n\n**dotnet-gcdump** has a **report** command that lists the objects recorded in the GC heaps. The output resembles output from the SOS `!dumpheap` command.\n\n## Diagnosing issues with assembly loading\n\n### Troubleshooting loading with EventPipes/ETW (.NET)\n\nThe **Loader** keyword (`0x8`) in the **Microsoft-Windows-DotNETRuntime** provider enables events relating to **loading and unloading** of **appdomains**, **assemblies** and **modules**.\n\nStarting with **.NET 5**, the new **AssemblyLoader** keyword (`0x4`) gives us a detailed view of the **assembly resolution process**. Additionally, we can group the activity events per assembly using the `ActivityID`.\n\n    dotnet-trace collect --providers Microsoft-Windows-DotNETRuntime:C -- testapp.exe\n\n### Troubleshooting loading using ETW (.NET Framework)\n\nThere is a number of ETW events defined under the **Microsoft-Windows-DotNETRuntimePrivate/Binding/** category. We may use, for example, **PerfView** to collect them. Just make sure that you have the .NET check box selected in the collection dialog. Start collection and stop it after the loading exception occurs. Then open the .etl file, go to the **Events** screen and filter them by *binding*. Select all of the events and press ENTER. PerfView will immediately print the instances of the selected events in the grid on the right. You may later search or filter the grid with the help of the search boxes above it.\n\n### Troubleshooting loading using Fusion log (.NET Framework)\n\nFusion log is available in all versions of the .NET Framework. There is a tool named **fuslogvw** in .NET SDK, which you may use to set the Fusion log configuration. Andreas Wäscher implemented an easier-to-use version of this tool, with a modern UI, named [Fusion++](https://github.com/awaescher/Fusion). You may download the precompiled version from the [release page](https://github.com/awaescher/Fusion/releases/).\n\nIf using neither of the above tools is possible (for example, you are in a restricted environment), you may configure the Fusion log through **registry settings**. The root of all the Fusion log settings is **HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Fusion**.\n\nWhen writing to a folder on a hard drive fusion logs are split among categories and processes, e.g.:\n\n```\nC:\\TEMP\\FUSLOGVW\n├───Default\n│   └───powershell.exe\n└───NativeImage\n    └───powershell.exe\n```\n\nLog to exception text:\n\n    HKEY_LOCAL_MACHINE\\software\\microsoft\\fusion\n        EnableLog    REG_DWORD    0x1\n\nor\n\n    reg delete HKLM\\Software\\Microsoft\\Fusion /va\n    reg add HKLM\\Software\\Microsoft\\Fusion /v EnableLog /t REG_DWORD /d 0x1\n\nLog failures to disk:\n\n    HKEY_LOCAL_MACHINE\\software\\microsoft\\fusion\n        LogFailures    REG_DWORD    0x1\n        LogPath    REG_SZ    c:\\logs\\fuslogvw\n\nor\n\n    reg delete HKLM\\Software\\Microsoft\\Fusion /va\n    reg add HKLM\\Software\\Microsoft\\Fusion /v LogFailures /t REG_DWORD /d 0x1\n    reg add HKLM\\Software\\Microsoft\\Fusion /v LogPath /t REG_SZ /d \"C:\\logs\\fuslogvw\"\n\nLog all binds to disk\n\n    HKEY_LOCAL_MACHINE\\software\\microsoft\\fusion\n        LogPath    REG_SZ    c:\\logs\\fuslogvw\n        ForceLog    REG_DWORD    0x1\n\nor\n\n    reg delete HKLM\\Software\\Microsoft\\Fusion /va\n    reg add HKLM\\Software\\Microsoft\\Fusion /v ForceLog /t REG_DWORD /d 0x1\n    reg add HKLM\\Software\\Microsoft\\Fusion /v LogPath /t REG_SZ /d \"C:\\logs\\fuslogvw\"\n\nLog disabled\n\n    HKEY_LOCAL_MACHINE\\software\\microsoft\\fusion\n        LogPath    REG_SZ    c:\\logs\\fuslogvw\n\nor\n\n    reg delete HKLM\\Software\\Microsoft\\Fusion /va\n\n### GAC (.NET Framework)\n\nFor .NET2.0/3.5 Global Assembly Cache was located in **c:\\Windows\\assembly** folder with a drag/drop option for installing/uninstalling assemblies. Citing [a stackoverflow answer](http://stackoverflow.com/questions/10013047/gacutil-vs-manually-editing-c-windows-assembly):\n\n> This functionality is provided by a custom shell extension, shfusion.dll. It flattens the GAC and makes it look like a single folder. And takes care of automatically un/registering the assemblies for you when you manipulate the explorer window. So you’re fine doing this.\n\nTo **disable GAC viewer in Windows Explorer**, add a DWORD value **DisableCacheViewer** set to 1 under the **HKLM\\Software\\Microsoft\\Fusion** key.\n\nNote that this will no longer work for .NET 4, it uses in a different folder to store GAC files (**c:\\windows\\microsoft.net\\assembly**) and that folder does not have the same kind of shell extension. Thus, you can see the raw content of it. However, you should not directly use it.\n\nIt is best to use **gacutil** to manipulate GAC content. Though it’s possible to install assembly in both GAC folders as stated [here](http://stackoverflow.com/questions/7095887/registering-the-same-version-of-an-assembly-but-with-different-target-frameworks), but I would not consider it a good practice as framework tools can’t deal with it. .NET GAC settings are stored under the registry key: HKLM\\Software\\Microsoft\\Fusion.\n\n#### Find assembly in cache\n\nWe can use the **gacutil /l** to find an assembly in GAC. If no name is provided, the command lists all the assemblies in cache.\n\n    gacutil /l System.Core\n\n    The Global Assembly Cache contains the following assemblies:\n      System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL\n      System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL\n\n    Number of items = 2\n\n#### Uninstall assembly from cache\n\n    gacutil /u MyTest.exe\n\n## Diagnosing network connectivity issues\n\n### .NET Core\n\n.NET Core provides a number of ETW and EventPipes providers to collect the network tracing events. Enabling the providers could be done in **dotnet-trace**, **PerfView**, or **dotnet-wtrace**. Network ETW providers use only two keywords (`Default = 0x1` and `Debug = 0x2`) and, as usual, we may filter the events by the log level (from 1 (critical) to 5 (verbose)).\n\nIn **.NET 5**, the providers were renamed and currently we can use the following names:\n\n- `Private.InternalDiagnostics.System.Net.Primitives` - cookie container, cache credentials logs\n- `Private.InternalDiagnostics.System.Net.Sockets` - logs describing operations on sockets, connection status events, \n- `Private.InternalDiagnostics.System.Net.NameResolution`\n- `Private.InternalDiagnostics.System.Net.Mail`\n- `Private.InternalDiagnostics.System.Net.Requests` - logs from System.Net.Requests classes\n- `Private.InternalDiagnostics.System.Net.HttpListener`\n- `Private.InternalDiagnostics.System.Net.WinHttpHandler`\n- `Private.InternalDiagnostics.System.Net.Http` - HttpClient and HTTP handler logs, authentication events\n- `Private.InternalDiagnostics.System.Net.Security` - SecureChannel (TLS) events, Windows SSPI logs\n\nFor previous .NET Core versions, the names were as follows:\n\n- `Microsoft-System-Net-Primitives`\n- `Microsoft-System-Net-Sockets`\n- `Microsoft-System-Net-NameResolution`\n- `Microsoft-System-Net-Mail`\n- `Microsoft-System-Net-Requests`\n- `Microsoft-System-Net-HttpListener`\n- `Microsoft-System-Net-WinHttpHandler`\n- `Microsoft-System-Net-Http`\n- `Microsoft-System-Net-Security`\n\nWe may create a network.rsp file that enables all these event sources and the Kestrel one. You may use it with **dotnet-trace**, for example:\n\n```\n$ dotnet-trace collect -n dotnet @network.rsp\n```\n\nThe network.rsp file for older .NET Core (before .NET 5) might look as follows:\n\n```\n--providers Microsoft-System-Net-Primitives,Microsoft-System-Net-Sockets,Microsoft-System-Net-NameResolution,Microsoft-System-Net-Mail,Microsoft-System-Net-Requests,Microsoft-System-Net-HttpListener,Microsoft-System-Net-WinHttpHandler,Microsoft-System-Net-Http,Microsoft-System-Net-Security,Microsoft-AspNetCore-Server-Kestrel\n```\n\nFor .NET 5 and newer:\n\n```\n--providers\nPrivate.InternalDiagnostics.System.Net.Primitives,Private.InternalDiagnostics.System.Net.Sockets,Private.InternalDiagnostics.System.Net.NameResolution,Private.InternalDiagnostics.System.Net.Mail,Private.InternalDiagnostics.System.Net.Requests,Private.InternalDiagnostics.System.Net.HttpListener,Private.InternalDiagnostics.System.Net.WinHttpHandler,Private.InternalDiagnostics.System.Net.Http,Private.InternalDiagnostics.System.Net.Security,Microsoft-AspNetCore-Server-Kestrel\n```\n\nI also developed [**dotnet-wtrace**](https://github.com/lowleveldesign/dotnet-wtrace), a lightweight traces that makes it straightfoward to live collect .NET events, including network traces.\n\n### .NET Framework\n\nAll classes from `System.Net`, if configured properly, may provide a lot of interesting logs through the default System.Diagnostics mechanisms. The list of the available trace sources is available in [Microsoft docs](https://docs.microsoft.com/en-us/dotnet/framework/network-programming/how-to-configure-network-tracing).\n\nThis is a configuration sample which writes network traces to a file:\n\n```xml\n<system.diagnostics>\n    <trace autoflush=\"true\" />\n    <sharedListeners>\n      <add name=\"file\" initializeData=\"C:\\logs\\network.log\" type=\"System.Diagnostics.TextWriterTraceListener\" />\n    </sharedListeners>\n    <sources>\n      <source name=\"System.Net\" switchValue=\"Verbose\" tracemode=\"includehex\" maxdatasize=\"512\">\n        <listeners>\n          <add name=\"file\" />\n        </listeners>\n      </source>\n      <source name=\"System.Net.Http\" switchValue=\"Verbose\">\n        <listeners>\n          <add name=\"file\" />\n        </listeners>\n      </source>\n      <source name=\"System.Net.HttpListener\" switchValue=\"Verbose\">\n        <listeners>\n          <add name=\"file\" />\n        </listeners>\n      </source>\n      <source name=\"System.Net.Sockets\" switchValue=\"Verbose\">\n        <listeners>\n          <add name=\"file\" />\n        </listeners>\n      </source>\n    </sources>\n</system.diagnostics>\n```\n\nThese logs may be verbose and numerous, therefore, I suggest starting with Information level and smaller number of sources. You may also consider using **EventProviderTraceListener** to make the trace writes faster and less impactful. An example configuration file with those changes:\n\n```xml\n<system.diagnostics>\n    <trace autoflush=\"true\" />\n    <sharedListeners>\n      <add name=\"etw\" initializeData=\"{0f09a664-1713-4665-91e8-8d6b8baee030}\" type=\"System.Diagnostics.Eventing.EventProviderTraceListener, System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" />\n    </sharedListeners>\n    <sources>\n      <source name=\"System.Net\" switchValue=\"Information\">\n        <listeners>\n          <add name=\"etw\" />\n        </listeners>\n      </source>\n      <source name=\"System.Net.Http\" switchValue=\"Information\">\n        <listeners>\n          <add name=\"etw\"/>\n        </listeners>\n      </source>\n      <source name=\"System.Net.HttpListener\" switchValue=\"Information\">\n        <listeners>\n          <add name=\"etw\"/>\n        </listeners>\n      </source>\n    </sources>\n</system.diagnostics>\n```\n\nAnd to collect such a trace:\n\n```shell\nlogman start \"net-trace-session\" -p \"{0f09a664-1713-4665-91e8-8d6b8baee030}\" -bs 512 -nb 8 64 -o \"c:\\temp\\net-trace.etl\" -ets & pause & logman stop net-trace-session -ets\n```\n\n## ASP.NET Core\n\n### Collecting ASP.NET Core logs\n\nFor low-level network traces, you may enable .NET network providers, as described in the previous section. ASP.NET Core framework logs events either through **DiagnosticSource** using **Microsoft.AspNetCore** as the source name or through the **ILogger** interface.\n\n#### ILogger logs\n\nThe CreateDefaultBuilder method adds LoggingEventSource (named **Microsoft-Extensions-Logging**) as one of the log outputs. The **FilterSpecs** argument makes it possible to filter the events by logger name and level, for example:\n\n```\nMicrosoft-Extensions-Logging:5:5:FilterSpecs=webapp.Pages.IndexModel:0\n```\n\nWe may define the log message format with keywords (pick one):\n\n- 0x1 - enable meta events\n- 0x2 - enable events with raw arguments\n- 0x4 - enable events with formatted message (the most readable)\n- 0x8 - enable events with data seriazlied to JSON\n\nFor example, to collect ILogger info messages: `dotnet-trace collect -p PID --providers \"Microsoft-Extensions-Logging:0x4:0x4\"`\n\n#### DiagnosticSource logs \n\nTo listen to **DiagnosticSource events**, we should enable the **Microsoft-Diagnostics-DiagnosticSource** event source. DiagnosticSource events often contain complex types and we need to use [parser specifications](https://github.com/dotnet/runtime/blob/main/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs) to extract the interesting properties.\n\nThe **Microsoft-Diagnostics-DiagnosticSourcex** event source some special keywords:\n\n- 0x1 - enable diagnostic messages\n- 0x2 - enable regular events\n- 0x0800 - disable the shortcuts keywords, listed below\n- 0x1000 - enable activity tracking and basic hosting events (ASP.NET Core)\n- 0x2000 - enable activity tracking and basic command events (EF Core)\n\nAlso, we should enable the minimal logging from the **System.Threading.Tasks.TplEventSource** provider to profit from the [activity tracking](https://docs.microsoft.com/en-us/archive/blogs/vancem/exploring-eventsource-activity-correlation-and-causation-features).\n\nWhen our application is hosted on the Kestrel server, we may enable the **Microsoft-AspNetCore-Server-Kestrel** provider to get Kestrel events.\n\nAn example command that enables all ASP.NET Core event traces and some other useful network event providers. It also adds activity tracking for **HttpClient** requests:\n\n```\n> dotnet-trace collect --providers \"Private.InternalDiagnostics.System.Net.Security,Private.InternalDiagnostics.System.Net.Sockets,Microsoft-AspNetCore-Server-Kestrel,Microsoft-Diagnostics-DiagnosticSource:0x1003:5:FilterAndPayloadSpecs=\\\"Microsoft.AspNetCore\\nHttpHandlerDiagnosticListener\\nHttpHandlerDiagnosticListener/System.Net.Http.Request@Activity2Start:Request.RequestUri\\nHttpHandlerDiagnosticListener/System.Net.Http.Response@Activity2Stop:Response.StatusCode\\\",System.Threading.Tasks.TplEventSource:0x80:4,Microsoft-Extensions-Logging:4:5\" -n webapp\n```\n\n### Collecting ASP.NET Core performance counters\n\nASP.NET Core provides some basic performance counters through the **Microsoft.AspNetCore.Hosting** event source. If we are also using Kestrel, we may add some interesting counters by enabling **Microsoft-AspNetCore-Server-Kestrel**:\n\n```\n> dotnet-counters monitor \"Microsoft.AspNetCore.Hosting\" \"Microsoft-AspNetCore-Server-Kestrel\" -n testapp\n\nPress p to pause, r to resume, q to quit.\n    Status: Running\n\n[Microsoft.AspNetCore.Hosting]\n    Current Requests                                                0\n    Failed Requests                                                 0\n    Request Rate (Count / 1 sec)                                    0\n    Total Requests                                                  0\n[Microsoft-AspNetCore-Server-Kestrel]\n    Connection Queue Length                                        0\n    Connection Rate (Count / 1 sec)                                0\n    Current Connections                                            1\n    Current TLS Handshakes                                         0\n    Current Upgraded Requests (WebSockets)                         0\n    Failed TLS Handshakes                                          2\n    Request Queue Length                                           0\n    TLS Handshake Rate (Count / 1 sec)                             0\n    Total Connections                                              7\n    Total TLS Handshakes                                           7\n```\n\n## ASP.NET (.NET Framework)\n\n### Examining ASP.NET process memory (and dumps)\n\nSome useful [PSSCOR4](http://www.microsoft.com/en-us/download/details.aspx?id=21255) commands for ASP.NET:\n\n```\n!ProcInfo [-env] [-time] [-mem]\n\nFindDebugTrue\n\n!FindDebugModules [-full]\n\n!DumpHttpContext dumps the HttpContexts in the heap.  It shows the status of the request and the return code, etc.  It also prints out the start time\n\n!ASPXPages just calls !DumpHttpContext to print out information on the ASPX pages  running on threads.\n\n!DumpASPNETCache [-short] [-stat] [-s]\n\n!DumpRequestTable [-a] [-p] [-i] [-c] [-m] [-q] [-n] [-e] [-w] [-h]                   [-r] [-t] [-x] [-dw] [-dh] [-de] [-dx]\n\n!DumpHistoryTable [-a]\n!DumpHistoryTable dumps the aspnet_wp history table.\n\n!DumpBuckets dumps entire request table buckets.\n\n!GetWorkItems given a CLinkListNode, print out request & work items.\n```\n\n[Netext](http://netext.codeplex.com/) commands for ASP.NET:\n\n```\n!whttp [/order] [/running] [/withthread] [/status <decimal>] [/notstatus <decimal>] [/verb <string>] [<expr>] - dump HttpContext objects\n\n!wconfig - dump configuration sections loaded into memory\n\n!wruntime - dump all active Http Runtime information\n```\n\n### Profiling ASP.NET\n\n### Application instrumentation\n\nInteresting tools and libraries:\n\n- [ASP.NET 4.5 page instrumentation mechanism - PageExecutionListener](http://weblogs.asp.net/imranbaloch/archive/2013/11/23/page-instrumentation-in-asp-net-4-5.aspx)\n- [Glimpse](https://github.com/glimpse/glimpse)\n- [MiniProfiler](https://miniprofiler.com/)\n- [Elmah](https://elmah.github.io/)\n\nWe may also use the ASP.NET trace listener to print diagnostic message to the page trace. In the configuration file below, we configure the Performance TraceSource to pass events to the ASP.NET trace listener.\n\n```xml\n<?xml version=\"1.0\"?>\n<configuration>\n  <system.diagnostics>\n    <trace autoflush=\"true\" />\n    <sharedListeners>\n      <add name=\"WebPageTraceListener\" type=\"System.Web.WebPageTraceListener, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" />\n    </sharedListeners>\n    <sources>\n      <source name=\"Performance\" switchValue=\"Verbose\">\n        <listeners>\n          <add name=\"WebPageTraceListener\" />\n        </listeners>\n      </source>\n    </sources>\n  </system.diagnostics>\n  \n  <system.web>\n    <trace enabled=\"true\" localOnly=\"true\" pageOutput=\"false\" />\n\n    <customErrors mode=\"Off\">\n    </customErrors>\n    \n    <compilation debug=\"true\" targetFramework=\"4.0\">\n    </compilation>\n  </system.web>\n</configuration>\n```\n\n### ASP.NET ETW providers\n\nASP.NET ETW providers are defined in the aspnet.mof file in the main .NET Framework folder. They should be installed with the framework:\n\n```\n> logman query /providers \"ASP.NET Events\"\n\nProvider                                 GUID\n-------------------------------------------------------------------------------\nASP.NET Events                           {AFF081FE-0247-4275-9C4E-021F3DC1DA35}\n\nValue               Keyword              Description\n-------------------------------------------------------------------------------\n0x0000000000000001  Infrastructure       Infrastructure Events\n0x0000000000000002  Module               Pipeline Module Events\n0x0000000000000004  Page                 Page Events\n0x0000000000000008  AppServices          Application Services Events\n\nValue               Level                Description\n-------------------------------------------------------------------------------\n0x01                Fatal                Abnormal exit or termination\n0x02                Error                Severe errors\n0x03                Warning              Warnings\n0x04                Information          Information\n0x05                Verbose              Detailed information\n```\n\nIf they are not, use mofcomp.exe to install them.\n\nTo start collecting trace events from the ASP.NET and IIS providers run the following command:\n\n```\nlogman start aspnettrace -pf ctrl-iis-aspnet.guids -ct perf -o aspnet.etl -ets\n```\n\nwhere the ctrl-iis-aspnet.guids looks as follows:\n\n```\n{AFF081FE-0247-4275-9C4E-021F3DC1DA35} 0xf    5  ASP.NET Events\n{3A2A4E84-4C21-4981-AE10-3FDA0D9B0F83} 0x1ffe 5  IIS: WWW Server\n```\n\nAnd stop it with the command:\n\n```\nlogman stop aspnettrace -ets\n```\n\n### Collect events using the Perfecto tool\n\nPerfecto is a tool that creates an ASP.NET data collector in the system and allows you to generate nice reports of requests made to your ASP.NET application. After installing you can either use the **perfmon** to start the report generation:\n\n1. On perfmon, navigate to the \"Performance\\Data Collector Sets\\User Defined\\ASPNET Perfecto\" node.\n2. Click the \"Start the Data Collector Set\" button on the tool bar.\n3. Wait for/or make requests to the server (more than 10 seconds).\n4. Click the \"Stop the Data Collector Set\" button on the tool bar.\n5. Click the \"View latest report\" button on the tool bar or navigate to the last report at \"Performance\\Reports\\User Defined\\ASPNET Perfecto\"\n\nor **logman**:\n\n```\nlogman.exe start -n \"Service\\ASPNET Perfecto\"\n\nlogman.exe stop -n \"Service\\ASPNET Perfecto\"\n```\n\nNote: The View commands are also available as toolbar buttons.\nSometimes you can see an error like below:\n\n```\nError Code: 0xc0000bf8\nError Message: At least one of the input binary log files contain fewer than two data samples.\n```\n\nThis usually happens when you collected data too fast. The performance counters are set by default to collect every 10 seconds. So a fast start/stop sequence may end without enough counter data being collected. Always allow more than 10 seconds between a start and stop commands. Or otherwise delete the performance counters collector or change the sample interval.\n\nRequirements:\n\n1. Windows >= Vista\n2. Installed IIS tracing (`dism /online /enable-feature /featurename:IIS-HttpTracing`)\n\n### Collect events using FREB\n\nNew IIS servers (7.0 up) contain a nice diagnostics functionality called Failed Request Tracing (or **FREB**). You may find a lot of information how to enable it on the [IIS official site](https://www.iis.net/learn/troubleshoot/using-failed-request-tracing/troubleshooting-failed-requests-using-tracing-in-iis) and in my [iis debugging recipe](asp.net/troubleshooting-iis.md).\n\n{% endraw %}\n"
  },
  {
    "path": "guides/diagnosing-native-windows-apps.md",
    "content": "---\r\nlayout: page\r\ntitle: Diagnosing native Windows applications\r\ndate: 2025-05-25 08:00:00 +0200\r\n---\r\n\r\n{% raw %}\r\n\r\n**Table of contents:**\r\n\r\n<!-- MarkdownTOC -->\r\n\r\n- [Debugging process execution](#debugging-process-execution)\r\n- [Collecting memory dumps on errors](#collecting-memory-dumps-on-errors)\r\n    - [Using procdump](#using-procdump)\r\n    - [Using Windows Error Reporting \\(WER\\)](#using-windows-error-reporting-wer)\r\n    - [Automatic dump collection using AeDebug registry key](#automatic-dump-collection-using-aedebug-registry-key)\r\n- [Diagnosing waits or high CPU usage](#diagnosing-waits-or-high-cpu-usage)\r\n    - [Collecting ETW trace](#collecting-etw-trace)\r\n    - [Anaysing the collected traces](#anaysing-the-collected-traces)\r\n- [Diagnosing issues with DLL loading](#diagnosing-issues-with-dll-loading)\r\n- [Diagnosing window functions \\(user32\\)](#diagnosing-window-functions-user32)\r\n\r\n<!-- /MarkdownTOC -->\r\n\r\nDebugging process execution\r\n---------------------------\r\n\r\nPlease check [the WinDbg guide](/guides/windbg) where I describe various troubleshooting commands in WinDbg, along with Time Travel Debugging.\r\n\r\nCollecting memory dumps on errors\r\n---------------------------------\r\n\r\n### Using procdump\r\n\r\nMy preferred tool to collect memory dumps is **[procdump](https://learn.microsoft.com/en-us/sysinternals/downloads/procdump)**.\r\n\r\nIt is often a good way to start diagnosing errors by observing 1st chance exceptions occurring in a process. At this point we don't want to collect any dumps, only logs. We may achieve this by specyfing a non-existing exception name in the filter command, for example:\r\n\r\n```\r\nC:\\Utils> procdump -e 1 -f \"DoesNotExist\" 8012\r\n...\r\n\r\nCLR Version: v4.0.30319\r\n\r\n[09:03:27] Exception: E0434F4D.System.NullReferenceException (\"Object reference not set to an instance of an object.\")\r\n[09:03:28] Exception: E0434F4D.System.NullReferenceException (\"Object reference not set to an instance of an object.\")\r\n```\r\n\r\nWe may also observe the logs in procmon. In order to see the procdump log events in **procmon** remember to add procdump.exe and procdump64.exe to the accepted process names in procmon filters.\r\n\r\nTo create a full memory dump when `NullReferenceException` occurs use the following command:\r\n\r\n```\r\nprocdump -ma -e 1 -f \"E0434F4D.System.NullReferenceException\" 8012\r\n```\r\n\r\nFrom some time procdump uses a managed debugger engine when attaching to .NET Framework processes. This is great because we can filter exceptions based on their managed names. Unfortunately, that works only for 1st chance exceptions (at least for .NET 4.0). 2nd chance exceptions are raised out of the .NET Framework and must be handled by a native debugger. Starting from .NET 4.0 it is no longer possible to attach both managed and native engine to the same process. Thus, if we want to make a dump on the 2nd chance exception for a .NET application, we need to use the **-g** option in order to force procdump to use the native engine.\r\n\r\n### Using Windows Error Reporting (WER)\r\n\r\nBy default WER takes dump only when necessary, but this behavior can be configured and we can force WER to always create a dump by modifying `HKLM\\Software\\Microsoft\\Windows\\Windows Error Reporting\\ForceQueue=1` or (`HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Windows Error Reporting\\ForceQueue=1`). The reports are usually saved at `%LocalAppData%\\Microsoft\\Windows\\WER`, in two directories: `ReportArchive`, when a server is available or `ReportQueue`, when the server is unavailable.  If you want to keep the data locally, just set the server to a non-existing machine (for example, `HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting\\CorporateWERServer=NonExistingServer`). For **system processes** you need to look at `C:\\ProgramData\\Microsoft\\Windows\\WER`. In Windows 2003 Server R2 Error Reporting stores errors in the signed-in user's directory (for example, `C:\\Documents and Settings\\me\\Local Settings\\Application Data\\PCHealth\\ErrorRep`).\r\n\r\nStarting with Windows Server 2008 and Windows Vista with Service Pack 1 (SP1), Windows Error Reporting can be configured to [collect full memory dumps on application crash](https://learn.microsoft.com/en-us/windows/win32/wer/collecting-user-mode-dumps). The registry key enabling this behavior is `HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\Windows Error Reporting\\LocalDumps`. An example configuration for saving full-memory dumps to the %SYSTEMDRIVE%\\dumps folder when the test.exe application fails looks as follows:\r\n\r\n```\r\nWindows Registry Editor Version 5.00\r\n\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting\\LocalDumps]\r\n\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting\\LocalDumps\\test.exe]\r\n\"DumpFolder\"=hex(2):25,00,53,00,59,00,53,00,54,00,45,00,4d,00,44,00,52,00,49,\\\r\n  00,56,00,45,00,25,00,5c,00,64,00,75,00,6d,00,70,00,73,00,00,00\r\n\"DumpType\"=dword:00000002\r\n```\r\n\r\nWith the help of [the WER API](https://learn.microsoft.com/en-us/windows/win32/wer/wer-reference), you may also force WER reports in your custom application or even\r\n[register a custom crash handler](https://minidump.net/windows-error-reporting/).\r\n\r\nTo **completely disable WER**, create a DWORD Value under the `HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting` key, named `Disabled` and set its value to `1`. For 32-bit apps use the `HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\Windows Error Reporting` key.\r\n\r\n### Automatic dump collection using AeDebug registry key\r\n\r\nThere is a special [AeDebug](https://learn.microsoft.com/en-us/windows/win32/debug/configuring-automatic-debugging) key in the registry defining what should happen when an unhandled exception occurs in an application. You may find it under the `HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion` key (or `HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows NT\\CurrentVersion` for 32-bit apps). Its important value keys include:\r\n\r\n- `Debugger` : REG_SZ - application which will be called to handle the problematic process (example value: `procdump.exe -accepteula -j \"c:\\dumps\" %ld %ld %p`), the first %ld parameter is replaced with the process ID and the second with the event handle\r\n- `Auto` : REG_SZ - defines if the debugger runs automatically, without prompting the user (example value: 1)\r\n- `UserDebuggerHotKey` : REG_DWORD - not sure, but it looks it enables the Debug button on the exception handling message box (example value: 1)\r\n\r\nTo set **WinDbg** as your default AeDebug debugger, run `windbg -I`. After running this command, WinDbg will launch on application crashes. You may also automate WinDbg to create a memory dump and then allow process to terminate, for example: `windbg -c \".dump /ma /u c:\\dumps\\crash.dmp; qd\" -p %ld -e %ld -g`.\r\n\r\nMy favourite tool to use as the automatic debugger is **procdump**. The command line to install it is `procdump -mp -i c:\\dumps`, where c:\\dumps is the folder where I would like to store the dumps of crashing apps.\r\n\r\nDiagnosing waits or high CPU usage\r\n----------------------------------\r\n\r\nThere are two ways of tracing CPU time. We could either use CPU sampling or Thread Time profiling. CPU sampling is about collecting samples in intervals: each CPU sample contains an instruction pointer to the currently executing code. Thus, this technique is excellent when diagnosing high CPU usage of an application. It won't work for analyzing waits in the applications. For such scenarios, we should rely on Thread Time profiling. It uses the system scheduler/dispatcher events to get detailed information about application CPU time. When combined with CPU sampling, it is the best non-invasive profiling solution.\r\n\r\n### Collecting ETW trace\r\n\r\nWe may use **PerfView** or **wpr.exe** to collect CPU samples and Thread Time events.\r\n\r\nWhen collecting CPU samples, PerfView relies on Profile events coming from the Kernel ETW provider which has very low impact on the system overall performance. An example command to start the CPU sampling:\r\n\r\n```shell\r\nperfview collect -NoGui -KernelEvents:Profile,ImageLoad,Process,Thread -ClrEvents:JITSymbols cpu-collect.etl\r\n```\r\n\r\nAlternatively, you may use the Collect dialog. Make sure the Cpu Samples checkbox is selected.\r\n\r\nTo collect Thread Time events, you may use the following command:\r\n\r\n```shell\r\nperfview collect -NoGui -ThreadTime thread-time-collect.etl\r\n```\r\n\r\nThe Collect dialog has also the Thread Time checkbox.\r\n\r\n### Anaysing the collected traces\r\n\r\nFor analyzing **CPU Samples**, use the **CPU Stacks** view. Always check the number of samples if it corresponds to the tracing time (CPU sampling works when we have enough events). If necessary, zoom into the interesting period using a histogram (select the time and press Alt + R). Checking the **By Name** tab could be enough to find the method responsible for the high CPU Usage (look at the inclusive time and make sure you use correct grouping patterns).\r\n\r\nWhen analyzing waits in an application, we should use the **Thread Time Stacks** views. The default one, **with StartStop activities**, tries to group the tasks under activities and helps diagnose application activities, such as HTTP requests or database queries. Remember that the exclusive time in the activities view is a sum of all the child tasks. The thread under the activity is the thread on which the task started, not necessarily the one on which it continued. The **with ReadyThread** view can help when we are looking for thread interactions. For example, we want to find the thread that released a lock on which a given thread was waiting. The **Thread Time Stacks** view (with no grouping) is the best one to visualize the application's sequence of actions. Expanding thread nodes in the CallTree could take lots of time, so make sure you use other events (for example, from the Events view) to set the time ranges. As usual, check the grouping patterns.\r\n\r\nDiagnosing issues with DLL loading\r\n----------------------------------\r\n\r\nAn invaluable source of information when dealing with DLL loading issues are Windows Loader snaps. Those are detailed logs of the steps that Windows Loader takes to resolve the application library dependencies. They are one of the available Global Flags that we can set for an executable, so we may use the **gflags.exe** tool to enable them.\r\n\r\n![gflags - loader snaps](/assets/img/gflags-loader-snaps.png)\r\n\r\nAlternatively, you may modify the process IFEO registry key, for example:\r\n\r\n```\r\nWindows Registry Editor Version 5.00\r\n\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\winver.exe]\r\n\"GlobalFlag\"=dword:000000002\r\n```\r\n\r\nOnce enabled, you need to start the failing application under a debugger and the Loader logs should appear in the debug output.\r\n\r\nAlternatively, you may collect a procmon or ETW trace and search for any failure in the file events.\r\n\r\nDiagnosing window functions (user32)\r\n------------------------------------\r\n\r\nThe code snippet below contains example commands creating breakpoints to trace window functions:\r\n\r\n```cpp\r\n# 32-bit\r\nbp user32!NtUserSetWindowPos \".printf \\\"SetWindowPos( hWnd: %p, hWndInsertAfter: %p, X: %d, Y: %d, cx: %d, cy: %d, uFlags: %x )\\\\n\\\", poi(@esp+4), poi(@esp+8), poi(@esp+0xC), poi(@esp+0x10), poi(@esp+0x14), poi(@esp+0x18), poi(@esp+0x1C); g\"\r\nbp user32!NtUserShowWindow \".printf \\\"ShowWindow( hWnd: %p, nCmdShow: %d )\\\\n\\\", poi(@esp+4), poi(@esp+8); g\"\r\nbp user32!SetWindowLongW \".printf \\\"SetWindowLongW( hWnd: %p, nIndex: %d, dwNewLong: %p )\\\\n\\\", poi(@esp+4), poi(@esp+8), poi(@esp+0xC); g\"\r\nbp user32!SetForegroundWindow \".printf \\\"SetForegroundWindow( hWnd: %p )\\\\n\\\", poi(@esp+4); g\"\r\nbp user32!NtUserSetParent \".printf \\\"SetParent( hWndChild: %p, hWndNewParent: %p )\\\\n\\\", poi(@esp+4), poi(@esp+8); g\"\r\n\r\n# 32-bit, but using dx\r\nbp user32!NtUserSetWindowPos \"dx new { function = \\\"SetWindowPos\\\", hWnd = *(void **)(@esp+4), hWndInsertAfter = *(void **)(@esp+8), X = *(int *)(@esp+0xC), Y = *(int *)(@esp+0x10), cx = *(int *)(@esp+0x14), cy = *(int *)(@esp+0x18), uFlags = *(unsigned int *)(@esp+0x1C) }; g\"\r\nbp user32!NtUserSetForegroundWindow \"dx new { function = \\\"SetForegroundWindow\\\", hWnd = *(void **)(@esp+4) }; g\"\r\nbp user32!NtUserShowWindow \"dx new { function = \\\"ShowWindow\\\", hWnd = *(void **)(@esp+4), nCmdShow = *(int *)(@esp+8) }; g\"\r\nbp user32!NtUserSetParent \"dx new { function = \\\"SetParent\\\", hWndChild = *(void **)(@esp+4), hWndNewParent = *(void **)(@esp+8) }; g\"\r\nbp user32!NtUserSetWindowLong \"dx new { function = \\\"SetWindowLongW\\\", hWnd = *(void **)(@esp+4), nIndex = *(int *)(@esp+8), dwNewLong = *(long *)(@esp+0xC) }; g\"\r\n\r\n# 64-bit\r\nbp user32!NtUserSetWindowPos \".printf \\\"SetWindowPos( hWnd: %p, hWndInsertAfter: %p, X: %d, Y: %d, cx: %d, cy: %d, uFlags: %x )\\\\n\\\", @rcx, @rdx, @r8, @r9, poi(@rsp+0x20), poi(@rsp+0x28), poi(@rsp+0x30); g\"\r\nbp user32!NtUserShowWindow \".printf \\\"ShowWindow( hWnd: %p, nCmdShow: %d )\\\\n\\\", @rcx, @rdx; g\"\r\nbp user32!SetWindowLongW \".printf \\\"SetWindowLongW( hWnd: %p, nIndex: %d, dwNewLong: %p )\\\\n\\\", @rcx, @rdx, @r8; g\"\r\nbp user32!SetForegroundWindow \".printf \\\"SetForegroundWindow( hWnd: %p )\\\\n\\\", @rcx; g\"\r\nbp user32!NtUserSetParent \".printf \\\"SetParent( hWndChild: %p, hWndNewParent: %p )\\\\n\\\", @rcx, @rdx; g\"\r\n\r\n# 64-bit, but using dx\r\nbp user32!NtUserSetWindowPos \"dx new { function = \\\"SetWindowPos\\\", hWnd = (void *)@rcx, hWndInsertAfter = (void *)@rdx, X = (int)@r8, Y = (int)@r9, cx = *(int *)(@rsp+0x28), cy = *(int *)(@rsp+0x30), uFlags = *(unsigned int *)(@rsp+0x38) }; g\"\r\nbp user32!SetForegroundWindow \"dx new { function = \\\"SetForegroundWindow\\\", hWnd = (void *)@rcx }; g\"\r\nbp user32!NtUserShowWindow \"dx new { function = \\\"ShowWindow\\\", hWnd = (void *)@rcx, nCmdShow = (int)@rdx }; g\"\r\nbp user32!_imp_NtUserSetParent \"dx new { function = \\\"SetParent\\\", hWndChild = (void *)@rcx, hWndNewParent = (void *)@rdx }; g\"\r\nbp user32!SetWindowLongW \"dx new { function = \\\"SetWindowLongW\\\", hWnd = (void *)@rcx, nIndex = (int)@rdx, dwNewLong = (long)@r8 }; g\"\r\n\r\n# conditional breakpoints\r\nbp user32!PeekMessageW \"r $t1 = poi(@esp+4); bp /1 @$ra \\\".lastevent; dt (combase!tagMSG)@$t1; g\\\"; g\"\r\nbp user32!PeekMessageW \".lastevent; r $t1 = poi(@esp+4); r $t2 = poi(@esp+8); .printf \\\"PeekMessageW(%x, %x)\\n\\\", @$t1, @$t2; ba e1 /1 @$ra \\\".if (poi(@$t1) == 0x40526) { .lastevent; dt (combase!tagMSG)@$t1; g } .else { g }\\\"; g\"\r\nbp user32!PeekMessageW \"r $t1 = poi(@esp+4); ba e1 /1 @$ra \\\".if (poi(@$t1) == 0x7049c) { .lastevent; dt (combase!tagMSG)@$t1; g } .else { g }\\\"; g\"\r\nbp user32!SetWindowLongW \".lastevent; dps @esp L4; r $t0 = poi(@esp+c); .if ($t0 = 0) { g }\"\r\nbp user32!SetWindowLongW \".lastevent; dps @esp L4; r $t0 = poi(@esp+8); .if ($t0 = 0xffffffeb) { r @eip; } .else { g }\"\r\nbp user32!SetWindowLongW \".lastevent; dps @esp L4; .if (poi(@esp+8) = -2) { r @eip; } .else { g }\"\r\n```\r\n\r\nWhen analyzing a TTD trace, it is quicker to list the function calls while extracting their parameters to anonymous objects, for example:\r\n\r\n```cpp\r\ndx -g @$cursession.TTD.Calls(\"user32!NtUserSetWindowPos\").Select(c => new { HWND = c.Parameters[0], WClass = @$scriptContents.findWindow(c.Parameters[0]).className, X = c.Parameters[2], Y = c.Parameters[3], TimeStart = c.TimeStart, SystemTime = c.SystemTimeStart })\r\n\r\ndx -g @$cursession.TTD.Calls(\"user32!SetParentStub\").Select(c => new { Child = c.Parameters[0], ChildClass = @$scriptContents.findWindow(c.Parameters[0]).className, Parent = c.Parameters[1], ParentClass = @$scriptContents.findWindow(c.Parameters[1]).className, TimeStart = c.TimeStart, SystemTime = c.SystemTimeStart })\r\n```\r\n\r\nI also created a [**winapi-user32.ps1**](/assets/other/winapi-user32.ps1.txt) script, which decodes some of the window flag values to their text representation, for example:\r\n\r\n```sh\r\n# load script\r\n. winapi-user32.ps1\r\n\r\n# decode GWL_STYLE flag\r\nGet-EnumFlagsFromMask -Enum ([GWL_STYLE]) -Mask 382664704\r\n# WS_MAXIMIZEBOX\r\n# WS_MINIMIZEBOX\r\n# WS_THICKFRAME\r\n# WS_SYSMENU\r\n# WS_DLGFRAME\r\n# WS_BORDER\r\n# WS_CAPTION\r\n# WS_CLIPCHILDREN\r\n# WS_CLIPSIBLINGS\r\n# WS_VISIBLE\r\n\r\n# decode GWL_EXSTYLE flag\r\nGet-EnumFlagsFromMask -Enum ([GWL_EXSTYLE]) -Mask 262400\r\n# WS_EX_WINDOWEDGE\r\n# WS_EX_APPWINDOW\r\n\r\nGet-EnumFlagsFromMask ([SWP]) 20\r\n# SWP_NOZORDER\r\n# SWP_NOACTIVATE\r\n```\r\n\r\n{% endraw %}\r\n"
  },
  {
    "path": "guides/ebpf.md",
    "content": "---\r\nlayout: page\r\ntitle: eBPF\r\ndate: 2025-12-22 08:00:00 +0200\r\n---\r\n\r\n{% raw %}\r\n\r\n**Table of contents:**\r\n\r\n<!-- MarkdownTOC -->\r\n\r\n- [General information](#general-information)\r\n- [bpftrace](#bpftrace)\r\n    - [Probe Metadata](#probe-metadata)\r\n    - [Language Syntax](#language-syntax)\r\n    - [CPU Sampling](#cpu-sampling)\r\n    - [Available functions](#available-functions)\r\n    - [My one-liners](#my-one-liners)\r\n\r\n<!-- /MarkdownTOC -->\r\n\r\nGeneral information\r\n-------------------\r\n\r\n[Main project page](https://ebpf.io/)\r\n\r\nTo use eBPF you need to hold the following **required capabilities**: `CAP_BPF`, `CAP_PERFMON` (loading tracing programs), `CAP_NET_ADMIN` (loading network programs).\r\n\r\nbpftrace\r\n--------\r\n\r\n### Probe Metadata\r\n\r\nInformation about available probes (instrumentation point for capturing event data) can be retrieved with the **-l** option, e.g.:\r\n\r\n```shell\r\nbpftrace -l 'tracepoint:syscalls:*execve*'\r\n\r\n# tracepoint:syscalls:sys_enter_execve\r\n# tracepoint:syscalls:sys_enter_execveat\r\n# tracepoint:syscalls:sys_exit_execve\r\n# tracepoint:syscalls:sys_exit_execveat\r\n\r\n# and parameters\r\nbpftrace -lv 'tracepoint:syscalls:sys_enter_execve*'\r\n# tracepoint:syscalls:sys_enter_execve\r\n#     int __syscall_nr\r\n#     const char * filename\r\n#     const char *const * argv\r\n#     const char *const * envp\r\n# tracepoint:syscalls:sys_enter_execveat\r\n#     int __syscall_nr\r\n#     int fd\r\n#     const char * filename\r\n#     const char *const * argv\r\n#     const char *const * envp\r\n#     int flags\r\n```\r\n\r\n### Language Syntax\r\n\r\nIn each event, we can reference one of the **[built-in variables](https://github.com/bpftrace/bpftrace/blob/master/man/adoc/bpftrace.adoc#builtins)**, including: `comm` (process name), `pid`, `tid`, or `args` (a special variable that allows us to access arguments of a given event, e.g., `args.filename` for `tracepoint:syscalls:sys_enter_openat`). Additionally, we can create so-called **scratch variables**, which will only be visible within a given probe:\r\n\r\n```perl\r\nBEGIN { let $n = (uint8)1; }\r\nEND { printf(\"%d\", $n) } # error - $n is not available\r\n```\r\n\r\nHashmaps, on the other hand, remain visible throughout the entire script execution:\r\n\r\n```perl\r\nBEGIN {\r\n    @myconf[\"only_stacks\"] = (uint8)0;\r\n}\r\n\r\nEND {\r\n    printf(\"Stats enabled: %d\\n\", @myconf[\"only_stats\"]);\r\n    delete(@myconf, \"only_stacks\");\r\n}\r\n```\r\n\r\nWe also cannot change the type of either a variable or a value stored in a map, e.g.:\r\n\r\n```perl\r\n@myconf[\"pid\"] = $# > 1 ? $2 : 0;\r\n@myconf[\"pid\"] = \"test\"; # error\r\n```\r\n\r\nThe default numeric type is `uint64` and everything is cast to it, e.g.:\r\n\r\n```perl\r\n# pid will be stored as uint64 even if we cast to int32\r\nBEGIN {\r\n    @myconf[\"pid\"] = $# > 1 ? $2 : 0;\r\n}\r\n\r\n# WARNING: comparison of integers of different signs: 'int32' and 'uint64' can lead to undefined behavior\r\ntracepoint:sched:sched_process_fork / @myconf[\"pid\"] != 0 && args.parent_pid == @myconf[\"pid\"] / \r\n\r\n# OK:\r\ntracepoint:sched:sched_process_fork / @myconf[\"pid\"] != 0 && args.parent_pid == (int32)@myconf[\"pid\"] /\r\n```\r\n\r\nAt the beginning of a script, we can use **preprocessor directives**, but `#define` only works for constants (when I tried to add a function, I got a strange error).\r\n\r\nIn the preamble, we can also create our own types, but it seems we can only use them when working with C pointers. I couldn't initialize a variable of my type (`$t : my_struct = {}`). However, we can use tuples, which should often be sufficient. We reference tuple fields by their numeric index, e.g.:\r\n\r\n```perl\r\ntracepoint:syscalls:sys_enter_openat\r\n{\r\n    @openat[tid] = (args.dfd, args.filename, args.mode);\r\n}\r\n\r\ntracepoint:syscalls:sys_exit_openat\r\n{\r\n    $eventName = \"file_openat\";\r\n    PRINT_EVENT_COMMONS;\r\n\r\n    $data = @openat[tid];\r\n    printf(\"dfd: %d filename: '%s', mode: %x, ret: %d\\n\", $data.0, str($data.1), $data.2, args.ret);\r\n    delete(@openat[tid]);\r\n}\r\n```\r\n\r\n`BEGIN` is one of the **[available probes](https://github.com/bpftrace/bpftrace/blob/master/man/adoc/bpftrace.adoc#probes)** that allows code execution at the start of a tracing session, e.g.:\r\n\r\n```shell\r\nbpftrace -e 'BEGIN { printf(\"hello world\\n\"); }'\r\n# Attaching 1 probe...\r\n# hello world\r\n# ^C\r\n```\r\n\r\nIf we prefix a variable name with `@`, we get a hashmap (without a name, we'll use the global hashmap). We can access its keys through square brackets. At the end of tracing, bpftrace outputs all used hashmaps, e.g.:\r\n\r\n```perl\r\nbpftrace -e 'tracepoint:syscalls:sys_enter_write { @[comm] = count(); }'\r\n# Attaching 1 probe...\r\n# ^C\r\n# \r\n# @[rtkit-daemon]: 1\r\n# @[Worker Launcher]: 1\r\n# ...\r\n\r\nbpftrace -e 'tracepoint:syscalls:sys_enter_write { @write[comm] = count(); } tracepoint:syscalls:sys_enter_writev { @writev[comm] = count(); }'\r\n# Attaching 2 probes...\r\n# ^C\r\n# \r\n# @write[redshift-gtk]: 2\r\n# @write[syncthing]: 2\r\n# @write[redshift]: 2\r\n# @writev[at-spi2-registr]: 2\r\n# @writev[redshift]: 4\r\n```\r\n\r\nIf we add `/ ... /` after a syscall name, we can place **a filter** between the slashes, e.g., `pid == 1234`, to display events only for the process with ID 1234, e.g.:\r\n\r\n```perl\r\nbpftrace -e 'tracepoint:syscalls:sys_enter_write / comm == \"fish\" / { @ = count(); }'\r\n# Attaching 1 probe...\r\n# ^C\r\n# \r\n# @: 415\r\n```\r\n\r\nWe can also use ifs inside action code.\r\n\r\n`count` is one of the **[map functions](https://github.com/bpftrace/bpftrace/blob/master/man/adoc/bpftrace.adoc#map-functions)** we can use to generate hashmaps. `hist`, `stats` and `avg` are other such functions.\r\n\r\n### CPU Sampling\r\n\r\nbpftrace [supports debuginfod symbols](https://github.com/iovisor/bcc/pull/3393/files) and this is awesome because, for example, ustack or kstack show real stacks. After collecting a trace, it can be converted to a flame graph using scripts from the [FlameGraph](https://github.com/brendangregg/FlameGraph) repository, e.g.:\r\n\r\n```perl\r\nbpftrace -o test-service.out -q -e 'profile:hz:99 / comm == \"test-service\" / { @[ustack()] = count(); }'\r\n\r\n./stackcollapse-bpftrace.pl test-service.out > test-service.flame\r\n./flamegraph.pl test-service.flame > test-service.flame.svg\r\n```\r\n\r\n### Available functions\r\n\r\nIn the **printf** function, the '-' character before the width means the text will be left-aligned, e.g.:\r\n\r\n```perl\r\nprintf(\"|%-15s|\\n\", \"TIME\");\r\n#|TIME           |\r\nprintf(\"|%15s|\\n\", \"TIME\");\r\n#|           TIME|\r\n```\r\n\r\n### My one-liners\r\n\r\n```perl\r\n# openat with process information and collected stack\r\nbpftrace -e 'tracepoint:syscalls:sys_enter_openat / strcontains(comm, \"dump-\") == 1 / { printf(\"%d:%s %d %s\\n\", pid, comm, args.dfd, str(args.filename)); print(ustack()); }'\r\n```\r\n\r\n{% endraw %}"
  },
  {
    "path": "guides/etw.md",
    "content": "---\nlayout: page\ntitle: Event Tracing for Windows (ETW)\ndate: 2025-10-02 08:00:00 +0200\nredirect_from:\n    - /guides/using-etw/\n---\n\n{% raw %}\n\n**Table of contents:**\n\n<!-- MarkdownTOC -->\n\n- [General information](#general-information)\n- [Tools](#tools)\n    - [Windows Performance Recorder \\(WPR\\)](#windows-performance-recorder-wpr)\n        - [Profiles](#profiles)\n        - [Starting and stopping the trace](#starting-and-stopping-the-trace)\n        - [Issues](#issues)\n    - [Windows Performance Analyzer \\(WPA\\)](#windows-performance-analyzer-wpa)\n        - [Installation](#installation)\n        - [Tips on analyzing events](#tips-on-analyzing-events)\n    - [Perfview](#perfview)\n        - [Installation](#installation_1)\n        - [Tips on recording events](#tips-on-recording-events)\n        - [Tips on analyzing events](#tips-on-analyzing-events_1)\n        - [Live view of events](#live-view-of-events)\n        - [Issues](#issues_1)\n    - [logman](#logman)\n        - [Querying providers installed in the system](#querying-providers-installed-in-the-system)\n        - [Starting and stopping the trace](#starting-and-stopping-the-trace_1)\n    - [wevtutil](#wevtutil)\n    - [tracerpt](#tracerpt)\n    - [xperf](#xperf)\n    - [TSS \\(TroubleShootingScript toolset\\)](#tss-troubleshootingscript-toolset)\n    - [MSO scripts \\(PowerShell\\)](#mso-scripts-powershell)\n- [Event types](#event-types)\n    - [Autologger events](#autologger-events)\n    - [System boot events](#system-boot-events)\n    - [File events](#file-events)\n    - [Registry events](#registry-events)\n    - [WPP events](#wpp-events)\n- [Libraries](#libraries)\n    - [ETW tools and libs \\(including EtwEnumerator\\)](#etw-tools-and-libs-including-etwenumerator)\n    - [TraceProcessing](#traceprocessing)\n    - [WPRContol](#wprcontol)\n    - [TraceEvent](#traceevent)\n    - [KrabsETW](#krabsetw)\n    - [Performance Logs and Alerts \\(PLA\\)](#performance-logs-and-alerts-pla)\n    - [System API](#system-api)\n\n<!-- /MarkdownTOC -->\n\nGeneral information\n-------------------\n\nWhen loading **symbols**, the ETW tools and libraries use the **\\_NT\\_SYMBOLS\\_PATH** environment variable to download (and cache) the PDB files and **\\_NT\\_SYMCACHE\\_PATH** to store their preprocessed (cached) versions. An example machine configuration might look as follows:\n\n```shell\nsetx /M _NT_SYMBOL_PATH \"SRV*C:\\symbols\\dbg*https://msdl.microsoft.com/download/symbols\"\nsetx /M _NT_SYMCACHE_PATH \"C:\\symcache\"\n```\n\nOn Windows 7 64-bit, to improve stack walking, disable paging of the drivers and kernel-mode system code:\n\n```sh\nreg add \"HKLM\\System\\CurrentControlSet\\Control\\Session Manager\\Memory Management\" -v DisablePagingExecutive -d 0x1 -t REG\\_DWORD -f\n# or\nwpr.exe -disablepagingexecutive`\n```\n\nFor **manifest-based providers** set `MatchAnyKeywords` to `0x00` to receive all events. Otherwise you need to create a bitmask which will be or-ed with event keywords. Additionally when `MatchAllKeywords` is set, its value is used for events that passed the `MatchAnyKeywords` test and providers additional and filtering.\n\nFor **classic providers** set `MatchAnyKeywords` to `0xFFFFFFFF` to receive all events.\n\nUp to 8 sessions may collect manifest-based provider events, but only 1 session may be created for a classic provider (when a new session is created the provider switches to the session).\n\nWhen creating a session we may also specify the minimal severity level for collected events, where `1` is the critical level and `5` the verbose level (all events are logged).\n\nTools\n-----\n\n### Windows Performance Recorder (WPR)\n\n#### Profiles\n\nAs its name suggests, WPR is a tool that records ETW traces and is available on all modern Windowses. It is straightforward to use and provides a big number of **ready-to-use tracing profiles**. We can list them with the `-profiles` command and show any profile details with the `profiledetails` command, for example:\n\n```shell\n# list available profiles with their short description\nwpr.exe -profiles\n\n# ...\n# GeneralProfile              First level triage\n#         CPU                         CPU usage\n#         DiskIO                      Disk I/O activity\n#         FileIO                      File I/O activity\n#         ...\n\n# show profile details\nwpr.exe -profiledetails CPU\n\n# ...\n# Profile                 : CPU.Verbose.Memory\n# \n# Collector Name          : WPR_initiated_WprApp_WPR System Collector\n# Buffer Size (KB)        : 1024\n# Number of Buffers       : 3258\n# Providers\n# System Keywords\n#         CpuConfig\n#         CSwitch\n#         ...\n#         SampledProfile\n#         ThreadPriority\n# System Stacks\n#         CSwitch\n#         ReadyThread\n#         SampledProfile\n# \n# Collector Name          : WPR_initiated_WprApp_WPR Event Collector\n# Buffer Size (KB)        : 1024\n# Number of Buffers       : 20\n# Providers\n#         b7a19fcd-15ba-41ba-a3d7-dc352d5f79ba: : 0xff\n#         e7ef96be-969f-414f-97d7-3ddb7b558ccc: 0x2000: 0xff\n#         Microsoft-JScript: 0x1: 0xff\n#         Microsoft-Windows-BrokerInfrastructure: 0x1: 0xff\n#         Microsoft-Windows-DotNETRuntime: 0x20098: 0x05\n#         ...\n#         Microsoft-Windows-Win32k: 0x80000: 0xff\n```\n\nProfiles often come in two versions: verbose and light, and we decide which one to use by appending \"Verbose\" or \"Light\" to the main profile name (if we do not specify the version, WPR defaults to \"Verbose\"), for example:\n\n```sh\nwpr.exe -profiledetails CPU.Light\n```\n\nThe trace could be memory- or file- based, with memory-based being the default. We can switch to the file-based profile by using the `-filemode` option. If we can find a profile for our tracing scenario, we may build a custom one (WPR profile schema is documented [here](https://learn.microsoft.com/en-us/windows-hardware/test/wpt/recording-profile-xml-reference)). It is often easier to base it one of the existing profiles, which we may extract with the `-exportprofile` command, for example:\n\n```sh\n# export the memory-based CPU.Light profilek\nwpr.exe -exportprofile CPU.Light C:\\temp\\CPU.light.wprp\n# export the file-based CPU.Light profilek\nwpr.exe -exportprofile CPU.Light C:\\temp\\CPU.light.wprp -filemode\n```\n\nInterestingly, in the XML file, profile names include also the tracing mode, so the memory-based profile will have name `CPU.Light.Memory`, as you can see in the example below:\n\n```xml\n<WindowsPerformanceRecorder Version=\"1.0\">\n  <Profiles>\n    <!-- ... -->\n    <Profile Id=\"CPU.Light.Memory\" Name=\"CPU\" Description=\"RunningProfile:CPU.Light.Memory\" LoggingMode=\"Memory\" DetailLevel=\"Light\">\n    <!-- or with the -filemode option -->\n    <Profile Id=\"CPU.Light.File\" Name=\"CPU\" Description=\"RunningProfile:CPU.Light.File\" LoggingMode=\"File\" DetailLevel=\"Light\">\n  </Profiles>\n</WindowsPerformanceRecorder>\n```\n\nAn exteremly important parameter of the collector configuration are buffers. If we look into the exported profiles, we will find that the number of buffers differs depending on the mode which we use for tracing. Memory-based profiles will use a much higher number of buffers, for example:\n\n```xml\n<!-- CPU.Verbose.Memory -->\n<SystemCollector Id=\"WPR_initiated_WprApp_WPR_System_Collector\" Name=\"WPR_initiated_WprApp_WPR System Collector\">\n  <BufferSize Value=\"1024\" />\n  <Buffers Value=\"1023\" />\n</SystemCollector>\n\n<!-- CPU.Verbose.File -->\n<SystemCollector Id=\"WPR_initiated_WprApp_WPR_System_Collector\" Name=\"WPR_initiated_WprApp_WPR System Collector\">\n  <BufferSize Value=\"1024\" />\n  <Buffers Value=\"20\" />\n</SystemCollector>\n```\n\nThe number of buffers depends also on the amount of memory on the host. Because `BufferSize` specifies memory size in KB, the above space is quite large (1GB). In memory mode, we operate on circular in-memory buffers - the system adds new buffers when the previous buffers fill up. When it reaches the maximum, it begins to overwrite events in the oldest buffers. For a file-based traces, the number of buffers is much smaller, as we only need to ensure that we are not dropping events because the disk cannot keep up with the write operations.\n\nApart from keywords and levels, we may **[filter the trace and stack events](https://devblogs.microsoft.com/performance-diagnostics/filtering-events-using-wpr/)** by the event IDs (`EventFilters`, `StackFilters`). Filtering by process name is also possible, however, in my tests I found that the `ProcessExeFilter` works only for processes already running when we start the trace:\n\n```xml\n<EventProvider Id=\"DotNetRuntime\" Name=\"e13c0d23-ccbc-4e12-931b-d9cc2eee27e4\" ProcessExeFilter=\"filecopy.exe\">\n  <Keywords>\n    <Keyword Value=\"0x60098\" />\n  </Keywords>\n</EventProvider>\n<Profile Id=\"Wtrace.Verbose.Memory\" Name=\"Wtrace\" LoggingMode=\"Memory\" DetailLevel=\"Verbose\" Description=\"wtrace trace in memory profile\">\n  <Collectors>\n    <EventCollectorId Value=\"wtrace-user\">\n      <EventProviders>\n        <EventProviderId Value=\"DotNetRuntime\" />\n      </EventProviders>\n    </EventCollectorId>\n  </Collectors>\n</Profile>\n```\n\nWorking with WPR profiles is described in details in a great series of posts on [Microsoft's Performance and Diagnostics blog](https://devblogs.microsoft.com/performance-diagnostics/) and I highly recommend reading them:\n\n- [WPR Start and Stop Commands](https://devblogs.microsoft.com/performance-diagnostics/wpr-start-and-stop-commands/)\n- [Authoring custom profiles – Part 1](https://devblogs.microsoft.com/performance-diagnostics/authoring-custom-profiles-part-1/)\n- [Authoring Custom Profiles – Part 2](https://devblogs.microsoft.com/performance-diagnostics/authoring-custom-profiles-part-2/)\n- [Authoring Custom Profiles – Part 3](https://devblogs.microsoft.com/performance-diagnostics/authoring-custom-profile-part3/)\n\nI also created **an [EtwMetadata.ps1](/assets/other/EtwMetadata.ps1.txt) script that you may use to decode the wprp files**. For example:\n\n```sh\nwpr.exe -exportprofile CPU.Light C:\\temp\\CPU.light.wprp\n\ncurl.exe -o C:\\temp\\EtwMetadata.ps1 https://wtrace.net/assets/other/EtwMetadata.ps1.txt\n\n. C:\\temp\\EtwMetadata.ps1\n# Initializing ETW providers metadata...\n\nGet-EtwProvidersFromWprProfile C:\\temp\\CPU.light.wprp\n\n# WARNING: No metadata found for provider 'b7a19fcd-15ba-41ba-a3d7-dc352d5f79ba'\n# WARNING: No metadata found for provider 'e7ef96be-969f-414f-97d7-3ddb7b558ccc'\n# Id                                   Name                                           Keywords\n# --                                   ----                                           --------\n# 36b6f488-aad7-48c2-afe3-d4ec2c8b46fa Microsoft-Windows-Performance-Recorder-Control @{Name=PerfStatus; Value=65536}\n# b675ec37-bdb6-4648-bc92-f3fdc74d3ca2 Microsoft-Windows-Kernel-EventTracing          @{Name=ETW_KEYWORD_LOST_EVENT; Val…\n# 83ed54f0-4d48-4e45-b16e-726ffd1fa4af Microsoft-Windows-Networking-Correlation       {@{Name=ActivityTransfer; Value=1}…\n# d8975f88-7ddb-4ed0-91bf-3adf48c48e0c Microsoft-Windows-RPCSS                        {@{Name=EpmapDebug; Value=256}, @{…\n# 6ad52b32-d609-4be9-ae07-ce8dae937e39 Microsoft-Windows-RPC\n# d49918cf-9489-4bf1-9d7b-014d864cf71f Microsoft-Windows-ProcessStateManager          {@{Name=StateChange; Value=1}, @{N…\n# e6835967-e0d2-41fb-bcec-58387404e25a Microsoft-Windows-BrokerInfrastructure         @{Name=BackgroundTask; Value=1}\n```\n\n#### Starting and stopping the trace\n\nAfter picking a profile or profiles that we want to use, we can **start a tracing session** with the `-start` command. Some examples:\n\n```sh\n# starts verbose CPU profile\nwpr.exe -start CPU.verbose\n# same as above\nwpr.exe -start CPU\n\n# starts light CPU profile\nwpr.exe -start CPU.light\n\n# multiple profiles start\nwpr.exe -start CPU -start VirtualAllocation -start Network\n\n# starts a custom WPRTest.Verbose profile defined in the C:\\temp\\CustomProfile.wprp file\nwpr.exe -start \"C:\\temp\\CustomProfile.wprp!WPRTest\" -filemode\n# starts a custom WPRTest.Light profile defined in the C:\\temp\\CustomProfile.wprp file\nwpr.exe -start \"C:\\temp\\CustomProfile.wprp!WPRTest.Light\"\n```\n\nThere could be only one WPR trace running in the system and we can check its status using the `-status` command:\n\n```sh\n wpr -status\n\n# Microsoft Windows Performance Recorder Version 10.0.26100 (CoreSystem)\n# Copyright (c) 2024 Microsoft Corporation. All rights reserved.\n# \n# WPR recording is in progress...\n# \n# Time since start        : 00:00:01\n# Dropped event           : 0\n# Logging mode            : File\n```\n\nTo **terminate the trace** we may use either the `-stop` or the `-cancel` command:\n\n```shell\n# stopping the trace and saving it to a file with an optional description\nwpr.exe -stop \"C:\\temp\\testapp-fail.etl\" \"Abnormal termination of testapp.exe\"\n# cancelling the trace (no trace files will be created)\nwpr.exe -cancel\n```\n\n#### Issues\n\n##### Error 0x80010106 (RPC_E_CHANGED_MODE)\n\nIf it happens when you run the `-stop` command, use wpr.exe from Windows SDK, build 1950 or later.\n\n##### Error 0xc5580612\n\nIf you are using `ProcessExeFilter` in your profile, this error may indicate that a process with a given name is not running when the trace starts (it is thrown by `WindowsPerformanceRecorderControl!WindowsPerformanceRecorder::CControlManager::VerifyAllProvidersEnabled`):\n\n```\nAn Event session cannot be started without any providers.\n\nProfile Id: Wtrace.Verbose.File\n\nError code: 0xc5580612\n\nAn Event session cannot be started without any providers.\n```\n\n### Windows Performance Analyzer (WPA)\n\n#### Installation\n\n**Windows Performance Analyzer (wpa.exe)**, may be installed from [Microsoft Store](https://apps.microsoft.com/store/detail/windows-performance-analyzer-preview/9N58QRW40DFW?hl=en-sh&gl=sh) (recommended) or as part of the  **Windows Performance Toolkit**, included in the [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/).\n\n#### Tips on analyzing events\n\nIn **CPU Wait analysis**, each row marks a moment, when a thread received CPU time ([MS docs](https://learn.microsoft.com/en-us/windows-hardware/test/wpt/cpu-analysis#cpu-usage-precise-graph)) after, for example, waiting on an event object. The `Readying Thread` is the thread that woke up the `New Thread`. And the `Old Thread` is the thread which gave place on a CPU to the `New Thread`. The diagram below from Microsoft documentation nicely explain those terms:\n\n![](/assets/img/cpu-usage-precise-diagram.jpg)\n\nHere is an example view of my test GUI app when I call the `Sleep` function after pressing a button:\n\n![](/assets/img/ui-delay-with-cpu-precise.png)\n\nAs you can see, the `Wait` column shows the time spent on waiting, while the UI view shows the time when the application was unresponsive.\n\nWPA allows us to **group the call stacks** by tags. The default stacktag list can be found in the `c:\\Program Files (x86)\\Windows Kits\\10\\Windows Performance Toolkit\\Catalog\\default.stacktags` file.\n\nWe may also **extend WPA with our own plugins**. The [SDK repository](https://github.com/microsoft/microsoft-performance-toolkit-sdk/) contains sample extensions. [Wpa.Demystifier](https://github.com/Zhentar/Wpa.Demystifier/tree/master) is another interesting extension to check.\n\n### Perfview\n\n#### Installation\n\nCould be downloaded from [its release page](https://github.com/microsoft/perfview/releases) or installed with winget:\n\n```sh\nwinget install --id Microsoft.PerfView\n```\n\n#### Tips on recording events\n\nMost often you will use the Collect dialog, but it is also possible to use PerfView from a command line. An example command collecting traces into a 500MB file (in circular mode) may look as follows:\n\n```sh\nperfview -AcceptEULA -ThreadTime -CircularMB:500 -Circular:1 -LogFile:perf.output -Merge:TRUE -Zip:TRUE -noView  collect\n```\n\nA new console window will open with the following text:\n\n```\nPre V4.0 .NET Rundown enabled, Type 'D' to disable and speed up .NET Rundown.\nDo NOT close this console window.   It will leave collection on!\nType S to stop collection, 'A' will abort.  (Also consider /MaxCollectSec:N)\n\nType 'S' when you are done with tracing and wait (DO NOT CLOSE THE WINDOW) till you see `Press enter to close window`. Then copy the files: PerfViewData.etl.zip and perf.output to the machine when you will perform analysis.\n```\n\nIf you are also interested in the network traces append the `-NetMonCapture` option. This will generate an additional PerfViewData_netmon.cab file.\n\nIf we use the EventSource provider and want to collect the call stacks along with the events, we need to append `@StacksEnabled=true` to the provider name, for example: `*EFTrace:@StacksEnabled=true`.\n\n#### Tips on analyzing events\n\nSelect a **time range** and press `Alt+R` to set it for the grid. We may also copy a range, paste it in the Start box and then press Enter to apply it (PerfView should fill the End box).\n\nThe table below contains grouping patterns I use for various analysis targets\n\nName     |  Pattern \n-------- | -------- \nJust my code with folded threads | `[My app + folded threads] \\Temporary ASP.NET Files\\->;!dynamicClass.S->;!=>OTHER;Thread->AllThreads` |\nJust my code with folded threads (ASP.NET view) | `[My app + folded threads and ASP.NET requests] Thread -> AllThreads;Request ID * URL: {*}-> URL $1;\\Temporary ASP.NET Files\\->;!dynamicClass.S->;!=>OTHER`\nJust my code with folded threads (Server requests view) | `[My app + folded threads and requests] Thread -> AllThreads;ASP.NET Request: * URL: {*}-> URL $1;\\Temporary ASP.NET Files\\->;!dynamicClass.S->;!=>OTHER`\nGroup requests | `^Request ID->ALL Requests`\nGroup requests by URL | `Request ID * URL:{*}->$1`\nGroup async calls (by Christophe Nasarre) | `{%}!{%}+<>c__DisplayClass*+<<{%}>b__*>d.MoveNext()->($1) $2 async $3`\n\nWhen exporting to **Excel**, the data coming from PerfView often does not have valid formatting and contains some strange characters at the beginning or at the end, for example:\n\n```\n0000  A0 A0 32 32 34    224\n```\n\nWe may clean up those values by using the **SUBSTITUTE** function, for example:\n\n```\n=SUBSTITUTE(A1,LEFT(A1,1),\"\")\n=SUBSTITUTE(A1,RIGHT(A1,1),\"\")\n```\n\nAnd later do the usual Copy, Paste as Values operation. Alternatively, we may copy the values column by column. In that case, PerfView won't insert those special characters.\n\nIf we want to open a trace created by PerfView in **WPA**, we need to first convert it, for example:\n\n```sh\nperfview /wpr unzip test.etl.zip\n# The above command should create two files (.etl and .etl.ngenpdb)\n# and we can open wpa\nwpa test.etl\n```\n\n#### Live view of events\n\nThe `Listen` user command enables a live view dump of events in the PerfView log:\n\n```sh\nPerfView.exe UserCommand Listen Microsoft-JScript:0x7:Verbose\n\n# inspired by Konrad Kokosa's tweet\nPerfView.exe UserCommand Listen Microsoft-Windows-DotNETRuntime:0x1:Verbose:@EventIDsToEnable=\"1 2\"\n```\n\n#### Issues\n\n##### Error 0x800700B7 (ERROR_ALREADY_EXISTS)\n\n```\n[Kernel Log: C:\\tools\\PerfViewData.kernel.etl]\n    Kernel keywords enabled: Default\n    Aborting tracing for sessions 'NT Kernel Logger' and 'PerfViewSession'.\n    Insuring .NET Allocation profiler not installed.\n    Completed: Collecting data C:\\tools\\PerfViewData.etl   (Elapsed Time: 0,858 sec)\n    Exception Occured: System.Runtime.InteropServices.COMException (0x800700B7): Cannot create a file when that file already exists. (Exception from HRESULT: 0x800700B7)\n       at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)\n       at Microsoft.Diagnostics.Tracing.Session.TraceEventSession.EnableKernelProvider(Keywords flags, Keywords stackCapture)\n       at PerfView.CommandProcessor.Start(CommandLineArgs parsedArgs)\n       at PerfView.CommandProcessor.Collect(CommandLineArgs parsedArgs)\n       at PerfView.MainWindow.c__DisplayClass9.b__7()\n       at PerfView.StatusBar.c__DisplayClass8.b__6(Object param0)\n    An exceptional condition occurred, see log for details.\n```\n\nIf you receive such error, make sure that no kernel log is running with `perfview listsessions` and eventually kill it with `perfview abort`.\n\n### logman\n\nNowadays, logman will not be our first choice tool to collect ETW trace, but the best thing about it is that it is a built-in tool and has been available in Windows for many years already, so might be the only option if you need to work on a legacy Windows system.\n\n#### Querying providers installed in the system\n\nLogman is great for querying ETW providers installed in the system or activated in a given process:\n\n```sh\n# list all providers in the system\nlogman query providers\n\n# show details about the \".NET Common Language Runtime\" provider\nlogman query providers \".NET Common Language Runtime\"\n\n# list providers active in a process with ID 808\nlogman query providers -pid 808\n```\n\n#### Starting and stopping the trace\n\nThe following commands start and stop a tracing session that is using one provider:\n\n```sh\nlogman start mysession -p {9744AD71-6D44-4462-8694-46BD49FC7C0C} -o \"c:\\temp\\test.etl\" -ets & timeout -1 & logman stop mysession -ets\n```\n\nFor the provider options you may additionally specify the keywords (flags) and levels that will be logged: `-p provider [flags [level]]`\n\nYou may also use a file with a list of providers:\n\n```sh\nlogman start mysession -pf providers.guids -o c:\\temp\\test.etl -ets & timeout -1 & logman stop mysession -ets\n```\n\nAnd the `providers.guids` file content is built of lines following the format: `{guid} [flags] [level] [provider name]` (flags, level, and provider name are optional), for example:\n\n```\n{AFF081FE-0247-4275-9C4E-021F3DC1DA35} 0xf    5  ASP.NET Events\n{3A2A4E84-4C21-4981-AE10-3FDA0D9B0F83} 0x1ffe 5  IIS: WWW Server\n```\n\nIf you want to record events from the **kernel provider** you need to name the session: `NT Kernel Logger`, for example:\n\n```sh\nlogman start \"NT Kernel Logger\" -p \"Windows Kernel Trace\" \"(process,thread,file,fileio,net)\" -o c:\\kernel.etl -ets & timeout -1 & logman stop \"NT Kernel Logger\" -ets\n```\n\nTo see the available kernel provider keywords, run:\n\n```sh\nlogman query providers \"Windows Kernel Trace\"\n\n# Provider                                 GUID\n# -------------------------------------------------------------------------------\n# Windows Kernel Trace                     {9E814AAD-3204-11D2-9A82-006008A86939}\n# \n# Value               Keyword              Description\n# -------------------------------------------------------------------------------\n# 0x0000000000000001  process              Process creations/deletions\n# 0x0000000000000002  thread               Thread creations/deletions\n# ...\n```\n\nAdditionally, we may change the way how events are saved to the file using the `-mode` parameter. For example, to use a circular file with maximum size of 200MB, we can run the following command:\n\n```sh\nlogman start \"NT Kernel Logger\" -p \"Windows Kernel Trace\" \"(process,thread,img)\" -o C:\\ntlm-kernel.etl -mode circular -max 200 -ets\n```\n\n### wevtutil\n\nWevtutil is a built-in tool that allows us to manage **manifest-based providers (publishers)** installed in our system. Example usages:\n\n```sh\n# list all installed publishers\nwevtutil ep\n# find MSMQ publishers\nwevtutil ep | findstr /i msmq\n\n# extract details about a Microsoft-Windows-MSMQ publisher\nwevtutil gp Microsoft-Windows-MSMQ /ge /gm /f:xml\n```\n\n### tracerpt\n\nTracerpt is another built-in tool. It may collect ETW traces, but I usually use it only to convert etl files from binary to text format. Example commands:\n\n```sh\n# convert etl file to evtx\ntracerpt -of EVTX test.etl -o test.evtx -summary test-summary.xml\n\n# dump events to an XML file\ntracerpt test.etl -o test.xml -summary test-summary.xml\n\n# dump events to a HTML file\ntracerpt.exe '.\\NT Kernel Logger.etl' -o -report -f html\n```\n\n### xperf\n\nFor a long time xperf was the best tool to collect ETW traces, providing ways to configure many aspects of the tracing sessions. It is now considered legacy (with [wpr](#windows-performance-recorder-wpr) being its replacement), but many people still find its command line syntax eaier to use than WPR profiles. Here are some usage examples:\n\n```sh\n# list available Kernel Flags\nxperf -providers KF\n#       PROC_THREAD         : Process and Thread create/delete\n#       LOADER              : Kernel and user mode Image Load/Unload events\n#       PROFILE             : CPU Sample profile\n#       CSWITCH             : Context Switch\n#       ...\n\n# list available Kernel Groups\nxperf -providers KG\n#       Base           : PROC_THREAD+LOADER+DISK_IO+HARD_FAULTS+PROFILE+MEMINFO+MEMINFO_WS\n#       Diag           : PROC_THREAD+LOADER+DISK_IO+HARD_FAULTS+DPC+INTERRUPT+CSWITCH+PERF_COUNTER+COMPACT_CSWITCH\n#       DiagEasy       : PROC_THREAD+LOADER+DISK_IO+HARD_FAULTS+DPC+INTERRUPT+CSWITCH+PERF_COUNTER\n#       ...\n\n# list installed providers\nxperf -providers I\n#       0063715b-eeda-4007-9429-ad526f62696e                              : Microsoft-Windows-Services\n#       0075e1ab-e1d1-5d1f-35f5-da36fb4f41b1                              : Microsoft-Windows-Network-ExecutionContext\n#       00b7e1df-b469-4c69-9c41-53a6576e3dad                              : Microsoft-Windows-Security-IdentityStore\n#       01090065-b467-4503-9b28-533766761087                              : Microsoft-Windows-ParentalControls\n#       ...\n\n# start the kernel trace, enabling flags defined in the DiagEasy group\nxperf -on DiagEasy\n# stop the kernel trace\nxperf -stop -d \"c:\\temp\\DiagEasy.etl\"\n\n# start the kernel with some additional settings and wait for the user to stop it\nxperf -on Latency -stackwalk Profile -buffersize 2048 -MaxFile 1024 -FileMode Circular && timeout -1 && xperf stop -d \"C:\\highCPUUsage.etl\"\n\n# in user-mode tracing you may still use kernel flags and groups but for each user-trace provider \n# you need to add some additional parameters: -on (GUID|KnownProviderName)[:Flags[:Level[:0xnnnnnnnn|'stack|[,]sid|[,]tsid']]]\nxperf -start ClrRundownSession -on ClrAll:0x118:5+a669021c-c450-4609-a035-5af59af4df18:0x118:5 -f clr_DCend.etl -buffersize 128 -minbuffers 256 -maxbuffers 512\ntimeout /t 15\nxperf -stop ClrSession ClrRundownSession -stop -d cpu_clr.etl\n\n# dump collected events to a text file\nxperf -i test.etl -o test.csv\n```\n\nChad Schultz published [many xperf scripts](https://github.com/itoleck/WindowsPerformance/tree/main/ETW/Tools/WPT/Xperf/CaptureScripts) in the [WindowsPerformance repository](https://github.com/itoleck/WindowsPerformance), so check them out if you are interested in using xperf.\n\n### TSS (TroubleShootingScript toolset)\n\nTSS contains tons of various scripts and ETW is only a part of it. TSS official documentation is [here](https://learn.microsoft.com/en-us/troubleshoot/windows-client/windows-tss/introduction-to-troubleshootingscript-toolset-tss) and we can download the package from <https://aka.ms/getTSS>.\n\nHere is an example PowerShell script to install and run the main script:\n\n```shell\npowershell.exe -NoProfile -ExecutionPolicy RemoteSigned -Command \"Invoke-WebRequest -Uri https://aka.ms/getTSS -OutFile $env:TEMP\\TSS.zip; Unblock-File $env:TEMP\\TSS.zip; Expand-Archive -Force -LiteralPath $env:TEMP\\TSS.zip -DestinationPath C:\\TSS; Remove-Item $env:TEMP\\TSS.zip; C:\\TSS\\TSS.ps1 -ListSupportedTrace\"\n```\n\nTSS defined many **troubleshooting scenarios** with precompiled parameters:\n\n```shell\nC:\\tSS\\TSS.ps1 -ListSupportedScenarioTrace\n# ...\n# NET_General        - collects CommonTask NET, NetshScenario InternetClient_dbg, Procmon, PSR, Video, SDP NET, xray, CollectComponentLog\n# ...\n```\n\nwhere:\n\n- `CommonTask` are commands run before and after the scenario (only `NET` in this case)\n- `NetshScenario` is the selected netsh scenario (`InternetClient_dbg`)\n- `Procmon` will start procmon\n- `PSR` will run step recorder\n- `Video` will record a video of what the user is doing\n- `SDP` (Support Diagnostic Package) and `NET` enable `General`, `SMB`, and `NET` counters\n- `xray` runs xray scripts to discover existing problems\n- `CollectComponentLog` collects logs of commands run in a given scenario\n\nTo start a scenario, we run:\n\n```shell\nC:\\TSS\\TSS.ps1 -Scenario NET_General\n```\n\nWe may also manually \"compose\" the TSS command. A nice GUI tool for this purpose is `.\\TSSGUI.ps1` (start it from the TSS folder). We may also list available TSS features:\n\n```shell\nC:\\TSS\\TSS.ps1 -ListSupportedCommands\nC:\\TSS\\TSS.ps1 -ListSupportedControls\nC:\\TSS\\TSS.ps1 -ListSupportedDiag\nC:\\TSS\\TSS.ps1 -ListSupportedLog\nC:\\TSS\\TSS.ps1 -ListSupportedNetshScenario\nC:\\TSS\\TSS.ps1 -ListSupportedNoOptions\nC:\\TSS\\TSS.ps1 -ListSupportedPerfCounters\nC:\\TSS\\TSS.ps1 -ListSupportedScenarioTrace\nC:\\TSS\\TSS.ps1 -ListSupportedSDP\nC:\\TSS\\TSS.ps1 -ListSupportedSetOptions\nC:\\TSS\\TSS.ps1 -ListSupportedTrace\nC:\\TSS\\TSS.ps1 -ListSupportedWPRScenario\nC:\\TSS\\TSS.ps1 -ListSupportedXperfProfile\n```\n\nExample commands to check which ETW providers the `NET_COM` component is using:\n\n```shell\n.\\TSS.ps1 -ListSupportedTrace | select-string \"_COM\"\n# [Component]  -NET_COM                  COM/DCOM/WinRT/PRC component tracing. -EnableCOMDebug will enable further debug logging\n# [Component]  -UEX_COM                  COM/DCOM/WinRT/PRC component ETW tracing. -EnableCOMDebug will enable further debug logging\n# Usage:\n#   .\\TSS.ps1 -<ComponentName> -<ComponentName>\n#   Example: .\\TSS.ps1 -UEX_FSLogix -UEX_Logon\n\n.\\TSS -ListETWProviders NeT_COM\n\n# List of 20 Provider GUIDs (Flags/Level) for ComponentName: NET_COM\n# ==========================================================\n# {9474a749-a98d-4f52-9f45-5b20247e4f01}\n# {bda92ae8-9f11-4d49-ba1d-a4c2abca692e}\n# ...\n```\n\nThe TSS commands create raports in the `C:\\MS_DATA` folder.\n\nTo collect the trace in the background we may use the `-StartNoWait` option and `-Stop` to stop the trace.\n\nIf we add the `-StartAutoLogger` option, our trace will start when the system boots. We stop by calling `TSS.ps1 -Stop`, as usual.\n\nExample commands:\n\n```shell\n# starting WPR using TSS\nC:\\TSS\\TSS.ps1 -WPR CPU -WPROptions \"-start Dotnet -start DesktopComposition\"\n\n# Starting time travel debugging session using TSS\n# 1234 is the process PID (we may use process name as well, for example winver.exe)\nC:\\TSS\\TSS.ps1 -AcceptEula -TTD 1234\n```\n\n### MSO scripts (PowerShell)\n\n[MSO-Scripts repository](https://github.com/microsoft/MSO-Scripts) hosts many interesting PowerShell scripts for working with ETW traces.\n\nEvent types\n-----------\n\n### Autologger events\n\nAutologger ETW session collects events appearing after the system start. It can be enabled with wpr:\n\n```sh\nwpr.exe -boottrace -addboot FileIO\n```\n\nAdditional information:\n\n- [Autologger session](https://learn.microsoft.com/en-us/windows/win32/etw/configuring-and-starting-an-autologger-session)\n- [Autologger with WPR](https://devblogs.microsoft.com/performance-diagnostics/setting-up-an-autologger-with-wpr/)\n\n### System boot events\n\nTo collect general profile traces use: \n\n```sh\nwpr.exe -start generalprofile -onoffscenario boot -numiterations 1\n```\n\n### File events\n\nDescribed in [a post on my blog](https://lowleveldesign.org/2020/08/15/fixing-empty-paths-in-fileio-events-etw/).\n\n### Registry events\n\nDescribed in [a post on my blog](https://lowleveldesign.org/2020/08/20/monitoring-registry-activity-with-etw/).\n\n### WPP events\n\nWPP events are legacy events, for which we need TMF files to decode their payload. TMF may be available as standalone files or they might be embedded into PDB files. For the latter case, we may extract them using **tracepdb.exe**, for example:\n\n```sh\ntracepdb.exe -f .\\combase.pdb -p .\\tmfs\n```\n\nTMF data is stored as a binary block in the PDB file:\n\n```\n0D9:46A0  BA 00 19 10 20 52 0A 00 01 00 06 00 54 4D 46 3A  º... R......TMF:\n0D9:46B0  00 64 61 66 38 39 65 63 31 2D 64 66 66 32 2D 33  .daf89ec1-dff2-3 \n0D9:46C0  30 35 35 2D 36 30 61 62 2D 36 33 64 34 63 31 31  055-60ab-63d4c11 \n0D9:46D0  62 33 64 39 63 20 4F 4C 45 43 4F 4D 20 2F 2F 20  b3d9c OLECOM //  \n0D9:46E0  53 52 43 3D 63 6F 6D 74 72 61 63 65 77 6F 72 6B  SRC=comtracework \n0D9:46F0  65 72 2E 63 78 78 20 4D 4A 3D 20 4D 4E 3D 00 23  er.cxx MJ= MN=.# \n0D9:4700  74 79 70 65 76 20 63 6F 6D 74 72 61 63 65 77 6F  typev comtracewo \n0D9:4710  72 6B 65 72 5F 63 78 78 31 38 36 20 31 31 20 22  rker_cxx186 11 \" \n0D9:4720  25 30 25 31 30 21 73 21 22 20 2F 2F 20 20 20 4C  %0%10!s!\" //   L \n0D9:4730  45 56 45 4C 3D 57 41 52 4E 49 4E 47 00 7B 00 6D  EVEL=WARNING.{.m \n0D9:4740  65 73 73 61 67 65 2C 20 49 74 65 6D 57 53 74 72  essage, ItemWStr \n0D9:4750  69 6E 67 20 2D 2D 20 31 30 00 7D 00 BA 00 19 10  ing -- 10.}.º... \n```\n\nThe GUID at the beginning of the block defines the provider ID and may appear multiple times in the PDB file. Tracepdb uses this ID as the name of the generated TMF file. When decoding WPP events, if we do not configure the `TDH_CONTEXT_WPP_TMFSEARCHPATH`, Tdh functions will look for TMF files in the path specified in the [TRACE_FORMAT_SEARCH_PATH environment variable](https://learn.microsoft.com/en-us/windows/win32/api/tdh/ne-tdh-tdh_context_type). **WPA** has a special view for WPP events and can load the TMF manifests from symbol files, so **remember to first load the symbols**.\n\nLibraries\n---------\n\nThis section lists some of the ETW libraries I used with my notes about them. It is not meant to be a comprehensive documentation of those libraries, but rather a list of tips and tricks.\n\n### ETW tools and libs (including EtwEnumerator)\n\n[Source code](https://github.com/microsoft/ETW)\n\nThis C++ library contains code to parse ETW events. The sample EtwEnumerator CLI tool formats events from a binary etl file to their text representation.\n\nTo build the library run:\n\n```shell\ncd EtwEnumerator\ncmake -B bin .\ncmake --build bin\n```\n\nThe `EtwEnumerator` instance stores information about the currently analyzed event in an efficient way, caching metadata for future processing of similar events. Please check the [README](https://github.com/microsoft/ETW/tree/main/EtwEnumerator). Below is an example C# code that formats event to a JSON string in the [ETW callback function](https://learn.microsoft.com/en-us/windows/win32/api/evntrace/nc-evntrace-pevent_record_callback):\n\n```cs\nEtwStringViewZ etwString;\nfixed (char* formatPtr = \"[%9]%8.%3::%4 [%1]\")\n{\n   if (!ee->FormatCurrentEvent((ushort*)formatPtr, EtwJsonSuffixFlags.EtwJsonSuffixFlags_Default, &etwString))\n   {\n       Trace.WriteLine(\"ERROR\");\n       return;\n   }\n}\n\nvar s = new string((char*)etwString.Data, 0, (int)etwString.DataLength);\nwriter.TryWrite(new MessageEvent(s));\n```\n\n### TraceProcessing\n\n[Documentation](https://learn.microsoft.com/en-us/windows/apps/trace-processing/) | [Code samples](https://github.com/microsoft/eventtracing-processing-samples)\n\nTraceProcessing library **categorized the events and splits them between Trace Processor**. Before processing the trace, we mark Trace Processors that we want to active, and we may query the events they processed after the analysis finishes, for example:\n\n```cs\nusing var trace = TraceProcessor.Create(traceFilePath);\n\nvar pendingProcesses = trace.UseProcesses();\nvar pendingFileIO = trace.UseFileIOData();\n\ntrace.Process();\n\nvar filecopyProcess = pendingProcesses.Result.Processes.Where(p => p.ImageName == \"filecopy.exe\").First();\n\nvar fev = pendingFileIO.Result.CreateFileObjectActivity.First(f => f.IssuingProcess.Id == filecopyProcess.Id\n                && f.FileName == \"sampling-2-1.etl\");\n\nConsole.WriteLine($\"Create file event: {fev.Path} ({fev.FileObject})\");\n\n```\n\nThe above code uses the buffered mode of opening a trace file, in which all processed events land in memory (we may notice that the application memory consumption will be really high for bigger traces). Therefore, for bigger traces we may also use [the streaming mode](https://learn.microsoft.com/en-us/windows/apps/trace-processing/streaming), but not all event types support it. An example session using streaming mode might be coded as follows:\n\n```cs\nusing var trace = TraceProcessor.Create(traceFilePath);\nvar pendingProcesses = trace.UseProcesses();\nint filecopyProcessId = 0;\n\nlong eventCount = 0;\nlong filecopyEventCount = 0;\n\n// ConsumerSchedule defines when our parser will be called, for example, we may choose\n// SecondPass when buffered processors will be available\ntrace.UseStreaming().UseUnparsedEvents(ConsumerSchedule.Default, context =>\n{\n    eventCount++;\n});\n\ntrace.UseStreaming().UseUnparsedEvents(ConsumerSchedule.SecondPass, context =>\n{\n    if (filecopyProcessId == 0)\n    {\n        filecopyProcessId = pendingProcesses.Result.Processes.Where(p => p.ImageName == \"filecopy.exe\").First().Id;\n    }\n    if (context.Event.ProcessId == filecopyProcessId)\n    {\n        filecopyEventCount++;\n    }\n});\n\ntrace.Process();\n\nreturn (filecopyEventCount, eventCount);\n```\n\nIn my tests, I discovered that **GenericEvents** processor is not very reliable as I could not find some of the events (for example, FileIo), visible in other tools, but maybe I was doing something wrong :)\n\n### WPRContol\n\nWPRControl is the COM object used by, for example, wpr.exe. Its API is [well-documented](https://learn.microsoft.com/en-us/windows-hardware/test/wpt/wprcontrol-api-reference), with `KernelTraceControl.h` and `WindowsPerformanceRecordedControl.h` headers and IDLs available for our usage.\n\n### TraceEvent\n\n[Source code](https://github.com/microsoft/perfview/tree/main/src/TraceEvent) | [Documentation](https://github.com/microsoft/perfview/tree/main/documentation)\n\nTraceEvent is a huge library which is the tracing engine that PerfView uses for collecting and processing events.\n\nWhen iterating through collected events, remember to clone the events you need for future processing as the current `TraceEvent` instance is in-memory replaced by the next analyzed event. For example the `requestStartEvent` and `requestStopEvent` in the code below will contain invalid data at the end of the loop (we should be calling `ev.Clone()` to save the event):\n\n```cs\nTraceEvent? requestStartEvent = null, requestStopEvent = null;\nforeach (var ev in traceLog.Events.Where(ev => ev.ProviderGuid == aspNetProviderId))\n{\n    if (ev.ActivityID == activityIdGuid)\n    {\n        if (ev.ID == (TraceEventID)2) // Request/Start\n        {\n            requestStartEvent = ev;\n        }\n        if (ev.ID == (TraceEventID)3) // Request/Stop\n        {\n            requestStopEvent = ev;\n        }\n    }\n}\n\n// requestStartEvent i requestStopEvent zawierają błędne dane, ponieważ obiekt, którego wewnętrznie używają ma nadpisane dane przez późniejsze eventy\n```\n\nIf you are interested how TraceEvent library processes the ETW events, the good place to start is the `ETWTraceEventSource.RawDispatchClassic` event callback function. It uses `TraceEvent.Lookup` to create the final instance of the `TraceEvent` class.\n\n### KrabsETW\n\n[Source code](https://github.com/microsoft/krabsetw)\n\nKrabsETW is used by the Office 365 Security team. An example code to start a live session looks as follows:\n\n```cs\nusing Microsoft.O365.Security.ETW;\nusing Microsoft.O365.Security.ETW.Kernel;\n\nusing var trace = new KernelTrace(\"krabsetw-lab\");\n\nvar processProvider = new ProcessProvider();\n\nprocessProvider.OnEvent += (record) =>\n{\n    if (record.Opcode == 0x01)\n    {\n        var image = record.GetAnsiString(\"ImageFileName\", \"Unknown\");\n        var pid = record.GetUInt32(\"ProcessId\", 0);\n        Console.WriteLine($\"{image} started with PID {pid}\");\n    }\n};\n\ntrace.Enable(processProvider);\n\nConsole.CancelKeyPress += (sender, ev) =>\n{\n    ev.Cancel = true;\n    trace.Stop();\n};\n\ntrace.Start();\n```\n\nThe KrabsETW is implemented in C++ CLI which complicates the deployment. Firstly, I needed to add `<RuntimeIdentifier>win-x64</RuntimeIdentifier>` to my csproj file to fix a problem with missing `Ijwhost.dll` library. However, it still produced errors when trimming and the application was failing:\n\n```sh\ndotnet publish -c release -r win-x64 -p:PublishSingleFile=true -p:PublishTrimmed=true --self-contained -p:IncludeNativeLibrariesForSelfExtract=true\n# MSBuild version 17.6.8+c70978d4d for .NET\n#   Determining projects to restore...\n#   All projects are up-to-date for restore.\n#   krabsetw-lab -> C:\\code\\krabsetw-lab\\bin\\release\\net7.0-windows\\win-x64\\krabsetw-lab.dl\n#   l\n#   Optimizing assemblies for size. This process might take a while.\n# C:\\Users\\me\\.nuget\\packages\\microsoft.o365.security.native.etw\\4.3.1\\lib\\net6.0\\Microsoft.O365.Security.Native.ETW.dll\n# : warning IL2104: Assembly 'Microsoft.O365.Security.Native.ETW' produced trim warnings. For more information see https:\n# //aka.ms/dotnet-illink/libraries [C:\\code\\krabsetw-lab\\krabsetw-lab.csproj]\n#   krabsetw-lab -> C:\\code\\krabsetw-lab\\bin\\release\\net7.0-windows\\win-x64\\publish\\\n```\n\n```sh\nkrabsetw-lab.exe\n# Unhandled exception. System.BadImageFormatException:\n# File name: 'C:\\code\\krabsetw-lab\\bin\\release\\net7.0-windows\\win-x64\\publish\\Microsoft.O365.Security.Native.ETW.dll'\n#    at Program.<Main>$(String[] args)\n```\n\nWhen processing events, KrabsETW uses `schema_locator` to cache and decode payload of a given event:\n\n```cpp\nstruct schema_key\n{\n    guid      provider;\n    uint16_t  id;\n    uint8_t   opcode;\n    uint8_t   version;\n    uint8_t   level;\n\n    // ...\n}\n\n\ninline const PTRACE_EVENT_INFO schema_locator::get_event_schema(const EVENT_RECORD &record) const\n{\n    // check the cache\n    auto key = schema_key(record);\n    auto& buffer = cache_[key];\n\n    if (!buffer) {\n        auto temp = get_event_schema_from_tdh(record);\n        buffer.swap(temp);\n    }\n\n    return (PTRACE_EVENT_INFO)(buffer.get());\n}\n```\n\n### Performance Logs and Alerts (PLA)\n\n[Documentation](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/pla/pla-portal)\n\nPLA is a COM library used by logman to provide trace collection options. The library registration can be located in the registry:\n\n```\nComputer\\HKEY_CLASSES_ROOT\\CLSID\\{03837513-098B-11D8-9414-505054503030}\n```\n\nThe main DLLs are **pla.dll** and **plasrv.exe**.\n\nFor example, the `ITraceDataProviderCollection::GetTraceDataProvidersByProcess` method, responsible for querying providers in a process, calls `TraceSession::LoadGuidArray`, which then uses `EnumerateTraceGuidsEx`.\n\n### System API\n\n[Documentation](https://learn.microsoft.com/en-us/windows/win32/api/_etw/)\n\nLow-level API to collect and analyze traces - all above libraries use these functions.\n\n{% endraw %}"
  },
  {
    "path": "guides/gdb.md",
    "content": "---\r\nlayout: page\r\ntitle: GDB usage guide\r\ndate: 2025-05-27 08:00:00 +0200\r\n---\r\n\r\n{% raw %}\r\n\r\n\r\n**Table of contents:**\r\n\r\n<!-- MarkdownTOC -->\r\n\r\n- [Configuration](#configuration)\r\n    - [.gdbinit](#gdbinit)\r\n    - [ptrace capability](#ptrace-capability)\r\n- [TUI](#tui)\r\n- [Symbols](#symbols)\r\n    - [Searching for symbols and addresses](#searching-for-symbols-and-addresses)\r\n    - [Searching for source code](#searching-for-source-code)\r\n- [Debugging child processes](#debugging-child-processes)\r\n- [Execution Control](#execution-control)\r\n    - [Process startup](#process-startup)\r\n    - [Breakpoints and catchpoints](#breakpoints-and-catchpoints)\r\n    - [Code execution](#code-execution)\r\n    - [Signals](#signals)\r\n- [State Control](#state-control)\r\n    - [Process information](#process-information)\r\n    - [Threads](#threads)\r\n    - [Shared libs](#shared-libs)\r\n    - [Stack](#stack)\r\n    - [Code and Assembler](#code-and-assembler)\r\n    - [Memory](#memory)\r\n    - [Expressions \\(variables, registers, etc.\\)](#expressions-variables-registers-etc)\r\n- [Extensions](#extensions)\r\n    - [Python interpreter](#python-interpreter)\r\n    - [GUI / CUI](#gui-cui)\r\n\r\n<!-- /MarkdownTOC -->\r\n\r\nConfiguration\r\n-------------\r\n\r\n### .gdbinit\r\n\r\nIt's worth enabling the following elements permanently in the `~/.gdbinit` file:\r\n\r\n```shell\r\n# show disassembly on every stop and use intel syntax\r\nset disassembly-flavor intel\r\nset disassemble-next-line on\r\n\r\n# enable debuginfod\r\nset debuginfod enable on\r\n\r\n# stop on forking and exceptions\r\ncatch fork\r\ncatch vfork\r\ncatch throw\r\ncatch rethrow\r\n```\r\n\r\nWe may check the debuginfod settings in GDB:\r\n\r\n```\r\n(gdb) show debuginfod\r\ndebuginfod enabled:  Debuginfod functionality is currently set to \"ask\".\r\ndebuginfod urls:  Debuginfod URLs have not been set.\r\ndebuginfod verbose:  Debuginfod verbose output is set to 1.\r\n```\r\n\r\n### ptrace capability\r\n\r\nTo ptrace any process, you may add ptrace capability to gdb:\r\n\r\n```shell\r\nsudo setcap cap_sys_ptrace=eip $(which gdb)\r\n```\r\n\r\nTUI\r\n---\r\n\r\nThis is a windowed interface for GDB. We enable/disable it using **Ctrl-x a**. **Ctrl-x 1** enables single-window mode, **Ctrl-x 2** enables two-window mode. The `tui layout` command determines what appears in the windows, e.g.:\r\n\r\n```shell\r\ntui layout split\r\ntui layout src\r\n```\r\n\r\n**Ctrl-x o** allows us to switch between active debugger windows.\r\n\r\nSymbols\r\n-------\r\n\r\n### Searching for symbols and addresses\r\n\r\n`info address` finds the symbol associated with a given memory address, `info symbol` finds the address associated with a given symbol, for example:\r\n\r\n```shell\r\ninfo address lo_getattr\r\n# Symbol \"lo_getattr\" is a function at address 0x555555556af0.\r\n\r\ninfo symbol 0x555555556af0\r\n# lo_getattr in section .text of /tmp/passthrough-minimal/passthrough_ll\r\n```\r\n\r\n`info types` searches for type declarations (accepts regexes). For functions we have `info functions` e.g.:\r\n\r\n```shell\r\ninfo functions statx\r\n# All functions matching regular expression \"statx\":\r\n# \r\n# File ../sysdeps/unix/sysv/linux/statx.c:\r\n# 25: int statx(int, const char *, int, unsigned int, struct statx *);\r\n# \r\n# File ./statx_generic.c:\r\n# 42: static int statx_generic(int, const char *, int, struct statx *, unsigned int);\r\n```\r\n\r\n`ptype` allows viewing the definition of a given type. As a parameter we can provide either the type name or a variable of that type, e.g.:\r\n\r\n```shell\r\nptype struct link_map\r\n# type = struct link_map {\r\n#     Elf64_Addr l_addr;\r\n#     char *l_name;\r\n#     Elf64_Dyn *l_ld;\r\n#     struct link_map *l_next;\r\n#     struct link_map *l_prev;\r\n#     struct link_map *l_real;\r\n#     Lmid_t l_ns;\r\n#     ...\r\n# }\r\n```\r\n\r\n`info scope` - shows symbols currently available in a given scope, e.g. for function `match_symbol`:\r\n\r\n```shell\r\ninfo scope match_symbol \r\n# Scope for match_symbol:\r\n# Symbol digits is optimized out.\r\n# Symbol _itoa_word is a function at address 0x7ffff7fda11a, length 1.\r\n# Symbol value is multi-location:\r\n#   Range 0x7ffff7fda21c-0x7ffff7fda220: a variable in $rcx\r\n#   Range 0x7ffff7fda240-0x7ffff7fda26f: a variable in $rcx\r\n#   Range 0x7ffff7fda26f-0x7ffff7fda275: a variable in $rdx\r\n# , length 8.\r\n# Symbol buflim is multi-location:\r\n#   Range 0x7ffff7fda21c-0x7ffff7fda220: a complex DWARF expression:\r\n#      0: DW_OP_fbreg -109\r\n#      3: DW_OP_stack_value\r\n# \r\n#   Range 0x7ffff7fda220-0x7ffff7fda275: a variable in $rsi\r\n# , length 8.\r\n# Symbol base is multi-location:\r\n#   Range 0x7ffff7fda21c-0x7ffff7fda275: the constant 10\r\n# , length 4.\r\n# Symbol upper_case is multi-location:\r\n#   Range 0x7ffff7fda21c-0x7ffff7fda275: the constant 0\r\n# , length 4.\r\n# Symbol digits is optimized out.\r\n```\r\n\r\n### Searching for source code\r\n\r\nThe `directory` command allows us to add additional directories for the source code:\r\n\r\n```shell\r\nshow directories \r\n# Source directories searched: $cdir:$cwd\r\n\r\ndirectory /tmp/openssl-0.9.8-easy_tls-orig/\r\n# Source directories searched: /tmp/openssl-0.9.8-easy_tls-orig:$cdir:$cwd\r\n```\r\n\r\nDebugging child processes\r\n-------------------------\r\n\r\n`set detach-on-fork off` makes the debugger debug both the parent and its fork. If we don't enable this, we can decide what happens at fork using `set follow-fork-mode`. The `parent` option will cause the debugger to continue debugging the parent. The `child` option will switch to the child.\r\n\r\nAt the moment of fork, it's possible that `continue` won't work. We then need to allow both parent and child to execute simultaneously using `set schedule-multiple on`.\r\n\r\nWe can view currently debugged processes with the `info inferiors` command, and switch between them with `inferior {ID}`.\r\n\r\nExecution Control\r\n-----------------\r\n\r\n### Process startup\r\n\r\nGDB takes the debugged binary as an argument. Then we can add startup arguments with the `run` command. It also accepts stdin redirection from any file, e.g.:\r\n\r\n```shell\r\nr mytestapp < /tmp/test_file\r\n```\r\n\r\n### Breakpoints and catchpoints\r\n\r\n`b func_name` sets a breakpoint on a function, `b file:line_num` sets a breakpoint on a line.\r\n\r\nAdditionally, we have special breakpoints called catchpoints for handling events (somewhat similar to `sxe` in WinDbg), e.g. `catch fork` to stop the debugger at fork:\r\n\r\n```shell\r\ncatch fork\r\n# Catchpoint 1 (fork)\r\n\r\ninfo breakpoints \r\n# Num     Type           Disp Enb Address            What\r\n# 1       catchpoint     keep y                      fork\r\n# 2       breakpoint     keep y   0x00000000004044f0 in main at test.c:38\r\n#     breakpoint already hit 1 time\r\n\r\n# Catchpoint 1 (forked process 5473), arch_fork (ctid=0x7ffff7ca8690) at ../sysdeps/unix/sysv/linux/arch-fork.h:50\r\n# 50    ret = INLINE_SYSCALL_CALL (clone, flags, 0, NULL, ctid, 0);\r\n# => 0x00007ffff7db9b57 <__GI__Fork+39>:  48 3d 00 f0 ff ff   cmp    rax,0xfffffffffffff000\r\n#    0x00007ffff7db9b5d <__GI__Fork+45>:  77 39               ja     0x7ffff7db9b98 <__GI__Fork+104>\r\n# set detach-on-fork off\r\nc\r\n# Continuing.\r\n# [New inferior 2 (process 5473)]\r\n# [Thread debugging using libthread_db enabled]\r\n# Using host libthread_db library \"/usr/lib/libthread_db.so.1\".\r\n```\r\n\r\nThe `catch` command alone will display available events (similar to `sx` in WinDbg).\r\n\r\n`rb function_regex` allows setting breakpoints based on regular expressions:\r\n\r\n```shell\r\nrb ssl_shim::wrapped_.*\r\n\r\n# Breakpoint 2 at 0x7ffff7f741cd: file src/lib.rs, line 308.\r\n# fn ssl_shim::wrapped_SSL_CTX_check_private_key(*mut ssl_shim::ssl::ssl_ctx_st) -> i32;\r\n# Breakpoint 3 at 0x7ffff7f74539: file src/lib.rs, line 406.\r\n# fn ssl_shim::wrapped_SSL_CTX_ctrl(*mut ssl_shim::ssl::ssl_ctx_st, i32, i64, *mut core::ffi::c_void) -> i64;\r\n# Breakpoint 4 at 0x7ffff7f73b4e: file src/lib.rs, line 124.\r\n# fn ssl_shim::wrapped_SSL_CTX_free(*mut ssl_shim::ssl::ssl_ctx_st);\r\n# Breakpoint 5 at 0x7ffff7f73f0d: file src/lib.rs, line 226.\r\n# fn ssl_shim::wrapped_SSL_CTX_get_client_CA_list(*mut ssl_shim::ssl::ssl_ctx_st) -> *mut ssl_shim::ssl::stack_st_X509_NAME;\r\n# ...\r\n```\r\n\r\n`info break` lists the breakpoints and catchpoints. `disable ID` disables the breakpoint, `enable ID` enables the breakpoint, `del ID` deletes the breakpoint.\r\n\r\n`commands ID` allows us to assign a command to a breakpoint:\r\n\r\n```shell\r\nb easy-tls.c:991\r\n\r\ninfo b\r\n# Num     Type           Disp Enb Address    What\r\n# 1       breakpoint     keep y   <PENDING>  easy_tls.c:991\r\n\r\ncommands 1\r\n# Type commands for breakpoint(s) 1, one per line.\r\n# End with a line saying just \"end\".\r\n>print r\r\n>end\r\n```\r\n\r\n`watch {var}` - break if the value of the variable changes\r\n\r\n### Code execution\r\n\r\n| Command             | Description |\r\n|---------------------|-------------|\r\n| `r {args}`          | (re)run the program |\r\n| `s`                 | step in |\r\n| `n`                 | step over |\r\n| `u`                 | until the next line (for example, to exit the loop) |\r\n| `c`                 | continue |\r\n| `ret {return_code}` | return from the current function |\r\n| `j {line}`          | jump to a given line |\r\n\r\n`info registers` - current register state for the selected stack frame\r\n\r\n`info threads` - list the active threads  \r\n`thread {num}` - switch focus to thread `{num}`\r\n\r\n`info inferiors` - list the debugged processes (when `detach-on-fork` is `off`)  \r\n`inferior {num}` - switch focus to a process `{num}`\r\n\r\n### Signals\r\n\r\nThe debugger intercepts some signals (e.g. SIGINT) and handles them. To send such a signal to the application we can use the `signal` command, e.g. `signal SIGINT`.\r\n\r\nState Control\r\n-------------\r\n\r\n### Process information\r\n\r\nWe can view currently debugged processes with the `info inferiors` command, and switch between them with `inferior {ID}`.\r\n\r\n`info proc` and its subcommands provide insight into the internals of the executing process, e.g.:\r\n\r\n```shell\r\ninfo proc\r\n# process 10372\r\n# cmdline = '/tmp/easy_tls_0_9_8o_stripped'\r\n# cwd = '/tmp'\r\n# exe = '/tmp/easy_tls_0_9_8o_stripped'\r\n```\r\n\r\n### Threads\r\n\r\n`info threads` to list the threads, `thread ID` to switch to a thread.\r\n\r\nWe can also execute a command on all the threads by using: `thread apply all`, for example `thread apply all bt`.\r\n\r\n### Shared libs\r\n\r\n`info proc exe` shows information about the main module\r\n\r\n`info dll` - shows the status of loaded libraries\r\n\r\n### Stack\r\n\r\n`bt` - shows the stack\r\n\r\n`f {num}` - selects a stack frame `{num}` as active\r\n`up` or `down` - moves up or down the stack\r\n\r\n### Code and Assembler\r\n\r\n`list` shows the current location in sources. You can also list a function by passing its name as parameters.\r\n\r\n`disassemble /s` shows the assembly code of the current function along with source code, if available. You can provide start and end addresses of any location in memory as parameters.\r\n\r\n### Memory\r\n\r\n`x` (examine)\r\n\r\n`mem read -tdouble -c10 arr` - read a count of 10 items of type double from an array\r\n\r\n`info proc mappings` lists memory regions occupied by the process.\r\n\r\n### Expressions (variables, registers, etc.)\r\n\r\n`info local` - show local variables  \r\n`info args` - show all arguments to the function  \r\n`info vars` - show all local variables\r\n\r\n`print EXP` allows executing a given expression and saving the result in history under some variable, e.g.:\r\n\r\n```shell\r\nprint $rcx\r\n# $1 = 0\r\n\r\n#  print the first 10 elements of the array arr\r\np *arr@10\r\n```\r\n\r\n`output` works similarly but doesn't save the result in history and doesn't insert a newline character.\r\n\r\nIn GDB, you may create custom variables with `set` for example, `set $t = my_var->t`.\r\n\r\nYou may use the output variable of the command to reference it:\r\n\r\n```\r\n(gdb) p x\r\n$12 = (int) 2\r\n```\r\n\r\nThe `$` is for the last variable in the output. To print structures we may use GDB functions\r\n\r\n`display EXP` - display variable on each debugger break (can be called multiple times)  \r\n`undisp {var}` - do not show the variable any longer\r\n\r\nExtensions\r\n----------\r\n\r\n### Python interpreter\r\n\r\nThe `python` command starts the Python interpreter, from where we can access the GDB interface through the gdb object, e.g.:\r\n\r\n```py\r\npython print (gdb.breakpoints())\r\n```\r\n\r\n### GUI / CUI\r\n\r\nInteresting extensions:\r\n\r\n- [gef](https://github.com/hugsy/gef)\r\n- [nnd](https://github.com/al13n321/nnd)\r\n\r\n{% endraw %}\r\n"
  },
  {
    "path": "guides/linux-tracing.md",
    "content": "---\r\nlayout: page\r\ntitle: Linux Kernel Tracing (/sys/kernel/tracing)\r\ndate: 2025-12-22 08:00:00 +0200\r\n---\r\n\r\n{% raw %}\r\n\r\n**Table of contents:**\r\n\r\n<!-- MarkdownTOC -->\r\n\r\n- [General information](#general-information)\r\n- [Collecting events](#collecting-events)\r\n- [Function tracing](#function-tracing)\r\n\r\n<!-- /MarkdownTOC -->\r\n\r\nGeneral information\r\n-------------------\r\n\r\nIf `/sys/kernel/tracing` is not available we may **mount it** with the following command:\r\n\r\n```shell\r\nmount -t tracefs nodev /sys/kernel/tracing\r\n```\r\n\r\nWriting to the buffer (trace / trace_pipe) is enabled globally by writing `1` to the file `/sys/kernel/tracing/tracing_on` (default value). If we write `0`, traces are still set up, but the kernel stops writing to the buffer. This is like a pause.\r\n\r\nCollecting events\r\n-----------------\r\n\r\n[Official documentation](https://docs.kernel.org/trace/events.html)\r\n\r\nThe list of events is available in the `available_events` file. We enable the tracer by sending the name to the `set_event` file or by setting `1` in the `enabled` file for events in the events directory (e.g., enabled in events/ will enable all events):\r\n\r\n```shell\r\n# events only\r\necho nop > current_tracer\r\n\r\n# clear trace\r\necho > trace\r\n\r\n# enable events\r\necho 1 > /sys/kernel/tracing/events/sched/sched_process_exec/enable\r\necho 1 > /sys/kernel/tracing/events/sched/sched_process_fork/enable\r\n\r\n# continuous reading or periodically cat /sys/kernel/tracing/trace\r\ncat /sys/kernel/tracing/trace_pipe\r\n\r\n# disable all events\r\necho 0 > /sys/kernel/tracing/events/enable\r\n```\r\n\r\nUsing the `trace_event=[event-list]` option in **boot options** we can enable very early tracing.\r\n\r\nWe can **filter** events by fields using the filter file in the given event's directory (events/). Additionally, filtering by PIDs is possible through the `set_event_pid` file. To automatically **filter forks and remove PIDs of processes that have ended**, you can set the `event-fork` option:\r\n\r\n```shell\r\necho 1 > options/event-fork\r\n\r\necho $$\r\n# 3187\r\necho 3187 > set_event_pid\r\n\r\n# clear trace\r\necho > trace\r\n\r\n# start tracing\r\necho 1 > events/sched/enable\r\n\r\nbash\r\n# in bash\r\n# [me@testbox tmp]$ echo $$\r\n# 7519\r\n\r\ncat set_event_pid\r\n# 3187\r\n# 7519\r\n\r\ncat trace\r\n\r\n# disable tracing\r\necho 0 > events/enable\r\n```\r\n\r\nCollected events can be found in `/sys/kernel/tracing/trace` (collection of recent events, for reading by us, new line clears it) or `/sys/kernel/tracing/trace_pipe` (event stream, events disappear after reading). Description of event fields can be found in the given event's directory, in the `format` file, e.g.:\r\n\r\n```shell\r\ncat events/sched/sched_process_exec/format\r\n# name: sched_process_exec\r\n# ID: 322\r\n# format:\r\n#     field:unsigned short common_type;   offset:0;   size:2; signed:0;\r\n#     field:unsigned char common_flags;   offset:2;   size:1; signed:0;\r\n#     field:unsigned char common_preempt_count;   offset:3;   size:1; signed:0;\r\n#     field:int common_pid;   offset:4;   size:4; signed:1;\r\n# \r\n#     field:__data_loc char[] filename;   offset:8;   size:4; signed:0;\r\n#     field:pid_t pid;    offset:12;  size:4; signed:1;\r\n#     field:pid_t old_pid;    offset:16;  size:4; signed:1;\r\n# \r\n# print fmt: \"filename=%s pid=%d old_pid=%d\", __get_str(filename), REC->pid, REC->old_pid\r\n```\r\n\r\nFunction tracing\r\n----------------\r\n\r\n[Official documentation](https://docs.kernel.org/trace/ftrace.html)\r\n\r\nFunction tracing feature should be enabled by default and it is controlled using `kernel.ftrace` global switch. To enable it, run:\r\n\r\n```sh\r\nsysctl kernel.ftrace_enabled=1\r\n```\r\n\r\n**Events/function calls** can be collected either aggregated (less invasive) or sequentially.\r\n\r\nTo enable statistics for (selected) kernel functions, we write `1` to `function_profile_enabled`. Statistics are collected for all functions listed in `available_filter_function`. We can filter these statistics by writing to `set_ftrace_filter` and `set_ftrace_notrace` (function) as well as `set_graph_function` and `set_graph_notrace` (function_graph). PIDs that interest us can be written to `set_ftrace_pid` or `set_ftrace_notrace_pid`. Call statistics can be found in `trace_stat/function<cpu>`. Example trace:\r\n\r\n```shell\r\necho 2594 > set_ftrace_pid\r\n\r\necho 1 > function_profile_enabled\r\n\r\n# collection time\r\n\r\necho 0 > function_profile_enabled\r\n\r\ncat trace_stat/function*\r\n```\r\n\r\nTo enable tracing of individual functions, we set the tracer to \"function\" (and possibly \"function_graph\") and read calls through `trace_pipe` or `trace`, as with events:\r\n\r\n```shell\r\n# enabling\r\necho 'tcp*' > set_ftrace_filter && echo function > current_tracer\r\n\r\n# collecting events from buffer\r\ncat trace > /tmp/tcp-trace.txt\r\n\r\n# disabling\r\necho nop > current_tracer && echo > set_ftrace_filter\r\n```\r\n\r\n{% endraw %}"
  },
  {
    "path": "guides/network-tracing-tools.md",
    "content": "---\nlayout: page\ntitle: Network tracing tools\ndate: 2024-01-01 08:00:00 +0200\nredirect_from:\n  - /guides/using-network-tracing-tools/\n---\n\n<!-- MarkdownTOC -->\n\n- [Testing connectivity](#testing-connectivity)\n- [Collecting network traces](#collecting-network-traces)\n    - [pktmon \\(Windows\\)](#pktmon-windows)\n    - [netsh \\(Windows\\)](#netsh-windows)\n    - [tcpdump \\(Linux\\)](#tcpdump-linux)\n- [Measuring network latency](#measuring-network-latency)\n- [Measuring network bandwidth](#measuring-network-bandwidth)\n- [Logging HTTP\\(S\\) requests in a proxy](#logging-https-requests-in-a-proxy)\n\n<!-- /MarkdownTOC -->\n\n## Testing connectivity\n\nIt is a common mistake to rely on ping when testing TCP connections. Ping uses a different protocol (ICMP) and although it is a fine tool to check if there is connectivity between two hosts (assuming ICMP traffic is not blocked), it will not tell us anything about opened TCP ports.\n\nOn **Linux**, to check if there is anything listening on a TCP port 80 on a remote host, you may use **netcat**:\n\n```shell\nnc -vnz 192.168.0.20 80\n```\n\nOn **Windows**, we may use the `Test-NetConnection` (`tnc`) cmdlet, for example:\n\n```sh\ntnc example.com -Port 443\n\n# ComputerName     : example.com\n# RemoteAddress    : 23.215.0.138\n# RemotePort       : 443\n# InterfaceAlias   : Ethernet\n# SourceAddress    : 192.168.88.164\n# TcpTestSucceeded : True\n```\n\nPsPing (a part of the [Sysinternals toolkit](https://technet.microsoft.com/en-us/sysinternals)) also has few interesting options when it comes to diagnosing network connectivity issues. The simplest usage is just a replacement for a ping.exe tool (performs ICMP ping):\n\n```shell\npsping www.google.com\n```\n\nBy adding a port number at the end of the host we will test a TCP handshake (or discover a closed port on the remote host):\n\n```shell\npsping www.google.com:80\n```\n\nTo test UDP add **-u** option on the command line.\n\n## Collecting network traces\n\nProbably the best tool to analyze network traffic is **[Wireshark](https://www.wireshark.org/)**. Of course, Wireshark may also collect network traffic. However, as it's a GUI application, you may have problems running it on servers. On Windows, Wireshark requires an npcap driver which might also generate problems. Therefore, a better choice might be to use command line tools that I discuss later in this ection.\n\nAnother problem in network traces is that they lack the ID of the process owning the network connection. We might get this information with the help of other tracing tools. For example, in [this blog post](https://lowleveldesign.org/2018/05/11/correlate-pids-with-network-packets-in-wireshark/), I present how to use Process Monitor logs for this purpose.\n\n### pktmon (Windows)\n\nSwitching to the command line tools, starting with **Window 10 (Server 2019)**, we have a new network tracing tool in our arsenal: **pktmon**. It groups packets per components in the network stack, which is especially helpful when monitoring virtualized applications. Here are some usage examples:\n\n```shell\n# List active components in the network stack\npktmon component list\n\n# Create a filter for TCP traffic for the 172.29.235.111 IP and the 8080 port\npktmon filter add -t tcp -i 172.29.235.111 -p 8080\n\n# Show the configured filters\npktmon filter list\n\n# Start the capturing session (-c) for all the components (--comp)\npktmon start -c --comp all && timeout -1 && pktmon stop\n\n# Start the capture session (-c) for all NICs only (--comp), logging the entire \n# packets (--pkt-size 0), overwriting the older packets when the output file \n# reaches 512MB (-m circular -s 512)\npktmon start -c --comp nics --pkt-size 0 -m circular -s 512 -f c:\\network-trace.etl && timeout -1 && pktmon stop\n```\n\nWe may later convert the etl file to open it in Wireshark: \n\n```shell\npktmon etl2pcap C:\\network-trace.etl --out C:\\network-trace.pcap\n```\n\nIf the pcap file contains duplicate network packets, it is probably because same packets were logged by different network components. We can use the `--comp` parameter also in the `etl2pcap` subcommand to filter the packets, for example:\n\n```shell\npktmon etl2pcap C:\\network-trace.etl --out C:\\network-trace.pcap --comp 12\n```\n\nIf you don't know the component number, you may use the `etl2txt` subcommand to list events in text format with their component IDs, and then pick the right component.\n\n### netsh (Windows)\n\nNetsh is another tool we could use for this purpose on Windows (even on **older Windows versions**). The **netsh trace {start\\|stop}** command will create an ETW-based network trace, allowing us to choose from a variety of diagnostics scenarios:\n\n```\n> netsh trace show scenarios\n\nAvailable scenarios (18):\n-------------------------------------------------------------------\nAddressAcquisition       : Troubleshoot address acquisition-related issues\nDirectAccess             : Troubleshoot DirectAccess related issues\nFileSharing              : Troubleshoot common file and printer sharing problems\nInternetClient           : Diagnose web connectivity issues\nInternetServer           : Set of HTTP service counters\nL2SEC                    : Troubleshoot layer 2 authentication related issues\nLAN                      : Troubleshoot wired LAN related issues\nLayer2                   : Troubleshoot layer 2 connectivity related issues\nMBN                      : Troubleshoot mobile broadband related issues\nNDIS                     : Troubleshoot network adapter related issues\nNetConnection            : Troubleshoot issues with network connections\nP2P-Grouping             : Troubleshoot Peer-to-Peer Grouping related issues\nP2P-PNRP                 : Troubleshoot Peer Name Resolution Protocol (PNRP) related issues\nRemoteAssistance         : Troubleshoot Windows Remote Assistance related issues\nVirtualization           : Troubleshoot network connectivity issues in virtualization environment\nWCN                      : Troubleshoot Windows Connect Now related issues\nWFP-IPsec                : Troubleshoot Windows Filtering Platform and IPsec related issues\nWLAN                     : Troubleshoot wireless LAN related issues\n```\n\n*NOTE: For DHCP traces you may check netsh dhcpclient trace ... commands. Also LAN and WLAN modes have some tracing capabilities which you may enable with a command netsh (w)lan set tracing mode=yes and stop with a command netsh (w)lan set tracing mode=no*\n\nTo know exactly which providers are enabled in each scenario use **netsh trace show scenario {scenarioname}**. After choosing the right scenario for your diagnosing case start the trace, for example:\n\n```shell\nnetsh trace start scenario=InternetClient capture=yes && timeout -1 && netsh trace stop\n```\n \nA new .etl file should be created in the output directory (as well as a .cab file with some interesting system logs). If you only need a trace file, you may add **report=no tracefile=d:\\temp\\net.etl** paramters. Some ETW providers do not generate information about the processes related to the specific events (for instance WFP provider) - keep this in mind when choosing your own set.\n\nMany interesting capture filters are available, you may use **netsh trace show CaptureFilterHelp** to list them. Most interesting include CaptureInterface, Protocol, Ethernet, IPv4, and IPv6 options set, for example:\n\n```shell\nnetsh trace start scenario=InternetClient capture=yes CaptureInterface=\"Local Area Connection 2\" Protocol=TCP Ethernet.Type=IPv4 IPv4.Address=157.59.136.1 maxSize=250 fileMode=circular overwrite=yes traceFile=c:\\temp\\nettrace.etl\n```\n\nWe can **convert the generated .etl file to .pcapng** with the [etl2pcapng](https://github.com/microsoft/etl2pcapng) tool, and open them in Wireshark.\n\n### tcpdump (Linux)\n\nMost commonly used tool to collect network traces on Linux is **tcpdump**. The BPF language is quite complex and allows various filtering options. A great explanation of its syntax can be found [here](http://www.biot.com/capstats/bpf.html). Below, you may find example session configurations.\n\n```shell\n# View traffic only between two hosts:\ntcpdump host 192.168.0.1 && host 192.168.0.2\n\n# View traffic in a particular network:\ntcpdump net 192.168.0.1/24\n\n# Dump traffic to a file and rotate it every 1KB:\ntcpdump -C 1024 -w test.pcap\n```\n\n## Measuring network latency\n\nOn **Windows**, we may use **psping**. We need to run it in a server mode on the connection target (-f for creating a temporary exception in the Windows Firewall, -s to enable server listening mode):\n\n```shell\npsping -f -s 192.168.1.3:4000\n```\n\nThen start the client and perform the test:\n\n```shell\npsping -l 16k -n 100 192.168.1.3:4000\n```\n\n## Measuring network bandwidth\n\n**iperf** is a tool that can measure bandwidth on Windows and Linux. We need to start the iperf server (-s) (the -e option is to enable enhanced output and -l sets the TCP read buffer size):\n\n```shell\niperf -s -l 128k -p 8080 -e\n```\n\nThen, for an example test, we may run the client for 30s (-t) using two parallel threads (-P) and showing interval summaries every 2s (-i):\n\n```shell\niperf -c 172.30.102.167 -p 8080 -l 128k -P 2 -i 2 -t 30\n```\n\nOn **Windows**, we may alternatively use **psping**. Again, we need to run it in a server mode on the connection target (-f for creating a temporary exception in the Windows Firewall, -s to enable server listening mode):\n\n```shell\npsping -f -s 192.168.1.3:4000\n```\n\nThen start the client and perform the test:\n\n```shell\npsping -b -l 16k -n 100 192.168.1.3:4000\n```\n\n## Logging HTTP(S) requests in a proxy\n\nIf you are on Windows, use the system settings to change the system proxy. On Linux, set the **HTTP_PROXY** and **HTTPS_PROXY** variables, for example:\n\n```bash\nexport HTTP_PROXY=\"http://localhost:8080\"\nexport HTTPS_PROXY=\"http://localhost:8080\"\n```\n\nWhen you make a request in code you should remember to configure its proxy according to the system settings, for exampe in C#:\n\n```csharp\nvar request = WebRequest.Create(url);\nrequest.Proxy = WebRequest.GetSystemWebProxy();\nrequest.Method = \"POST\";\nrequest.ContentType = \"application/json; charset=utf-8\";\n...\n```\n\nor in the configuration file:\n\n```xml\n  <system.net>\n    <defaultProxy>\n      <proxy autoDetect=\"False\" proxyaddress=\"http://127.0.0.1:8080\" bypassonlocal=\"False\" usesystemdefault=\"False\" />\n    </defaultProxy>\n  </system.net>\n```\n\nThen run [Fiddler](http://www.telerik.com/fiddler) (or [Burp Suite](https://portswigger.net/burp/) or any other proxy) and requests data should appear in the sessions window. Unfortunately, this approach won't work for requests to applications served on the local server. A workaround is to use one of the Fiddler's localhost alternatives in the url: `ipv4.fiddler`, `ipv6.fiddler` or `localhost.fiddler` (more [here](http://docs.telerik.com/fiddler/Configure-Fiddler/Tasks/MonitorLocalTraffic)).\n\n**NOTE for WCF clients**: WCF has its own proxy settings, to use the default proxy add an `useDefaultWebProxy=true` attribute to your binding.\n\nIf you want to trace HTTPS traffic you probably also need to **install the Root CA** of your proxy. On Windows, install the certificate to the Third-Party Root Certification Authorities. On Ubuntu Linux, run the following commands:\n\n```bash\nsudo mkdir /usr/share/ca-certificates/extra\nsudo cp mitmproxy.crt /usr/share/ca-certificates/extra/mitmproxy.crt\nsudo dpkg-reconfigure ca-certificates\n```\n\n*NOTE for Python*: if there is Python code that you need to trace, use `export REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt` to force Python to validate TLS certs with your system cert store.\n\nIf you would like to apply custom modifications to the proxied requests, you should consider implementing your own network proxy. I present several C# examples of such proxies in [a blog post](https://lowleveldesign.wordpress.com/2020/02/03/writing-network-proxies-for-development-purposes-in-c/) on my blog.\n"
  },
  {
    "path": "guides/using-withdll-and-detours-to-trace-winapi.md",
    "content": "---\nlayout: page\ntitle: Using withdll and detours to trace Win API calls \ndate: 2023-11-25 08:00:00 +0200\n---\n\n**Table of contents:**\n\n<!-- MarkdownTOC -->\n\n- [Introducing withdll](#introducing-withdll)\n- [Detours syelog library and log collector \\(syelogd.exe\\)](#detours-syelog-library-and-log-collector-syelogdexe)\n- [Detours sample libraries that log Win API functions calls](#detours-sample-libraries-that-log-win-api-functions-calls)\n- [Injecting libraries with withdll](#injecting-libraries-with-withdll)\n\n<!-- /MarkdownTOC -->\n\n## Introducing withdll\n\nThe [Detours](https://github.com/microsoft/Detours) repository contains many interesting samples, some of which could be particularly useful in software troubleshooting. Inspired by one of those samples, named withdll, I created my clone of it in C# with some additional features. In this guide, I will present to you how you may use withdll with Detours samples to collect traces of Win API calls. \n\n## Detours syelog library and log collector (syelogd.exe)\n\nDetours developers implemented a logging library, syelog, based on Windows named pipes. As you may see in the sltest example, it is straightforward to use. We may receive the logged messages with the syelogd application (also a Detours sample). Here is the result of running sltest and syelogd in separate console windows:\n\n![](/assets/img/withdll-sltest-sylogd.png)\n\nEach syelog message has a timestamp, process ID, facility number, severity code, and the textual message. Syelogd prints them in separate columns in the output. The timestamp could be either absolute (as in the example output) or relative to the last received message if you use the /d option. Having covered the receiver, let us focus on the senders.\n\n## Detours sample libraries that log Win API functions calls\n\nThe Detours repository contains a few syelog-based tracers. The most thorough tracer is [**traceapi**](https://github.com/microsoft/Detours/tree/main/samples/traceapi). It hooks [a vast number of Win32 API functions](https://github.com/microsoft/Detours/blob/main/samples/traceapi/_win32.cpp). More tailored loggers include:\n\n- [**tracemem**](https://github.com/microsoft/Detours/tree/main/samples/tracemem) to trace heap allocations \n- [**tracereg**](https://github.com/microsoft/Detours/tree/main/samples/tracereg) to trace registry operations \n- [**tracetcp**](https://github.com/microsoft/Detours/tree/main/samples/tracetcp) to trace TCP connections \n- [**tracessl**](https://github.com/microsoft/Detours/tree/main/samples/tracessl) to trace plain text messages sent over TLS (it hooks EncryptMessage and DecryptMessage functions) \n\nAnd, if we are not satisfied with the examples provided, it is quite easy to create a custom tracer (you may start by adding new hooks to, for example, trcmem.cpp). \n\nThe last step to start collecting Win API traces is to put the tracing libraries into the memory of the process that we want to analyze. And that is the place where withdll comes to the rescue.\n\n## Injecting libraries with withdll\n\nThe detours repository already contains a withdll sample that wraps the DetoursCreateProcessWithDlls function and allows you to start a new process with given DLLs injected. Unfortunately, it does not allow injecting DLLs into a running process. I decided to implement this feature in my version of withdll, and, to make it a bit more interesting, I reimplemented it in C#. Thanks to the excellent [win32metadata](https://github.com/microsoft/win32metadata) and [cswin32](https://github.com/microsoft/cswin32) projects, I could [easily generate C# bindings for structures and functions defined in the detours’ header](https://lowleveldesign.wordpress.com/2023/11/23/generating-c-bindings-for-native-windows-libraries/). You may download the compiled executable from the [release page](https://github.com/lowleveldesign/withdll/releases). I also added the detours sample tracers and syelogd.exe, so you may quickly run the first tracing session 😊.  \n\nWithdll is a 64-bit application (compiled with NativeAOT and statically linked with the detours library) but supports both 32-bit and 64-bit targets. An example command line to inject a DLL into a running process with PID 1234 may look as follows: \n\n```\nwithdll.exe -d trcapi32.dll 1234\n```\n\nAnd to start, for example, winver.exe with injected traceapi libraries, you may run:\n\n```\nwithdll.exe -d trcapi64.dll C:\\Windows\\System32\\winver.exe\nwithdll.exe -d trcapi32.dll C:\\Windows\\SysWow64\\winver.exe\n```\n\nPlease note that you may inject multiple DLLs at once. If you compile a library for 32-bit and 64-bit architectures, add a “bitness suffix” to its base name, and withdll will replace the suffix if the target process is 32-bit. For example, if we have trcapi32.dll and trcapi64.dll in the same folder and we run `withdll.exe -d trcapi64.dll C:\\Windows\\SysWow64\\winver.exe`, winver.exe instance will have trcapi32.dll in its loaded module list. \n\nFinally, if you would like to **always inject a DLL into a given application**, you may use the Image File Execution Option registry key. However, to profit from this key, withdll must play the role of a debugger when launching the application. Therefore, when defining a Debugger value key, add an additional `--debug` switch to the withdll command, for example: \n\n```\nWindows Registry Editor Version 5.00\n\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\winver.exe]\n\"Debugger\"=\"c:\\\\tools\\\\withdll.exe --debug -d c:\\\\tools\\\\trcapi64.dll\"\n```\n\nI also recorded a short video presenting the usage of withdll with the traceapi sample library: \n\n[![Using detours and withdll to trace Win API calls](https://img.youtube.com/vi/q_iBojsF1sA/mqdefault.jpg)](https://www.youtube.com/watch?v=q_iBojsF1sA)\n"
  },
  {
    "path": "guides/windbg.md",
    "content": "---\nlayout: page\ntitle: WinDbg usage guide\ndate: 2026-02-20 08:00:00 +0200\nredirect_from:\n    - /guides/using-ttd/\n    - /guides/using-windbg/\n---\n\n{% raw %}\n\n**Table of contents:**\n\n<!-- MarkdownTOC -->\n\n- [Installing WinDbg](#installing-windbg)\n    - [WinDbgX \\(WinDbgNext, formely WinDbg Preview\\)](#windbgx-windbgnext-formely-windbg-preview)\n    - [Classic WinDbg](#classic-windbg)\n    - [Extensions](#extensions)\n- [Configuring WinDbg](#configuring-windbg)\n    - [Referencing extensions and scripts for easy access](#referencing-extensions-and-scripts-for-easy-access)\n    - [Installing WinDbg as the Windows AE debugger](#installing-windbg-as-the-windows-ae-debugger)\n- [Controlling the debugging session](#controlling-the-debugging-session)\n    - [Enable local kernel-mode debugging](#enable-local-kernel-mode-debugging)\n    - [Setup Windows Kernel Debugging over network](#setup-windows-kernel-debugging-over-network)\n    - [Debugging system services \\(local remote debugging\\)](#debugging-system-services-local-remote-debugging)\n    - [Getting information about the debugging session](#getting-information-about-the-debugging-session)\n- [Symbols and modules](#symbols-and-modules)\n- [Working with memory](#working-with-memory)\n    - [General memory commands](#general-memory-commands)\n    - [Stack](#stack)\n    - [Variables](#variables)\n    - [Strings](#strings)\n    - [Fixed size arrays](#fixed-size-arrays)\n- [Analyzing exceptions and errors](#analyzing-exceptions-and-errors)\n    - [Reading the exception record](#reading-the-exception-record)\n    - [Find Windows Runtime Error message](#find-windows-runtime-error-message)\n    - [Find the C++ exception object in the SEH exception record](#find-the-c-exception-object-in-the-seh-exception-record)\n    - [Read the Last Windows Error value](#read-the-last-windows-error-value)\n    - [Scanning the stack for native exception records](#scanning-the-stack-for-native-exception-records)\n    - [Finding exception handlers](#finding-exception-handlers)\n    - [Breaking on a specific exception event](#breaking-on-a-specific-exception-event)\n    - [Breaking on a specific Windows Error](#breaking-on-a-specific-windows-error)\n    - [Breaking on a function return](#breaking-on-a-function-return)\n    - [Decoding error numbers](#decoding-error-numbers)\n- [Diagnosing dead-locks and hangs](#diagnosing-dead-locks-and-hangs)\n    - [Listing threads call stacks](#listing-threads-call-stacks)\n    - [Finding locks in memory dumps](#finding-locks-in-memory-dumps)\n- [System objects in the debugger](#system-objects-in-the-debugger)\n    - [Processes \\(kernel-mode\\)](#processes-kernel-mode)\n    - [Handles](#handles)\n    - [Threads](#threads)\n    - [Critical sections](#critical-sections)\n- [Controlling process execution](#controlling-process-execution)\n    - [Controlling the target \\(g, t, p\\)](#controlling-the-target-g-t-p)\n    - [Watch trace](#watch-trace)\n    - [Breaking when a specific function is in the call stack](#breaking-when-a-specific-function-is-in-the-call-stack)\n    - [Breaking on a specific function enter and leave](#breaking-on-a-specific-function-enter-and-leave)\n    - [Breaking for all methods in the C++ object virtual table](#breaking-for-all-methods-in-the-c-object-virtual-table)\n    - [Breaking when a user-mode process is created \\(kernel-mode\\)](#breaking-when-a-user-mode-process-is-created-kernel-mode)\n    - [Setting a user-mode breakpoint in kernel-mode](#setting-a-user-mode-breakpoint-in-kernel-mode)\n- [Scripting the debugger](#scripting-the-debugger)\n    - [Using meta-commands \\(legacy way\\)](#using-meta-commands-legacy-way)\n    - [Using the dx command](#using-the-dx-command)\n        - [Using variables and creating new objects in the dx query](#using-variables-and-creating-new-objects-in-the-dx-query)\n        - [Using text files](#using-text-files)\n        - [Example queries with explanations](#example-queries-with-explanations)\n        - [Managed application support in the dx queries](#managed-application-support-in-the-dx-queries)\n    - [Using the JavaScript engine](#using-the-javascript-engine)\n        - [Loading a script](#loading-a-script)\n        - [Running a script](#running-a-script)\n        - [Working with types](#working-with-types)\n        - [Accessing the debugger engine objects](#accessing-the-debugger-engine-objects)\n        - [Evaluating expressions in a debugger context](#evaluating-expressions-in-a-debugger-context)\n        - [Debugging a script](#debugging-a-script)\n    - [Launching commands from a script file](#launching-commands-from-a-script-file)\n- [Time Travel Debugging \\(TTD\\)](#time-travel-debugging-ttd)\n    - [Installation](#installation)\n    - [Collection](#collection)\n    - [Accessing TTD data](#accessing-ttd-data)\n    - [Querying debugging events](#querying-debugging-events)\n    - [Examining function calls](#examining-function-calls)\n    - [Position in TTD trace](#position-in-ttd-trace)\n    - [Examining memory access](#examining-memory-access)\n- [Misc tips](#misc-tips)\n    - [Converting a memory dump from one format to another](#converting-a-memory-dump-from-one-format-to-another)\n    - [Loading an arbitrary DLL into WinDbg for analysis](#loading-an-arbitrary-dll-into-windbg-for-analysis)\n    - [Keyboard and mouse shortcuts](#keyboard-and-mouse-shortcuts)\n    - [Running a command for all the processes](#running-a-command-for-all-the-processes)\n    - [Attaching to multiple processes at once](#attaching-to-multiple-processes-at-once)\n    - [Injecting a DLL into a process being debugged](#injecting-a-dll-into-a-process-being-debugged)\n    - [Save and reopen formatted WinDbg output](#save-and-reopen-formatted-windbg-output)\n\n<!-- /MarkdownTOC -->\n\nInstalling WinDbg\n-----------------\n\nThere are two versions of WinDbg available nowadays. The modern one, called WinDbgX or WinDbg Preview, and the old one. The modern WinDbg has many interesting features (support for Time-Travel debugging is one of them), so that's the version you probably want to use if you're on a supported system.\n\n### WinDbgX (WinDbgNext, formely WinDbg Preview)\n\nOn modern systems download the [appinstaller](https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/) file and choose Install in the context menu. If you are on Windows Server 2019 and you don't see the Install option in the context menu, there is a big chance you're missing the App Installer package on your system. In that case, you may download and run [this PowerShell script](/assets/other/windbg-install.ps1.txt) ([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).\n\n### Classic WinDbg\n\nIf you need to debug on an old system with no support for WinDbgX, you need to download Windows SDK and install the Debugging Tools for Windows feature. Executables will be in the Debuggers folder, for example, `c:\\Program Files (x86)\\Windows Kits\\10\\Debuggers`.\n\n### Extensions\n\nSome problems may require actions that are challenging to achieve using the default WinDbg commands. One solution is to create a debugger script using the [legacy scripting language](https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/command-tokens), the [dx command](https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/dx--display-visualizer-variables-), or the [JavaScript Debugger](https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/javascript-debugger-scripting). Another option is to search for an extension that may already have the desired feature implemented. Here's a list of extensions I use daily when troubleshooting user-mode issues:\n\n- [PDE](https://onedrive.live.com/?authkey=%21AJeSzeiu8SQ7T4w&id=DAE128BD454CF957%217152&cid=DAE128BD454CF957) by Andrew Richards - contains lots of useful commands (run `!pde.help` to learn more)\n- [lldext](https://github.com/lowleveldesign/lldext) - contains my utility commands and scripts\n- [comon](https://github.com/lowleveldesign/comon) - contains commands to help debug COM services\n- [MEX](https://www.microsoft.com/en-us/download/details.aspx?id=53304) - another extension with many helper commands (run `!mex.help` to list them)\n- [dotnet-sos](https://learn.microsoft.com/en-us/dotnet/core/diagnostics/dotnet-sos) - to debug .NET applications\n\nAdditionally, you may also check the following repositories containing WinDbg scripts for various problems:\n\n- [TimMisiak/WinDbgCookbook](https://github.com/TimMisiak/WinDbgCookbook)\n- [hugsy/windbg_js_scripts](https://github.com/hugsy/windbg_js_scripts)\n- [0vercl0k/windbg-scripts](https://github.com/0vercl0k/windbg-scripts)\n- [yardenshafir/WinDbg_Scripts](https://github.com/yardenshafir/WinDbg_Scripts)\n\nConfiguring WinDbg\n------------------\n\n### Referencing extensions and scripts for easy access\n\nWhen we use the `.load` or `.scriptload` commands, WinDbg will search for extensions in the following folders:\n\n- `{install_folder}\\{target_arch}\\winxp`\n- `{install_folder}\\{target_arch}\\winext`\n- `{install_folder}\\{target_arch}\\winext\\arcade`\n- `{install_folder}\\{target_arch}\\pri`\n- `{install_folder}\\{target_arch}`\n- `%LOCALAPPDATA%\\DBG\\EngineExtensions32` or `%LOCALAPPDATA%\\DBG\\EngineExtensions` (only WinDbgX)\n- `%PATH%`\n\nwhere target_arch is either x86 or amd64.\n\nI usually include the directories containing the JavaScript scripts in the PATH since they are architecture-agnostic. As for the 32- and 64-bit DLLs, I store them in EngineExtensions32 and EngineExtensions folders, respectively.\n\nIt is also possible to configure [extensions galleries](https://github.com/microsoft/WinDbg-Samples/tree/master/Manifest). Unfortunately, I didn't manage to make it work with my own extensions.\n\n### Installing WinDbg as the Windows AE debugger\n\nThe `windbgx -I` command registers WinDbg as the automatic system debugger - it will launch anytime an application crashes. The modified AeDebug registry keys:\n\n```\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\nHKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\n```\n\nHowever, we may also use configure those keys manually and use WinDbg to, for example, create a memory dump when the application crashes:\n\n```\nREG_SZ Debugger = \"C:\\Users\\me\\AppData\\Local\\Microsoft\\WindowsApps\\WinDbgX.exe\" -c \".dump /ma /u C:\\dumps\\crash.dmp; qd\" -p %ld -e %ld -g\nREG_SZ Auto = 1\n```\n\nIf you miss the -g option, WinDbg will inject a remote thread with a breakpoint instruction, which will hide our original exception. In such case, you might need to scan the stack to find the original exception record.\n\nControlling the debugging session\n---------------------------------\n\n### Enable local kernel-mode debugging\n\nIf you are a software developer, you may not have much experience with kernel debugging. But it can be very useful to know how to inspect kernel objects in some cases. For instance, you can troubleshoot thread waits in kernel-mode more effectively and find out the causes of dead-locks or hangs faster.\n\nTo do full kernel debugging (so to control the kernel code execution) you need another Windows machine. But if you just want to analyse the kernel internal memory, you can enable local kernel debugging on your own machine. This is how you do it:\n\n```shell\nbcdedit /debug on\n```\n\nAfter a restart, you should be able to attach to your local kernel from WinDbg.\n\nAnother option is to use [LiveKd](https://learn.microsoft.com/en-us/sysinternals/downloads/livekd) which creates a snaphost of the kernel memory and attaches a debugger to it. It is also capable of creating a kernel memory dump for later analysis. An example command to create such a dump looks as follows:\n\n```shell\nlivekd -accepteula -b -vsym -k \"c:\\Program Files (x86)\\Windows Kits\\10\\Debuggers\\x64\\kd.exe\" -o c:\\tmp\\kernel.dmp\n```\n\n**You don't need to boot the system in debugging mode to use livekd.** So it is safe to use even in production environments.\n\n### Setup Windows Kernel Debugging over network\n\nTurn on network debugging (HOSTIP is the address of the machine on which we will run the debugger):\n\n```sh\nbcdedit /dbgsettings NET HOSTIP:192.168.0.2 PORT:60000\n# Key=3ma3qyz02ptls.23uxbvnd0e2zh.1gnwiqb6v3mpb.mjltos9cf63x\n\nbcdedit /debug {current} on\n# The operation completed successfully.\n```\n\nThen on the host machine, run windbg, select **Attach to kernel** and fill the port and key textboxes.\n\nWhen debugging a **Hyper-V Gen 2 VM** remember to turn off the secure booting:\n\n```sh\nSet-VMFirmware -VMName \"Windows 2012 R2\" -EnableSecureBoot Off -Confirm\n```\n\nIf you are hosting your guest on **QEMU KVM** and want to use network debugging, you need to either create your VM as a Generic one (not Windows) or update the VM configuration XML, changing the vendor_id under the hyperv node, for example:\n\n```xml\n<domain type=\"kvm\">\n  <name>win2k19</name>\n  <!-- ... -->\n  <features>\n    <acpi/>\n    <apic/>\n    <hyperv mode=\"custom\">\n      <relaxed state=\"on\"/>\n      <vapic state=\"on\"/>\n      <spinlocks state=\"on\" retries=\"8191\"/>\n      <vendor_id state=\"on\" value=\"KVMKVMKVM\"/>\n    </hyperv>\n    <!-- ... -->\n  </features>\n  <!-- ... -->\n</domain> \n```\n\nI highly recommend checking [this post by the OSR team](https://www.osr.com/blog/2021/10/05/using-windbg-over-kdnet-on-qemu-kvm/) describing why those changes are required and revealing some details about the kdnet inner working. \n\n### Debugging system services (local remote debugging)\n\nAttaching a debugger to a Windows service running in session 0 should not be a problem, assuming you have the SeDebugPrivilege and can access the service. However, debugging the service startup process can be challenging.\n\nI typically use a WinDbg remote session over named pipes along with the Image File Execution Options registry key. The approach involves starting the service under a debugger (using the -server option), both running in session 0, and then connecting to the debugger server from a local debugger instance. Here is  an example registry configuration for a testservice.exe:\n\n```\nWindows Registry Editor Version 5.00\n\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\myapp.exe]\n\"Debugger\"=\"windbgx.exe -Q -server npipe:pipe=svcpipe\"\n```\n\nWhen the testservice starts, the debugger server will wait for the client to connect. You may start the client with the following command:\n\n```sh\nwindbgx -remote \"npipe:pipe=svcpipe,server=localhost\"\n```\n\nIf the Windows Service Manager stops the service before you manage to connect to it, you may need to adjust the service start timeout. For example, to set it to 3 minutes (180000 ms), use the following registry configuration:\n\n```\nWindows Registry Editor Version 5.00\n\n[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control]\n\"ServicesPipeTimeout\"=dword:0002bf20\n```\n\nTo terminate the entire session and exit the debugging server, use the `q` command. To exit from one debugging client without terminating the server, you must issue a command from that specific client. If this client is KD or CDB, use the CTRL+B key to exit. If you are using a script to run KD or CDB, use `.remote_exit`.\n\n### Getting information about the debugging session\n\nThe `|` command displays a path to the process image. You may run `vercommand` to check how the debugger was launched. The `vertarget` command shows the OS version, the process lifetime, and more, for example, the dump time when debugging a memory dump. The `.time` command displays information about the system time variable (session time).\n\n`.lastevent` shows the last reason why the debugger stopped and `.eventlog` displays the recent events.\n\nSymbols and modules\n-------------------\n\nThe `lm` command lists all modules with symbol load info. To examine a specific module, use `lmvm {module-name}`. To find out if a given address belongs to any of the loaded dlls you may use the `!dlls -c {addr}` command. Another way would be to use the `lma {addr}` command.\n\nThe `.sympath` command shows the symbol search path and allows its modification. Use `.reload /f {module-name}` to reload symbols for a given module.\n\nThe `x {module-name}!{function}` command resolves a function address, and `ln {address}` finds the nearest symbol.\n\nIn WinDbgX, we may also list and filter modules with the `@$curprocess.Modules` property. Some usage examples:\n\n```shell\n# Display information about the win32u module\ndx @$curprocess.Modules[\"win32u.dll\"]\n\n# Show public exports of the win32u module\ndx @$curprocess.Modules[\"win32u.dll\"].Contents.Exports\n\n# List modules with information if they have combase.dll as a direct import\ndx -g @$curprocess.Modules.Select(m => new { Name = m.Name, HasCombase = m.Contents.Imports.Any(i => i.ModuleName == \"combase.dll\") })\n```\n\n**When we don't have access to the symbol server**, we may create a list of required symbols with `symchk.exe` (part of the Debugging Tools for Windows installation) and download them later on a different host. First, we need to prepare the manifest, for example:\n\n```shell\nsymchk /id test.dmp /om test.dmp.sym /s C:\\non-existing\n```\n\nThen copy it to the machine with the symbol server access, and download the required symbols, for example:\n\n```shell\nsymchk /im test.dmp.sym /s SRV*C:\\symbols*https://msdl.microsoft.com/download/symbols\n```\n\nIf **you want to add a PDB file (or files) to an existing symbol store**, you may use the `symstore add` command, for example:\n\n```sh\n# /r – recursive, /o – verbose output, /f – a path to files to index (@ symbol before the name denotes a file which contains the list of files)\n# /s – root directory of the store, /t – product name, /v – version, /c – comment\nsymstore add /r /o /f C:\\src\\myapp\\bin /s \\\\symsrv\\symbols\\ /t myapp /v '1.0.1' /c 'rel 1.0.1'\n```\n\nWorking with memory\n-------------------\n\n### General memory commands\n\nThe `!address` command shows information about a specific region of memory, for example:\n\n```shell\n!address 0x00fd7df8\n# Usage:                  Image\n# Base Address:           00fd6000\n# End Address:            00fdc000\n# Region Size:            00006000 (  24.000 kB)\n# State:                  00001000          MEM_COMMIT\n# Protect:                00000002          PAGE_READONLY\n# Type:                   01000000          MEM_IMAGE\n# Allocation Base:        00fb0000\n# Allocation Protect:     00000080          PAGE_EXECUTE_WRITECOPY\n# ...\n```\n\nAdditionally, it can display regions of memory of specific type, for example:\n\n```shell\n!address -f:FileMap\n#   BaseAddr EndAddr+1 RgnSize     Type       State                 Protect             Usage\n# -----------------------------------------------------------------------------------------------\n#   9a0000   9b0000    10000 MEM_MAPPED  MEM_COMMIT  PAGE_READWRITE                     MappedFile \"PageFile\"\n#   9b0000   9b1000     1000 MEM_MAPPED  MEM_COMMIT  PAGE_READONLY                      MappedFile \"PageFile\"\n\n!address -f:MEM_MAPPED\n#   BaseAddr EndAddr+1 RgnSize     Type       State                 Protect             Usage\n# -----------------------------------------------------------------------------------------------\n#   9a0000   9b0000    10000 MEM_MAPPED  MEM_COMMIT  PAGE_READWRITE                     MappedFile \"PageFile\"\n#   9b0000   9b1000     1000 MEM_MAPPED  MEM_COMMIT  PAGE_READONLY                      MappedFile \"PageFile\"\n```\n\n### Stack\n\nStack grows from high to low addresses. Thus, when you see addresses bigger than the frame base (such as ebp+C) they usually refer to the function arguments. Smaller addresses (such as ebp-20) usually refer to local function variables.\n\nTo display stack frames use the `k` command. The `kP` command will additionally print function arguments if private symbols are available. The `kbM` command outputs stack frames with first three parameters passed on the stack (those will be first three parameters of the function in x86).\n\nWhen there are many threads running in a process it's common that some of them have the same call stacks. To better organize call stacks we can use the `!uniqstack` command. Adding -b parameter adds first three parameters to the output, -v displays all parameters (but requires private symbols).\n\nTo switch a local context to a different stack frame we can use the `.frame` command:\n\n```shell\n.frame [/c] [/r] [FrameNumber]\n.frame [/c] [/r] = BasePtr [FrameIncrement]\n.frame [/c] [/r] = BasePtr StackPtr InstructionPtr\n```\n\nThe `!for_each_frame` extension command enables you to execute a single command repeatedly, once for each frame in the stack.\n\nIn WinDbgX, we may access the call stack frames using `@$curstack.Frames`, for example:\n\n```shell\ndx @$curstack.Frames\n# @$curstack.Frames\n#     [0x0]            : ntdll!LdrpDoDebuggerBreak + 0x30 [Switch To]\n#     [0x1]            : ntdll!LdrpInitializeProcess + 0x1cfa [Switch To]\n\ndx @$curstack.Frames[0].Attributes\n# InstructionOffset : 0x7ffa1102b784\n# ReturnOffset     : 0x7ffa1102e9d6\n# FrameOffset      : 0xea5055f370\n# StackOffset      : 0xea5055f340\n# FuncTableEntry   : 0x0\n# Virtual          : 1\n# FrameNumber      : 0x0\n# SourceInformation\n```\n\n### Variables\n\nWhen you have private symbols you may list local variables with the `dv` command.\n\nAdditionally the `dt` command allows you to work with type symbols. You may either list them, eg.: `dt notepad!g_*` or dump a data address using a given type format, eg.: `dt nt!_PEB 0x13123`.\n\nThe `dx` command allows you to dump local variables or read them from any place in the memory. It uses a navigation expressions just like Visual Studio (you may define your own file .natvis files). You load the interesting .natvis file with the `.nvload` command.\n\n`#FIELD_OFFSET(Type, Field)` is an interesting operator which returns the offset of the field in the type, eg. `? #FIELD_OFFSET(_PEB, ImageSubsystemMajorVersion)`.\n\n### Strings\n\nThe `!du` command from the [PDE extension](https://onedrive.live.com/redir?resid=DAE128BD454CF957!7152&authkey=!AJeSzeiu8SQ7T4w&ithint=folder%2czip) shows strings up to 4GB (the default du command stops when it hits the range limit).\n\nThe PDE extension also contains the `!ssz` command to look for zero-terminated (either unicode or ascii) strings. To change a text in memory use `!ezu`, for example: `ezu  \"test string\"`. The extension works on committed memory.\n\nAnother interesting command is `!grep`, which allows you to filter the output of other commands: `!grep _NT !peb`.\n\n### Fixed size arrays\n\nPrinting an array of a specific size with dx might be tricky. The code below shows two ways of printing a fixed-size char array:\n\n```sh\ndx (*((char (*)[16])0x31aa5526)),c\n# (*((jvm!char (*)[16])0x31aa5526)),c                 [Type: char [16]]\n#     [0]              : 106 'j' [Type: char]\n#     ...\n#     [15]             : 116 't' [Type: char]\n\ndx ((char*)0x31aa5526),16c\n# ((char*)0x31aa5526),16c                 : 0x31aa5526 [Type: char *]\n#     [0]              : 106 'j' [Type: char]\n#     ...\n#     [15]             : 116 't' [Type: char]\n```\n\nAltenatively, we could use `db 0x31aa5526 L10`.\n\nAnalyzing exceptions and errors\n-------------------------------\n\n### Reading the exception record\n\nThe  `.ecxr` debugger command instructs the debugger to restore the thread context to its state when the initial fault happened. When dispatching a SEH exception, the OS builds an internal structure called an `exception record`. It also conveniently saves the thread context at the time of the initial fault in a context record structure.\n\n```cpp\ntypedef struct _EXCEPTION_RECORD {\n  DWORD                    ExceptionCode;\n  DWORD                    ExceptionFlags;\n  struct _EXCEPTION_RECORD *ExceptionRecord;\n  PVOID                    ExceptionAddress;\n  DWORD                    NumberParameters;\n  ULONG_PTR                ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS];\n} EXCEPTION_RECORD;\n```\n\n`.lastevent` will also show you information about the last error that occured (if the debugger stopped because of an error). You may then examine the exception record using the `.exr` command, for example:\n\n```sh\n.lastevent\n# Last event: 15ae8.133b4: CLR exception - code e0434f4d (first/second chance not available)\n#   debugger time: Thu Jul 30 19:23:53.169 2015 (UTC + 2:00)\n\n.exr -1\n# ExceptionAddress: 000007fe9b17f963\n#    ExceptionCode: e0434f4d (CLR exception)\n#   ExceptionFlags: 00000000\n# NumberParameters: 0\n```\n\nIf we look at the raw memory, we will find that .exr changes the order of the EXCEPTION_RECORD fields, for example:\n\n```sh\n.exr 0430af24\n# ExceptionAddress: abe8f04d\n#    ExceptionCode: c0000005 (Access violation)\n#   ExceptionFlags: 00000000\n# NumberParameters: 2\n#    Parameter[0]: 00000000\n#    Parameter[1]: abe8f04d\n```\n\n```\n0430af24  c0000005 <- exception code\n0430af28  00000000\n0430af2c  00000000\n0430af30  abe8f04d <- exception address (code address)\n0430af34  00000002 <- parameters number\n0430af38  00000000\n0430af3c  abe8f04d\n```\n\n### Find Windows Runtime Error message\n\nIf you need to diagnose Windows Runtime Error for example: `(2f88.3358): Windows Runtime Originate Error - code 40080201 (first chance)`, you may enable first chance notification for this error: `sxe 40080201`. When stopped, retrieve the exception context, and the third parameter should contain an error message:\n\n```sh\n.exr -1\n# ExceptionAddress: 77942822 (KERNELBASE!RaiseException+0x00000062)\n#    ExceptionCode: 40080201 (Windows Runtime Originate Error)\n#   ExceptionFlags: 00000000\n# NumberParameters: 3\n#    Parameter[0]: 80040155\n#    Parameter[1]: 00000052\n#    Parameter[2]: 0dddf680\n\ndu 0dddf680\n# 0dddf680  \"Failed to find proxy registratio\"\n# 0dddf6c0  \"n for IID: {xxxxxxxx-xxxx-xxxx-x\"\n# 0dddf700  \"xxx-xxxxxxxxxxxx}.\"\n```\n\nWe may automate this step by using the `$exr_param2` pseudo-register:\n\n```sh\nsxe -c \"du @$exr_param2 L40; g\" 40080201\n```\n\n### Find the C++ exception object in the SEH exception record\n\n*(Tested on MSVC140)*\n\nIf it's the first chance exception, we can find the exception record at the top of the stack:\n\n```sh\ndps @esp\n# 00f3fb28  7657ec52 KERNELBASE!RaiseException+0x62\n# 00f3fb2c  00f3fb30\n# 00f3fb30  e06d7363\n# 00f3fb34  00000001\n# 00f3fb38  00000000\n# 00f3fb3c  7657ebf0 KERNELBASE!RaiseException\n# 00f3fb40  00000003\n# 00f3fb44  19930520\n# 00f3fb48  00f3fbd8\n# 00f3fb4c  009ab96c exceptions!_TI3?AVinvalid_argumentstd\n```\n\nWith dx and the `MSVCP140D!EHExceptionRecord` symbol (without this symbol, we need to get the value from `.exr -1`), we may decode the exception record parameters:\n\n```sh\ndx -r2 (MSVCP140D!EHExceptionRecord*)0x00f3fb30\n# (MSVCP140D!EHExceptionRecord*)0x00f3fb30                 : 0xf3fb30 [Type: EHExceptionRecord *]\n#     [+0x000] ExceptionCode    : 0xe06d7363 [Type: unsigned long]\n#     [+0x004] ExceptionFlags   : 0x1 [Type: unsigned long]\n#     [+0x008] ExceptionRecord  : 0x0 [Type: _EXCEPTION_RECORD *]\n#     [+0x00c] ExceptionAddress : 0x7657ebf0 [Type: void *]\n#     [+0x010] NumberParameters : 0x3 [Type: unsigned long]\n#     [+0x014] params           [Type: EHExceptionRecord::EHParameters]\n#         [+0x000] magicNumber      : 0x19930520 [Type: unsigned long]\n#         [+0x004] pExceptionObject : 0xf3fbd8 [Type: void *]\n#         [+0x008] pThrowInfo       : 0x9ab96c [Type: _s_ThrowInfo *]\n```\n\nAs you can see, the second parameter points to the C++ exception object. If we know its type, we may dump its properties, for example:\n\n```sh\ndx (exceptions!std::invalid_argument*)0x00f3fbd8 \n#   [+0x004] _Data            : __std_exception_data\n\ndx -r1 (*((exceptions!__std_exception_data *)0xf3fbdc))\n# (*((exceptions!__std_exception_data *)0xf3fbdc))                 [Type: __std_exception_data]\n#     [+0x000] _What            : 0x1449748 : \"arg1\" [Type: char *]\n#     [+0x004] _DoFree          : true [Type: bool]\n```\n\n### Read the Last Windows Error value\n\nTo get the last error value for the current thread we may use the `!gle` or `!teb` command. `!gle` has an additional -all parameter which shows the last errors for all the threads:\n\n```sh\n!gle -all\n# Last error for thread 0:\n# LastErrorValue: (Win32) 0 (0) - The operation completed successfully.\n# LastStatusValue: (NTSTATUS) 0xc0000034 - Object Name not found.\n# \n# Last error for thread 1:\n# LastErrorValue: (Win32) 0 (0) - The operation completed successfully.\n# LastStatusValue: (NTSTATUS) 0 - STATUS_SUCCESS\n```\n\n### Scanning the stack for native exception records\n\nSometimes, when the memory dump was incorrectly collected, we may not see the exception information and the `.exr -1` does not work. When this happens, there is still a chance that the original exception is somewhere in the stack. Using the `.foreach` command, we may scan the stack and try all the addresses to see if any of them is a valid exception record. For example:\n\n```sh\n.foreach /ps1 ($addr { dp /c1 @$csp L100 }) { .echo $addr; .exr $addr }\n# 0430af24\n# ExceptionAddress: abe8f04d\n#    ExceptionCode: c0000005 (Access violation)\n#   ExceptionFlags: 00000000\n# NumberParameters: 2\n#    Parameter[0]: 00000000\n#    Parameter[1]: abe8f04d\n```\n\n### Finding exception handlers\n\nTo list exception handlers for the currently running method use `!exchain` command.\n\nManaged exception handlers can be listed using the `!EHInfo` command from the SOS extenaion. I present how to use this command to list ASP.NET MVC exception handlers [on my blog](https://lowleveldesign.wordpress.com/2013/04/26/life-of-exception-in-asp-net/).\n\nIn 32-bit application, pointer to the exception handler is kept in `fs:[0]`. The prolog for a method with exception handling has the following structure:\n\n```\nmov     eax,fs:[00000000]\npush    eax\nmov     fs:[00000000],esp\n```\n\nAn Example session of retrieving the exception handler:\n\n```sh\ndd /c1 fs:[0]-8 L10\n# 0053:fffffff8  00000000\n# 0053:fffffffc  00000000\n# 0053:00000000  0072ef74 <-- this is our first exception pointer to a handler\n# 0053:00000004  00730000\n# 0053:00000008  0072c000\n\ndd /c1 0072ef74-8 L10\n# 0072ef6c  0072eefc\n# 0072ef70  74275582\n# 0072ef74  0072f04c <-- previous handler\n# 0072ef78  744048b9 <-- handler address\n# 0072ef7c  2778008f\n# 0072ef80  00000000\n# 0072ef84  0072f058\n# 0072ef88  744064f9\n```\n\nIn 64-bit applications, information about exception handlers is stored in the PE file. We can list them using, for example, the `dumpbin /unwindinfo` command.\n\n### Breaking on a specific exception event\n\nThe `sx-` commands define how WinDbg handles exception events that happen in the process lifetime. For example, to stop the debugger when a C++ exception is thrown (1st change exception) we would use the `sxe eh` command. If we only need information that an exception occurred, we could use the `sxn eh` command. Additionally, the -c parameter gives us a possibility to run our custom command on error:\n\n```sh\nsxe -c \".lastevent;!pe;!clrstack;g\" clr\n```\n\n### Breaking on a specific Windows Error\n\nThere is a special global variable in ntdll, `g_dwLastErrorToBreakOn`, that you may set to cause a break whenever a given last error code is set by the application. For example, to break the application execution whenever it reports the `0x4cf` (ERROR_NETWORK_UNREACHABLE) error, run:\n\n```sh\ned ntdll!g_dwLastErrorToBreakOn 0x4cf\n```\n\nYou may find the list of errors in [the Windows documentation](https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes).\n\n### Breaking on a function return\n\nIf we want to break when a function finishes, for example, to analyze its result, we may use a nested one-time breakpoint on the function return address, for example:\n\n```sh\nbp kernelbase!CreateFileW \"bp /1 $ra \\\"r @rax\\\"; g\"\n```\n\n### Decoding error numbers\n\nIf you receive an error message with a cryptic error number like this, for example: *Compiler Error Message: The compiler failed with error code -1073741502*, you may use the `!error` command:\n\n```sh\n!error c0000142\n# Error code: (NTSTATUS) 0xc0000142 (3221225794) - {DLL Initialization Failed} Initialization of the dynamic link library %hs failed. The process is terminating abnormally.\n```\n\nEven more error codes and error messages are contained in the `!pde.err` command from the PDE extension.\n\nIf you need to convert HRESULT to Windows Error, the following pseudo-code might help:\n\n```cpp\na = hresult & 0x1FF0000\nif (a == 0x70000) {\n    winerror = hresult & 0xFFFF\n} else {\n    winerror = hresult\n}\n```\n\nConverting Windows Error to HRESULT is straightforward: `hresult = 0x80070000 | winerror`.\n\nA great **command line tool** for decoding error number is [err.exe or Error Code Look-up](https://www.microsoft.com/en-us/download/details.aspx?id=985). It looks for the specific value in Windows headers, additionally performing the convertion to hex, for example:\n\n```sh\nerr -1073741502\n# for decimal -1073741502 / hex 0xc0000142 :\n#  STATUS_DLL_INIT_FAILED                                        ntstatus.h\n# {DLL Initialization Failed}\n# Initialization of the dynamic link library %hs failed. The\n# process is terminating abnormally.\n# ...\n```\n\nThere is also a subcommand in the Windows built-in `net` command to decode Windows error numbers (and only error numbers), for example:\n\n```sh\nnet helpmsg 2\n# The system cannot find the file specified.\n```\n\nDiagnosing dead-locks and hangs\n-------------------------------\n\nWe 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.\n\n### Listing threads call stacks\n\nTo list native stacks for all the threads run: `~*k` or `!uniqstacks`.\n\n### Finding locks in memory dumps\n\nThere are many types of objects that the thread can wait on. You usually see WaitOnMultipleObjects on many threads.\n\nIf you see `RtlWaitForCriticalSection` it might indicate that the thread is waiting on a critical section`. Its adress should be in the call stack. And we may list the critical sections using the `!cs` command. With the -s option, we may examine details of a specific critical section:\n\n```sh\n!cs -s 000000001a496f50\n# -----------------------------------------\n# Critical section   = 0x000000001a496f50 (+0x1A496F50)\n# DebugInfo          = 0x0000000013c9bee0\n# LOCKED\n# LockCount          = 0x0\n# WaiterWoken        = No\n# OwningThread       = 0x0000000000001b04\n# RecursionCount     = 0x1\n# LockSemaphore      = 0x0\n# SpinCount          = 0x00000000020007d0\n```\n\nLockCount tells you how many threads are currently waiting on a given cs. The OwningThread is a thread that owns the cs at the time the command is run. You can easily identify the thread that is waiting on a given cs by issuing kv command and looking for critical section identifier in the call parameters.\n\nWe can also look for **synchronization object handles** using the `!handle` command. For example, we may list all the Mutant objects in a process by using the `!handle 0 f Mutant` command.\n\nSystem objects in the debugger\n------------------------------\n\nThe `!object` command displays some basic information about a kernel object:\n\n```sh\n!object  ffffc30162f26080\n# Object: ffffc30162f26080  Type: (ffffc30161891d20) Process\n#     ObjectHeader: ffffc30162f26050 (new version)\n#     HandleCount: 23  PointerCount: 582900\n```\n\nWe may then analyze the object header to learn some more details about the object, for example:\n\n```sh\ndx (nt!_OBJECT_HEADER *)0xffffc30162f26050\n# (nt!_OBJECT_HEADER *)0xffffc30162f26050                 : 0xffffc30162f26050 [Type: _OBJECT_HEADER *]\n#     [+0x000] PointerCount     : 582900 [Type: __int64]\n#     [+0x008] HandleCount      : 23 [Type: __int64]\n#     [+0x008] NextToFree       : 0x17 [Type: void *]\n#     [+0x010] Lock             [Type: _EX_PUSH_LOCK]\n#     [+0x018] TypeIndex        : 0x5 [Type: unsigned char]\n#     [+0x019] TraceFlags       : 0x0 [Type: unsigned char]\n#     [+0x019 ( 0: 0)] DbgRefTrace      : 0x0 [Type: unsigned char]\n#     [+0x019 ( 1: 1)] DbgTracePermanent : 0x0 [Type: unsigned char]\n#     [+0x01a] InfoMask         : 0x88 [Type: unsigned char]\n#     [+0x01b] Flags            : 0x0 [Type: unsigned char]\n#     [+0x01b ( 0: 0)] NewObject        : 0x0 [Type: unsigned char]\n#     [+0x01b ( 1: 1)] KernelObject     : 0x0 [Type: unsigned char]\n#     [+0x01b ( 2: 2)] KernelOnlyAccess : 0x0 [Type: unsigned char]\n#     [+0x01b ( 3: 3)] ExclusiveObject  : 0x0 [Type: unsigned char]\n#     [+0x01b ( 4: 4)] PermanentObject  : 0x0 [Type: unsigned char]\n#     [+0x01b ( 5: 5)] DefaultSecurityQuota : 0x0 [Type: unsigned char]\n#     [+0x01b ( 6: 6)] SingleHandleEntry : 0x0 [Type: unsigned char]\n#     [+0x01b ( 7: 7)] DeletedInline    : 0x0 [Type: unsigned char]\n#     [+0x01c] Reserved         : 0x62005c [Type: unsigned long]\n#     [+0x020] ObjectCreateInfo : 0xffffc301671872c0 [Type: _OBJECT_CREATE_INFORMATION *]\n#     [+0x020] QuotaBlockCharged : 0xffffc301671872c0 [Type: void *]\n#     [+0x028] SecurityDescriptor : 0xffffd689feeef0ea [Type: void *]\n#     [+0x030] Body             [Type: _QUAD]\n#     ObjectType       : Process\n#     UnderlyingObject [Type: _EPROCESS]\n\ndx -r1 (*((ntkrnlmp!_EPROCESS *)0xffffc30162f26080))\n# (*((ntkrnlmp!_EPROCESS *)0xffffc30162f26080))                 [Type: _EPROCESS]\n#     [+0x000] Pcb              [Type: _KPROCESS]\n#     [+0x438] ProcessLock      [Type: _EX_PUSH_LOCK]\n#     [+0x440] UniqueProcessId  : 0x1488 [Type: void *]\n#     [+0x448] ActiveProcessLinks [Type: _LIST_ENTRY]\n#     [+0x458] RundownProtect   [Type: _EX_RUNDOWN_REF]\n#     [+0x460] Flags2           : 0x200d014 [Type: unsigned long]\n#     [+0x460 ( 0: 0)] JobNotReallyActive : 0x0 [Type: unsigned long]\n#     [+0x460 ( 1: 1)] AccountingFolded : 0x0 [Type: unsigned long]\n#     [+0x460 ( 2: 2)] NewProcessReported : 0x1 [Type: unsigned long]\n#     ...\n```\n\n### Processes (kernel-mode)\n\nEach time you break into the kernel-mode debugger, one of the processes will be active. You may learn which one by running the `!process -1 0` command. If you are going to work with user-mode memory space you need to reload the process modules symbols (otherwise you will see symbols from the last reload). You may do so while switching process context with `.process /i` (/i means invasive debugging and allows you to control the process from the kernel debugger) or `.process /r /p` (/r reloads user-mode symbols after the process context has been set (the behavior is the same as `.reload /user`), /p translates all transition page table entries (PTEs) for this process to physical addresses before access).\n\n`!peb` shows loaded modules, environment variables, command line arg, and more.\n\nThe `!process 0 0 {image}` command finds a proces using its image name, e.g.: `!process 0 0 LINQPad.UserQuery.exe`.\n\nWhen we know the process ID, we may use `!process {PID | address} 0x7` (the 0x7 flag will list all the threads with their stacks).\n\n### Handles\n\nThere is a special debugger extension command `!handle` that allows you to find system handles reserved by a process.\n\nTo list all handles reserved by a process use -1 (in kernel mode) or 0 (in user-mode). You may filter the list by setting a type of a handle:\n\n```shell\n!handle 0 1 File\n# ...\n# Handle 1c0\n#   Type          File\n# 7 handles of type File\n```\n\n### Threads\n\nThe `!thread {addr}` command shows details about a specific thread. Each thread has its own register values. These values are stored in the CPU registers when the thread is executing and are stored in memory when another thread is executing. You can set the register context using .thread command:\n\n```\n.thread [/p [/r] ] [/P] [/w] [Thread]\n```\n\nor\n\n```\n.trap [Address]\n.cxr [Options] [Address]\n```\n\nFor **WOW64 processes**, the /w parameter (`.thread /w`) will additionally switch to the x86 context. After loading the thread context, the commands opearating on stack should start working (remember to be in the right process context).\n\n**To list all threads** in a current process use the `~*`command (user-mode). Dot (.) in the first column signals a currently selected thread and hash (#) points to a thread on which an exception occurred.\n\n`!runaway` shows the time consumed by each thread:\n\n```shell\n!runaway 7\n# User Mode Time\n#  Thread       Time\n#   0:bfc       0 days 0:00:00.031\n#   3:10c       0 days 0:00:00.000\n#   2:844       0 days 0:00:00.000\n#   1:15bc      0 days 0:00:00.000\n# Kernel Mode Time\n#  Thread       Time\n#   0:bfc       0 days 0:00:00.046\n#   3:10c       0 days 0:00:00.000\n#   2:844       0 days 0:00:00.000\n#   1:15bc      0 days 0:00:00.000\n# Elapsed Time\n#  Thread       Time\n#   0:bfc       0 days 0:27:19.817\n#   1:15bc      0 days 0:27:19.810\n#   2:844       0 days 0:27:19.809\n#   3:10c       0 days 0:27:19.809\n```\n\n`~~[thread-id]` - in case you would like to use the system thread id you may with this syntax.\n\n`!tls Slot` extension displays a thread local storage slot (or -1 for all slots)\n\n### Critical sections\n\nDisplay information about a particular critical section: `!critsec {address}`.\n\n`!locks` extension in Ntsdexts.dll displays a list of critical sections associated with the current process.\n\n`!cs -lso [Address]`  - display information about critical sections (-l - only locked critical sections, -o - owner's stack, -s  - initialization stack, if available)\n\n`!critsec Address` - information about a specific critical section\n\n```sh\n!cs -lso\n# -----------------------------------------\n# DebugInfo          = 0x77294380\n# Critical section   = 0x772920c0 (ntdll!LdrpLoaderLock+0x0)\n# LOCKED\n# LockCount          = 0x10\n# WaiterWoken        = No\n# OwningThread       = 0x00002c78\n# RecursionCount     = 0x1\n# LockSemaphore      = 0x194\n# SpinCount          = 0x00000000\n# -----------------------------------------\n# DebugInfo          = 0x00581850\n# Critical section   = 0x5164a394 (AcLayers!NS_VirtualRegistry::csRegCriticalSection+0x0)\n# LOCKED\n# LockCount          = 0x4\n# WaiterWoken        = No\n# OwningThread       = 0x0000206c\n# RecursionCount     = 0x1\n# LockSemaphore      = 0x788\n# SpinCount          = 0x00000000\n```\n\nFinally, we may use the raw output:\n\n```shell\ndx -r1 ((ole32!_RTL_CRITICAL_SECTION_DEBUG *)0x581850)\n# ((ole32!_RTL_CRITICAL_SECTION_DEBUG *)0x581850)                 : 0x581850 [Type: _RTL_CRITICAL_SECTION_DEBUG *]\n#     [+0x000] Type             : 0x0 [Type: unsigned short]\n#     [+0x002] CreatorBackTraceIndex : 0x0 [Type: unsigned short]\n#     [+0x004] CriticalSection  : 0x5164a394 [Type: _RTL_CRITICAL_SECTION *]\n#     [+0x008] ProcessLocksList [Type: _LIST_ENTRY]\n#     [+0x010] EntryCount       : 0x0 [Type: unsigned long]\n#     [+0x014] ContentionCount  : 0x6 [Type: unsigned long]\n#     [+0x018] Flags            : 0x0 [Type: unsigned long]\n#     [+0x01c] CreatorBackTraceIndexHigh : 0x0 [Type: unsigned short]\n#     [+0x01e] SpareUSHORT      : 0x0 [Type: unsigned short]\n```\n\nControlling process execution\n-----------------------------\n\n### Controlling the target (g, t, p)\n\nTo go up the funtion use `gu` command. We can go to a specified address using `ga [address]`. We can also step or trace to a specified address using accordingly `pa` and `ta` commands.\n\nUseful commands are `pc` and `tc` which step or trace to the next call statement. `pt` and `tt` step or trace to the next return statement.\n\n### Watch trace\n\n`wt` is a very powerful command and might be excellent at revealing what the function under the cursor is doing, eg. (-oa displays the actual address of the call sites, -or displays the return register values):\n\n```shell\nwt -l1 -oa -or\n# Tracing notepad!NPInit to return address 00007ff6`72c23af5\n#    11     0 [  0] notepad!NPInit\n#                       call at 00007ff6`72c27749\n#    14     0 [  1]   notepad!_chkstk rax = 1570\n#    20    14 [  0] notepad!NPInit\n#                       call at 00007ff6`72c27772\n#    11     0 [  1]   USER32!RegisterWindowMessageW rax = c06f\n#    26    25 [  0] notepad!NPInit\n#                       call at 00007ff6`72c2778f\n#    11     0 [  1]   USER32!RegisterWindowMessageW rax = c06c\n#    31    36 [  0] notepad!NPInit\n#                       call at 00007ff6`72c277a5\n#     6     0 [  1]   USER32!NtUserGetDC rax = 9011652\n# >> More than one level popped 0 -> 0\n#    37    42 [  0] notepad!NPInit\n#                       call at 00007ff6`72c277bc\n#  1635     0 [  1]   notepad!InitStrings rax = 1\n#    42  1677 [  0] notepad!NPInit\n#                       call at 00007ff6`72c277d0\n#     8     0 [  1]   USER32!LoadCursorW rax = 10007\n#    46  1685 [  0] notepad!NPInit\n#                       call at 00007ff6`72c277e4\n#     8     0 [  1]   USER32!LoadCursorW rax = 10009\n#    50  1693 [  0] notepad!NPInit\n#                       call at 00007ff6`72c277fb\n#    24     0 [  1]   USER32!LoadAcceleratorsW\n#    24     0 [  1]   USER32!LoadAcc rax = 0\n#    59  1741 [  0] notepad!NPInit\n#                       call at 00007ff6`72c27d84\n#     6     0 [  1]   notepad!_security_check_cookie rax = 0\n#    69  1747 [  0] notepad!NPInit\n# \n# 1816 instructions were executed in 1815 events (0 from other threads)\n# \n# Function Name                               Invocations MinInst MaxInst AvgInst\n# USER32!LoadAcc                                        1      24      24      24\n# USER32!LoadAcceleratorsW                              1      24      24      24\n# USER32!LoadCursorW                                    2       8       8       8\n# USER32!NtUserGetDC                                    1       6       6       6\n# USER32!RegisterWindowMessageW                         2      11      11      11\n# notepad!InitStrings                                   1    1635    1635    1635\n# notepad!NPInit                                        1      69      69      69\n# notepad!_chkstk                                       1      14      14      14\n# notepad!_security_check_cookie                        1       6       6       6\n# \n# 1 system call was executed\n# \n# Calls  System Call\n#     1  USER32!NtUserGetDC\n```\n\nThe first number in the trace output specifies the number of instructions that were executed from the beginning of the trace in a given function (it is always incrementing), the second number specifies the number of instructions executed in the child functions (it is also always incrementing), and the third represents the depth of the function in the stack (parameter -l).\n\nIf the `wt` command does not work, you may achieve similar results manually with the help of the target controlling commands:\n\n- stepping until a specified address: `ta`, `pa`\n- stepping until the next branching instruction: `th`, `ph`\n- stepping until the next call instruction: `tc`, `pc`\n- stepping until the next return: `tt`, `pt`\n- stepping until the next return or call instruction: `tct`, `pct`\n\n\n### Breaking when a specific function is in the call stack\n\n```shell\nbp Module!MyFunctionWithConditionalBreakpoint \"r $t0 = 0;.foreach (v { k }) { .if ($spat(\\\"v\\\", \\\"*Module!ClassA:MemberFunction*\\\")) { r $t0 = 1;.break } }; .if($t0 = 0) { gc }\"\n```\n\n### Breaking on a specific function enter and leave\n\nThe trick is to set a one-time breakpoint on the return address (`bp /1 @$ra`) when the main breakpoint is hit, for example:\n\n```shell\nbp 031a6160 \"dt ntdll!_GUID poi(@esp + 8); .printf /D \\\"==> obj addr: %p\\\", poi(@esp + C);.echo; bp /1 @$ra; g\"\nbp kernel32!RegOpenKeyExW \"du @rdx; bp /1 @$ra \\\"r @$retreg; g\\\"; g\"\n```\n\n```shell\nbp kernelbase!CreateFileW \".printf \\\"CreateFileW('%mu', ...)\\\", @rcx; bp /1 @$ra \\\".printf \\\\\\\" => %p\\\\\\\\n\\\\\\\", @rax; g\\\"; g\"\nbp kernelbase!DeviceIoControl \".printf \\\"DeviceIoControl(%p, %p, ...)\\\\n\\\", @rcx, @rdx; g\"\nbp kernelbase!CloseHandle \".printf \\\"CloseHandle(%p)\\\\n\\\", @rcx;g\"\n```\n\nRemove the 'g' commands from the above samples if you want the debugger to stop.\n\n### Breaking for all methods in the C++ object virtual table\n\nThis could be useful when debugging COM interfaces, as in the example below. When we know the number of methods in the interface and the address of the virtual table, we may set the breakpoint using the .for loop, for example:\n\n```shell\n.for (r $t0 = 0; @$t0 < 5; r $t0= @$t0 + 1) { bp poi(5f4d8948 + @$t0 * @$ptrsize) }\n```\n\n### Breaking when a user-mode process is created (kernel-mode)\n\n`bp nt!PspInsertProcess`\n\nThe breakpoint is hit whenever a new user-mode process is created. To know what process is it we may access the \\_EPROCESS structure ImageFileName field.\n\n```shell\n# x64\ndt nt!_EPROCESS @rcx ImageFileName\n# x86\ndt nt!_EPROCESS @eax ImageFileName\n```\n\n### Setting a user-mode breakpoint in kernel-mode\n\nYou may set a breakpoint in user space, but you need to be in a valid process context:\n\n```shell\n!process 0 0 notepad.exe\n# PROCESS ffffe0014f80d680\n#     SessionId: 2  Cid: 0e44    Peb: 7ff7360ef000  ParentCid: 0aac\n#     DirBase: 2d497000  ObjectTable: ffffc00054529240  HandleCount:\n#     Image: notepad.exe\n\n.process /i ffffe0014f80d680\n# You need to continue execution (press 'g' ) for the context\n# to be switched. When the debugger breaks in again, you will be in\n# the new process context.\n\nkd> g\n```\n\nThen when you are in a given process context, set the breakpoint:\n\n```shell\n.reload /user\n\n!process -1 0\n# PROCESS ffffe0014f80d680\n#     SessionId: 2  Cid: 0e44    Peb: 7ff7360ef000  ParentCid: 0aac\n#     DirBase: 2d497000  ObjectTable: ffffc00054529240  HandleCount:\n#     Image: notepad.exe\n\nx kernel32!CreateFileW\n# 00007ffa`d8502508 KERNEL32!CreateFileW ()\n\nbp 00007ffa`d8502508\n```\n\nAlternative way (which does not require process context switching) is to use data execution breakpoints, eg.:\n\n```shell\n!process 0 0 notepad.exe\n# PROCESS ffffe0014ca22480\n#     SessionId: 2  Cid: 0614    Peb: 7ff73628f000  ParentCid: 0d88\n#     DirBase: 5607b000  ObjectTable: ffffc0005c2dfc40  HandleCount:\n#     Image: notepad.exe\n\n.process /r /p ffffe0014ca22480\n# Implicit process is now ffffe001`4ca22480\n# .cache forcedecodeuser done\n# Loading User Symbols\n# ..........................\n\nx KERNEL32!CreateFileW\n# 00007ffa`d8502508 KERNEL32!CreateFileW ()\n\nba e1 00007ffa`d8502508\n```\n\nFor both those commands you may limit their scope to a particular process using /p switch.\n\nScripting the debugger\n----------------------\n\n### Using meta-commands (legacy way)\n\nWinDbg contains several meta-commands (starting with a dot) that allow you to control the debugger actions. The `.expr` command prints the expression evaluator (MASM or C++) that will be used when interpreting the symbols in the executed commands. You may use the /s to change it. The `?` command uses the default evaluator, and `??` always uses the C++ evaluator. Also, you can mix the evaluators in one expression by using `@@c++(expression)` or `@@masm(expression)` syntax, for example: `? @@c++(@$peb->ImageSubsystemMajorVersion) + @@masm(0y1)`.\n\nWhen using `.if` and `.foreach`, sometimes the names are not resolved - use spaces between them. For example, the command would fail if there was no space between poi( and addr in the code below.\n\n```shell\n.foreach (addr {!DumpHeap -mt 71d75b24 -short}) { .if (dwo(poi( addr + 5c ) + c)) { !do addr } }\n```\n\n### Using the dx command\n\nThe [dx command](https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/dx--display-visualizer-variables-) allows us to query the Debugger Object Model. There is a set of root objects from which we may start our query, including `@$cursession`, `@$curprocess`, `@$curthread`, `@$curstack`, or `@$curframe`.\n\n`dx Debugger.State` shows the current state of the debugger. The -h parameter additionally displays help for the debugger objects, for example:\n\n```shell\ndx -h Debugger.State\n# Debugger.State                 [State pertaining to the current execution of the debugger (e.g.: user variables)]\n#     DebuggerInformation [Debugger variables which are owned by the debugger and can be referenced by a pseudo-register prefix of @$]\n#     DebuggerVariables [Debugger variables which are owned by the debugger and can be referenced by a pseudo-register prefix of @$]\n#     FunctionAliases  [Functions aliased to names which are accessible via a pseudo-register prefix of @$ or executable via a '!' command prefix]\n#     PseudoRegisters  [Categorizied debugger managed pseudo-registers which can be referenced by a pseudo-register prefix of @$]\n#     Scripts          [Scripts which have been loaded into the debugger and have properties, methods, or other accessible constructs]\n#     UserVariables    [User variables which are maintained by the debugger and can be referenced by a pseudo-register prefix of @$]\n#     ExtensionGallery [Extension Gallery]\n```\n\nIf we add the -v parameter, dx will print not only the values of the properties and fields but also the methods we may call on an object:\n\n```shell\ndx -v -r1 Debugger.Sessions[0].Processes[15416].Threads[12796]\n# Debugger.Sessions[0].Processes[15416].Threads[12796]                 [Switch To]\n#     Id               : 0x31fc\n#     Index            : 0x0\n#     Stack           \n#     Registers       \n#     SwitchTo         [SwitchTo() - Switch to this thread as the default context]\n#     Environment     \n#     TTD             \n#     ToDisplayString  [ToDisplayString([FormatSpecifier]) - Method which converts the object to its display string representation according to an optional format specifier]\n```\n\n#### Using variables and creating new objects in the dx query\n\nIn our queries we may create anonymous objets, lambdas, arrays and objects of the Debugger Object Model types, for example:\n\n```sh\n# Create an anonymous object for each call to RtlSetLastWin32Error that contains TTD time of the call and the error code value\ndx -g @$cursession.TTD.Calls(\"ntdll!RtlSetLastWin32Error\").Select(c => new { TimeStart = c.TimeStart, Error = c.Parameters[0] })\n# =========================================\n# =           = (+) TimeStart = Error     =\n# =========================================\n# = [0x0]     - 725:3B        - 0xbb      =\n# = [0x1]     - 725:3D6       - 0x57      =\n# = [0x2]     - 725:4AA       - 0x57      =\n# = [0x3]     - 725:EF0       - 0xbb      =\n# ....\n\n# Create a simple array containing four numbers\ndx Debugger.Utility.Collections.CreateArray(1, 2, 3, 4)\n# Debugger.Utility.Collections.CreateArray(1, 2, 3, 4)                \n#     [0x0]            : 1\n#     [0x1]            : 2\n#     [0x2]            : 3\n#     [0x3]            : 4\n\n# Create a TTD position object and use it to set the current trace position\ndx -s @$create(\"Debugger.Models.TTD.Position\", 4173, 75).SeekTo()\n\n# Create a lambda function to sum two numbers\ndx ((x, y) => x + y)(1, 2)\n# ((x, y) => x + y)(1, 2) : 3\n```\n\nAdditionally, we may assign the created object or the result of a dx query to a variable, for example:\n\n```shell\n# Assign a lambda function to a $sum variable and use it\ndx @$sum = (x, y) => x + y\ndx @$sum(1, 2)\n# @$sum(1, 2)      : 3\n\n# Save all calls to the CreateFileW function to the @$calls variable\ndx @$calls = @$cursession.TTD.Calls(\"kernelbase!CreateFileW\")\n```\n\nWe may also use variables and pseudo-registers available in the debugger context. You may list them by examining the `Debugger.State.DebuggerVariables`, `Debugger.State.PseudoRegisters`, and `Debugger.State.UserVariables` objects.\n\n#### Using text files\n\nThe `FileSystem` API allows us to access the host file system. To have the full control over the lifetime of the opened file handle, I recommend using the file object explicitly. The following code is an example when we read all lines from a file to an array:\n\n```cpp\ndx @$file = Debugger.Utility.FileSystem.OpenFile(\"c:\\\\temp\\\\test.txt\")\ndx @$lines = Debugger.Utility.FileSystem.CreateTextReader(@$file).ReadLineContents().ToArray()\ndx @$file.Close()\n```\n\n#### Example queries with explanations\n\n```sh\n# Find kernel32 exports that contain the 'RegGetVal' string (by Tim Misiak)\ndx @$curprocess.Modules[\"kernel32\"].Contents.Exports.Where(exp => exp.Name.Contains(\"RegGetVal\"))\n\n# Show the address of the exported RegGetValueW function (by Tim Misiak)\ndx -r1 @$curprocess.Modules[\"kernel32\"].Contents.Exports.Single(exp => exp.Name == \"RegGetValueW\").CodeAddress\n\n# Set a breakpoint on every exported function of the bindfltapi module\ndx @$curprocess.Modules[\"bindfltapi\"].Contents.Exports.Select(m =>  Debugger.Utility.Control.ExecuteCommand($\"bp {m.CodeAddress}\"))\n\n# Show the number of calls made to functions with names starting from NdrClient in the rpcrt4 module\ndx -g @$cursession.TTD.Calls(\"rpcrt4!NdrClient*\").GroupBy(c => c.Function).Select(g => new { Function = g.First().Function, Count = g.Count() })\n```\n\nMore examples of the dx queries for analysing the TTD traces can be found in the [TTD guide](/guides/using-ttd).\n\n#### Managed application support in the dx queries\n\nThe SOS extension does not currently support the Debugger Object Models, but we can see that some of the debugger objects understand the managed context. For example, when we list **stack frames** of a managed process, the method names should be properly decoded:\n\n```shell\ndx -r1 @$curprocess.Threads[13236].Stack.Frames\n# @$curprocess.Threads[13236].Stack.Frames                \n#     [0x0]            : ntdll!NtReadFile + 0x14 [Switch To]\n#     [0x1]            : KERNELBASE!ReadFile + 0x7b [Switch To]\n#     [0x2]            : System_Console!Interop.Kernel32.ReadFile + 0x84 [Switch To]\n#     [0x3]            : System_Console!System.ConsolePal.WindowsConsoleStream.ReadFileNative + 0x60 [Switch To]\n#     [0x4]            : System_Console!System.ConsolePal.WindowsConsoleStream.Read + 0x2b [Switch To]\n#     [0x5]            : System_Console!System.IO.ConsoleStream.Read + 0x74 [Switch To]\n#     [0x6]            : System_Private_CoreLib!System.IO.StreamReader.ReadBuffer + 0x268 [Switch To]\n#     [0x7]            : System_Private_CoreLib!System.IO.StreamReader.ReadLine + 0xd3 [Switch To]\n#     [0x8]            : System_Console!System.IO.SyncTextReader.ReadLine + 0x3d [Switch To]\n#     [0x9]            : System_Console!System.Console.ReadLine + 0x19 [Switch To]\n#     [0xa]            : testcs!Program.Main + 0xc6 [Switch To]\n#     ...\n\ndx -r1 @$curprocess.Threads[13236].Stack.Frames[10]\n# @$curprocess.Threads[13236].Stack.Frames[10]                 : testcs!Program.Main + 0xc6 [Switch To]\n#     LocalVariables  \n#     Parameters       : ()\n#     Attributes      \n\ndx -r1 @$curprocess.Threads[13236].Stack.Frames[10].LocalVariables\n# @$curprocess.Threads[13236].Stack.Frames[10].LocalVariables                \n#     ex               : 0x0 [Type: System.Exception]\n#     slot0            [Type: System.Runtime.CompilerServices.DefaultInterpolatedStringHandler]\n#     ...\n```\n\nAdditionally, we may query **the managed heap** (the `ManagedHeap` property is a nice replacement for the `!DumpHeap` command):\n\n```shell\ndx -r1 @$curprocess.Memory.ManagedHeap\n# @$curprocess.Memory.ManagedHeap                \n#     GCHandles       \n#     Objects         \n#     ObjectsByType\n\ndx -r1 @$curprocess.Memory.ManagedHeap.Objects\n# @$curprocess.Memory.ManagedHeap.Objects                \n#     [0x0]            : 0x1ab6fc00020   size = 60   type = int[]\n#     [0x1]            : 0x1ab6fc00080   size = 80   type = System.OutOfMemoryException\n#     [0x2]            : 0x1ab6fc00100   size = 80   type = System.StackOverflowException\n#     [0x3]            : 0x1ab6fc00180   size = 80   type = System.ExecutionEngineException\n#     [0x4]            : 0x1ab6fc00200   size = 18   type = System.Object\n#     [0x5]            : 0x1ab6fc00218   size = 18   type = System.String\n#     [0x6]            : 0x1ab6fc00230   size = 50   type = System.Collections.Generic.Dictionary<string,object>\n#     [0x7]            : 0x1ab6fc00280   size = 48   type = System.String\n#     [...]           \n```\n\n### Using the JavaScript engine\n\nLinks:\n\n- [Official Microsoft documentation](https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/javascript-debugger-scripting)\n- [The API reference for the host object](https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/native-objects-in-javascript-extensions-debugger-objects)\n- [Debugger data model, Javascript & x64 exception handling](https://doar-e.github.io/blog/2017/12/01/debugger-data-model) - a great article on scripting the debugger by Alex \"0vercl0k\" Souchet\n\n#### Loading a script\n\nThe `.scriptproviders` command must include the JavaScript provider in the output.\n\nThen we may run a script with the `.scriptrun` command or load it using the `.scriptload` command. The difference is that model modifications made by the `.scriptload` will stay in place until the call to `.scriptunload`. Also, `.scriptrun` will call the `invokeScript` JS function after the usual calls to the root code and the `initializeScript` function.\n\n`.scriptlist` lists the loaded scripts.\n\n#### Running a script\n\nAfter loading a script file, we may find it in the `Debugger.State.Scripts` list (`.scriptlist` will show it, too):\n\n```shell\n.scriptload c:\\windbg-js\\windbg-scripting.js\n# JavaScript script successfully loaded from 'c:\\windbg-js\\windbg-scripting.js'\n\ndx -r1 Debugger.State.Scripts\n# Debugger.State.Scripts\n#     windbg-scripting\n```\n\nThen we are ready to call any defined public function, for example, logn:\n\n```shell\ndx Debugger.State.Scripts.@\"windbg-scripting\".Contents.logn(\"test\")\n# test\n\nDebugger.State.Scripts.@\"windbg-scripting\".Contents.logn(\"test\")\n```\n\nThe `@$scriptContents` variable is a shortcut to all the public functions from all the loaded scripts, so our call could be more compact:\n\n```shell\ndx @$scriptContents.logn(\"test\")\n# test\n\n@$scriptContents.logn(\"test\")\n```\n\n#### Working with types\n\nThe `Number` type in JavaScript has a 53-bit limitation, which prevents us from working with 64-bit types. Fortunately, WinDbg provides us with the `Int64` type with methods for operations on 64-bit numbers such as `getLowPart`, `getHighPart`, `bitwiseAnd`, or `bitwiseShiftLeft` (others in [the documentation](https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/javascript-debugger-scripting#work-with-64-bit-values-in-javascript-extensions)). It also has a properly implemented `toString` and can be safely used for hexadecimal conversion of data from the debugger, for example:\n\n```js\nfunction initializeScript()\n{\n    return [new host.apiVersionSupport(1, 7), new host.functionAlias(runTest, \"runTest\")]\n}\n\nfunction __hexString2(n) {\n    return n.toString(16);\n}\n\nfunction runTest(n) {\n    return __hexString2(n);\n}\n```\n\n```shell\ndx @$n = 0xffffffffffffffff\n# @$n = 0xffffffffffffffff : -1\n\n!runTest(@$n)\n# @$runTest(@$n)   : ffffffffffffffff\n#     Length           : 0x10\n```\n\nAdditiona, the JS provider tracks created `Int64` objects and, if an object for a given value already exists, it will be returned, for example:\n\n```js\nconst call = host.currentSession.TTD.Calls(\"combase!CoCreateInstance\").First();\n\nconst ppv = call.Parameters.ppv.address;\n\ncall.TimeEnd.SeekTo();\n\nconst cobj = host.evaluateExpression(`*(void **)${ppv}`).address;\nconst i2 = new host.Int64(cobj);\n\nconst m = new Map();\nm.set(i2, clsid);\nm.set(cobj, clsid);\n// the m size is 1\n__logn(`m size : ${m.size}`);\n```\n\n#### Accessing the debugger engine objects\n\nThe `host.namespace` gives us access to the `debuggerRootNamespace` which we normally use with the `dx` command:\n\n```shell\ndx @$debuggerRootNamespace\n# @$debuggerRootNamespace                \n#     Debugger\n```\n\n```js\nvar ctl = host.namespace.Debugger.Utility.Control;   \nctl.ExecuteCommand(\".process /p /r \" + procId);\n```\n\nDML might pollute the command output. If that's the case, you may disable it with the `.prefer_dml 0` command.\n\n#### Evaluating expressions in a debugger context\n\nThe `host.evaluateExpression` allows to evaluate expressions, for eaxmple:\n\n```js\nfunction exc(addr) {\n    let exceptionRecord = host.evaluateExpression(`(_EXCEPTION_RECORD*)${addr}`);\n    let exceptionCode = host.evaluateExpression(`(DWORD)${exceptionRecord.ExceptionCode}`)\n\n    if (exceptionCode === 0xe06d7363) {\n        println(\"== EH exception ==\");\n        exceptionRecord.\n    } else {\n        logn(`Other exception: ${exceptionCode}`)\n    }\n}\n```\n\nIt is quite slow, so using it in frequently executed functions is not practical.\n\n#### Debugging a script\n\nAfter we loaded the script (`.scriptload`), we may also debug its parts thanks to the `.scriptdebug` command, for example:\n\n```shell\n.scriptload c:\\windbg-js\\strings.js\n\n.scriptdebug strings.js\n\n# *** Inside JS debugger context ***\n|\n#     ...\n#     [11] NatVis script from 'C:\\Program Files\\WindowsApps\\Microsoft.WinDbg_1.2308.2002.0_x64__8wekyb3d8bbwe\\amd64\\Visualizers\\winrt.natvis'\n#     [12] [*DEBUGGED*] JavaScript script from 'c:\\windbg-js\\strings.js'\n# \nbp logn\n# Breakpoint 1 set at logn (11:5)\nbl\n#       Id State    Pos\n#        1 enabled  11:5\n# \nq\n```\n\nWe are running a debugger in the debugger, so it could be a bit confusing :) After quitting the JavaScript debugger, it will keep the breakpoints information, so when we call our function from the main debugger, we will land in the JavaScript debugger again, for example:\n\n```shell\ndx @$scriptContents.logn(\"test\")\n# >>> ****** SCRIPT BREAK strings [Breakpoint 1] ******\n#            Location: line = 11, column = 5\n#            Text: log(s + \"\\n\")\n#\n# *** Inside JS debugger context ***\ndv\n#                    s = test\n```\n\nThe number of commands available in the inner JavaScript debugger is quite long and we may list them with the `.help` command. Especially, the evaluate expression (`?` or `??`) are very useful as they allow us to execute any JavaScript expressions and check their results:\n\n```shell\n? host\n# host             : {...}\n#     __proto__        : {...}\n#     ...\n#     Int64            : function () { [native code] }\n#     parseInt64       : function () { [native code] }\n#     namespace        : {...}\n#     evaluateExpression : function () { [native code] }\n#     evaluateExpressionInContext : function () { [native code] }\n#     getModuleSymbol  : function () { [native code] }\n#     getModuleContainingSymbol : function () { [native code] }\n#     getModuleContainingSymbolInformation : function () { [native code] }\n#     getModuleSymbolAddress : function () { [native code] }\n#     setModuleSymbol  : function () { [native code] }\n#     getModuleType    : function () { [native code] }\n#     ...\n```\n\n### Launching commands from a script file\n\nWe can also execute commands from a script file. We use the `$$` command family for that purpose. The -c option allows us to run a command on a debugger launch. So if we pass the `$$<` command with a file path, windbg will read the file and execute the commands from it as if they were entered manually, for example:\n\n```shell\nwindbgx -c \"$$<test.txt\" notepad\n```\n\nAnd the test.txt content:\n\n```shell\nsxe -c \".echo advapi32; g\" ld:advapi32\ng\n```\n\nWe may use the `$$>args<` command variant to pass arguments to our script.\n\nWhen analyzing multiple files, I often use PowerShell to call WinDbg with the commands I want to run. In each WinDbg session, I pass the output of the commands to the windbg.log file, for example:\n\n```shell\nGet-ChildItem .\\dumps | % { Start-Process -Wait -FilePath windbg-x64\\windbg.exe -ArgumentList @(\"-loga\", \"windbg.log\", \"-y\", \"`\"SRV*C:\\dbg\\symbols*https://msdl.microsoft.com/download/symbols`\"\", \"-c\", \"`\".exr -1; .ecxr; k; q`\"\", \"-z\", $_.FullName) }\n```\n\nTo make a **comment**, you can use one of the comment commands: `$$ my comment` or `* my comment`. The difference between them is that `*` comments everything till the end of the line, while `$$` comments text till the semicolon (or end of a line), e.g., `r eax; $$ some text; r ebx; * more text; r ecx` will print eax, ebx but not ecx. The `.echo` command ends if the debugger encounters a semicolon (unless the semicolon occurs within a quoted string).\n\nTime Travel Debugging (TTD)\n---------------------------\n\n[TTD](https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/time-travel-debugging-overview) is a fantastic way to debug application code. After collecting a debug trace, we may query process memory, function calls, going deeper and deeper into the call stacks if necessary, and jump through various process lifetime events.\n\n### Installation\n\nThe collector is installed with WinDbgX and we may enable it when starting a WinDbgX debugging session.\n\nAlternatively, we could [install the command-line TTD collector](https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/time-travel-debugging-ttd-exe-command-line-util#how-to-download-and-install-the-ttdexe-command-line-utility-preferred-method). The PowerShell script published on the linked site is capable of installing TTD even on systems not supporting the MSIX installations. The command-line tool is probably the best option when collecting TTD traces on server systems. When done, you may uninstall the driver by using the -cleanup option.\n\n### Collection\n\nIf you have WinDbgX, you may use TTD by checking the \"Record with Time Travel Debugging\" checkbox when you start a new process or attach to a running one. When you stop the TTD trace in WinDbgX it will terminate the target process (TTD.exe, described later, can detach from a process without killing it).\n\nAn alternative to WinDbgX is running the command-line TTD collector. Some usage examples:\n\n```sh\n# launch a new winver.exe process and record the trace in C:\\logs\nttd.exe -accepteula -out c:\\logs winver.exe\n\n# attach and trace the process with ID 1234 and all its newly started children\nttd.exe -accepteula -children -out c:\\logs -attach 1234 \n\n# attach and trace the process with ID 1234 to a ring buffer, backed by a trace file of maximum size 1024 MB\nttd.exe -accepteula -ring -maxFile 1024 -out c:\\logs -attach 1234\n\n# record a trace of the running and newly started processes, add a timestamp to the trace file names\nttd.exe -accepteula -timestampFilename -out c:\\logs -monitor winver.exe\nttd.exe -accepteula -timestampFilename -out c:\\logs -monitor app1.exe -monitor app2.exe\n```\n\n### Accessing TTD data\n\nWe can acess TTD objects by querying the TTD property of the session or process objects:\n\n```sh\ndx -v @$cursession.TTD\n# @$cursession.TTD                \n#     HeapLookup       [Returns a vector of heap blocks that contain the provided address: TTD.Utility.HeapLookup(address)]\n#     Calls            [Returns call information from the trace for the specified set of methods: TTD.Calls(\"module!method1\", \"module!method2\", ...) For example: dx @$cursession.TTD.Calls(\"user32!SendMessageA\")]\n#     Memory           [Returns memory access information for specified address range: TTD.Memory(startAddress, endAddress [, \"rwec\"])]\n#     MemoryForPositionRange [Returns memory access information for specified address range and position range: TTD.MemoryForPositionRange(startAddress, endAddress [, \"rwec\"], minPosition, maxPosition)]\n#     PinObjectPosition [Pins an object to the given time position: TTD.PinObjectPosition(obj, pos)]\n#     AsyncQueryEnabled : false\n#     Data             : Normalized data sources based on the contents of the time travel trace\n#     Utility          : Methods that can be useful when analyzing time travel traces\n#     ToDisplayString  [ToDisplayString([FormatSpecifier]) - Method which converts the object to its display string representation according to an optional format specifier]\n\ndx -v @$curprocess.TTD\n# @$curprocess.TTD                \n#     Index           \n#     Threads         \n#     Events          \n#     DebugOutput     \n#     Lifetime         : [66:0, 118A2:0]\n#     DefaultMemoryPolicy : GloballyAggressive\n#     SetPosition      [Sets the debugger to point to the given position on this process.]\n#     GatherMemoryUse  [0]\n#     RecordClients  \n```\n\n### Querying debugging events\n\nThe `@$curprocess.Events` collection contains [TTD Event objects](https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/time-travel-debugging-event-objects). We can use the group query to learn what type of events we have in our trace:\n\n```sh\ndx -g @$curprocess.TTD.Events.GroupBy(ev => ev.Type).Select(g => new { Type = g.First().Type, Count = g.Count() })\n# ===========================================================\n# =                         = (+) Type            = Count   =\n# ===========================================================\n# = [\"ModuleLoaded\"]        - ModuleLoaded        - 0x23    =\n# = [\"ThreadCreated\"]       - ThreadCreated       - 0x9     =\n# = [\"ThreadTerminated\"]    - ThreadTerminated    - 0x9     =\n# = [\"Exception\"]           - Exception           - 0x4     =\n# = [\"ModuleUnloaded\"]      - ModuleUnloaded      - 0x23    =\n# ===========================================================\n```\n\nNext, we may filter the list for events that interest us, for example, to extract the first [TTD Exception object](https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/time-travel-debugging-exception-objects), we may run the following query:\n\n```sh\ndx @$curprocess.TTD.Events.Where(ev => ev.Type == \"Exception\").Select(ev => ev.Exception).First()\n# @$curprocess.TTD.Events.Where(ev => ev.Type == \"Exception\").Select(ev => ev.Exception).First()                 : Exception 0xE0434352 of type Software at PC: 0X7FF91E0842D0\n#     Position         : 7E7C:0 [Time Travel]\n#     Type             : Software\n#     ProgramCounter   : 0x7ff91e0842d0\n#     Code             : 0xe0434352\n#     Flags            : 0x1\n#     RecordAddress    : 0x0\n# ...\n```\n\n### Examining function calls\n\nThe `Calls` method of the `TTD` objects allows us to query [function calls](https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/time-travel-debugging-calls-objects) made in the trace. We may use either an address or a symbol name (even with wildcards) as a parameter to the Calls method:\n\n```shell\nx OLEAUT32!IDispatch_Invoke_Proxy\n# 75a13bf0          OLEAUT32!IDispatch_Invoke_Proxy (void)\n\n# we may use the address of a function\ndx @$cursession.TTD.Calls(0x75a13bf0).Count()\n# @$cursession.TTD.Calls(0x75a13bf0).Count() : 0x6a18\n\n# or its symbolic name\ndx @$cursession.TTD.Calls(\"OLEAUT32!IDispatch_Invoke_Proxy\").Count()\n# @$cursession.TTD.Calls(\"OLEAUT32!IDispatch_Invoke_Proxy\").Count() : 0x6a18\n```\n\nThanks to **wildcards**, we can easily get statistics on function calls from a given module or modules (this call might take some time for longer traces):\n\n```shell\n# Show the number of calls made to functions with names starting from NdrClient in the rpcrt4 module\ndx -g @$cursession.TTD.Calls(\"rpcrt4!NdrClient*\").GroupBy(c => c.Function).Select(g => new { Function = g.First().Function, Count = g.Count() })\n# ==============================================================================\n# =                                   = (+) Function                  = Count  =\n# ==============================================================================\n# = [\"RPCRT4!NdrClientCall2\"]         - RPCRT4!NdrClientCall2         - 0x5    =\n# = [\"RPCRT4!NdrClientInitialize\"]    - RPCRT4!NdrClientInitialize    - 0x5    =\n# = [\"RPCRT4!NdrClientCall3\"]         - RPCRT4!NdrClientCall3         - 0x8    =\n# = [\"RPCRT4!NdrClientZeroOut\"]       - RPCRT4!NdrClientZeroOut       - 0x1    =\n# ==============================================================================\n```\n\nTimeStart shows the position of a call in a trace and we may use it to jump between different places in the trace. SystemTimeStart shows the clock time of a given call:\n\n```shell\ndx -g @$cursession.TTD.Calls(\"user32!DialogBox*\").Select(c => new { Function = c.Function, TimeStart = c.TimeStart, SystemTimeStart = c.SystemTimeStart })\n# ==============================================================================================================\n# =          = (+) Function                         = (+) TimeStart = (+) SystemTimeStart                      =\n# ==============================================================================================================\n# = [0x0]    - USER32!DialogBoxIndirectParamW       - 62E569:57     - Friday, February 2, 2024 16:03:39.391    =\n# = [0x1]    - USER32!DialogBoxIndirectParamAorW    - 62E569:5C     - Friday, February 2, 2024 16:03:39.391    =\n# = [0x2]    - USER32!DialogBox2                    - 631C23:102    - Friday, February 2, 2024 16:03:39.791    =\n```\n\nEach function call has a Parameters property that gives us access to the function parameters (without private symbols, we can access the first four parameters) of a call:\n\n```shell\n# Check which LastErrors were set during the call\ndx -h @$cursession.TTD.Calls(\"ntdll!RtlSetLastWin32Error\").Select(c => c.Parameters[0]).Distinct()\n# @$cursession.TTD.Calls(\"ntdll!RtlSetLastWin32Error\").Select(c => c.Parameters[0]).Distinct()                \n#     [0x0]            : 0xbb\n#     [0x1]            : 0x57\n#     [0x2]            : 0x0\n#     [0x3]            : 0x7e\n#     [0x4]            : 0x3f0\n\n# Find LastError calls when LastError is not zero\ndx -g @$cursession.TTD.Calls(\"ntdll!RtlSetLastWin32Error\").Where(c => c.Parameters[0] != 0).Select(c => new { TimeStart = c.TimeStart, Error = c.Parameters[0] })\n# =========================================\n# =           = (+) TimeStart = Error     =\n# =========================================\n# = [0x0]     - 725:3B        - 0xbb      =\n# = [0x1]     - 725:3D6       - 0x57      =\n# = [0x2]     - 725:4AA       - 0x57      =\n# = [0x3]     - 725:EF0       - 0xbb      =\n# ....\n```\n\n### Position in TTD trace\n\nThe [TTD Position object](https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/time-travel-debugging-position-objects) describes a moment in time in the trace. Its `SeekTo` method allows us to jump to this moment and analyze the process state:\n\n```shell\ndx -r1 @$create(\"Debugger.Models.TTD.Position\", 34395, 1278)\n# @$create(\"Debugger.Models.TTD.Position\", 34395, 1278)                 : 865B:4FE [Time Travel]\n#     Sequence         : 0x865b\n#     Steps            : 0x4fe\n#     SeekTo           [Method which seeks to time position]\n#     ToSystemTime     [Method which obtains the approximate system time at a given position]\n\ndx -s @$create(\"Debugger.Models.TTD.Position\", 34395, 1278).SeekTo()\n# (1d30.1b94): Break instruction exception - code 80000003 (first/second chance not available)\n# Time Travel Position: 865B:4FE\n```\n\nAlternatively, we could use `!tt 865B:4FE` to jump to a specific time position.\n\nIf we are troubleshooting an issue spanning multiple processes, we may simultaneously record TTD traces for all of them, and later, use the TTD Position objects to set the same moment in time in all the traces. It is a very effective technique when debugging locking issues.\n\n### Examining memory access\n\nThe `Memory` and `MemoryForPositionRange` methods of the TTD Session object return [TTD Memory objects](https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/time-travel-debugging-memory-objects) describing various operations on the memory. For example, the command below shows all the changes to the global GcInProgress variable in a .NET application:\n\n```shell\ndx -g @$cursession.TTD.Memory(&coreclr!g_pGCHeap->GcInProgress, &coreclr!g_pGCHeap->GcInProgress+4, \"w\")\n# ==============================================================================================================================================================================================================================================================================================================\n# =          = (+) EventType = (+) ThreadId = (+) UniqueThreadId = (+) TimeStart = (+) TimeEnd = (+) AccessType = (+) IP            = (+) Address       = (+) Size = (+) Value        = (+) OverwrittenValue = (+) SystemTimeStart                            = (+) SystemTimeEnd                              =\n# ==============================================================================================================================================================================================================================================================================================================\n# = [0x0]    - 0x1           - 0x2c80       - 0x2                - C79:58C       - C79:58C     - Write          - 0x7ff8fdbce0ee    - 0x7ff8fe00caf0    - 0x8      - 0x2b4800c9bc0    - 0x0                  - poniedziałek, 15 kwietnia 2024 10:14:18.475    - poniedziałek, 15 kwietnia 2024 10:14:18.475    =\n# = [0x1]    - 0x1           - 0x2c80       - 0x2                - 3AF4:5A       - 3AF4:5A     - Write          - 0x7ff8fdcdacc3    - 0x7ff8fe00cae8    - 0x4      - 0x1              - 0x0                  - poniedziałek, 15 kwietnia 2024 10:14:20.896    - poniedziałek, 15 kwietnia 2024 10:14:20.896    =\n# = [0x2]    - 0x1           - 0x2c80       - 0x2                - 3B26:E6C      - 3B26:E6C    - Write          - 0x7ff8fdcdacc3    - 0x7ff8fe00cae8    - 0x4      - 0x0              - 0x1                  - poniedziałek, 15 kwietnia 2024 10:14:20.910    - poniedziałek, 15 kwietnia 2024 10:14:20.910    =\n# = [0x3]    - 0x1           - 0x2c80       - 0x2                - 87DF:5A       - 87DF:5A     - Write          - 0x7ff8fdcdacc3    - 0x7ff8fe00cae8    - 0x4      - 0x1              - 0x0                  - poniedziałek, 15 kwietnia 2024 10:14:24.539    - poniedziałek, 15 kwietnia 2024 10:14:24.539    =\n# = [0x4]    - 0x1           - 0x2c80       - 0x2                - 880C:50C      - 880C:50C    - Write          - 0x7ff8fdcdacc3    - 0x7ff8fe00cae8    - 0x4      - 0x0              - 0x1                  - poniedziałek, 15 kwietnia 2024 10:14:24.548    - poniedziałek, 15 kwietnia 2024 10:14:24.548    =\n# = [0x5]    - 0x1           - 0x2c80       - 0x2                - 889F:5A       - 889F:5A     - Write          - 0x7ff8fdcdacc3    - 0x7ff8fe00cae8    - 0x4      - 0x1              - 0x0                  - poniedziałek, 15 kwietnia 2024 10:14:25.769    - poniedziałek, 15 kwietnia 2024 10:14:25.769    =\n# ==============================================================================================================================================================================================================================================================================================================\n```\n\nThe `MemoryForPositionRange` method allows us to additionally limit memory access queries to a specific time-range. It makes sense to use this method for scope-based addresses, such as function parameters or local variables. Below, you may see an example of a query when we list all the places in the CreateFileW function that read the file name (the first argument to the function):\n\n```shell\ndx -s @$call = @$cursession.TTD.Calls(\"kernelbase!CreateFileW\").First()\ndx -g @$cursession.TTD.MemoryForPositionRange(@$call.Parameters[0], @$call.Parameters[0] + sizeof(wchar_t), \"r\", @$call.TimeStart, @$call.TimeEnd)\n# ======================================================================================================================================================\n# =          = (+) Position = ThreadId  = UniqueThreadId = Address          = IP                = Size   = AccessType = Value               = (+) Data =\n# ======================================================================================================================================================\n# = [0x0]    - AB:1981      - 0x2018    - 0x2            - 0x236011c33c0    - 0x7ff91e04a836    - 0x2    - Read       - 0x55005c003a0043    - {...}    =\n# = [0x1]    - AB:1AD4      - 0x2018    - 0x2            - 0x236011c33c0    - 0x7ff91e04b6e1    - 0x2    - Read       - 0x55005c003a0043    - {...}    =\n# = [0x2]    - AB:1C27      - 0x2018    - 0x2            - 0x236011c33c0    - 0x7ff91e04b796    - 0x2    - Read       - 0x55005c003a0043    - {...}    =\n# = [0x3]    - AB:1C5E      - 0x2018    - 0x2            - 0x236011c33c0    - 0x7ff91e04bca9    - 0x2    - Read       - 0x55005c003a0043    - {...}    =\n# = [0x4]    - AB:1CC8      - 0x2018    - 0x2            - 0x236011c33c0    - 0x7ff91e04caa8    - 0x2    - Read       - 0x55005c003a0043    - {...}    =\n# = [0x5]    - AB:1CCA      - 0x2018    - 0x2            - 0x236011c33c0    - 0x7ff91e04caae    - 0x2    - Read       - 0x55005c003a0043    - {...}    =\n# = [0x6]    - AB:1CCF      - 0x2018    - 0x2            - 0x236011c33c0    - 0x7ff91e04cabe    - 0x2    - Read       - 0x55005c003a0043    - {...}    =\n# = [0x7]    - AB:1E23      - 0x2018    - 0x2            - 0x236011c33c0    - 0x7ff91e04bd5a    - 0x2    - Read       - 0x55005c003a0043    - {...}    =\n# = [0x8]    - AB:1E2A      - 0x2018    - 0x2            - 0x236011c33c0    - 0x7ff91e04bd7b    - 0x2    - Read       - 0x55005c003a0043    - {...}    =\n# = [0x9]    - AB:1E5C      - 0x2018    - 0x2            - 0x236011c33c0    - 0x7ff91e04be56    - 0x2    - Read       - 0x55005c003a0043    - {...}    =\n# = [0xa]    - AB:1E68      - 0x2018    - 0x2            - 0x236011c33c0    - 0x7ff91e04be7a    - 0x2    - Read       - 0x55005c003a0043    - {...}    =\n# ======================================================================================================================================================\n```\n\nMisc tips\n---------\n\n### Converting a memory dump from one format to another\n\nWhen debugging a full memory dump (**/ma**), we may convert it to a smaller memory dump using again the `.dump` command, for example:\n\n```shell\n.dump /mpi c:\\tmp\\smaller.dmp\n```\n\n### Loading an arbitrary DLL into WinDbg for analysis\n\nWinDbg allows analysis of an arbitrary PE file if we load it as a crash dump (the **Open dump file** menu option or the -z command-line argument), for example: `windbgx -z C:\\Windows\\System32\\shell32.dll`. WinDbg will load a DLL/EXE as a data file.\n\nAlternatively, if we want to normally load the DLL, we may use **rundll32.exe** as our debugging target and wait until the DLL gets loaded, for example: `windbgx -c \"sxe ld:jscript9.dll;g\" rundll32.exe .\\jscript9.dll,TestFunction`. The TestFunction in the snippet could be any string. Rundll32.exe loads the DLL before validating the exported function address.\n\n### Keyboard and mouse shortcuts\n\nThe **SHIFT + \\[UP ARROW\\]** completes the current command from previously executed commands (much as F8 in cmd).\n\nIf you double-click on a word in the command window in WinDbgX, the debugger will **highlight** all occurrences of the selected term. You may highlight other words with different colors if you press the ctrl key when double-clicking on them. To unhighlight a given word, double-click on it again, pressing the ctrl key.\n\n### Running a command for all the processes\n\n```shell\ndx -r2 @$cursession.Processes.Where(p => p.Name == \"test.exe\").Select(p => Debugger.Utility.Control.ExecuteCommand(\"|~[0n\" + p.Id + \"]s;bp testlib!TestMethod \\\".lastevent; r @rdx; u poi(@rdx); g\\\"\"))\n```\n\n### Attaching to multiple processes at once\n\nIn PowerShell:\n\n```shell\nGet-Process -Name disp+work | where Id -ne 6612 | % { \".attach -b 0n$($_.Id)\" } | Out-File -Encoding ascii c:\\tmp\\attach_all.txt\nwindbgx.exe -c \"`$`$<C:\\tmp\\attach_all.txt\" -pn winver.exe\n```\n\n### Injecting a DLL into a process being debugged\n\nYou may use the `!injectdll` command from my [lldext](https://github.com/lowleveldesign/lldext) extension.\n\nOr use the `.call` method, as shown in the shell32.dll example below. We start by allocating some space for the DLL name and filling it up:\n\n```shell\n.dvalloc 0x1a\n# Allocated 1000 bytes starting at 00000279`c1be0000\n\nezu 00000279`c1be0000 \"shell32.dll\"\n\ndu 00000279`c1be0000\n# 00000279`c1be0000  \"shell32.dll\"\n```\n\nThe .call command requires private symbols. Microsoft does not publish public symbols for KernelBase!LoadLibraryW, but we may create them (thanks to the [SymbolBuilderComposition extension](https://github.com/microsoft/WinDbg-Samples/tree/master/TargetComposition/SymBuilder)):\n\n```shell\n? kernelbase!LoadLibraryW - kernelbase\n# Evaluate expression: 533568 = 00000000`00082440\n\n.load c:\\dbg64ex\\SymbolBuilderComposition.dll\n\ndx @$sym = Debugger.Utility.SymbolBuilder.CreateSymbols(\"kernelbase.dll\")\n\ndx @$fnLoadLibraryW = @$sym.Functions.Create(\"LoadLibraryW\", \"void*\", 0x0000000000082440, 0x8)\ndx @$param =  @$fnLoadLibraryW.Parameters.Add(\"lpLibFileName\", \"wchar_t*\")\ndx @$param.LiveRanges.Add(0, 8, \"@rcx\")\n\n.reload /f kernelbase.dll\n\n.call kernelbase!LoadLibraryW(0x00000279`c1be0000)\n\n~.g\n\nlm\n# start             end                 module name\n# ...\n# 00007ff9`b3390000 00007ff9`b3be9000   SHELL32    (deferred)\n# ...\n```\n\n### Save and reopen formatted WinDbg output\n\nSometimes you may want to persist debugger output while preserving DML tags. This is achieved using the **Save Window to File** button in the **Command** ribbon tab. The resulting file uses a .dml extension; opening it in a text editor confirms that the markup remains intact.\n\nTo reload this output into a new WinDbg command window, use the `.dml_start` command:\n\n```shell\n.dml_start C:\\temp\\test.dml\n```\n\n{% endraw %}\n"
  },
  {
    "path": "guides/windows-performance-counters.md",
    "content": "---\nlayout: page\ntitle: Windows Performance Counters\ndate: 2024-01-01 08:00:00 +0200\nredirect_from:\n  - /guides/using-perfomance-counters/\n---\n\n{% raw %}\n\n**Table of contents:**\n\n<!-- MarkdownTOC -->\n\n- [General information](#general-information)\n- [Listing Performance Counters installed in the system](#listing-performance-counters-installed-in-the-system)\n- [Collecting performance data](#collecting-performance-data)\n- [Examining the collected performance data](#examining-the-collected-performance-data)\n    - [Using system tools](#using-system-tools)\n    - [Using Log Parser](#using-log-parser)\n    - [Save performance data in SQL Server](#save-performance-data-in-sql-server)\n- [Fix problems with Performance Counters](#fix-problems-with-performance-counters)\n    - [Corrupted counters](#corrupted-counters)\n\n<!-- /MarkdownTOC -->\n\n## General information\n\nThe Performance Counter selection uses following syntax: `\\\\Computer\\PerfObject(ParentInstance/ObjectInstance#InstanceIndex)\\Counter`.\n\nIn order to match the process instance index with a PID you may use a special counter `\\Process(*)\\ID Process`. Similar counter (`\\.NET CLR Memory(*)\\Process ID`) exists for .NET Framework apps. If we want to track performance data for a particular process, we should start with collecting data from those two counters, for example:\n\n```shell\ntypeperf -c \"\\Process(*)\\ID Process\" -si 1 -sc 1 -f CSV -o pids.txt\ntypeperf -c \"\\.NET CLR Memory(*)\\Process ID\" -si 1 -sc 1 -f CSV -o clr-pids.txt\n```\n\nAn application that supports Performance Counters must have a **Performance** key under the **HKLM\\SYSTEM\\CurrentControlSet\\Services\\appname** key. The following example shows the values that you must include for this key.\n\n    HKEY_LOCAL_MACHINE\n       \\SYSTEM\n          \\CurrentControlSet\n             \\Services\n                \\application-name\n                   \\Linkage\n                      Export = a REG_MULTI_SZ value that will be passed to the `OpenPerformanceData` function\n                   \\Performance\n                      Library = Name of your performance DLL\n                      Open = Name of your Open function in your DLL\n                      Collect = Name of your Collect function in your DLL\n                      Close = Name of your Close function in your DLL\n                      Open Timeout = Timeout when waiting for the `OpenPerformanceData` to finish\n                      Collect Timeout = Timeout when waiting for the `CollectPerformanceData` to finish\n                      Disable Performance Counters = A value added by system if something is wrong with the library\n\nThe Performance Counter names and descriptions are stored under the **HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Perflib** key in the registry.\n\n    HKEY_LOCAL_MACHINE\n       \\SOFTWARE\n          \\Microsoft\n             \\Windows NT\n                \\CurrentVersion\n                   \\Perflib\n                      Last Counter = highest counter index\n                      Last Help = highest help index\n                      \\009\n                         Counters = 2 System 4 Memory...\n                         Help = 3 The System Object Type...\n                      \\supported language, other than English\n                         Counters = ...\n                         Help = ...\n\n## Listing Performance Counters installed in the system\n\nTo list the available Performance Counters we may use the **Get-Counter** cmdlet in **PowerShell** or the **typeperf** command.\n\nFor example, below, we look for Performance Counters in the `processor` set:\n\n```\nPS> Get-Counter -listset processor\n\nCounterSetName     : Processor\nMachineName        : .\nCounterSetType     : MultiInstance\nDescription        : The Processor performance object consists of counters that measure aspects of processor activity.\n                     The processor is the part of the computer that performs arithmetic and logical computations, initi\n                     ates operations on peripherals, and runs the threads of processes.  A computer can have multiple p\n                     rocessors.  The processor object represents each processor as an instance of the object.\nPaths              : {\\Processor(*)\\% Processor Time, \\Processor(*)\\% User Time, \\Processor(*)\\% Privileged Time, \\Proc\n                     essor(*)\\Interrupts/sec...}\nPathsWithInstances : {\\Processor(0)\\% Processor Time, \\Processor(1)\\% Processor Time, \\Processor(_Total)\\% Processor Ti\n                     me, \\Processor(0)\\% User Time...}\nCounter            : {\\Processor(*)\\% Processor Time, \\Processor(*)\\% User Time, \\Processor(*)\\% Privileged Time, \\Proc\n                     essor(*)\\Interrupts/sec...}\n```\n\nThe Get-Counter cmdlet accepts also **wildcards** and is case insensitive so to list Performance Counter sets which starts with `.net` you may issue command: `Get-Counter -listset .net*`. \n\nTo find all Performance Counters for the `.NET CLR Memory` object using **typeperf**, we could run:\n\n```\n> typeperf -q \".NET CLR Memory\"\n\\.NET CLR Memory(*)\\# Gen 0 Collections\n\\.NET CLR Memory(*)\\# Gen 1 Collections\n...\n```\n\nIf we also want to include instance information:\n\n```\n> typeperf -qx \".NET CLR Memory\"\n\\.NET CLR Memory(_Global_)\\# Gen 0 Collections\n\\.NET CLR Memory(powershell)\\# Gen 0 Collections\n\\.NET CLR Memory(powershell#1)\\# Gen 0 Collections\n\\.NET CLR Memory(_Global_)\\# Gen 1 Collections\n\\.NET CLR Memory(powershell)\\# Gen 1 Collections\n...\n```\n\nFinally, the **lodctr** extracts Performance Counters information from the registry:\n\n```\n> lodctr /q:\".NET CLR Data\"\nPerformance Counter ID Queries [PERFLIB]:\n    Base Index: 0x00000737 (1847)\n    Last Counter Text ID: 0x0000435A (17242)\n    Last Help Text ID: 0x0000435B (17243)\n\n[.NET CLR Data] Performance Counters (Enabled)\n    DLL Name: netfxperf.dll\n    Open Procedure: OpenPerformanceData\n    Collect Procedure: CollectPerformanceData\n    Close Procedure: ClosePerformanceData\n    First Counter ID: 0x000013A4 (5028)\n    Last Counter ID: 0x000013B0 (5040)\n    First Help ID: 0x000013A5 (5029)\n    Last Help ID: 0x000013B1 (5041)\n```\n\n## Collecting performance data\n\nWe could use the same tools we used for querying also to collect Performance Counters data. In **PowerShell**, to collect 50 samples (with 1s interval) from all the process counters and save them to a binary file we could run the following set of commands: \n\n```shell\n(Cet-Counter -listset process).Paths > counters.txt\nGet-Counter (gc .\\counters.txt) -sampleinterval 1 -maxsamples 20 | Export-Counter testdata.blg -FileFormat BLG  -Force\n```\n\nAnother example shows how to collect samples with interval 2s until ctrl-c is pressed:\n\n```shell\nGet-Counter (gc .\\counters.txt) -sampleinterval 2 -continuous /\n```\n\nWe may achieve the same results with **typeperf**, for example:\n\n```shell\ntypeperf -cf .\\counters.txt -si 1 -o testdata.blg -f BIN -sc 20\ntypeperf -cf .\\counters.txt -si 1\n```\n\nOf course, with both PowerShell or typeperf, we may also retrieve only one counter data:\n\n```shell\ntypeperf -c \"\\process(*)\\% Processor Time\" -si 1 -sc 20 -o testdata.blg -f BIN\n```\n\nFinally, we have a gui tool, **perfmon** that allows us to pick the interesting counters and present their values in a graph. We may also trigger a scheduled task when a specific counter threshold is met. You just need to manually create a **User-Created Data Collector** of type **Performance Counter Alert**. You will then be able select which counter values are interesting for you.\n\n## Examining the collected performance data\n\n### Using system tools\n\nIf we saved the counters data to a binary file, we can open it with **perfmon**:\n\n```shell\nperfmon /sys /open \"c:\\temp\\testdata.blg\"\n```\n\n*REMARK: Remember to specify full path to the binary file.*\n\nA command line tool to query the collected performance data is **relog**. For example, to list the Performance Counters available in the input file, run the following command:\n\n```shell\nrelog -q testdata.blg\n```\n\nIn PowerShell, the **Import-Counter** cmdlet reads performance data generated by any Performance Counter tool and converts it to the performance data objects (the same as generated by the **Get-Counter** command).\n\nCollect Performance Counter binary data and convert it using the **Import-Counter** cmdlet:\n\n```shell\ntypeperf -cf .\\counters.txt -si 1 -o testdata.blg -f BIN -sc 20\nImport-Counter .\\testdata.blg\n```\n\nThe Import-Counter cmdlet may show statistics for the performance data file, for example:\n\n```\nPS C:\\temp> Import-Counter .\\testdata.blg -summary\n\nOldestRecord                   NewestRecord                   SampleCount\n------------                   ------------                   -----------\n2012-03-31 15:54:27            2012-03-31 15:54:46            20\n```\n\n### Using Log Parser\n\n**[Log Parser Studio](https://techcommunity.microsoft.com/t5/exchange-team-blog/introducing-log-parser-studio/ba-p/601131)** and the command line **[logparser](https://www.microsoft.com/en-in/download/details.aspx?id=24659)** tool (and library) are great data analysing tools and we may use them to query Performance Counters data as well. They do not understand the BLG format so before we can look into the data we need to convert the BLG file to CSV format (additional filtering is possible):\n\n```shell\nrelog -f CSV testdata.blg -o testdata.csv\n```\n\nAnd we are ready to use logparser to parse the data, for example:\n\n```shell\nlogparser \"select * from testdata.csv\" -o:DATAGRID\n\nlogparser \"select top 2 [Event Name], Type, [User Data] into c:\\temp\\test.csv from dumpfile.csv\"\n```\n\nTo draw a chart presenting the Performance Counters data use the following syntax:\n\n```shell\nlogparser \"select [time], [\\\\pecet\\process(system)\\% user time],[\\\\pecet\\process(_total)\\% user time] into test.gif from testdata.csv\" -o:CHART\n\nlogparser \"select to_timestamp(time, 'MM/dd/yyyy HH:mm:ss.ll'), [\\\\pecet\\process(system)\\% user time],[\\\\pecet\\process(_total)\\% user time] into test.gif from testdata.csv\" -o:CHART\n```\n\n### Save performance data in SQL Server\n\nTo save Performance Counters data in SQL Server, you need to create a new Data Source (ODBC) using the SQL Server driver (SQLSRV32.dll). Then run the relog tool, for example:\n\n```\n> relog -f SQL -o SQL:Test!fd .\\memperfdata-blog.csv\n\nInput\n----------------\nFile(s):\n     .\\memperfdata-blog.csv (CSV)\n\nBegin:    2012-4-17 6:44:15\nEnd:      2012-4-17 6:44:25\nSamples:  10\n\n100.00%\n\nOutput\n----------------\nFile:     SQL:Test!fd\n\nBegin:    2012-4-17 6:44:15\nEnd:      2012-4-17 6:44:25\nSamples:  4\n\nThe command completed successfully.\n```\n\nMore information:\n\n- Relog Syntax Examples (for SQL Server)\n  <http://www.resquel.com/ssb/2009/02/26/RelogSyntaxExamplesForSQLServer.aspx>\n- SQL Log File Schema\n  <http://msdn.microsoft.com/en-us/library/aa373198(v=vs.85).aspx>\n\n## Fix problems with Performance Counters\n\n### Corrupted counters\n\nPerformance Counters sometimes might become corrupted - in such a case try to locate last Performance Counter data backup in C:\\Windows\\System32 folder. It should have a name similar to **PerfStringBackup.ini**. Before making any changes make backup of your current perf counters:\n\n```\nlodctr /S:PerfStringBackup_broken.ini\n```\n\nand then restore the counters:\n\n```\nlodctr /R:PerfStringBackup.ini\n```\n\n{% endraw %}\n"
  },
  {
    "path": "guides.md",
    "content": "---\nlayout: page\ntitle: Guides\n---\n\nPlease first check the [Windows degugging configuration guide](configuring-windows-for-effective-troubleshooting) as it presents fundamental settings and tools for effective problems troubleshooting on Windows. Similarly, I published the [Linux debugging configuration guide](configuring-linux-for-effective-troubleshooting) (work in progress).\n\n### :triangular_ruler: Troubleshooting scenarios\n\n#### [Diagnosing .NET applications](diagnosing-dotnet-apps)\n\nThis guide describes ways of troubleshooting various problems in .NET applications, such as high CPU usage, memory leaks, network issues, etc.\n\n#### [Diagnosing native Windows applications](diagnosing-native-windows-apps)\n\nThis guide describes ways of troubleshooting various problems in native applications on Windows, such as high CPU usage, hangs, abnormal terminations, etc.\n\n#### [COM troubleshooting](com-troubleshooting)\n\nA guide presenting troubleshooting techniques and tools (including the [comon extension](https://github.com/lowleveldesign/comon)) useful for debugging COM objects.\n\n### :wrench: Tools usage\n\n#### [WinDbg usage guide](windbg)\n\nMy field notes describing usage of WinDbg and WinDbgX (new WinDbg).\n\n#### [GDB usage guide](gdb)\n\nMy field notes describing usage of GDB.\n\n#### [Event Tracing for Windows (ETW)](etw)\n\nThis guide describes how to collect and analyze ETW traces.\n\n#### [Linux Kernel Tracing](linux-tracing)\n\nThe guide presents tracing frameworks available through `/sys/kernel/tracing` mount point.\n\n#### [eBPF](ebpf)\n\nThe guide describes how to use eBPF to trace system and application events.\n\n#### [Network tracing tools](network-tracing-tools)\n\nThis guide lists various network tools you may use to diagnose connectivity problems and collect network traces on Windows and Linux.\n\n#### [Windows Performance Counters](windows-performance-counters)\n\nThe guide presents how to query Windows Performance Counters and analyze the collected data.\n\n#### [Using withdll and detours to trace Win API calls](using-withdll-and-detours-to-trace-winapi)\n\nThis guide describes how to use [withdll](https://github.com/lowleveldesign/withdll) and [Detours](https://github.com/microsoft/Detours) samples to collect traces of Win API calls.\n"
  },
  {
    "path": "index.md",
    "content": "---\ntitle: wtrace.net\ndescription: Tools and materials for software and system troubleshooting \nfeature_image: /assets/img/background.jpg\n---\n\n## Hello fellow troubleshooters!\n\nI created this site to share guides and tools that I developed during my career as a software developer and troubleshooter. The [**guides**](/guides/) focus on practical techniques, tools, and scripts with usage examples rather than theoretical concepts. I regularly update them with new discoveries and insights.\n\n### Quick Links\n\n- [WinDbg usage guide](/guides/windbg)\n- [Diagnosing native Windows applications](/guides/diagnosing-native-windows-apps)\n- [Diagnosing .NET applications](/guides/diagnosing-dotnet-apps)\n- [Network tracing tools](/guides/network-tracing-tools/)\n- [Event Tracing for Windows](/guides/etw)\n"
  },
  {
    "path": "site.webmanifest",
    "content": "{\n    \"name\": \"\",\n    \"short_name\": \"\",\n    \"icons\": [\n        {\n            \"src\": \"/android-chrome-192x192.png\",\n            \"sizes\": \"192x192\",\n            \"type\": \"image/png\"\n        },\n        {\n            \"src\": \"/android-chrome-512x512.png\",\n            \"sizes\": \"512x512\",\n            \"type\": \"image/png\"\n        }\n    ],\n    \"theme_color\": \"#ffffff\",\n    \"background_color\": \"#ffffff\",\n    \"display\": \"standalone\"\n}\n"
  },
  {
    "path": "tools.md",
    "content": "---\nlayout: page\ntitle: Tools\n---\n\n### :feet: Tracing tools\n\n#### [wtrace](https://github.com/lowleveldesign/wtrace)\n\nA command-line tool for live recording ETW trace events on Windows systems. Wtrace collects, among others, File I/O and Registry operations, TPC/IP connections, and RPC calls. Its purpose is to give you some insights into what is happening in the system.\n\n#### [dotnet-wtrace](http://github.com/lowleveldesign/dotnet-wtrace)\n\nA cross-platform command-line tool for live recording .NET trace events. Dotnet-wtrace collects, among others, GC, network, ASP.NET Core, and exception events.\n\n#### [withdll](https://github.com/lowleveldesign/withdll)\n\nA small tool which can inject DLLs into already running and newly started processes. The injected DLL may, for example, trace or patch functions in the remote process.\n\n### :beetle: Debugging tools\n\n#### [lldext](https://github.com/lowleveldesign/lldext) (a WinDbg extension)\n\nThe repository contains the source code of a native lldext extension and my various scripts enhancing debugging with WinDbg.\n\n#### [comon](https://github.com/lowleveldesign/comon) (a WinDbg extension)\n\nA WinDbg extension showing traces of COM class creations and interface querying. You may use it to investigate various COM issues and better understand application logic.\n"
  }
]