crc.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* crc.c - crc function */
  2. /*
  3. * GRUB -- GRand Unified Bootloader
  4. * Copyright (C) 2008 Free Software Foundation, Inc.
  5. *
  6. * GRUB is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * GRUB is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with GRUB. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include <grub/types.h>
  20. #include <grub/symbol.h>
  21. #include <grub/lib.h>
  22. GRUB_EXPORT(grub_getcrc32);
  23. static grub_uint32_t crc32_table [256];
  24. static grub_uint32_t
  25. reflect (grub_uint32_t ref, int len)
  26. {
  27. grub_uint32_t result = 0;
  28. int i;
  29. for (i = 1; i <= len; i++)
  30. {
  31. if (ref & 1)
  32. result |= 1 << (len - i);
  33. ref >>= 1;
  34. }
  35. return result;
  36. }
  37. static void
  38. init_crc32_table (void)
  39. {
  40. grub_uint32_t polynomial = 0x04c11db7;
  41. int i, j;
  42. for(i = 0; i < 256; i++)
  43. {
  44. crc32_table[i] = reflect(i, 8) << 24;
  45. for (j = 0; j < 8; j++)
  46. crc32_table[i] = (crc32_table[i] << 1) ^
  47. (crc32_table[i] & (1 << 31) ? polynomial : 0);
  48. crc32_table[i] = reflect(crc32_table[i], 32);
  49. }
  50. }
  51. grub_uint32_t
  52. grub_getcrc32 (grub_uint32_t crc, void *buf, int size)
  53. {
  54. int i;
  55. grub_uint8_t *data = buf;
  56. if (! crc32_table[1])
  57. init_crc32_table ();
  58. crc^= 0xffffffff;
  59. for (i = 0; i < size; i++)
  60. {
  61. crc = (crc >> 8) ^ crc32_table[(crc & 0xFF) ^ *data];
  62. data++;
  63. }
  64. return crc ^ 0xffffffff;
  65. }