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