v1.5 branch refresh based upon upstream master @ c8677ca89e53e3be7988d54280fce166cc894a7e
[librecmc/librecmc.git] / tools / firmware-utils / src / mkdhpimg.c
1 /*
2  * Copyright (c) 2016 FUKAUMI Naoki <naobsd@gmail.com>
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License version 2 as published
6  * by the Free Software Foundation.
7  *
8  */
9
10 #include <sys/stat.h>
11 #include <err.h>
12 #include <fcntl.h>
13 #include <stdint.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <unistd.h>
18
19 #include "buffalo-lib.h"
20
21 #define DHP_HEADER_SIZE 20
22
23 static char *progname;
24
25 static void
26 usage(void)
27 {
28
29         fprintf(stderr, "usage: %s <in> <out>\n", progname);
30         exit(EXIT_FAILURE);
31 }
32
33 int
34 main(int argc, char *argv[])
35 {
36         struct stat in_st;
37         size_t size;
38         uint32_t crc;
39         int in, out;
40         uint8_t *buf;
41
42         progname = argv[0];
43
44         if (argc != 3)
45                 usage();
46
47         if ((in = open(argv[1], O_RDONLY)) == -1)
48                 err(EXIT_FAILURE, "%s", argv[1]);
49
50         if (fstat(in, &in_st) == -1)
51                 err(EXIT_FAILURE, "%s", argv[1]);
52
53         size = DHP_HEADER_SIZE + in_st.st_size;
54
55         if ((buf = malloc(size)) == NULL)
56                 err(EXIT_FAILURE, "malloc");
57
58         memset(buf, 0, DHP_HEADER_SIZE);
59         buf[0x0] = 0x62;
60         buf[0x1] = 0x67;
61         buf[0x2] = 0x6e;
62         buf[0xb] = 0xb1;
63         buf[0xc] = (size >> 24) & 0xff;
64         buf[0xd] = (size >> 16) & 0xff;
65         buf[0xe] = (size >> 8) & 0xff;
66         buf[0xf] = size & 0xff;
67
68         read(in, &buf[DHP_HEADER_SIZE], in_st.st_size);
69         close(in);
70
71         crc = buffalo_crc(buf, size);
72         buf[0x10] = (crc >> 24) & 0xff;
73         buf[0x11] = (crc >> 16) & 0xff;
74         buf[0x12] = (crc >> 8) & 0xff;
75         buf[0x13] = crc & 0xff;
76
77         if ((out = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644)) == -1)
78                 err(EXIT_FAILURE, "%s", argv[2]);
79         write(out, buf, size);
80         close(out);
81
82         free(buf);
83
84         return EXIT_SUCCESS;
85 }