How to know if we can read or write to a memory location (memory block)?

Started by gwapo, April 06, 2006, 02:10:41 AM

Previous topic - Next topic

gwapo

Hi,

My method is fairly BAD as it is hard to trace and probably not a good practice (not to mention it's not reliable). I usually setup a SEH handler and "try" to read or write to a memory, if it failed to read/write then I raise an error to my SEH handler.

Although my programs are already working fine with the method above, I'm looking for a better way to "check" read and write permission to a memory block without setting up SEH handler, any tips your guys could share?


Thanks,

-chris

hutch--

Chris,

There is an API for checking if a memory pointer is valid, IsBadCodePtr() and similar, but its always a case of never do more than you need as it adds overhead, complexity and slows things down if its not really needed. If its memory that is allocated within a single process, you need do no more than deallocate it and set the memory operand to zero, something like this,


invoke GlobalAlloc(args etc ...)
mob hMem, eax

    ; use the memory

invoke GlobalFree(hMem)
mov hMem, 0


Then you just test the "hMem" for whether its zero or not. It looks crude and simple but by it being so, its also small, fast and reliable.

Normally you set up stuff like SEH for situation that you cannot control from within a single thread and this may be the reurn value for a system DLL or some other external memory source.
Download site for MASM32      New MASM Forum
https://masm32.com          https://masm32.com/board/index.php

gwapo

Hutch,

Thanks for telling me about IsBadReadPtr and IsBadWritePtr, probably this is the solution I am looking for.

The reason I need to check for read/write is because the buffer I am reading or writing is allocated somewhere else. For example, I have a DLL that exports a function that can write to a pointer passed to it, my function may look like something:


PassString proc lpWriteOutputHere:dword

   mov  eax, lpWriteOutputHere

   mov  dword ptr [eax], "Hell"
   mov  dword ptr [eax+4], "o Wo"
   mov  dword ptr [eax+8], "rld!"

   ret
PassString endp


If memory pointed by lpWriteOutputHere has write permission then the function above will work, however, if the memory pointed by lpWriteOutputHere has no write permission or it is pointing to an inssuficient buffer then it will fail. Therefore I am checking for the following conditions:

1. Can I write to the buffer?
2. Is there enough memory for the output buffer?


I think the API IsBadWritePtr can help me on this one, thanks,

-chris