xref: /openbmc/u-boot/common/main.c (revision 3b57fe0a)
1 /*
2  * (C) Copyright 2000
3  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
4  *
5  * See file CREDITS for list of people who contributed to this
6  * project.
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License as
10  * published by the Free Software Foundation; either version 2 of
11  * the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
21  * MA 02111-1307 USA
22  */
23 
24 /* #define	DEBUG	*/
25 
26 #include <common.h>
27 #include <watchdog.h>
28 #include <command.h>
29 #include <cmd_nvedit.h>
30 #include <cmd_bootm.h>
31 #include <malloc.h>
32 #if defined(CONFIG_BOOT_RETRY_TIME) && defined(CONFIG_RESET_TO_RETRY)
33 #include <cmd_boot.h>		/* for do_reset() prototype */
34 #endif
35 
36 #ifdef CFG_HUSH_PARSER
37 #include <hush.h>
38 #endif
39 
40 #define MAX_DELAY_STOP_STR 32
41 
42 static char * delete_char (char *buffer, char *p, int *colp, int *np, int plen);
43 static int parse_line (char *, char *[]);
44 #if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
45 static int abortboot(int);
46 #endif
47 
48 #undef DEBUG_PARSER
49 
50 char        console_buffer[CFG_CBSIZE];		/* console I/O buffer	*/
51 
52 static char erase_seq[] = "\b \b";		/* erase sequence	*/
53 static char   tab_seq[] = "        ";		/* used to expand TABs	*/
54 
55 #ifdef CONFIG_BOOT_RETRY_TIME
56 static uint64_t endtime = 0;  /* must be set, default is instant timeout */
57 static int      retry_time = -1; /* -1 so can call readline before main_loop */
58 #endif
59 
60 #define	endtick(seconds) (get_ticks() + (uint64_t)(seconds) * get_tbclk())
61 
62 #ifndef CONFIG_BOOT_RETRY_MIN
63 #define CONFIG_BOOT_RETRY_MIN CONFIG_BOOT_RETRY_TIME
64 #endif
65 
66 #ifdef CONFIG_MODEM_SUPPORT
67 int do_mdm_init = 0;
68 extern void mdm_init(void); /* defined in board.c */
69 #endif
70 
71 /***************************************************************************
72  * Watch for 'delay' seconds for autoboot stop or autoboot delay string.
73  * returns: 0 -  no key string, allow autoboot
74  *          1 - got key string, abort
75  */
76 #if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
77 # if defined(CONFIG_AUTOBOOT_KEYED)
78 static __inline__ int abortboot(int bootdelay)
79 {
80 	int abort = 0;
81 	uint64_t etime = endtick(bootdelay);
82 	struct
83 	{
84 		char* str;
85 		u_int len;
86 		int retry;
87 	}
88 	delaykey [] =
89 	{
90 		{ str: getenv ("bootdelaykey"),  retry: 1 },
91 		{ str: getenv ("bootdelaykey2"), retry: 1 },
92 		{ str: getenv ("bootstopkey"),   retry: 0 },
93 		{ str: getenv ("bootstopkey2"),  retry: 0 },
94 	};
95 
96 	char presskey [MAX_DELAY_STOP_STR];
97 	u_int presskey_len = 0;
98 	u_int presskey_max = 0;
99 	u_int i;
100 
101 #  ifdef CONFIG_AUTOBOOT_PROMPT
102 	printf (CONFIG_AUTOBOOT_PROMPT, bootdelay);
103 #  endif
104 
105 #  ifdef CONFIG_AUTOBOOT_DELAY_STR
106 	if (delaykey[0].str == NULL)
107 		delaykey[0].str = CONFIG_AUTOBOOT_DELAY_STR;
108 #  endif
109 #  ifdef CONFIG_AUTOBOOT_DELAY_STR2
110 	if (delaykey[1].str == NULL)
111 		delaykey[1].str = CONFIG_AUTOBOOT_DELAY_STR2;
112 #  endif
113 #  ifdef CONFIG_AUTOBOOT_STOP_STR
114 	if (delaykey[2].str == NULL)
115 		delaykey[2].str = CONFIG_AUTOBOOT_STOP_STR;
116 #  endif
117 #  ifdef CONFIG_AUTOBOOT_STOP_STR2
118 	if (delaykey[3].str == NULL)
119 		delaykey[3].str = CONFIG_AUTOBOOT_STOP_STR2;
120 #  endif
121 
122 	for (i = 0; i < sizeof(delaykey) / sizeof(delaykey[0]); i ++) {
123 		delaykey[i].len = delaykey[i].str == NULL ?
124 				    0 : strlen (delaykey[i].str);
125 		delaykey[i].len = delaykey[i].len > MAX_DELAY_STOP_STR ?
126 				    MAX_DELAY_STOP_STR : delaykey[i].len;
127 
128 		presskey_max = presskey_max > delaykey[i].len ?
129 				    presskey_max : delaykey[i].len;
130 
131 #  if DEBUG_BOOTKEYS
132 		printf("%s key:<%s>\n",
133 		       delaykey[i].retry ? "delay" : "stop",
134 		       delaykey[i].str ? delaykey[i].str : "NULL");
135 #  endif
136 	}
137 
138 	/* In order to keep up with incoming data, check timeout only
139 	 * when catch up.
140 	 */
141 	while (!abort && get_ticks() <= etime) {
142 		for (i = 0; i < sizeof(delaykey) / sizeof(delaykey[0]); i ++) {
143 			if (delaykey[i].len > 0 &&
144 			    presskey_len >= delaykey[i].len &&
145 			    memcmp (presskey + presskey_len - delaykey[i].len,
146 		        	    delaykey[i].str,
147 				    delaykey[i].len) == 0) {
148 #  if DEBUG_BOOTKEYS
149 				printf("got %skey\n",
150 				       delaykey[i].retry ? "delay" : "stop");
151 #  endif
152 
153 #  ifdef CONFIG_BOOT_RETRY_TIME
154 				/* don't retry auto boot */
155 				if (! delaykey[i].retry)
156 					retry_time = -1;
157 #  endif
158 				abort = 1;
159 			}
160 		}
161 
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 #  if DEBUG_BOOTKEYS
175 	if (!abort)
176 		printf("key timeout\n");
177 #  endif
178 
179 	return abort;
180 }
181 
182 # else	/* !defined(CONFIG_AUTOBOOT_KEYED) */
183 
184 #ifdef CONFIG_MENUKEY
185 static int menukey = 0;
186 #endif
187 
188 static __inline__ int abortboot(int bootdelay)
189 {
190 	int abort = 0;
191 
192 #ifdef CONFIG_MENUPROMPT
193 	printf(CONFIG_MENUPROMPT, bootdelay);
194 #else
195 	printf("Hit any key to stop autoboot: %2d ", bootdelay);
196 #endif
197 
198 #if defined CONFIG_ZERO_BOOTDELAY_CHECK
199         /*
200          * Check if key already pressed
201          * Don't check if bootdelay < 0
202          */
203 	if (bootdelay >= 0) {
204 		if (tstc()) {	/* we got a key press	*/
205 			(void) getc();  /* consume input	*/
206 			printf ("\b\b\b 0\n");
207 			return 1; 	/* don't auto boot	*/
208 		}
209         }
210 #endif
211 
212 	while (bootdelay > 0) {
213 		int i;
214 
215 		--bootdelay;
216 		/* delay 100 * 10ms */
217 		for (i=0; !abort && i<100; ++i) {
218 			if (tstc()) {	/* we got a key press	*/
219 				abort  = 1;	/* don't auto boot	*/
220 				bootdelay = 0;	/* no more delay	*/
221 # ifdef CONFIG_MENUKEY
222 				menukey = getc();
223 # else
224 				(void) getc();  /* consume input	*/
225 # endif
226 				break;
227 			}
228 			udelay (10000);
229 		}
230 
231 		printf ("\b\b\b%2d ", bootdelay);
232 	}
233 
234 	putc ('\n');
235 
236 	return abort;
237 }
238 # endif	/* CONFIG_AUTOBOOT_KEYED */
239 #endif	/* CONFIG_BOOTDELAY >= 0  */
240 
241 /****************************************************************************/
242 
243 void main_loop (void)
244 {
245 #ifndef CFG_HUSH_PARSER
246 	static char lastcommand[CFG_CBSIZE] = { 0, };
247 	int len;
248 	int rc = 1;
249 	int flag;
250 #endif
251 
252 #if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
253 	char *s;
254 	int bootdelay;
255 #endif
256 #ifdef CONFIG_PREBOOT
257 	char *p;
258 #endif
259 
260 #if defined(CONFIG_VFD) && defined(VFD_TEST_LOGO)
261 	ulong bmp = 0;		/* default bitmap */
262 	extern int trab_vfd (ulong bitmap);
263 
264 #ifdef CONFIG_MODEM_SUPPORT
265 	if (do_mdm_init)
266 		bmp = 1;	/* alternate bitmap */
267 #endif
268 	trab_vfd (bmp);
269 #endif	/* CONFIG_VFD && VFD_TEST_LOGO */
270 
271 #ifdef CONFIG_MODEM_SUPPORT
272 	debug ("DEBUG: main_loop:   do_mdm_init=%d\n", do_mdm_init);
273 	if (do_mdm_init) {
274 		uchar *str = strdup(getenv("mdm_cmd"));
275 		setenv ("preboot", str);  /* set or delete definition */
276 		if (str != NULL)
277 			free (str);
278 		mdm_init(); /* wait for modem connection */
279 	}
280 #endif  /* CONFIG_MODEM_SUPPORT */
281 
282 #ifdef CONFIG_VERSION_VARIABLE
283 	{
284 		extern char version_string[];
285 		char *str = getenv("ver");
286 
287 		if (!str)
288 			setenv ("ver", version_string);  /* set version variable */
289 	}
290 #endif /* CONFIG_VERSION_VARIABLE */
291 
292 #ifdef CFG_HUSH_PARSER
293 	u_boot_hush_start ();
294 #endif
295 
296 #ifdef CONFIG_PREBOOT
297 	if ((p = getenv ("preboot")) != NULL) {
298 # ifdef CONFIG_AUTOBOOT_KEYED
299 		int prev = disable_ctrlc(1);	/* disable Control C checking */
300 # endif
301 
302 # ifndef CFG_HUSH_PARSER
303 		run_command (p, 0);
304 # else
305 		parse_string_outer(p, FLAG_PARSE_SEMICOLON |
306 				    FLAG_EXIT_FROM_LOOP);
307 # endif
308 
309 # ifdef CONFIG_AUTOBOOT_KEYED
310 		disable_ctrlc(prev);	/* restore Control C checking */
311 # endif
312 	}
313 #endif /* CONFIG_PREBOOT */
314 
315 #if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
316 	s = getenv ("bootdelay");
317 	bootdelay = s ? (int)simple_strtol(s, NULL, 10) : CONFIG_BOOTDELAY;
318 
319 	debug ("### main_loop entered: bootdelay=%d\n\n", bootdelay);
320 
321 # ifdef CONFIG_BOOT_RETRY_TIME
322 	s = getenv ("bootretry");
323 	if (s != NULL)
324 		retry_time = (int)simple_strtoul(s, NULL, 10);
325 	else
326 		retry_time =  CONFIG_BOOT_RETRY_TIME;
327 	if (retry_time >= 0 && retry_time < CONFIG_BOOT_RETRY_MIN)
328 		retry_time = CONFIG_BOOT_RETRY_MIN;
329 # endif	/* CONFIG_BOOT_RETRY_TIME */
330 
331 	s = getenv ("bootcmd");
332 
333 	debug ("### main_loop: bootcmd=\"%s\"\n", s ? s : "<UNDEFINED>");
334 
335 	if (bootdelay >= 0 && s && !abortboot (bootdelay)) {
336 # ifdef CONFIG_AUTOBOOT_KEYED
337 		int prev = disable_ctrlc(1);	/* disable Control C checking */
338 # endif
339 
340 # ifndef CFG_HUSH_PARSER
341 		run_command (s, 0);
342 # else
343 		parse_string_outer(s, FLAG_PARSE_SEMICOLON |
344 				    FLAG_EXIT_FROM_LOOP);
345 # endif
346 
347 # ifdef CONFIG_AUTOBOOT_KEYED
348 		disable_ctrlc(prev);	/* restore Control C checking */
349 # endif
350 	}
351 
352 # ifdef CONFIG_MENUKEY
353 	if (menukey == CONFIG_MENUKEY) {
354 	    s = getenv("menucmd");
355 	    if (s) {
356 # ifndef CFG_HUSH_PARSER
357 		run_command (s, bd, 0);
358 # else
359 		parse_string_outer(s, FLAG_PARSE_SEMICOLON |
360 				    FLAG_EXIT_FROM_LOOP);
361 # endif
362 	    }
363 	}
364 #endif /* CONFIG_MENUKEY */
365 #endif	/* CONFIG_BOOTDELAY */
366 
367 #ifdef CONFIG_AMIGAONEG3SE
368 	{
369 	    extern void video_banner(void);
370 	    video_banner();
371 	}
372 #endif
373 
374 	/*
375 	 * Main Loop for Monitor Command Processing
376 	 */
377 #ifdef CFG_HUSH_PARSER
378 	parse_file_outer();
379 	/* This point is never reached */
380 	for (;;);
381 #else
382 	for (;;) {
383 #ifdef CONFIG_BOOT_RETRY_TIME
384 		if (rc >= 0) {
385 			/* Saw enough of a valid command to
386 			 * restart the timeout.
387 			 */
388 			reset_cmd_timeout();
389 		}
390 #endif
391 		len = readline (CFG_PROMPT);
392 
393 		flag = 0;	/* assume no special flags for now */
394 		if (len > 0)
395 			strcpy (lastcommand, console_buffer);
396 		else if (len == 0)
397 			flag |= CMD_FLAG_REPEAT;
398 #ifdef CONFIG_BOOT_RETRY_TIME
399 		else if (len == -2) {
400 			/* -2 means timed out, retry autoboot
401 			 */
402 			printf("\nTimed out waiting for command\n");
403 # ifdef CONFIG_RESET_TO_RETRY
404 			/* Reinit board to run initialization code again */
405 			do_reset (NULL, 0, 0, NULL);
406 # else
407 			return;		/* retry autoboot */
408 # endif
409 		}
410 #endif
411 
412 		if (len == -1)
413 			printf ("<INTERRUPT>\n");
414 		else
415 			rc = run_command (lastcommand, flag);
416 
417 		if (rc <= 0) {
418 			/* invalid command or not repeatable, forget it */
419 			lastcommand[0] = 0;
420 		}
421 	}
422 #endif /*CFG_HUSH_PARSER*/
423 }
424 
425 /***************************************************************************
426  * reset command line timeout to retry_time seconds
427  */
428 #ifdef CONFIG_BOOT_RETRY_TIME
429 void reset_cmd_timeout(void)
430 {
431 	endtime = endtick(retry_time);
432 }
433 #endif
434 
435 /****************************************************************************/
436 
437 /*
438  * Prompt for input and read a line.
439  * If  CONFIG_BOOT_RETRY_TIME is defined and retry_time >= 0,
440  * time out when time goes past endtime (timebase time in ticks).
441  * Return:	number of read characters
442  *		-1 if break
443  *		-2 if timed out
444  */
445 int readline (const char *const prompt)
446 {
447 	char   *p = console_buffer;
448 	int	n = 0;				/* buffer index		*/
449 	int	plen = 0;			/* prompt length	*/
450 	int	col;				/* output column cnt	*/
451 	char	c;
452 
453 	/* print prompt */
454 	if (prompt) {
455 		plen = strlen (prompt);
456 		puts (prompt);
457 	}
458 	col = plen;
459 
460 	for (;;) {
461 #ifdef CONFIG_BOOT_RETRY_TIME
462 		while (!tstc()) {	/* while no incoming data */
463 			if (retry_time >= 0 && get_ticks() > endtime)
464 				return (-2);	/* timed out */
465 		}
466 #endif
467 		WATCHDOG_RESET();		/* Trigger watchdog, if needed */
468 
469 #ifdef CONFIG_SHOW_ACTIVITY
470 		while (!tstc()) {
471 			extern void show_activity(int arg);
472 			show_activity(0);
473 		}
474 #endif
475 		c = getc();
476 
477 		/*
478 		 * Special character handling
479 		 */
480 		switch (c) {
481 		case '\r':				/* Enter		*/
482 		case '\n':
483 			*p = '\0';
484 			puts ("\r\n");
485 			return (p - console_buffer);
486 
487 		case 0x03:				/* ^C - break		*/
488 			console_buffer[0] = '\0';	/* discard input */
489 			return (-1);
490 
491 		case 0x15:				/* ^U - erase line	*/
492 			while (col > plen) {
493 				puts (erase_seq);
494 				--col;
495 			}
496 			p = console_buffer;
497 			n = 0;
498 			continue;
499 
500 		case 0x17:				/* ^W - erase word 	*/
501 			p=delete_char(console_buffer, p, &col, &n, plen);
502 			while ((n > 0) && (*p != ' ')) {
503 				p=delete_char(console_buffer, p, &col, &n, plen);
504 			}
505 			continue;
506 
507 		case 0x08:				/* ^H  - backspace	*/
508 		case 0x7F:				/* DEL - backspace	*/
509 			p=delete_char(console_buffer, p, &col, &n, plen);
510 			continue;
511 
512 		default:
513 			/*
514 			 * Must be a normal character then
515 			 */
516 			if (n < CFG_CBSIZE-2) {
517 				if (c == '\t') {	/* expand TABs		*/
518 					puts (tab_seq+(col&07));
519 					col += 8 - (col&07);
520 				} else {
521 					++col;		/* echo input		*/
522 					putc (c);
523 				}
524 				*p++ = c;
525 				++n;
526 			} else {			/* Buffer full		*/
527 				putc ('\a');
528 			}
529 		}
530 	}
531 }
532 
533 /****************************************************************************/
534 
535 static char * delete_char (char *buffer, char *p, int *colp, int *np, int plen)
536 {
537 	char *s;
538 
539 	if (*np == 0) {
540 		return (p);
541 	}
542 
543 	if (*(--p) == '\t') {			/* will retype the whole line	*/
544 		while (*colp > plen) {
545 			puts (erase_seq);
546 			(*colp)--;
547 		}
548 		for (s=buffer; s<p; ++s) {
549 			if (*s == '\t') {
550 				puts (tab_seq+((*colp) & 07));
551 				*colp += 8 - ((*colp) & 07);
552 			} else {
553 				++(*colp);
554 				putc (*s);
555 			}
556 		}
557 	} else {
558 		puts (erase_seq);
559 		(*colp)--;
560 	}
561 	(*np)--;
562 	return (p);
563 }
564 
565 /****************************************************************************/
566 
567 int parse_line (char *line, char *argv[])
568 {
569 	int nargs = 0;
570 
571 #ifdef DEBUG_PARSER
572 	printf ("parse_line: \"%s\"\n", line);
573 #endif
574 	while (nargs < CFG_MAXARGS) {
575 
576 		/* skip any white space */
577 		while ((*line == ' ') || (*line == '\t')) {
578 			++line;
579 		}
580 
581 		if (*line == '\0') {	/* end of line, no more args	*/
582 			argv[nargs] = NULL;
583 #ifdef DEBUG_PARSER
584 		printf ("parse_line: nargs=%d\n", nargs);
585 #endif
586 			return (nargs);
587 		}
588 
589 		argv[nargs++] = line;	/* begin of argument string	*/
590 
591 		/* find end of string */
592 		while (*line && (*line != ' ') && (*line != '\t')) {
593 			++line;
594 		}
595 
596 		if (*line == '\0') {	/* end of line, no more args	*/
597 			argv[nargs] = NULL;
598 #ifdef DEBUG_PARSER
599 		printf ("parse_line: nargs=%d\n", nargs);
600 #endif
601 			return (nargs);
602 		}
603 
604 		*line++ = '\0';		/* terminate current arg	 */
605 	}
606 
607 	printf ("** Too many args (max. %d) **\n", CFG_MAXARGS);
608 
609 #ifdef DEBUG_PARSER
610 	printf ("parse_line: nargs=%d\n", nargs);
611 #endif
612 	return (nargs);
613 }
614 
615 /****************************************************************************/
616 
617 static void process_macros (const char *input, char *output)
618 {
619 	char c, prev;
620 	const char *varname_start = NULL;
621 	int inputcnt  = strlen (input);
622 	int outputcnt = CFG_CBSIZE;
623 	int state = 0;	/* 0 = waiting for '$'	*/
624 			/* 1 = waiting for '('	*/
625 			/* 2 = waiting for ')'	*/
626 	                /* 3 = waiting for '''  */
627 #ifdef DEBUG_PARSER
628 	char *output_start = output;
629 
630 	printf ("[PROCESS_MACROS] INPUT len %d: \"%s\"\n", strlen(input), input);
631 #endif
632 
633 	prev = '\0';			/* previous character	*/
634 
635 	while (inputcnt && outputcnt) {
636 	    c = *input++;
637 	    inputcnt--;
638 
639 	    if (state!=3) {
640 	    /* remove one level of escape characters */
641 	    if ((c == '\\') && (prev != '\\')) {
642 		if (inputcnt-- == 0)
643 			break;
644 		prev = c;
645 	    	c = *input++;
646 	    }
647 	    }
648 
649 	    switch (state) {
650 	    case 0:			/* Waiting for (unescaped) $	*/
651 		if ((c == '\'') && (prev != '\\')) {
652 			state = 3;
653 			break;
654 		}
655 		if ((c == '$') && (prev != '\\')) {
656 			state++;
657 		} else {
658 			*(output++) = c;
659 			outputcnt--;
660 		}
661 		break;
662 	    case 1:			/* Waiting for (	*/
663 		if (c == '(') {
664 			state++;
665 			varname_start = input;
666 		} else {
667 			state = 0;
668 			*(output++) = '$';
669 			outputcnt--;
670 
671 			if (outputcnt) {
672 				*(output++) = c;
673 				outputcnt--;
674 			}
675 		}
676 		break;
677 	    case 2:			/* Waiting for )	*/
678 		if (c == ')') {
679 			int i;
680 			char envname[CFG_CBSIZE], *envval;
681 			int envcnt = input-varname_start-1; /* Varname # of chars */
682 
683 			/* Get the varname */
684 			for (i = 0; i < envcnt; i++) {
685 				envname[i] = varname_start[i];
686 			}
687 			envname[i] = 0;
688 
689 			/* Get its value */
690 			envval = getenv (envname);
691 
692 			/* Copy into the line if it exists */
693 			if (envval != NULL)
694 				while ((*envval) && outputcnt) {
695 					*(output++) = *(envval++);
696 					outputcnt--;
697 				}
698 			/* Look for another '$' */
699 			state = 0;
700 		}
701 		break;
702 	    case 3:			/* Waiting for '	*/
703 		if ((c == '\'') && (prev != '\\')) {
704 			state = 0;
705 		} else {
706 			*(output++) = c;
707 			outputcnt--;
708 		}
709 		break;
710 	    }
711 	    prev = c;
712 	}
713 
714 	if (outputcnt)
715 		*output = 0;
716 
717 #ifdef DEBUG_PARSER
718 	printf ("[PROCESS_MACROS] OUTPUT len %d: \"%s\"\n",
719 		strlen(output_start), output_start);
720 #endif
721 }
722 
723 /****************************************************************************
724  * returns:
725  *	1  - command executed, repeatable
726  *	0  - command executed but not repeatable, interrupted commands are
727  *	     always considered not repeatable
728  *	-1 - not executed (unrecognized, bootd recursion or too many args)
729  *           (If cmd is NULL or "" or longer than CFG_CBSIZE-1 it is
730  *           considered unrecognized)
731  *
732  * WARNING:
733  *
734  * We must create a temporary copy of the command since the command we get
735  * may be the result from getenv(), which returns a pointer directly to
736  * the environment data, which may change magicly when the command we run
737  * creates or modifies environment variables (like "bootp" does).
738  */
739 
740 int run_command (const char *cmd, int flag)
741 {
742 	cmd_tbl_t *cmdtp;
743 	char cmdbuf[CFG_CBSIZE];	/* working copy of cmd		*/
744 	char *token;			/* start of token in cmdbuf	*/
745 	char *sep;			/* end of token (separator) in cmdbuf */
746 	char finaltoken[CFG_CBSIZE];
747 	char *str = cmdbuf;
748 	char *argv[CFG_MAXARGS + 1];	/* NULL terminated	*/
749 	int argc, inquotes;
750 	int repeatable = 1;
751 	int rc = 0;
752 
753 #ifdef DEBUG_PARSER
754 	printf ("[RUN_COMMAND] cmd[%p]=\"", cmd);
755 	puts (cmd ? cmd : "NULL");	/* use puts - string may be loooong */
756 	puts ("\"\n");
757 #endif
758 
759 	clear_ctrlc();		/* forget any previous Control C */
760 
761 	if (!cmd || !*cmd) {
762 		return -1;	/* empty command */
763 	}
764 
765 	if (strlen(cmd) >= CFG_CBSIZE) {
766 		puts ("## Command too long!\n");
767 		return -1;
768 	}
769 
770 	strcpy (cmdbuf, cmd);
771 
772 	/* Process separators and check for invalid
773 	 * repeatable commands
774 	 */
775 
776 #ifdef DEBUG_PARSER
777 	printf ("[PROCESS_SEPARATORS] %s\n", cmd);
778 #endif
779 	while (*str) {
780 
781 		/*
782 		 * Find separator, or string end
783 		 * Allow simple escape of ';' by writing "\;"
784 		 */
785 		for (inquotes = 0, sep = str; *sep; sep++) {
786 			if ((*sep=='\'') &&
787 			    (*(sep-1) != '\\'))
788 				inquotes=!inquotes;
789 
790 			if (!inquotes &&
791 			    (*sep == ';') &&	/* separator		*/
792 			    ( sep != str) &&	/* past string start	*/
793 			    (*(sep-1) != '\\'))	/* and NOT escaped	*/
794 				break;
795 		}
796 
797 		/*
798 		 * Limit the token to data between separators
799 		 */
800 		token = str;
801 		if (*sep) {
802 			str = sep + 1;	/* start of command for next pass */
803 			*sep = '\0';
804 		}
805 		else
806 			str = sep;	/* no more commands for next pass */
807 #ifdef DEBUG_PARSER
808 		printf ("token: \"%s\"\n", token);
809 #endif
810 
811 		/* find macros in this token and replace them */
812 		process_macros (token, finaltoken);
813 
814 		/* Extract arguments */
815 		argc = parse_line (finaltoken, argv);
816 
817 		/* Look up command in command table */
818 		if ((cmdtp = find_cmd(argv[0])) == NULL) {
819 			printf ("Unknown command '%s' - try 'help'\n", argv[0]);
820 			rc = -1;	/* give up after bad command */
821 			continue;
822 		}
823 
824 		/* found - check max args */
825 		if (argc > cmdtp->maxargs) {
826 			printf ("Usage:\n%s\n", cmdtp->usage);
827 			rc = -1;
828 			continue;
829 		}
830 
831 #if (CONFIG_COMMANDS & CFG_CMD_BOOTD)
832 		/* avoid "bootd" recursion */
833 		if (cmdtp->cmd == do_bootd) {
834 #ifdef DEBUG_PARSER
835 			printf ("[%s]\n", finaltoken);
836 #endif
837 			if (flag & CMD_FLAG_BOOTD) {
838 				printf ("'bootd' recursion detected\n");
839 				rc = -1;
840 				continue;
841 			}
842 			else
843 				flag |= CMD_FLAG_BOOTD;
844 		}
845 #endif	/* CFG_CMD_BOOTD */
846 
847 		/* OK - call function to do the command */
848 		if ((cmdtp->cmd) (cmdtp, flag, argc, argv) != 0) {
849 			rc = -1;
850 		}
851 
852 		repeatable &= cmdtp->repeatable;
853 
854 		/* Did the user stop this? */
855 		if (had_ctrlc ())
856 			return 0;	/* if stopped then not repeatable */
857 	}
858 
859 	return rc ? rc : repeatable;
860 }
861 
862 /****************************************************************************/
863 
864 #if (CONFIG_COMMANDS & CFG_CMD_RUN)
865 int do_run (cmd_tbl_t * cmdtp, int flag, int argc, char *argv[])
866 {
867 	int i;
868 
869 	if (argc < 2) {
870 		printf ("Usage:\n%s\n", cmdtp->usage);
871 		return 1;
872 	}
873 
874 	for (i=1; i<argc; ++i) {
875 		char *arg;
876 
877 		if ((arg = getenv (argv[i])) == NULL) {
878 			printf ("## Error: \"%s\" not defined\n", argv[i]);
879 			return 1;
880 		}
881 #ifndef CFG_HUSH_PARSER
882 		if (run_command (arg, flag) == -1)
883 			return 1;
884 #else
885 		if (parse_string_outer(arg,
886 		    FLAG_PARSE_SEMICOLON | FLAG_EXIT_FROM_LOOP) != 0)
887 			return 1;
888 #endif
889 	}
890 	return 0;
891 }
892 #endif	/* CFG_CMD_RUN */
893