Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Application Loader's Command Line Parser

Tags:

c#

.net

I was recently working on a generic parser and gotten to the point of folding ([...] / {...}) management I was interested to know how the .Net args parser works (The parser that is essentially populating the args array in the application entry point).

I started looking around the CLR (mscorlib.dll) but didn't find what is was looking for, so my question is what mechanism is used to parse these arguments, if it's a CLR Type which one it is, or if it's an un-managed P/Invoke call where it's being declared.

like image 686
Matan Shahar Avatar asked May 14 '26 03:05

Matan Shahar


2 Answers

Microsoft recently released the source code of the .NET Compiler Platform, so we can just take a look!

It contains a class Microsoft.CodeAnalysis.CommandLineParser with a SplitCommandLineIntoArguments method, which is described as follows:

/// <summary>
/// Split a command line by the same rules as Main would get the commands.
/// </summary>
/// <remarks>
/// Rules for command line parsing, according to MSDN:
/// ...
/// </remarks>

So here's a complete C# implementation of the args parser, conveniently available under the Apache License:

  • http://source.roslyn.codeplex.com/#Microsoft.CodeAnalysis/NonPortable/CommandLine/CommonCommandLineParser.cs
like image 153
Heinzi Avatar answered May 15 '26 16:05

Heinzi


This is the Call Stack inside the main function of a Console application:

Program.Main(string[] args = {string[0]}) Line 18 + 0x5 bytes   C#
mscoreei.dll!6f79f5a3()     
mscoree.dll!70bc7f16()  
mscoree.dll!70bc4de3()  
kernel32.dll!76f03677()     
ntdll.dll!77c09d72()    
ntdll.dll!77c09d45()    

At least main(string[]) is directly called from the native code. I'm still not sure that the parsing also took place inside the native code, maybe it is a managed function and it was called before main.

like image 41
Alireza Avatar answered May 15 '26 15:05

Alireza