core icon indicating copy to clipboard operation
core copied to clipboard

How to debug the source code using Visual Studio 2017?

Open scheshan opened this issue 9 years ago • 94 comments

This question is related to this one.

Is it possible to debug the .NET Core and ASP.NET Core source code in my projects?

scheshan avatar Aug 25 '17 09:08 scheshan

@noahfalk can you give guidance here?

Petermarcu avatar Aug 30 '17 16:08 Petermarcu

Is it possible to debug the .NET Core and ASP.NET Core source code in my projects?

Yes. These instructions are for windows (since we are talking about Visual Studio which only runs on windows. It is also important that we are talking about V2.0 (or later) .NET Core (e.g. what you get from https://www.microsoft.com/net/core#windowscmd)

  1. Uncheck the (Tools -> Options -> Debugging -> Just My Code) checkbox.
  2. Insure that the (Tools -> Options -> Debugging -> Symbol Settings -> Microsoft Symbol Servers) checkbox is set
  3. Insure that the (Tools -> Options -> Debugging -> Enable Source Link support) checkbox is checked

These steps will allow Visual Studio to find the *.PDB files that are needed for the .NET Core and ASP.NET Core libraries. However you need more than just the *.PDB files you also need the source code itself. Going forward we intend for all our libraries to have 'SourceLink' information so that you can fetch the source directly from GitHub. When this is present, VS will simply fetch the source from GitHub and the experience is beautiful. I have tested this on Visual Studio 15.3 (the latest released version).

This 'it just works' experience (when you step into or set breakpoints on framework code VS should simply fetch the correct source code), should work for V2.0 ASP.NET DLLs (that is Microsoft.aspnet*.dll). Sadly the CoreFX, and CoreClr dlls (Typically System.* dlls), will not be fixed until the V2.01 release (In a few weeks) and thus you need to fetch source code yourself using the instructions below.

Getting source from GitHub

Ultimately you should not need to do this, all our DLLs will have SourceLink information and VS will simply fetch it from GitHub for you. However some of our libraries currently do not have SourceLink information. We will fix this but the experience in that case is VS will ask you where to fetch the file from. You can work around this by fetching the source code from GitHub yourself and pointing VS at it.

  1. If the source code path contains src\mscorlib it lives in the https://github.com/dotnet/coreclr
  2. If the source code path contains corefx\src it lives in https://github.com/dotnet/corefx
  3. If the source code path has the form .r*\src where it is an ASP.NET DLL and it lives in https://github.com/aspnet/* (where * is the name from the source code path).
    For example
C:\b\w\f92f3e96777ec37d\.r\Mvc\src\Microsoft.AspNetCore.Mvc\MvcServiceCollectionExtensions.cs

lives in https://github.com/aspnet/Mvc

Once you know the repository, you can fetch the repository and set it to the 2.0.0 version of the source like this.

    git clone https://github.com/dotnet/coreclr
    cd coreclr 
    git checkout v2.0.0

At this point you can answer the VS dialog prompting you for the source file path. Once you set it for one source file it will work for any other source file in the same directory structure.

You can also set up where VS searches without having to wait to be prompted by right clicking on the solution -> Properties -> Debug Source Files and then add your directory to the 'Directories Containing Source Code'. Once you set up these paths, VS should simply find your source code.

Finally there is an option in (Tools -> Options -> Debugging -> General -> Require Source Files to match Exactly) which is set by default. If you have problems getting VS to find your source, you can try unselecting that checkbox to see if your version is wrong and the source checksums don't match.

ASP.NET 2.0 SourceLink (VS fetches from GitHub directly) should be working

The V2.0 ASP.NET DLLs (aspnet.dll) have the needed SourceLink information, they should just work. the instructions above for fetching source code for these DLLs. Please comment below if this is not the case.

Note that we did UPDATE the ASP.NET PDBs so they have sourceLink, which means that if you tried to step into ASP.NET dlls before, you may have already cached an old version of the PDBs and if so, Visual Studio will not try to refetch it. You can force the refetch by exiting Visual Studio deleting the %TEMP%\SymbolCache directory and then retrying. In addition once Visual Studio has attempted to fetch a particular source file it will not attempt doing it again. You can clear that history by right clicking on the solution -> Properties -> Debug Source Files and removing all names from the 'Do not look for these source files' textbox.

vancem avatar Aug 30 '17 23:08 vancem

@vancem Thank you for your detailed introductions. And I still have some advises.

  1. It seems people can easily debugging the nuget packages' source code if the authors add the 'SourceLink information'. Is there any documents about the SourceLink?
  2. Can we directly view the source code by the 'go to the definition' button? Other languages' IDEs(Java, Python, Go) have this feature and I think it will be very useful.

scheshan avatar Aug 31 '17 06:08 scheshan

@scheshan - Visual Studio does have a Edit.GotoDefinition (usually bound to the F12 key), which if activiated will find the symbol the cursor is on. However for code that is not part of the project, it takes you to a 'standin' that represents the interface (what can be determined without the source code). This is because it is more the exception than the rule that you want to debug through code that is not your own (that is why 'just my code' is on by default). I don't know of a way off hand of getting to source code for things outside your project except when actively debugging (but others who know more about VS may know of something).

More information on using SourceLink for your own projects is at https://github.com/ctaggart/SourceLink.

vancem avatar Aug 31 '17 14:08 vancem

@gregg-miskelly may know more about the behavior/limitations of goto definition in VS.

noahfalk avatar Aug 31 '17 20:08 noahfalk

Could go-to-definition be made to work with SourceLink?

*For CoreFX/CoreCLR -- this is probably the wrong approach as the dll that your project references isn't what you are going to running against, and I believe Roslyn already has solutions for indexing select open source projects anyway. *For more normal NuGet packages where the implementation assembly is the same as what you compile against -- seems like an interesting idea to me, but the C# IDE folks would be better to comment on it that I would. @Pilchie @DustinCampbell?

gregg-miskelly avatar Aug 31 '17 23:08 gregg-miskelly

To be clear, if the question is "can 'Go To Definition' be made to work with source link today", then the answer is 'no'.

gregg-miskelly avatar Aug 31 '17 23:08 gregg-miskelly

/cc @tmat

davidfowl avatar Aug 31 '17 23:08 davidfowl

/cc @nguerrera At some point we had an idea that we could recreate a source project from information stored in the PDB -- it would require the compiler to add a bit more information to the PDB (such as unique ids of referenced assemblies and the compilation options used to build the assembly). But the idea hasn't been implemented yet.

Re reference assemblies vs. implementation assemblies -- I could imagine that if the reference assembly is in a nuget package, we could provide UI (e.g. combo box in the editor) with a selection of target frameworks that the package includes implementation assemblies for and then you could select one and that would navigate to the corresponding source.

UPDATE: The above doesn't take into consideration the current debugging context. If we are attached to a process then we know what the current runtime is and thus should be able to find the corresponding implementation assembly automatically. The IDE is currently not taking the current debugging context into consideration in features like Go To Definition, but it perhaps could.

tmat avatar Aug 31 '17 23:08 tmat

Stepping into core source code doesn't work at all for me. I'm trying to figure out why my custom authentication service isn't working properly but I can't step into the ControllerBase.Challenge() method in the following code (which was created by the default project template).

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public IActionResult ExternalLogin(string provider, string returnUrl = null)
    {
      // Request a redirect to the external login provider.
      var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { returnUrl });
      var properties = this.signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
      return Challenge(properties, provider);
    }

If I set a breakpoint at return Challenge(properties, provider); it gets hit when I debug, but when I click "step into (F11)" it skips right over it and goes to the } on the next line.

