Processo de Execução Gerenciada

De execução gerenciado processo inclui as seguintes etapas são discutidas detalhadamente mais adiante neste tópico:

  1. Choosing a compiler.

    To obtain the benefits provided by the common language runtime, you must use one or more language compilers that target the runtime.

  2. Compilar seu código para MSIL.

    Compilação converte seu código fonte para o Microsoft Intermediate Language (MSIL) e gera os metadadosnecessários.

  3. Compiling MSIL to native code.

    At execution time, a just-in-time (JIT) compiler translates the MSIL into native code. During this compilation, code must pass a verification process that examines the MSIL and metadata to find out whether the code can be determined to be type safe.

  4. Running code.

    O Common Language Runtime fornece a infra-estrutura que permite a execução local e serviços que podem ser usados durante a execução.

Choosing a Compiler

Para obter os benefícios fornecidos pelo Common Language Runtime (CLR), você deve usar um ou mais compiladores de linguagem que destino o tempo de execução, como, por exemplo, Visual Basic, C#, Visual C++, F# ou um dos muitos compiladores de terceiros-terceiro como, por exemplo, um compilador Eiffel, Perl ou COBOL.

Because it is a multilanguage execution environment, the runtime supports a wide variety of data types and language features. The language compiler you use determines which runtime features are available, and you design your code using those features. Your compiler, not the runtime, establishes the syntax your code must use. Se seu componente deve ser completamente utilizável por componentes escritos em outras linguagens, os tipos exportados do seu componentedevem expor somente recursos de linguagem que estão incluídos na CLS (Common Language Specification) (CLS). You can use the CLSCompliantAttribute attribute to ensure that your code is CLS-compliant. For more information, see Gravando código compatível com CLS.

Back to top

Compiling to MSIL

When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. Before code can be run, MSIL must be converted to CPU-specific code, usually by a just-in-time (JIT) compiler. Because the common language runtime supplies one or more JIT compilers for each computer architecture it supports, the same set of MSIL can be JIT-compiled and run on any supported architecture.

When a compiler produces MSIL, it also produces metadata. Metadata describes the types in your code, including the definition of each type, the signatures of each type's members, the members that your code references, and other data that the runtime uses at execution time. O MSIL e os metadados estão contidos em um arquivo portátil executável (PE) que se baseia, e que estende o Microsoft PE publicado e formato COFF (COFF) usados historicamente paraconteúdodo executável. This file format, which accommodates MSIL or native code as well as metadata, enables the operating system to recognize common language runtime images. A presença de metadados no arquivo com o MSIL permite que seu código descreva a mesmo, o que significa que não há nenhuma necessidade de bibliotecas de tipos ou de Interface Definição Language (IDL). The runtime locates and extracts the metadata from the file as needed during execution.

Back to top

Compiling MSIL to Native Code

Antes de executar o Microsoft Intermediate Language (MSIL), deve ser compilado contra o Common Language Runtime para código nativo para a arquitetura dacomputador de destino. The .NET Framework provides two ways to perform this conversion:

Compilação pelo compilador JIT

JIT compilation converts MSIL to native code on demand at application run time, when the contents of an assembly are loaded and executed. Because the common language runtime supplies a JIT compiler for each supported CPU architecture, developers can build a set of MSIL assemblies that can be JIT-compiled and run on different computers with different machine architectures. No entanto, se o seu código gerenciado chama plataforma-específico nativo APIs ou uma plataforma-específico de classedebiblioteca, ele será executado somente no sistema operacional.

CompilaçãoJIT leva em consideração a possibilidade de que alguns códigos nunca podem ser chamado durante a execução. Em vez de usar o tempo e memória para converter todos os MSIL em um arquivo PE para código nativo , ele converte o MSIL , conforme necessário durante a execução e armazena o código nativo resultante na memória para que seja acessível para chamadas subseqüentes no contexto do processo. The loader creates and attaches a stub to each method in a type when the type is loaded and initialized. When a method is called for the first time, the stub passes control to the JIT compiler, which converts the MSIL for that method into native code and modifies the stub to point directly to the generated native code. Portanto, as chamadas subseqüentes para o JIT-compilado método ir diretamente para o código nativo .

