- if (stat(argv[1], &stat_buf) == -1) {
- fprintf(stderr, "Can't stat %s: %s\n", argv[1], strerror(errno));
- exit(EXIT_FAILURE);
- }
-
- fd = open(argv[1], O_RDONLY);
- if (fd < 0) {
- fprintf(stderr, "Can't open %s: %s", argv[1], strerror(errno));
- exit(EXIT_FAILURE);
- }
-
- printf("Reading firmware from %s...\n", argv[1]);
- do {
- memset(buf, 0, sizeof(buf));
- r = read(fd, buf, 4);
- if (r < 0) {
- perror("read");
- exit(EXIT_FAILURE);
- } else if (r == 0) {
- break;
- } else if (r != 4) {
- printf("can't get length information!\n");
- exit(EXIT_FAILURE);
- }
-
- for (i = 0; i < r; i++) {
- if (!validate_nibble(buf[i])) {
- fprintf(stderr, "Firmware file not valid!\n");
- exit(EXIT_FAILURE);
- }
- }
-
- len = (ascii_to_nibble(buf[0]) & 0xf)<< 4;
- len |= ascii_to_nibble(buf[1]) & 0xf;
- len <<= 8;
- len |= (ascii_to_nibble(buf[2]) & 0xf)<< 4;
- len |= ascii_to_nibble(buf[3]) & 0xf;
-
- /* This might be wrong, but it works for current fw */
- if (len > MAX_BLOCK_LENGTH) {
- fprintf(stderr, "Invalid block-length %u > %u for block %d!\n", len, MAX_BLOCK_LENGTH, fw_blocks+1);
- exit(EXIT_FAILURE);
- }
-
- fw = realloc(fw, sizeof(uint8_t*) * (fw_blocks + 1));
- if (fw == NULL) {
- perror("Can't reallocate fw-blocklist");
- exit(EXIT_FAILURE);
- }
-
- fw[fw_blocks] = malloc(len + 4);
- if (fw[fw_blocks] == NULL) {
- perror("Can't allocate memory for fw-block");
- exit(EXIT_FAILURE);
- }
-
- fw[fw_blocks][0] = (fw_blocks >> 8) & 0xff;
- fw[fw_blocks][1] = fw_blocks & 0xff;
- fw[fw_blocks][2] = (len >> 8) & 0xff;
- fw[fw_blocks][3] = len & 0xff;
-
- r = read(fd, buf, len * 2);
- if (r < 0) {
- perror("read");
- exit(EXIT_FAILURE);
- } else if (r < len * 2) {
- fprintf(stderr, "short read, aborting (%d < %d)\n", r, len * 2);
- exit(EXIT_FAILURE);
- }
-
- for (i = 0; i < r; i+=2) {
- if ((!validate_nibble(buf[i])) ||
- (!validate_nibble(buf[i+1]))) {
- fprintf(stderr, "Firmware file not valid!\n");
- exit(EXIT_FAILURE);
- }
-
- fw[fw_blocks][(i/2) + 4] = (ascii_to_nibble(buf[i]) & 0xf)<< 4;
- fw[fw_blocks][(i/2) + 4] |= ascii_to_nibble(buf[i+1]) & 0xf;
- }
-
- fw_blocks++;
- if (debug)
- printf("Firmware block %d with length %u read.\n", fw_blocks, len);
- } while(r > 0);
-
- if (fw_blocks == 0) {
- fprintf(stderr, "Firmware file not valid!\n");