Leaked source code of windows server 2003
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.

86 lines
1.6 KiB

  1. #include "stdafx.h"
  2. #include "FileHash.h"
  3. static DWORD crc_table[256];
  4. static BOOL g_bCRC32Init = FALSE;
  5. void InitCRC32Table()
  6. {
  7. DWORD crc, poly;
  8. int i, j;
  9. poly = 0xEDB88320;
  10. for (i = 0; i < 256; i++)
  11. {
  12. crc = i;
  13. for (j = 8; j > 0; j--)
  14. {
  15. if (crc & 1)
  16. crc = (crc >> 1) ^ poly;
  17. else
  18. crc >>= 1;
  19. }
  20. crc_table[i] = crc;
  21. }
  22. }
  23. DWORD GetCRC32(BYTE *pData, DWORD dwSize)
  24. {
  25. if(!g_bCRC32Init)
  26. InitCRC32Table();
  27. register unsigned long crc;
  28. BYTE *pEnd = pData + dwSize;
  29. crc = 0xFFFFFFFF;
  30. while (pData<pEnd)
  31. crc = ((crc>>8) & 0x00FFFFFF) ^ crc_table[ (crc^(*(pData++))) & 0xFF ];
  32. return ( crc^0xFFFFFFFF );
  33. }
  34. HRESULT GetCRC32(HANDLE hFile, DWORD dwSize, DWORD *pdwCRC32)
  35. {
  36. HRESULT hr = E_FAIL;
  37. if(0 == dwSize)
  38. {
  39. *pdwCRC32 = 0;
  40. return S_OK;
  41. }
  42. HANDLE hMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, dwSize, NULL);
  43. if(!hMapping)
  44. return hr;
  45. BYTE *pData = (BYTE*)MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, dwSize);
  46. if(pData)
  47. {
  48. *pdwCRC32 = GetCRC32(pData, dwSize);
  49. hr = S_OK;
  50. UnmapViewOfFile(pData);
  51. }
  52. CloseHandle(hMapping);
  53. return hr;
  54. }
  55. HRESULT GetCRC32(TCHAR *szFile, DWORD *pdwSize, DWORD *pdwCRC32)
  56. {
  57. HRESULT hr = E_FAIL;
  58. HANDLE hFile = CreateFile(szFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  59. if(INVALID_HANDLE_VALUE == hFile)
  60. return hr;
  61. DWORD dwHigh = 0;
  62. *pdwSize = GetFileSize(hFile, &dwHigh);
  63. // We don't support files larger than 4 gig
  64. if(0 == dwHigh)
  65. hr = GetCRC32(hFile, *pdwSize, pdwCRC32);
  66. CloseHandle(hFile);
  67. return hr;
  68. }