3 * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
5 * Add to readline cmdline-editing by
7 * JinHua Luo, GuangDong Linux Center, <luo.jinhua@gd-linux.com>
9 * SPDX-License-Identifier: GPL-2.0+
24 #include <linux/ctype.h>
26 DECLARE_GLOBAL_DATA_PTR;
29 * Board-specific Platform code can reimplement show_boot_progress () if needed
31 void inline __show_boot_progress (int val) {}
32 void show_boot_progress (int val) __attribute__((weak, alias("__show_boot_progress")));
34 #define MAX_DELAY_STOP_STR 32
36 #define DEBUG_PARSER 0 /* set to 1 to debug */
38 #define debug_parser(fmt, args...) \
39 debug_cond(DEBUG_PARSER, fmt, ##args)
41 #ifndef DEBUG_BOOTKEYS
42 #define DEBUG_BOOTKEYS 0
44 #define debug_bootkeys(fmt, args...) \
45 debug_cond(DEBUG_BOOTKEYS, fmt, ##args)
47 char console_buffer[CONFIG_SYS_CBSIZE + 1]; /* console I/O buffer */
49 static char * delete_char (char *buffer, char *p, int *colp, int *np, int plen);
50 static const char erase_seq[] = "\b \b"; /* erase sequence */
51 static const char tab_seq[] = " "; /* used to expand TABs */
53 #ifdef CONFIG_BOOT_RETRY_TIME
54 static uint64_t endtime = 0; /* must be set, default is instant timeout */
55 static int retry_time = -1; /* -1 so can call readline before main_loop */
58 #define endtick(seconds) (get_ticks() + (uint64_t)(seconds) * get_tbclk())
60 #ifndef CONFIG_BOOT_RETRY_MIN
61 #define CONFIG_BOOT_RETRY_MIN CONFIG_BOOT_RETRY_TIME
64 #ifdef CONFIG_MODEM_SUPPORT
66 extern void mdm_init(void); /* defined in board.c */
69 /***************************************************************************
70 * Watch for 'delay' seconds for autoboot stop or autoboot delay string.
71 * returns: 0 - no key string, allow autoboot 1 - got key string, abort
73 #if defined(CONFIG_BOOTDELAY)
74 # if defined(CONFIG_AUTOBOOT_KEYED)
75 static int abortboot_keyed(int bootdelay)
78 uint64_t etime = endtick(bootdelay);
85 { str: getenv ("bootdelaykey"), retry: 1 },
86 { str: getenv ("bootdelaykey2"), retry: 1 },
87 { str: getenv ("bootstopkey"), retry: 0 },
88 { str: getenv ("bootstopkey2"), retry: 0 },
91 char presskey [MAX_DELAY_STOP_STR];
92 u_int presskey_len = 0;
93 u_int presskey_max = 0;
96 #ifndef CONFIG_ZERO_BOOTDELAY_CHECK
101 # ifdef CONFIG_AUTOBOOT_PROMPT
102 printf(CONFIG_AUTOBOOT_PROMPT);
105 # ifdef CONFIG_AUTOBOOT_DELAY_STR
106 if (delaykey[0].str == NULL)
107 delaykey[0].str = CONFIG_AUTOBOOT_DELAY_STR;
109 # ifdef CONFIG_AUTOBOOT_DELAY_STR2
110 if (delaykey[1].str == NULL)
111 delaykey[1].str = CONFIG_AUTOBOOT_DELAY_STR2;
113 # ifdef CONFIG_AUTOBOOT_STOP_STR
114 if (delaykey[2].str == NULL)
115 delaykey[2].str = CONFIG_AUTOBOOT_STOP_STR;
117 # ifdef CONFIG_AUTOBOOT_STOP_STR2
118 if (delaykey[3].str == NULL)
119 delaykey[3].str = CONFIG_AUTOBOOT_STOP_STR2;
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;
128 presskey_max = presskey_max > delaykey[i].len ?
129 presskey_max : delaykey[i].len;
131 debug_bootkeys("%s key:<%s>\n",
132 delaykey[i].retry ? "delay" : "stop",
133 delaykey[i].str ? delaykey[i].str : "NULL");
136 /* In order to keep up with incoming data, check timeout only
141 if (presskey_len < presskey_max) {
142 presskey [presskey_len ++] = getc();
145 for (i = 0; i < presskey_max - 1; i ++)
146 presskey [i] = presskey [i + 1];
148 presskey [i] = getc();
152 for (i = 0; i < sizeof(delaykey) / sizeof(delaykey[0]); i ++) {
153 if (delaykey[i].len > 0 &&
154 presskey_len >= delaykey[i].len &&
155 memcmp (presskey + presskey_len - delaykey[i].len,
157 delaykey[i].len) == 0) {
158 debug_bootkeys("got %skey\n",
159 delaykey[i].retry ? "delay" :
162 # ifdef CONFIG_BOOT_RETRY_TIME
163 /* don't retry auto boot */
164 if (! delaykey[i].retry)
170 } while (!abort && get_ticks() <= etime);
173 debug_bootkeys("key timeout\n");
175 #ifdef CONFIG_SILENT_CONSOLE
177 gd->flags &= ~GD_FLG_SILENT;
183 # else /* !defined(CONFIG_AUTOBOOT_KEYED) */
185 #ifdef CONFIG_MENUKEY
186 static int menukey = 0;
189 static int abortboot_normal(int bootdelay)
194 #ifdef CONFIG_MENUPROMPT
195 printf(CONFIG_MENUPROMPT);
198 printf("Hit any key to stop autoboot: %2d ", bootdelay);
201 #if defined CONFIG_ZERO_BOOTDELAY_CHECK
203 * Check if key already pressed
204 * Don't check if bootdelay < 0
206 if (bootdelay >= 0) {
207 if (tstc()) { /* we got a key press */
208 (void) getc(); /* consume input */
210 abort = 1; /* don't auto boot */
215 while ((bootdelay > 0) && (!abort)) {
220 if (tstc()) { /* we got a key press */
221 abort = 1; /* don't auto boot */
222 bootdelay = 0; /* no more delay */
223 # ifdef CONFIG_MENUKEY
226 (void) getc(); /* consume input */
231 } while (!abort && get_timer(ts) < 1000);
233 printf("\b\b\b%2d ", bootdelay);
238 #ifdef CONFIG_SILENT_CONSOLE
240 gd->flags &= ~GD_FLG_SILENT;
245 # endif /* CONFIG_AUTOBOOT_KEYED */
247 static int abortboot(int bootdelay)
249 #ifdef CONFIG_AUTOBOOT_KEYED
250 return abortboot_keyed(bootdelay);
252 return abortboot_normal(bootdelay);
255 #endif /* CONFIG_BOOTDELAY */
258 * Runs the given boot command securely. Specifically:
259 * - Doesn't run the command with the shell (run_command or parse_string_outer),
260 * since that's a lot of code surface that an attacker might exploit.
261 * Because of this, we don't do any argument parsing--the secure boot command
262 * has to be a full-fledged u-boot command.
263 * - Doesn't check for keypresses before booting, since that could be a
264 * security hole; also disables Ctrl-C.
265 * - Doesn't allow the command to return.
267 * Upon any failures, this function will drop into an infinite loop after
268 * printing the error message to console.
271 #if defined(CONFIG_BOOTDELAY) && defined(CONFIG_OF_CONTROL)
272 static void secure_boot_cmd(char *cmd)
278 printf("## Error: Secure boot command not specified\n");
282 /* Disable Ctrl-C just in case some command is used that checks it. */
285 /* Find the command directly. */
286 cmdtp = find_cmd(cmd);
288 printf("## Error: \"%s\" not defined\n", cmd);
292 /* Run the command, forcing no flags and faking argc and argv. */
293 rc = (cmdtp->cmd)(cmdtp, 0, 1, &cmd);
295 /* Shouldn't ever return from boot command. */
296 printf("## Error: \"%s\" returned (code %d)\n", cmd, rc);
300 * Not a whole lot to do here. Rebooting won't help much, since we'll
301 * just end up right back here. Just loop.
306 static void process_fdt_options(const void *blob)
310 /* Add an env variable to point to a kernel payload, if available */
311 addr = fdtdec_get_config_int(gd->fdt_blob, "kernel-offset", 0);
313 setenv_addr("kernaddr", (void *)(CONFIG_SYS_TEXT_BASE + addr));
315 /* Add an env variable to point to a root disk, if available */
316 addr = fdtdec_get_config_int(gd->fdt_blob, "rootdisk-offset", 0);
318 setenv_addr("rootaddr", (void *)(CONFIG_SYS_TEXT_BASE + addr));
320 #endif /* CONFIG_OF_CONTROL */
322 #ifdef CONFIG_BOOTDELAY
323 static void process_boot_delay(void)
325 #ifdef CONFIG_OF_CONTROL
330 #ifdef CONFIG_BOOTCOUNT_LIMIT
331 unsigned long bootcount = 0;
332 unsigned long bootlimit = 0;
333 #endif /* CONFIG_BOOTCOUNT_LIMIT */
335 #ifdef CONFIG_BOOTCOUNT_LIMIT
336 bootcount = bootcount_load();
338 bootcount_store (bootcount);
339 setenv_ulong("bootcount", bootcount);
340 bootlimit = getenv_ulong("bootlimit", 10, 0);
341 #endif /* CONFIG_BOOTCOUNT_LIMIT */
343 s = getenv ("bootdelay");
344 bootdelay = s ? (int)simple_strtol(s, NULL, 10) : CONFIG_BOOTDELAY;
346 #ifdef CONFIG_OF_CONTROL
347 bootdelay = fdtdec_get_config_int(gd->fdt_blob, "bootdelay",
351 debug ("### main_loop entered: bootdelay=%d\n\n", bootdelay);
353 #if defined(CONFIG_MENU_SHOW)
354 bootdelay = menu_show(bootdelay);
356 # ifdef CONFIG_BOOT_RETRY_TIME
358 # endif /* CONFIG_BOOT_RETRY_TIME */
361 if (gd->flags & GD_FLG_POSTFAIL) {
362 s = getenv("failbootcmd");
365 #endif /* CONFIG_POST */
366 #ifdef CONFIG_BOOTCOUNT_LIMIT
367 if (bootlimit && (bootcount > bootlimit)) {
368 printf ("Warning: Bootlimit (%u) exceeded. Using altbootcmd.\n",
369 (unsigned)bootlimit);
370 s = getenv ("altbootcmd");
373 #endif /* CONFIG_BOOTCOUNT_LIMIT */
374 s = getenv ("bootcmd");
375 #ifdef CONFIG_OF_CONTROL
376 /* Allow the fdt to override the boot command */
377 env = fdtdec_get_config_string(gd->fdt_blob, "bootcmd");
381 process_fdt_options(gd->fdt_blob);
384 * If the bootsecure option was chosen, use secure_boot_cmd().
385 * Always use 'env' in this case, since bootsecure requres that the
386 * bootcmd was specified in the FDT too.
388 if (fdtdec_get_config_int(gd->fdt_blob, "bootsecure", 0))
389 secure_boot_cmd(env);
391 #endif /* CONFIG_OF_CONTROL */
393 debug ("### main_loop: bootcmd=\"%s\"\n", s ? s : "<UNDEFINED>");
395 if (bootdelay != -1 && s && !abortboot(bootdelay)) {
396 #if defined(CONFIG_AUTOBOOT_KEYED) && !defined(CONFIG_AUTOBOOT_KEYED_CTRLC)
397 int prev = disable_ctrlc(1); /* disable Control C checking */
400 run_command_list(s, -1, 0);
402 #if defined(CONFIG_AUTOBOOT_KEYED) && !defined(CONFIG_AUTOBOOT_KEYED_CTRLC)
403 disable_ctrlc(prev); /* restore Control C checking */
407 #ifdef CONFIG_MENUKEY
408 if (menukey == CONFIG_MENUKEY) {
409 s = getenv("menucmd");
411 run_command_list(s, -1, 0);
413 #endif /* CONFIG_MENUKEY */
415 #endif /* CONFIG_BOOTDELAY */
419 #ifndef CONFIG_SYS_HUSH_PARSER
420 static char lastcommand[CONFIG_SYS_CBSIZE] = { 0, };
425 #ifdef CONFIG_PREBOOT
429 bootstage_mark_name(BOOTSTAGE_ID_MAIN_LOOP, "main_loop");
431 #ifndef CONFIG_SYS_GENERIC_BOARD
432 puts("Warning: Your board does not use generic board. Please read\n");
433 puts("doc/README.generic-board and take action. Boards not\n");
434 puts("upgraded by the late 2014 may break or be removed.\n");
437 #ifdef CONFIG_MODEM_SUPPORT
438 debug("DEBUG: main_loop: do_mdm_init=%d\n", do_mdm_init);
440 char *str = strdup(getenv("mdm_cmd"));
441 setenv("preboot", str); /* set or delete definition */
444 mdm_init(); /* wait for modem connection */
446 #endif /* CONFIG_MODEM_SUPPORT */
448 #ifdef CONFIG_VERSION_VARIABLE
450 setenv("ver", version_string); /* set version variable */
452 #endif /* CONFIG_VERSION_VARIABLE */
454 #ifdef CONFIG_SYS_HUSH_PARSER
458 #if defined(CONFIG_HUSH_INIT_VAR)
462 #ifdef CONFIG_PREBOOT
463 p = getenv("preboot");
465 # ifdef CONFIG_AUTOBOOT_KEYED
466 int prev = disable_ctrlc(1); /* disable Control C checking */
469 run_command_list(p, -1, 0);
471 # ifdef CONFIG_AUTOBOOT_KEYED
472 disable_ctrlc(prev); /* restore Control C checking */
475 #endif /* CONFIG_PREBOOT */
477 #if defined(CONFIG_UPDATE_TFTP)
479 #endif /* CONFIG_UPDATE_TFTP */
481 #ifdef CONFIG_BOOTDELAY
482 process_boot_delay();
485 * Main Loop for Monitor Command Processing
487 #ifdef CONFIG_SYS_HUSH_PARSER
489 /* This point is never reached */
493 #ifdef CONFIG_BOOT_RETRY_TIME
495 /* Saw enough of a valid command to
496 * restart the timeout.
501 len = readline (CONFIG_SYS_PROMPT);
503 flag = 0; /* assume no special flags for now */
505 strcpy (lastcommand, console_buffer);
507 flag |= CMD_FLAG_REPEAT;
508 #ifdef CONFIG_BOOT_RETRY_TIME
509 else if (len == -2) {
510 /* -2 means timed out, retry autoboot
512 puts ("\nTimed out waiting for command\n");
513 # ifdef CONFIG_RESET_TO_RETRY
514 /* Reinit board to run initialization code again */
515 do_reset (NULL, 0, 0, NULL);
517 return; /* retry autoboot */
523 puts ("<INTERRUPT>\n");
525 rc = run_command(lastcommand, flag);
528 /* invalid command or not repeatable, forget it */
532 #endif /*CONFIG_SYS_HUSH_PARSER*/
535 #ifdef CONFIG_BOOT_RETRY_TIME
536 /***************************************************************************
537 * initialize command line timeout
539 void init_cmd_timeout(void)
541 char *s = getenv ("bootretry");
544 retry_time = (int)simple_strtol(s, NULL, 10);
546 retry_time = CONFIG_BOOT_RETRY_TIME;
548 if (retry_time >= 0 && retry_time < CONFIG_BOOT_RETRY_MIN)
549 retry_time = CONFIG_BOOT_RETRY_MIN;
552 /***************************************************************************
553 * reset command line timeout to retry_time seconds
555 void reset_cmd_timeout(void)
557 endtime = endtick(retry_time);
561 #ifdef CONFIG_CMDLINE_EDITING
564 * cmdline-editing related codes from vivi.
565 * Author: Janghoon Lyu <nandy@mizi.com>
568 #define putnstr(str,n) do { \
569 printf ("%.*s", (int)n, str); \
572 #define CTL_CH(c) ((c) - 'a' + 1)
573 #define CTL_BACKSPACE ('\b')
574 #define DEL ((char)255)
575 #define DEL7 ((char)127)
576 #define CREAD_HIST_CHAR ('!')
578 #define getcmd_putch(ch) putc(ch)
579 #define getcmd_getch() getc()
580 #define getcmd_cbeep() getcmd_putch('\a')
583 #define HIST_SIZE CONFIG_SYS_CBSIZE
586 static int hist_add_idx;
587 static int hist_cur = -1;
588 static unsigned hist_num;
590 static char *hist_list[HIST_MAX];
591 static char hist_lines[HIST_MAX][HIST_SIZE + 1]; /* Save room for NULL */
593 #define add_idx_minus_one() ((hist_add_idx == 0) ? hist_max : hist_add_idx-1)
595 static void hist_init(void)
604 for (i = 0; i < HIST_MAX; i++) {
605 hist_list[i] = hist_lines[i];
606 hist_list[i][0] = '\0';
610 static void cread_add_to_hist(char *line)
612 strcpy(hist_list[hist_add_idx], line);
614 if (++hist_add_idx >= HIST_MAX)
617 if (hist_add_idx > hist_max)
618 hist_max = hist_add_idx;
623 static char* hist_prev(void)
635 if (hist_cur == hist_add_idx) {
639 ret = hist_list[hist_cur];
644 static char* hist_next(void)
651 if (hist_cur == hist_add_idx)
654 if (++hist_cur > hist_max)
657 if (hist_cur == hist_add_idx) {
660 ret = hist_list[hist_cur];
665 #ifndef CONFIG_CMDLINE_EDITING
666 static void cread_print_hist_list(void)
671 n = hist_num - hist_max;
673 i = hist_add_idx + 1;
677 if (i == hist_add_idx)
679 printf("%s\n", hist_list[i]);
684 #endif /* CONFIG_CMDLINE_EDITING */
686 #define BEGINNING_OF_LINE() { \
688 getcmd_putch(CTL_BACKSPACE); \
693 #define ERASE_TO_EOL() { \
694 if (num < eol_num) { \
695 printf("%*s", (int)(eol_num - num), ""); \
697 getcmd_putch(CTL_BACKSPACE); \
698 } while (--eol_num > num); \
702 #define REFRESH_TO_EOL() { \
703 if (num < eol_num) { \
704 wlen = eol_num - num; \
705 putnstr(buf + num, wlen); \
710 static void cread_add_char(char ichar, int insert, unsigned long *num,
711 unsigned long *eol_num, char *buf, unsigned long len)
716 if (insert || *num == *eol_num) {
717 if (*eol_num > len - 1) {
725 wlen = *eol_num - *num;
727 memmove(&buf[*num+1], &buf[*num], wlen-1);
731 putnstr(buf + *num, wlen);
734 getcmd_putch(CTL_BACKSPACE);
737 /* echo the character */
740 putnstr(buf + *num, wlen);
745 static void cread_add_str(char *str, int strsize, int insert, unsigned long *num,
746 unsigned long *eol_num, char *buf, unsigned long len)
749 cread_add_char(*str, insert, num, eol_num, buf, len);
754 static int cread_line(const char *const prompt, char *buf, unsigned int *len,
757 unsigned long num = 0;
758 unsigned long eol_num = 0;
764 int init_len = strlen(buf);
768 cread_add_str(buf, init_len, 1, &num, &eol_num, buf, *len);
771 #ifdef CONFIG_BOOT_RETRY_TIME
772 while (!tstc()) { /* while no incoming data */
773 if (retry_time >= 0 && get_ticks() > endtime)
774 return (-2); /* timed out */
778 if (first && timeout) {
779 uint64_t etime = endtick(timeout);
781 while (!tstc()) { /* while no incoming data */
782 if (get_ticks() >= etime)
783 return -2; /* timed out */
789 ichar = getcmd_getch();
791 if ((ichar == '\n') || (ichar == '\r')) {
797 * handle standard linux xterm esc sequences for arrow key, etc.
802 esc_save[esc_len] = ichar;
805 cread_add_str(esc_save, esc_len, insert,
806 &num, &eol_num, buf, *len);
814 case 'D': /* <- key */
818 case 'C': /* -> key */
821 break; /* pass off to ^F handler */
822 case 'H': /* Home key */
825 break; /* pass off to ^A handler */
826 case 'A': /* up arrow */
829 break; /* pass off to ^P handler */
830 case 'B': /* down arrow */
833 break; /* pass off to ^N handler */
835 esc_save[esc_len++] = ichar;
836 cread_add_str(esc_save, esc_len, insert,
837 &num, &eol_num, buf, *len);
846 esc_save[esc_len] = ichar;
849 puts("impossible condition #876\n");
857 case CTL_CH('c'): /* ^C - break */
858 *buf = '\0'; /* discard input */
862 getcmd_putch(buf[num]);
868 getcmd_putch(CTL_BACKSPACE);
874 wlen = eol_num - num - 1;
876 memmove(&buf[num], &buf[num+1], wlen);
877 putnstr(buf + num, wlen);
882 getcmd_putch(CTL_BACKSPACE);
905 wlen = eol_num - num;
907 memmove(&buf[num], &buf[num+1], wlen);
908 getcmd_putch(CTL_BACKSPACE);
909 putnstr(buf + num, wlen);
912 getcmd_putch(CTL_BACKSPACE);
924 if (ichar == CTL_CH('p'))
934 /* nuke the current line */
938 /* erase to end of line */
941 /* copy new line into place and display */
943 eol_num = strlen(buf);
947 #ifdef CONFIG_AUTO_COMPLETE
951 /* do not autocomplete when in the middle */
958 col = strlen(prompt) + eol_num;
960 if (cmd_auto_complete(prompt, buf, &num2, &col)) {
969 cread_add_char(ichar, insert, &num, &eol_num, buf, *len);
974 buf[eol_num] = '\0'; /* lose the newline */
976 if (buf[0] && buf[0] != CREAD_HIST_CHAR)
977 cread_add_to_hist(buf);
978 hist_cur = hist_add_idx;
983 #endif /* CONFIG_CMDLINE_EDITING */
985 /****************************************************************************/
988 * Prompt for input and read a line.
989 * If CONFIG_BOOT_RETRY_TIME is defined and retry_time >= 0,
990 * time out when time goes past endtime (timebase time in ticks).
991 * Return: number of read characters
995 int readline (const char *const prompt)
998 * If console_buffer isn't 0-length the user will be prompted to modify
999 * it instead of entering it from scratch as desired.
1001 console_buffer[0] = '\0';
1003 return readline_into_buffer(prompt, console_buffer, 0);
1007 int readline_into_buffer(const char *const prompt, char *buffer, int timeout)
1010 #ifdef CONFIG_CMDLINE_EDITING
1011 unsigned int len = CONFIG_SYS_CBSIZE;
1013 static int initted = 0;
1016 * History uses a global array which is not
1017 * writable until after relocation to RAM.
1018 * Revert to non-history version if still
1019 * running from flash.
1021 if (gd->flags & GD_FLG_RELOC) {
1030 rc = cread_line(prompt, p, &len, timeout);
1031 return rc < 0 ? rc : len;
1034 #endif /* CONFIG_CMDLINE_EDITING */
1036 int n = 0; /* buffer index */
1037 int plen = 0; /* prompt length */
1038 int col; /* output column cnt */
1043 plen = strlen (prompt);
1049 #ifdef CONFIG_BOOT_RETRY_TIME
1050 while (!tstc()) { /* while no incoming data */
1051 if (retry_time >= 0 && get_ticks() > endtime)
1052 return (-2); /* timed out */
1056 WATCHDOG_RESET(); /* Trigger watchdog, if needed */
1058 #ifdef CONFIG_SHOW_ACTIVITY
1067 * Special character handling
1070 case '\r': /* Enter */
1076 case '\0': /* nul */
1079 case 0x03: /* ^C - break */
1080 p_buf[0] = '\0'; /* discard input */
1083 case 0x15: /* ^U - erase line */
1084 while (col > plen) {
1092 case 0x17: /* ^W - erase word */
1093 p=delete_char(p_buf, p, &col, &n, plen);
1094 while ((n > 0) && (*p != ' ')) {
1095 p=delete_char(p_buf, p, &col, &n, plen);
1099 case 0x08: /* ^H - backspace */
1100 case 0x7F: /* DEL - backspace */
1101 p=delete_char(p_buf, p, &col, &n, plen);
1106 * Must be a normal character then
1108 if (n < CONFIG_SYS_CBSIZE-2) {
1109 if (c == '\t') { /* expand TABs */
1110 #ifdef CONFIG_AUTO_COMPLETE
1111 /* if auto completion triggered just continue */
1113 if (cmd_auto_complete(prompt, console_buffer, &n, &col)) {
1114 p = p_buf + n; /* reset */
1118 puts (tab_seq+(col&07));
1119 col += 8 - (col&07);
1124 * Echo input using puts() to force an
1125 * LCD flush if we are using an LCD
1134 } else { /* Buffer full */
1139 #ifdef CONFIG_CMDLINE_EDITING
1144 /****************************************************************************/
1146 static char * delete_char (char *buffer, char *p, int *colp, int *np, int plen)
1154 if (*(--p) == '\t') { /* will retype the whole line */
1155 while (*colp > plen) {
1159 for (s=buffer; s<p; ++s) {
1161 puts (tab_seq+((*colp) & 07));
1162 *colp += 8 - ((*colp) & 07);
1176 /****************************************************************************/
1178 int parse_line (char *line, char *argv[])
1182 debug_parser("parse_line: \"%s\"\n", line);
1183 while (nargs < CONFIG_SYS_MAXARGS) {
1185 /* skip any white space */
1186 while (isblank(*line))
1189 if (*line == '\0') { /* end of line, no more args */
1191 debug_parser("parse_line: nargs=%d\n", nargs);
1195 argv[nargs++] = line; /* begin of argument string */
1197 /* find end of string */
1198 while (*line && !isblank(*line))
1201 if (*line == '\0') { /* end of line, no more args */
1203 debug_parser("parse_line: nargs=%d\n", nargs);
1207 *line++ = '\0'; /* terminate current arg */
1210 printf ("** Too many args (max. %d) **\n", CONFIG_SYS_MAXARGS);
1212 debug_parser("parse_line: nargs=%d\n", nargs);
1216 /****************************************************************************/
1218 #ifndef CONFIG_SYS_HUSH_PARSER
1219 static void process_macros (const char *input, char *output)
1222 const char *varname_start = NULL;
1223 int inputcnt = strlen (input);
1224 int outputcnt = CONFIG_SYS_CBSIZE;
1225 int state = 0; /* 0 = waiting for '$' */
1227 /* 1 = waiting for '(' or '{' */
1228 /* 2 = waiting for ')' or '}' */
1229 /* 3 = waiting for ''' */
1230 char *output_start = output;
1232 debug_parser("[PROCESS_MACROS] INPUT len %zd: \"%s\"\n", strlen(input),
1235 prev = '\0'; /* previous character */
1237 while (inputcnt && outputcnt) {
1242 /* remove one level of escape characters */
1243 if ((c == '\\') && (prev != '\\')) {
1244 if (inputcnt-- == 0)
1252 case 0: /* Waiting for (unescaped) $ */
1253 if ((c == '\'') && (prev != '\\')) {
1257 if ((c == '$') && (prev != '\\')) {
1264 case 1: /* Waiting for ( */
1265 if (c == '(' || c == '{') {
1267 varname_start = input;
1279 case 2: /* Waiting for ) */
1280 if (c == ')' || c == '}') {
1282 char envname[CONFIG_SYS_CBSIZE], *envval;
1283 int envcnt = input - varname_start - 1; /* Varname # of chars */
1285 /* Get the varname */
1286 for (i = 0; i < envcnt; i++) {
1287 envname[i] = varname_start[i];
1292 envval = getenv (envname);
1294 /* Copy into the line if it exists */
1296 while ((*envval) && outputcnt) {
1297 *(output++) = *(envval++);
1300 /* Look for another '$' */
1304 case 3: /* Waiting for ' */
1305 if ((c == '\'') && (prev != '\\')) {
1321 debug_parser("[PROCESS_MACROS] OUTPUT len %zd: \"%s\"\n",
1322 strlen(output_start), output_start);
1325 /****************************************************************************
1327 * 1 - command executed, repeatable
1328 * 0 - command executed but not repeatable, interrupted commands are
1329 * always considered not repeatable
1330 * -1 - not executed (unrecognized, bootd recursion or too many args)
1331 * (If cmd is NULL or "" or longer than CONFIG_SYS_CBSIZE-1 it is
1332 * considered unrecognized)
1336 * We must create a temporary copy of the command since the command we get
1337 * may be the result from getenv(), which returns a pointer directly to
1338 * the environment data, which may change magicly when the command we run
1339 * creates or modifies environment variables (like "bootp" does).
1341 static int builtin_run_command(const char *cmd, int flag)
1343 char cmdbuf[CONFIG_SYS_CBSIZE]; /* working copy of cmd */
1344 char *token; /* start of token in cmdbuf */
1345 char *sep; /* end of token (separator) in cmdbuf */
1346 char finaltoken[CONFIG_SYS_CBSIZE];
1348 char *argv[CONFIG_SYS_MAXARGS + 1]; /* NULL terminated */
1353 debug_parser("[RUN_COMMAND] cmd[%p]=\"", cmd);
1355 /* use puts - string may be loooong */
1356 puts(cmd ? cmd : "NULL");
1359 clear_ctrlc(); /* forget any previous Control C */
1361 if (!cmd || !*cmd) {
1362 return -1; /* empty command */
1365 if (strlen(cmd) >= CONFIG_SYS_CBSIZE) {
1366 puts ("## Command too long!\n");
1370 strcpy (cmdbuf, cmd);
1372 /* Process separators and check for invalid
1373 * repeatable commands
1376 debug_parser("[PROCESS_SEPARATORS] %s\n", cmd);
1380 * Find separator, or string end
1381 * Allow simple escape of ';' by writing "\;"
1383 for (inquotes = 0, sep = str; *sep; sep++) {
1389 (*sep == ';') && /* separator */
1390 ( sep != str) && /* past string start */
1391 (*(sep-1) != '\\')) /* and NOT escaped */
1396 * Limit the token to data between separators
1400 str = sep + 1; /* start of command for next pass */
1404 str = sep; /* no more commands for next pass */
1405 debug_parser("token: \"%s\"\n", token);
1407 /* find macros in this token and replace them */
1408 process_macros (token, finaltoken);
1410 /* Extract arguments */
1411 if ((argc = parse_line (finaltoken, argv)) == 0) {
1412 rc = -1; /* no command at all */
1416 if (cmd_process(flag, argc, argv, &repeatable, NULL))
1419 /* Did the user stop this? */
1421 return -1; /* if stopped then not repeatable */
1424 return rc ? rc : repeatable;
1429 * Run a command using the selected parser.
1431 * @param cmd Command to run
1432 * @param flag Execution flags (CMD_FLAG_...)
1433 * @return 0 on success, or != 0 on error.
1435 int run_command(const char *cmd, int flag)
1437 #ifndef CONFIG_SYS_HUSH_PARSER
1439 * builtin_run_command can return 0 or 1 for success, so clean up
1442 if (builtin_run_command(cmd, flag) == -1)
1447 return parse_string_outer(cmd,
1448 FLAG_PARSE_SEMICOLON | FLAG_EXIT_FROM_LOOP);
1452 #ifndef CONFIG_SYS_HUSH_PARSER
1454 * Execute a list of command separated by ; or \n using the built-in parser.
1456 * This function cannot take a const char * for the command, since if it
1457 * finds newlines in the string, it replaces them with \0.
1459 * @param cmd String containing list of commands
1460 * @param flag Execution flags (CMD_FLAG_...)
1461 * @return 0 on success, or != 0 on error.
1463 static int builtin_run_command_list(char *cmd, int flag)
1469 * Break into individual lines, and execute each line; terminate on
1474 if (*next == '\n') {
1476 /* run only non-empty commands */
1478 debug("** exec: \"%s\"\n", line);
1479 if (builtin_run_command(line, 0) < 0) {
1488 if (rcode == 0 && *line)
1489 rcode = (builtin_run_command(line, 0) >= 0);
1495 int run_command_list(const char *cmd, int len, int flag)
1498 char *buff = (char *)cmd; /* cast away const */
1503 #ifdef CONFIG_SYS_HUSH_PARSER
1504 /* hush will never change our string */
1507 /* the built-in parser will change our string if it sees \n */
1508 need_buff = strchr(cmd, '\n') != NULL;
1512 buff = malloc(len + 1);
1515 memcpy(buff, cmd, len);
1518 #ifdef CONFIG_SYS_HUSH_PARSER
1519 rcode = parse_string_outer(buff, FLAG_PARSE_SEMICOLON);
1522 * This function will overwrite any \n it sees with a \0, which
1523 * is why it can't work with a const char *. Here we are making
1524 * using of internal knowledge of this function, to avoid always
1525 * doing a malloc() which is actually required only in a case that
1528 rcode = builtin_run_command_list(buff, flag);
1536 /****************************************************************************/
1538 #if defined(CONFIG_CMD_RUN)
1539 int do_run (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
1544 return CMD_RET_USAGE;
1546 for (i=1; i<argc; ++i) {
1549 if ((arg = getenv (argv[i])) == NULL) {
1550 printf ("## Error: \"%s\" not defined\n", argv[i]);
1554 if (run_command_list(arg, -1, flag) != 0)