The Common Language Runtime (CLR) - uni … Common Language Runtime (CLR) Based on ... Generator...
Transcript of The Common Language Runtime (CLR) - uni … Common Language Runtime (CLR) Based on ... Generator...
The Common Language Runtime (CLR)
Based on
Mark Sapossnek
Computer Science DepartmentMetropolitan College
Boston University
Web Form
.NET Framework
Windows
Web Service
CLR
What is the CLR?The .NET Platform
.NET FoundationWeb Services
Your InternalWeb Service
Third-PartyWeb Services
.NET EnterpriseServers
Clients Applications
Protocols: HTTP,HTML, XML, SOAP, UDDI
Tools:Visual Studio.NET,
Notepad
A set of technologies for developing and using components to create:
Web FormsWeb ServicesWindows applications
Supports the software lifecycleDevelopmentDebuggingDeployment Maintenance
What Is the CLR?The .NET Framework
Common Language Specification
Common Language Runtime
VB C++ C#
ASP.NET: Web Servicesand Web Forms
JScript …
WindowsForms
Base Classes
ADO.NET: Data and XML
Visual Studio.NET
What Is the CLR?The .NET Framework
What Is the CLR?Overview
The CLR provides a run-time environment that manages the execution of code and provides services that improves development, deploy-ment, and run time.Code that targets the CLR is called managed code.
What Is the CLR?Goals
Development servicesDeep cross-language interoperabilityIncreased productivity
Deployment servicesSimple, reliable deploymentFewer versioning problems – NO MORE ‘DLL HELL’
Run-time servicesPerformance Scalability Availability
What Is the CLR?Goal: Simpler Development
Plumbing disappearsMetadataTransparent proxiesMemory managementConsistent exception handling
Great WYSIWYG tool supportDesigners and wizardsDebuggers Profilers
Increased productivity
What Is the CLR?Goal: Simpler, Safer Deployment
No registration, zero-impact installXCOPY deployment, incremental download
Side-by-side versions of shared componentsCapture version at compile timeAdministrative policy at run time
Evidence-based security policyBased on code as well as userCode origin (location)Publisher (public key)
DLL Hell
What Is the CLR?Goal: Scalability
Smart device to Web FarmAutomatic memory management
Self-configuringDynamically tuning
Thread poolAsynchronous messaging
Object remotingEvents
Smart device versionMultiple RTOSesSame tools used for desktop
What Is the CLR?Goal: Rich Web Clients, Safe Hosting
WinForms on the clientASP.NET Web Forms on the serverCode is granted permissions
Evidence is used by policy to grant permissionsApplication that starts runtime
Like Internet Explorer, IIS, SQL Server™, Shell
Provides some evidenceControls code loadingMaps applications to processes
COM, ASP, VB, C++All services availableMany services redesigned
Ease of useScalabilityConsistent API
Consistent framework raises the abstraction layerGradual transition from simplicity to full powerLess training, greater productivity
What Is the CLR?Goal: Converge Programming Models
What Is the CLR?Goal: Multiple Languages
Common Type SystemObject-oriented in flavorProcedural languages well supportedFunctional languages possible
CLS guides frameworks designRules for wide reachAll .NET Framework functionality available
Over 15 languages investigatedMost are CLS consumersMany are CLS extenders
Choose the right language for a particular job
What Is the CLR?Highlights
Common Type SystemMapping of data types: Programming language Framework
Just-in-time (JIT) compilersJIT compiles intermediate language (MSIL) into native codeHighly optimized for platform or device
Garbage collectorPermission and policy-based securityExceptionsThreadingReflectionDiagnostics and profiling
What Is the CLR?Services
Code managementMemory management and isolationVerification of type safetyConversion of MSIL to native code Loading and execution of managed code Creation and management of metadataInsertion and execution of security checks
Handling cross-language exceptionsInteroperation between .NET Framework objects and COM objects and Win32 DLLsAutomation of object layout for late bindingDeveloper services (profiling, debugging, etc.)
What Is the CLR? Architecture
Class Loader
MSIL to NativeCompilers (JIT)
CodeManager
GarbageCollector (GC)
Security Engine Debug Engine
Type Checker Exception Manager
Thread Support COM Marshaler
Base Class Library (.NET Framework) Support
What Is the CLR? Soon To Be a Standard
Microsoft, with HP and Intel, submitted proposal to ECMA to standardize:
C#Common Language Infrastructure
Includes the Common Language Runtime and a subset of the .NET Framework classes
http://msdn.microsoft.com/net/ecma/http://www.ecma.ch
AssembliesOverview
Contains code and metadataAssemblies function as:
Unit of deploymentType boundarySecurity boundaryReference scope boundaryVersion boundaryUnit of side-by-side execution
AssembliesOverview
Assemblies can be:Static: DLL, EXE
Uses existing COFF binary formatVia existing extension mechanism
DynamicCreate assemblies with
.NET Framework SDKVisual Studio.NETYour own code
Dynamic assemblies
ManifestMetadata about the assembly itself
Type metadata Completely describes all types defined in an assembly
Managed codeMicrosoft Intermediate Language (MSIL)
ResourcesFor example, .bmp, .jpg
AssembliesComponents of an Assembly
AssembliesComponents of an Assembly
An assembly is a logical unit, not physicalIt can consist of multiple modules (.DLL, .JPG, etc.)
AssemblyModule
FileType
In this figure, containment implies a 1:M relationship
AssembliesComponents of an Assembly
A single-file assembly A multi-file assembly
ManifestMetadata
MSIL
File1.dll Metadata
MSIL
File2.dll Graphic.jpg
Resource
Logo.gif
Resource
Manifest
File3.dll
AssembliesAssembly Generation Tool: al.exe
Takes one or more files (containing either MSIL or resource files) and produces a file with an assembly manifest.When compiling a C# file, you can specify that it create a module instead of an assembly by using /target:module.
AssembliesManifest
Manifest contains:Identity information
Name, version number, culture, strong name
List of files in the assemblyMap of assembly types to filesDependencies
Other assemblies used by this assembly
Exported typesSecurity permissions needed to run
Type Descriptions
ClassesBase classesImplemented interfacesData membersMethods
Assembly Description
NameVersionCulture
Other assembliesSecurity PermissionsExported Types
AssembliesManifest and Metadata
Manifest
Metadata
AssembliesWhat’s In the Metadata
Description of typesName, visibility, base class, interfaces implementedMembers
methods, fields, properties, events, nested types
AttributesUser-definedCompiler-definedFramework-defined
AssembliesDemo: ILDASM.EXE
Allows you to inspect the metadata and disassembled IL code in an assemblyGreat way to see what’s really going onUse ildasm /? to see the various options
AssembliesMetadata
Key to simpler programming modelGenerated automatically
Stored with code in executable file (.dll or .exe)
AssembliesMetadata: Creation and Use
Assembly(Manifest, metadataand code)
Debugger
Schema Generator
Profiler
OtherCompiler
Proxy Generator
Type Browser
Compiler
SourceCode
XML encoding(WSDL)
Serialization(e.g. SOAP)
Designers
Reflection
AssembliesCompilers Use Metadata
For cross-language data type importEmit metadata with output code
Describe types defined and usedRecord external assemblies referencedRecord version information
Custom attributes can be used ObsoleteCLS complianceCompiled for debuggingLanguage-specific markers
AssembliesOther Tools Use Metadata
Designer behavior Controlled by user-supplied attributes
CategoryDescription
Designer extensibilityUser-supplied attributes specify code to use
Type convertersEditors
Web methods marked by custom attributeType viewer
AssembliesGlobal Assembly Cache
A set of assemblies that can be referenced by any application on a machineShould be used only when needed
Private assemblies are preferredLocated at %SystemRoot%\assembly
(c:\winnt\assembly)Add assemblies by
Installer programgacutil.exeWindows Explorer
Assembly Cache Viewer (shfusion.dll) is a shell extension for GAC that is installed with the .NET Framework SDK
.NET Framework Configuration Tool (mscorcfg.msc)Assembly must have a strong name
AssembliesStrong Names
Strong names identify an assemblyContains text name, version, culture, public key, and digital signature
Generated from an assembly using a private keyBenefits
Guarantees name uniquenessProtect version lineage
No one else can create a new version of your assemblyProvides strong integrity check
Guarantees that contents of an assembly didn’t change since it was built
AssembliesStrong Names
To sign an assembly with a strong name:Use Assembly Generation tool: al.exeUse assembly attributes (AssemblyKeyFileAttribute or AssemblyKeyNameAttribute)
Requires a key pair (private and public) To generate a key pair use the Strong Name tool: sn.exe
AssembliesDemo: Installing an Assembly in GAC
Create assemblySign assembly with key from sn.exeInstall into GAC via gacutil.exe, Assembly Cache Viewer and .NET Framework Configuration Tool
AssembliesSigncode
A strong name identifies an assembly but it does not authenticate an assembly
Strong names do NOT imply a level of trustSigncode allows the embedding of a certificate in an assembly
Now your assembly can be authenticated
AssembliesSigncode
To use signcode:Obtain a Software Publisher Certificate (.spc)Use signcode.exe to sign the assembly
Signcode can only sign one file at a timeFor an assembly, you sign the file containing the manifest
Purchase one from a well known Certificate Authority (such as Verisign)Create your own
For testing purposes onlyUse Makecert.exe to create a X.509 certificateUse cert2spc.exe to generate an SPC from a X.509 certificate
AssembliesHow Do You Obtain a Certificate?
AssembliesStrong Names and Signcode
Strong names and signcode provide different, complimentary levels of protectionYou can assign a strong name or assign a signcode signature to an assembly, or both When using both, the strong name must be assigned first
AssembliesSigncode
Specify what permissions your assembly needsOnly specify required permissionsHandle optional permissions dynamically
Set security policy on run-time machine
Unit of deploymentOne or more files, independent of packagingSelf-describing via manifest and metadata
VersioningCaptured by compilerPolicy per-application as well as per-machine
Security boundaryAssemblies are granted permissionsMethods can demand proof that a permission has been granted to entire call chain
Mediate type import and exportTypes named relative to assembly
AssembliesDeployment
AssembliesDeployment
Applications are configurable unitsOne or more assembliesApplication-specific files or data
Assemblies are located based on:Their logical name and the application that loads them
Applications can have private versions of assemblies
Private version preferred to shared versionVersion policy can be per application
AssembliesMSIL
Microsoft Intermediate Language
.assembly hello {}
.assembly extern mscorlib {}
.method static public void main() il managed {.entrypoint.maxstack 1ldstr "Hello World from IL!"call void [mscorlib]System.Console::WriteLine(class
System.String)ret
}
AssembliesMSIL
Compiled with ilasm.exeMSIL was designed for the CLR
Object-oriented (primitives are not special)Designed for the Common Type SystemDoes not embed type information
See documentation in \FrameworkSDK\Tool Developers Guide\docs
Source Code
C++, C#, VB or any .NET language
csc.exe or vbc.exeCompiler
Assembly
DLL or EXE
Execution ModelCreate Assembly
CLR
Execution Model
VBSource Code
CompilerC++C#
Assembly AssemblyAssembly
Operating System Services
MSIL
Common Language Runtime JIT Compiler
Compiler Compiler
NativeCode
ManagedCode
ManagedCode
ManagedCode
UnmanagedCode
CLR Services
Ngen
Execution ModelCompiling IL to Native Code
JIT compilerGenerates optimized native codeCompiled when a method is first calledIncludes verification of IL code
Ngen.exe
Install-time native code generationUsed when assembly is installed on machineReduces start-up timeNative code has version checks and reverts to run-time JIT if they fail
Execution ModelRun-Time Hosts
ASP.NETInternet ExplorerShell executablesMore in future
For example: SQL Server (Yukon)Can create your own run-time hosts
Execution ModelBinding to Assemblies
An application consists of one or more assemblies.How does one assembly bind to another?
Based upon metadata and policyLocal (preferred)Assembly Global Cache
Multiple versions of an assembly may exist on the same machine.
Easier software deployment, updates and removalMultiple versions of an assembly can even be used by the same application
Execution ModelApplication Domains
Traditionally, processes were used to isolate applications running on the same computer
Isolates failure of one applicationIsolates memory
ProblemsUses more resourcesIf needed, inter-process calls can be expensive
Execution ModelApplication Domains
.NET introduces Application Domains, which allow you to run multiple applications within the same processEnabled by code verification
No code will crash the processManaged by the System.AppDomain classCommon assemblies can be shared across domains or can be specific to a domain
Execution ModelApplication Domains
Benefits:Application domains are isolatedFaults are isolatedIndividual applications can be stopped without stopping the processCan configure each application domain independentlyCan configure security for each domainCross-domain calls can be done through proxies
More efficient than cross-process calls