dotnetspider.com


 


TutorialsForumResourcesReviewsJobsInterviewVideosCommunitiesProjectsTraining

Subscribe to Subscribers


Online MembersRavindran
Ajatshatru Upadhyay
abhishek
More...




Forums » .NET » ASP.NET »

What is Safecode and unsafe code?


Posted Date: 23 Jun 2008      Posted By:: Radha     Member Level: Silver    Member Rank: 0     Points: 1   Responses: 9



What is Safecode and unsafe code?




Responses

#253865    Author:       Member Level: Gold      Member Rank: 311     Date: 23/Jun/2008   Rating: 2 out of 52 out of 5     Points: 1

Safe and Unsafe Code (C# vs Java)

A particularly interesting feature of C# is its support for non-type-safe code. Normally, the common language runtime (CLR) takes on the responsibility for overseeing the behavior of Microsoft intermediate language (MSIL) code, and prevents any questionable operations. However, there are times when you wish to directly access low-level functionality such as Win32 API calls, and you are permitted to do this, as long as you take responsibility for ensuring such code operates correctly. Such code must be placed inside unsafe blocks in our source code.

The unsafe Keyword
C# code that makes low-level API calls, uses pointer arithmetic, or carries out some other unsavory operation, has to be placed inside blocks marked with the unsafe keyword. Any of the following can be marked as unsafe:

An entire method.

A code block in braces.

An individual statement.

The following example demonstrates the use of unsafe in all three of the above situations:

C# Copy Codeclass TestUnsafe
{
unsafe static void PointyMethod()
{
int i=10;

int *p = &i;
System.Console.WriteLine("*p = " + *p);
System.Console.WriteLine("Address of p = {0:X2}\n", (int)p);
}

static void StillPointy()
{
int i=10;

unsafe
{
int *p = &i;
System.Console.WriteLine("*p = " + *p);
System.Console.WriteLine("Address of p = {0:X2}\n", (int)p);
}
}

static void Main()
{
PointyMethod();
StillPointy();
}
}

In this code, the entire PointyMethod() method is marked unsafe because the method declares and uses pointers. The StillPointy() method marks a block of code as unsafe as this block once again uses pointers.
------------



#253866    Author:       Member Level: Gold      Member Rank: 0     Date: 23/Jun/2008   Rating: 2 out of 52 out of 5     Points: 1

Safe code : complied by CLR
Unsafe code : Not complied by CLR



#253870    Author:       Member Level: Gold      Member Rank: 138     Date: 23/Jun/2008   Rating: 2 out of 52 out of 5     Points: 4

Safecode or managed code is the code that runs under CLR.The memory management of safe code is handled by CLR.

Unsafe code or managed code is direct memory access or file i/o or database operations.Here you need to manage memory yourself by calling dispose on objects.






#253891    Author:       Member Level: Gold      Member Rank: 112     Date: 23/Jun/2008   Rating: 2 out of 52 out of 5     Points: 6

Safe code is code that is verifiably safe. That is, runtime can verify and make sure that it is not referring to inappropriate memory or memory of the wrong type. If we want to work directly with memory addresses and can manipulate bytes at these addresses then we have to declare that code chunk as unsafe using the unsafe Keyword in C#. So that CLR will not do any do any extra verification on this code and it is really possible to verify this code by CLR even if it is required.

Thus the unsafe just means that it is unverifiable by the runtime. And the normal managed code which is verifiable in every means is called the Type Safe code.

All methods that contain unsafe code should be marked with the unsafe keyword. In
addition, the C# compiler requires you to compile the source code by using the /unsafe
compiler switch.

When the JIT compiler attempts to compile an unsafe method, it checks to see if the assembly containing the method has been granted the System.Security.Permissions.Security-Permission with the System.Security.Permissions.SecurityPermission Flag's
SkipVerification flag set. If this flag is set, the JIT compiler will compile the unsafe code and allow it to execute. The CLR is trusting this code and is hoping the direct address and byte manipulations do not cause any harm. If the flag is not set, the JIT compiler throws either a System.InvalidProgramException or a System.Security.VerificationException, preventing the method from executing

All Normal managed code are labeled as type safe by default because it will be using the .Net provided libraries and classes for accomplishing the task

Microsoft supplies a utility called PEVerify.exe, which examines all of an assembly's methods
and notifies you of any methods that contain unsafe code. This will let you know if there may be
Problems running your application via the intranet or Internet



#253904    Author:       Member Level: Gold      Member Rank: 654     Date: 23/Jun/2008   Rating: 2 out of 52 out of 5     Points: 1

Code that is verifiably type-safe accesses memory only through object references and associated features such as fields and properties. By accessing memory through well-defined paths, the CLR can verify that code is not accessing memory locations to which it should not have access. If code uses pointer arithmetic to access memory, it is not possible to verify whether that code is reading from or writing to memory locations that wouldn't normally be accessible to it. Code that is not verifiably type-safe is also referred to as unsafe code. Because this code is still managed and still runs under the control of the CLR, it is important to note that unmanaged and unsafe are two very distinct concepts.

while programming in the .net framework we don’t need to use unsafe code, but in some cases there is no way not to, such as the following:

Real-time applications, we might need to use pointers to enhance performance in such applications.
External functions, in non-.net DLLs some functions requires a pointer as a parameter, such as Windows APIs that were written in C.
Debugging, sometimes we need to inspect the memory contents for debugging purposes, or you might need to write an application that analyzes another application process and memory.
Unsafe code as I said before is mostly about pointers which have the following advantages and disadvantages.

Advantages:

Performance and flexibility, by using pointer you can access data and manipulate it in the most efficient way possible.
Compatibility, in most cases we still need to use old windows APIs, which use pointers extensively. Or third parties may supply DLLs that some of it’s functions need pointer parameters. Although this can be done by using DLLImport and System.IntPtr class, but in some cases it’s just much simpler to use pointer.
Memory Addresses, there is no way to know the memory address of some data without using pointers.
Disadvantages:

Complex syntax, to use pointers you need to go throw more complex syntax than we used to experience in C#.
Harder to use, you need be more careful and logical while using pointers, miss using pointer might lead to the following:
Overwrite other variables.
Stack overflow.
Access areas of memory that doesn’t contain any data as they do.
Overwrite some information of the code for the .net runtime, which will surely lead you application to crash.
Type-safety, using pointers will cause the code to fail in the .net type-safety checks, and of course if your security police don’t allow non type-safety code, then the .net framework will refuse to execute it.



#257163    Author:       Member Level: Gold      Member Rank: 23     Date: 28/Jun/2008   Rating: 2 out of 52 out of 5     Points: 6

Hi

A particularly interesting feature of C# is its support for non-type-safe code. Normally, the common language runtime (CLR) takes on the responsibility for overseeing the behavior of Microsoft intermediate language (MSIL) code, and prevents any questionable operations. However, there are times when you wish to directly access low-level functionality such as Win32 API calls, and you are permitted to do this, as long as you take responsibility for ensuring such code operates correctly. Such code must be placed inside unsafe blocks in our source code.

Check out the below link
http://msdn.microsoft.com/en-us/library/ms228628(VS.80).aspx

Thanks -- Vj
http://dotnetvj.blogspot.com

Thanks -- Vijaya Kadiyala
http://www.DotNetVJ.com
Microsoft MVP
Me & My Little Techie



#268904    Author:       Member Level: Gold      Member Rank: 259     Date: 23/Jul/2008   Rating: 2 out of 52 out of 5     Points: 1

C# statements execute in either a safe or an unsafe context. Safe context is the default, but any code using pointers requires unsafe context.The unsafe keyword denotes an unsafe context. Again, unsafe context is required for any operation involving pointers.

Unsafe code, or a block of code which is marked as unsafe, is managed by CLR, but a programmer is allowed to use pointers to manipulate memory directly. This code runs outside the control of memory management (GC). When you compile this code, it is unable to escape the watchful eye of the CLR. Unsafe can be applied as a modifier in the declaration of callable members such as methods, properties, constructors and extenders (but not static constructors).

Using unsafe code is more efficient than using references to access objects, imparts an extra layer and GC adds its overheads. You may use unsafe code to parts of your application where you want to be as efficient as possible. You may want to use COM interface method, which requires a pointer as an argument. You may also want to some C or C++ code that uses pointer if you don't want to convert the pointers to references.

Please rate this post, if it is useful for you.

Thanks & Regards
Ashok



#268906    Author:       Member Level: Gold      Member Rank: 259     Date: 23/Jul/2008   Rating: 2 out of 52 out of 5     Points: 1

Unsafe Code

One of the big selling features of .NET is the concept of verifiably type-safe code. Code that is verifiably type-safe accesses types only in well-defined, allowable ways. For example, given a valid object reference, type-safe code can access memory only at fixed offsets that correspond to actual field members. If the code access memory at offsets outside the range of memory that belongs to the object’s publicly exposed fields, it is not type-safe.

During JIT compilation, a process called verification attempts to determine whether the code is type-safe. Code that passes these tests is called verifiably type-safe code.

Code that is not verifiably type-safe can still execute if security policy allows it to bypass verification. Because type safety is an essential part of isolating assemblies, the runtime cannot reliably enforce security if code violates type safety rules. The default security settings allow non-verifiable code only in a fully trusted context, which means only for code that originates from the local computer. Mobile code has to be type-safe in order to run on other computers.

It is possible to have type-safe code that is not verifiable due to limitations of the verification process or of the compiler. Some languages (Microsoft Visual C++, for example) simply cannot generate verifiably type-safe code. In other languages, you may have to avoid certain language constructs. Whatever the reason, code that is not verifiably type-safe is called "unsafe."

Please rate this post, if it is useful for you.

Thanks & Regards
Ashok



#268908    Author:       Member Level: Gold      Member Rank: 259     Date: 23/Jul/2008   Rating: 2 out of 52 out of 5     Points: 1

Safe code is code that is verifiably safe. That is, runtime can verify and make sure that it is not referring to inappropriate memory or memory of the wrong type. If we want to work directly with memory addresses and can manipulate bytes at these addresses then we have to declare that code chunk as unsafe using the unsafe Keyword in C#. So that CLR will not do any do any extra verification on this code and it is really possible to verify this code by CLR even if it is required.

Thus the unsafe just means that it is unverifiable by the runtime. And the normal managed code which is verifiable in every means is called the Type Safe code.

All methods that contain unsafe code should be marked with the unsafe keyword. In
addition, the C# compiler requires you to compile the source code by using the /unsafe
compiler switch.

Please rate this post, if it is useful for you.

Thanks & Regards
Ashok




Post Reply

 This thread is locked for new responses. Please post your comments and questions as a separate thread.
If required, refer to the URL of this page in your new post.


Next : designing dropdownlist...vvv urgent
Previous : Give a few examples of types of applications that can benefit from using XML.
Return to Discussion Forum
Post New Message
Category: ASP.NET

Related Messages

My Profile

Active Members
TodayLast 7 Daysmore...


Awards & Gifts


Email subscription
  • .NET Jobs
  • .NET Articles
  • .NET Forums
  • Articles Rss Feeds
    Forum Rss Feeds



    About Us    Trademark Disclaimer    Contact Us    Copyright    Privacy Policy    Terms Of Use    Revenue Sharing sites   Advertise   Talk to Tony John
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India
    2005 - 2012 All Rights Reserved.
    .NET and other trademarks mentioned in this site belong to Microsoft and other respective trademark owners.
    Articles, tutorials and all other content offered here is for educational purpose only.
    We are not associated with Microsoft or its partners.