当前位置: 移动技术网 > IT编程>开发语言>c# > 简单介绍托管执行和 CLI

简单介绍托管执行和 CLI

2019年12月10日  | 移动技术网IT编程  | 我要评论

处理器不能直接解释程序集。程序集用的是另一种语言,即公共中间语言(common intermediate language,cil),或称为中间语言(il)。

c# 编译器将 c# 源代码文件转换成中间语言。为了将 cil 代码转换成处理器能理解的机器码,还要完成一个额外的步骤(通常在运行时进行)。该步骤涉及 c# 程序执行的一个重要元素:ves(virtual execution system,虚拟执行系统)。ves 也称为运行时(runtime)。

它根据需要编译 cil 代码,这个过程称为即时编译或 jit 编译(just-in-time compilation)。如代码在像“运行时”这样的一个“代理” 的上下文中执行,就称为托管代码(managed code),在“运行时”的控制下执行的过程则称为托管执行(managed execution)。

之所以 称为“托管”,是因为“运行时”管理着诸如内存分配、安全性和 jit 编译等方面,从而控制了主要的程序行为。执行时不需要“运行时”的代码称为本机代码(native code)或非托管代码(unmanaged code)。

说明:“运行时”既可能指“程序执行的时候”,也可能指“虚拟执行系统”。为明确起见,用“执行时”表示“程序执行的时候”,用“运行时”表示负责管理 c# 程序执行的代理。

“运行时”规范包含在一个包容面更广的规范中,即 cli(common language infrastructure,公共语言基础结构)规范。作为国际标准,cli 包含了以下几方面的规范:

  • ves 或“运行时”。
  • cil。
  • 支持语言互操作性的类型系统,称为 cts(common type system,公共类型系统)。
  • 如何编写通过 cli 兼容语言访问的库的指导原则,这部分内容具体放在公共语言规范(common language specification,cls)中。
  • 使各种服务能被 cli 识别的元数据(包括程序集的布局或文件格式规范)。
  • 在“运行时”执行引擎的上下文中运行,程序员不需要直接写代码就能使用几种服务和功能,包括:

    • 语言互操作性:不同源语言间的互操作性。语言编译器将每种源语言转换成相同中间语言(cil)来实现这种互操作性。
    • 类型安全:检查类型间转换,确保兼容的类型才能相互转换。这有助于防范缓冲区溢出(这是产生安全隐患的主要原因)。
    • 代码访问安全性:程序集开发者的代码有权在计算机上执行的证明。
    • 垃圾回收:一种内存管理机制,自动释放“运行时”为数据分配的空间。
    • 平台可移植性:同一程序集可在多种操作系统上运行。要实现这一点,一个显而易见的限制就是不能使用平台特有的库。所以平台依赖问题需单独解决。
    • bcl(基类库):提供开发者能(在所有 .net 框架中)依赖的大型代码库,使其不必亲自写这些代码。

注意: 本篇只是简单介绍了 cli,目的是让读者熟悉 c# 程序的执行环境。此外,本篇还提及了本系列博文后面才会用到的一些术语。在时机合适的时候,我会专门总结 cli 及其与 c# 的关系。

cil 和 ildasm

前面说过,c# 编译器将 c# 代码转换成 cil 代码而不是机器码。处理器只理解机器码,所以 cil 代码必须先转换成机器码才能由处理器执行。可用 cil 反汇编程序将程序集解构为 cil。通常使用 microsoft 特有的文件名 ildasm 来称呼这种 cil 反汇编程序(ildasm 是 il disassembler 的简称),它能对程序集执行反汇编,提取 c# 编译器生成的cil。

反汇编 .net 程序集的结果比机器码更易理解。许多开发人员害怕即使别人没有拿到源代码,程序也容易被反汇编并曝光其算法。其实无论是否基于 cli,任何程序防止反编译唯一安全的方法就是禁止访问编译好的程序(例如只在网站上存放程序,不把它分发到用户机器)。

但假如目的只是减小别人获得源代码的可能性,可考虑使用一些混淆器(obfuscator)产品。这种产品会打开 il 代码,转换成一种功能不变但更难理解的形式。这可以防止普通开发者访问代码,使程序集难以被反编译成容易理解的代码。除非程序需要对算法进行高级安全防护,否则混淆器足矣。

查看 myapp.dll 的 cil 输出

myapp.dll 程序请参考这篇文章:

安装了 visual studio 之后 ildasm 会默认被安装,位置是:c:\program files (x86)\microsoft sdks\windows\v10.0a(随便一个目录)\bin\netfx 4.8 tools(随便一个目录)\x64

双击运行 ildasm.exe,把 myapp.dll 拖进去,如下图:

双击即可查看到 il 代码,下面是 manifest 的 il 代码

