CLR SafeHandle Consideration

CLR SafeHandle Consideration

原贴地址:
http://eparg.spaces.live.com/blog/cns!59BFC22C0E7E1A76!576.entry
原贴时间:
2006-03-01
原贴作者:
eparg

Suppose u r the dev for the FileStream, you may want to design the class as the following:
FileStream
{
IntPtr OSHandle;
void FooRead();//Calls into API and use the OSHandle;
Finalizer();//Clean resource
}
In the Finalizer, of course you should call Flush and Closehandle to release the resource.
However, u have no idea about what will happen in the FooRead function because it calls into API. For example:
FileSystem fs=new FileSystem();
fs.FooRead();
//Never use fs anymore
After FooRead goes into API, everything may happen. For example, the API may Sleep, thus the GC is safe to happen. Since the fs is not used any longer, the fs will be collected. However, it does not mean the OSHandle used in the API will be cleard to zero. Instead, the risk is that the Finalizer may be triggered, and close the handle. Since the handle is closed, the FooRead fails.

To solve the problem, u may want to change the design:
FileSystem
{
HandleObj OSHandle=new HandleObj(...);
void FooRead();//Calls into API and use the OSHandle;
Finalizer();//Clean resource
}
We wrap the handle in a class, instead of IntPtr. In the Finalizer, we call Flush only, and left the CloseHandle function in the finalizer of HandleObj class. With this design, even if the Finalizer executes during the call to FooRead, the handle is not closed. Combining with KeepAlive function in FooRead against OSHandle, problem1 is solved.
However, with this design, how can u ensure the squence of the two finalizers when both HandleObject and FileSystem ready to be collected?
...
CLR1 has to use very complex way to handle above problems, such like HandleProtector.TryAddRef... In CLR2, the Safehandle helps us to simplify the task. Since Safehandle uses critical finalizer, we can use our design2, by declaring the OSHandle as Safehandle type to solve it.

Some article mentions handle recycling attack. However, I do not think Safehandle helps much because
1) we are still able to get the int32 value by calling DangerousGetHandle.
2) handle recycling does not open a door for malicious code. malicious code comes from elsewhere. When malicious code gets in and is able to call CloseHandle, anything would happen


Cool article:
http://blogs.msdn.com/bclteam/archive/2005/03/16/396900.aspx

你可能感兴趣的:(Blog,idea)