crcit.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * (C) Copyright 2005
  3. * 2N Telekomunikace, Ladislav Michl <michl@2n.cz>
  4. *
  5. * See file CREDITS for list of people who contributed to this
  6. * project.
  7. *
  8. * This program is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU General Public License as
  10. * published by the Free Software Foundation; either version 2 of
  11. * the License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, write to the Free Software
  20. * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  21. * MA 02111-1307 USA
  22. */
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <stdint.h>
  26. #include <fcntl.h>
  27. #include <string.h>
  28. #include <unistd.h>
  29. #include <sys/types.h>
  30. #include <sys/stat.h>
  31. #include "crcek.h"
  32. extern uint32_t crc32(uint32_t, const unsigned char *, uint);
  33. static uint32_t data[LOADER_SIZE/4 + 3];
  34. static int do_crc(char *path, unsigned version)
  35. {
  36. uint32_t *p;
  37. ssize_t size;
  38. int fd;
  39. fd = open(path, O_RDONLY);
  40. if (fd == -1) {
  41. perror("Error opening file");
  42. return EXIT_FAILURE;
  43. }
  44. p = data + 2;
  45. size = read(fd, p, LOADER_SIZE + 4);
  46. if (size == -1) {
  47. perror("Error reading file");
  48. return EXIT_FAILURE;
  49. }
  50. if (size > LOADER_SIZE) {
  51. fprintf(stderr, "File too large\n");
  52. return EXIT_FAILURE;
  53. }
  54. size = (size + 3) & ~3; /* round up to 4 bytes */
  55. size += 4; /* add size of version field */
  56. data[0] = size;
  57. data[1] = version;
  58. data[size/4 + 1] = crc32(0, (unsigned char *)(data + 1), size);
  59. close(fd);
  60. if (write(STDOUT_FILENO, data, size + 4 /*size*/ + 4 /*crc*/) == -1) {
  61. perror("Error writing file");
  62. return EXIT_FAILURE;
  63. }
  64. return EXIT_SUCCESS;
  65. }
  66. int main(int argc, char * const *argv)
  67. {
  68. if (argc == 2) {
  69. return do_crc(argv[1], 0);
  70. } else if ((argc == 4) && (strcmp(argv[1], "-v") == 0)) {
  71. char *endptr, *nptr = argv[2];
  72. unsigned ver = strtoul(nptr, &endptr, 0);
  73. if (*nptr != '\0' && *endptr == '\0')
  74. return do_crc(argv[3], ver);
  75. }
  76. fprintf(stderr, "Usage: crcit [-v version] <image>\n");
  77. return EXIT_FAILURE;
  78. }