crc.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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/lib/crc.h>
  21. static grub_uint32_t crc32c_table [256];
  22. /* Helper for init_crc32c_table. */
  23. static grub_uint32_t
  24. reflect (grub_uint32_t ref, int len)
  25. {
  26. grub_uint32_t result = 0;
  27. int i;
  28. for (i = 1; i <= len; i++)
  29. {
  30. if (ref & 1)
  31. result |= 1 << (len - i);
  32. ref >>= 1;
  33. }
  34. return result;
  35. }
  36. static void
  37. init_crc32c_table (void)
  38. {
  39. grub_uint32_t polynomial = 0x1edc6f41;
  40. int i, j;
  41. for(i = 0; i < 256; i++)
  42. {
  43. crc32c_table[i] = reflect(i, 8) << 24;
  44. for (j = 0; j < 8; j++)
  45. crc32c_table[i] = (crc32c_table[i] << 1) ^
  46. (crc32c_table[i] & (1 << 31) ? polynomial : 0);
  47. crc32c_table[i] = reflect(crc32c_table[i], 32);
  48. }
  49. }
  50. grub_uint32_t
  51. grub_getcrc32c (grub_uint32_t crc, const void *buf, int size)
  52. {
  53. int i;
  54. const grub_uint8_t *data = buf;
  55. if (! crc32c_table[1])
  56. init_crc32c_table ();
  57. crc^= 0xffffffff;
  58. for (i = 0; i < size; i++)
  59. {
  60. crc = (crc >> 8) ^ crc32c_table[(crc & 0xFF) ^ *data];
  61. data++;
  62. }
  63. return crc ^ 0xffffffff;
  64. }