开发者

How do detect if an address will cause an access violation?

I'm creating a class for a Lua binding which holds a pointer and can be changed by the scripter. It will include a few functions such as :ReadString and :ReadBool, but I don't want the application to crash if I can tell that the address they supplied will cause an access violation.

Is the a good way to detect if an address is outside of the readable/writable memory? Thanks!

A function library that may be useful is the "Virtual" function libraries, for example VirtualQuery

I'm not really looking for a foolproof design, I just want to omit the obvious (null pointe开发者_StackOverflow社区rs, pointers way outside the possible memory location)

I understand how unsafe this library is, and I'm not looking for safety, just sanity.


There are ways, but they do not serve the purpose you intend. That is; yes, you can determine whether an address appears to be valid at the current moment in time. But; no, you cannot determine whether that address will be valid a few clock cycles from now. Another thread could change the virtual memory map and a formerly valid address would become invalid.

The only way to properly handle the possibility of accessing suspect pointers is using whatever native exception handling is available on your platform. This may involve handling the signal SIG_BUS or it may involve using the proprietary __try and __catch extensions.

The idiom to use is the one wherein you attempt the access, and explicitly handle the resulting exception, if any does happen to occur.

You also have the problem of ensuring that the pointers you return point to your memory or to some other memory. For that, you could make your own data structure, a tree springs to mind, which stores the valid address ranges your "pointers" can achieve. Otherwise, the script code can hand you some absolute addresses and you will change memory structures by the operating system for the process environment.

The application you write about is highly suspect and you should probably start over with a less explosive design. But I thought I would tell you how to play with fire if you really want to.


Check out Raymond Chen's blog post, which goes more deeply into why this practice is bad. Most interestingly, he points out that, once a page is tested by IsBadReadPtr, further accesses to that page will not raise exceptions!


There is no, and that's why you should never do things like this.


Perhaps try using segvcatch, which can convert segfaults into C++ exceptions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