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+
23 #include <linux/ctype.h>
25 DECLARE_GLOBAL_DATA_PTR;
28 * Board-specific Platform code can reimplement show_boot_progress () if needed
30 void inline __show_boot_progress (int val) {}
31 void show_boot_progress (int val) __attribute__((weak, alias("__show_boot_progress")));
33 #define MAX_DELAY_STOP_STR 32
35 #define DEBUG_PARSER 0 /* set to 1 to debug */
37 #define debug_parser(fmt, args...) \
38 debug_cond(DEBUG_PARSER, fmt, ##args)
40 #ifndef DEBUG_BOOTKEYS
41 #define DEBUG_BOOTKEYS 0
43 #define debug_bootkeys(fmt, args...) \
44 debug_cond(DEBUG_BOOTKEYS, fmt, ##args)
46 char console_buffer[CONFIG_SYS_CBSIZE + 1]; /* console I/O buffer */
48 static char * delete_char (char *buffer, char *p, int *colp, int *np, int plen);
49 static const char erase_seq[] = "\b \b"; /* erase sequence */
50 static const char tab_seq[] = " "; /* used to expand TABs */
52 #ifdef CONFIG_BOOT_RETRY_TIME
53 static uint64_t endtime = 0; /* must be set, default is instant timeout */
54 static int retry_time = -1; /* -1 so can call readline before main_loop */
57 #define endtick(seconds) (get_ticks() + (uint64_t)(seconds) * get_tbclk())
59 #ifndef CONFIG_BOOT_RETRY_MIN
60 #define CONFIG_BOOT_RETRY_MIN CONFIG_BOOT_RETRY_TIME
63 #ifdef CONFIG_MODEM_SUPPORT
65 extern void mdm_init(void); /* defined in board.c */
68 /***************************************************************************
69 * Watch for 'delay' seconds for autoboot stop or autoboot delay string.
70 * returns: 0 - no key string, allow autoboot 1 - got key string, abort
72 #if defined(CONFIG_BOOTDELAY)
73 # if defined(CONFIG_AUTOBOOT_KEYED)
74 static int abortboot_keyed(int bootdelay)
77 uint64_t etime = endtick(bootdelay);
84 { str: getenv ("bootdelaykey"), retry: 1 },
85 { str: getenv ("bootdelaykey2"), retry: 1 },
86 { str: getenv ("bootstopkey"), retry: 0 },
87 { str: getenv ("bootstopkey2"), retry: 0 },
90 char presskey [MAX_DELAY_STOP_STR];
91 u_int presskey_len = 0;
92 u_int presskey_max = 0;
95 #ifndef CONFIG_ZERO_BOOTDELAY_CHECK
100 # ifdef CONFIG_AUTOBOOT_PROMPT
101 printf(CONFIG_AUTOBOOT_PROMPT);
104 # ifdef CONFIG_AUTOBOOT_DELAY_STR
105 if (delaykey[0].str == NULL)
106 delaykey[0].str = CONFIG_AUTOBOOT_DELAY_STR;
108 # ifdef CONFIG_AUTOBOOT_DELAY_STR2
109 if (delaykey[1].str == NULL)
110 delaykey[1].str = CONFIG_AUTOBOOT_DELAY_STR2;
112 # ifdef CONFIG_AUTOBOOT_STOP_STR
113 if (delaykey[2].str == NULL)
114 delaykey[2].str = CONFIG_AUTOBOOT_STOP_STR;
116 # ifdef CONFIG_AUTOBOOT_STOP_STR2
117 if (delaykey[3].str == NULL)
118 delaykey[3].str = CONFIG_AUTOBOOT_STOP_STR2;
121 for (i = 0; i < sizeof(delaykey) / sizeof(delaykey[0]); i ++) {
122 delaykey[i].len = delaykey[i].str == NULL ?
123 0 : strlen (delaykey[i].str);
124 delaykey[i].len = delaykey[i].len > MAX_DELAY_STOP_STR ?
125 MAX_DELAY_STOP_STR : delaykey[i].len;
127 presskey_max = presskey_max > delaykey[i].len ?
128 presskey_max : delaykey[i].len;
130 debug_bootkeys("%s key:<%s>\n",
131 delaykey[i].retry ? "delay" : "stop",
132 delaykey[i].str ? delaykey[i].str : "NULL");
135 /* In order to keep up with incoming data, check timeout only
140 if (presskey_len < presskey_max) {
141 presskey [presskey_len ++] = getc();
144 for (i = 0; i < presskey_max - 1; i ++)
145 presskey [i] = presskey [i + 1];
147 presskey [i] = getc();
151 for (i = 0; i < sizeof(delaykey) / sizeof(delaykey[0]); i ++) {
152 if (delaykey[i].len > 0 &&
153 presskey_len >= delaykey[i].len &&
154 memcmp (presskey + presskey_len - delaykey[i].len,
156 delaykey[i].len) == 0) {
157 debug_bootkeys("got %skey\n",
158 delaykey[i].retry ? "delay" :
161 # ifdef CONFIG_BOOT_RETRY_TIME
162 /* don't retry auto boot */
163 if (! delaykey[i].retry)
169 } while (!abort && get_ticks() <= etime);
172 debug_bootkeys("key timeout\n");
174 #ifdef CONFIG_SILENT_CONSOLE
176 gd->flags &= ~GD_FLG_SILENT;
182 # else /* !defined(CONFIG_AUTOBOOT_KEYED) */
184 #ifdef CONFIG_MENUKEY
185 static int menukey = 0;
188 static int abortboot_normal(int bootdelay)
193 #ifdef CONFIG_MENUPROMPT
194 printf(CONFIG_MENUPROMPT);
197 printf("Hit any key to stop autoboot: %2d ", bootdelay);
200 #if defined CONFIG_ZERO_BOOTDELAY_CHECK
202 * Check if key already pressed
203 * Don't check if bootdelay < 0
205 if (bootdelay >= 0) {
206 if (tstc()) { /* we got a key press */
207 (void) getc(); /* consume input */
209 abort = 1; /* don't auto boot */
214 while ((bootdelay > 0) && (!abort)) {
219 if (tstc()) { /* we got a key press */
220 abort = 1; /* don't auto boot */
221 bootdelay = 0; /* no more delay */
222 # ifdef CONFIG_MENUKEY
225 (void) getc(); /* consume input */
230 } while (!abort && get_timer(ts) < 1000);
232 printf("\b\b\b%2d ", bootdelay);
237 #ifdef CONFIG_SILENT_CONSOLE
239 gd->flags &= ~GD_FLG_SILENT;
244 # endif /* CONFIG_AUTOBOOT_KEYED */
246 static int abortboot(int bootdelay)
248 #ifdef CONFIG_AUTOBOOT_KEYED
249 return abortboot_keyed(bootdelay);
251 return abortboot_normal(bootdelay);
254 #endif /* CONFIG_BOOTDELAY */
257 * Runs the given boot command securely. Specifically:
258 * - Doesn't run the command with the shell (run_command or parse_string_outer),
259 * since that's a lot of code surface that an attacker might exploit.
260 * Because of this, we don't do any argument parsing--the secure boot command
261 * has to be a full-fledged u-boot command.
262 * - Doesn't check for keypresses before booting, since that could be a
263 * security hole; also disables Ctrl-C.
264 * - Doesn't allow the command to return.
266 * Upon any failures, this function will drop into an infinite loop after
267 * printing the error message to console.
270 #if defined(CONFIG_BOOTDELAY) && defined(CONFIG_OF_CONTROL)
271 static void secure_boot_cmd(char *cmd)
277 printf("## Error: Secure boot command not specified\n");
281 /* Disable Ctrl-C just in case some command is used that checks it. */
284 /* Find the command directly. */
285 cmdtp = find_cmd(cmd);
287 printf("## Error: \"%s\" not defined\n", cmd);
291 /* Run the command, forcing no flags and faking argc and argv. */
292 rc = (cmdtp->cmd)(cmdtp, 0, 1, &cmd);
294 /* Shouldn't ever return from boot command. */
295 printf("## Error: \"%s\" returned (code %d)\n", cmd, rc);
299 * Not a whole lot to do here. Rebooting won't help much, since we'll
300 * just end up right back here. Just loop.
305 static void process_fdt_options(const void *blob)
309 /* Add an env variable to point to a kernel payload, if available */
310 addr = fdtdec_get_config_int(gd->fdt_blob, "kernel-offset", 0);
312 setenv_addr("kernaddr", (void *)(CONFIG_SYS_TEXT_BASE + addr));
314 /* Add an env variable to point to a root disk, if available */
315 addr = fdtdec_get_config_int(gd->fdt_blob, "rootdisk-offset", 0);
317 setenv_addr("rootaddr", (void *)(CONFIG_SYS_TEXT_BASE + addr));
319 #endif /* CONFIG_OF_CONTROL */
321 #ifdef CONFIG_BOOTDELAY
322 static void process_boot_delay(void)
324 #ifdef CONFIG_OF_CONTROL
329 #ifdef CONFIG_BOOTCOUNT_LIMIT
330 unsigned long bootcount = 0;
331 unsigned long bootlimit = 0;
332 #endif /* CONFIG_BOOTCOUNT_LIMIT */
334 #ifdef CONFIG_BOOTCOUNT_LIMIT
335 bootcount = bootcount_load();
337 bootcount_store (bootcount);
338 setenv_ulong("bootcount", bootcount);
339 bootlimit = getenv_ulong("bootlimit", 10, 0);
340 #endif /* CONFIG_BOOTCOUNT_LIMIT */
342 s = getenv ("bootdelay");
343 bootdelay = s ? (int)simple_strtol(s, NULL, 10) : CONFIG_BOOTDELAY;
345 #ifdef CONFIG_OF_CONTROL
346 bootdelay = fdtdec_get_config_int(gd->fdt_blob, "bootdelay",
350 debug ("### main_loop entered: bootdelay=%d\n\n", bootdelay);
352 #if defined(CONFIG_MENU_SHOW)
353 bootdelay = menu_show(bootdelay);
355 # ifdef CONFIG_BOOT_RETRY_TIME
357 # endif /* CONFIG_BOOT_RETRY_TIME */
360 if (gd->flags & GD_FLG_POSTFAIL) {
361 s = getenv("failbootcmd");
364 #endif /* CONFIG_POST */
365 #ifdef CONFIG_BOOTCOUNT_LIMIT
366 if (bootlimit && (bootcount > bootlimit)) {
367 printf ("Warning: Bootlimit (%u) exceeded. Using altbootcmd.\n",
368 (unsigned)bootlimit);
369 s = getenv ("altbootcmd");
372 #endif /* CONFIG_BOOTCOUNT_LIMIT */
373 s = getenv ("bootcmd");
374 #ifdef CONFIG_OF_CONTROL
375 /* Allow the fdt to override the boot command */
376 env = fdtdec_get_config_string(gd->fdt_blob, "bootcmd");
380 process_fdt_options(gd->fdt_blob);
383 * If the bootsecure option was chosen, use secure_boot_cmd().
384 * Always use 'env' in this case, since bootsecure requres that the
385 * bootcmd was specified in the FDT too.
387 if (fdtdec_get_config_int(gd->fdt_blob, "bootsecure", 0))
388 secure_boot_cmd(env);
390 #endif /* CONFIG_OF_CONTROL */
392 debug ("### main_loop: bootcmd=\"%s\"\n", s ? s : "<UNDEFINED>");
394 if (bootdelay != -1 && s && !abortboot(bootdelay)) {
395 #if defined(CONFIG_AUTOBOOT_KEYED) && !defined(CONFIG_AUTOBOOT_KEYED_CTRLC)
396 int prev = disable_ctrlc(1); /* disable Control C checking */
399 run_command_list(s, -1, 0);
401 #if defined(CONFIG_AUTOBOOT_KEYED) && !defined(CONFIG_AUTOBOOT_KEYED_CTRLC)
402 disable_ctrlc(prev); /* restore Control C checking */
406 #ifdef CONFIG_MENUKEY
407 if (menukey == CONFIG_MENUKEY) {
408 s = getenv("menucmd");
410 run_command_list(s, -1, 0);
412 #endif /* CONFIG_MENUKEY */
414 #endif /* CONFIG_BOOTDELAY */
418 #ifndef CONFIG_SYS_HUSH_PARSER
419 static char lastcommand[CONFIG_SYS_CBSIZE] = { 0, };
424 #ifdef CONFIG_PREBOOT
428 bootstage_mark_name(BOOTSTAGE_ID_MAIN_LOOP, "main_loop");
430 #ifndef CONFIG_SYS_GENERIC_BOARD
431 puts("Warning: Your board does not use generic board. Please read\n");
432 puts("doc/README.generic-board and take action. Boards not\n");
433 puts("upgraded by the late 2014 may break or be removed.\n");
436 #ifdef CONFIG_MODEM_SUPPORT
437 debug("DEBUG: main_loop: do_mdm_init=%d\n", do_mdm_init);
439 char *str = strdup(getenv("mdm_cmd"));
440 setenv("preboot", str); /* set or delete definition */
443 mdm_init(); /* wait for modem connection */
445 #endif /* CONFIG_MODEM_SUPPORT */
447 #ifdef CONFIG_VERSION_VARIABLE
449 setenv("ver", version_string); /* set version variable */
451 #endif /* CONFIG_VERSION_VARIABLE */
453 #ifdef CONFIG_SYS_HUSH_PARSER
457 #if defined(CONFIG_HUSH_INIT_VAR)
461 #ifdef CONFIG_PREBOOT
462 p = getenv("preboot");
464 # ifdef CONFIG_AUTOBOOT_KEYED
465 int prev = disable_ctrlc(1); /* disable Control C checking */
468 run_command_list(p, -1, 0);
470 # ifdef CONFIG_AUTOBOOT_KEYED
471 disable_ctrlc(prev); /* restore Control C checking */
474 #endif /* CONFIG_PREBOOT */
476 #if defined(CONFIG_UPDATE_TFTP)
478 #endif /* CONFIG_UPDATE_TFTP */
480 #ifdef CONFIG_BOOTDELAY
481 process_boot_delay();
484 * Main Loop for Monitor Command Processing
486 #ifdef CONFIG_SYS_HUSH_PARSER
488 /* This point is never reached */
492 #ifdef CONFIG_BOOT_RETRY_TIME
494 /* Saw enough of a valid command to
495 * restart the timeout.
500 len = readline (CONFIG_SYS_PROMPT);
502 flag = 0; /* assume no special flags for now */
504 strcpy (lastcommand, console_buffer);
506 flag |= CMD_FLAG_REPEAT;
507 #ifdef CONFIG_BOOT_RETRY_TIME
508 else if (len == -2) {
509 /* -2 means timed out, retry autoboot
511 puts ("\nTimed out waiting for command\n");
512 # ifdef CONFIG_RESET_TO_RETRY
513 /* Reinit board to run initialization code again */
514 do_reset (NULL, 0, 0, NULL);
516 return; /* retry autoboot */
522 puts ("<INTERRUPT>\n");
524 rc = run_command(lastcommand, flag);
527 /* invalid command or not repeatable, forget it */
531 #endif /*CONFIG_SYS_HUSH_PARSER*/
534 #ifdef CONFIG_BOOT_RETRY_TIME
535 /***************************************************************************
536 * initialize command line timeout
538 void init_cmd_timeout(void)
540 char *s = getenv ("bootretry");
543 retry_time = (int)simple_strtol(s, NULL, 10);
545 retry_time = CONFIG_BOOT_RETRY_TIME;
547 if (retry_time >= 0 && retry_time < CONFIG_BOOT_RETRY_MIN)
548 retry_time = CONFIG_BOOT_RETRY_MIN;
551 /***************************************************************************
552 * reset command line timeout to retry_time seconds
554 void reset_cmd_timeout(void)
556 endtime = endtick(retry_time);
560 #ifdef CONFIG_CMDLINE_EDITING
563 * cmdline-editing related codes from vivi.
564 * Author: Janghoon Lyu <nandy@mizi.com>
567 #define putnstr(str,n) do { \
568 printf ("%.*s", (int)n, str); \
571 #define CTL_CH(c) ((c) - 'a' + 1)
572 #define CTL_BACKSPACE ('\b')
573 #define DEL ((char)255)
574 #define DEL7 ((char)127)
575 #define CREAD_HIST_CHAR ('!')
577 #define getcmd_putch(ch) putc(ch)
578 #define getcmd_getch() getc()
579 #define getcmd_cbeep() getcmd_putch('\a')
582 #define HIST_SIZE CONFIG_SYS_CBSIZE
585 static int hist_add_idx;
586 static int hist_cur = -1;
587 static unsigned hist_num;
589 static char *hist_list[HIST_MAX];
590 static char hist_lines[HIST_MAX][HIST_SIZE + 1]; /* Save room for NULL */
592 #define add_idx_minus_one() ((hist_add_idx == 0) ? hist_max : hist_add_idx-1)
594 static void hist_init(void)
603 for (i = 0; i < HIST_MAX; i++) {
604 hist_list[i] = hist_lines[i];
605 hist_list[i][0] = '\0';
609 static void cread_add_to_hist(char *line)
611 strcpy(hist_list[hist_add_idx], line);
613 if (++hist_add_idx >= HIST_MAX)
616 if (hist_add_idx > hist_max)
617 hist_max = hist_add_idx;
622 static char* hist_prev(void)
634 if (hist_cur == hist_add_idx) {
638 ret = hist_list[hist_cur];
643 static char* hist_next(void)
650 if (hist_cur == hist_add_idx)
653 if (++hist_cur > hist_max)
656 if (hist_cur == hist_add_idx) {
659 ret = hist_list[hist_cur];
664 #ifndef CONFIG_CMDLINE_EDITING
665 static void cread_print_hist_list(void)
670 n = hist_num - hist_max;
672 i = hist_add_idx + 1;
676 if (i == hist_add_idx)
678 printf("%s\n", hist_list[i]);
683 #endif /* CONFIG_CMDLINE_EDITING */
685 #define BEGINNING_OF_LINE() { \
687 getcmd_putch(CTL_BACKSPACE); \
692 #define ERASE_TO_EOL() { \
693 if (num < eol_num) { \
694 printf("%*s", (int)(eol_num - num), ""); \
696 getcmd_putch(CTL_BACKSPACE); \
697 } while (--eol_num > num); \
701 #define REFRESH_TO_EOL() { \
702 if (num < eol_num) { \
703 wlen = eol_num - num; \
704 putnstr(buf + num, wlen); \
709 static void cread_add_char(char ichar, int insert, unsigned long *num,
710 unsigned long *eol_num, char *buf, unsigned long len)
715 if (insert || *num == *eol_num) {
716 if (*eol_num > len - 1) {
724 wlen = *eol_num - *num;
726 memmove(&buf[*num+1], &buf[*num], wlen-1);
730 putnstr(buf + *num, wlen);
733 getcmd_putch(CTL_BACKSPACE);
736 /* echo the character */
739 putnstr(buf + *num, wlen);
744 static void cread_add_str(char *str, int strsize, int insert, unsigned long *num,
745 unsigned long *eol_num, char *buf, unsigned long len)
748 cread_add_char(*str, insert, num, eol_num, buf, len);
753 static int cread_line(const char *const prompt, char *buf, unsigned int *len,
756 unsigned long num = 0;
757 unsigned long eol_num = 0;
763 int init_len = strlen(buf);
767 cread_add_str(buf, init_len, 1, &num, &eol_num, buf, *len);
770 #ifdef CONFIG_BOOT_RETRY_TIME
771 while (!tstc()) { /* while no incoming data */
772 if (retry_time >= 0 && get_ticks() > endtime)
773 return (-2); /* timed out */
777 if (first && timeout) {
778 uint64_t etime = endtick(timeout);
780 while (!tstc()) { /* while no incoming data */
781 if (get_ticks() >= etime)
782 return -2; /* timed out */
788 ichar = getcmd_getch();
790 if ((ichar == '\n') || (ichar == '\r')) {
796 * handle standard linux xterm esc sequences for arrow key, etc.
801 esc_save[esc_len] = ichar;
804 cread_add_str(esc_save, esc_len, insert,
805 &num, &eol_num, buf, *len);
813 case 'D': /* <- key */
817 case 'C': /* -> key */
820 break; /* pass off to ^F handler */
821 case 'H': /* Home key */
824 break; /* pass off to ^A handler */
825 case 'A': /* up arrow */
828 break; /* pass off to ^P handler */
829 case 'B': /* down arrow */
832 break; /* pass off to ^N handler */
834 esc_save[esc_len++] = ichar;
835 cread_add_str(esc_save, esc_len, insert,
836 &num, &eol_num, buf, *len);
845 esc_save[esc_len] = ichar;
848 puts("impossible condition #876\n");
856 case CTL_CH('c'): /* ^C - break */
857 *buf = '\0'; /* discard input */
861 getcmd_putch(buf[num]);
867 getcmd_putch(CTL_BACKSPACE);
873 wlen = eol_num - num - 1;
875 memmove(&buf[num], &buf[num+1], wlen);
876 putnstr(buf + num, wlen);
881 getcmd_putch(CTL_BACKSPACE);
904 wlen = eol_num - num;
906 memmove(&buf[num], &buf[num+1], wlen);
907 getcmd_putch(CTL_BACKSPACE);
908 putnstr(buf + num, wlen);
911 getcmd_putch(CTL_BACKSPACE);
923 if (ichar == CTL_CH('p'))
933 /* nuke the current line */
937 /* erase to end of line */
940 /* copy new line into place and display */
942 eol_num = strlen(buf);
946 #ifdef CONFIG_AUTO_COMPLETE
950 /* do not autocomplete when in the middle */
957 col = strlen(prompt) + eol_num;
959 if (cmd_auto_complete(prompt, buf, &num2, &col)) {
968 cread_add_char(ichar, insert, &num, &eol_num, buf, *len);
973 buf[eol_num] = '\0'; /* lose the newline */
975 if (buf[0] && buf[0] != CREAD_HIST_CHAR)
976 cread_add_to_hist(buf);
977 hist_cur = hist_add_idx;
982 #endif /* CONFIG_CMDLINE_EDITING */
984 /****************************************************************************/
987 * Prompt for input and read a line.
988 * If CONFIG_BOOT_RETRY_TIME is defined and retry_time >= 0,
989 * time out when time goes past endtime (timebase time in ticks).
990 * Return: number of read characters
994 int readline (const char *const prompt)
997 * If console_buffer isn't 0-length the user will be prompted to modify
998 * it instead of entering it from scratch as desired.
1000 console_buffer[0] = '\0';
1002 return readline_into_buffer(prompt, console_buffer, 0);
1006 int readline_into_buffer(const char *const prompt, char *buffer, int timeout)
1009 #ifdef CONFIG_CMDLINE_EDITING
1010 unsigned int len = CONFIG_SYS_CBSIZE;
1012 static int initted = 0;
1015 * History uses a global array which is not
1016 * writable until after relocation to RAM.
1017 * Revert to non-history version if still
1018 * running from flash.
1020 if (gd->flags & GD_FLG_RELOC) {
1029 rc = cread_line(prompt, p, &len, timeout);
1030 return rc < 0 ? rc : len;
1033 #endif /* CONFIG_CMDLINE_EDITING */
1035 int n = 0; /* buffer index */
1036 int plen = 0; /* prompt length */
1037 int col; /* output column cnt */
1042 plen = strlen (prompt);
1048 #ifdef CONFIG_BOOT_RETRY_TIME
1049 while (!tstc()) { /* while no incoming data */
1050 if (retry_time >= 0 && get_ticks() > endtime)
1051 return (-2); /* timed out */
1055 WATCHDOG_RESET(); /* Trigger watchdog, if needed */
1057 #ifdef CONFIG_SHOW_ACTIVITY
1066 * Special character handling
1069 case '\r': /* Enter */
1075 case '\0': /* nul */
1078 case 0x03: /* ^C - break */
1079 p_buf[0] = '\0'; /* discard input */
1082 case 0x15: /* ^U - erase line */
1083 while (col > plen) {
1091 case 0x17: /* ^W - erase word */
1092 p=delete_char(p_buf, p, &col, &n, plen);
1093 while ((n > 0) && (*p != ' ')) {
1094 p=delete_char(p_buf, p, &col, &n, plen);
1098 case 0x08: /* ^H - backspace */
1099 case 0x7F: /* DEL - backspace */
1100 p=delete_char(p_buf, p, &col, &n, plen);
1105 * Must be a normal character then
1107 if (n < CONFIG_SYS_CBSIZE-2) {
1108 if (c == '\t') { /* expand TABs */
1109 #ifdef CONFIG_AUTO_COMPLETE
1110 /* if auto completion triggered just continue */
1112 if (cmd_auto_complete(prompt, console_buffer, &n, &col)) {
1113 p = p_buf + n; /* reset */
1117 puts (tab_seq+(col&07));
1118 col += 8 - (col&07);
1123 * Echo input using puts() to force an
1124 * LCD flush if we are using an LCD
1133 } else { /* Buffer full */
1138 #ifdef CONFIG_CMDLINE_EDITING
1143 /****************************************************************************/
1145 static char * delete_char (char *buffer, char *p, int *colp, int *np, int plen)
1153 if (*(--p) == '\t') { /* will retype the whole line */
1154 while (*colp > plen) {
1158 for (s=buffer; s<p; ++s) {
1160 puts (tab_seq+((*colp) & 07));
1161 *colp += 8 - ((*colp) & 07);
1175 /****************************************************************************/
1177 int parse_line (char *line, char *argv[])
1181 debug_parser("parse_line: \"%s\"\n", line);
1182 while (nargs < CONFIG_SYS_MAXARGS) {
1184 /* skip any white space */
1185 while (isblank(*line))
1188 if (*line == '\0') { /* end of line, no more args */
1190 debug_parser("parse_line: nargs=%d\n", nargs);
1194 argv[nargs++] = line; /* begin of argument string */
1196 /* find end of string */
1197 while (*line && !isblank(*line))
1200 if (*line == '\0') { /* end of line, no more args */
1202 debug_parser("parse_line: nargs=%d\n", nargs);
1206 *line++ = '\0'; /* terminate current arg */
1209 printf ("** Too many args (max. %d) **\n", CONFIG_SYS_MAXARGS);
1211 debug_parser("parse_line: nargs=%d\n", nargs);
1215 /****************************************************************************/
1217 #ifndef CONFIG_SYS_HUSH_PARSER
1218 static void process_macros (const char *input, char *output)
1221 const char *varname_start = NULL;
1222 int inputcnt = strlen (input);
1223 int outputcnt = CONFIG_SYS_CBSIZE;
1224 int state = 0; /* 0 = waiting for '$' */
1226 /* 1 = waiting for '(' or '{' */
1227 /* 2 = waiting for ')' or '}' */
1228 /* 3 = waiting for ''' */
1229 char *output_start = output;
1231 debug_parser("[PROCESS_MACROS] INPUT len %zd: \"%s\"\n", strlen(input),
1234 prev = '\0'; /* previous character */
1236 while (inputcnt && outputcnt) {
1241 /* remove one level of escape characters */
1242 if ((c == '\\') && (prev != '\\')) {
1243 if (inputcnt-- == 0)
1251 case 0: /* Waiting for (unescaped) $ */
1252 if ((c == '\'') && (prev != '\\')) {
1256 if ((c == '$') && (prev != '\\')) {
1263 case 1: /* Waiting for ( */
1264 if (c == '(' || c == '{') {
1266 varname_start = input;
1278 case 2: /* Waiting for ) */
1279 if (c == ')' || c == '}') {
1281 char envname[CONFIG_SYS_CBSIZE], *envval;
1282 int envcnt = input - varname_start - 1; /* Varname # of chars */
1284 /* Get the varname */
1285 for (i = 0; i < envcnt; i++) {
1286 envname[i] = varname_start[i];
1291 envval = getenv (envname);
1293 /* Copy into the line if it exists */
1295 while ((*envval) && outputcnt) {
1296 *(output++) = *(envval++);
1299 /* Look for another '$' */
1303 case 3: /* Waiting for ' */
1304 if ((c == '\'') && (prev != '\\')) {
1320 debug_parser("[PROCESS_MACROS] OUTPUT len %zd: \"%s\"\n",
1321 strlen(output_start), output_start);
1324 /****************************************************************************
1326 * 1 - command executed, repeatable
1327 * 0 - command executed but not repeatable, interrupted commands are
1328 * always considered not repeatable
1329 * -1 - not executed (unrecognized, bootd recursion or too many args)
1330 * (If cmd is NULL or "" or longer than CONFIG_SYS_CBSIZE-1 it is
1331 * considered unrecognized)
1335 * We must create a temporary copy of the command since the command we get
1336 * may be the result from getenv(), which returns a pointer directly to
1337 * the environment data, which may change magicly when the command we run
1338 * creates or modifies environment variables (like "bootp" does).
1340 static int builtin_run_command(const char *cmd, int flag)
1342 char cmdbuf[CONFIG_SYS_CBSIZE]; /* working copy of cmd */
1343 char *token; /* start of token in cmdbuf */
1344 char *sep; /* end of token (separator) in cmdbuf */
1345 char finaltoken[CONFIG_SYS_CBSIZE];
1347 char *argv[CONFIG_SYS_MAXARGS + 1]; /* NULL terminated */
1352 debug_parser("[RUN_COMMAND] cmd[%p]=\"", cmd);
1354 /* use puts - string may be loooong */
1355 puts(cmd ? cmd : "NULL");
1358 clear_ctrlc(); /* forget any previous Control C */
1360 if (!cmd || !*cmd) {
1361 return -1; /* empty command */
1364 if (strlen(cmd) >= CONFIG_SYS_CBSIZE) {
1365 puts ("## Command too long!\n");
1369 strcpy (cmdbuf, cmd);
1371 /* Process separators and check for invalid
1372 * repeatable commands
1375 debug_parser("[PROCESS_SEPARATORS] %s\n", cmd);
1379 * Find separator, or string end
1380 * Allow simple escape of ';' by writing "\;"
1382 for (inquotes = 0, sep = str; *sep; sep++) {
1388 (*sep == ';') && /* separator */
1389 ( sep != str) && /* past string start */
1390 (*(sep-1) != '\\')) /* and NOT escaped */
1395 * Limit the token to data between separators
1399 str = sep + 1; /* start of command for next pass */
1403 str = sep; /* no more commands for next pass */
1404 debug_parser("token: \"%s\"\n", token);
1406 /* find macros in this token and replace them */
1407 process_macros (token, finaltoken);
1409 /* Extract arguments */
1410 if ((argc = parse_line (finaltoken, argv)) == 0) {
1411 rc = -1; /* no command at all */
1415 if (cmd_process(flag, argc, argv, &repeatable, NULL))
1418 /* Did the user stop this? */
1420 return -1; /* if stopped then not repeatable */
1423 return rc ? rc : repeatable;
1428 * Run a command using the selected parser.
1430 * @param cmd Command to run
1431 * @param flag Execution flags (CMD_FLAG_...)
1432 * @return 0 on success, or != 0 on error.
1434 int run_command(const char *cmd, int flag)
1436 #ifndef CONFIG_SYS_HUSH_PARSER
1438 * builtin_run_command can return 0 or 1 for success, so clean up
1441 if (builtin_run_command(cmd, flag) == -1)
1446 return parse_string_outer(cmd,
1447 FLAG_PARSE_SEMICOLON | FLAG_EXIT_FROM_LOOP);
1451 #ifndef CONFIG_SYS_HUSH_PARSER
1453 * Execute a list of command separated by ; or \n using the built-in parser.
1455 * This function cannot take a const char * for the command, since if it
1456 * finds newlines in the string, it replaces them with \0.
1458 * @param cmd String containing list of commands
1459 * @param flag Execution flags (CMD_FLAG_...)
1460 * @return 0 on success, or != 0 on error.
1462 static int builtin_run_command_list(char *cmd, int flag)
1468 * Break into individual lines, and execute each line; terminate on
1473 if (*next == '\n') {
1475 /* run only non-empty commands */
1477 debug("** exec: \"%s\"\n", line);
1478 if (builtin_run_command(line, 0) < 0) {
1487 if (rcode == 0 && *line)
1488 rcode = (builtin_run_command(line, 0) >= 0);
1494 int run_command_list(const char *cmd, int len, int flag)
1497 char *buff = (char *)cmd; /* cast away const */
1502 #ifdef CONFIG_SYS_HUSH_PARSER
1503 /* hush will never change our string */
1506 /* the built-in parser will change our string if it sees \n */
1507 need_buff = strchr(cmd, '\n') != NULL;
1511 buff = malloc(len + 1);
1514 memcpy(buff, cmd, len);
1517 #ifdef CONFIG_SYS_HUSH_PARSER
1518 rcode = parse_string_outer(buff, FLAG_PARSE_SEMICOLON);
1521 * This function will overwrite any \n it sees with a \0, which
1522 * is why it can't work with a const char *. Here we are making
1523 * using of internal knowledge of this function, to avoid always
1524 * doing a malloc() which is actually required only in a case that
1527 rcode = builtin_run_command_list(buff, flag);
1535 /****************************************************************************/
1537 #if defined(CONFIG_CMD_RUN)
1538 int do_run (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
1543 return CMD_RET_USAGE;
1545 for (i=1; i<argc; ++i) {
1548 if ((arg = getenv (argv[i])) == NULL) {
1549 printf ("## Error: \"%s\" not defined\n", argv[i]);
1553 if (run_command_list(arg, -1, flag) != 0)