views:

70

answers:

4

We have an array that is oversized for alignment purposes, such that off by one errors are not caught by the usual mechanisms.

Is it possible to protect a small, arbitrary region (16 bytes at the beginning and end of an array) in Windows, such that it causes an access violation? Language is C++.

A: 

I don't think this can be done. You could always throw an exception yourself.

0A0D
+4  A: 

I believe that in the x86 architecture the finest granularity you can achieve in marking memory as protected is for a page (4K I think). You could set up the array such that the beginning or end falls across a page boundary (and have that page protected). But to have both ends fall across such boundaries would of course require a very specific array length.

Here is an example of how to set up guard pages.

Mark Wilkins
+1  A: 

You can do this on a UNIXish OS with a combination of __attribute__((aligned (PAGESIZE))) and mprotect. On Windows, I think there is an equivalent to mprotect, but it is also limited to one page of memory.

The reason it's not possible to protect things with finer granularity is that the memory access is done by hardware, not software. It would be very slow if every single memory access required going through some data structure to check if the page is protected.

Borealid
+1  A: 

Not directly. The closest you can do is setting up a data breakpoint on those buffers. However, the x86 has a grand total of 4 such breakpoints, and they're 8 bytes max. Furthermore, you need to be in ring 0 (kernel mode) to set them.

MSalters
SetThreadContext can do the Kernel mode part of the job for you. Sources showing how to do it can be found on http://www.morearty.com/code/breakpoint (you are correct on other limitations).
Suma
Actually, its MSDN page explicitly states that "Some values in the CONTEXT structure that cannot be specified are silently set to the correct value. This includes ... global enabling bits in the debugging register ... ". Presumably, not all Windows versions are equally strict so YMMV.
MSalters