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.
19 #include <sys/types.h>
22 static char *progname
;
23 static unsigned int xtra_offset
;
24 static unsigned char eof_mark
[4] = {0xde, 0xad, 0xc0, 0xde};
25 static unsigned char jffs2_pad_be
[] = "\x19\x85\x20\x04\x04\x00\x00\x00\xc4\x94\xdb\xf4";
26 static unsigned char jffs2_pad_le
[] = "\x85\x19\x04\x20\x00\x00\x00\x04\xa8\xfb\xa0\xb4";
27 static unsigned char *pad
= eof_mark
;
28 static int pad_len
= sizeof(eof_mark
);
29 static bool pad_to_stdout
= false;
31 #define ERR(fmt, ...) do { \
33 fprintf(stderr, "[%s] *** error: " fmt "\n", \
34 progname, ## __VA_ARGS__ ); \
37 #define ERRS(fmt, ...) do { \
40 fprintf(stderr, "[%s] *** error: " fmt ", %s\n", \
41 progname, ## __VA_ARGS__, strerror(save)); \
44 #define BUF_SIZE (64 * 1024)
45 #define ALIGN(_x,_y) (((_x) + ((_y) - 1)) & ~((_y) - 1))
47 static int pad_image(char *name
, uint32_t pad_mask
)
56 buf
= malloc(BUF_SIZE
);
58 ERR("No memory for buffer");
62 fd
= open(name
, O_RDWR
);
64 ERRS("Unable to open %s", name
);
68 in_len
= lseek(fd
, 0, SEEK_END
);
75 outfd
= STDOUT_FILENO
;
77 memset(buf
, '\xff', BUF_SIZE
);
79 in_len
+= xtra_offset
;
87 for (i
= 10; i
< 32; i
++) {
93 in_len
= ALIGN(in_len
, mask
);
95 for (i
= 10; i
< 32; i
++) {
97 if ((in_len
& (mask
- 1)) == 0)
101 fprintf(stderr
, "padding image to %08x\n", (unsigned int) in_len
- xtra_offset
);
103 while (out_len
< in_len
) {
106 len
= in_len
- out_len
;
110 t
= write(outfd
, buf
, len
);
112 ERRS("Unable to write to %s", name
);
119 /* write out the JFFS end-of-filesystem marker */
120 t
= write(outfd
, pad
, pad_len
);
122 ERRS("Unable to write to %s", name
);
138 static int usage(void)
141 "Usage: %s file [<options>] [pad0] [pad1] [padN]\n"
143 " -x <offset>: Add an extra offset for padding data\n"
144 " -J: Use a fake big-endian jffs2 padding element instead of EOF\n"
145 " This is used to work around broken boot loaders that\n"
146 " try to parse the entire firmware area as one big jffs2\n"
147 " -j: (like -J, but little-endian instead of big-endian)\n"
148 " -c: write padding to stdout\n"
154 int main(int argc
, char* argv
[])
158 int ret
= EXIT_FAILURE
;
162 progname
= basename(argv
[0]);
172 while ((ch
= getopt(argc
, argv
, "x:Jjc")) != -1) {
175 xtra_offset
= strtoul(optarg
, NULL
, 0);
176 fprintf(stderr
, "assuming %u bytes offset\n",
181 pad_len
= sizeof(jffs2_pad_be
) - 1;
185 pad_len
= sizeof(jffs2_pad_le
) - 1;
188 pad_to_stdout
= true;
195 for (i
= optind
; i
< argc
; i
++)
196 pad_mask
|= strtoul(argv
[i
], NULL
, 0) * 1024;
199 pad_mask
= (4 * 1024) | (8 * 1024) | (64 * 1024) |
202 err
= pad_image(image
, pad_mask
);