2 * Copyright (C) 2011 Gabor Juhos <juhosg@openwrt.org>
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.
18 #include <sys/types.h>
21 static char *progname;
22 static unsigned int xtra_offset;
23 static unsigned char eof_mark[4] = {0xde, 0xad, 0xc0, 0xde};
24 static unsigned char jffs2_pad_be[] = "\x19\x85\x20\x04\x04\x00\x00\x00\xc4\x94\xdb\xf4";
25 static unsigned char jffs2_pad_le[] = "\x85\x19\x04\x20\x00\x00\x00\x04\xa8\xfb\xa0\xb4";
26 static unsigned char *pad = eof_mark;
27 static int pad_len = sizeof(eof_mark);
29 #define ERR(fmt, ...) do { \
31 fprintf(stderr, "[%s] *** error: " fmt "\n", \
32 progname, ## __VA_ARGS__ ); \
35 #define ERRS(fmt, ...) do { \
38 fprintf(stderr, "[%s] *** error: " fmt ", %s\n", \
39 progname, ## __VA_ARGS__, strerror(save)); \
42 #define BUF_SIZE (64 * 1024)
43 #define ALIGN(_x,_y) (((_x) + ((_y) - 1)) & ~((_y) - 1))
45 static int pad_image(char *name, uint32_t pad_mask)
53 buf = malloc(BUF_SIZE);
55 ERR("No memory for buffer");
59 fd = open(name, O_RDWR);
61 ERRS("Unable to open %s", name);
65 in_len = lseek(fd, 0, SEEK_END);
69 memset(buf, '\xff', BUF_SIZE);
71 in_len += xtra_offset;
79 for (i = 10; i < 32; i++) {
85 in_len = ALIGN(in_len, mask);
87 for (i = 10; i < 32; i++) {
89 if ((in_len & (mask - 1)) == 0)
93 printf("padding image to %08x\n", (unsigned int) in_len - xtra_offset);
95 while (out_len < in_len) {
98 len = in_len - out_len;
102 t = write(fd, buf, len);
104 ERRS("Unable to write to %s", name);
111 /* write out the JFFS end-of-filesystem marker */
112 t = write(fd, pad, pad_len);
114 ERRS("Unable to write to %s", name);
130 static int usage(void)
133 "Usage: %s file [<options>] [pad0] [pad1] [padN]\n"
135 " -x <offset>: Add an extra offset for padding data\n"
136 " -J: Use a fake big-endian jffs2 padding element instead of EOF\n"
137 " This is used to work around broken boot loaders that\n"
138 " try to parse the entire firmware area as one big jffs2\n"
139 " -j: (like -J, but little-endian instead of big-endian)\n"
145 int main(int argc, char* argv[])
149 int ret = EXIT_FAILURE;
153 progname = basename(argv[0]);
163 while ((ch = getopt(argc, argv, "x:Jj")) != -1) {
166 xtra_offset = strtoul(optarg, NULL, 0);
167 fprintf(stderr, "assuming %u bytes offset\n",
172 pad_len = sizeof(jffs2_pad_be) - 1;
176 pad_len = sizeof(jffs2_pad_le) - 1;
183 for (i = optind; i < argc; i++)
184 pad_mask |= strtoul(argv[i], NULL, 0) * 1024;
187 pad_mask = (4 * 1024) | (8 * 1024) | (64 * 1024) |
190 err = pad_image(image, pad_mask);