xref: /rk3399_rockchip-uboot/common/main.c (revision ea5427e2607041f6f5cf0bff8f5c85bc7f67dbf8)
1 /*
2  * (C) Copyright 2000
3  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
4  *
5  * Add to readline cmdline-editing by
6  * (C) Copyright 2005
7  * JinHua Luo, GuangDong Linux Center, <luo.jinhua@gd-linux.com>
8  *
9  * See file CREDITS for list of people who contributed to this
10  * project.
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License as
14  * published by the Free Software Foundation; either version 2 of
15  * the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
25  * MA 02111-1307 USA
26  */
27 
28 /* #define	DEBUG	*/
29 
30 #include <common.h>
31 #include <watchdog.h>
32 #include <command.h>
33 #include <fdtdec.h>
34 #include <malloc.h>
35 #include <version.h>
36 #ifdef CONFIG_MODEM_SUPPORT
37 #include <malloc.h>		/* for free() prototype */
38 #endif
39 
40 #ifdef CONFIG_SYS_HUSH_PARSER
41 #include <hush.h>
42 #endif
43 
44 #ifdef CONFIG_OF_CONTROL
45 #include <fdtdec.h>
46 #endif
47 
48 #include <post.h>
49 #include <linux/ctype.h>
50 #include <menu.h>
51 
52 DECLARE_GLOBAL_DATA_PTR;
53 
54 /*
55  * Board-specific Platform code can reimplement show_boot_progress () if needed
56  */
57 void inline __show_boot_progress (int val) {}
58 void show_boot_progress (int val) __attribute__((weak, alias("__show_boot_progress")));
59 
60 #define MAX_DELAY_STOP_STR 32
61 
62 #undef DEBUG_PARSER
63 
64 char        console_buffer[CONFIG_SYS_CBSIZE + 1];	/* console I/O buffer	*/
65 
66 static char * delete_char (char *buffer, char *p, int *colp, int *np, int plen);
67 static const char erase_seq[] = "\b \b";		/* erase sequence	*/
68 static const char   tab_seq[] = "        ";		/* used to expand TABs	*/
69 
70 #ifdef CONFIG_BOOT_RETRY_TIME
71 static uint64_t endtime = 0;  /* must be set, default is instant timeout */
72 static int      retry_time = -1; /* -1 so can call readline before main_loop */
73 #endif
74 
75 #define	endtick(seconds) (get_ticks() + (uint64_t)(seconds) * get_tbclk())
76 
77 #ifndef CONFIG_BOOT_RETRY_MIN
78 #define CONFIG_BOOT_RETRY_MIN CONFIG_BOOT_RETRY_TIME
79 #endif
80 
81 #ifdef CONFIG_MODEM_SUPPORT
82 int do_mdm_init = 0;
83 extern void mdm_init(void); /* defined in board.c */
84 #endif
85 
86 /***************************************************************************
87  * Watch for 'delay' seconds for autoboot stop or autoboot delay string.
88  * returns: 0 -  no key string, allow autoboot 1 - got key string, abort
89  */
90 #if defined(CONFIG_BOOTDELAY)
91 # if defined(CONFIG_AUTOBOOT_KEYED)
92 #ifndef CONFIG_MENU
93 static inline
94 #endif
95 int abortboot(int bootdelay)
96 {
97 	int abort = 0;
98 	uint64_t etime = endtick(bootdelay);
99 	struct {
100 		char* str;
101 		u_int len;
102 		int retry;
103 	}
104 	delaykey [] = {
105 		{ str: getenv ("bootdelaykey"),  retry: 1 },
106 		{ str: getenv ("bootdelaykey2"), retry: 1 },
107 		{ str: getenv ("bootstopkey"),   retry: 0 },
108 		{ str: getenv ("bootstopkey2"),  retry: 0 },
109 	};
110 
111 	char presskey [MAX_DELAY_STOP_STR];
112 	u_int presskey_len = 0;
113 	u_int presskey_max = 0;
114 	u_int i;
115 
116 #ifndef CONFIG_ZERO_BOOTDELAY_CHECK
117 	if (bootdelay == 0)
118 		return 0;
119 #endif
120 
121 #  ifdef CONFIG_AUTOBOOT_PROMPT
122 	printf(CONFIG_AUTOBOOT_PROMPT);
123 #  endif
124 
125 #  ifdef CONFIG_AUTOBOOT_DELAY_STR
126 	if (delaykey[0].str == NULL)
127 		delaykey[0].str = CONFIG_AUTOBOOT_DELAY_STR;
128 #  endif
129 #  ifdef CONFIG_AUTOBOOT_DELAY_STR2
130 	if (delaykey[1].str == NULL)
131 		delaykey[1].str = CONFIG_AUTOBOOT_DELAY_STR2;
132 #  endif
133 #  ifdef CONFIG_AUTOBOOT_STOP_STR
134 	if (delaykey[2].str == NULL)
135 		delaykey[2].str = CONFIG_AUTOBOOT_STOP_STR;
136 #  endif
137 #  ifdef CONFIG_AUTOBOOT_STOP_STR2
138 	if (delaykey[3].str == NULL)
139 		delaykey[3].str = CONFIG_AUTOBOOT_STOP_STR2;
140 #  endif
141 
142 	for (i = 0; i < sizeof(delaykey) / sizeof(delaykey[0]); i ++) {
143 		delaykey[i].len = delaykey[i].str == NULL ?
144 				    0 : strlen (delaykey[i].str);
145 		delaykey[i].len = delaykey[i].len > MAX_DELAY_STOP_STR ?
146 				    MAX_DELAY_STOP_STR : delaykey[i].len;
147 
148 		presskey_max = presskey_max > delaykey[i].len ?
149 				    presskey_max : delaykey[i].len;
150 
151 #  if DEBUG_BOOTKEYS
152 		printf("%s key:<%s>\n",
153 		       delaykey[i].retry ? "delay" : "stop",
154 		       delaykey[i].str ? delaykey[i].str : "NULL");
155 #  endif
156 	}
157 
158 	/* In order to keep up with incoming data, check timeout only
159 	 * when catch up.
160 	 */
161 	do {
162 		if (tstc()) {
163 			if (presskey_len < presskey_max) {
164 				presskey [presskey_len ++] = getc();
165 			}
166 			else {
167 				for (i = 0; i < presskey_max - 1; i ++)
168 					presskey [i] = presskey [i + 1];
169 
170 				presskey [i] = getc();
171 			}
172 		}
173 
174 		for (i = 0; i < sizeof(delaykey) / sizeof(delaykey[0]); i ++) {
175 			if (delaykey[i].len > 0 &&
176 			    presskey_len >= delaykey[i].len &&
177 			    memcmp (presskey + presskey_len - delaykey[i].len,
178 				    delaykey[i].str,
179 				    delaykey[i].len) == 0) {
180 #  if DEBUG_BOOTKEYS
181 				printf("got %skey\n",
182 				       delaykey[i].retry ? "delay" : "stop");
183 #  endif
184 
185 #  ifdef CONFIG_BOOT_RETRY_TIME
186 				/* don't retry auto boot */
187 				if (! delaykey[i].retry)
188 					retry_time = -1;
189 #  endif
190 				abort = 1;
191 			}
192 		}
193 	} while (!abort && get_ticks() <= etime);
194 
195 #  if DEBUG_BOOTKEYS
196 	if (!abort)
197 		puts("key timeout\n");
198 #  endif
199 
200 #ifdef CONFIG_SILENT_CONSOLE
201 	if (abort)
202 		gd->flags &= ~GD_FLG_SILENT;
203 #endif
204 
205 	return abort;
206 }
207 
208 # else	/* !defined(CONFIG_AUTOBOOT_KEYED) */
209 
210 #ifdef CONFIG_MENUKEY
211 static int menukey = 0;
212 #endif
213 
214 #ifndef CONFIG_MENU
215 static inline
216 #endif
217 int abortboot(int bootdelay)
218 {
219 	int abort = 0;
220 	unsigned long ts;
221 
222 #ifdef CONFIG_MENUPROMPT
223 	printf(CONFIG_MENUPROMPT);
224 #else
225 	if (bootdelay >= 0)
226 		printf("Hit any key to stop autoboot: %2d ", bootdelay);
227 #endif
228 
229 #if defined CONFIG_ZERO_BOOTDELAY_CHECK
230 	/*
231 	 * Check if key already pressed
232 	 * Don't check if bootdelay < 0
233 	 */
234 	if (bootdelay >= 0) {
235 		if (tstc()) {	/* we got a key press	*/
236 			(void) getc();  /* consume input	*/
237 			puts ("\b\b\b 0");
238 			abort = 1;	/* don't auto boot	*/
239 		}
240 	}
241 #endif
242 
243 	while ((bootdelay > 0) && (!abort)) {
244 		--bootdelay;
245 		/* delay 1000 ms */
246 		ts = get_timer(0);
247 		do {
248 			if (tstc()) {	/* we got a key press	*/
249 				abort  = 1;	/* don't auto boot	*/
250 				bootdelay = 0;	/* no more delay	*/
251 # ifdef CONFIG_MENUKEY
252 				menukey = getc();
253 # else
254 				(void) getc();  /* consume input	*/
255 # endif
256 				break;
257 			}
258 			udelay(10000);
259 		} while (!abort && get_timer(ts) < 1000);
260 
261 		printf("\b\b\b%2d ", bootdelay);
262 	}
263 
264 	putc('\n');
265 
266 #ifdef CONFIG_SILENT_CONSOLE
267 	if (abort)
268 		gd->flags &= ~GD_FLG_SILENT;
269 #endif
270 
271 	return abort;
272 }
273 # endif	/* CONFIG_AUTOBOOT_KEYED */
274 #endif	/* CONFIG_BOOTDELAY */
275 
276 /*
277  * Runs the given boot command securely.  Specifically:
278  * - Doesn't run the command with the shell (run_command or parse_string_outer),
279  *   since that's a lot of code surface that an attacker might exploit.
280  *   Because of this, we don't do any argument parsing--the secure boot command
281  *   has to be a full-fledged u-boot command.
282  * - Doesn't check for keypresses before booting, since that could be a
283  *   security hole; also disables Ctrl-C.
284  * - Doesn't allow the command to return.
285  *
286  * Upon any failures, this function will drop into an infinite loop after
287  * printing the error message to console.
288  */
289 
290 #if defined(CONFIG_BOOTDELAY) && defined(CONFIG_OF_CONTROL)
291 static void secure_boot_cmd(char *cmd)
292 {
293 	cmd_tbl_t *cmdtp;
294 	int rc;
295 
296 	if (!cmd) {
297 		printf("## Error: Secure boot command not specified\n");
298 		goto err;
299 	}
300 
301 	/* Disable Ctrl-C just in case some command is used that checks it. */
302 	disable_ctrlc(1);
303 
304 	/* Find the command directly. */
305 	cmdtp = find_cmd(cmd);
306 	if (!cmdtp) {
307 		printf("## Error: \"%s\" not defined\n", cmd);
308 		goto err;
309 	}
310 
311 	/* Run the command, forcing no flags and faking argc and argv. */
312 	rc = (cmdtp->cmd)(cmdtp, 0, 1, &cmd);
313 
314 	/* Shouldn't ever return from boot command. */
315 	printf("## Error: \"%s\" returned (code %d)\n", cmd, rc);
316 
317 err:
318 	/*
319 	 * Not a whole lot to do here.  Rebooting won't help much, since we'll
320 	 * just end up right back here.  Just loop.
321 	 */
322 	hang();
323 }
324 
325 static void process_fdt_options(const void *blob)
326 {
327 	ulong addr;
328 
329 	/* Add an env variable to point to a kernel payload, if available */
330 	addr = fdtdec_get_config_int(gd->fdt_blob, "kernel-offset", 0);
331 	if (addr)
332 		setenv_addr("kernaddr", (void *)(CONFIG_SYS_TEXT_BASE + addr));
333 
334 	/* Add an env variable to point to a root disk, if available */
335 	addr = fdtdec_get_config_int(gd->fdt_blob, "rootdisk-offset", 0);
336 	if (addr)
337 		setenv_addr("rootaddr", (void *)(CONFIG_SYS_TEXT_BASE + addr));
338 }
339 #endif /* CONFIG_OF_CONTROL */
340 
341 
342 /****************************************************************************/
343 
344 void main_loop (void)
345 {
346 #ifndef CONFIG_SYS_HUSH_PARSER
347 	static char lastcommand[CONFIG_SYS_CBSIZE] = { 0, };
348 	int len;
349 	int rc = 1;
350 	int flag;
351 #endif
352 #if defined(CONFIG_BOOTDELAY) && defined(CONFIG_OF_CONTROL)
353 	char *env;
354 #endif
355 #if defined(CONFIG_BOOTDELAY)
356 	char *s;
357 	int bootdelay;
358 #endif
359 #ifdef CONFIG_PREBOOT
360 	char *p;
361 #endif
362 #ifdef CONFIG_BOOTCOUNT_LIMIT
363 	unsigned long bootcount = 0;
364 	unsigned long bootlimit = 0;
365 	char *bcs;
366 	char bcs_set[16];
367 #endif /* CONFIG_BOOTCOUNT_LIMIT */
368 
369 	bootstage_mark_name(BOOTSTAGE_ID_MAIN_LOOP, "main_loop");
370 
371 #ifdef CONFIG_BOOTCOUNT_LIMIT
372 	bootcount = bootcount_load();
373 	bootcount++;
374 	bootcount_store (bootcount);
375 	sprintf (bcs_set, "%lu", bootcount);
376 	setenv ("bootcount", bcs_set);
377 	bcs = getenv ("bootlimit");
378 	bootlimit = bcs ? simple_strtoul (bcs, NULL, 10) : 0;
379 #endif /* CONFIG_BOOTCOUNT_LIMIT */
380 
381 #ifdef CONFIG_MODEM_SUPPORT
382 	debug ("DEBUG: main_loop:   do_mdm_init=%d\n", do_mdm_init);
383 	if (do_mdm_init) {
384 		char *str = strdup(getenv("mdm_cmd"));
385 		setenv ("preboot", str);  /* set or delete definition */
386 		if (str != NULL)
387 			free (str);
388 		mdm_init(); /* wait for modem connection */
389 	}
390 #endif  /* CONFIG_MODEM_SUPPORT */
391 
392 #ifdef CONFIG_VERSION_VARIABLE
393 	{
394 		setenv ("ver", version_string);  /* set version variable */
395 	}
396 #endif /* CONFIG_VERSION_VARIABLE */
397 
398 #ifdef CONFIG_SYS_HUSH_PARSER
399 	u_boot_hush_start ();
400 #endif
401 
402 #if defined(CONFIG_HUSH_INIT_VAR)
403 	hush_init_var ();
404 #endif
405 
406 #ifdef CONFIG_PREBOOT
407 	if ((p = getenv ("preboot")) != NULL) {
408 # ifdef CONFIG_AUTOBOOT_KEYED
409 		int prev = disable_ctrlc(1);	/* disable Control C checking */
410 # endif
411 
412 		run_command_list(p, -1, 0);
413 
414 # ifdef CONFIG_AUTOBOOT_KEYED
415 		disable_ctrlc(prev);	/* restore Control C checking */
416 # endif
417 	}
418 #endif /* CONFIG_PREBOOT */
419 
420 #if defined(CONFIG_UPDATE_TFTP)
421 	update_tftp (0UL);
422 #endif /* CONFIG_UPDATE_TFTP */
423 
424 #if defined(CONFIG_BOOTDELAY)
425 	s = getenv ("bootdelay");
426 	bootdelay = s ? (int)simple_strtol(s, NULL, 10) : CONFIG_BOOTDELAY;
427 
428 	debug ("### main_loop entered: bootdelay=%d\n\n", bootdelay);
429 
430 #if defined(CONFIG_MENU_SHOW)
431 	bootdelay = menu_show(bootdelay);
432 #endif
433 # ifdef CONFIG_BOOT_RETRY_TIME
434 	init_cmd_timeout ();
435 # endif	/* CONFIG_BOOT_RETRY_TIME */
436 
437 #ifdef CONFIG_POST
438 	if (gd->flags & GD_FLG_POSTFAIL) {
439 		s = getenv("failbootcmd");
440 	}
441 	else
442 #endif /* CONFIG_POST */
443 #ifdef CONFIG_BOOTCOUNT_LIMIT
444 	if (bootlimit && (bootcount > bootlimit)) {
445 		printf ("Warning: Bootlimit (%u) exceeded. Using altbootcmd.\n",
446 		        (unsigned)bootlimit);
447 		s = getenv ("altbootcmd");
448 	}
449 	else
450 #endif /* CONFIG_BOOTCOUNT_LIMIT */
451 		s = getenv ("bootcmd");
452 #ifdef CONFIG_OF_CONTROL
453 	/* Allow the fdt to override the boot command */
454 	env = fdtdec_get_config_string(gd->fdt_blob, "bootcmd");
455 	if (env)
456 		s = env;
457 
458 	process_fdt_options(gd->fdt_blob);
459 
460 	/*
461 	 * If the bootsecure option was chosen, use secure_boot_cmd().
462 	 * Always use 'env' in this case, since bootsecure requres that the
463 	 * bootcmd was specified in the FDT too.
464 	 */
465 	if (fdtdec_get_config_int(gd->fdt_blob, "bootsecure", 0))
466 		secure_boot_cmd(env);
467 
468 #endif /* CONFIG_OF_CONTROL */
469 
470 	debug ("### main_loop: bootcmd=\"%s\"\n", s ? s : "<UNDEFINED>");
471 
472 	if (bootdelay != -1 && s && !abortboot(bootdelay)) {
473 # ifdef CONFIG_AUTOBOOT_KEYED
474 		int prev = disable_ctrlc(1);	/* disable Control C checking */
475 # endif
476 
477 		run_command_list(s, -1, 0);
478 
479 # ifdef CONFIG_AUTOBOOT_KEYED
480 		disable_ctrlc(prev);	/* restore Control C checking */
481 # endif
482 	}
483 
484 # ifdef CONFIG_MENUKEY
485 	if (menukey == CONFIG_MENUKEY) {
486 		s = getenv("menucmd");
487 		if (s)
488 			run_command_list(s, -1, 0);
489 	}
490 #endif /* CONFIG_MENUKEY */
491 #endif /* CONFIG_BOOTDELAY */
492 
493 	/*
494 	 * Main Loop for Monitor Command Processing
495 	 */
496 #ifdef CONFIG_SYS_HUSH_PARSER
497 	parse_file_outer();
498 	/* This point is never reached */
499 	for (;;);
500 #else
501 	for (;;) {
502 #ifdef CONFIG_BOOT_RETRY_TIME
503 		if (rc >= 0) {
504 			/* Saw enough of a valid command to
505 			 * restart the timeout.
506 			 */
507 			reset_cmd_timeout();
508 		}
509 #endif
510 		len = readline (CONFIG_SYS_PROMPT);
511 
512 		flag = 0;	/* assume no special flags for now */
513 		if (len > 0)
514 			strcpy (lastcommand, console_buffer);
515 		else if (len == 0)
516 			flag |= CMD_FLAG_REPEAT;
517 #ifdef CONFIG_BOOT_RETRY_TIME
518 		else if (len == -2) {
519 			/* -2 means timed out, retry autoboot
520 			 */
521 			puts ("\nTimed out waiting for command\n");
522 # ifdef CONFIG_RESET_TO_RETRY
523 			/* Reinit board to run initialization code again */
524 			do_reset (NULL, 0, 0, NULL);
525 # else
526 			return;		/* retry autoboot */
527 # endif
528 		}
529 #endif
530 
531 		if (len == -1)
532 			puts ("<INTERRUPT>\n");
533 		else
534 			rc = run_command(lastcommand, flag);
535 
536 		if (rc <= 0) {
537 			/* invalid command or not repeatable, forget it */
538 			lastcommand[0] = 0;
539 		}
540 	}
541 #endif /*CONFIG_SYS_HUSH_PARSER*/
542 }
543 
544 #ifdef CONFIG_BOOT_RETRY_TIME
545 /***************************************************************************
546  * initialize command line timeout
547  */
548 void init_cmd_timeout(void)
549 {
550 	char *s = getenv ("bootretry");
551 
552 	if (s != NULL)
553 		retry_time = (int)simple_strtol(s, NULL, 10);
554 	else
555 		retry_time =  CONFIG_BOOT_RETRY_TIME;
556 
557 	if (retry_time >= 0 && retry_time < CONFIG_BOOT_RETRY_MIN)
558 		retry_time = CONFIG_BOOT_RETRY_MIN;
559 }
560 
561 /***************************************************************************
562  * reset command line timeout to retry_time seconds
563  */
564 void reset_cmd_timeout(void)
565 {
566 	endtime = endtick(retry_time);
567 }
568 #endif
569 
570 #ifdef CONFIG_CMDLINE_EDITING
571 
572 /*
573  * cmdline-editing related codes from vivi.
574  * Author: Janghoon Lyu <nandy@mizi.com>
575  */
576 
577 #define putnstr(str,n)	do {			\
578 		printf ("%.*s", (int)n, str);	\
579 	} while (0)
580 
581 #define CTL_CH(c)		((c) - 'a' + 1)
582 #define CTL_BACKSPACE		('\b')
583 #define DEL			((char)255)
584 #define DEL7			((char)127)
585 #define CREAD_HIST_CHAR		('!')
586 
587 #define getcmd_putch(ch)	putc(ch)
588 #define getcmd_getch()		getc()
589 #define getcmd_cbeep()		getcmd_putch('\a')
590 
591 #define HIST_MAX		20
592 #define HIST_SIZE		CONFIG_SYS_CBSIZE
593 
594 static int hist_max;
595 static int hist_add_idx;
596 static int hist_cur = -1;
597 static unsigned hist_num;
598 
599 static char *hist_list[HIST_MAX];
600 static char hist_lines[HIST_MAX][HIST_SIZE + 1];	/* Save room for NULL */
601 
602 #define add_idx_minus_one() ((hist_add_idx == 0) ? hist_max : hist_add_idx-1)
603 
604 static void hist_init(void)
605 {
606 	int i;
607 
608 	hist_max = 0;
609 	hist_add_idx = 0;
610 	hist_cur = -1;
611 	hist_num = 0;
612 
613 	for (i = 0; i < HIST_MAX; i++) {
614 		hist_list[i] = hist_lines[i];
615 		hist_list[i][0] = '\0';
616 	}
617 }
618 
619 static void cread_add_to_hist(char *line)
620 {
621 	strcpy(hist_list[hist_add_idx], line);
622 
623 	if (++hist_add_idx >= HIST_MAX)
624 		hist_add_idx = 0;
625 
626 	if (hist_add_idx > hist_max)
627 		hist_max = hist_add_idx;
628 
629 	hist_num++;
630 }
631 
632 static char* hist_prev(void)
633 {
634 	char *ret;
635 	int old_cur;
636 
637 	if (hist_cur < 0)
638 		return NULL;
639 
640 	old_cur = hist_cur;
641 	if (--hist_cur < 0)
642 		hist_cur = hist_max;
643 
644 	if (hist_cur == hist_add_idx) {
645 		hist_cur = old_cur;
646 		ret = NULL;
647 	} else
648 		ret = hist_list[hist_cur];
649 
650 	return (ret);
651 }
652 
653 static char* hist_next(void)
654 {
655 	char *ret;
656 
657 	if (hist_cur < 0)
658 		return NULL;
659 
660 	if (hist_cur == hist_add_idx)
661 		return NULL;
662 
663 	if (++hist_cur > hist_max)
664 		hist_cur = 0;
665 
666 	if (hist_cur == hist_add_idx) {
667 		ret = "";
668 	} else
669 		ret = hist_list[hist_cur];
670 
671 	return (ret);
672 }
673 
674 #ifndef CONFIG_CMDLINE_EDITING
675 static void cread_print_hist_list(void)
676 {
677 	int i;
678 	unsigned long n;
679 
680 	n = hist_num - hist_max;
681 
682 	i = hist_add_idx + 1;
683 	while (1) {
684 		if (i > hist_max)
685 			i = 0;
686 		if (i == hist_add_idx)
687 			break;
688 		printf("%s\n", hist_list[i]);
689 		n++;
690 		i++;
691 	}
692 }
693 #endif /* CONFIG_CMDLINE_EDITING */
694 
695 #define BEGINNING_OF_LINE() {			\
696 	while (num) {				\
697 		getcmd_putch(CTL_BACKSPACE);	\
698 		num--;				\
699 	}					\
700 }
701 
702 #define ERASE_TO_EOL() {				\
703 	if (num < eol_num) {				\
704 		printf("%*s", (int)(eol_num - num), ""); \
705 		do {					\
706 			getcmd_putch(CTL_BACKSPACE);	\
707 		} while (--eol_num > num);		\
708 	}						\
709 }
710 
711 #define REFRESH_TO_EOL() {			\
712 	if (num < eol_num) {			\
713 		wlen = eol_num - num;		\
714 		putnstr(buf + num, wlen);	\
715 		num = eol_num;			\
716 	}					\
717 }
718 
719 static void cread_add_char(char ichar, int insert, unsigned long *num,
720 	       unsigned long *eol_num, char *buf, unsigned long len)
721 {
722 	unsigned long wlen;
723 
724 	/* room ??? */
725 	if (insert || *num == *eol_num) {
726 		if (*eol_num > len - 1) {
727 			getcmd_cbeep();
728 			return;
729 		}
730 		(*eol_num)++;
731 	}
732 
733 	if (insert) {
734 		wlen = *eol_num - *num;
735 		if (wlen > 1) {
736 			memmove(&buf[*num+1], &buf[*num], wlen-1);
737 		}
738 
739 		buf[*num] = ichar;
740 		putnstr(buf + *num, wlen);
741 		(*num)++;
742 		while (--wlen) {
743 			getcmd_putch(CTL_BACKSPACE);
744 		}
745 	} else {
746 		/* echo the character */
747 		wlen = 1;
748 		buf[*num] = ichar;
749 		putnstr(buf + *num, wlen);
750 		(*num)++;
751 	}
752 }
753 
754 static void cread_add_str(char *str, int strsize, int insert, unsigned long *num,
755 	      unsigned long *eol_num, char *buf, unsigned long len)
756 {
757 	while (strsize--) {
758 		cread_add_char(*str, insert, num, eol_num, buf, len);
759 		str++;
760 	}
761 }
762 
763 static int cread_line(const char *const prompt, char *buf, unsigned int *len,
764 		int timeout)
765 {
766 	unsigned long num = 0;
767 	unsigned long eol_num = 0;
768 	unsigned long wlen;
769 	char ichar;
770 	int insert = 1;
771 	int esc_len = 0;
772 	char esc_save[8];
773 	int init_len = strlen(buf);
774 	int first = 1;
775 
776 	if (init_len)
777 		cread_add_str(buf, init_len, 1, &num, &eol_num, buf, *len);
778 
779 	while (1) {
780 #ifdef CONFIG_BOOT_RETRY_TIME
781 		while (!tstc()) {	/* while no incoming data */
782 			if (retry_time >= 0 && get_ticks() > endtime)
783 				return (-2);	/* timed out */
784 			WATCHDOG_RESET();
785 		}
786 #endif
787 		if (first && timeout) {
788 			uint64_t etime = endtick(timeout);
789 
790 			while (!tstc()) {	/* while no incoming data */
791 				if (get_ticks() >= etime)
792 					return -2;	/* timed out */
793 				WATCHDOG_RESET();
794 			}
795 			first = 0;
796 		}
797 
798 		ichar = getcmd_getch();
799 
800 		if ((ichar == '\n') || (ichar == '\r')) {
801 			putc('\n');
802 			break;
803 		}
804 
805 		/*
806 		 * handle standard linux xterm esc sequences for arrow key, etc.
807 		 */
808 		if (esc_len != 0) {
809 			if (esc_len == 1) {
810 				if (ichar == '[') {
811 					esc_save[esc_len] = ichar;
812 					esc_len = 2;
813 				} else {
814 					cread_add_str(esc_save, esc_len, insert,
815 						      &num, &eol_num, buf, *len);
816 					esc_len = 0;
817 				}
818 				continue;
819 			}
820 
821 			switch (ichar) {
822 
823 			case 'D':	/* <- key */
824 				ichar = CTL_CH('b');
825 				esc_len = 0;
826 				break;
827 			case 'C':	/* -> key */
828 				ichar = CTL_CH('f');
829 				esc_len = 0;
830 				break;	/* pass off to ^F handler */
831 			case 'H':	/* Home key */
832 				ichar = CTL_CH('a');
833 				esc_len = 0;
834 				break;	/* pass off to ^A handler */
835 			case 'A':	/* up arrow */
836 				ichar = CTL_CH('p');
837 				esc_len = 0;
838 				break;	/* pass off to ^P handler */
839 			case 'B':	/* down arrow */
840 				ichar = CTL_CH('n');
841 				esc_len = 0;
842 				break;	/* pass off to ^N handler */
843 			default:
844 				esc_save[esc_len++] = ichar;
845 				cread_add_str(esc_save, esc_len, insert,
846 					      &num, &eol_num, buf, *len);
847 				esc_len = 0;
848 				continue;
849 			}
850 		}
851 
852 		switch (ichar) {
853 		case 0x1b:
854 			if (esc_len == 0) {
855 				esc_save[esc_len] = ichar;
856 				esc_len = 1;
857 			} else {
858 				puts("impossible condition #876\n");
859 				esc_len = 0;
860 			}
861 			break;
862 
863 		case CTL_CH('a'):
864 			BEGINNING_OF_LINE();
865 			break;
866 		case CTL_CH('c'):	/* ^C - break */
867 			*buf = '\0';	/* discard input */
868 			return (-1);
869 		case CTL_CH('f'):
870 			if (num < eol_num) {
871 				getcmd_putch(buf[num]);
872 				num++;
873 			}
874 			break;
875 		case CTL_CH('b'):
876 			if (num) {
877 				getcmd_putch(CTL_BACKSPACE);
878 				num--;
879 			}
880 			break;
881 		case CTL_CH('d'):
882 			if (num < eol_num) {
883 				wlen = eol_num - num - 1;
884 				if (wlen) {
885 					memmove(&buf[num], &buf[num+1], wlen);
886 					putnstr(buf + num, wlen);
887 				}
888 
889 				getcmd_putch(' ');
890 				do {
891 					getcmd_putch(CTL_BACKSPACE);
892 				} while (wlen--);
893 				eol_num--;
894 			}
895 			break;
896 		case CTL_CH('k'):
897 			ERASE_TO_EOL();
898 			break;
899 		case CTL_CH('e'):
900 			REFRESH_TO_EOL();
901 			break;
902 		case CTL_CH('o'):
903 			insert = !insert;
904 			break;
905 		case CTL_CH('x'):
906 		case CTL_CH('u'):
907 			BEGINNING_OF_LINE();
908 			ERASE_TO_EOL();
909 			break;
910 		case DEL:
911 		case DEL7:
912 		case 8:
913 			if (num) {
914 				wlen = eol_num - num;
915 				num--;
916 				memmove(&buf[num], &buf[num+1], wlen);
917 				getcmd_putch(CTL_BACKSPACE);
918 				putnstr(buf + num, wlen);
919 				getcmd_putch(' ');
920 				do {
921 					getcmd_putch(CTL_BACKSPACE);
922 				} while (wlen--);
923 				eol_num--;
924 			}
925 			break;
926 		case CTL_CH('p'):
927 		case CTL_CH('n'):
928 		{
929 			char * hline;
930 
931 			esc_len = 0;
932 
933 			if (ichar == CTL_CH('p'))
934 				hline = hist_prev();
935 			else
936 				hline = hist_next();
937 
938 			if (!hline) {
939 				getcmd_cbeep();
940 				continue;
941 			}
942 
943 			/* nuke the current line */
944 			/* first, go home */
945 			BEGINNING_OF_LINE();
946 
947 			/* erase to end of line */
948 			ERASE_TO_EOL();
949 
950 			/* copy new line into place and display */
951 			strcpy(buf, hline);
952 			eol_num = strlen(buf);
953 			REFRESH_TO_EOL();
954 			continue;
955 		}
956 #ifdef CONFIG_AUTO_COMPLETE
957 		case '\t': {
958 			int num2, col;
959 
960 			/* do not autocomplete when in the middle */
961 			if (num < eol_num) {
962 				getcmd_cbeep();
963 				break;
964 			}
965 
966 			buf[num] = '\0';
967 			col = strlen(prompt) + eol_num;
968 			num2 = num;
969 			if (cmd_auto_complete(prompt, buf, &num2, &col)) {
970 				col = num2 - num;
971 				num += col;
972 				eol_num += col;
973 			}
974 			break;
975 		}
976 #endif
977 		default:
978 			cread_add_char(ichar, insert, &num, &eol_num, buf, *len);
979 			break;
980 		}
981 	}
982 	*len = eol_num;
983 	buf[eol_num] = '\0';	/* lose the newline */
984 
985 	if (buf[0] && buf[0] != CREAD_HIST_CHAR)
986 		cread_add_to_hist(buf);
987 	hist_cur = hist_add_idx;
988 
989 	return 0;
990 }
991 
992 #endif /* CONFIG_CMDLINE_EDITING */
993 
994 /****************************************************************************/
995 
996 /*
997  * Prompt for input and read a line.
998  * If  CONFIG_BOOT_RETRY_TIME is defined and retry_time >= 0,
999  * time out when time goes past endtime (timebase time in ticks).
1000  * Return:	number of read characters
1001  *		-1 if break
1002  *		-2 if timed out
1003  */
1004 int readline (const char *const prompt)
1005 {
1006 	/*
1007 	 * If console_buffer isn't 0-length the user will be prompted to modify
1008 	 * it instead of entering it from scratch as desired.
1009 	 */
1010 	console_buffer[0] = '\0';
1011 
1012 	return readline_into_buffer(prompt, console_buffer, 0);
1013 }
1014 
1015 
1016 int readline_into_buffer(const char *const prompt, char *buffer, int timeout)
1017 {
1018 	char *p = buffer;
1019 #ifdef CONFIG_CMDLINE_EDITING
1020 	unsigned int len = CONFIG_SYS_CBSIZE;
1021 	int rc;
1022 	static int initted = 0;
1023 
1024 	/*
1025 	 * History uses a global array which is not
1026 	 * writable until after relocation to RAM.
1027 	 * Revert to non-history version if still
1028 	 * running from flash.
1029 	 */
1030 	if (gd->flags & GD_FLG_RELOC) {
1031 		if (!initted) {
1032 			hist_init();
1033 			initted = 1;
1034 		}
1035 
1036 		if (prompt)
1037 			puts (prompt);
1038 
1039 		rc = cread_line(prompt, p, &len, timeout);
1040 		return rc < 0 ? rc : len;
1041 
1042 	} else {
1043 #endif	/* CONFIG_CMDLINE_EDITING */
1044 	char * p_buf = p;
1045 	int	n = 0;				/* buffer index		*/
1046 	int	plen = 0;			/* prompt length	*/
1047 	int	col;				/* output column cnt	*/
1048 	char	c;
1049 
1050 	/* print prompt */
1051 	if (prompt) {
1052 		plen = strlen (prompt);
1053 		puts (prompt);
1054 	}
1055 	col = plen;
1056 
1057 	for (;;) {
1058 #ifdef CONFIG_BOOT_RETRY_TIME
1059 		while (!tstc()) {	/* while no incoming data */
1060 			if (retry_time >= 0 && get_ticks() > endtime)
1061 				return (-2);	/* timed out */
1062 			WATCHDOG_RESET();
1063 		}
1064 #endif
1065 		WATCHDOG_RESET();		/* Trigger watchdog, if needed */
1066 
1067 #ifdef CONFIG_SHOW_ACTIVITY
1068 		while (!tstc()) {
1069 			show_activity(0);
1070 			WATCHDOG_RESET();
1071 		}
1072 #endif
1073 		c = getc();
1074 
1075 		/*
1076 		 * Special character handling
1077 		 */
1078 		switch (c) {
1079 		case '\r':				/* Enter		*/
1080 		case '\n':
1081 			*p = '\0';
1082 			puts ("\r\n");
1083 			return (p - p_buf);
1084 
1085 		case '\0':				/* nul			*/
1086 			continue;
1087 
1088 		case 0x03:				/* ^C - break		*/
1089 			p_buf[0] = '\0';	/* discard input */
1090 			return (-1);
1091 
1092 		case 0x15:				/* ^U - erase line	*/
1093 			while (col > plen) {
1094 				puts (erase_seq);
1095 				--col;
1096 			}
1097 			p = p_buf;
1098 			n = 0;
1099 			continue;
1100 
1101 		case 0x17:				/* ^W - erase word	*/
1102 			p=delete_char(p_buf, p, &col, &n, plen);
1103 			while ((n > 0) && (*p != ' ')) {
1104 				p=delete_char(p_buf, p, &col, &n, plen);
1105 			}
1106 			continue;
1107 
1108 		case 0x08:				/* ^H  - backspace	*/
1109 		case 0x7F:				/* DEL - backspace	*/
1110 			p=delete_char(p_buf, p, &col, &n, plen);
1111 			continue;
1112 
1113 		default:
1114 			/*
1115 			 * Must be a normal character then
1116 			 */
1117 			if (n < CONFIG_SYS_CBSIZE-2) {
1118 				if (c == '\t') {	/* expand TABs		*/
1119 #ifdef CONFIG_AUTO_COMPLETE
1120 					/* if auto completion triggered just continue */
1121 					*p = '\0';
1122 					if (cmd_auto_complete(prompt, console_buffer, &n, &col)) {
1123 						p = p_buf + n;	/* reset */
1124 						continue;
1125 					}
1126 #endif
1127 					puts (tab_seq+(col&07));
1128 					col += 8 - (col&07);
1129 				} else {
1130 					char buf[2];
1131 
1132 					/*
1133 					 * Echo input using puts() to force am
1134 					 * LCD flush if we are using an LCD
1135 					 */
1136 					++col;
1137 					buf[0] = c;
1138 					buf[1] = '\0';
1139 					puts(buf);
1140 				}
1141 				*p++ = c;
1142 				++n;
1143 			} else {			/* Buffer full		*/
1144 				putc ('\a');
1145 			}
1146 		}
1147 	}
1148 #ifdef CONFIG_CMDLINE_EDITING
1149 	}
1150 #endif
1151 }
1152 
1153 /****************************************************************************/
1154 
1155 static char * delete_char (char *buffer, char *p, int *colp, int *np, int plen)
1156 {
1157 	char *s;
1158 
1159 	if (*np == 0) {
1160 		return (p);
1161 	}
1162 
1163 	if (*(--p) == '\t') {			/* will retype the whole line	*/
1164 		while (*colp > plen) {
1165 			puts (erase_seq);
1166 			(*colp)--;
1167 		}
1168 		for (s=buffer; s<p; ++s) {
1169 			if (*s == '\t') {
1170 				puts (tab_seq+((*colp) & 07));
1171 				*colp += 8 - ((*colp) & 07);
1172 			} else {
1173 				++(*colp);
1174 				putc (*s);
1175 			}
1176 		}
1177 	} else {
1178 		puts (erase_seq);
1179 		(*colp)--;
1180 	}
1181 	(*np)--;
1182 	return (p);
1183 }
1184 
1185 /****************************************************************************/
1186 
1187 int parse_line (char *line, char *argv[])
1188 {
1189 	int nargs = 0;
1190 
1191 #ifdef DEBUG_PARSER
1192 	printf ("parse_line: \"%s\"\n", line);
1193 #endif
1194 	while (nargs < CONFIG_SYS_MAXARGS) {
1195 
1196 		/* skip any white space */
1197 		while (isblank(*line))
1198 			++line;
1199 
1200 		if (*line == '\0') {	/* end of line, no more args	*/
1201 			argv[nargs] = NULL;
1202 #ifdef DEBUG_PARSER
1203 		printf ("parse_line: nargs=%d\n", nargs);
1204 #endif
1205 			return (nargs);
1206 		}
1207 
1208 		argv[nargs++] = line;	/* begin of argument string	*/
1209 
1210 		/* find end of string */
1211 		while (*line && !isblank(*line))
1212 			++line;
1213 
1214 		if (*line == '\0') {	/* end of line, no more args	*/
1215 			argv[nargs] = NULL;
1216 #ifdef DEBUG_PARSER
1217 		printf ("parse_line: nargs=%d\n", nargs);
1218 #endif
1219 			return (nargs);
1220 		}
1221 
1222 		*line++ = '\0';		/* terminate current arg	 */
1223 	}
1224 
1225 	printf ("** Too many args (max. %d) **\n", CONFIG_SYS_MAXARGS);
1226 
1227 #ifdef DEBUG_PARSER
1228 	printf ("parse_line: nargs=%d\n", nargs);
1229 #endif
1230 	return (nargs);
1231 }
1232 
1233 /****************************************************************************/
1234 
1235 #ifndef CONFIG_SYS_HUSH_PARSER
1236 static void process_macros (const char *input, char *output)
1237 {
1238 	char c, prev;
1239 	const char *varname_start = NULL;
1240 	int inputcnt = strlen (input);
1241 	int outputcnt = CONFIG_SYS_CBSIZE;
1242 	int state = 0;		/* 0 = waiting for '$'  */
1243 
1244 	/* 1 = waiting for '(' or '{' */
1245 	/* 2 = waiting for ')' or '}' */
1246 	/* 3 = waiting for '''  */
1247 #ifdef DEBUG_PARSER
1248 	char *output_start = output;
1249 
1250 	printf ("[PROCESS_MACROS] INPUT len %d: \"%s\"\n", strlen (input),
1251 		input);
1252 #endif
1253 
1254 	prev = '\0';		/* previous character   */
1255 
1256 	while (inputcnt && outputcnt) {
1257 		c = *input++;
1258 		inputcnt--;
1259 
1260 		if (state != 3) {
1261 			/* remove one level of escape characters */
1262 			if ((c == '\\') && (prev != '\\')) {
1263 				if (inputcnt-- == 0)
1264 					break;
1265 				prev = c;
1266 				c = *input++;
1267 			}
1268 		}
1269 
1270 		switch (state) {
1271 		case 0:	/* Waiting for (unescaped) $    */
1272 			if ((c == '\'') && (prev != '\\')) {
1273 				state = 3;
1274 				break;
1275 			}
1276 			if ((c == '$') && (prev != '\\')) {
1277 				state++;
1278 			} else {
1279 				*(output++) = c;
1280 				outputcnt--;
1281 			}
1282 			break;
1283 		case 1:	/* Waiting for (        */
1284 			if (c == '(' || c == '{') {
1285 				state++;
1286 				varname_start = input;
1287 			} else {
1288 				state = 0;
1289 				*(output++) = '$';
1290 				outputcnt--;
1291 
1292 				if (outputcnt) {
1293 					*(output++) = c;
1294 					outputcnt--;
1295 				}
1296 			}
1297 			break;
1298 		case 2:	/* Waiting for )        */
1299 			if (c == ')' || c == '}') {
1300 				int i;
1301 				char envname[CONFIG_SYS_CBSIZE], *envval;
1302 				int envcnt = input - varname_start - 1;	/* Varname # of chars */
1303 
1304 				/* Get the varname */
1305 				for (i = 0; i < envcnt; i++) {
1306 					envname[i] = varname_start[i];
1307 				}
1308 				envname[i] = 0;
1309 
1310 				/* Get its value */
1311 				envval = getenv (envname);
1312 
1313 				/* Copy into the line if it exists */
1314 				if (envval != NULL)
1315 					while ((*envval) && outputcnt) {
1316 						*(output++) = *(envval++);
1317 						outputcnt--;
1318 					}
1319 				/* Look for another '$' */
1320 				state = 0;
1321 			}
1322 			break;
1323 		case 3:	/* Waiting for '        */
1324 			if ((c == '\'') && (prev != '\\')) {
1325 				state = 0;
1326 			} else {
1327 				*(output++) = c;
1328 				outputcnt--;
1329 			}
1330 			break;
1331 		}
1332 		prev = c;
1333 	}
1334 
1335 	if (outputcnt)
1336 		*output = 0;
1337 	else
1338 		*(output - 1) = 0;
1339 
1340 #ifdef DEBUG_PARSER
1341 	printf ("[PROCESS_MACROS] OUTPUT len %d: \"%s\"\n",
1342 		strlen (output_start), output_start);
1343 #endif
1344 }
1345 
1346 /****************************************************************************
1347  * returns:
1348  *	1  - command executed, repeatable
1349  *	0  - command executed but not repeatable, interrupted commands are
1350  *	     always considered not repeatable
1351  *	-1 - not executed (unrecognized, bootd recursion or too many args)
1352  *           (If cmd is NULL or "" or longer than CONFIG_SYS_CBSIZE-1 it is
1353  *           considered unrecognized)
1354  *
1355  * WARNING:
1356  *
1357  * We must create a temporary copy of the command since the command we get
1358  * may be the result from getenv(), which returns a pointer directly to
1359  * the environment data, which may change magicly when the command we run
1360  * creates or modifies environment variables (like "bootp" does).
1361  */
1362 static int builtin_run_command(const char *cmd, int flag)
1363 {
1364 	char cmdbuf[CONFIG_SYS_CBSIZE];	/* working copy of cmd		*/
1365 	char *token;			/* start of token in cmdbuf	*/
1366 	char *sep;			/* end of token (separator) in cmdbuf */
1367 	char finaltoken[CONFIG_SYS_CBSIZE];
1368 	char *str = cmdbuf;
1369 	char *argv[CONFIG_SYS_MAXARGS + 1];	/* NULL terminated	*/
1370 	int argc, inquotes;
1371 	int repeatable = 1;
1372 	int rc = 0;
1373 
1374 #ifdef DEBUG_PARSER
1375 	printf ("[RUN_COMMAND] cmd[%p]=\"", cmd);
1376 	puts (cmd ? cmd : "NULL");	/* use puts - string may be loooong */
1377 	puts ("\"\n");
1378 #endif
1379 
1380 	clear_ctrlc();		/* forget any previous Control C */
1381 
1382 	if (!cmd || !*cmd) {
1383 		return -1;	/* empty command */
1384 	}
1385 
1386 	if (strlen(cmd) >= CONFIG_SYS_CBSIZE) {
1387 		puts ("## Command too long!\n");
1388 		return -1;
1389 	}
1390 
1391 	strcpy (cmdbuf, cmd);
1392 
1393 	/* Process separators and check for invalid
1394 	 * repeatable commands
1395 	 */
1396 
1397 #ifdef DEBUG_PARSER
1398 	printf ("[PROCESS_SEPARATORS] %s\n", cmd);
1399 #endif
1400 	while (*str) {
1401 
1402 		/*
1403 		 * Find separator, or string end
1404 		 * Allow simple escape of ';' by writing "\;"
1405 		 */
1406 		for (inquotes = 0, sep = str; *sep; sep++) {
1407 			if ((*sep=='\'') &&
1408 			    (*(sep-1) != '\\'))
1409 				inquotes=!inquotes;
1410 
1411 			if (!inquotes &&
1412 			    (*sep == ';') &&	/* separator		*/
1413 			    ( sep != str) &&	/* past string start	*/
1414 			    (*(sep-1) != '\\'))	/* and NOT escaped	*/
1415 				break;
1416 		}
1417 
1418 		/*
1419 		 * Limit the token to data between separators
1420 		 */
1421 		token = str;
1422 		if (*sep) {
1423 			str = sep + 1;	/* start of command for next pass */
1424 			*sep = '\0';
1425 		}
1426 		else
1427 			str = sep;	/* no more commands for next pass */
1428 #ifdef DEBUG_PARSER
1429 		printf ("token: \"%s\"\n", token);
1430 #endif
1431 
1432 		/* find macros in this token and replace them */
1433 		process_macros (token, finaltoken);
1434 
1435 		/* Extract arguments */
1436 		if ((argc = parse_line (finaltoken, argv)) == 0) {
1437 			rc = -1;	/* no command at all */
1438 			continue;
1439 		}
1440 
1441 		if (cmd_process(flag, argc, argv, &repeatable, NULL))
1442 			rc = -1;
1443 
1444 		/* Did the user stop this? */
1445 		if (had_ctrlc ())
1446 			return -1;	/* if stopped then not repeatable */
1447 	}
1448 
1449 	return rc ? rc : repeatable;
1450 }
1451 #endif
1452 
1453 /*
1454  * Run a command using the selected parser.
1455  *
1456  * @param cmd	Command to run
1457  * @param flag	Execution flags (CMD_FLAG_...)
1458  * @return 0 on success, or != 0 on error.
1459  */
1460 int run_command(const char *cmd, int flag)
1461 {
1462 #ifndef CONFIG_SYS_HUSH_PARSER
1463 	/*
1464 	 * builtin_run_command can return 0 or 1 for success, so clean up
1465 	 * its result.
1466 	 */
1467 	if (builtin_run_command(cmd, flag) == -1)
1468 		return 1;
1469 
1470 	return 0;
1471 #else
1472 	return parse_string_outer(cmd,
1473 			FLAG_PARSE_SEMICOLON | FLAG_EXIT_FROM_LOOP);
1474 #endif
1475 }
1476 
1477 #ifndef CONFIG_SYS_HUSH_PARSER
1478 /**
1479  * Execute a list of command separated by ; or \n using the built-in parser.
1480  *
1481  * This function cannot take a const char * for the command, since if it
1482  * finds newlines in the string, it replaces them with \0.
1483  *
1484  * @param cmd	String containing list of commands
1485  * @param flag	Execution flags (CMD_FLAG_...)
1486  * @return 0 on success, or != 0 on error.
1487  */
1488 static int builtin_run_command_list(char *cmd, int flag)
1489 {
1490 	char *line, *next;
1491 	int rcode = 0;
1492 
1493 	/*
1494 	 * Break into individual lines, and execute each line; terminate on
1495 	 * error.
1496 	 */
1497 	line = next = cmd;
1498 	while (*next) {
1499 		if (*next == '\n') {
1500 			*next = '\0';
1501 			/* run only non-empty commands */
1502 			if (*line) {
1503 				debug("** exec: \"%s\"\n", line);
1504 				if (builtin_run_command(line, 0) < 0) {
1505 					rcode = 1;
1506 					break;
1507 				}
1508 			}
1509 			line = next + 1;
1510 		}
1511 		++next;
1512 	}
1513 	if (rcode == 0 && *line)
1514 		rcode = (builtin_run_command(line, 0) >= 0);
1515 
1516 	return rcode;
1517 }
1518 #endif
1519 
1520 int run_command_list(const char *cmd, int len, int flag)
1521 {
1522 	int need_buff = 1;
1523 	char *buff = (char *)cmd;	/* cast away const */
1524 	int rcode = 0;
1525 
1526 	if (len == -1) {
1527 		len = strlen(cmd);
1528 #ifdef CONFIG_SYS_HUSH_PARSER
1529 		/* hush will never change our string */
1530 		need_buff = 0;
1531 #else
1532 		/* the built-in parser will change our string if it sees \n */
1533 		need_buff = strchr(cmd, '\n') != NULL;
1534 #endif
1535 	}
1536 	if (need_buff) {
1537 		buff = malloc(len + 1);
1538 		if (!buff)
1539 			return 1;
1540 		memcpy(buff, cmd, len);
1541 		buff[len] = '\0';
1542 	}
1543 #ifdef CONFIG_SYS_HUSH_PARSER
1544 	rcode = parse_string_outer(buff, FLAG_PARSE_SEMICOLON);
1545 #else
1546 	/*
1547 	 * This function will overwrite any \n it sees with a \0, which
1548 	 * is why it can't work with a const char *. Here we are making
1549 	 * using of internal knowledge of this function, to avoid always
1550 	 * doing a malloc() which is actually required only in a case that
1551 	 * is pretty rare.
1552 	 */
1553 	rcode = builtin_run_command_list(buff, flag);
1554 	if (need_buff)
1555 		free(buff);
1556 #endif
1557 
1558 	return rcode;
1559 }
1560 
1561 /****************************************************************************/
1562 
1563 #if defined(CONFIG_CMD_RUN)
1564 int do_run (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
1565 {
1566 	int i;
1567 
1568 	if (argc < 2)
1569 		return CMD_RET_USAGE;
1570 
1571 	for (i=1; i<argc; ++i) {
1572 		char *arg;
1573 
1574 		if ((arg = getenv (argv[i])) == NULL) {
1575 			printf ("## Error: \"%s\" not defined\n", argv[i]);
1576 			return 1;
1577 		}
1578 
1579 		if (run_command(arg, flag) != 0)
1580 			return 1;
1581 	}
1582 	return 0;
1583 }
1584 #endif
1585