SynapseIndia DotNet development-Presentation on .Net Framework
.NET Framework:
Topics
Execution ModelIntermediate Language (IL), verification, JIT
compilation, metadata, and assembly loadingHow Things Relate at
RuntimeCode, Types, Objects, a threads stack, and the heapGarbage
CollectionHow a reference-tracking GC works
Topics
Execution ModelIntermediate Language (IL), verification, JIT
compilation, metadata, and assembly loadingHow Things Relate at
RuntimeCode, Types, Objects, a threads stack, and the heapGarbage
CollectionHow a reference-tracking GC works
C# Source Code File(s)
Managed Assembly (IL and Metadata)
Fortran Source Code File(s)
C++ Source Code File(s)
Basic Source Code File(s)
C# Compiler
Basic Compiler
C++ Compiler
Fortran Compiler
Compiling Source CodeInto Assemblies
Managed Assembly (IL and Metadata)
Managed Assembly (IL and Metadata)
Managed Assembly (IL and Metadata)
An Assembly
An Assembly is the managed equivalent of an EXE/DLLImplements and
optionally exports a collection of typesIt is the unit of
versioning, security, and deploymentParts of an Assembly
fileWindows PE headerCLR header (Information interpreted by the CLR
and utilities)Metadata (Type definition and reference
tables)Intermediate Language (code emitted by compiler)
ILDasm.exe
Intermediate Language
All .NET compilers produce IL codeIL is CPU-independent machine
languageCreated by Microsoft with input from external commercial
and academic language/compiler writersIL is higher-level than most
CPU machine languagesSome sample IL instructionsCreate and
initialize objects (including arrays)Call virtual methodsThrow and
catch exceptionsStore/load values to/from fields, parameters, and
local variablesDevelopers can write in IL assembler (ILAsm.exe)Many
compilers produce IL source code and compile it by spawning
ILAsm.exe
ILDasm.exe
Benefits Of IL
IL is not tied to any specific CPUManaged modules can run on any
CPU (x86, Itanium, Opteron, etc), as long as the OS on that CPU
supports the CLRMany believe that write once, run everywhere is the
biggest benefitI disagree, security and verification of code is the
really BIG win!
Real Benefit Of IL: Security And Verification
When processing IL, CLR verifies it to ensure that everything it
does is safeEvery method is called with correct number and type of
parametersEvery methods return value is used properlyEvery method
has a return statementMetadata includes all the type/method info
used for verification
Benefits Of Safe Code
Multiple managed applications can run in 1 Windows
processApplications cant corrupt each other (or themselves)Reduces
OS resource usage, improves performanceAdministrators can trust
appsISPs forbidding ISAPI DLLsSQL Server running IL for stored
proceduresInternet downloaded code (with Code Access Security)Note:
Administrator can turn off verification
Executing Managed IL Code
When loaded, the runtime creates method stubsWhen a method is
called, the stub jumps to runtimeRuntime loads IL and compiles itIL
is compiled into native CPU codeJust like compiler back-endMethod
stub is removed and points to compiled codeCompiled code is
executedIn future, when method is called, it just runs
Console
Managed EXE
MSCorEE.dll
JITCompiler
JITCompiler
JITCompiler function { 1. In the assembly that implements the type
(Console), look up the method (WriteLine) being called in the
metadata. 2. From the metadata, get the IL for this method and
verify it. 3. Allocate a block of memory. 4. Compile the IL into
native CPU instructions; the native code is saved in the memory
allocated in step #3. 5. Modify the methods entry in the Types
table so that it now points to the memory block allocated in step
#3. 6. Jump to the native code contained inside the memory
block.}
static void WriteLine()
static void WriteLine(String)
(remaining members)
Native CPU Instructions
static void Main() { Console.WriteLine(Hello);
Console.WriteLine(Goodbye);}
NativeMethod
All Types/Modules AreSelf-Describing
1 TypeDef entry for AppEntry refers to MethodDef entry for Main2
TypeRef entries for System.Object and System.ConsoleBoth entries
refer to AssemblyRef entry for MSCorLib
public class App { public static void Main() {
System.Console.WriteLine("Hi"); } }
Metadata Definition Tables(Partial List)
TypeDef: 1 entry for each type definedTypes name, base type, flags
(i.e. public, private, etc.) and index into MethodDef &
FieldDef tablesMethodDef: 1 entry for each method definedMethods
name, flags (private, public, virtual, static, etc), IL offset, and
index to ParamDef tableFieldDef: 1 entry for each field
definedName, flags (i.e. private, public, etc.), and typeParamDef:
1 entry for each parameter defdName, and flags (in, out, retval,
etc.)
Metadata Reference Tables(Partial List)
AssemblyRef: 1 entry for each assembly refdName, version, culture,
public key tokenTypeRef: 1 entry for each type refdTypes name, and
index into AssemblyRef tableMemberRef: 1 entry for each member
refdName, signature, and index into TypeRef table
ILDasm.exe Metadata And IL
Code Attempts ToAccess A Type/Method
23000001: AssemblyRef entry for MSCorLib 01000003: TypeRef entry to
System.Console06000001: MethodDef for Main (FYI)
.method /*06000001*/ public hidebysig static void Main(class
System.String[] args) il managed { .entrypoint // Code size 11
(0xb) .maxstack 8 IL_0000: ldstr "Hi IL_0005: call void
['mscorlib'/* 23000001 */] System.Console/* 01000003
*/::WriteLine(class System.String) IL_000a: ret } // end of method
'App::Main'
IL Call with Metadata token
How The CLR Resolves An Assembly Reference
MemberRef
MethodDef
MemberRef TypeRef TypeRef AssemblyRef
Create internal type structure
Load Assembly
Look-up TypeDef
MethodDef TypeDef
Emit Native Call
Topics
Execution ModelIntermediate Language (IL), verification, JIT
compilation, metadata, and assembly loadingHow Things Relate at
RuntimeCode, Types, Objects, a threads stack, and the heapGarbage
CollectionHow a reference-tracking GC works
Windows Process
A Threads Stack
CLR (Thread Pool & Managed Heap)
name (String)
[return address]
void M1() { String name = Joe; M2(name); ... return;}
void M2(String s) { Int32 length = s.Length; Int32 tally; ...
return;}
Simple Class Hierarchy
class Manager : Employee { public override String
GenProgressReport() { ... }}
class Employee { public Int32 GetYearsEmployed() { ... } public
virtual String GenProgressReport() { ... } public static Employee
Lookup(String name) { ... }}
Instance Method Mapping Using this
public Int32 GetYearsEmployed(); public (static) Int32
GetYearsEmployed(Employee this);
public virtual String GenProgressReport(); public (static) String GenProgressReport(Employee this);
public static Employee Lookup(String name); public static
Employee Lookup(String name);
Employee e = new
Employee();e.GetYearsEmployed();e.GenProgressReport();
Employee e = new
Employee();Employee.GetYearsEmployed(e);Employee.GenProgressReport(e);
this is what makes instance data available to instance
methods
IL Instructions ToCall A Method
CallIs usable for static, instance, and virtual instance methodsNo
null check for the this pointer (for instance methods)Used to call
virtual methods non-polymorphicallybase.OnPaint();CallvirtUsable
for instance and virtual methods onlySlower perfNull check for all
instance methodsPolymorphs for virtual methodsNo polymorphic
behavior for non-virtual methodsC# and VB use callvirt to perform a
null check when calling instance methods
.method private hidebysig static void Main() cil managed {
.entrypoint // Code size 27 (0x1b) .maxstack 1 .locals init (object
V_0) IL_0000: newobj instance void System.Object::.ctor() IL_0005:
stloc.0 IL_0006: ldloc.0 IL_0007: callvirt instance int32
System.Object::GetHashCode() IL_000c: pop IL_000d: ldloc.0 IL_000e:
callvirt instance class System.Type System.Object::GetType()
IL_0013: pop IL_0014: ldc.i4.1 IL_0015: call void
System.Console::WriteLine(int32) IL_001a: ret} // end of method
App::Main
class App { static void Main() { Object o = new Object();
o.GetHashCode();// Virtual o.GetType();// Non-virtual instance
Console.WriteLine(1);// Static }}
Windows Process
= 5
Memory: Code, Types, Objects
JittedCode
JittedCode
JittedCode
JittedCode
Stack
void M3() { Employee e; Int32 year; e = new Manager(); e =
Employee.Lookup(Joe); year = e.GetYearsEmployed();
e.GenProgressReport();}
null
= 0
Topics
Execution ModelIntermediate Language (IL), verification, JIT
compilation, metadata, and assembly loadingHow Things Relate at
RuntimeCode, Types, Objects, a threads stack, and the heapGarbage
CollectionHow a reference-tracking GC works
The Managed Heap
All reference types are allocated on the managed heapYour code
never frees an objectThe GC frees objects when they are no longer
reachableEach process gets its own managed heapVirtual address
space region, sparsely allocatedThe new operator always allocates
objects at the endIf heap is full, a GC occursReality: GC occurs
when generation 0 is full
NextObjPtr
Roots And GC Preparation
Every application has a set of RootsA Root is a memory location
that can refer to an objectOr, the memory location can contain
nullRoots can be any of the followingGlobal & static fields,
local parameters, local variables, CPU registersWhen a method is
JIT compiled, the JIT compiler creates a table indicating the
methods rootsThe GC uses this tableThe table looks something like
this...
Start OffsetEnd
OffsetRoots________________0x000000000x00000020this, arg1, arg2,
ECX, EDX0x000000210x00000122this, arg2, fs,
EBX0x000001230x00000145fs
When A GC Starts...
All objects in heap are considered garbageThe GC assumes that no
roots refer to objectsGC examines roots and marks each reachable
objectIf a GC starts and the CPUs IP is at 0x00000100, the objects
pointed to by the this parameter, arg2 parameter, fs local
variable, and the EBX register are roots; these objects are marked
as in useAs reachable objects are found, GC uses metadata to checks
each objects fields for references to other objectsThese objects
are marked in use too, and so onGC walks up the threads call stack
determining roots for the calling methods by accessing each methods
tableFor objects already in use, fields arent checkedImproves
performancePrevents infinite loops due to circular referencesThe GC
uses other means to obtain the set of roots stored in global and
static variables
A
B
C
D
E
F
G
H
I
J
ROOTS (strong references) Globals Statics Locals CPU
Registers
NextObjPtr
Before A Collection
Managed Heap
Compacting The Heap
After all roots have been checked and all objects have been marked
in use...The GC walks linearly through heap for free gaps and
shifts reachable objects down (simple memory copy)As objects are
shifted down in memory, roots are updated to point to the objects
new memory addressAfter all objects have been shifted...The
NextObjPtr pointer is positioned after last objectThe new operation
that caused the GC is retriedThis time, there should be available
memory in the heap and the object construction should succeedIf
not, an OutOfMemoryException is thrown
A
C
D
F
H
ROOTS (strong references) Globals Statics Locals CPU
Registers
NextObjPtr
After A Collection
Managed Heap
Root Example
class App { public static void Main() { // ArrayList object created
in heap, a is now a root ArrayList a = new ArrayList(); // Create
10000 objects in the heap for (int x = 0; x < 10000; x++) {
a.Add(new Object()); } // Local a is a root that refers to 10000
objects Console.WriteLine(a.Length); // After line above, a is not
a root and all 10001 // objects may be collected. // NOTE: Method
doesnt have to return Console.WriteLine(End of method); } }
Microsoft Products And Services For Lifelong
Learningwww.microsoft.com/learning
Assessmentshttp://www.microsoft.com/assessment/Courses2415: Programming with the Microsoft .NET Framework (Microsoft Visual Basic .NET)2349: Programming with the Microsoft .NET Framework (Microsoft Visual C# .NET)BooksThe Microsoft Platform Ahead, ISBN: 0-7356-2064-4Network Programming for the Microsoft .NET Framework, ISBN: 0-7356-1959-XProgramming Microsoft .NET, ISBN: 0-7356-1376-1Applied Microsoft Windows .NET Framework Programming, ISBN: 0-7356-1422-9Applied Microsoft Windows .NET Framework Programming in Microsoft Visual Basic .NET, ISBN: 0-7356-1787-2Microsoft Windows .NET Framework 1.1 Class Library ReferencesPerformance Testing Microsoft .NET Web Applications, ISBN: 0-7356-1538-1
*
* 2004 Microsoft Corporation. All rights reserved.This presentation
is for informational purposes only. Microsoft makes no warranties,
express or implied, in this summary.
*
01/01/15 12:30
*
* 2004 Microsoft Corporation. All rights reserved.This presentation
is for informational purposes only. Microsoft makes no warranties,
express or implied, in this summary.
*
01/01/15 12:30
*
* 2004 Microsoft Corporation. All rights reserved.This presentation
is for informational purposes only. Microsoft makes no warranties,
express or implied, in this summary.
*
01/01/15 12:30
*
* 2004 Microsoft Corporation. All rights reserved.This presentation
is for informational purposes only. Microsoft makes no warranties,
express or implied, in this summary.
*
01/01/15 12:30
*
* 2004 Microsoft Corporation. All rights reserved.This presentation
is for informational purposes only. Microsoft makes no warranties,
express or implied, in this summary.
*
01/01/15 12:30
*
* 2004 Microsoft Corporation. All rights reserved.This presentation
is for informational purposes only. Microsoft makes no warranties,
express or implied, in this summary.
*
01/01/15 12:30