// metadata version: v4.0.30319
.assembly extern system.runtime
{
  .publickeytoken = (b0 3f 5f 7f 11 d5 0a 3a )                         // .?_....:
  .ver 4:2:1:0
}
.assembly extern system.console
{
  .publickeytoken = (b0 3f 5f 7f 11 d5 0a 3a )                         // .?_....:
  .ver 4:1:1:0
}
.assembly myapp
{
  .custom instance void [system.runtime]system.runtime.compilerservices.compilationrelaxationsattribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) 
  .custom instance void [system.runtime]system.runtime.compilerservices.runtimecompatibilityattribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4e 6f 6e 45 78   // ....t..wrapnonex
                                                                                                                   63 65 70 74 69 6f 6e 54 68 72 6f 77 73 01 )       // ceptionthrows.

  // --- 下列自定义特性会自动添加,不要取消注释 -------
  //  .custom instance void [system.runtime]system.diagnostics.debuggableattribute::.ctor(valuetype [system.runtime]system.diagnostics.debuggableattribute/debuggingmodes) = ( 01 00 07 01 00 00 00 00 ) 

  .custom instance void [system.runtime]system.runtime.versioning.targetframeworkattribute::.ctor(string) = ( 01 00 18 2e 4e 45 54 43 6f 72 65 41 70 70 2c 56   // ....netcoreapp,v
                                                                                                              65 72 73 69 6f 6e 3d 76 33 2e 30 01 00 54 0e 14   // ersion=v3.0..t..
                                                                                                              46 72 61 6d 65 77 6f 72 6b 44 69 73 70 6c 61 79   // frameworkdisplay
                                                                                                              4e 61 6d 65 00 )                                  // name.
  .custom instance void [system.runtime]system.reflection.assemblycompanyattribute::.ctor(string) = ( 01 00 05 6d 79 41 70 70 00 00 )                   // ...myapp..
  .custom instance void [system.runtime]system.reflection.assemblyconfigurationattribute::.ctor(string) = ( 01 00 05 44 65 62 75 67 00 00 )                   // ...debug..
  .custom instance void [system.runtime]system.reflection.assemblyfileversionattribute::.ctor(string) = ( 01 00 07 31 2e 30 2e 30 2e 30 00 00 )             // ...1.0.0.0..
  .custom instance void [system.runtime]system.reflection.assemblyinformationalversionattribute::.ctor(string) = ( 01 00 05 31 2e 30 2e 30 00 00 )                   // ...1.0.0..
  .custom instance void [system.runtime]system.reflection.assemblyproductattribute::.ctor(string) = ( 01 00 05 6d 79 41 70 70 00 00 )                   // ...myapp..
  .custom instance void [system.runtime]system.reflection.assemblytitleattribute::.ctor(string) = ( 01 00 05 6d 79 41 70 70 00 00 )                   // ...myapp..
  .hash algorithm 0x00008004
  .ver 1:0:0:0
}
.module myapp.dll
// mvid: {29fc93a2-9a52-445c-a581-09aa5bcc11c7}
.imagebase 0x00400000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003       // windows_cui
.corflags 0x00000001    //  ilonly
// image base: 0x000002015d090000

.class private auto ansi beforefieldint

.class private auto ansi beforefieldinit myapp.program
       extends [system.runtime]system.object
{
} // end of class myapp.program

.ctor:void()

.method public hidebysig specialname rtspecialname 
        instance void  .ctor() cil managed
{
  // 代码大小       8 (0x8)
  .maxstack  8
  il_0000:  ldarg.0
  il_0001:  call       instance void [system.runtime]system.object::.ctor()
  il_0006:  nop
  il_0007:  ret
} // end of method program::.ctor

main:void(string[])

.method private hidebysig static void  main(string[] args) cil managed
{
  .entrypoint
  // 代码大小       42 (0x2a)
  .maxstack  2
  .locals init (valuetype [system.runtime]system.datetime v_0)
  il_0000:  nop
  il_0001:  ldstr      "hello world!"
  il_0006:  call       void [system.console]system.console::writeline(string)
  il_000b:  nop
  il_000c:  ldstr      "the current time is "
  il_0011:  call       valuetype [system.runtime]system.datetime [system.runtime]system.datetime::get_now()
  il_0016:  stloc.0
  il_0017:  ldloca.s   v_0
  il_0019:  call       instance string [system.runtime]system.datetime::tostring()
  il_001e:  call       string [system.runtime]system.string::concat(string,
                                                                    string)
  il_0023:  call       void [system.console]system.console::writeline(string)
  il_0028:  nop
  il_0029:  ret
} // end of method program::main

最开头是清单(manifest)信息。其中不仅包括被反编译的模块的全名(myapp),还包括它依赖的所有模块和程序集及其版本信息。

基于这样的一个 cil 代码清单,最有趣的可能就是能相对比较容易地理解程序所做的事情,这比阅读并理解机器码(汇编程序)容易多了。

上述代码出现了对 system.console.writeline() 的显式引用。 cil 代码清单包含许多外围信息,但如果开发者想要理解 c# 模块(或任何基于 cli 的程序)的内部工作原理,但又拿不到源代码,只要作者没有使用混淆器,理解这样的 cil 代码清单还是比较容易的。

事实上,一些免费工具(比如 red gate reflector,ilspy,justdecompile,dotpeek 和 codereflect)都能将 cil 自动反编译成 c#。

使用 ilspy 查看 myapp.dll 反编译后的代码

ilspy 的地址:https://github.com/icsharpcode/ilspy

双击运行 ilspy.exe,把 myapp.dll 拖进去,如下图:

注意: 反汇编(disassemble)和反编译(decompile)的区别。反汇编得到的是汇编代码,反编译得到的是所用语言的源代码。

原文链接:


  1. cil 的第三种说法是 microsoft il(msil)。 本博客使用 cil 一词,因其是 cli 标准所采纳的。c# 程序员交流时经常使用 il 一词,因为他们都假定 il 是指 cil 而不是其他中间语言。

  2. “运行时”(runtime) 作为名词使用时一律添加引号。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网