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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值