4

This confuses me a lot.

My understanding is that when I compile an application it becomes optimized code that my operating system reads. Things from my source code such as variable names, line numbers, etc., no longer have meaning.

So then how am I able to build-and-run code like

try
{
    // ... 
}
catch ( Exception E )
{
    Console.WriteLine("Exception occured: {0}", E.StackTrace);
} 

and get all this detailed information about what part of my source code is respomsible for an exception.

Now, I understand that in .NET my C# code doesn't intially become low-level "operating system code" but rather Microsoft Intermediary Language. What I'm guessing it that MIL, in order to generate this exception info, perserves some type of mapping between my source code and the compiled code. This seems like a huge waste, isn't it? So "compiling" in .NET isn't really translating source code to machine code; it is creating machine code in addition to source code. That means that all the applications on my Windows machine have metadata pertraining to their source code.

Or am I completely wrong about all this?

MethodMan
  • 18,625
  • 6
  • 34
  • 52
user6048670
  • 2,861
  • 4
  • 16
  • 20

2 Answers2

5

When you compile an assembly the compiler also generates a .pdb file, which is essentially a database file for running your assembly in debug mode. It also contains mappings between the optimized code and the original code, which allows the debugger to know line numbers of methods calls.

Details on .pdb files here: https://msdn.microsoft.com/en-us/library/yd4f8bd1(vs.71).aspx

Federico Dipuma
  • 17,655
  • 4
  • 39
  • 56
2

Stack trace basically contains several parts of information:

  1. Information about what call chain lead to the current execution point. It's not surprise that you can access such information, since when you return from one function, execution should get back to whatever function called it, and so on, up to your program entry point. All function names are also freely available (remember, you can yourself get information about any .NET methods via reflection for example). So this part should not surprise you.

  2. Information about source code file where exception occured, including path to that file (on machine where code was compiled) and line number. This information is stored in separate (.pdb) file, and is optional. If you do not deploy your .pdb files on target machine - you won't see this info in stack traces. You may or may not generate .pdb for your production release, and you may or may not deploy them to target machine.

Evk
  • 98,527
  • 8
  • 141
  • 191