xref: /rk3399_rockchip-uboot/tools/rockchip/boot_merger.c (revision 6aa65bb1ee0951865e27da81dde1de76c6d4687e)
1 /*
2  * (C) Copyright 2008-2015 Fuzhou Rockchip Electronics Co., Ltd
3  *
4  * SPDX-License-Identifier:	GPL-2.0+
5  */
6 #include "boot_merger.h"
7 #include <time.h>
8 #include <sys/stat.h>
9 #include <version.h>
10 
11 /* #define USE_P_RC4 */
12 
13 bool gDebug =
14 #ifdef DEBUG
15         true;
16 #else
17         false;
18 #endif /* DEBUG */
19 
20 #define ENTRY_ALIGN (2048)
21 options gOpts;
22 char gLegacyPath[MAX_LINE_LEN] = { 0 };
23 char gNewPath[MAX_LINE_LEN] = { 0 };
24 char gSubfix[MAX_LINE_LEN] = OUT_SUBFIX;
25 char gEat[MAX_LINE_LEN];
26 char *gConfigPath;
27 uint8_t *gBuf;
28 
29 static uint32_t g_merge_max_size = MAX_MERGE_SIZE;
30 
31 uint32_t gTable_Crc32[256] = {
32 	0x00000000, 0x04c10db7, 0x09821b6e, 0x0d4316d9, 0x130436dc, 0x17c53b6b,
33 	0x1a862db2, 0x1e472005, 0x26086db8, 0x22c9600f, 0x2f8a76d6, 0x2b4b7b61,
34 	0x350c5b64, 0x31cd56d3, 0x3c8e400a, 0x384f4dbd, 0x4c10db70, 0x48d1d6c7,
35 	0x4592c01e, 0x4153cda9, 0x5f14edac, 0x5bd5e01b, 0x5696f6c2, 0x5257fb75,
36 	0x6a18b6c8, 0x6ed9bb7f, 0x639aada6, 0x675ba011, 0x791c8014, 0x7ddd8da3,
37 	0x709e9b7a, 0x745f96cd, 0x9821b6e0, 0x9ce0bb57, 0x91a3ad8e, 0x9562a039,
38 	0x8b25803c, 0x8fe48d8b, 0x82a79b52, 0x866696e5, 0xbe29db58, 0xbae8d6ef,
39 	0xb7abc036, 0xb36acd81, 0xad2ded84, 0xa9ece033, 0xa4aff6ea, 0xa06efb5d,
40 	0xd4316d90, 0xd0f06027, 0xddb376fe, 0xd9727b49, 0xc7355b4c, 0xc3f456fb,
41 	0xceb74022, 0xca764d95, 0xf2390028, 0xf6f80d9f, 0xfbbb1b46, 0xff7a16f1,
42 	0xe13d36f4, 0xe5fc3b43, 0xe8bf2d9a, 0xec7e202d, 0x34826077, 0x30436dc0,
43 	0x3d007b19, 0x39c176ae, 0x278656ab, 0x23475b1c, 0x2e044dc5, 0x2ac54072,
44 	0x128a0dcf, 0x164b0078, 0x1b0816a1, 0x1fc91b16, 0x018e3b13, 0x054f36a4,
45 	0x080c207d, 0x0ccd2dca, 0x7892bb07, 0x7c53b6b0, 0x7110a069, 0x75d1adde,
46 	0x6b968ddb, 0x6f57806c, 0x621496b5, 0x66d59b02, 0x5e9ad6bf, 0x5a5bdb08,
47 	0x5718cdd1, 0x53d9c066, 0x4d9ee063, 0x495fedd4, 0x441cfb0d, 0x40ddf6ba,
48 	0xaca3d697, 0xa862db20, 0xa521cdf9, 0xa1e0c04e, 0xbfa7e04b, 0xbb66edfc,
49 	0xb625fb25, 0xb2e4f692, 0x8aabbb2f, 0x8e6ab698, 0x8329a041, 0x87e8adf6,
50 	0x99af8df3, 0x9d6e8044, 0x902d969d, 0x94ec9b2a, 0xe0b30de7, 0xe4720050,
51 	0xe9311689, 0xedf01b3e, 0xf3b73b3b, 0xf776368c, 0xfa352055, 0xfef42de2,
52 	0xc6bb605f, 0xc27a6de8, 0xcf397b31, 0xcbf87686, 0xd5bf5683, 0xd17e5b34,
53 	0xdc3d4ded, 0xd8fc405a, 0x6904c0ee, 0x6dc5cd59, 0x6086db80, 0x6447d637,
54 	0x7a00f632, 0x7ec1fb85, 0x7382ed5c, 0x7743e0eb, 0x4f0cad56, 0x4bcda0e1,
55 	0x468eb638, 0x424fbb8f, 0x5c089b8a, 0x58c9963d, 0x558a80e4, 0x514b8d53,
56 	0x25141b9e, 0x21d51629, 0x2c9600f0, 0x28570d47, 0x36102d42, 0x32d120f5,
57 	0x3f92362c, 0x3b533b9b, 0x031c7626, 0x07dd7b91, 0x0a9e6d48, 0x0e5f60ff,
58 	0x101840fa, 0x14d94d4d, 0x199a5b94, 0x1d5b5623, 0xf125760e, 0xf5e47bb9,
59 	0xf8a76d60, 0xfc6660d7, 0xe22140d2, 0xe6e04d65, 0xeba35bbc, 0xef62560b,
60 	0xd72d1bb6, 0xd3ec1601, 0xdeaf00d8, 0xda6e0d6f, 0xc4292d6a, 0xc0e820dd,
61 	0xcdab3604, 0xc96a3bb3, 0xbd35ad7e, 0xb9f4a0c9, 0xb4b7b610, 0xb076bba7,
62 	0xae319ba2, 0xaaf09615, 0xa7b380cc, 0xa3728d7b, 0x9b3dc0c6, 0x9ffccd71,
63 	0x92bfdba8, 0x967ed61f, 0x8839f61a, 0x8cf8fbad, 0x81bbed74, 0x857ae0c3,
64 	0x5d86a099, 0x5947ad2e, 0x5404bbf7, 0x50c5b640, 0x4e829645, 0x4a439bf2,
65 	0x47008d2b, 0x43c1809c, 0x7b8ecd21, 0x7f4fc096, 0x720cd64f, 0x76cddbf8,
66 	0x688afbfd, 0x6c4bf64a, 0x6108e093, 0x65c9ed24, 0x11967be9, 0x1557765e,
67 	0x18146087, 0x1cd56d30, 0x02924d35, 0x06534082, 0x0b10565b, 0x0fd15bec,
68 	0x379e1651, 0x335f1be6, 0x3e1c0d3f, 0x3add0088, 0x249a208d, 0x205b2d3a,
69 	0x2d183be3, 0x29d93654, 0xc5a71679, 0xc1661bce, 0xcc250d17, 0xc8e400a0,
70 	0xd6a320a5, 0xd2622d12, 0xdf213bcb, 0xdbe0367c, 0xe3af7bc1, 0xe76e7676,
71 	0xea2d60af, 0xeeec6d18, 0xf0ab4d1d, 0xf46a40aa, 0xf9295673, 0xfde85bc4,
72 	0x89b7cd09, 0x8d76c0be, 0x8035d667, 0x84f4dbd0, 0x9ab3fbd5, 0x9e72f662,
73 	0x9331e0bb, 0x97f0ed0c, 0xafbfa0b1, 0xab7ead06, 0xa63dbbdf, 0xa2fcb668,
74 	0xbcbb966d, 0xb87a9bda, 0xb5398d03, 0xb1f880b4,
75 };
76 
77 uint32_t CRC_32(uint8_t *pData, uint32_t ulSize)
78 {
79 	uint32_t i;
80 	uint32_t nAccum = 0;
81 	for (i = 0; i < ulSize; i++) {
82 		nAccum = (nAccum << 8) ^ gTable_Crc32[(nAccum >> 24) ^ (*pData++)];
83 	}
84 	return nAccum;
85 }
86 
87 void P_RC4(uint8_t *buf, uint32_t len)
88 {
89 	uint8_t S[256], K[256], temp;
90 	uint32_t i, j, t, x;
91 	uint8_t key[16] = { 124, 78, 3, 4, 85, 5, 9, 7, 45, 44, 123, 56, 23, 13, 23,
92 	                    17
93 	                  };
94 
95 	j = 0;
96 	for (i = 0; i < 256; i++) {
97 		S[i] = (uint8_t) i;
98 		j &= 0x0f;
99 		K[i] = key[j];
100 		j++;
101 	}
102 
103 	j = 0;
104 	for (i = 0; i < 256; i++) {
105 		j = (j + S[i] + K[i]) % 256;
106 		temp = S[i];
107 		S[i] = S[j];
108 		S[j] = temp;
109 	}
110 
111 	i = j = 0;
112 	for (x = 0; x < len; x++) {
113 		i = (i + 1) % 256;
114 		j = (j + S[i]) % 256;
115 		temp = S[i];
116 		S[i] = S[j];
117 		S[j] = temp;
118 		t = (S[i] + (S[j] % 256)) % 256;
119 		buf[x] = buf[x] ^ S[t];
120 	}
121 }
122 
123 static inline void fixPath(char *path)
124 {
125 	int i, len = strlen(path);
126 	char tmp[MAX_LINE_LEN];
127 	char *start, *end;
128 
129 	for (i = 0; i < len; i++) {
130 		if (path[i] == '\\')
131 			path[i] = '/';
132 		else if (path[i] == '\r' || path[i] == '\n')
133 			path[i] = '\0';
134 	}
135 
136 	if (strlen(gLegacyPath) && strlen(gNewPath)) {
137 		start = strstr(path, gLegacyPath);
138 		if (start) {
139 			end = start + strlen(gLegacyPath);
140 			/* Backup, so tmp can be src for strcat() */
141 			strcpy(tmp, end);
142 			/* Terminate, so path can be dest for strcat() */
143 			*start = '\0';
144 			strcat(path, tmp);
145 		}
146 	}
147 }
148 
149 static bool parseChip(FILE *file)
150 {
151 	if (SCANF_EAT(file) != 0) {
152 		return false;
153 	}
154 	if (fscanf(file, OPT_NAME "=%s", gOpts.chip) != 1) {
155 		return false;
156 	}
157 	LOGD("chip:%s\n", gOpts.chip);
158 	return true;
159 }
160 
161 static bool parseVersion(FILE *file)
162 {
163 	if (SCANF_EAT(file) != 0) {
164 		return false;
165 	}
166 	if (fscanf(file, OPT_MAJOR "=%d", &gOpts.major) != 1)
167 		return false;
168 	if (SCANF_EAT(file) != 0) {
169 		return false;
170 	}
171 	if (fscanf(file, OPT_MINOR "=%d", &gOpts.minor) != 1)
172 		return false;
173 	LOGD("major:%d, minor:%d\n", gOpts.major, gOpts.minor);
174 	return true;
175 }
176 
177 static bool parse471(FILE *file)
178 {
179 	int i, index, pos;
180 	char buf[MAX_LINE_LEN];
181 
182 	if (SCANF_EAT(file) != 0) {
183 		return false;
184 	}
185 	if (fscanf(file, OPT_NUM "=%d", &gOpts.code471Num) != 1)
186 		return false;
187 	LOGD("num:%d\n", gOpts.code471Num);
188 	if (!gOpts.code471Num)
189 		return true;
190 	if (gOpts.code471Num < 0)
191 		return false;
192 	gOpts.code471Path = (line_t *)malloc(sizeof(line_t) * gOpts.code471Num);
193 	for (i = 0; i < gOpts.code471Num; i++) {
194 		if (SCANF_EAT(file) != 0) {
195 			return false;
196 		}
197 		if (fscanf(file, OPT_PATH "%d=%[^\r^\n]", &index, buf) != 2)
198 			return false;
199 		index--;
200 		fixPath(buf);
201 		strcpy((char *)gOpts.code471Path[index], buf);
202 		LOGD("path%i:%s\n", index, gOpts.code471Path[index]);
203 	}
204 	pos = ftell(file);
205 	if (SCANF_EAT(file) != 0) {
206 		return false;
207 	}
208 	if (fscanf(file, OPT_SLEEP "=%d", &gOpts.code471Sleep) != 1)
209 		fseek(file, pos, SEEK_SET);
210 	LOGD("sleep:%d\n", gOpts.code471Sleep);
211 	return true;
212 }
213 
214 static bool parse472(FILE *file)
215 {
216 	int i, index, pos;
217 	char buf[MAX_LINE_LEN];
218 
219 	if (SCANF_EAT(file) != 0) {
220 		return false;
221 	}
222 	if (fscanf(file, OPT_NUM "=%d", &gOpts.code472Num) != 1)
223 		return false;
224 	LOGD("num:%d\n", gOpts.code472Num);
225 	if (!gOpts.code472Num)
226 		return true;
227 	if (gOpts.code472Num < 0)
228 		return false;
229 	gOpts.code472Path = (line_t *)malloc(sizeof(line_t) * gOpts.code472Num);
230 	for (i = 0; i < gOpts.code472Num; i++) {
231 		if (SCANF_EAT(file) != 0) {
232 			return false;
233 		}
234 		if (fscanf(file, OPT_PATH "%d=%[^\r^\n]", &index, buf) != 2)
235 			return false;
236 		fixPath(buf);
237 		index--;
238 		strcpy((char *)gOpts.code472Path[index], buf);
239 		LOGD("path%i:%s\n", index, gOpts.code472Path[index]);
240 	}
241 	pos = ftell(file);
242 	if (SCANF_EAT(file) != 0) {
243 		return false;
244 	}
245 	if (fscanf(file, OPT_SLEEP "=%d", &gOpts.code472Sleep) != 1)
246 		fseek(file, pos, SEEK_SET);
247 	LOGD("sleep:%d\n", gOpts.code472Sleep);
248 	return true;
249 }
250 
251 static bool parseLoader(FILE *file)
252 {
253 	int i, j, index, pos;
254 	char buf[MAX_LINE_LEN];
255 	char buf2[MAX_LINE_LEN];
256 
257 	if (SCANF_EAT(file) != 0) {
258 		return false;
259 	}
260 	pos = ftell(file);
261 	if (fscanf(file, OPT_NUM "=%d", &gOpts.loaderNum) != 1) {
262 		fseek(file, pos, SEEK_SET);
263 		if (fscanf(file, OPT_LOADER_NUM "=%d", &gOpts.loaderNum) != 1) {
264 			return false;
265 		}
266 	}
267 	LOGD("num:%d\n", gOpts.loaderNum);
268 	if (!gOpts.loaderNum)
269 		return false;
270 	if (gOpts.loaderNum < 0)
271 		return false;
272 	gOpts.loader = (name_entry *)malloc(sizeof(name_entry) * gOpts.loaderNum);
273 	for (i = 0; i < gOpts.loaderNum; i++) {
274 		if (SCANF_EAT(file) != 0) {
275 			return false;
276 		}
277 		if (fscanf(file, OPT_LOADER_NAME "%d=%s", &index, buf) != 2)
278 			return false;
279 		index--;
280 		strcpy(gOpts.loader[index].name, buf);
281 		LOGD("name%d:%s\n", index, gOpts.loader[index].name);
282 	}
283 	for (i = 0; i < gOpts.loaderNum; i++) {
284 		if (SCANF_EAT(file) != 0) {
285 			return false;
286 		}
287 		if (fscanf(file, "%[^=]=%[^\r^\n]", buf, buf2) != 2)
288 			return false;
289 		for (j = 0; j < gOpts.loaderNum; j++) {
290 			if (!strcmp(gOpts.loader[j].name, buf)) {
291 				fixPath(buf2);
292 				strcpy(gOpts.loader[j].path, buf2);
293 				LOGD("%s=%s\n", gOpts.loader[j].name, gOpts.loader[j].path);
294 				break;
295 			}
296 		}
297 		if (j >= gOpts.loaderNum) {
298 			return false;
299 		}
300 	}
301 	return true;
302 }
303 
304 static bool parseOut(FILE *file)
305 {
306 	if (SCANF_EAT(file) != 0) {
307 		return false;
308 	}
309 	if (fscanf(file, OPT_OUT_PATH "=%[^\r^\n]", gOpts.outPath) != 1)
310 		return false;
311 	fixPath(gOpts.outPath);
312 	printf("out:%s\n", gOpts.outPath);
313 	return true;
314 }
315 
316 void printOpts(FILE *out)
317 {
318 	uint32_t i;
319 	fprintf(out, SEC_CHIP "\n" OPT_NAME "=%s\n", gOpts.chip);
320 	fprintf(out, SEC_VERSION "\n" OPT_MAJOR "=%d\n" OPT_MINOR "=%d\n",
321 	        gOpts.major, gOpts.minor);
322 
323 	fprintf(out, SEC_471 "\n" OPT_NUM "=%d\n", gOpts.code471Num);
324 	for (i = 0; i < gOpts.code471Num; i++) {
325 		fprintf(out, OPT_PATH "%d=%s\n", i + 1, gOpts.code471Path[i]);
326 	}
327 	if (gOpts.code471Sleep > 0)
328 		fprintf(out, OPT_SLEEP "=%d\n", gOpts.code471Sleep);
329 
330 	fprintf(out, SEC_472 "\n" OPT_NUM "=%d\n", gOpts.code472Num);
331 	for (i = 0; i < gOpts.code472Num; i++) {
332 		fprintf(out, OPT_PATH "%d=%s\n", i + 1, gOpts.code472Path[i]);
333 	}
334 	if (gOpts.code472Sleep > 0)
335 		fprintf(out, OPT_SLEEP "=%d\n", gOpts.code472Sleep);
336 
337 	fprintf(out, SEC_LOADER "\n" OPT_NUM "=%d\n", gOpts.loaderNum);
338 	for (i = 0; i < gOpts.loaderNum; i++) {
339 		fprintf(out, OPT_LOADER_NAME "%d=%s\n", i + 1, gOpts.loader[i].name);
340 	}
341 	for (i = 0; i < gOpts.loaderNum; i++) {
342 		fprintf(out, "%s=%s\n", gOpts.loader[i].name, gOpts.loader[i].path);
343 	}
344 
345 	fprintf(out, SEC_OUT "\n" OPT_OUT_PATH "=%s\n", gOpts.outPath);
346 }
347 
348 static bool parseOpts_from_file(void)
349 {
350 	bool ret = false;
351 	bool chipOk = false;
352 	bool versionOk = false;
353 	bool code471Ok = true;
354 	bool code472Ok = true;
355 	bool loaderOk = false;
356 	bool outOk = false;
357 	char buf[MAX_LINE_LEN];
358 
359 	char *configPath = (gConfigPath == NULL) ? DEF_CONFIG_FILE : gConfigPath;
360 	FILE *file;
361 	file = fopen(configPath, "r");
362 	if (!file) {
363 		fprintf(stderr, "config(%s) not found!\n", configPath);
364 		if (configPath == (char *)DEF_CONFIG_FILE) {
365 			file = fopen(DEF_CONFIG_FILE, "w");
366 			if (file) {
367 				fprintf(stderr, "create defconfig\n");
368 				printOpts(file);
369 			}
370 		}
371 		goto end;
372 	}
373 
374 	LOGD("start parse\n");
375 
376 	if (SCANF_EAT(file) != 0) {
377 		goto end;
378 	}
379 	while (fscanf(file, "%s", buf) == 1) {
380 		if (!strcmp(buf, SEC_CHIP)) {
381 			chipOk = parseChip(file);
382 			if (!chipOk) {
383 				LOGE("parseChip failed!\n");
384 				goto end;
385 			}
386 		} else if (!strcmp(buf, SEC_VERSION)) {
387 			versionOk = parseVersion(file);
388 			if (!versionOk) {
389 				LOGE("parseVersion failed!\n");
390 				goto end;
391 			}
392 		} else if (!strcmp(buf, SEC_471)) {
393 			code471Ok = parse471(file);
394 			if (!code471Ok) {
395 				LOGE("parse471 failed!\n");
396 				goto end;
397 			}
398 		} else if (!strcmp(buf, SEC_472)) {
399 			code472Ok = parse472(file);
400 			if (!code472Ok) {
401 				LOGE("parse472 failed!\n");
402 				goto end;
403 			}
404 		} else if (!strcmp(buf, SEC_LOADER)) {
405 			loaderOk = parseLoader(file);
406 			if (!loaderOk) {
407 				LOGE("parseLoader failed!\n");
408 				goto end;
409 			}
410 		} else if (!strcmp(buf, SEC_OUT)) {
411 			outOk = parseOut(file);
412 			if (!outOk) {
413 				LOGE("parseOut failed!\n");
414 				goto end;
415 			}
416 		} else if (buf[0] == '#') {
417 			continue;
418 		} else {
419 			LOGE("unknown sec: %s!\n", buf);
420 			goto end;
421 		}
422 		if (SCANF_EAT(file) != 0) {
423 			goto end;
424 		}
425 	}
426 
427 	if (chipOk && versionOk && code471Ok && code472Ok && loaderOk && outOk)
428 		ret = true;
429 end:
430 	if (file)
431 		fclose(file);
432 	return ret;
433 }
434 
435 static bool parseOpts_from_cmdline(int argc, char **argv)
436 {
437 	int i;
438 	int tag = 0;
439 	int v0, v1, v2, v3;
440 
441 	for (i = 2; i < argc; i++) {
442 		if (!strcmp(OPT_471, argv[i])) {
443 			i++;
444 			snprintf(gOpts.code471Path[0], sizeof(gOpts.code471Path[0]), "%s",
445 			         argv[i]);
446 			tag |= 1;
447 		} else if (!strcmp(OPT_472, argv[i])) {
448 			i++;
449 			snprintf(gOpts.code472Path[0], sizeof(gOpts.code472Path[0]), "%s",
450 			         argv[i]);
451 			tag |= 2;
452 		} else if (!strcmp(OPT_DATA, argv[i])) {
453 			i++;
454 			snprintf(gOpts.loader[0].path, sizeof(gOpts.loader[0].path), "%s",
455 			         argv[i]);
456 			tag |= 4;
457 		} else if (!strcmp(OPT_BOOT, argv[i])) {
458 			i++;
459 			snprintf(gOpts.loader[1].path, sizeof(gOpts.loader[1].path), "%s",
460 			         argv[i]);
461 			tag |= 8;
462 		} else if (!strcmp(OPT_OUT, argv[i])) {
463 			i++;
464 			snprintf(gOpts.outPath, sizeof(gOpts.outPath), "%s", argv[i]);
465 			tag |= 0x10;
466 		} else if (!strcmp(OPT_CHIP, argv[i])) {
467 			i++;
468 			snprintf(gOpts.chip, sizeof(gOpts.chip), "%s", argv[i]);
469 			tag |= 0x20;
470 		} else if (!strcmp(OPT_VERSION, argv[i])) {
471 		}
472 	}
473 
474 	sscanf(gOpts.loader[0].path, "%*[^v]v%d.%d.bin", &v0, &v1);
475 	sscanf(gOpts.loader[1].path, "%*[^v]v%d.%d.bin", &v2, &v3);
476 	gOpts.major = v2;
477 	gOpts.minor = v3;
478 	snprintf(gOpts.outPath, sizeof(gOpts.outPath),
479 	         "%s_loader_v%d.%02d.%d%02d.bin", gOpts.chip, v0, v1, v2, v3);
480 	return ((tag & 0x0f) == 0x0f) ? true : false;
481 }
482 
483 bool initOpts(int argc, char **argv)
484 {
485 	bool ret;
486 
487 	/* set default opts */
488 	gOpts.major = DEF_MAJOR;
489 	gOpts.minor = DEF_MINOR;
490 	strcpy(gOpts.chip, DEF_CHIP);
491 	gOpts.code471Sleep = DEF_CODE471_SLEEP;
492 	gOpts.code472Sleep = DEF_CODE472_SLEEP;
493 	gOpts.code471Num = DEF_CODE471_NUM;
494 	gOpts.code471Path = (line_t *)malloc(sizeof(line_t) * gOpts.code471Num);
495 	strcpy((char *)gOpts.code471Path[0], DEF_CODE471_PATH);
496 	gOpts.code472Num = DEF_CODE472_NUM;
497 	gOpts.code472Path = (line_t *)malloc(sizeof(line_t) * gOpts.code472Num);
498 	strcpy((char *)gOpts.code472Path[0], DEF_CODE472_PATH);
499 	gOpts.loaderNum = DEF_LOADER_NUM;
500 	gOpts.loader = (name_entry *)malloc(sizeof(name_entry) * gOpts.loaderNum);
501 	strcpy(gOpts.loader[0].name, DEF_LOADER0);
502 	strcpy(gOpts.loader[0].path, DEF_LOADER0_PATH);
503 	strcpy(gOpts.loader[1].name, DEF_LOADER1);
504 	strcpy(gOpts.loader[1].path, DEF_LOADER1_PATH);
505 	strcpy(gOpts.outPath, DEF_OUT_PATH);
506 
507 	if (argc > 10)
508 		ret = parseOpts_from_cmdline(argc, argv);
509 	else
510 		ret = parseOpts_from_file();
511 
512 	return ret;
513 }
514 
515 /************merge code****************/
516 
517 static inline uint32_t getBCD(unsigned short value)
518 {
519 	uint8_t tmp[2] = { 0 };
520 	int i;
521 	uint32_t ret;
522 	if (value > 0xFFFF) {
523 		return 0;
524 	}
525 	for (i = 0; i < 2; i++) {
526 		tmp[i] = (((value / 10) % 10) << 4) | (value % 10);
527 		value /= 100;
528 	}
529 	ret = ((uint16_t)(tmp[1] << 8)) | tmp[0];
530 
531 	LOGD("ret:%x\n", ret);
532 	return ret & 0xFF;
533 }
534 
535 static inline void str2wide(const char *str, uint16_t *wide, int len)
536 {
537 	int i;
538 	for (i = 0; i < len; i++) {
539 		wide[i] = (uint16_t) str[i];
540 	}
541 	wide[len] = 0;
542 }
543 
544 static inline void getName(char *path, uint16_t *dst)
545 {
546 	char *end;
547 	char *start;
548 	int len;
549 	if (!path || !dst)
550 		return;
551 	start = strrchr(path, '/');
552 	if (!start)
553 		start = path;
554 	else
555 		start++;
556 	end = strrchr(path, '.');
557 	if (!end)
558 		end = path + strlen(path);
559 	len = end - start;
560 	if (len >= MAX_NAME_LEN)
561 		len = MAX_NAME_LEN - 1;
562 	str2wide(start, dst, len);
563 
564 	if (gDebug) {
565 		char name[MAX_NAME_LEN];
566 		memset(name, 0, sizeof(name));
567 		memcpy(name, start, len);
568 		LOGD("path:%s, name:%s\n", path, name);
569 	}
570 }
571 
572 static inline bool getFileSize(const char *path, uint32_t *size)
573 {
574 	struct stat st;
575 	if (stat(path, &st) < 0)
576 		return false;
577 	*size = st.st_size;
578 	LOGD("path:%s, size:%d\n", path, *size);
579 	return true;
580 }
581 
582 static inline rk_time getTime(void)
583 {
584 	rk_time rkTime;
585 
586 	struct tm *tm;
587 	time_t tt = time(NULL);
588 	tm = localtime(&tt);
589 	rkTime.year = tm->tm_year + 1900;
590 	rkTime.month = tm->tm_mon + 1;
591 	rkTime.day = tm->tm_mday;
592 	rkTime.hour = tm->tm_hour;
593 	rkTime.minute = tm->tm_min;
594 	rkTime.second = tm->tm_sec;
595 	LOGD("%d-%d-%d %02d:%02d:%02d\n", rkTime.year, rkTime.month, rkTime.day,
596 	     rkTime.hour, rkTime.minute, rkTime.second);
597 	return rkTime;
598 }
599 
600 static bool writeFile(FILE *outFile, const char *path, bool fix)
601 {
602 	bool ret = false;
603 	uint32_t size = 0, fixSize = 0;
604 	uint8_t *buf;
605 
606 	FILE *inFile = fopen(path, "rb");
607 	if (!inFile)
608 		goto end;
609 
610 	if (!getFileSize(path, &size))
611 		goto end;
612 	if (fix) {
613 		fixSize = ((size - 1) / SMALL_PACKET + 1) * SMALL_PACKET;
614 		uint32_t tmp = fixSize % ENTRY_ALIGN;
615 		tmp = tmp ? (ENTRY_ALIGN - tmp) : 0;
616 		fixSize += tmp;
617 		memset(gBuf, 0, fixSize);
618 	} else {
619 		memset(gBuf, 0, size + ENTRY_ALIGN);
620 	}
621 	if (!fread(gBuf, size, 1, inFile))
622 		goto end;
623 
624 	if (fix) {
625 
626 		buf = gBuf;
627 		size = fixSize;
628 		while (1) {
629 			P_RC4(buf, fixSize < SMALL_PACKET ? fixSize : SMALL_PACKET);
630 			buf += SMALL_PACKET;
631 			if (fixSize <= SMALL_PACKET)
632 				break;
633 			fixSize -= SMALL_PACKET;
634 		}
635 	} else {
636 		uint32_t tmp = size % ENTRY_ALIGN;
637 		tmp = tmp ? (ENTRY_ALIGN - tmp) : 0;
638 		size += tmp;
639 		P_RC4(gBuf, size);
640 	}
641 
642 	if (!fwrite(gBuf, size, 1, outFile))
643 		goto end;
644 	ret = true;
645 end:
646 	if (inFile)
647 		fclose(inFile);
648 	if (!ret)
649 		LOGE("write entry(%s) failed\n", path);
650 	return ret;
651 }
652 
653 static bool saveEntry(FILE *outFile, char *path, rk_entry_type type,
654                       uint16_t delay, uint32_t *offset, char *fixName,
655                       bool fix)
656 {
657 	LOGD("write:%s\n", path);
658 	uint32_t size;
659 	rk_boot_entry entry;
660 	memset(&entry, 0, sizeof(rk_boot_entry));
661 
662 	LOGD("write:%s\n", path);
663 
664 	getName(fixName ? fixName : path, entry.name);
665 	entry.size = sizeof(rk_boot_entry);
666 	entry.type = type;
667 	entry.dataOffset = *offset;
668 	if (!getFileSize(path, &size)) {
669 		LOGE("save entry(%s) failed:\n\tcannot get file size.\n", path);
670 		return false;
671 	}
672 	if (fix)
673 		size = ((size - 1) / SMALL_PACKET + 1) * SMALL_PACKET;
674 	uint32_t tmp = size % ENTRY_ALIGN;
675 	size += tmp ? (ENTRY_ALIGN - tmp) : 0;
676 	LOGD("align size:%d\n", size);
677 	entry.dataSize = size;
678 	entry.dataDelay = delay;
679 	*offset += size;
680 	fwrite(&entry, sizeof(rk_boot_entry), 1, outFile);
681 	return true;
682 }
683 
684 static inline uint32_t convertChipType(const char *chip)
685 {
686 	char buffer[5];
687 	memset(buffer, 0, sizeof(buffer));
688 	snprintf(buffer, sizeof(buffer), "%s", chip);
689 	return buffer[0] << 24 | buffer[1] << 16 | buffer[2] << 8 | buffer[3];
690 }
691 
692 static inline uint32_t getChipType(const char *chip)
693 {
694 	LOGD("chip:%s\n", chip);
695 	int chipType = RKNONE_DEVICE;
696 	if (!chip) {
697 		goto end;
698 	}
699 	if (!strcmp(chip, CHIP_RK28)) {
700 		chipType = RK28_DEVICE;
701 	} else if (!strcmp(chip, CHIP_RK28)) {
702 		chipType = RK28_DEVICE;
703 	} else if (!strcmp(chip, CHIP_RK281X)) {
704 		chipType = RK281X_DEVICE;
705 	} else if (!strcmp(chip, CHIP_RKPANDA)) {
706 		chipType = RKPANDA_DEVICE;
707 	} else if (!strcmp(chip, CHIP_RK27)) {
708 		chipType = RK27_DEVICE;
709 	} else if (!strcmp(chip, CHIP_RKNANO)) {
710 		chipType = RKNANO_DEVICE;
711 	} else if (!strcmp(chip, CHIP_RKSMART)) {
712 		chipType = RKSMART_DEVICE;
713 	} else if (!strcmp(chip, CHIP_RKCROWN)) {
714 		chipType = RKCROWN_DEVICE;
715 	} else if (!strcmp(chip, CHIP_RKCAYMAN)) {
716 		chipType = RKCAYMAN_DEVICE;
717 	} else if (!strcmp(chip, CHIP_RK29)) {
718 		chipType = RK29_DEVICE;
719 	} else if (!strcmp(chip, CHIP_RK292X)) {
720 		chipType = RK292X_DEVICE;
721 	} else if (!strcmp(chip, CHIP_RK30)) {
722 		chipType = RK30_DEVICE;
723 	} else if (!strcmp(chip, CHIP_RK30B)) {
724 		chipType = RK30B_DEVICE;
725 	} else if (!strcmp(chip, CHIP_RK31)) {
726 		chipType = RK31_DEVICE;
727 	} else if (!strcmp(chip, CHIP_RK32)) {
728 		chipType = RK32_DEVICE;
729 	} else {
730 		chipType = convertChipType(chip + 2);
731 	}
732 
733 end:
734 	LOGD("type:0x%x\n", chipType);
735 	if (chipType == RKNONE_DEVICE) {
736 		LOGE("chip type not support!\n");
737 	}
738 	return chipType;
739 }
740 
741 static inline void getBoothdr(rk_boot_header *hdr)
742 {
743 	memset(hdr, 0, sizeof(rk_boot_header));
744 	hdr->tag = TAG;
745 	hdr->size = sizeof(rk_boot_header);
746 	hdr->version = (getBCD(gOpts.major) << 8) | getBCD(gOpts.minor);
747 	hdr->mergerVersion = MERGER_VERSION;
748 	hdr->releaseTime = getTime();
749 	hdr->chipType = getChipType(gOpts.chip);
750 
751 	hdr->code471Num = gOpts.code471Num;
752 	hdr->code471Offset = sizeof(rk_boot_header);
753 	hdr->code471Size = sizeof(rk_boot_entry);
754 
755 	hdr->code472Num = gOpts.code472Num;
756 	hdr->code472Offset = hdr->code471Offset + gOpts.code471Num * hdr->code471Size;
757 	hdr->code472Size = sizeof(rk_boot_entry);
758 
759 	hdr->loaderNum = gOpts.loaderNum;
760 	hdr->loaderOffset = hdr->code472Offset + gOpts.code472Num * hdr->code472Size;
761 	hdr->loaderSize = sizeof(rk_boot_entry);
762 #ifndef USE_P_RC4
763 	hdr->rc4Flag = 1;
764 #endif
765 }
766 
767 static inline uint32_t getCrc(const char *path)
768 {
769 	uint32_t size = 0;
770 	uint32_t crc = 0;
771 	FILE *file = fopen(path, "rb");
772 	getFileSize(path, &size);
773 	if (!file)
774 		goto end;
775 	if (!fread(gBuf, size, 1, file))
776 		goto end;
777 	crc = CRC_32(gBuf, size);
778 	LOGD("crc:0x%08x\n", crc);
779 end:
780 	if (file)
781 		fclose(file);
782 	return crc;
783 }
784 
785 static bool mergeBoot(int argc, char **argv)
786 {
787 	uint32_t dataOffset;
788 	bool ret = false;
789 	int i;
790 	FILE *outFile;
791 	uint32_t crc;
792 	rk_boot_header hdr;
793 
794 	if (!initOpts(argc, argv))
795 		return false;
796 	{
797 		char *subfix = strstr(gOpts.outPath, OUT_SUBFIX);
798 		char version[MAX_LINE_LEN];
799 		snprintf(version, sizeof(version), "%s", gSubfix);
800 		if (subfix && !strcmp(subfix, OUT_SUBFIX)) {
801 			subfix[0] = '\0';
802 		}
803 		strcat(gOpts.outPath, version);
804 		printf("fix opt:%s\n", gOpts.outPath);
805 	}
806 
807 	if (gDebug) {
808 		printf("---------------\nUSING CONFIG:\n");
809 		printOpts(stdout);
810 		printf("---------------\n\n");
811 	}
812 
813 	outFile = fopen(gOpts.outPath, "wb+");
814 	if (!outFile) {
815 		LOGE("open out file(%s) failed\n", gOpts.outPath);
816 		goto end;
817 	}
818 
819 	getBoothdr(&hdr);
820 	LOGD("write hdr\n");
821 	fwrite(&hdr, 1, sizeof(rk_boot_header), outFile);
822 
823 	dataOffset = sizeof(rk_boot_header) +
824 	             (gOpts.code471Num + gOpts.code472Num + gOpts.loaderNum) *
825 	             sizeof(rk_boot_entry);
826 
827 	LOGD("write code 471 entry\n");
828 	for (i = 0; i < gOpts.code471Num; i++) {
829 		if (!saveEntry(outFile, (char *)gOpts.code471Path[i], ENTRY_471,
830 		               gOpts.code471Sleep, &dataOffset, NULL, false))
831 			goto end;
832 	}
833 	LOGD("write code 472 entry\n");
834 	for (i = 0; i < gOpts.code472Num; i++) {
835 		if (!saveEntry(outFile, (char *)gOpts.code472Path[i], ENTRY_472,
836 		               gOpts.code472Sleep, &dataOffset, NULL, false))
837 			goto end;
838 	}
839 	LOGD("write loader entry\n");
840 	for (i = 0; i < gOpts.loaderNum; i++) {
841 		if (!saveEntry(outFile, gOpts.loader[i].path, ENTRY_LOADER, 0, &dataOffset,
842 		               gOpts.loader[i].name, true))
843 			goto end;
844 	}
845 
846 	LOGD("write code 471\n");
847 	for (i = 0; i < gOpts.code471Num; i++) {
848 		if (!writeFile(outFile, (char *)gOpts.code471Path[i], false))
849 			goto end;
850 	}
851 	LOGD("write code 472\n");
852 	for (i = 0; i < gOpts.code472Num; i++) {
853 		if (!writeFile(outFile, (char *)gOpts.code472Path[i], false))
854 			goto end;
855 	}
856 	LOGD("write loader\n");
857 	for (i = 0; i < gOpts.loaderNum; i++) {
858 		if (!writeFile(outFile, gOpts.loader[i].path, true))
859 			goto end;
860 	}
861 	fflush(outFile);
862 
863 	LOGD("write crc\n");
864 	crc = getCrc(gOpts.outPath);
865 	if (!fwrite(&crc, sizeof(crc), 1, outFile))
866 		goto end;
867 
868 	ret = true;
869 end:
870 	if (outFile)
871 		fclose(outFile);
872 	return ret;
873 }
874 
875 /************merge code end************/
876 /************unpack code***************/
877 
878 static inline void wide2str(const uint16_t *wide, char *str, int len)
879 {
880 	int i;
881 	for (i = 0; i < len; i++) {
882 		str[i] = (char)(wide[i] & 0xFF);
883 	}
884 	str[len] = 0;
885 }
886 
887 static bool unpackEntry(rk_boot_entry *entry, const char *name, FILE *inFile)
888 {
889 	bool ret = false;
890 	int size, i;
891 	FILE *outFile = fopen(name, "wb+");
892 	if (!outFile)
893 		goto end;
894 	printf("unpack entry(%s)\n", name);
895 	fseek(inFile, entry->dataOffset, SEEK_SET);
896 	size = entry->dataSize;
897 	if (!fread(gBuf, size, 1, inFile))
898 		goto end;
899 	if (entry->type == ENTRY_LOADER) {
900 		for (i = 0; i < size / SMALL_PACKET; i++)
901 			P_RC4(gBuf + i * SMALL_PACKET, SMALL_PACKET);
902 		if (size % SMALL_PACKET) {
903 			P_RC4(gBuf + i * SMALL_PACKET, size - SMALL_PACKET * 512);
904 		}
905 	} else {
906 		P_RC4(gBuf, size);
907 	}
908 	if (!fwrite(gBuf, size, 1, outFile))
909 		goto end;
910 	ret = true;
911 end:
912 	if (outFile)
913 		fclose(outFile);
914 	return ret;
915 }
916 
917 static bool unpackBoot(char *path)
918 {
919 	bool ret = false;
920 	FILE *inFile = fopen(path, "rb");
921 	int entryNum, i;
922 	char name[MAX_NAME_LEN];
923 	rk_boot_entry *entrys;
924 	if (!inFile) {
925 		fprintf(stderr, "loader(%s) not found\n", path);
926 		goto end;
927 	}
928 
929 	rk_boot_header hdr;
930 	if (!fread(&hdr, sizeof(rk_boot_header), 1, inFile)) {
931 		fprintf(stderr, "read header failed\n");
932 		goto end;
933 	}
934 
935 	entryNum = hdr.code471Num + hdr.code472Num + hdr.loaderNum;
936 	entrys = (rk_boot_entry *)malloc(sizeof(rk_boot_entry) * entryNum);
937 	if (!fread(entrys, sizeof(rk_boot_entry) * entryNum, 1, inFile)) {
938 		fprintf(stderr, "read data failed\n");
939 		goto end;
940 	}
941 
942 	LOGD("entry num:%d\n", entryNum);
943 	for (i = 0; i < entryNum; i++) {
944 		wide2str(entrys[i].name, name, MAX_NAME_LEN);
945 
946 		LOGD("entry:t=%d, name=%s, off=%d, size=%d\n", entrys[i].type, name,
947 		     entrys[i].dataOffset, entrys[i].dataSize);
948 		if (!unpackEntry(entrys + i, name, inFile)) {
949 			fprintf(stderr, "unpack entry(%s) failed\n", name);
950 			goto end;
951 		}
952 	}
953 
954 	ret = true;
955 end:
956 	if (inFile)
957 		fclose(inFile);
958 	return ret;
959 }
960 
961 /************unpack code end***********/
962 
963 static void printHelp(void)
964 {
965 	printf("Usage1: boot_merger [options]... FILE\n");
966 	printf("Merge or unpack Rockchip's loader (Default action is to merge.)\n");
967 	printf("Options:\n");
968 	printf("\t" OPT_MERGE "\t\t\tMerge loader with specified config.\n");
969 	printf("\t" OPT_UNPACK "\t\tUnpack specified loader to current dir.\n");
970 	printf("\t" OPT_VERBOSE "\t\tDisplay more runtime informations.\n");
971 	printf("\t" OPT_HELP "\t\t\tDisplay this information.\n");
972 	printf("\t" OPT_VERSION "\t\tDisplay version information.\n");
973 	printf("\t" OPT_SUBFIX "\t\tSpec subfix.\n");
974 	printf("\t" OPT_REPLACE "\t\tReplace some part of binary path.\n");
975 	printf("\t" OPT_SIZE
976 	       "\t\tImage size.\"--size [image KB size]\", must be 512KB aligned\n");
977 	printf("Usage2: boot_merger [options] [parameter]\n");
978 	printf("All below five option are must in this mode!\n");
979 	printf("\t" OPT_CHIP "\t\tChip type, used for check with usbplug.\n");
980 	printf("\t" OPT_471 "\t\t471 for download, ddr.bin.\n");
981 	printf("\t" OPT_472 "\t\t472 for download, usbplug.bin.\n");
982 	printf("\t" OPT_DATA "\t\tloader0 for flash, ddr.bin.\n");
983 	printf("\t" OPT_BOOT "\t\tloader1 for flash, miniloader.bin.\n");
984 	printf("\n./tools/boot_merger --pack --verbose -c RK322A -1 "
985 	       "rkbin/rk322x_ddr_300MHz_v1.04.bin -2 "
986 	       "rkbin/rk32/rk322x_usbplug_v2.32.bin -d "
987 	       "rkbin/rk32/rk322x_ddr_300MHz_v1.04.bin -b "
988 	       "rkbin/rk32/rk322x_miniloader_v2.32.bin\n");
989 }
990 
991 int main(int argc, char **argv)
992 {
993 
994 	int i;
995 	bool merge = true;
996 	char *optPath = NULL;
997 
998 	for (i = 1; i < argc; i++) {
999 		if (!strcmp(OPT_VERBOSE, argv[i])) {
1000 			gDebug = true;
1001 			printf("enable debug\n");
1002 		} else if (!strcmp(OPT_HELP, argv[i])) {
1003 			printHelp();
1004 			return 0;
1005 		} else if (!strcmp(OPT_VERSION, argv[i])) {
1006 			printf("boot_merger (cjf@rock-chips.com)\t" VERSION "\n");
1007 			return 0;
1008 		} else if (!strcmp(OPT_MERGE, argv[i])) {
1009 			merge = true;
1010 		} else if (!strcmp(OPT_UNPACK, argv[i])) {
1011 			merge = false;
1012 		} else if (!strcmp(OPT_SUBFIX, argv[i])) {
1013 			i++;
1014 			snprintf(gSubfix, sizeof(gSubfix), "%s", argv[i]);
1015 		} else if (!strcmp(OPT_REPLACE, argv[i])) {
1016 			i++;
1017 			snprintf(gLegacyPath, sizeof(gLegacyPath), "%s", argv[i]);
1018 			i++;
1019 			snprintf(gNewPath, sizeof(gNewPath), "%s", argv[i]);
1020 		} else if (!strcmp(OPT_SIZE, argv[i])) {
1021 			g_merge_max_size = strtoul(argv[++i], NULL, 10);
1022 			if (g_merge_max_size % 512) {
1023 				printHelp();
1024 				return -1;
1025 			}
1026 			g_merge_max_size *= 1024; /* bytes */
1027 		} else {
1028 			optPath = argv[i];
1029 			break;
1030 		}
1031 	}
1032 	if (!merge && !optPath) {
1033 		fprintf(stderr, "need set out path to unpack!\n");
1034 		printHelp();
1035 		return -1;
1036 	}
1037 
1038 	gBuf = calloc(g_merge_max_size, 1);
1039 	if (!gBuf) {
1040 		LOGE("Merge image: calloc buffer error.\n");
1041 		return -1;
1042 	}
1043 
1044 	if (merge) {
1045 		LOGD("do_merge\n");
1046 		gConfigPath = optPath;
1047 		if (!mergeBoot(argc, argv)) {
1048 			fprintf(stderr, "merge failed!\n");
1049 			return -1;
1050 		}
1051 		printf("merge success(%s)\n", gOpts.outPath);
1052 	} else {
1053 		LOGD("do_unpack\n");
1054 		if (!unpackBoot(optPath)) {
1055 			fprintf(stderr, "unpack failed!\n");
1056 			return -1;
1057 		}
1058 		printf("unpack success\n");
1059 	}
1060 	return 0;
1061 }
1062