CLR SafeHandle Consideration

本文探讨了在CLR中设计类似FileStream类时如何正确管理操作系统句柄的问题。通过对比不同设计方案,介绍了使用SafeHandle来避免句柄在最终化期间被意外关闭的风险。
部署运行你感兴趣的模型镜像

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

您可能感兴趣的与本文相关的镜像

GPT-SoVITS

GPT-SoVITS

AI应用

GPT-SoVITS 是一个开源的文本到语音(TTS)和语音转换模型,它结合了 GPT 的生成能力和 SoVITS 的语音转换技术。该项目以其强大的声音克隆能力而闻名,仅需少量语音样本(如5秒)即可实现高质量的即时语音合成,也可通过更长的音频(如1分钟)进行微调以获得更逼真的效果

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值