C#顶级语句的主函数

起因

在做一个测试使用的顶级语句,要把汇编显示出来的时候,发现指定生成汇编代码的方法Main的时候,是没有生成汇编代码,于是看看顶级语句和普通的Main函数有什么差异.

顶级语句

Console.WriteLine("hello csharp");
#输出Main方法的汇编代码
$env:DOTNET_JitDisasm="Main"

csharp-hello-disasm

于是将使用顶级语句生成的dll(动态库),进行反编译看看有没有Main函数

using System;
using System.Runtime.CompilerServices;

[CompilerGenerated]  //使用顶级语句,在编译时,自动生成Program
internal class Program
{
    private static void <Main>$(string[] args)  //没有生成Main函数,而是叫<Main>$
    { 
        Console.WriteLine("hello csharp");
    }
}

所以要修改一下指定的函数名称:

#顶级语句,不是Main,而是<Main>$
$env:DOTNET_JitDisasm="<Main>$"
; Assembly listing for method Program:<Main>$(System.String[])
; Emitting BLENDED_CODE for X64 with AVX - Windows
; debuggable code
; rbp based frame
; fully interruptible
; No PGO data
; Final local variable assignments
;
;  V00 arg0         [V00    ] (  1,  1   )     ref  ->  [rbp+10H]   do-not-enreg[] class-hnd
;  V01 OutArgs      [V01    ] (  1,  1   )  struct (32) [rsp+00H]   do-not-enreg[XS] addr-exposed "OutgoingArgSpace"
;
; Lcl frame size = 40

G_M56640_IG01:  ;; offset=0000H
       push     rbp
       push     rdi
       sub      rsp, 40
       lea      rbp, [rsp+30H]
       mov      gword ptr [rbp+10H], rcx
                                                ;; size=15 bbWeight=1 PerfScore 3.75
G_M56640_IG02:  ;; offset=000FH
       cmp      dword ptr [(reloc 0x7ffc2a49b7e0)], 0
       je       SHORT G_M56640_IG04
                                                ;; size=9 bbWeight=1 PerfScore 4.00
G_M56640_IG03:  ;; offset=0018H
       call     CORINFO_HELP_DBG_IS_JUST_MY_CODE
                                                ;; size=5 bbWeight=0.50 PerfScore 0.50
G_M56640_IG04:  ;; offset=001DH
       mov      rcx, 0x1E8008317E8      ; 'hello csharp'

       call     [System.Console:WriteLine(System.String)]
       nop
       nop
                                                ;; size=18 bbWeight=1 PerfScore 3.75
G_M56640_IG05:  ;; offset=002FH
       add      rsp, 40
       pop      rdi
       pop      rbp
       ret
                                                ;; size=7 bbWeight=1 PerfScore 2.25

; Total bytes of code 54, prolog size 15, PerfScore 19.65, instruction count 16, allocated bytes for code 54 (MethodHash=79b422bf) ; for method Program:<Main>$(System.String[])
; ============================================================

hello csharp


秋风 2023-05-14