.Net基础——程序集与CIL

时间:2023-03-08 19:15:45

1. 程序集和CIL:

  • 程序集是由.NET语言的编译器接受源代码文件产生的输出文件,通常分为 exe和dll两类,其中exe包含Main入口方法可以双击执行,dll则需要被其他程序集调用执行。
  • CIL(Common Intermediate Language): 公共中间语言,需要被编译成二进制机器码之后才会被计算机执行。

2. 程序集包含:

  • 程序的CIL
  • 程序中使用的类型的元数据(metadata)
  • 程序集清单
  • 一些资源集

程序被编译成程序集(exe为例)之后,双击运行,程序集会被加载入CLR(Common Language Runtime),执行下面的步骤:
  1.检查程序集的安全特性。
  2.进行内存分配。
  3.把程序集中的可执行代码发送给JIT(Just-in-Time)编译器,把其中的一部分代码编译成为本机代码。
其中,JIT只会编译被调用的部分CIL代码,并把编译的结果缓存起来,以备在后面的程序中的多次调用, 这保证了编译与运行的效率。

经过JIT编译之后的代码即是本机代码,本机代码最终被CPU执行。

我们通过一段简单的代码来加深理解:

1. 打开VS,用C#编写一段如下程序:

using System;

namespace ILTest
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello Fred");
Console.Read();
}
}
}

2. 使用 ILASM 工具将程序集反编译为IL(也可生成为ILTest.txt,后缀名不影响文本文件内容):

ildasm ILTest.exe /output:ILTest.IL

生成文本文件如下:

 //  Microsoft (R) .NET Framework IL Disassembler.  Version 4.6.1055.0

 // Metadata version: v4.0.30319
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C E0 ) // .z\V.4..
.ver :::
}
.assembly ILTest
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( )
.custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 4E 6F 6E // ....T..WrapNonEx
6F 6E 6F ) // ceptionThrows. // --- 下列自定义特性会自动添加,不要取消注释 -------
// .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 07 01 00 00 00 00 ) .custom instance void [mscorlib]System.Reflection.AssemblyTitleAttribute::.ctor(string) = ( 4C ) // ...ILTest..
.custom instance void [mscorlib]System.Reflection.AssemblyDescriptionAttribute::.ctor(string) = ( )
.custom instance void [mscorlib]System.Reflection.AssemblyConfigurationAttribute::.ctor(string) = ( )
.custom instance void [mscorlib]System.Reflection.AssemblyCompanyAttribute::.ctor(string) = ( )
.custom instance void [mscorlib]System.Reflection.AssemblyProductAttribute::.ctor(string) = ( 4C ) // ...ILTest..
.custom instance void [mscorlib]System.Reflection.AssemblyCopyrightAttribute::.ctor(string) = ( 6F C2 A9 // ...Copyright ..
) // 2018..
.custom instance void [mscorlib]System.Reflection.AssemblyTrademarkAttribute::.ctor(string) = ( )
.custom instance void [mscorlib]System.Runtime.InteropServices.ComVisibleAttribute::.ctor(bool) = ( )
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 2D // ..$84f5b40e-91ae
2D 2D 2D // -4bfc-ab89-4a0ff
) // f6d081a..
.custom instance void [mscorlib]System.Reflection.AssemblyFileVersionAttribute::.ctor(string) = ( 2E 2E 2E ) // ...1.0.0.0..
.custom instance void [mscorlib]System.Runtime.Versioning.TargetFrameworkAttribute::.ctor(string) = ( 1C 2E 4E 6D 6F 6B // ....NETFramework
2C 6F 6E 3D 2E 2E // ,Version=v4.6.1.
0E 6D 6F 6B // .T..FrameworkDis
6C 4E 6D 2E 4E // playName..NET Fr
6D 6F 6B 2E 2E ) // amework 4.6.1
.hash algorithm 0x00008004
.ver :::
}
.module ILTest.exe
// MVID: {90543B0E-D1B4-4FFF-9260-57E27FBC4F8B}
.imagebase 0x00400000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003 // WINDOWS_CUI
.corflags 0x00020003 // ILONLY 32BITPREFERRED
// Image base: 0x00960000 // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi beforefieldinit ILTest.Program
extends [mscorlib]System.Object
{
.method public hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// 代码大小 19 (0x13)
.maxstack
IL_0000: nop
IL_0001: ldstr "Hello Fred"
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: call int32 [mscorlib]System.Console::Read()
IL_0011: pop
IL_0012: ret
} // end of method Program::Main .method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// 代码大小 8 (0x8)
.maxstack
IL_0000: ldarg.
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method Program::.ctor } // end of class ILTest.Program //

其中包含了程序的元数据,程序集清单和一些其他资源信息。

它们描述并组成了这段程序的类型信息,安全信息,版本信息以及对其它程序集的引用信息等,使得程序集拥有了自我描述的特性。其中,元数据是反射得以实现的重要条件。

除此之外还包含了IL代码,IL是经过编译器(这里是csc)编译产生的中间语言代码。

我们可以通过修改IL代码来控制程序的执行:

打开生成的文本文件,将Main方法中的输出字符串修改为"Hello Tommy":
.Net基础——程序集与CIL

使用ILASM工具将IL文件重新编译成ILTest2.exe:

.Net基础——程序集与CIL

双击运行exe结果如下:

.Net基础——程序集与CIL

也许你会觉得纳闷,为什么要把源代码先翻译成CIL再翻译成本机代码,而不是一步到位呢??

因为当程序被编译成程序集之后就脱离了语言的限制,例如C#程序可以调用VB生成的程序集。

程序集将语言的特殊性转换成了CIL这一通用且规范的概念,好比全国各个地方的人讲着不同的方言,彼此之间难以沟通,但是先将方言翻译成CIL这一普通话,便消除了语言差异带来的交流障碍。

除此之外,如果直接从高级语言编译成机器语言,由于不同厂商生产的CPU会读取不同的指令集,如果有x门高级语言,有y种读取不同指令集的CPU,那么需要有x*y种编译器去将不同的语言与CPU指令一一匹配。

有了CIL之后,我们只需x种编译器将高级语言转换成CIL,再经过y种编译器将CIL转换成二进制指令,一共仅需要x+y种不同的编译器。

原创文章,转载请注明出处。


注:①公共中间语言在一些地方也被叫做MSIL(Microsoft Intermediate Language)或IL(Intermediate Language)。本文中的CIL,IL,MSIL指的都是公共中间语言这一概念。

  ②ILASM和ILDASM工具详见:.Net Framework IL汇编与反汇编工具

相关文章