I'm using VS 2017 (15.3.3) with, as far as I can tell, the proper settings. image image I deleted my %TEMP%/SymbolCache directory which at least caused visual studio to spend a long time downloading various symbols the next time I tried to debug the project. The project is a DotNetCore 2.0 project.

NightWatchman avatar Sep 08 '17 17:09 NightWatchman

@NightWatchman a few questions:

  1. Do you have symbols downloaded for whatever dll contains the implementation of 'Challenge'? (check the modules window)
  2. If so: what happens if you try and step into that function via the disassembly window?
  3. If not: why is downloading symbols failing? (Check symbols information)

gregg-miskelly avatar Sep 09 '17 00:09 gregg-miskelly

I'm going to close this issue now as its been over 30 days without a response. Let us know if you need more assistance.

Petermarcu avatar Oct 12 '17 06:10 Petermarcu

I have a update on this for the current version of .NET Core (Version 2.0.3).

On Windows, if you install this version of the .NET Framework then the normal Microsoft symbol server http://msdl.microsoft.com/download/symbols can find all the necessary symbolic (PDB) and annotated with SourceLink information to do source stepping in both the .NET Runtime Framework (CoreFX) as well as ASP.NET by fetching the symbolic information from that server and the source code from the appropriate GIT repository.

The upshot of this is that if you debug a .NET Core application using version 2.0.3 of the runtime (e,g. from https://www.microsoft.com/net/download/windows) and do the following

  1. Uncheck the (Tools -> Options -> Debugging -> Just My Code) checkbox.
  2. Insure that the (Tools -> Options -> Debugging -> Symbol Settings -> Microsoft Symbol Servers) checkbox is set
  3. Insure that the (Tools -> Options -> Debugging -> Enable Source Link support) checkbox is checked

Then you should be able to step into (or set breakpoints in) Framework or ASP.NET code and the source code will automatically be brought up.

Note that the framework code is precompiled and optimized by default, which means that stepping and local variable access in framework code may not be nice as you would like (variables may be unavailable)

vancem avatar Dec 08 '17 16:12 vancem

One other useful note. As mentioned above, by default the code in the Framework is optimized, however you can force it to NOT be. First you have to run the program with the COMPLUS_ZapDisable=1 environment variable set. You can set this variable conveniently by

  1. Right clicking on the Project (csproj) file in SolutionExplorer -> Properties -> Debug
  2. Click the 'Add' button in the 'Environment Variables' section of the Debug Pane.

This will cause the code to NOT use the rregenerated (Zapped) code. Next tell Visual Studio to suppress optimization by

  • Check the checkbox in Tools -> Options -> Debugging -> General -> Suppress JIT optimization on module Load

Once you do this for your project, you don't need to do it again (until you have another project in which you want to step through framework code.

vancem avatar Dec 08 '17 20:12 vancem

I have written a blog post that is likely to be more user friendly here

https://blogs.msdn.microsoft.com/vancem/2017/12/20/update-debugging-through-the-net-core-framework-v2-0-3-windows/

vancem avatar Dec 20 '17 17:12 vancem

Is there currently a way to set it up so that go to definition brings me to the core source code? It's not really debugging I want this for, it is just to get an idea of what the magic method an article tells me to add actually does for my own understanding as searching on github can be a bit confusing and cumbersome (for me at least).

GuerrillaCoder avatar Jan 12 '18 01:01 GuerrillaCoder

@GuerrillaCoder Not currently. It's a feature we are considering to add to VS.

tmat avatar Jan 12 '18 01:01 tmat

@GuerrillaCoder

Something I have found to be very useful when understanding other people's code is to run a good profiler to allow me to understand it. The basic idea is to collect a DETAILED profile that will show you what your program is doing not to tune is performance but just to browse the execution and goto the source code as you do so. This has the advantage of focusing you in on the important code that actually RUNS in your case.

The PerfView tool is particularly good at doing this because it supports a 'Goto Source' feature that 'just works (if you use Version 2.0.3 of the .NET Core runtime and the V2.0.0 version of PerfView you can run (on windows).

It is pretty slick and works well for the kind of browsing you seem to want to do.

TO do this download the V2.0.0 version of PerfView and run the command

PerfView /DotnetAllocSampled /CpuSampleMSec=.125 collect

Thus turns on sampling (about 5K /sec) on any allocation as well as 8 times a millisecond. This does not slow the program down much but might not give you the level of detail you want (code that does not allocate much or use much CPU will be missed). If you want to catch everything use the /dotnetCalls, but be warned you should only do that in small scenarios because it slows the program down alot.

Once you have your data you can then open up the trace and go to the 'Advanced Group -> Any Stacks' view go to the 'Call Tree' tab (You should also read the tutorial / video on PerfView basics, including symbol resolution and grouping).

But the very cool thing is that once you find a method of interest, for example

system.console!System.Console.WriteLine(System.String)

you can select the node, right click and select 'Goto Source' and PerfView knows enough to fetch the right code from GitHub, download it and show you an annotated version of it.

Very Handy!

vancem avatar Jan 13 '18 01:01 vancem

@vancem That sounds excellent I will give it a go!

GuerrillaCoder avatar Jan 13 '18 10:01 GuerrillaCoder

Are there additional steps for debugging an open sourced package that is not a framework package? I am trying to step through the code for the Newtonsoft serializer, and have followed the instructions given in the blog post, but cannot step into the serializer code.

wiiNinja avatar Jan 19 '18 19:01 wiiNinja