2 * xorimage.c - partially based on OpenWrt's addpattern.c
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 static char default_pattern[] = "12345678";
29 static int is_hex_pattern;
32 int xor_data(uint8_t *data, size_t len, const uint8_t *pattern, int p_len, int p_off)
36 *data ^= pattern[offset];
38 offset = (offset + 1) % p_len;
44 void usage(void) __attribute__ (( __noreturn__ ));
48 fprintf(stderr, "Usage: xorimage [-i infile] [-o outfile] [-p <pattern>] [-x]\n");
53 int main(int argc, char **argv)
55 char buf[1024]; /* keep this at 1k or adjust garbage calc below */
60 const char *pattern = default_pattern;
61 char hex_pattern[128];
68 while ((c = getopt(argc, argv, "i:o:p:xh")) != -1) {
80 is_hex_pattern = true;
88 if (optind != argc || optind == 1) {
89 fprintf(stderr, "illegal arg \"%s\"\n", argv[optind]);
93 if (ifn && !(in = fopen(ifn, "r"))) {
94 fprintf(stderr, "can not open \"%s\" for reading\n", ifn);
98 if (ofn && !(out = fopen(ofn, "w"))) {
99 fprintf(stderr, "can not open \"%s\" for writing\n", ofn);
103 p_len = strlen(pattern);
106 fprintf(stderr, "pattern cannot be empty\n");
110 if (is_hex_pattern) {
113 if ((p_len / 2) > sizeof(hex_pattern)) {
114 fprintf(stderr, "provided hex pattern is too long\n");
118 if (p_len % 2 != 0) {
119 fprintf(stderr, "the number of characters (hex) is incorrect\n");
123 for (i = 0; i < (p_len / 2); i++) {
124 if (sscanf(pattern + (i * 2), "%2x", &hex_buf) < 0) {
125 fprintf(stderr, "invalid hex digit around %d\n", i * 2);
128 hex_pattern[i] = (char)hex_buf;
132 while ((n = fread(buf, 1, sizeof(buf), in)) > 0) {
133 if (n < sizeof(buf)) {
136 fprintf(stderr, "fread error\n");
141 if (is_hex_pattern) {
142 p_off = xor_data(buf, n, hex_pattern, (p_len / 2),
145 p_off = xor_data(buf, n, pattern, p_len, p_off);
148 if (!fwrite(buf, n, 1, out)) {
150 fprintf(stderr, "fwrite error\n");