CLR SafeHandle Consideration

标签: functionapiclassideac
1505人阅读 评论(0) 收藏 举报

CLR SafeHandle Consideration


Suppose u r the dev for the FileStream, you may want to design the class as the following:
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();
//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:
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:


* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    • 访问:140600次
    • 积分:1623
    • 等级:
    • 排名:千里之外
    • 原创:25篇
    • 转载:0篇
    • 译文:0篇
    • 评论:83条