. NET that little Thing (02). NET operating mechanism

Source: Internet
Author: User

. NET operating mechanism
1. NET program is compiled into what form of code
2 How the JIT works
3 briefly describes the loading mechanism of the Assembly
4 How to configure the version policy for an assembly

1. NET program is compiled into what form of code

. NET program will be compiled the first time after writing is complete. For C #, whether it's a VS IDE or any other indirect approach, essentially executes the compiler cse.exe to compile C # code. After this compilation, the program is compiled into an intermediate code (IL), and all necessary metadata and assemblies are packaged together and loaded onto the file header. The compiled file is a standard Pe/coff application file, and the first part of the file contains the Pe/coff header. And then, yes. NET-specific header information, which includes the assembly version number, file name, and module version number, as well as options such as strong signatures, which are often referred to as CLR headers. After the CLR header is the metadata for the file, the metadata contains all types of definitions, all references, and an assembly's manifest. After that, it's the middle code IL.

Use the. NET ILDASM tool to view metadata and IL code. In the VS Command window, enter:

ILDasm Xxx.exe

The format of the intermediate code is somewhat similar to assembly language, but it cannot be run directly. When the CLR runs an assembly, the IL code is compiled two times as needed, a process known as Instant compilation (Jit,just in time). The immediate compilation is conceptually more consistent with the traditional compilation, the CLR looks at the metadata to determine which intermediate code to load, and compiles the intermediate code of the required assembly in real time, and the result of this compilation is the machine code that will eventually be executed on the CLR.

Instant compilation is the most common method of execution, but it is not the only one.. NET provides another way to deploy, which is to compile intermediate code immediately at deployment time to generate machine code and store it in the cache, which can load the compiled machine code directly when the CLR needs to load the assembly. However, the nature of the second compilation is constant.

. NET program forms the CLR header, meta data, and intermediate code after the first compilation. When the implementation runs and deploys, it will be compiled two times, and the result of the compilation is the machine code executable in the CLR.


2 How the JIT works

When you compile the IL code, the. NET provides two alternative ways of:

    • Real-time compilation with the JIT engine
    • A cache of machine code forms is generated at the time of component deployment for the CLR to invoke.

The CLR loads the order when the CLR needs to execute a method, local cache, and determines that the local cache is the latest version. If the cached version is not up-to-date, the CLR ignores the cached machine code and looks for the latest version of the intermediate code. Also, if the CLR does not find any cached code, it will look for the appropriate intermediate code and compile the intermediate code in a real-time compilation (JIT) fashion.

Real-time compilation requires not only compiling the called method, but also compiling or searching the local cache for all types used by the method.

During the real-time compilation process, the JIT engine looks for a data structure that contains all the method stubs for that type, and for methods that are not compiled into machine code, the stub contains a simple command to invoke JIT, and when the method's real-time compilation is finished, the stub command is replaced with a simple jmp instruction. Causes the code to jump to the machine code location of the method.

In the actual environment, the principle mechanism of different types of methods JIT is different, such as virtual method, delegate method, abstract method, etc.

Before compiling the intermediate code, the JIT engine looks for the method's native machine code cache and determines whether it is available, if it is available directly, if it is unavailable, the JIT engine looks for the method stub in the type, finds the intermediate code, and compiles it.


3 briefly describes the loading mechanism of the Assembly

1. How the assembly is actively loaded
Assembly loading can completely ignore any policy, and the programmer explicitly loads it through the location in the program. System.Reflection.Assembly.LoadFrom (String assemblyfile) provides such a feature. This method takes a codebase-style string that specifies the location of the assembly to load.

