No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

78 líneas
1.7 KiB

  1. #pragma once
  2. #include <windows.h>
  3. /*
  4. A safer replacement for the obsolete IsBadReadPtr() and IsBadWritePtr() WinAPI functions
  5. on top of VirtualQuery() which respects Windows guard pages. It does not use SEH
  6. and is designed to be compatible with the above-mentioned functions.
  7. The calls to the IsBadReadPtr() and IsBadWritePtr() can be replaced with the calls to
  8. the IsBadMemPtr() as follows:
  9. - IsBadReadPtr(...) => IsBadMemPtr(FALSE, ...)
  10. - IsBadWritePtr(...) => IsBadMemPtr(TRUE, ...)
  11. */
  12. BOOL IsBadMemPtr(/*BOOL write, */void* ptr, size_t size)
  13. {
  14. MEMORY_BASIC_INFORMATION mbi;
  15. BOOL ok;
  16. DWORD mask;
  17. BYTE* p = (BYTE*)ptr;
  18. BYTE* maxp = p + size;
  19. BYTE* regend = NULL;
  20. if (size == 0)
  21. {
  22. return FALSE;
  23. }
  24. if (p == NULL)
  25. {
  26. return TRUE;
  27. }
  28. /*if (write == FALSE)
  29. {
  30. mask = PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
  31. }
  32. else
  33. {*/
  34. mask = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
  35. /*}*/
  36. do
  37. {
  38. if (p == ptr || p == regend)
  39. {
  40. if (VirtualQuery((LPCVOID)p, &mbi, sizeof(mbi)) == 0)
  41. {
  42. return TRUE;
  43. }
  44. else
  45. {
  46. regend = ((BYTE*)mbi.BaseAddress + mbi.RegionSize);
  47. }
  48. }
  49. ok = (mbi.Protect & mask) != 0;
  50. if (mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS))
  51. {
  52. ok = FALSE;
  53. }
  54. if (!ok)
  55. {
  56. return TRUE;
  57. }
  58. if (maxp <= regend) /* the whole address range is inside the current memory region */
  59. {
  60. return FALSE;
  61. }
  62. else if (maxp > regend) /* this region is a part of (or overlaps with) the address range we are checking */
  63. {
  64. p = regend; /* lets move to the next memory region */
  65. }
  66. } while (p < maxp);
  67. return FALSE;
  68. }