系列首篇,從 C# 編譯輸出的 PE 檔案結構切入,建立「原始碼 → 模組 → 組件 → 執行檔」的完整認知,並實操 ILDasm 反編譯工具。
C# 編譯器 (csc.exe) 將原始碼轉換為:
兩者封裝在符合 Windows PE 格式的 .exe/.dll 中。
工具位於 SDK\bin\ildasm.exe,核心功能:
ildasm foo.exe /output:foo.il 生成 IL 檔 + 資源檔csc /t:module One.cs → One.netmodule
csc /t:library /addmodule:One.netmodule Two.cs → Two.dll
csc /out:App.exe /t:exe /r:Two.dll /r:mscorlib.dll Program.cs → App.exe
關鍵參數:
/t:module 產生無組件清單的模組/addmodule 將模組合併入組件/r 參考組件(mscorlib.dll 為核心庫,含 Console 等)AssemblyDef、FileDef、ExportedTypeDef 等自描述資訊File size : 5632
CLR meta-data size : 2212 (39.28%)
Managed code : 287 (5.10%)
TypeDef - 4 (56 bytes)
MethodDef - 8 (112 bytes)
#Strings - 920 bytes
#Blob - 328 bytes
顯示元數據佔比近 40%,Managed code 僅 5%,印證 .NET 程式「元數據豐富、代碼精簡」特性。
.class public auto ansi beforefieldinit ...Two
extends [mscorlib]System.Object
{
.method public hidebysig instance string SayHello() cil managed
{
.maxstack 1
.locals init ([0] string CS$1$0000)
IL_0000: nop
IL_0001: ldstr "Hello, world."
IL_0006: stloc.0
IL_0007: br.s IL_0009
IL_0009: ldloc.0
IL_000a: ret
}
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
}
關鍵指令:ldstr (載入字面字串)、newobj (建立物件)、callvirt (虛呼叫)、ret (返回)。
深入 44 張元數據表結構、6 大堆、IL 指令集細節與 Metadata Token 機制。