Tutorial :Expose memory as read-only



Question:

In C can a function expose memory that it "manageds" at a lower level as readonly to those calling that function (exposing its address). return * const is not effective but I wondered if I was overlooking a programming tick?

Thanks.

const uint8_t * get_value(int index)   {  static uint8_t data[2] = {0, 0};  return (const uint8_t *)&data[index];  }    int main(void)  {  uint8_t * value;  value = get_value(1);    *value += 1;  return 0;  }  

@j_random_hacker Suggested a good compromise to my question that gives that extra barrier I'm looking for to prevent casual mis-use of that data.

typedef struct  {      const uint8_t * value;      const uint8_t size;    } readonly_t;    readonly_t get_value(int index, int size)   {      static uint8_t data[2] = {0, 0};      uint8_t rsize;        /* ... validate index, size params */        readonly_t r = { &data[index], rsize };      return r;  }  


Solution:1

It's C! You can't :) There is always a way to circumvent it. Just make it const and hope somebody will not change it.

If you are hosting an add-in or something, you should run it in a separate process to limit its access to memory.


Solution:2

Use VirtualProtect: http://msdn.microsoft.com/en-us/library/aa366898(VS.85).aspx

With PAGE_READONLY: http://msdn.microsoft.com/en-us/library/aa366786(VS.85).aspx


Solution:3

Don't return a pointer, return the pointed to object's value as in:

uint8_t get_value(int index)   {      static uint8_t data[2] = {0, 0};      return data[index];  }  


Solution:4

Memory protection is not a language construct in 'C, it is something to do with the hardware. For example, if the memory pointed to by the pointer is in some ROM area or something, writing is not possible. And on the other way round, we can even make the part of the ReadOnly at the hardware level, then you can expect some memory exception.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »