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