Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
2.5 KiB

  1. //Copyright (c) 1997-2000 Microsoft Corporation
  2. // Memory mapped file routines
  3. #include <windows.h>
  4. #include "w95trace.h"
  5. #include "mappedfile.h"
  6. BOOL CMemMappedFile::Open(
  7. LPCTSTR szName, // name of the mapped file
  8. unsigned long ulMemSize // size of the mapped file
  9. )
  10. {
  11. // assumption: the code isn't going to call Open twice w/different szName
  12. if (!m_hMappedFile)
  13. {
  14. // Create the mapped file from system page file. If it has been created
  15. // previously, then CreateFileMapping acts like OpenFileMapping.
  16. m_hMappedFile = CreateFileMapping(
  17. INVALID_HANDLE_VALUE, // Current file handle.
  18. NULL, // Default security.
  19. PAGE_READWRITE, // Read/write permission.
  20. 0, // Hi-order DWORD of file size
  21. ulMemSize, // Lo-order DWORD of file size
  22. szName); // Name of mapping object.
  23. if (!m_hMappedFile)
  24. {
  25. DBPRINTF(TEXT("CMemMappedFile::Open: CreateFileMapping %s failed 0x%x\r\n"), szName, GetLastError());
  26. return FALSE;
  27. }
  28. // Note if this is the first open for the file?
  29. m_fFirstOpen = (GetLastError() == ERROR_SUCCESS)?TRUE:FALSE;
  30. }
  31. return TRUE;
  32. }
  33. BOOL CMemMappedFile::AccessMem(
  34. void **ppvMappedAddr // returned pointer into memory
  35. )
  36. {
  37. if (IsBadWritePtr(ppvMappedAddr, sizeof(void *)))
  38. return FALSE;
  39. if (!m_hMappedFile)
  40. return FALSE;
  41. // Get a pointer to the mapped memory if we don't already have it
  42. if (!m_pvMappedAddr)
  43. {
  44. DBPRINTF(TEXT("MapViewOfFile\r\n"));
  45. m_pvMappedAddr = MapViewOfFile(
  46. m_hMappedFile, // Handle to mapping object.
  47. FILE_MAP_ALL_ACCESS, // Read/write permission
  48. 0, // Max. object size.
  49. 0, // Size of hFile.
  50. 0); // Map entire file.
  51. *ppvMappedAddr = m_pvMappedAddr;
  52. }
  53. if (NULL == m_pvMappedAddr)
  54. {
  55. DBPRINTF(TEXT("CMemMappedFile::AccessMem: MapViewOfFile failed 0x%x\r\n"), GetLastError());
  56. return FALSE;
  57. }
  58. return TRUE;
  59. }
  60. void CMemMappedFile::Close()
  61. {
  62. if (m_pvMappedAddr)
  63. {
  64. UnmapViewOfFile(m_pvMappedAddr);
  65. m_pvMappedAddr = 0;
  66. }
  67. if (m_hMappedFile)
  68. {
  69. CloseHandle(m_hMappedFile);
  70. m_hMappedFile = 0;
  71. }
  72. m_fFirstOpen = FALSE;
  73. }