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 * See file CREDITS for list of people who contributed to this
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.
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.
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,
39 #include <linux/ctype.h>
41 DECLARE_GLOBAL_DATA_PTR;
44 * Board-specific Platform code can reimplement show_boot_progress () if needed
46 void inline __show_boot_progress (int val) {}
47 void show_boot_progress (int val) __attribute__((weak, alias("__show_boot_progress")));
49 #define MAX_DELAY_STOP_STR 32
51 #define DEBUG_PARSER 0 /* set to 1 to debug */
53 #define debug_parser(fmt, args...) \
54 debug_cond(DEBUG_PARSER, fmt, ##args)
56 #ifndef DEBUG_BOOTKEYS
57 #define DEBUG_BOOTKEYS 0
59 #define debug_bootkeys(fmt, args...) \
60 debug_cond(DEBUG_BOOTKEYS, fmt, ##args)
62 char console_buffer[CONFIG_SYS_CBSIZE + 1]; /* console I/O buffer */
64 static char * delete_char (char *buffer, char *p, int *colp, int *np, int plen);
65 static const char erase_seq[] = "\b \b"; /* erase sequence */
66 static const char tab_seq[] = " "; /* used to expand TABs */
68 #ifdef CONFIG_BOOT_RETRY_TIME
69 static uint64_t endtime = 0; /* must be set, default is instant timeout */
70 static int retry_time = -1; /* -1 so can call readline before main_loop */
73 #define endtick(seconds) (get_ticks() + (uint64_t)(seconds) * get_tbclk())
75 #ifndef CONFIG_BOOT_RETRY_MIN
76 #define CONFIG_BOOT_RETRY_MIN CONFIG_BOOT_RETRY_TIME
79 #ifdef CONFIG_MODEM_SUPPORT
81 extern void mdm_init(void); /* defined in board.c */
84 /***************************************************************************
85 * Watch for 'delay' seconds for autoboot stop or autoboot delay string.
86 * returns: 0 - no key string, allow autoboot 1 - got key string, abort
88 #if defined(CONFIG_BOOTDELAY)
89 # if defined(CONFIG_AUTOBOOT_KEYED)
90 static int abortboot_keyed(int bootdelay)
93 uint64_t etime = endtick(bootdelay);
100 { str: getenv ("bootdelaykey"), retry: 1 },
101 { str: getenv ("bootdelaykey2"), retry: 1 },
102 { str: getenv ("bootstopkey"), retry: 0 },
103 { str: getenv ("bootstopkey2"), retry: 0 },
106 char presskey [MAX_DELAY_STOP_STR];
107 u_int presskey_len = 0;
108 u_int presskey_max = 0;
111 #ifndef CONFIG_ZERO_BOOTDELAY_CHECK
116 # ifdef CONFIG_AUTOBOOT_PROMPT
117 printf(CONFIG_AUTOBOOT_PROMPT);
120 # ifdef CONFIG_AUTOBOOT_DELAY_STR
121 if (delaykey[0].str == NULL)
122 delaykey[0].str = CONFIG_AUTOBOOT_DELAY_STR;
124 # ifdef CONFIG_AUTOBOOT_DELAY_STR2
125 if (delaykey[1].str == NULL)
126 delaykey[1].str = CONFIG_AUTOBOOT_DELAY_STR2;
128 # ifdef CONFIG_AUTOBOOT_STOP_STR
129 if (delaykey[2].str == NULL)
130 delaykey[2].str = CONFIG_AUTOBOOT_STOP_STR;
132 # ifdef CONFIG_AUTOBOOT_STOP_STR2
133 if (delaykey[3].str == NULL)
134 delaykey[3].str = CONFIG_AUTOBOOT_STOP_STR2;
137 for (i = 0; i < sizeof(delaykey) / sizeof(delaykey[0]); i ++) {
138 delaykey[i].len = delaykey[i].str == NULL ?
139 0 : strlen (delaykey[i].str);
140 delaykey[i].len = delaykey[i].len > MAX_DELAY_STOP_STR ?
141 MAX_DELAY_STOP_STR : delaykey[i].len;
143 presskey_max = presskey_max > delaykey[i].len ?
144 presskey_max : delaykey[i].len;
146 debug_bootkeys("%s key:<%s>\n",
147 delaykey[i].retry ? "delay" : "stop",
148 delaykey[i].str ? delaykey[i].str : "NULL");
151 /* In order to keep up with incoming data, check timeout only
156 if (presskey_len < presskey_max) {
157 presskey [presskey_len ++] = getc();
160 for (i = 0; i < presskey_max - 1; i ++)
161 presskey [i] = presskey [i + 1];
163 presskey [i] = getc();
167 for (i = 0; i < sizeof(delaykey) / sizeof(delaykey[0]); i ++) {
168 if (delaykey[i].len > 0 &&
169 presskey_len >= delaykey[i].len &&
170 memcmp (presskey + presskey_len - delaykey[i].len,
172 delaykey[i].len) == 0) {
173 debug_bootkeys("got %skey\n",
174 delaykey[i].retry ? "delay" :
177 # ifdef CONFIG_BOOT_RETRY_TIME
178 /* don't retry auto boot */
179 if (! delaykey[i].retry)
185 } while (!abort && get_ticks() <= etime);
188 debug_bootkeys("key timeout\n");
190 #ifdef CONFIG_SILENT_CONSOLE
192 gd->flags &= ~GD_FLG_SILENT;
198 # else /* !defined(CONFIG_AUTOBOOT_KEYED) */
200 #ifdef CONFIG_MENUKEY
201 static int menukey = 0;
204 static int abortboot_normal(int bootdelay)
209 #ifdef CONFIG_MENUPROMPT
210 printf(CONFIG_MENUPROMPT);
213 printf("Hit any key to stop autoboot: %2d ", bootdelay);
216 #if defined CONFIG_ZERO_BOOTDELAY_CHECK
218 * Check if key already pressed
219 * Don't check if bootdelay < 0
221 if (bootdelay >= 0) {
222 if (tstc()) { /* we got a key press */
223 (void) getc(); /* consume input */
225 abort = 1; /* don't auto boot */
230 while ((bootdelay > 0) && (!abort)) {
235 if (tstc()) { /* we got a key press */
236 abort = 1; /* don't auto boot */
237 bootdelay = 0; /* no more delay */
238 # ifdef CONFIG_MENUKEY
241 (void) getc(); /* consume input */
246 } while (!abort && get_timer(ts) < 1000);
248 printf("\b\b\b%2d ", bootdelay);
253 #ifdef CONFIG_SILENT_CONSOLE
255 gd->flags &= ~GD_FLG_SILENT;
260 # endif /* CONFIG_AUTOBOOT_KEYED */
262 static int abortboot(int bootdelay)
264 #ifdef CONFIG_AUTOBOOT_KEYED
265 return abortboot_keyed(bootdelay);
267 return abortboot_normal(bootdelay);
270 #endif /* CONFIG_BOOTDELAY */
273 * Runs the given boot command securely. Specifically:
274 * - Doesn't run the command with the shell (run_command or parse_string_outer),
275 * since that's a lot of code surface that an attacker might exploit.
276 * Because of this, we don't do any argument parsing--the secure boot command
277 * has to be a full-fledged u-boot command.
278 * - Doesn't check for keypresses before booting, since that could be a
279 * security hole; also disables Ctrl-C.
280 * - Doesn't allow the command to return.
282 * Upon any failures, this function will drop into an infinite loop after
283 * printing the error message to console.
286 #if defined(CONFIG_BOOTDELAY) && defined(CONFIG_OF_CONTROL)
287 static void secure_boot_cmd(char *cmd)
293 printf("## Error: Secure boot command not specified\n");
297 /* Disable Ctrl-C just in case some command is used that checks it. */
300 /* Find the command directly. */
301 cmdtp = find_cmd(cmd);
303 printf("## Error: \"%s\" not defined\n", cmd);
307 /* Run the command, forcing no flags and faking argc and argv. */
308 rc = (cmdtp->cmd)(cmdtp, 0, 1, &cmd);
310 /* Shouldn't ever return from boot command. */
311 printf("## Error: \"%s\" returned (code %d)\n", cmd, rc);
315 * Not a whole lot to do here. Rebooting won't help much, since we'll
316 * just end up right back here. Just loop.
321 static void process_fdt_options(const void *blob)
325 /* Add an env variable to point to a kernel payload, if available */
326 addr = fdtdec_get_config_int(gd->fdt_blob, "kernel-offset", 0);
328 setenv_addr("kernaddr", (void *)(CONFIG_SYS_TEXT_BASE + addr));
330 /* Add an env variable to point to a root disk, if available */
331 addr = fdtdec_get_config_int(gd->fdt_blob, "rootdisk-offset", 0);
333 setenv_addr("rootaddr", (void *)(CONFIG_SYS_TEXT_BASE + addr));
335 #endif /* CONFIG_OF_CONTROL */
337 #ifdef CONFIG_BOOTDELAY
338 static void process_boot_delay(void)
340 #ifdef CONFIG_OF_CONTROL
345 #ifdef CONFIG_BOOTCOUNT_LIMIT
346 unsigned long bootcount = 0;
347 unsigned long bootlimit = 0;
348 #endif /* CONFIG_BOOTCOUNT_LIMIT */
350 #ifdef CONFIG_BOOTCOUNT_LIMIT
351 bootcount = bootcount_load();
353 bootcount_store (bootcount);
354 setenv_ulong("bootcount", bootcount);
355 bootlimit = getenv_ulong("bootlimit", 10, 0);
356 #endif /* CONFIG_BOOTCOUNT_LIMIT */
358 s = getenv ("bootdelay");
359 bootdelay = s ? (int)simple_strtol(s, NULL, 10) : CONFIG_BOOTDELAY;
361 debug ("### main_loop entered: bootdelay=%d\n\n", bootdelay);
363 #if defined(CONFIG_MENU_SHOW)
364 bootdelay = menu_show(bootdelay);
366 # ifdef CONFIG_BOOT_RETRY_TIME
368 # endif /* CONFIG_BOOT_RETRY_TIME */
371 if (gd->flags & GD_FLG_POSTFAIL) {
372 s = getenv("failbootcmd");
375 #endif /* CONFIG_POST */
376 #ifdef CONFIG_BOOTCOUNT_LIMIT
377 if (bootlimit && (bootcount > bootlimit)) {
378 printf ("Warning: Bootlimit (%u) exceeded. Using altbootcmd.\n",
379 (unsigned)bootlimit);
380 s = getenv ("altbootcmd");
383 #endif /* CONFIG_BOOTCOUNT_LIMIT */
384 s = getenv ("bootcmd");
385 #ifdef CONFIG_OF_CONTROL
386 /* Allow the fdt to override the boot command */
387 env = fdtdec_get_config_string(gd->fdt_blob, "bootcmd");
391 process_fdt_options(gd->fdt_blob);
394 * If the bootsecure option was chosen, use secure_boot_cmd().
395 * Always use 'env' in this case, since bootsecure requres that the
396 * bootcmd was specified in the FDT too.
398 if (fdtdec_get_config_int(gd->fdt_blob, "bootsecure", 0))
399 secure_boot_cmd(env);
401 #endif /* CONFIG_OF_CONTROL */
403 debug ("### main_loop: bootcmd=\"%s\"\n", s ? s : "<UNDEFINED>");
405 if (bootdelay != -1 && s && !abortboot(bootdelay)) {
406 #ifdef CONFIG_AUTOBOOT_KEYED
407 int prev = disable_ctrlc(1); /* disable Control C checking */
410 run_command_list(s, -1, 0);
412 #ifdef CONFIG_AUTOBOOT_KEYED
413 disable_ctrlc(prev); /* restore Control C checking */
417 #ifdef CONFIG_MENUKEY
418 if (menukey == CONFIG_MENUKEY) {
419 s = getenv("menucmd");
421 run_command_list(s, -1, 0);
423 #endif /* CONFIG_MENUKEY */
425 #endif /* CONFIG_BOOTDELAY */
429 #ifndef CONFIG_SYS_HUSH_PARSER
430 static char lastcommand[CONFIG_SYS_CBSIZE] = { 0, };
435 #ifdef CONFIG_PREBOOT
439 bootstage_mark_name(BOOTSTAGE_ID_MAIN_LOOP, "main_loop");
441 #ifdef CONFIG_MODEM_SUPPORT
442 debug("DEBUG: main_loop: do_mdm_init=%d\n", do_mdm_init);
444 char *str = strdup(getenv("mdm_cmd"));
445 setenv("preboot", str); /* set or delete definition */
448 mdm_init(); /* wait for modem connection */
450 #endif /* CONFIG_MODEM_SUPPORT */
452 #ifdef CONFIG_VERSION_VARIABLE
454 setenv("ver", version_string); /* set version variable */
456 #endif /* CONFIG_VERSION_VARIABLE */
458 #ifdef CONFIG_SYS_HUSH_PARSER
462 #if defined(CONFIG_HUSH_INIT_VAR)
466 #ifdef CONFIG_PREBOOT
467 p = getenv("preboot");
469 # ifdef CONFIG_AUTOBOOT_KEYED
470 int prev = disable_ctrlc(1); /* disable Control C checking */
473 run_command_list(p, -1, 0);
475 # ifdef CONFIG_AUTOBOOT_KEYED
476 disable_ctrlc(prev); /* restore Control C checking */
479 #endif /* CONFIG_PREBOOT */
481 #if defined(CONFIG_UPDATE_TFTP)
483 #endif /* CONFIG_UPDATE_TFTP */
485 #ifdef CONFIG_BOOTDELAY
486 process_boot_delay();
489 * Main Loop for Monitor Command Processing
491 #ifdef CONFIG_SYS_HUSH_PARSER
493 /* This point is never reached */
497 #ifdef CONFIG_BOOT_RETRY_TIME
499 /* Saw enough of a valid command to
500 * restart the timeout.
505 len = readline (CONFIG_SYS_PROMPT);
507 flag = 0; /* assume no special flags for now */
509 strcpy (lastcommand, console_buffer);
511 flag |= CMD_FLAG_REPEAT;
512 #ifdef CONFIG_BOOT_RETRY_TIME
513 else if (len == -2) {
514 /* -2 means timed out, retry autoboot
516 puts ("\nTimed out waiting for command\n");
517 # ifdef CONFIG_RESET_TO_RETRY
518 /* Reinit board to run initialization code again */
519 do_reset (NULL, 0, 0, NULL);
521 return; /* retry autoboot */
527 puts ("<INTERRUPT>\n");
529 rc = run_command(lastcommand, flag);
532 /* invalid command or not repeatable, forget it */
536 #endif /*CONFIG_SYS_HUSH_PARSER*/
539 #ifdef CONFIG_BOOT_RETRY_TIME
540 /***************************************************************************
541 * initialize command line timeout
543 void init_cmd_timeout(void)
545 char *s = getenv ("bootretry");
548 retry_time = (int)simple_strtol(s, NULL, 10);
550 retry_time = CONFIG_BOOT_RETRY_TIME;
552 if (retry_time >= 0 && retry_time < CONFIG_BOOT_RETRY_MIN)
553 retry_time = CONFIG_BOOT_RETRY_MIN;
556 /***************************************************************************
557 * reset command line timeout to retry_time seconds
559 void reset_cmd_timeout(void)
561 endtime = endtick(retry_time);
565 #ifdef CONFIG_CMDLINE_EDITING
568 * cmdline-editing related codes from vivi.
569 * Author: Janghoon Lyu <nandy@mizi.com>
572 #define putnstr(str,n) do { \
573 printf ("%.*s", (int)n, str); \
576 #define CTL_CH(c) ((c) - 'a' + 1)
577 #define CTL_BACKSPACE ('\b')
578 #define DEL ((char)255)
579 #define DEL7 ((char)127)
580 #define CREAD_HIST_CHAR ('!')
582 #define getcmd_putch(ch) putc(ch)
583 #define getcmd_getch() getc()
584 #define getcmd_cbeep() getcmd_putch('\a')
587 #define HIST_SIZE CONFIG_SYS_CBSIZE
590 static int hist_add_idx;
591 static int hist_cur = -1;
592 static unsigned hist_num;
594 static char *hist_list[HIST_MAX];
595 static char hist_lines[HIST_MAX][HIST_SIZE + 1]; /* Save room for NULL */
597 #define add_idx_minus_one() ((hist_add_idx == 0) ? hist_max : hist_add_idx-1)
599 static void hist_init(void)
608 for (i = 0; i < HIST_MAX; i++) {
609 hist_list[i] = hist_lines[i];
610 hist_list[i][0] = '\0';
614 static void cread_add_to_hist(char *line)
616 strcpy(hist_list[hist_add_idx], line);
618 if (++hist_add_idx >= HIST_MAX)
621 if (hist_add_idx > hist_max)
622 hist_max = hist_add_idx;
627 static char* hist_prev(void)
639 if (hist_cur == hist_add_idx) {
643 ret = hist_list[hist_cur];
648 static char* hist_next(void)
655 if (hist_cur == hist_add_idx)
658 if (++hist_cur > hist_max)
661 if (hist_cur == hist_add_idx) {
664 ret = hist_list[hist_cur];
669 #ifndef CONFIG_CMDLINE_EDITING
670 static void cread_print_hist_list(void)
675 n = hist_num - hist_max;
677 i = hist_add_idx + 1;
681 if (i == hist_add_idx)
683 printf("%s\n", hist_list[i]);
688 #endif /* CONFIG_CMDLINE_EDITING */
690 #define BEGINNING_OF_LINE() { \
692 getcmd_putch(CTL_BACKSPACE); \
697 #define ERASE_TO_EOL() { \
698 if (num < eol_num) { \
699 printf("%*s", (int)(eol_num - num), ""); \
701 getcmd_putch(CTL_BACKSPACE); \
702 } while (--eol_num > num); \
706 #define REFRESH_TO_EOL() { \
707 if (num < eol_num) { \
708 wlen = eol_num - num; \
709 putnstr(buf + num, wlen); \
714 static void cread_add_char(char ichar, int insert, unsigned long *num,
715 unsigned long *eol_num, char *buf, unsigned long len)
720 if (insert || *num == *eol_num) {
721 if (*eol_num > len - 1) {
729 wlen = *eol_num - *num;
731 memmove(&buf[*num+1], &buf[*num], wlen-1);
735 putnstr(buf + *num, wlen);
738 getcmd_putch(CTL_BACKSPACE);
741 /* echo the character */
744 putnstr(buf + *num, wlen);
749 static void cread_add_str(char *str, int strsize, int insert, unsigned long *num,
750 unsigned long *eol_num, char *buf, unsigned long len)
753 cread_add_char(*str, insert, num, eol_num, buf, len);
758 static int cread_line(const char *const prompt, char *buf, unsigned int *len,
761 unsigned long num = 0;
762 unsigned long eol_num = 0;
768 int init_len = strlen(buf);
772 cread_add_str(buf, init_len, 1, &num, &eol_num, buf, *len);
775 #ifdef CONFIG_BOOT_RETRY_TIME
776 while (!tstc()) { /* while no incoming data */
777 if (retry_time >= 0 && get_ticks() > endtime)
778 return (-2); /* timed out */
782 if (first && timeout) {
783 uint64_t etime = endtick(timeout);
785 while (!tstc()) { /* while no incoming data */
786 if (get_ticks() >= etime)
787 return -2; /* timed out */
793 ichar = getcmd_getch();
795 if ((ichar == '\n') || (ichar == '\r')) {
801 * handle standard linux xterm esc sequences for arrow key, etc.
806 esc_save[esc_len] = ichar;
809 cread_add_str(esc_save, esc_len, insert,
810 &num, &eol_num, buf, *len);
818 case 'D': /* <- key */
822 case 'C': /* -> key */
825 break; /* pass off to ^F handler */
826 case 'H': /* Home key */
829 break; /* pass off to ^A handler */
830 case 'A': /* up arrow */
833 break; /* pass off to ^P handler */
834 case 'B': /* down arrow */
837 break; /* pass off to ^N handler */
839 esc_save[esc_len++] = ichar;
840 cread_add_str(esc_save, esc_len, insert,
841 &num, &eol_num, buf, *len);
850 esc_save[esc_len] = ichar;
853 puts("impossible condition #876\n");
861 case CTL_CH('c'): /* ^C - break */
862 *buf = '\0'; /* discard input */
866 getcmd_putch(buf[num]);
872 getcmd_putch(CTL_BACKSPACE);
878 wlen = eol_num - num - 1;
880 memmove(&buf[num], &buf[num+1], wlen);
881 putnstr(buf + num, wlen);
886 getcmd_putch(CTL_BACKSPACE);
909 wlen = eol_num - num;
911 memmove(&buf[num], &buf[num+1], wlen);
912 getcmd_putch(CTL_BACKSPACE);
913 putnstr(buf + num, wlen);
916 getcmd_putch(CTL_BACKSPACE);
928 if (ichar == CTL_CH('p'))
938 /* nuke the current line */
942 /* erase to end of line */
945 /* copy new line into place and display */
947 eol_num = strlen(buf);
951 #ifdef CONFIG_AUTO_COMPLETE
955 /* do not autocomplete when in the middle */
962 col = strlen(prompt) + eol_num;
964 if (cmd_auto_complete(prompt, buf, &num2, &col)) {
973 cread_add_char(ichar, insert, &num, &eol_num, buf, *len);
978 buf[eol_num] = '\0'; /* lose the newline */
980 if (buf[0] && buf[0] != CREAD_HIST_CHAR)
981 cread_add_to_hist(buf);
982 hist_cur = hist_add_idx;
987 #endif /* CONFIG_CMDLINE_EDITING */
989 /****************************************************************************/
992 * Prompt for input and read a line.
993 * If CONFIG_BOOT_RETRY_TIME is defined and retry_time >= 0,
994 * time out when time goes past endtime (timebase time in ticks).
995 * Return: number of read characters
999 int readline (const char *const prompt)
1002 * If console_buffer isn't 0-length the user will be prompted to modify
1003 * it instead of entering it from scratch as desired.
1005 console_buffer[0] = '\0';
1007 return readline_into_buffer(prompt, console_buffer, 0);
1011 int readline_into_buffer(const char *const prompt, char *buffer, int timeout)
1014 #ifdef CONFIG_CMDLINE_EDITING
1015 unsigned int len = CONFIG_SYS_CBSIZE;
1017 static int initted = 0;
1020 * History uses a global array which is not
1021 * writable until after relocation to RAM.
1022 * Revert to non-history version if still
1023 * running from flash.
1025 if (gd->flags & GD_FLG_RELOC) {
1034 rc = cread_line(prompt, p, &len, timeout);
1035 return rc < 0 ? rc : len;
1038 #endif /* CONFIG_CMDLINE_EDITING */
1040 int n = 0; /* buffer index */
1041 int plen = 0; /* prompt length */
1042 int col; /* output column cnt */
1047 plen = strlen (prompt);
1053 #ifdef CONFIG_BOOT_RETRY_TIME
1054 while (!tstc()) { /* while no incoming data */
1055 if (retry_time >= 0 && get_ticks() > endtime)
1056 return (-2); /* timed out */
1060 WATCHDOG_RESET(); /* Trigger watchdog, if needed */
1062 #ifdef CONFIG_SHOW_ACTIVITY
1071 * Special character handling
1074 case '\r': /* Enter */
1080 case '\0': /* nul */
1083 case 0x03: /* ^C - break */
1084 p_buf[0] = '\0'; /* discard input */
1087 case 0x15: /* ^U - erase line */
1088 while (col > plen) {
1096 case 0x17: /* ^W - erase word */
1097 p=delete_char(p_buf, p, &col, &n, plen);
1098 while ((n > 0) && (*p != ' ')) {
1099 p=delete_char(p_buf, p, &col, &n, plen);
1103 case 0x08: /* ^H - backspace */
1104 case 0x7F: /* DEL - backspace */
1105 p=delete_char(p_buf, p, &col, &n, plen);
1110 * Must be a normal character then
1112 if (n < CONFIG_SYS_CBSIZE-2) {
1113 if (c == '\t') { /* expand TABs */
1114 #ifdef CONFIG_AUTO_COMPLETE
1115 /* if auto completion triggered just continue */
1117 if (cmd_auto_complete(prompt, console_buffer, &n, &col)) {
1118 p = p_buf + n; /* reset */
1122 puts (tab_seq+(col&07));
1123 col += 8 - (col&07);
1128 * Echo input using puts() to force an
1129 * LCD flush if we are using an LCD
1138 } else { /* Buffer full */
1143 #ifdef CONFIG_CMDLINE_EDITING
1148 /****************************************************************************/
1150 static char * delete_char (char *buffer, char *p, int *colp, int *np, int plen)
1158 if (*(--p) == '\t') { /* will retype the whole line */
1159 while (*colp > plen) {
1163 for (s=buffer; s<p; ++s) {
1165 puts (tab_seq+((*colp) & 07));
1166 *colp += 8 - ((*colp) & 07);
1180 /****************************************************************************/
1182 int parse_line (char *line, char *argv[])
1186 debug_parser("parse_line: \"%s\"\n", line);
1187 while (nargs < CONFIG_SYS_MAXARGS) {
1189 /* skip any white space */
1190 while (isblank(*line))
1193 if (*line == '\0') { /* end of line, no more args */
1195 debug_parser("parse_line: nargs=%d\n", nargs);
1199 argv[nargs++] = line; /* begin of argument string */
1201 /* find end of string */
1202 while (*line && !isblank(*line))
1205 if (*line == '\0') { /* end of line, no more args */
1207 debug_parser("parse_line: nargs=%d\n", nargs);
1211 *line++ = '\0'; /* terminate current arg */
1214 printf ("** Too many args (max. %d) **\n", CONFIG_SYS_MAXARGS);
1216 debug_parser("parse_line: nargs=%d\n", nargs);
1220 /****************************************************************************/
1222 #ifndef CONFIG_SYS_HUSH_PARSER
1223 static void process_macros (const char *input, char *output)
1226 const char *varname_start = NULL;
1227 int inputcnt = strlen (input);
1228 int outputcnt = CONFIG_SYS_CBSIZE;
1229 int state = 0; /* 0 = waiting for '$' */
1231 /* 1 = waiting for '(' or '{' */
1232 /* 2 = waiting for ')' or '}' */
1233 /* 3 = waiting for ''' */
1234 char *output_start = output;
1236 debug_parser("[PROCESS_MACROS] INPUT len %zd: \"%s\"\n", strlen(input),
1239 prev = '\0'; /* previous character */
1241 while (inputcnt && outputcnt) {
1246 /* remove one level of escape characters */
1247 if ((c == '\\') && (prev != '\\')) {
1248 if (inputcnt-- == 0)
1256 case 0: /* Waiting for (unescaped) $ */
1257 if ((c == '\'') && (prev != '\\')) {
1261 if ((c == '$') && (prev != '\\')) {
1268 case 1: /* Waiting for ( */
1269 if (c == '(' || c == '{') {
1271 varname_start = input;
1283 case 2: /* Waiting for ) */
1284 if (c == ')' || c == '}') {
1286 char envname[CONFIG_SYS_CBSIZE], *envval;
1287 int envcnt = input - varname_start - 1; /* Varname # of chars */
1289 /* Get the varname */
1290 for (i = 0; i < envcnt; i++) {
1291 envname[i] = varname_start[i];
1296 envval = getenv (envname);
1298 /* Copy into the line if it exists */
1300 while ((*envval) && outputcnt) {
1301 *(output++) = *(envval++);
1304 /* Look for another '$' */
1308 case 3: /* Waiting for ' */
1309 if ((c == '\'') && (prev != '\\')) {
1325 debug_parser("[PROCESS_MACROS] OUTPUT len %zd: \"%s\"\n",
1326 strlen(output_start), output_start);
1329 /****************************************************************************
1331 * 1 - command executed, repeatable
1332 * 0 - command executed but not repeatable, interrupted commands are
1333 * always considered not repeatable
1334 * -1 - not executed (unrecognized, bootd recursion or too many args)
1335 * (If cmd is NULL or "" or longer than CONFIG_SYS_CBSIZE-1 it is
1336 * considered unrecognized)
1340 * We must create a temporary copy of the command since the command we get
1341 * may be the result from getenv(), which returns a pointer directly to
1342 * the environment data, which may change magicly when the command we run
1343 * creates or modifies environment variables (like "bootp" does).
1345 static int builtin_run_command(const char *cmd, int flag)
1347 char cmdbuf[CONFIG_SYS_CBSIZE]; /* working copy of cmd */
1348 char *token; /* start of token in cmdbuf */
1349 char *sep; /* end of token (separator) in cmdbuf */
1350 char finaltoken[CONFIG_SYS_CBSIZE];
1352 char *argv[CONFIG_SYS_MAXARGS + 1]; /* NULL terminated */
1357 debug_parser("[RUN_COMMAND] cmd[%p]=\"", cmd);
1359 /* use puts - string may be loooong */
1360 puts(cmd ? cmd : "NULL");
1363 clear_ctrlc(); /* forget any previous Control C */
1365 if (!cmd || !*cmd) {
1366 return -1; /* empty command */
1369 if (strlen(cmd) >= CONFIG_SYS_CBSIZE) {
1370 puts ("## Command too long!\n");
1374 strcpy (cmdbuf, cmd);
1376 /* Process separators and check for invalid
1377 * repeatable commands
1380 debug_parser("[PROCESS_SEPARATORS] %s\n", cmd);
1384 * Find separator, or string end
1385 * Allow simple escape of ';' by writing "\;"
1387 for (inquotes = 0, sep = str; *sep; sep++) {
1393 (*sep == ';') && /* separator */
1394 ( sep != str) && /* past string start */
1395 (*(sep-1) != '\\')) /* and NOT escaped */
1400 * Limit the token to data between separators
1404 str = sep + 1; /* start of command for next pass */
1408 str = sep; /* no more commands for next pass */
1409 debug_parser("token: \"%s\"\n", token);
1411 /* find macros in this token and replace them */
1412 process_macros (token, finaltoken);
1414 /* Extract arguments */
1415 if ((argc = parse_line (finaltoken, argv)) == 0) {
1416 rc = -1; /* no command at all */
1420 if (cmd_process(flag, argc, argv, &repeatable, NULL))
1423 /* Did the user stop this? */
1425 return -1; /* if stopped then not repeatable */
1428 return rc ? rc : repeatable;
1433 * Run a command using the selected parser.
1435 * @param cmd Command to run
1436 * @param flag Execution flags (CMD_FLAG_...)
1437 * @return 0 on success, or != 0 on error.
1439 int run_command(const char *cmd, int flag)
1441 #ifndef CONFIG_SYS_HUSH_PARSER
1443 * builtin_run_command can return 0 or 1 for success, so clean up
1446 if (builtin_run_command(cmd, flag) == -1)
1451 return parse_string_outer(cmd,
1452 FLAG_PARSE_SEMICOLON | FLAG_EXIT_FROM_LOOP);
1456 #ifndef CONFIG_SYS_HUSH_PARSER
1458 * Execute a list of command separated by ; or \n using the built-in parser.
1460 * This function cannot take a const char * for the command, since if it
1461 * finds newlines in the string, it replaces them with \0.
1463 * @param cmd String containing list of commands
1464 * @param flag Execution flags (CMD_FLAG_...)
1465 * @return 0 on success, or != 0 on error.
1467 static int builtin_run_command_list(char *cmd, int flag)
1473 * Break into individual lines, and execute each line; terminate on
1478 if (*next == '\n') {
1480 /* run only non-empty commands */
1482 debug("** exec: \"%s\"\n", line);
1483 if (builtin_run_command(line, 0) < 0) {
1492 if (rcode == 0 && *line)
1493 rcode = (builtin_run_command(line, 0) >= 0);
1499 int run_command_list(const char *cmd, int len, int flag)
1502 char *buff = (char *)cmd; /* cast away const */
1507 #ifdef CONFIG_SYS_HUSH_PARSER
1508 /* hush will never change our string */
1511 /* the built-in parser will change our string if it sees \n */
1512 need_buff = strchr(cmd, '\n') != NULL;
1516 buff = malloc(len + 1);
1519 memcpy(buff, cmd, len);
1522 #ifdef CONFIG_SYS_HUSH_PARSER
1523 rcode = parse_string_outer(buff, FLAG_PARSE_SEMICOLON);
1526 * This function will overwrite any \n it sees with a \0, which
1527 * is why it can't work with a const char *. Here we are making
1528 * using of internal knowledge of this function, to avoid always
1529 * doing a malloc() which is actually required only in a case that
1532 rcode = builtin_run_command_list(buff, flag);
1540 /****************************************************************************/
1542 #if defined(CONFIG_CMD_RUN)
1543 int do_run (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
1548 return CMD_RET_USAGE;
1550 for (i=1; i<argc; ++i) {
1553 if ((arg = getenv (argv[i])) == NULL) {
1554 printf ("## Error: \"%s\" not defined\n", argv[i]);
1558 if (run_command(arg, flag) != 0)