CodeBase is a way of specifying a path in. NET, whose value records the location of the module, either a URL, or file://to the local location.

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Reflection;namespaceNET. Mst. second{classLoadFrom {Static voidMain (string[] args) {            //needs to be modified for different host directory structuresString codebase =@".. \.. \.. \.. \2-4 Compile\compile\compile.dll"; //To load an assembly from a specified locationAssembly Compiledll =Assembly.LoadFrom (codebase); //Creating ObjectsObject compile = Compiledll. CreateInstance ("NET.MST.Second.Compile");            Console.WriteLine (compile);        Console.read (); }    }}

In the code, the program actively loads the Compile.dll in the directory of the compile assembly. The CreateInstance method is then used to create a compile type. Note that this is called a parameterless construction method.

Loading assemblies by location is really handy, but it comes with some of the following drawbacks:

    • If an assembly with the same identity is already loaded, LoadFrom still returns the loaded assembly, even if a different path is specified.
    • If you load an assembly with LoadFrom, and then an assembly in the load context attempts to load an assembly with the same display name, the load attempt fails. This behavior can occur when the assembly is deserialized.
    • If you load an assembly with LoadFrom, and the probing path includes an assembly with the same identity but different locations, InvalidCastException, missingmethodexception, or other unexpected behavior occurs.
    • LoadFrom requires that the specified path contain fileiopermissionaccess.read and FileIOPermissionAccess. PathDiscovery or WebPermission.
    • If the assemblyfile has a native image, it is not used. The assembly cannot be loaded as a non-specific domain.


2. Loading assemblies by name, version, culture, and public key
In addition to loading assemblies by location. NET also provides a mechanism for loading assemblies through the assembly's name, version, culture, and public key. The first thing to do is to find a unique assembly through these four elements.


When an assembly is loaded by name, version, culture, and public key, the version policy is applied first to determine all the available versions, and the CLR is searched at the location specified by the CODEBASE , and then in the application domain directory if it fails Search under the application directory , and finally pass the resulting assembly to the loader for loading and compiling.
The application domain directory in the diagram refers to the directory returned by Appdomain.basedirectory, and the application directory refers to the directory that contains the application configuration file.
The CLR provides a program interface that allows programmers to actively load assemblies according to the assembly's name, version, culture, and public key. The System.Reflection.Assembly.Load method is the interface.

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Reflection;namespaceload{classLoad {Static voidMain (string[] args) {            //needs to be modified for different host installation scenariosString assemblyname =@"Compile,"+"version=0.0.0.0,"+"Culture=neutral,"+"PUBLICKEYTOKEN=60C29E5F0AF3E9BB"; //to load an assembly based on the four features of an assemblyAssembly Compiledll =Assembly.Load (AssemblyName); //Creating ObjectsObject compile = Compiledll. CreateInstance ("NET.MST.Second.Compile");            Console.WriteLine (compile);        Console.read (); }    }}

The CLR actively loads the assembly through System.Reflection.Assembly.LoadFrom and System.Reflection.Assemblty.Load. The former passes the location while the latter identifies the assembly by uniquely identifying the 4 elements that strongly name the assembly. The CLR's loading mechanism is consistent with the Load method, and its intrinsic strategy is to find the assembly in turn through version policy, codebase location, application domain location, and application location.


4 How to configure the version policy for an assembly

When an assembly is loaded by name, version, culture, and public key, the CLR allows the programmer to specify which versions of the assembly can be loaded in place of the current version. These are all implemented through version policy. The so-called versioning strategy is the redirection of an assembly version that directs the loading of the current version to an alternative version of loading . Version policies can be configured at the following three levels:

    • Application Policy
    • Publisher policy
    • Computer Policy

These three-level version policies can be configured through an XML file.

1. Application Policy
Application policies can be configured in the application configuration file, and the application configuration file is located in the application directory. For. EXE application whose configuration file is composed of an EXE file name plus a. config suffix name, such as an Test.exe application whose configuration file is Test.exe.config. For any Web application, the file name of its profile is Web. config.
The version policy is recorded under the Assemblybinding node of the configuration file. The following code is an example of an application's configuration file, which only selects the version Policy section that this section cares about.
Web. config

<?XML version= "1.0"?><Configuration>  <Runtime>    <assemblybinding>      <!--version redirection of this Assembly -      <dependentassembly>        <assemblyidentityname= "NET.MST.Second.Compile"PublicKeyToken= "60C29E5F0AF3E9BB">        </assemblyidentity>      </dependentassembly>      <!--Redirected Policies -      <BindingRedirectoldversion= "0.0.0.0-12.2.2.2"newversion= "12.3.0.0">      </BindingRedirect>    </assemblybinding>  </Runtime></Configuration>

In this configuration file, the version policy of the NET.MST.SECOND.COMPILE,60C29E5F0AF3E9BB component is specified, which redirects all versions between 0.0.0.0 to 12.2.2.2 to the 12.3.0.0 version.

2. Publisher policy
The publisher policy is for those assemblies that are placed in the global assembly cache (GAC). The name of the publisher policy profile is very strange, and it is a string: the major version number. The minor version number. assembly name. dll. Because of this, there can only be one publisher policy for each major/minor version number of an assembly.

3. Computer Policy
Similarly, the computer policy is also represented by a configuration file, and its format is basically similar to code 2-7. The file name of the computer-level version policy configuration file is: Machine.config, which is stored in the%systemroot%\ Microsoft.net\ the framework\v****\config\ directory.

Read here, the reader may have the question: version policy can be configured at 3 levels, how do these strategies work together? According to. NET mechanism, the 3-level version strategy will be executed sequentially, and the execution results at the previous level will be entered as the next level of execution.

, the 3-level version policy is executed sequentially in the order of the application, Publisher, and computer. Where the publisher policy is optional, the publisher policy will not be executed in the following two scenarios.

    • The assembly was not added to the GAC.
    • Application policy development ignores publisher policies.

In the first case, there is no publisher policy profile at all, and of course the CLR does not execute the publisher policy. In the second case, the programmer specifies that the publisher policy is ignored in the application policy by adding the Publisherpolicy node to the application configuration file and setting the Apply property value to No.
Web. config

<?XML version= "1.0"?><Configuration>  <Runtime>    <assemblybinding>      <!--version redirection of this Assembly -      <dependentassembly>        <assemblyidentityname= "NET.MST.Second.Compile"PublicKeyToken= "60C29E5F0AF3E9BB">        </assemblyidentity>      </dependentassembly>      <!--Redirected Policies -      <BindingRedirectoldversion= "0.0.0.0-12.2.2.2"newversion= "12.3.0.0">      </BindingRedirect>      <!--Specify ignore publisher policy -      <publisherpolicyApply= "No">      </publisherpolicy>    </assemblybinding>  </Runtime></Configuration>

The CLR supports setting a version policy at 3 levels, followed by application policy, publisher policy, and computer policy. All policy settings are implemented by modifying the configuration file. The 3-level policy is executed sequentially by the CLR, and the result of the previous policy is entered as the next policy. The publisher policy is for only those assemblies that are placed in the GAC and can be specified in the application policy to be ignored.

Reprint please specify the source:

Jesselzj
Source: http://jesselzj.cnblogs.com

. NET that little Thing (02). NET operating mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.