views:

95

answers:

1

Does there exist a way to catch a write into write-protected page?

I plan doing a self -like object system where you copy the object to instantiate it. (because it sounds simple and compact thing compared to the rest) Obviously, the objects created for this purpose ought be write-protected some way. I've seen there's a way to flag something write-protected from the program headers in the ELF. (RE, RWE, RW -flags)

Does this provide write-protection at all? I remember it should raise a segfault, is this true? How to catch the write into a write-protected page. Is this a good way to implement what I'm wanting for and is there a better way?

+1  A: 

Yes, you can use mprotect.

Yes, a write to protected memory will raise a segfault. You can install a handler, e.g. in C++:

std::signal(SIGSEGV, my_segv_handler_func);

This is a plausible way of doing what you want, although you'd have to add a lot of extra management goo to make it work. For example, this sort of write-detection is done in hardware, and on x86 architectures you've got a page size of 4k. So you can protect things 4k at a time, aligned on 4k boundaries -- not a generic "start at address X and go N bytes". I believe you'd either have to

  1. have a mapping of objects to pages such that you can identify whether a write to a page is a write to a particular protected object, or
  2. roll your own malloc that always allocates on 4k boundaries, which would force you to use a minimum alloc'd block size of 4k

I don't know off the top of my head if there's a better way, but it sounds fun to play with. :)

Mark Maxham