xref: /rk3399_rockchip-uboot/tools/rockchip/boot_merger.c (revision 45c2a034cd1ef3d6670aa94d37bb0ed75ede2b20)
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, gNewPath);
145 			strcat(path, tmp);
146 		}
147 	}
148 }
149 
150 static bool parseChip(FILE *file)
151 {
152 	if (SCANF_EAT(file) != 0) {
153 		return false;
154 	}
155 	if (fscanf(file, OPT_NAME "=%s", gOpts.chip) != 1) {
156 		return false;
157 	}
158 	LOGD("chip:%s\n", gOpts.chip);
159 	return true;
160 }
161 
162 static bool parseVersion(FILE *file)
163 {
164 	if (SCANF_EAT(file) != 0) {
165 		return false;
166 	}
167 	if (fscanf(file, OPT_MAJOR "=%d", &gOpts.major) != 1)
168 		return false;
169 	if (SCANF_EAT(file) != 0) {
170 		return false;
171 	}
172 	if (fscanf(file, OPT_MINOR "=%d", &gOpts.minor) != 1)
173 		return false;
174 	LOGD("major:%d, minor:%d\n", gOpts.major, gOpts.minor);
175 	return true;
176 }
177 
178 static bool parse471(FILE *file)
179 {
180 	int i, index, pos;
181 	char buf[MAX_LINE_LEN];
182 
183 	if (SCANF_EAT(file) != 0) {
184 		return false;
185 	}
186 	if (fscanf(file, OPT_NUM "=%d", &gOpts.code471Num) != 1)
187 		return false;
188 	LOGD("num:%d\n", gOpts.code471Num);
189 	if (!gOpts.code471Num)
190 		return true;
191 	if (gOpts.code471Num < 0)
192 		return false;
193 	gOpts.code471Path = (line_t *)malloc(sizeof(line_t) * gOpts.code471Num);
194 	for (i = 0; i < gOpts.code471Num; i++) {
195 		if (SCANF_EAT(file) != 0) {
196 			return false;
197 		}
198 		if (fscanf(file, OPT_PATH "%d=%[^\r^\n]", &index, buf) != 2)
199 			return false;
200 		index--;
201 		fixPath(buf);
202 		strcpy((char *)gOpts.code471Path[index], buf);
203 		LOGD("path%i:%s\n", index, gOpts.code471Path[index]);
204 	}
205 	pos = ftell(file);
206 	if (SCANF_EAT(file) != 0) {
207 		return false;
208 	}
209 	if (fscanf(file, OPT_SLEEP "=%d", &gOpts.code471Sleep) != 1)
210 		fseek(file, pos, SEEK_SET);
211 	LOGD("sleep:%d\n", gOpts.code471Sleep);
212 	return true;
213 }
214 
215 static bool parse472(FILE *file)
216 {
217 	int i, index, pos;
218 	char buf[MAX_LINE_LEN];
219 
220 	if (SCANF_EAT(file) != 0) {
221 		return false;
222 	}
223 	if (fscanf(file, OPT_NUM "=%d", &gOpts.code472Num) != 1)
224 		return false;
225 	LOGD("num:%d\n", gOpts.code472Num);
226 	if (!gOpts.code472Num)
227 		return true;
228 	if (gOpts.code472Num < 0)
229 		return false;
230 	gOpts.code472Path = (line_t *)malloc(sizeof(line_t) * gOpts.code472Num);
231 	for (i = 0; i < gOpts.code472Num; i++) {
232 		if (SCANF_EAT(file) != 0) {
233 			return false;
234 		}
235 		if (fscanf(file, OPT_PATH "%d=%[^\r^\n]", &index, buf) != 2)
236 			return false;
237 		fixPath(buf);
238 		index--;
239 		strcpy((char *)gOpts.code472Path[index], buf);
240 		LOGD("path%i:%s\n", index, gOpts.code472Path[index]);
241 	}
242 	pos = ftell(file);
243 	if (SCANF_EAT(file) != 0) {
244 		return false;
245 	}
246 	if (fscanf(file, OPT_SLEEP "=%d", &gOpts.code472Sleep) != 1)
247 		fseek(file, pos, SEEK_SET);
248 	LOGD("sleep:%d\n", gOpts.code472Sleep);
249 	return true;
250 }
251 
252 static bool parseLoader(FILE *file)
253 {
254 	int i, j, index, pos;
255 	char buf[MAX_LINE_LEN];
256 	char buf2[MAX_LINE_LEN];
257 
258 	if (SCANF_EAT(file) != 0) {
259 		return false;
260 	}
261 	pos = ftell(file);
262 	if (fscanf(file, OPT_NUM "=%d", &gOpts.loaderNum) != 1) {
263 		fseek(file, pos, SEEK_SET);
264 		if (fscanf(file, OPT_LOADER_NUM "=%d", &gOpts.loaderNum) != 1) {
265 			return false;
266 		}
267 	}
268 	LOGD("num:%d\n", gOpts.loaderNum);
269 	if (!gOpts.loaderNum)
270 		return false;
271 	if (gOpts.loaderNum < 0)
272 		return false;
273 	gOpts.loader = (name_entry *)malloc(sizeof(name_entry) * gOpts.loaderNum);
274 	for (i = 0; i < gOpts.loaderNum; i++) {
275 		if (SCANF_EAT(file) != 0) {
276 			return false;
277 		}
278 		if (fscanf(file, OPT_LOADER_NAME "%d=%s", &index, buf) != 2)
279 			return false;
280 		index--;
281 		strcpy(gOpts.loader[index].name, buf);
282 		LOGD("name%d:%s\n", index, gOpts.loader[index].name);
283 	}
284 	for (i = 0; i < gOpts.loaderNum; i++) {
285 		if (SCANF_EAT(file) != 0) {
286 			return false;
287 		}
288 		if (fscanf(file, "%[^=]=%[^\r^\n]", buf, buf2) != 2)
289 			return false;
290 		for (j = 0; j < gOpts.loaderNum; j++) {
291 			if (!strcmp(gOpts.loader[j].name, buf)) {
292 				fixPath(buf2);
293 				strcpy(gOpts.loader[j].path, buf2);
294 				LOGD("%s=%s\n", gOpts.loader[j].name, gOpts.loader[j].path);
295 				break;
296 			}
297 		}
298 		if (j >= gOpts.loaderNum) {
299 			return false;
300 		}
301 	}
302 	return true;
303 }
304 
305 static bool parseOut(FILE *file)
306 {
307 	if (SCANF_EAT(file) != 0) {
308 		return false;
309 	}
310 	if (fscanf(file, OPT_OUT_PATH "=%[^\r^\n]", gOpts.outPath) != 1)
311 		return false;
312 	fixPath(gOpts.outPath);
313 	printf("out:%s\n", gOpts.outPath);
314 	return true;
315 }
316 
317 void printOpts(FILE *out)
318 {
319 	uint32_t i;
320 	fprintf(out, SEC_CHIP "\n" OPT_NAME "=%s\n", gOpts.chip);
321 	fprintf(out, SEC_VERSION "\n" OPT_MAJOR "=%d\n" OPT_MINOR "=%d\n",
322 	        gOpts.major, gOpts.minor);
323 
324 	fprintf(out, SEC_471 "\n" OPT_NUM "=%d\n", gOpts.code471Num);
325 	for (i = 0; i < gOpts.code471Num; i++) {
326 		fprintf(out, OPT_PATH "%d=%s\n", i + 1, gOpts.code471Path[i]);
327 	}
328 	if (gOpts.code471Sleep > 0)
329 		fprintf(out, OPT_SLEEP "=%d\n", gOpts.code471Sleep);
330 
331 	fprintf(out, SEC_472 "\n" OPT_NUM "=%d\n", gOpts.code472Num);
332 	for (i = 0; i < gOpts.code472Num; i++) {
333 		fprintf(out, OPT_PATH "%d=%s\n", i + 1, gOpts.code472Path[i]);
334 	}
335 	if (gOpts.code472Sleep > 0)
336 		fprintf(out, OPT_SLEEP "=%d\n", gOpts.code472Sleep);
337 
338 	fprintf(out, SEC_LOADER "\n" OPT_NUM "=%d\n", gOpts.loaderNum);
339 	for (i = 0; i < gOpts.loaderNum; i++) {
340 		fprintf(out, OPT_LOADER_NAME "%d=%s\n", i + 1, gOpts.loader[i].name);
341 	}
342 	for (i = 0; i < gOpts.loaderNum; i++) {
343 		fprintf(out, "%s=%s\n", gOpts.loader[i].name, gOpts.loader[i].path);
344 	}
345 
346 	fprintf(out, SEC_OUT "\n" OPT_OUT_PATH "=%s\n", gOpts.outPath);
347 }
348 
349 static bool parseOpts_from_file(void)
350 {
351 	bool ret = false;
352 	bool chipOk = false;
353 	bool versionOk = false;
354 	bool code471Ok = true;
355 	bool code472Ok = true;
356 	bool loaderOk = false;
357 	bool outOk = false;
358 	char buf[MAX_LINE_LEN];
359 
360 	char *configPath = (gConfigPath == NULL) ? DEF_CONFIG_FILE : gConfigPath;
361 	FILE *file;
362 	file = fopen(configPath, "r");
363 	if (!file) {
364 		fprintf(stderr, "config(%s) not found!\n", configPath);
365 		if (configPath == (char *)DEF_CONFIG_FILE) {
366 			file = fopen(DEF_CONFIG_FILE, "w");
367 			if (file) {
368 				fprintf(stderr, "create defconfig\n");
369 				printOpts(file);
370 			}
371 		}
372 		goto end;
373 	}
374 
375 	LOGD("start parse\n");
376 
377 	if (SCANF_EAT(file) != 0) {
378 		goto end;
379 	}
380 	while (fscanf(file, "%s", buf) == 1) {
381 		if (!strcmp(buf, SEC_CHIP)) {
382 			chipOk = parseChip(file);
383 			if (!chipOk) {
384 				LOGE("parseChip failed!\n");
385 				goto end;
386 			}
387 		} else if (!strcmp(buf, SEC_VERSION)) {
388 			versionOk = parseVersion(file);
389 			if (!versionOk) {
390 				LOGE("parseVersion failed!\n");
391 				goto end;
392 			}
393 		} else if (!strcmp(buf, SEC_471)) {
394 			code471Ok = parse471(file);
395 			if (!code471Ok) {
396 				LOGE("parse471 failed!\n");
397 				goto end;
398 			}
399 		} else if (!strcmp(buf, SEC_472)) {
400 			code472Ok = parse472(file);
401 			if (!code472Ok) {
402 				LOGE("parse472 failed!\n");
403 				goto end;
404 			}
405 		} else if (!strcmp(buf, SEC_LOADER)) {
406 			loaderOk = parseLoader(file);
407 			if (!loaderOk) {
408 				LOGE("parseLoader failed!\n");
409 				goto end;
410 			}
411 		} else if (!strcmp(buf, SEC_OUT)) {
412 			outOk = parseOut(file);
413 			if (!outOk) {
414 				LOGE("parseOut failed!\n");
415 				goto end;
416 			}
417 		} else if (buf[0] == '#') {
418 			continue;
419 		} else {
420 			LOGE("unknown sec: %s!\n", buf);
421 			goto end;
422 		}
423 		if (SCANF_EAT(file) != 0) {
424 			goto end;
425 		}
426 	}
427 
428 	if (chipOk && versionOk && code471Ok && code472Ok && loaderOk && outOk)
429 		ret = true;
430 end:
431 	if (file)
432 		fclose(file);
433 	return ret;
434 }
435 
436 static bool parseOpts_from_cmdline(int argc, char **argv)
437 {
438 	int i;
439 	int tag = 0;
440 	int v0, v1, v2, v3;
441 
442 	for (i = 2; i < argc; i++) {
443 		if (!strcmp(OPT_471, argv[i])) {
444 			i++;
445 			snprintf(gOpts.code471Path[0], sizeof(gOpts.code471Path[0]), "%s",
446 			         argv[i]);
447 			tag |= 1;
448 		} else if (!strcmp(OPT_472, argv[i])) {
449 			i++;
450 			snprintf(gOpts.code472Path[0], sizeof(gOpts.code472Path[0]), "%s",
451 			         argv[i]);
452 			tag |= 2;
453 		} else if (!strcmp(OPT_DATA, argv[i])) {
454 			i++;
455 			snprintf(gOpts.loader[0].path, sizeof(gOpts.loader[0].path), "%s",
456 			         argv[i]);
457 			tag |= 4;
458 		} else if (!strcmp(OPT_BOOT, argv[i])) {
459 			i++;
460 			snprintf(gOpts.loader[1].path, sizeof(gOpts.loader[1].path), "%s",
461 			         argv[i]);
462 			tag |= 8;
463 		} else if (!strcmp(OPT_OUT, argv[i])) {
464 			i++;
465 			snprintf(gOpts.outPath, sizeof(gOpts.outPath), "%s", argv[i]);
466 			tag |= 0x10;
467 		} else if (!strcmp(OPT_CHIP, argv[i])) {
468 			i++;
469 			snprintf(gOpts.chip, sizeof(gOpts.chip), "%s", argv[i]);
470 			tag |= 0x20;
471 		} else if (!strcmp(OPT_VERSION, argv[i])) {
472 		}
473 	}
474 
475 	sscanf(gOpts.loader[0].path, "%*[^v]v%d.%d.bin", &v0, &v1);
476 	sscanf(gOpts.loader[1].path, "%*[^v]v%d.%d.bin", &v2, &v3);
477 	gOpts.major = v2;
478 	gOpts.minor = v3;
479 	snprintf(gOpts.outPath, sizeof(gOpts.outPath),
480 	         "%s_loader_v%d.%02d.%d%02d.bin", gOpts.chip, v0, v1, v2, v3);
481 	return ((tag & 0x0f) == 0x0f) ? true : false;
482 }
483 
484 bool initOpts(int argc, char **argv)
485 {
486 	bool ret;
487 
488 	/* set default opts */
489 	gOpts.major = DEF_MAJOR;
490 	gOpts.minor = DEF_MINOR;
491 	strcpy(gOpts.chip, DEF_CHIP);
492 	gOpts.code471Sleep = DEF_CODE471_SLEEP;
493 	gOpts.code472Sleep = DEF_CODE472_SLEEP;
494 	gOpts.code471Num = DEF_CODE471_NUM;
495 	gOpts.code471Path = (line_t *)malloc(sizeof(line_t) * gOpts.code471Num);
496 	strcpy((char *)gOpts.code471Path[0], DEF_CODE471_PATH);
497 	gOpts.code472Num = DEF_CODE472_NUM;
498 	gOpts.code472Path = (line_t *)malloc(sizeof(line_t) * gOpts.code472Num);
499 	strcpy((char *)gOpts.code472Path[0], DEF_CODE472_PATH);
500 	gOpts.loaderNum = DEF_LOADER_NUM;
501 	gOpts.loader = (name_entry *)malloc(sizeof(name_entry) * gOpts.loaderNum);
502 	strcpy(gOpts.loader[0].name, DEF_LOADER0);
503 	strcpy(gOpts.loader[0].path, DEF_LOADER0_PATH);
504 	strcpy(gOpts.loader[1].name, DEF_LOADER1);
505 	strcpy(gOpts.loader[1].path, DEF_LOADER1_PATH);
506 	strcpy(gOpts.outPath, DEF_OUT_PATH);
507 
508 	if (argc > 10)
509 		ret = parseOpts_from_cmdline(argc, argv);
510 	else
511 		ret = parseOpts_from_file();
512 
513 	return ret;
514 }
515 
516 /************merge code****************/
517 
518 static inline uint32_t getBCD(unsigned short value)
519 {
520 	uint8_t tmp[2] = { 0 };
521 	int i;
522 	uint32_t ret;
523 	if (value > 0xFFFF) {
524 		return 0;
525 	}
526 	for (i = 0; i < 2; i++) {
527 		tmp[i] = (((value / 10) % 10) << 4) | (value % 10);
528 		value /= 100;
529 	}
530 	ret = ((uint16_t)(tmp[1] << 8)) | tmp[0];
531 
532 	LOGD("ret:%x\n", ret);
533 	return ret & 0xFF;
534 }
535 
536 static inline void str2wide(const char *str, uint16_t *wide, int len)
537 {
538 	int i;
539 	for (i = 0; i < len; i++) {
540 		wide[i] = (uint16_t) str[i];
541 	}
542 	wide[len] = 0;
543 }
544 
545 static inline void getName(char *path, uint16_t *dst)
546 {
547 	char *end;
548 	char *start;
549 	int len;
550 	if (!path || !dst)
551 		return;
552 	start = strrchr(path, '/');
553 	if (!start)
554 		start = path;
555 	else
556 		start++;
557 	end = strrchr(path, '.');
558 	if (!end)
559 		end = path + strlen(path);
560 	len = end - start;
561 	if (len >= MAX_NAME_LEN)
562 		len = MAX_NAME_LEN - 1;
563 	str2wide(start, dst, len);
564 
565 	if (gDebug) {
566 		char name[MAX_NAME_LEN];
567 		memset(name, 0, sizeof(name));
568 		memcpy(name, start, len);
569 		LOGD("path:%s, name:%s\n", path, name);
570 	}
571 }
572 
573 static inline bool getFileSize(const char *path, uint32_t *size)
574 {
575 	struct stat st;
576 	if (stat(path, &st) < 0)
577 		return false;
578 	*size = st.st_size;
579 	LOGD("path:%s, size:%d\n", path, *size);
580 	return true;
581 }
582 
583 static inline rk_time getTime(void)
584 {
585 	rk_time rkTime;
586 
587 	struct tm *tm;
588 	time_t tt = time(NULL);
589 	tm = localtime(&tt);
590 	rkTime.year = tm->tm_year + 1900;
591 	rkTime.month = tm->tm_mon + 1;
592 	rkTime.day = tm->tm_mday;
593 	rkTime.hour = tm->tm_hour;
594 	rkTime.minute = tm->tm_min;
595 	rkTime.second = tm->tm_sec;
596 	LOGD("%d-%d-%d %02d:%02d:%02d\n", rkTime.year, rkTime.month, rkTime.day,
597 	     rkTime.hour, rkTime.minute, rkTime.second);
598 	return rkTime;
599 }
600 
601 static bool writeFile(FILE *outFile, const char *path, bool fix)
602 {
603 	bool ret = false;
604 	uint32_t size = 0, fixSize = 0;
605 	uint8_t *buf;
606 
607 	FILE *inFile = fopen(path, "rb");
608 	if (!inFile)
609 		goto end;
610 
611 	if (!getFileSize(path, &size))
612 		goto end;
613 	if (fix) {
614 		fixSize = ((size - 1) / SMALL_PACKET + 1) * SMALL_PACKET;
615 		uint32_t tmp = fixSize % ENTRY_ALIGN;
616 		tmp = tmp ? (ENTRY_ALIGN - tmp) : 0;
617 		fixSize += tmp;
618 		memset(gBuf, 0, fixSize);
619 	} else {
620 		memset(gBuf, 0, size + ENTRY_ALIGN);
621 	}
622 	if (!fread(gBuf, size, 1, inFile))
623 		goto end;
624 
625 	if (fix) {
626 
627 		buf = gBuf;
628 		size = fixSize;
629 		while (1) {
630 			P_RC4(buf, fixSize < SMALL_PACKET ? fixSize : SMALL_PACKET);
631 			buf += SMALL_PACKET;
632 			if (fixSize <= SMALL_PACKET)
633 				break;
634 			fixSize -= SMALL_PACKET;
635 		}
636 	} else {
637 		uint32_t tmp = size % ENTRY_ALIGN;
638 		tmp = tmp ? (ENTRY_ALIGN - tmp) : 0;
639 		size += tmp;
640 		P_RC4(gBuf, size);
641 	}
642 
643 	if (!fwrite(gBuf, size, 1, outFile))
644 		goto end;
645 	ret = true;
646 end:
647 	if (inFile)
648 		fclose(inFile);
649 	if (!ret)
650 		LOGE("write entry(%s) failed\n", path);
651 	return ret;
652 }
653 
654 static bool saveEntry(FILE *outFile, char *path, rk_entry_type type,
655                       uint16_t delay, uint32_t *offset, char *fixName,
656                       bool fix)
657 {
658 	LOGD("write:%s\n", path);
659 	uint32_t size;
660 	rk_boot_entry entry;
661 	memset(&entry, 0, sizeof(rk_boot_entry));
662 
663 	LOGD("write:%s\n", path);
664 
665 	getName(fixName ? fixName : path, entry.name);
666 	entry.size = sizeof(rk_boot_entry);
667 	entry.type = type;
668 	entry.dataOffset = *offset;
669 	if (!getFileSize(path, &size)) {
670 		LOGE("save entry(%s) failed:\n\tcannot get file size.\n", path);
671 		return false;
672 	}
673 	if (fix)
674 		size = ((size - 1) / SMALL_PACKET + 1) * SMALL_PACKET;
675 	uint32_t tmp = size % ENTRY_ALIGN;
676 	size += tmp ? (ENTRY_ALIGN - tmp) : 0;
677 	LOGD("align size:%d\n", size);
678 	entry.dataSize = size;
679 	entry.dataDelay = delay;
680 	*offset += size;
681 	fwrite(&entry, sizeof(rk_boot_entry), 1, outFile);
682 	return true;
683 }
684 
685 static inline uint32_t convertChipType(const char *chip)
686 {
687 	char buffer[5];
688 	memset(buffer, 0, sizeof(buffer));
689 	snprintf(buffer, sizeof(buffer), "%s", chip);
690 	return buffer[0] << 24 | buffer[1] << 16 | buffer[2] << 8 | buffer[3];
691 }
692 
693 static inline uint32_t getChipType(const char *chip)
694 {
695 	LOGD("chip:%s\n", chip);
696 	int chipType = RKNONE_DEVICE;
697 	if (!chip) {
698 		goto end;
699 	}
700 	if (!strcmp(chip, CHIP_RK28)) {
701 		chipType = RK28_DEVICE;
702 	} else if (!strcmp(chip, CHIP_RK28)) {
703 		chipType = RK28_DEVICE;
704 	} else if (!strcmp(chip, CHIP_RK281X)) {
705 		chipType = RK281X_DEVICE;
706 	} else if (!strcmp(chip, CHIP_RKPANDA)) {
707 		chipType = RKPANDA_DEVICE;
708 	} else if (!strcmp(chip, CHIP_RK27)) {
709 		chipType = RK27_DEVICE;
710 	} else if (!strcmp(chip, CHIP_RKNANO)) {
711 		chipType = RKNANO_DEVICE;
712 	} else if (!strcmp(chip, CHIP_RKSMART)) {
713 		chipType = RKSMART_DEVICE;
714 	} else if (!strcmp(chip, CHIP_RKCROWN)) {
715 		chipType = RKCROWN_DEVICE;
716 	} else if (!strcmp(chip, CHIP_RKCAYMAN)) {
717 		chipType = RKCAYMAN_DEVICE;
718 	} else if (!strcmp(chip, CHIP_RK29)) {
719 		chipType = RK29_DEVICE;
720 	} else if (!strcmp(chip, CHIP_RK292X)) {
721 		chipType = RK292X_DEVICE;
722 	} else if (!strcmp(chip, CHIP_RK30)) {
723 		chipType = RK30_DEVICE;
724 	} else if (!strcmp(chip, CHIP_RK30B)) {
725 		chipType = RK30B_DEVICE;
726 	} else if (!strcmp(chip, CHIP_RK31)) {
727 		chipType = RK31_DEVICE;
728 	} else if (!strcmp(chip, CHIP_RK32)) {
729 		chipType = RK32_DEVICE;
730 	} else {
731 		chipType = convertChipType(chip + 2);
732 	}
733 
734 end:
735 	LOGD("type:0x%x\n", chipType);
736 	if (chipType == RKNONE_DEVICE) {
737 		LOGE("chip type not support!\n");
738 	}
739 	return chipType;
740 }
741 
742 static inline void getBoothdr(rk_boot_header *hdr)
743 {
744 	memset(hdr, 0, sizeof(rk_boot_header));
745 	hdr->tag = TAG;
746 	hdr->size = sizeof(rk_boot_header);
747 	hdr->version = (getBCD(gOpts.major) << 8) | getBCD(gOpts.minor);
748 	hdr->mergerVersion = MERGER_VERSION;
749 	hdr->releaseTime = getTime();
750 	hdr->chipType = getChipType(gOpts.chip);
751 
752 	hdr->code471Num = gOpts.code471Num;
753 	hdr->code471Offset = sizeof(rk_boot_header);
754 	hdr->code471Size = sizeof(rk_boot_entry);
755 
756 	hdr->code472Num = gOpts.code472Num;
757 	hdr->code472Offset = hdr->code471Offset + gOpts.code471Num * hdr->code471Size;
758 	hdr->code472Size = sizeof(rk_boot_entry);
759 
760 	hdr->loaderNum = gOpts.loaderNum;
761 	hdr->loaderOffset = hdr->code472Offset + gOpts.code472Num * hdr->code472Size;
762 	hdr->loaderSize = sizeof(rk_boot_entry);
763 #ifndef USE_P_RC4
764 	hdr->rc4Flag = 1;
765 #endif
766 }
767 
768 static inline uint32_t getCrc(const char *path)
769 {
770 	uint32_t size = 0;
771 	uint32_t crc = 0;
772 	FILE *file = fopen(path, "rb");
773 	getFileSize(path, &size);
774 	if (!file)
775 		goto end;
776 	if (!fread(gBuf, size, 1, file))
777 		goto end;
778 	crc = CRC_32(gBuf, size);
779 	LOGD("crc:0x%08x\n", crc);
780 end:
781 	if (file)
782 		fclose(file);
783 	return crc;
784 }
785 
786 static bool mergeBoot(int argc, char **argv)
787 {
788 	uint32_t dataOffset;
789 	bool ret = false;
790 	int i;
791 	FILE *outFile;
792 	uint32_t crc;
793 	rk_boot_header hdr;
794 
795 	if (!initOpts(argc, argv))
796 		return false;
797 	{
798 		char *subfix = strstr(gOpts.outPath, OUT_SUBFIX);
799 		char version[MAX_LINE_LEN];
800 		snprintf(version, sizeof(version), "%s", gSubfix);
801 		if (subfix && !strcmp(subfix, OUT_SUBFIX)) {
802 			subfix[0] = '\0';
803 		}
804 		strcat(gOpts.outPath, version);
805 		printf("fix opt:%s\n", gOpts.outPath);
806 	}
807 
808 	if (gDebug) {
809 		printf("---------------\nUSING CONFIG:\n");
810 		printOpts(stdout);
811 		printf("---------------\n\n");
812 	}
813 
814 	outFile = fopen(gOpts.outPath, "wb+");
815 	if (!outFile) {
816 		LOGE("open out file(%s) failed\n", gOpts.outPath);
817 		goto end;
818 	}
819 
820 	getBoothdr(&hdr);
821 	LOGD("write hdr\n");
822 	fwrite(&hdr, 1, sizeof(rk_boot_header), outFile);
823 
824 	dataOffset = sizeof(rk_boot_header) +
825 	             (gOpts.code471Num + gOpts.code472Num + gOpts.loaderNum) *
826 	             sizeof(rk_boot_entry);
827 
828 	LOGD("write code 471 entry\n");
829 	for (i = 0; i < gOpts.code471Num; i++) {
830 		if (!saveEntry(outFile, (char *)gOpts.code471Path[i], ENTRY_471,
831 		               gOpts.code471Sleep, &dataOffset, NULL, false))
832 			goto end;
833 	}
834 	LOGD("write code 472 entry\n");
835 	for (i = 0; i < gOpts.code472Num; i++) {
836 		if (!saveEntry(outFile, (char *)gOpts.code472Path[i], ENTRY_472,
837 		               gOpts.code472Sleep, &dataOffset, NULL, false))
838 			goto end;
839 	}
840 	LOGD("write loader entry\n");
841 	for (i = 0; i < gOpts.loaderNum; i++) {
842 		if (!saveEntry(outFile, gOpts.loader[i].path, ENTRY_LOADER, 0, &dataOffset,
843 		               gOpts.loader[i].name, true))
844 			goto end;
845 	}
846 
847 	LOGD("write code 471\n");
848 	for (i = 0; i < gOpts.code471Num; i++) {
849 		if (!writeFile(outFile, (char *)gOpts.code471Path[i], false))
850 			goto end;
851 	}
852 	LOGD("write code 472\n");
853 	for (i = 0; i < gOpts.code472Num; i++) {
854 		if (!writeFile(outFile, (char *)gOpts.code472Path[i], false))
855 			goto end;
856 	}
857 	LOGD("write loader\n");
858 	for (i = 0; i < gOpts.loaderNum; i++) {
859 		if (!writeFile(outFile, gOpts.loader[i].path, true))
860 			goto end;
861 	}
862 	fflush(outFile);
863 
864 	LOGD("write crc\n");
865 	crc = getCrc(gOpts.outPath);
866 	if (!fwrite(&crc, sizeof(crc), 1, outFile))
867 		goto end;
868 
869 	ret = true;
870 end:
871 	if (outFile)
872 		fclose(outFile);
873 	return ret;
874 }
875 
876 /************merge code end************/
877 /************unpack code***************/
878 
879 static inline void wide2str(const uint16_t *wide, char *str, int len)
880 {
881 	int i;
882 	for (i = 0; i < len; i++) {
883 		str[i] = (char)(wide[i] & 0xFF);
884 	}
885 	str[len] = 0;
886 }
887 
888 static bool unpackEntry(rk_boot_entry *entry, const char *name, FILE *inFile)
889 {
890 	bool ret = false;
891 	int size, i;
892 	FILE *outFile = fopen(name, "wb+");
893 	if (!outFile)
894 		goto end;
895 	printf("unpack entry(%s)\n", name);
896 	fseek(inFile, entry->dataOffset, SEEK_SET);
897 	size = entry->dataSize;
898 	if (!fread(gBuf, size, 1, inFile))
899 		goto end;
900 	if (entry->type == ENTRY_LOADER) {
901 		for (i = 0; i < size / SMALL_PACKET; i++)
902 			P_RC4(gBuf + i * SMALL_PACKET, SMALL_PACKET);
903 		if (size % SMALL_PACKET) {
904 			P_RC4(gBuf + i * SMALL_PACKET, size - SMALL_PACKET * 512);
905 		}
906 	} else {
907 		P_RC4(gBuf, size);
908 	}
909 	if (!fwrite(gBuf, size, 1, outFile))
910 		goto end;
911 	ret = true;
912 end:
913 	if (outFile)
914 		fclose(outFile);
915 	return ret;
916 }
917 
918 static bool unpackBoot(char *path)
919 {
920 	bool ret = false;
921 	FILE *inFile = fopen(path, "rb");
922 	int entryNum, i;
923 	char name[MAX_NAME_LEN];
924 	rk_boot_entry *entrys;
925 	if (!inFile) {
926 		fprintf(stderr, "loader(%s) not found\n", path);
927 		goto end;
928 	}
929 
930 	rk_boot_header hdr;
931 	if (!fread(&hdr, sizeof(rk_boot_header), 1, inFile)) {
932 		fprintf(stderr, "read header failed\n");
933 		goto end;
934 	}
935 
936 	entryNum = hdr.code471Num + hdr.code472Num + hdr.loaderNum;
937 	entrys = (rk_boot_entry *)malloc(sizeof(rk_boot_entry) * entryNum);
938 	if (!fread(entrys, sizeof(rk_boot_entry) * entryNum, 1, inFile)) {
939 		fprintf(stderr, "read data failed\n");
940 		goto end;
941 	}
942 
943 	LOGD("entry num:%d\n", entryNum);
944 	for (i = 0; i < entryNum; i++) {
945 		wide2str(entrys[i].name, name, MAX_NAME_LEN);
946 
947 		LOGD("entry:t=%d, name=%s, off=%d, size=%d\n", entrys[i].type, name,
948 		     entrys[i].dataOffset, entrys[i].dataSize);
949 		if (!unpackEntry(entrys + i, name, inFile)) {
950 			fprintf(stderr, "unpack entry(%s) failed\n", name);
951 			goto end;
952 		}
953 	}
954 
955 	ret = true;
956 end:
957 	if (inFile)
958 		fclose(inFile);
959 	return ret;
960 }
961 
962 /************unpack code end***********/
963 
964 static void printHelp(void)
965 {
966 	printf("Usage1: boot_merger [options]... FILE\n");
967 	printf("Merge or unpack Rockchip's loader (Default action is to merge.)\n");
968 	printf("Options:\n");
969 	printf("\t" OPT_MERGE "\t\t\tMerge loader with specified config.\n");
970 	printf("\t" OPT_UNPACK "\t\tUnpack specified loader to current dir.\n");
971 	printf("\t" OPT_VERBOSE "\t\tDisplay more runtime informations.\n");
972 	printf("\t" OPT_HELP "\t\t\tDisplay this information.\n");
973 	printf("\t" OPT_VERSION "\t\tDisplay version information.\n");
974 	printf("\t" OPT_SUBFIX "\t\tSpec subfix.\n");
975 	printf("\t" OPT_REPLACE "\t\tReplace some part of binary path.\n");
976 	printf("\t" OPT_SIZE
977 	       "\t\tImage size.\"--size [image KB size]\", must be 512KB aligned\n");
978 	printf("Usage2: boot_merger [options] [parameter]\n");
979 	printf("All below five option are must in this mode!\n");
980 	printf("\t" OPT_CHIP "\t\tChip type, used for check with usbplug.\n");
981 	printf("\t" OPT_471 "\t\t471 for download, ddr.bin.\n");
982 	printf("\t" OPT_472 "\t\t472 for download, usbplug.bin.\n");
983 	printf("\t" OPT_DATA "\t\tloader0 for flash, ddr.bin.\n");
984 	printf("\t" OPT_BOOT "\t\tloader1 for flash, miniloader.bin.\n");
985 	printf("\n./tools/boot_merger --pack --verbose -c RK322A -1 "
986 	       "rkbin/rk322x_ddr_300MHz_v1.04.bin -2 "
987 	       "rkbin/rk32/rk322x_usbplug_v2.32.bin -d "
988 	       "rkbin/rk32/rk322x_ddr_300MHz_v1.04.bin -b "
989 	       "rkbin/rk32/rk322x_miniloader_v2.32.bin\n");
990 }
991 
992 int main(int argc, char **argv)
993 {
994 
995 	int i;
996 	bool merge = true;
997 	char *optPath = NULL;
998 
999 	for (i = 1; i < argc; i++) {
1000 		if (!strcmp(OPT_VERBOSE, argv[i])) {
1001 			gDebug = true;
1002 			printf("enable debug\n");
1003 		} else if (!strcmp(OPT_HELP, argv[i])) {
1004 			printHelp();
1005 			return 0;
1006 		} else if (!strcmp(OPT_VERSION, argv[i])) {
1007 			printf("boot_merger (cjf@rock-chips.com)\t" VERSION "\n");
1008 			return 0;
1009 		} else if (!strcmp(OPT_MERGE, argv[i])) {
1010 			merge = true;
1011 		} else if (!strcmp(OPT_UNPACK, argv[i])) {
1012 			merge = false;
1013 		} else if (!strcmp(OPT_SUBFIX, argv[i])) {
1014 			i++;
1015 			snprintf(gSubfix, sizeof(gSubfix), "%s", argv[i]);
1016 		} else if (!strcmp(OPT_REPLACE, argv[i])) {
1017 			i++;
1018 			snprintf(gLegacyPath, sizeof(gLegacyPath), "%s", argv[i]);
1019 			i++;
1020 			snprintf(gNewPath, sizeof(gNewPath), "%s", argv[i]);
1021 		} else if (!strcmp(OPT_SIZE, argv[i])) {
1022 			g_merge_max_size = strtoul(argv[++i], NULL, 10);
1023 			if (g_merge_max_size % 512) {
1024 				printHelp();
1025 				return -1;
1026 			}
1027 			g_merge_max_size *= 1024; /* bytes */
1028 		} else {
1029 			optPath = argv[i];
1030 			break;
1031 		}
1032 	}
1033 	if (!merge && !optPath) {
1034 		fprintf(stderr, "need set out path to unpack!\n");
1035 		printHelp();
1036 		return -1;
1037 	}
1038 
1039 	gBuf = calloc(g_merge_max_size, 1);
1040 	if (!gBuf) {
1041 		LOGE("Merge image: calloc buffer error.\n");
1042 		return -1;
1043 	}
1044 
1045 	if (merge) {
1046 		LOGD("do_merge\n");
1047 		gConfigPath = optPath;
1048 		if (!mergeBoot(argc, argv)) {
1049 			fprintf(stderr, "merge failed!\n");
1050 			return -1;
1051 		}
1052 		printf("merge success(%s)\n", gOpts.outPath);
1053 	} else {
1054 		LOGD("do_unpack\n");
1055 		if (!unpackBoot(optPath)) {
1056 			fprintf(stderr, "unpack failed!\n");
1057 			return -1;
1058 		}
1059 		printf("unpack success\n");
1060 	}
1061 	return 0;
1062 }
1063