34e6546a2d7db72748146ef233830c2e8de9ce97
[oweals/openwrt.git] / tools / firmware-utils / src / mktplinkfw.c
1 /*
2  * Copyright (C) 2009 Gabor Juhos <juhosg@openwrt.org>
3  *
4  * This tool was based on:
5  *   TP-Link WR941 V2 firmware checksum fixing tool.
6  *   Copyright (C) 2008,2009 Wang Jian <lark@linux.net.cn>
7  *
8  * This program is free software; you can redistribute it and/or modify it
9  * under the terms of the GNU General Public License version 2 as published
10  * by the Free Software Foundation.
11  *
12  */
13
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <stdint.h>
17 #include <string.h>
18 #include <unistd.h>     /* for unlink() */
19 #include <libgen.h>
20 #include <getopt.h>     /* for getopt() */
21 #include <stdarg.h>
22 #include <errno.h>
23 #include <sys/stat.h>
24
25 #include <arpa/inet.h>
26 #include <netinet/in.h>
27
28 #include "md5.h"
29
30 #define ALIGN(x,a) ({ typeof(a) __a = (a); (((x) + __a - 1) & ~(__a - 1)); })
31 #define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0]))
32
33 #define HEADER_VERSION_V1       0x01000000
34 #define HEADER_VERSION_V2       0x02000000
35
36 #define MD5SUM_LEN      16
37
38 struct file_info {
39         char            *file_name;     /* name of the file */
40         uint32_t        file_size;      /* length of the file */
41 };
42
43 struct fw_header {
44         uint32_t        version;        /* header version */
45         char            vendor_name[24];
46         char            fw_version[36];
47         uint32_t        hw_id;          /* hardware id */
48         uint32_t        hw_rev;         /* hardware revision */
49         uint32_t        region_code;    /* region code */
50         uint8_t         md5sum1[MD5SUM_LEN];
51         uint32_t        unk2;
52         uint8_t         md5sum2[MD5SUM_LEN];
53         uint32_t        unk3;
54         uint32_t        kernel_la;      /* kernel load address */
55         uint32_t        kernel_ep;      /* kernel entry point */
56         uint32_t        fw_length;      /* total length of the firmware */
57         uint32_t        kernel_ofs;     /* kernel data offset */
58         uint32_t        kernel_len;     /* kernel data length */
59         uint32_t        rootfs_ofs;     /* rootfs data offset */
60         uint32_t        rootfs_len;     /* rootfs data length */
61         uint32_t        boot_ofs;       /* bootloader data offset */
62         uint32_t        boot_len;       /* bootloader data length */
63         uint16_t        ver_hi;
64         uint16_t        ver_mid;
65         uint16_t        ver_lo;
66         uint8_t         pad[130];
67         char            region_str1[32];
68         char            region_str2[32];
69         uint8_t         pad2[160];
70 } __attribute__ ((packed));
71
72 struct flash_layout {
73         char            *id;
74         uint32_t        fw_max_len;
75         uint32_t        kernel_la;
76         uint32_t        kernel_ep;
77         uint32_t        rootfs_ofs;
78 };
79
80 struct fw_region {
81         char            name[4];
82         uint32_t        code;
83 };
84
85
86 /*
87  * Globals
88  */
89 static char *ofname;
90 static char *progname;
91 static char *vendor = "TP-LINK Technologies";
92 static char *version = "ver. 1.0";
93 static char *fw_ver = "0.0.0";
94 static uint32_t hdr_ver = HEADER_VERSION_V1;
95
96 static char *layout_id;
97 static struct flash_layout *layout;
98 static char *opt_hw_id;
99 static uint32_t hw_id;
100 static char *opt_hw_rev;
101 static uint32_t hw_rev;
102 static uint32_t opt_hdr_ver = 1;
103 static char *country;
104 static const struct fw_region *region;
105 static int fw_ver_lo;
106 static int fw_ver_mid;
107 static int fw_ver_hi;
108 static struct file_info kernel_info;
109 static uint32_t kernel_la = 0;
110 static uint32_t kernel_ep = 0;
111 static uint32_t kernel_len = 0;
112 static struct file_info rootfs_info;
113 static uint32_t rootfs_ofs = 0;
114 static uint32_t rootfs_align;
115 static struct file_info boot_info;
116 static int combined;
117 static int strip_padding;
118 static int ignore_size;
119 static int add_jffs2_eof;
120 static unsigned char jffs2_eof_mark[4] = {0xde, 0xad, 0xc0, 0xde};
121 static uint32_t fw_max_len;
122 static uint32_t reserved_space;
123
124 static struct file_info inspect_info;
125 static int extract = 0;
126
127 static const char md5salt_normal[MD5SUM_LEN] = {
128         0xdc, 0xd7, 0x3a, 0xa5, 0xc3, 0x95, 0x98, 0xfb,
129         0xdd, 0xf9, 0xe7, 0xf4, 0x0e, 0xae, 0x47, 0x38,
130 };
131
132 static const char md5salt_boot[MD5SUM_LEN] = {
133         0x8c, 0xef, 0x33, 0x5b, 0xd5, 0xc5, 0xce, 0xfa,
134         0xa7, 0x9c, 0x28, 0xda, 0xb2, 0xe9, 0x0f, 0x42,
135 };
136
137 static struct flash_layout layouts[] = {
138         {
139                 .id             = "4M",
140                 .fw_max_len     = 0x3c0000,
141                 .kernel_la      = 0x80060000,
142                 .kernel_ep      = 0x80060000,
143                 .rootfs_ofs     = 0x140000,
144         }, {
145                 .id             = "4Mlzma",
146                 .fw_max_len     = 0x3c0000,
147                 .kernel_la      = 0x80060000,
148                 .kernel_ep      = 0x80060000,
149                 .rootfs_ofs     = 0x100000,
150         }, {
151                 .id             = "8M",
152                 .fw_max_len     = 0x7c0000,
153                 .kernel_la      = 0x80060000,
154                 .kernel_ep      = 0x80060000,
155                 .rootfs_ofs     = 0x140000,
156         }, {
157                 .id             = "8Mlzma",
158                 .fw_max_len     = 0x7c0000,
159                 .kernel_la      = 0x80060000,
160                 .kernel_ep      = 0x80060000,
161                 .rootfs_ofs     = 0x100000,
162         }, {
163                 .id             = "16M",
164                 .fw_max_len     = 0xf80000,
165                 .kernel_la      = 0x80060000,
166                 .kernel_ep      = 0x80060000,
167                 .rootfs_ofs     = 0x140000,
168         }, {
169                 .id             = "16Mlzma",
170                 .fw_max_len     = 0xf80000,
171                 .kernel_la      = 0x80060000,
172                 .kernel_ep      = 0x80060000,
173                 .rootfs_ofs     = 0x100000,
174         }, {
175                 .id             = "16Mppc",
176                 .fw_max_len     = 0xf80000,
177                 .kernel_la      = 0x00000000 ,
178                 .kernel_ep      = 0xc0000000,
179                 .rootfs_ofs     = 0x2a0000,
180         }, {
181                 /* terminating entry */
182         }
183 };
184
185 static const struct fw_region regions[] = {
186         /* Default region (universal) uses code 0 as well */
187         {"US", 1},
188         {"EU", 0},
189 };
190
191 /*
192  * Message macros
193  */
194 #define ERR(fmt, ...) do { \
195         fflush(0); \
196         fprintf(stderr, "[%s] *** error: " fmt "\n", \
197                         progname, ## __VA_ARGS__ ); \
198 } while (0)
199
200 #define ERRS(fmt, ...) do { \
201         int save = errno; \
202         fflush(0); \
203         fprintf(stderr, "[%s] *** error: " fmt ": %s\n", \
204                         progname, ## __VA_ARGS__, strerror(save)); \
205 } while (0)
206
207 #define DBG(fmt, ...) do { \
208         fprintf(stderr, "[%s] " fmt "\n", progname, ## __VA_ARGS__ ); \
209 } while (0)
210
211 static struct flash_layout *find_layout(const char *id)
212 {
213         struct flash_layout *ret;
214         struct flash_layout *l;
215
216         ret = NULL;
217         for (l = layouts; l->id != NULL; l++){
218                 if (strcasecmp(id, l->id) == 0) {
219                         ret = l;
220                         break;
221                 }
222         };
223
224         return ret;
225 }
226
227 static const struct fw_region * find_region(const char *country) {
228         size_t i;
229
230         for (i = 0; i < ARRAY_SIZE(regions); i++) {
231                 if (strcasecmp(regions[i].name, country) == 0)
232                         return &regions[i];
233         }
234
235         return NULL;
236 }
237
238 static void usage(int status)
239 {
240         fprintf(stderr, "Usage: %s [OPTIONS...]\n", progname);
241         fprintf(stderr,
242 "\n"
243 "Options:\n"
244 "  -c              use combined kernel image\n"
245 "  -E <ep>         overwrite kernel entry point with <ep> (hexval prefixed with 0x)\n"
246 "  -L <la>         overwrite kernel load address with <la> (hexval prefixed with 0x)\n"
247 "  -H <hwid>       use hardware id specified with <hwid>\n"
248 "  -W <hwrev>      use hardware revision specified with <hwrev>\n"
249 "  -C <country>    set region code to <country>\n"
250 "  -F <id>         use flash layout specified with <id>\n"
251 "  -k <file>       read kernel image from the file <file>\n"
252 "  -r <file>       read rootfs image from the file <file>\n"
253 "  -a <align>      align the rootfs start on an <align> bytes boundary\n"
254 "  -R <offset>     overwrite rootfs offset with <offset> (hexval prefixed with 0x)\n"
255 "  -o <file>       write output to the file <file>\n"
256 "  -s              strip padding from the end of the image\n"
257 "  -S              ignore firmware size limit (only for combined images)\n"
258 "  -j              add jffs2 end-of-filesystem markers\n"
259 "  -N <vendor>     set image vendor to <vendor>\n"
260 "  -V <version>    set image version to <version>\n"
261 "  -v <version>    set firmware version to <version>\n"
262 "  -m <version>    set header version to <version>\n"
263 "  -i <file>       inspect given firmware file <file>\n"
264 "  -x              extract kernel and rootfs while inspecting (requires -i)\n"
265 "  -X <size>       reserve <size> bytes in the firmware image (hexval prefixed with 0x)\n"
266 "  -h              show this screen\n"
267         );
268
269         exit(status);
270 }
271
272 static void get_md5(const char *data, int size, uint8_t *md5)
273 {
274         MD5_CTX ctx;
275
276         MD5_Init(&ctx);
277         MD5_Update(&ctx, data, size);
278         MD5_Final(md5, &ctx);
279 }
280
281 static int get_file_stat(struct file_info *fdata)
282 {
283         struct stat st;
284         int res;
285
286         if (fdata->file_name == NULL)
287                 return 0;
288
289         res = stat(fdata->file_name, &st);
290         if (res){
291                 ERRS("stat failed on %s", fdata->file_name);
292                 return res;
293         }
294
295         fdata->file_size = st.st_size;
296         return 0;
297 }
298
299 static int read_to_buf(const struct file_info *fdata, char *buf)
300 {
301         FILE *f;
302         int ret = EXIT_FAILURE;
303
304         f = fopen(fdata->file_name, "r");
305         if (f == NULL) {
306                 ERRS("could not open \"%s\" for reading", fdata->file_name);
307                 goto out;
308         }
309
310         errno = 0;
311         fread(buf, fdata->file_size, 1, f);
312         if (errno != 0) {
313                 ERRS("unable to read from file \"%s\"", fdata->file_name);
314                 goto out_close;
315         }
316
317         ret = EXIT_SUCCESS;
318
319  out_close:
320         fclose(f);
321  out:
322         return ret;
323 }
324
325 static int check_options(void)
326 {
327         int ret;
328         int exceed_bytes;
329
330         if (inspect_info.file_name) {
331                 ret = get_file_stat(&inspect_info);
332                 if (ret)
333                         return ret;
334
335                 return 0;
336         } else if (extract) {
337                 ERR("no firmware for inspection specified");
338                 return -1;
339         }
340
341         if (opt_hw_id == NULL) {
342                 ERR("hardware id not specified");
343                 return -1;
344         }
345         hw_id = strtoul(opt_hw_id, NULL, 0);
346
347         if (layout_id == NULL) {
348                 ERR("flash layout is not specified");
349                 return -1;
350         }
351
352         if (opt_hw_rev)
353                 hw_rev = strtoul(opt_hw_rev, NULL, 0);
354         else
355                 hw_rev = 1;
356
357         if (country) {
358                 region = find_region(country);
359                 if (!region) {
360                         ERR("unknown region code \"%s\"", country);
361                         return -1;
362                 }
363         }
364
365         layout = find_layout(layout_id);
366         if (layout == NULL) {
367                 ERR("unknown flash layout \"%s\"", layout_id);
368                 return -1;
369         }
370
371         if (!kernel_la)
372                 kernel_la = layout->kernel_la;
373         if (!kernel_ep)
374                 kernel_ep = layout->kernel_ep;
375         if (!rootfs_ofs)
376                 rootfs_ofs = layout->rootfs_ofs;
377
378         if (reserved_space > layout->fw_max_len) {
379                 ERR("reserved space is not valid");
380                 return -1;
381         }
382
383         fw_max_len = layout->fw_max_len - reserved_space;
384
385         if (kernel_info.file_name == NULL) {
386                 ERR("no kernel image specified");
387                 return -1;
388         }
389
390         ret = get_file_stat(&kernel_info);
391         if (ret)
392                 return ret;
393
394         kernel_len = kernel_info.file_size;
395
396         if (combined) {
397                 exceed_bytes = kernel_info.file_size - (fw_max_len - sizeof(struct fw_header));
398                 if (exceed_bytes > 0) {
399                         if (!ignore_size) {
400                                 ERR("kernel image is too big by %i bytes", exceed_bytes);
401                                 return -1;
402                         }
403                         layout->fw_max_len = sizeof(struct fw_header) +
404                                              kernel_info.file_size +
405                                              reserved_space;
406                 }
407         } else {
408                 if (rootfs_info.file_name == NULL) {
409                         ERR("no rootfs image specified");
410                         return -1;
411                 }
412
413                 ret = get_file_stat(&rootfs_info);
414                 if (ret)
415                         return ret;
416
417                 if (rootfs_align) {
418                         kernel_len += sizeof(struct fw_header);
419                         kernel_len = ALIGN(kernel_len, rootfs_align);
420                         kernel_len -= sizeof(struct fw_header);
421
422                         DBG("kernel length aligned to %u", kernel_len);
423
424                         exceed_bytes = kernel_len + rootfs_info.file_size - (fw_max_len - sizeof(struct fw_header));
425                         if (exceed_bytes > 0) {
426                                 ERR("images are too big by %i bytes", exceed_bytes);
427                                 return -1;
428                         }
429                 } else {
430                         exceed_bytes = kernel_info.file_size - (rootfs_ofs - sizeof(struct fw_header));
431                         if (exceed_bytes > 0) {
432                                 ERR("kernel image is too big by %i bytes", exceed_bytes);
433                                 return -1;
434                         }
435
436                         exceed_bytes = rootfs_info.file_size - (fw_max_len - rootfs_ofs);
437                         if (exceed_bytes > 0) {
438                                 ERR("rootfs image is too big by %i bytes", exceed_bytes);
439                                 return -1;
440                         }
441                 }
442         }
443
444         if (ofname == NULL) {
445                 ERR("no output file specified");
446                 return -1;
447         }
448
449         ret = sscanf(fw_ver, "%d.%d.%d", &fw_ver_hi, &fw_ver_mid, &fw_ver_lo);
450         if (ret != 3) {
451                 ERR("invalid firmware version '%s'", fw_ver);
452                 return -1;
453         }
454
455         if (opt_hdr_ver == 1) {
456                 hdr_ver = HEADER_VERSION_V1;
457         } else if (opt_hdr_ver == 2) {
458                 hdr_ver = HEADER_VERSION_V2;
459         } else {
460                 ERR("invalid header version '%u'", opt_hdr_ver);
461                 return -1;
462         }
463
464         return 0;
465 }
466
467 static void fill_header(char *buf, int len)
468 {
469         struct fw_header *hdr = (struct fw_header *)buf;
470
471         memset(hdr, 0, sizeof(struct fw_header));
472
473         hdr->version = htonl(hdr_ver);
474         strncpy(hdr->vendor_name, vendor, sizeof(hdr->vendor_name));
475         strncpy(hdr->fw_version, version, sizeof(hdr->fw_version));
476         hdr->hw_id = htonl(hw_id);
477         hdr->hw_rev = htonl(hw_rev);
478
479         if (boot_info.file_size == 0)
480                 memcpy(hdr->md5sum1, md5salt_normal, sizeof(hdr->md5sum1));
481         else
482                 memcpy(hdr->md5sum1, md5salt_boot, sizeof(hdr->md5sum1));
483
484         hdr->kernel_la = htonl(kernel_la);
485         hdr->kernel_ep = htonl(kernel_ep);
486         hdr->fw_length = htonl(layout->fw_max_len);
487         hdr->kernel_ofs = htonl(sizeof(struct fw_header));
488         hdr->kernel_len = htonl(kernel_len);
489         if (!combined) {
490                 hdr->rootfs_ofs = htonl(rootfs_ofs);
491                 hdr->rootfs_len = htonl(rootfs_info.file_size);
492         }
493
494         hdr->ver_hi = htons(fw_ver_hi);
495         hdr->ver_mid = htons(fw_ver_mid);
496         hdr->ver_lo = htons(fw_ver_lo);
497
498         if (region) {
499                 hdr->region_code = htonl(region->code);
500                 snprintf(
501                         hdr->region_str1, sizeof(hdr->region_str1), "00000000;%02X%02X%02X%02X;",
502                         region->name[0], region->name[1], region->name[2], region->name[3]
503                 );
504                 snprintf(
505                         hdr->region_str2, sizeof(hdr->region_str2), "%02X%02X%02X%02X",
506                         region->name[0], region->name[1], region->name[2], region->name[3]
507                 );
508         }
509
510         get_md5(buf, len, hdr->md5sum1);
511 }
512
513 static int pad_jffs2(char *buf, int currlen)
514 {
515         int len;
516         uint32_t pad_mask;
517
518         len = currlen;
519         pad_mask = (64 * 1024);
520         while ((len < layout->fw_max_len) && (pad_mask != 0)) {
521                 uint32_t mask;
522                 int i;
523
524                 for (i = 10; i < 32; i++) {
525                         mask = 1 << i;
526                         if (pad_mask & mask)
527                                 break;
528                 }
529
530                 len = ALIGN(len, mask);
531
532                 for (i = 10; i < 32; i++) {
533                         mask = 1 << i;
534                         if ((len & (mask - 1)) == 0)
535                                 pad_mask &= ~mask;
536                 }
537
538                 for (i = 0; i < sizeof(jffs2_eof_mark); i++)
539                         buf[len + i] = jffs2_eof_mark[i];
540
541                 len += sizeof(jffs2_eof_mark);
542         }
543
544         return len;
545 }
546
547 static int write_fw(const char *data, int len)
548 {
549         FILE *f;
550         int ret = EXIT_FAILURE;
551
552         f = fopen(ofname, "w");
553         if (f == NULL) {
554                 ERRS("could not open \"%s\" for writing", ofname);
555                 goto out;
556         }
557
558         errno = 0;
559         fwrite(data, len, 1, f);
560         if (errno) {
561                 ERRS("unable to write output file");
562                 goto out_flush;
563         }
564
565         DBG("firmware file \"%s\" completed", ofname);
566
567         ret = EXIT_SUCCESS;
568
569  out_flush:
570         fflush(f);
571         fclose(f);
572         if (ret != EXIT_SUCCESS) {
573                 unlink(ofname);
574         }
575  out:
576         return ret;
577 }
578
579 static int build_fw(void)
580 {
581         int buflen;
582         char *buf;
583         char *p;
584         int ret = EXIT_FAILURE;
585         int writelen = 0;
586
587         buflen = layout->fw_max_len;
588
589         buf = malloc(buflen);
590         if (!buf) {
591                 ERR("no memory for buffer\n");
592                 goto out;
593         }
594
595         memset(buf, 0xff, buflen);
596         p = buf + sizeof(struct fw_header);
597         ret = read_to_buf(&kernel_info, p);
598         if (ret)
599                 goto out_free_buf;
600
601         writelen = sizeof(struct fw_header) + kernel_len;
602
603         if (!combined) {
604                 if (rootfs_align)
605                         p = buf + writelen;
606                 else
607                         p = buf + rootfs_ofs;
608
609                 ret = read_to_buf(&rootfs_info, p);
610                 if (ret)
611                         goto out_free_buf;
612
613                 if (rootfs_align)
614                         writelen += rootfs_info.file_size;
615                 else
616                         writelen = rootfs_ofs + rootfs_info.file_size;
617
618                 if (add_jffs2_eof)
619                         writelen = pad_jffs2(buf, writelen);
620         }
621
622         if (!strip_padding)
623                 writelen = buflen;
624
625         fill_header(buf, writelen);
626         ret = write_fw(buf, writelen);
627         if (ret)
628                 goto out_free_buf;
629
630         ret = EXIT_SUCCESS;
631
632  out_free_buf:
633         free(buf);
634  out:
635         return ret;
636 }
637
638 /* Helper functions to inspect_fw() representing different output formats */
639 static inline void inspect_fw_pstr(const char *label, const char *str)
640 {
641         printf("%-23s: %s\n", label, str);
642 }
643
644 static inline void inspect_fw_phex(const char *label, uint32_t val)
645 {
646         printf("%-23s: 0x%08x\n", label, val);
647 }
648
649 static inline void inspect_fw_phexdec(const char *label, uint32_t val)
650 {
651         printf("%-23s: 0x%08x / %8u bytes\n", label, val, val);
652 }
653
654 static inline void inspect_fw_pmd5sum(const char *label, const uint8_t *val, const char *text)
655 {
656         int i;
657
658         printf("%-23s:", label);
659         for (i=0; i<MD5SUM_LEN; i++)
660                 printf(" %02x", val[i]);
661         printf(" %s\n", text);
662 }
663
664 static int inspect_fw(void)
665 {
666         char *buf;
667         struct fw_header *hdr;
668         uint8_t md5sum[MD5SUM_LEN];
669         int ret = EXIT_FAILURE;
670
671         buf = malloc(inspect_info.file_size);
672         if (!buf) {
673                 ERR("no memory for buffer!\n");
674                 goto out;
675         }
676
677         ret = read_to_buf(&inspect_info, buf);
678         if (ret)
679                 goto out_free_buf;
680         hdr = (struct fw_header *)buf;
681
682         inspect_fw_pstr("File name", inspect_info.file_name);
683         inspect_fw_phexdec("File size", inspect_info.file_size);
684
685         if ((ntohl(hdr->version) != HEADER_VERSION_V1) &&
686             (ntohl(hdr->version) != HEADER_VERSION_V2)) {
687                 ERR("file does not seem to have V1/V2 header!\n");
688                 goto out_free_buf;
689         }
690
691         inspect_fw_phexdec("Version 1 Header size", sizeof(struct fw_header));
692
693         memcpy(md5sum, hdr->md5sum1, sizeof(md5sum));
694         if (ntohl(hdr->boot_len) == 0)
695                 memcpy(hdr->md5sum1, md5salt_normal, sizeof(md5sum));
696         else
697                 memcpy(hdr->md5sum1, md5salt_boot, sizeof(md5sum));
698         get_md5(buf, inspect_info.file_size, hdr->md5sum1);
699
700         if (memcmp(md5sum, hdr->md5sum1, sizeof(md5sum))) {
701                 inspect_fw_pmd5sum("Header MD5Sum1", md5sum, "(*ERROR*)");
702                 inspect_fw_pmd5sum("          --> expected", hdr->md5sum1, "");
703         } else {
704                 inspect_fw_pmd5sum("Header MD5Sum1", md5sum, "(ok)");
705         }
706         if (ntohl(hdr->unk2) != 0)
707                 inspect_fw_phexdec("Unknown value 2", hdr->unk2);
708         inspect_fw_pmd5sum("Header MD5Sum2", hdr->md5sum2,
709                            "(purpose yet unknown, unchecked here)");
710         if (ntohl(hdr->unk3) != 0)
711                 inspect_fw_phexdec("Unknown value 3", hdr->unk3);
712
713         printf("\n");
714
715         inspect_fw_pstr("Vendor name", hdr->vendor_name);
716         inspect_fw_pstr("Firmware version", hdr->fw_version);
717         inspect_fw_phex("Hardware ID", ntohl(hdr->hw_id));
718         inspect_fw_phex("Hardware Revision", ntohl(hdr->hw_rev));
719         inspect_fw_phex("Region code", ntohl(hdr->region_code));
720
721         printf("\n");
722
723         inspect_fw_phexdec("Kernel data offset",
724                            ntohl(hdr->kernel_ofs));
725         inspect_fw_phexdec("Kernel data length",
726                            ntohl(hdr->kernel_len));
727         inspect_fw_phex("Kernel load address",
728                         ntohl(hdr->kernel_la));
729         inspect_fw_phex("Kernel entry point",
730                         ntohl(hdr->kernel_ep));
731         inspect_fw_phexdec("Rootfs data offset",
732                            ntohl(hdr->rootfs_ofs));
733         inspect_fw_phexdec("Rootfs data length",
734                            ntohl(hdr->rootfs_len));
735         inspect_fw_phexdec("Boot loader data offset",
736                            ntohl(hdr->boot_ofs));
737         inspect_fw_phexdec("Boot loader data length",
738                            ntohl(hdr->boot_len));
739         inspect_fw_phexdec("Total firmware length",
740                            ntohl(hdr->fw_length));
741
742         if (extract) {
743                 FILE *fp;
744                 char *filename;
745
746                 printf("\n");
747
748                 filename = malloc(strlen(inspect_info.file_name) + 8);
749                 sprintf(filename, "%s-kernel", inspect_info.file_name);
750                 printf("Extracting kernel to \"%s\"...\n", filename);
751                 fp = fopen(filename, "w");
752                 if (fp) {
753                         if (!fwrite(buf + ntohl(hdr->kernel_ofs),
754                                     ntohl(hdr->kernel_len), 1, fp)) {
755                                 ERR("error in fwrite(): %s", strerror(errno));
756                         }
757                         fclose(fp);
758                 } else {
759                         ERR("error in fopen(): %s", strerror(errno));
760                 }
761                 free(filename);
762
763                 filename = malloc(strlen(inspect_info.file_name) + 8);
764                 sprintf(filename, "%s-rootfs", inspect_info.file_name);
765                 printf("Extracting rootfs to \"%s\"...\n", filename);
766                 fp = fopen(filename, "w");
767                 if (fp) {
768                         if (!fwrite(buf + ntohl(hdr->rootfs_ofs),
769                                     ntohl(hdr->rootfs_len), 1, fp)) {
770                                 ERR("error in fwrite(): %s", strerror(errno));
771                         }
772                         fclose(fp);
773                 } else {
774                         ERR("error in fopen(): %s", strerror(errno));
775                 }
776                 free(filename);
777         }
778
779  out_free_buf:
780         free(buf);
781  out:
782         return ret;
783 }
784
785 int main(int argc, char *argv[])
786 {
787         int ret = EXIT_FAILURE;
788
789         progname = basename(argv[0]);
790
791         while ( 1 ) {
792                 int c;
793
794                 c = getopt(argc, argv, "a:H:E:F:L:m:V:N:W:C:ci:k:r:R:o:xX:hsSjv:");
795                 if (c == -1)
796                         break;
797
798                 switch (c) {
799                 case 'a':
800                         sscanf(optarg, "0x%x", &rootfs_align);
801                         break;
802                 case 'H':
803                         opt_hw_id = optarg;
804                         break;
805                 case 'E':
806                         sscanf(optarg, "0x%x", &kernel_ep);
807                         break;
808                 case 'F':
809                         layout_id = optarg;
810                         break;
811                 case 'W':
812                         opt_hw_rev = optarg;
813                         break;
814                 case 'C':
815                         country = optarg;
816                         break;
817                 case 'L':
818                         sscanf(optarg, "0x%x", &kernel_la);
819                         break;
820                 case 'm':
821                         sscanf(optarg, "%u", &opt_hdr_ver);
822                         break;
823                 case 'V':
824                         version = optarg;
825                         break;
826                 case 'v':
827                         fw_ver = optarg;
828                         break;
829                 case 'N':
830                         vendor = optarg;
831                         break;
832                 case 'c':
833                         combined++;
834                         break;
835                 case 'k':
836                         kernel_info.file_name = optarg;
837                         break;
838                 case 'r':
839                         rootfs_info.file_name = optarg;
840                         break;
841                 case 'R':
842                         sscanf(optarg, "0x%x", &rootfs_ofs);
843                         break;
844                 case 'o':
845                         ofname = optarg;
846                         break;
847                 case 's':
848                         strip_padding = 1;
849                         break;
850                 case 'S':
851                         ignore_size = 1;
852                         break;
853                 case 'i':
854                         inspect_info.file_name = optarg;
855                         break;
856                 case 'j':
857                         add_jffs2_eof = 1;
858                         break;
859                 case 'x':
860                         extract = 1;
861                         break;
862                 case 'h':
863                         usage(EXIT_SUCCESS);
864                         break;
865                 case 'X':
866                         sscanf(optarg, "0x%x", &reserved_space);
867                         break;
868                 default:
869                         usage(EXIT_FAILURE);
870                         break;
871                 }
872         }
873
874         ret = check_options();
875         if (ret)
876                 goto out;
877
878         if (!inspect_info.file_name)
879                 ret = build_fw();
880         else
881                 ret = inspect_fw();
882
883  out:
884         return ret;
885 }