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 #ifdef CONFIG_MODEM_SUPPORT
431 debug("DEBUG: main_loop: do_mdm_init=%d\n", do_mdm_init);
433 char *str = strdup(getenv("mdm_cmd"));
434 setenv("preboot", str); /* set or delete definition */
437 mdm_init(); /* wait for modem connection */
439 #endif /* CONFIG_MODEM_SUPPORT */
441 #ifdef CONFIG_VERSION_VARIABLE
443 setenv("ver", version_string); /* set version variable */
445 #endif /* CONFIG_VERSION_VARIABLE */
447 #ifdef CONFIG_SYS_HUSH_PARSER
451 #if defined(CONFIG_HUSH_INIT_VAR)
455 #ifdef CONFIG_PREBOOT
456 p = getenv("preboot");
458 # ifdef CONFIG_AUTOBOOT_KEYED
459 int prev = disable_ctrlc(1); /* disable Control C checking */
462 run_command_list(p, -1, 0);
464 # ifdef CONFIG_AUTOBOOT_KEYED
465 disable_ctrlc(prev); /* restore Control C checking */
468 #endif /* CONFIG_PREBOOT */
470 #if defined(CONFIG_UPDATE_TFTP)
472 #endif /* CONFIG_UPDATE_TFTP */
474 #ifdef CONFIG_BOOTDELAY
475 process_boot_delay();
478 * Main Loop for Monitor Command Processing
480 #ifdef CONFIG_SYS_HUSH_PARSER
482 /* This point is never reached */
486 #ifdef CONFIG_BOOT_RETRY_TIME
488 /* Saw enough of a valid command to
489 * restart the timeout.
494 len = readline (CONFIG_SYS_PROMPT);
496 flag = 0; /* assume no special flags for now */
498 strcpy (lastcommand, console_buffer);
500 flag |= CMD_FLAG_REPEAT;
501 #ifdef CONFIG_BOOT_RETRY_TIME
502 else if (len == -2) {
503 /* -2 means timed out, retry autoboot
505 puts ("\nTimed out waiting for command\n");
506 # ifdef CONFIG_RESET_TO_RETRY
507 /* Reinit board to run initialization code again */
508 do_reset (NULL, 0, 0, NULL);
510 return; /* retry autoboot */
516 puts ("<INTERRUPT>\n");
518 rc = run_command(lastcommand, flag);
521 /* invalid command or not repeatable, forget it */
525 #endif /*CONFIG_SYS_HUSH_PARSER*/
528 #ifdef CONFIG_BOOT_RETRY_TIME
529 /***************************************************************************
530 * initialize command line timeout
532 void init_cmd_timeout(void)
534 char *s = getenv ("bootretry");
537 retry_time = (int)simple_strtol(s, NULL, 10);
539 retry_time = CONFIG_BOOT_RETRY_TIME;
541 if (retry_time >= 0 && retry_time < CONFIG_BOOT_RETRY_MIN)
542 retry_time = CONFIG_BOOT_RETRY_MIN;
545 /***************************************************************************
546 * reset command line timeout to retry_time seconds
548 void reset_cmd_timeout(void)
550 endtime = endtick(retry_time);
554 #ifdef CONFIG_CMDLINE_EDITING
557 * cmdline-editing related codes from vivi.
558 * Author: Janghoon Lyu <nandy@mizi.com>
561 #define putnstr(str,n) do { \
562 printf ("%.*s", (int)n, str); \
565 #define CTL_CH(c) ((c) - 'a' + 1)
566 #define CTL_BACKSPACE ('\b')
567 #define DEL ((char)255)
568 #define DEL7 ((char)127)
569 #define CREAD_HIST_CHAR ('!')
571 #define getcmd_putch(ch) putc(ch)
572 #define getcmd_getch() getc()
573 #define getcmd_cbeep() getcmd_putch('\a')
576 #define HIST_SIZE CONFIG_SYS_CBSIZE
579 static int hist_add_idx;
580 static int hist_cur = -1;
581 static unsigned hist_num;
583 static char *hist_list[HIST_MAX];
584 static char hist_lines[HIST_MAX][HIST_SIZE + 1]; /* Save room for NULL */
586 #define add_idx_minus_one() ((hist_add_idx == 0) ? hist_max : hist_add_idx-1)
588 static void hist_init(void)
597 for (i = 0; i < HIST_MAX; i++) {
598 hist_list[i] = hist_lines[i];
599 hist_list[i][0] = '\0';
603 static void cread_add_to_hist(char *line)
605 strcpy(hist_list[hist_add_idx], line);
607 if (++hist_add_idx >= HIST_MAX)
610 if (hist_add_idx > hist_max)
611 hist_max = hist_add_idx;
616 static char* hist_prev(void)
628 if (hist_cur == hist_add_idx) {
632 ret = hist_list[hist_cur];
637 static char* hist_next(void)
644 if (hist_cur == hist_add_idx)
647 if (++hist_cur > hist_max)
650 if (hist_cur == hist_add_idx) {
653 ret = hist_list[hist_cur];
658 #ifndef CONFIG_CMDLINE_EDITING
659 static void cread_print_hist_list(void)
664 n = hist_num - hist_max;
666 i = hist_add_idx + 1;
670 if (i == hist_add_idx)
672 printf("%s\n", hist_list[i]);
677 #endif /* CONFIG_CMDLINE_EDITING */
679 #define BEGINNING_OF_LINE() { \
681 getcmd_putch(CTL_BACKSPACE); \
686 #define ERASE_TO_EOL() { \
687 if (num < eol_num) { \
688 printf("%*s", (int)(eol_num - num), ""); \
690 getcmd_putch(CTL_BACKSPACE); \
691 } while (--eol_num > num); \
695 #define REFRESH_TO_EOL() { \
696 if (num < eol_num) { \
697 wlen = eol_num - num; \
698 putnstr(buf + num, wlen); \
703 static void cread_add_char(char ichar, int insert, unsigned long *num,
704 unsigned long *eol_num, char *buf, unsigned long len)
709 if (insert || *num == *eol_num) {
710 if (*eol_num > len - 1) {
718 wlen = *eol_num - *num;
720 memmove(&buf[*num+1], &buf[*num], wlen-1);
724 putnstr(buf + *num, wlen);
727 getcmd_putch(CTL_BACKSPACE);
730 /* echo the character */
733 putnstr(buf + *num, wlen);
738 static void cread_add_str(char *str, int strsize, int insert, unsigned long *num,
739 unsigned long *eol_num, char *buf, unsigned long len)
742 cread_add_char(*str, insert, num, eol_num, buf, len);
747 static int cread_line(const char *const prompt, char *buf, unsigned int *len,
750 unsigned long num = 0;
751 unsigned long eol_num = 0;
757 int init_len = strlen(buf);
761 cread_add_str(buf, init_len, 1, &num, &eol_num, buf, *len);
764 #ifdef CONFIG_BOOT_RETRY_TIME
765 while (!tstc()) { /* while no incoming data */
766 if (retry_time >= 0 && get_ticks() > endtime)
767 return (-2); /* timed out */
771 if (first && timeout) {
772 uint64_t etime = endtick(timeout);
774 while (!tstc()) { /* while no incoming data */
775 if (get_ticks() >= etime)
776 return -2; /* timed out */
782 ichar = getcmd_getch();
784 if ((ichar == '\n') || (ichar == '\r')) {
790 * handle standard linux xterm esc sequences for arrow key, etc.
795 esc_save[esc_len] = ichar;
798 cread_add_str(esc_save, esc_len, insert,
799 &num, &eol_num, buf, *len);
807 case 'D': /* <- key */
811 case 'C': /* -> key */
814 break; /* pass off to ^F handler */
815 case 'H': /* Home key */
818 break; /* pass off to ^A handler */
819 case 'A': /* up arrow */
822 break; /* pass off to ^P handler */
823 case 'B': /* down arrow */
826 break; /* pass off to ^N handler */
828 esc_save[esc_len++] = ichar;
829 cread_add_str(esc_save, esc_len, insert,
830 &num, &eol_num, buf, *len);
839 esc_save[esc_len] = ichar;
842 puts("impossible condition #876\n");
850 case CTL_CH('c'): /* ^C - break */
851 *buf = '\0'; /* discard input */
855 getcmd_putch(buf[num]);
861 getcmd_putch(CTL_BACKSPACE);
867 wlen = eol_num - num - 1;
869 memmove(&buf[num], &buf[num+1], wlen);
870 putnstr(buf + num, wlen);
875 getcmd_putch(CTL_BACKSPACE);
898 wlen = eol_num - num;
900 memmove(&buf[num], &buf[num+1], wlen);
901 getcmd_putch(CTL_BACKSPACE);
902 putnstr(buf + num, wlen);
905 getcmd_putch(CTL_BACKSPACE);
917 if (ichar == CTL_CH('p'))
927 /* nuke the current line */
931 /* erase to end of line */
934 /* copy new line into place and display */
936 eol_num = strlen(buf);
940 #ifdef CONFIG_AUTO_COMPLETE
944 /* do not autocomplete when in the middle */
951 col = strlen(prompt) + eol_num;
953 if (cmd_auto_complete(prompt, buf, &num2, &col)) {
962 cread_add_char(ichar, insert, &num, &eol_num, buf, *len);
967 buf[eol_num] = '\0'; /* lose the newline */
969 if (buf[0] && buf[0] != CREAD_HIST_CHAR)
970 cread_add_to_hist(buf);
971 hist_cur = hist_add_idx;
976 #endif /* CONFIG_CMDLINE_EDITING */
978 /****************************************************************************/
981 * Prompt for input and read a line.
982 * If CONFIG_BOOT_RETRY_TIME is defined and retry_time >= 0,
983 * time out when time goes past endtime (timebase time in ticks).
984 * Return: number of read characters
988 int readline (const char *const prompt)
991 * If console_buffer isn't 0-length the user will be prompted to modify
992 * it instead of entering it from scratch as desired.
994 console_buffer[0] = '\0';
996 return readline_into_buffer(prompt, console_buffer, 0);
1000 int readline_into_buffer(const char *const prompt, char *buffer, int timeout)
1003 #ifdef CONFIG_CMDLINE_EDITING
1004 unsigned int len = CONFIG_SYS_CBSIZE;
1006 static int initted = 0;
1009 * History uses a global array which is not
1010 * writable until after relocation to RAM.
1011 * Revert to non-history version if still
1012 * running from flash.
1014 if (gd->flags & GD_FLG_RELOC) {
1023 rc = cread_line(prompt, p, &len, timeout);
1024 return rc < 0 ? rc : len;
1027 #endif /* CONFIG_CMDLINE_EDITING */
1029 int n = 0; /* buffer index */
1030 int plen = 0; /* prompt length */
1031 int col; /* output column cnt */
1036 plen = strlen (prompt);
1042 #ifdef CONFIG_BOOT_RETRY_TIME
1043 while (!tstc()) { /* while no incoming data */
1044 if (retry_time >= 0 && get_ticks() > endtime)
1045 return (-2); /* timed out */
1049 WATCHDOG_RESET(); /* Trigger watchdog, if needed */
1051 #ifdef CONFIG_SHOW_ACTIVITY
1060 * Special character handling
1063 case '\r': /* Enter */
1069 case '\0': /* nul */
1072 case 0x03: /* ^C - break */
1073 p_buf[0] = '\0'; /* discard input */
1076 case 0x15: /* ^U - erase line */
1077 while (col > plen) {
1085 case 0x17: /* ^W - erase word */
1086 p=delete_char(p_buf, p, &col, &n, plen);
1087 while ((n > 0) && (*p != ' ')) {
1088 p=delete_char(p_buf, p, &col, &n, plen);
1092 case 0x08: /* ^H - backspace */
1093 case 0x7F: /* DEL - backspace */
1094 p=delete_char(p_buf, p, &col, &n, plen);
1099 * Must be a normal character then
1101 if (n < CONFIG_SYS_CBSIZE-2) {
1102 if (c == '\t') { /* expand TABs */
1103 #ifdef CONFIG_AUTO_COMPLETE
1104 /* if auto completion triggered just continue */
1106 if (cmd_auto_complete(prompt, console_buffer, &n, &col)) {
1107 p = p_buf + n; /* reset */
1111 puts (tab_seq+(col&07));
1112 col += 8 - (col&07);
1117 * Echo input using puts() to force an
1118 * LCD flush if we are using an LCD
1127 } else { /* Buffer full */
1132 #ifdef CONFIG_CMDLINE_EDITING
1137 /****************************************************************************/
1139 static char * delete_char (char *buffer, char *p, int *colp, int *np, int plen)
1147 if (*(--p) == '\t') { /* will retype the whole line */
1148 while (*colp > plen) {
1152 for (s=buffer; s<p; ++s) {
1154 puts (tab_seq+((*colp) & 07));
1155 *colp += 8 - ((*colp) & 07);
1169 /****************************************************************************/
1171 int parse_line (char *line, char *argv[])
1175 debug_parser("parse_line: \"%s\"\n", line);
1176 while (nargs < CONFIG_SYS_MAXARGS) {
1178 /* skip any white space */
1179 while (isblank(*line))
1182 if (*line == '\0') { /* end of line, no more args */
1184 debug_parser("parse_line: nargs=%d\n", nargs);
1188 argv[nargs++] = line; /* begin of argument string */
1190 /* find end of string */
1191 while (*line && !isblank(*line))
1194 if (*line == '\0') { /* end of line, no more args */
1196 debug_parser("parse_line: nargs=%d\n", nargs);
1200 *line++ = '\0'; /* terminate current arg */
1203 printf ("** Too many args (max. %d) **\n", CONFIG_SYS_MAXARGS);
1205 debug_parser("parse_line: nargs=%d\n", nargs);
1209 /****************************************************************************/
1211 #ifndef CONFIG_SYS_HUSH_PARSER
1212 static void process_macros (const char *input, char *output)
1215 const char *varname_start = NULL;
1216 int inputcnt = strlen (input);
1217 int outputcnt = CONFIG_SYS_CBSIZE;
1218 int state = 0; /* 0 = waiting for '$' */
1220 /* 1 = waiting for '(' or '{' */
1221 /* 2 = waiting for ')' or '}' */
1222 /* 3 = waiting for ''' */
1223 char *output_start = output;
1225 debug_parser("[PROCESS_MACROS] INPUT len %zd: \"%s\"\n", strlen(input),
1228 prev = '\0'; /* previous character */
1230 while (inputcnt && outputcnt) {
1235 /* remove one level of escape characters */
1236 if ((c == '\\') && (prev != '\\')) {
1237 if (inputcnt-- == 0)
1245 case 0: /* Waiting for (unescaped) $ */
1246 if ((c == '\'') && (prev != '\\')) {
1250 if ((c == '$') && (prev != '\\')) {
1257 case 1: /* Waiting for ( */
1258 if (c == '(' || c == '{') {
1260 varname_start = input;
1272 case 2: /* Waiting for ) */
1273 if (c == ')' || c == '}') {
1275 char envname[CONFIG_SYS_CBSIZE], *envval;
1276 int envcnt = input - varname_start - 1; /* Varname # of chars */
1278 /* Get the varname */
1279 for (i = 0; i < envcnt; i++) {
1280 envname[i] = varname_start[i];
1285 envval = getenv (envname);
1287 /* Copy into the line if it exists */
1289 while ((*envval) && outputcnt) {
1290 *(output++) = *(envval++);
1293 /* Look for another '$' */
1297 case 3: /* Waiting for ' */
1298 if ((c == '\'') && (prev != '\\')) {
1314 debug_parser("[PROCESS_MACROS] OUTPUT len %zd: \"%s\"\n",
1315 strlen(output_start), output_start);
1318 /****************************************************************************
1320 * 1 - command executed, repeatable
1321 * 0 - command executed but not repeatable, interrupted commands are
1322 * always considered not repeatable
1323 * -1 - not executed (unrecognized, bootd recursion or too many args)
1324 * (If cmd is NULL or "" or longer than CONFIG_SYS_CBSIZE-1 it is
1325 * considered unrecognized)
1329 * We must create a temporary copy of the command since the command we get
1330 * may be the result from getenv(), which returns a pointer directly to
1331 * the environment data, which may change magicly when the command we run
1332 * creates or modifies environment variables (like "bootp" does).
1334 static int builtin_run_command(const char *cmd, int flag)
1336 char cmdbuf[CONFIG_SYS_CBSIZE]; /* working copy of cmd */
1337 char *token; /* start of token in cmdbuf */
1338 char *sep; /* end of token (separator) in cmdbuf */
1339 char finaltoken[CONFIG_SYS_CBSIZE];
1341 char *argv[CONFIG_SYS_MAXARGS + 1]; /* NULL terminated */
1346 debug_parser("[RUN_COMMAND] cmd[%p]=\"", cmd);
1348 /* use puts - string may be loooong */
1349 puts(cmd ? cmd : "NULL");
1352 clear_ctrlc(); /* forget any previous Control C */
1354 if (!cmd || !*cmd) {
1355 return -1; /* empty command */
1358 if (strlen(cmd) >= CONFIG_SYS_CBSIZE) {
1359 puts ("## Command too long!\n");
1363 strcpy (cmdbuf, cmd);
1365 /* Process separators and check for invalid
1366 * repeatable commands
1369 debug_parser("[PROCESS_SEPARATORS] %s\n", cmd);
1373 * Find separator, or string end
1374 * Allow simple escape of ';' by writing "\;"
1376 for (inquotes = 0, sep = str; *sep; sep++) {
1382 (*sep == ';') && /* separator */
1383 ( sep != str) && /* past string start */
1384 (*(sep-1) != '\\')) /* and NOT escaped */
1389 * Limit the token to data between separators
1393 str = sep + 1; /* start of command for next pass */
1397 str = sep; /* no more commands for next pass */
1398 debug_parser("token: \"%s\"\n", token);
1400 /* find macros in this token and replace them */
1401 process_macros (token, finaltoken);
1403 /* Extract arguments */
1404 if ((argc = parse_line (finaltoken, argv)) == 0) {
1405 rc = -1; /* no command at all */
1409 if (cmd_process(flag, argc, argv, &repeatable, NULL))
1412 /* Did the user stop this? */
1414 return -1; /* if stopped then not repeatable */
1417 return rc ? rc : repeatable;
1422 * Run a command using the selected parser.
1424 * @param cmd Command to run
1425 * @param flag Execution flags (CMD_FLAG_...)
1426 * @return 0 on success, or != 0 on error.
1428 int run_command(const char *cmd, int flag)
1430 #ifndef CONFIG_SYS_HUSH_PARSER
1432 * builtin_run_command can return 0 or 1 for success, so clean up
1435 if (builtin_run_command(cmd, flag) == -1)
1440 return parse_string_outer(cmd,
1441 FLAG_PARSE_SEMICOLON | FLAG_EXIT_FROM_LOOP);
1445 #ifndef CONFIG_SYS_HUSH_PARSER
1447 * Execute a list of command separated by ; or \n using the built-in parser.
1449 * This function cannot take a const char * for the command, since if it
1450 * finds newlines in the string, it replaces them with \0.
1452 * @param cmd String containing list of commands
1453 * @param flag Execution flags (CMD_FLAG_...)
1454 * @return 0 on success, or != 0 on error.
1456 static int builtin_run_command_list(char *cmd, int flag)
1462 * Break into individual lines, and execute each line; terminate on
1467 if (*next == '\n') {
1469 /* run only non-empty commands */
1471 debug("** exec: \"%s\"\n", line);
1472 if (builtin_run_command(line, 0) < 0) {
1481 if (rcode == 0 && *line)
1482 rcode = (builtin_run_command(line, 0) >= 0);
1488 int run_command_list(const char *cmd, int len, int flag)
1491 char *buff = (char *)cmd; /* cast away const */
1496 #ifdef CONFIG_SYS_HUSH_PARSER
1497 /* hush will never change our string */
1500 /* the built-in parser will change our string if it sees \n */
1501 need_buff = strchr(cmd, '\n') != NULL;
1505 buff = malloc(len + 1);
1508 memcpy(buff, cmd, len);
1511 #ifdef CONFIG_SYS_HUSH_PARSER
1512 rcode = parse_string_outer(buff, FLAG_PARSE_SEMICOLON);
1515 * This function will overwrite any \n it sees with a \0, which
1516 * is why it can't work with a const char *. Here we are making
1517 * using of internal knowledge of this function, to avoid always
1518 * doing a malloc() which is actually required only in a case that
1521 rcode = builtin_run_command_list(buff, flag);
1529 /****************************************************************************/
1531 #if defined(CONFIG_CMD_RUN)
1532 int do_run (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
1537 return CMD_RET_USAGE;
1539 for (i=1; i<argc; ++i) {
1542 if ((arg = getenv (argv[i])) == NULL) {
1543 printf ("## Error: \"%s\" not defined\n", argv[i]);
1547 if (run_command(arg, flag) != 0)