Install-Time Code Generation Using NGen.exe

Porque o compilador JIT converte um assembly MSIL para código nativo quando a definição de métodos individuais que são chamados de assembly , ele afeta o desempenho negativamente em tempo de execução. Na maioria dos casos, que diminui o desempenho é aceitável. More importantly, the code generated by the JIT compiler is bound to the process that triggered the compilation. It cannot be shared across multiple processes. To allow the generated code to be shared across multiple invocations of an application or across multiple processes that share a set of assemblies, the common language runtime supports an ahead-of-time compilation mode. This ahead-of-time compilation mode uses the NGen (Native Image Generator) to convert MSIL assemblies to native code much like the JIT compiler does. However, the operation of Ngen.exe differs from that of the JIT compiler in three ways:

  • Ele executa a conversão de MSIL para código nativo , antes de executar o aplicativo em vez de enquanto o aplicativo é executado.

  • Ele compila um assembly de todo momento, em vez de um método de cada vez.

  • It persists the generated code in the Native Image Cache as a file on disk.

Code Verification

Como parte da sua compilação para código nativo , o código MSIL deve passar umprocesso de verificação, a menos que o administrador tiver estabelecido uma política de segurança que permite que o código ignorar a verificação. A verificação examina o MSIL e metadados para descobrir se o código de tipo seguro, que significa que ele acessa os locais de memória está autorizado a acessar. Tipo de segurança ajuda a isolar objetos uns dos outros e ajuda a protegê-los da corrupção inadvertida ou mal-intencionada. It also provides assurance that security restrictions on code can be reliably enforced.

The runtime relies on the fact that the following statements are true for code that is verifiably type safe:

  • A reference to a type is strictly compatible with the type being referenced.

  • Only appropriately defined operations are invoked on an object.

  • Identities are what they claim to be.

During the verification process, MSIL code is examined in an attempt to confirm that the code can access memory locations and call methods only through properly defined types. For example, code cannot allow an object's fields to be accessed in a manner that allows memory locations to be overrun. Additionally, verification inspects code to determine whether the MSIL has been correctly generated, because incorrect MSIL can lead to a violation of the type safety rules. The verification process passes a well-defined set of type-safe code, and it passes only code that is type safe. However, some type-safe code might not pass verification because of some limitations of the verification process, and some languages, by design, do not produce verifiably type-safe code. If type-safe code is required by the security policy but the code does not pass verification, an exception is thrown when the code is run.

Back to top

Running Code

O Common Language Runtime fornece a infra-estrutura que permite a execução gerenciado tomar o lugar e serviços que podem ser usados durante a execução. Before a method can be run, it must be compiled to processor-specific code. Cada método para o qual o MSIL foi gerado é JIT-compilado quando ele é chamado pela primeira vez e, em seguida, executar. The next time the method is run, the existing JIT-compiled native code is run. O processo de de JIT-compilar e executar o código é repetido até que a execução esteja concluída.

During execution, managed code receives services such as garbage collection, security, interoperability with unmanaged code, cross-language debugging support, and enhanced deployment and versioning support.

No Microsoft Windows XP e Windows Vista, o carregador do sistema operacional verifica os módulos gerenciado examinando um bit nocabeçalhode COFF. The bit being set denotes a managed module. Se o carregador detecta os módulos gerenciado , ele carrega mscoree, e _CorValidateImage e _CorImageUnloading o carregador de notificação quando as imagens demódulo gerenciadosão carregadas e descarregadas. _CorValidateImageexecuta as seguintes ações:

  1. Ensures that the code is valid managed code.

  2. Changes the entry point in the image to an entry point in the runtime.

On 64-bit Windows, _CorValidateImage modifies the image that is in memory by transforming it from PE32 to PE32+ format.

Back to top

Consulte também

Referência

Ilasm. exe (Assembler MSIL)

Conceitos

CLS (Common Language Specification)

Metadados e componentes autodescritivos

Implantando o.NET Framework e aplicativos

Assemblies no Common Language Runtime

Domínios de Aplicativo

Hosts em tempo de execução

Outros recursos

Visão geral sobre o .NET Framework

Segurança no .NET Framework

Interoperação com Código Não Gerenciado