I am learning about managed and unmanaged code in CLR. So I wrote this example with C-style pointers in C#:
unsafe static void Main(string[] args)
{
int x;
int* y;
y = &x;
*y = 50;
Console.WriteLine(*y);
Console.WriteLine(((int)y).ToString());
}
So I am wondering what really is unsafe in IL code that I got from the code above?
.assembly extern mscorlib
{}
.assembly UnsafePointers
{}
.module UnsafePointers.exe
.class private auto ansi beforefieldinit UnsafePointers.Program
extends [mscorlib]System.Object
{
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 34 (0x22)
.locals init (int32 x,
int32* y)
IL_0001: ldloca x
IL_0003: conv.u
IL_0004: stloc y
IL_0005: ldloc y
IL_0006: ldc.i4 50
IL_0008: stind.i4
IL_0009: ldloc y
IL_000a: ldind.i4
IL_000b: call void [mscorlib]System.Console::WriteLine(int32)
IL_0010: nop
IL_0011: ldloca y
IL_0012: conv.i4
IL_0016: call instance string [mscorlib]System.Int32::ToString()
IL_001b: call void [mscorlib]System.Console::WriteLine(string)
IL_0021: ret
}
}
Does CLR manages this code? And what can go wrong with a code above?
What makes this code unsafe is the use of the 'ldind.i4' statement. This loads a signed 4-byte integer from a memory address. Any memory address can be given, allowing you to read from any memory address in the current process. This is considered unsafe and unverifiable. For instance, you could use this to look inside other appdomains, which is not allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With