1

C++ コードの例外ハンドラーには次のものが必要です。たとえば、次のコード ブロックがあるとします。

void myFunction(LPCTSTR pStr, int ncbNumCharsInStr)
{
    __try
    {
        //Do work with 'pStr'

    }
    __except(1)
    {
        //Catch all

        //But here I need to log `pStr` into event log
        //For that I don't want to raise another exception
        //if memory block of size `ncbNumCharsInStr` * sizeof(TCHAR)
        //pointed by 'pStr' is unreadable.
        if(memory_readable(pStr, ncbNumCharsInStr * sizeof(TCHAR)))
        {
            Log(L"Failed processing: %s", pStr);
        }
        else
        {
            Log(L"String at 0x%X, %d chars long is unreadable!", pStr, ncbNumCharsInStr);
        }
    }
}

実装する方法はありますmemory_readableか?

4

2 に答える 2

5

VirtualQuery関数が役立つ場合があります以下は、それを使用して実装する方法を簡単に説明memory_readableしたものです。

bool memory_readable(void *ptr, size_t byteCount)
{
  MEMORY_BASIC_INFORMATION mbi;
  if (VirtualQuery(ptr, &mbi, sizeof(MEMORY_BASIC_INFORMATION)) == 0)
    return false;

  if (mbi.State != MEM_COMMIT)
    return false;

  if (mbi.Protect == PAGE_NOACCESS || mbi.Protect == PAGE_EXECUTE)
    return false;

  // This checks that the start of memory block is in the same "region" as the
  // end. If it isn't you "simplify" the problem into checking that the rest of 
  // the memory is readable.
  size_t blockOffset = (size_t)((char *)ptr - (char *)mbi.AllocationBase);
  size_t blockBytesPostPtr = mbi.RegionSize - blockOffset;

  if (blockBytesPostPtr < byteCount)
    return memory_readable((char *)ptr + blockBytesPostPtr,
                           byteCount - blockBytesPostPtr);

  return true;
}

注: 私のバックグラウンドは C であるため、C++ で a にキャストするよりも優れたオプションがあると思いますが、char *それらが何であるかはわかりません。

于 2013-08-23T05:19:39.403 に答える