]> git.sur5r.net Git - u-boot/blob - common/main.c
fdt: Allow device tree to specify secure booting
[u-boot] / common / main.c
1 /*
2  * (C) Copyright 2000
3  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
4  *
5  * Add to readline cmdline-editing by
6  * (C) Copyright 2005
7  * JinHua Luo, GuangDong Linux Center, <luo.jinhua@gd-linux.com>
8  *
9  * See file CREDITS for list of people who contributed to this
10  * project.
11  *
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.
16  *
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.
21  *
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,
25  * MA 02111-1307 USA
26  */
27
28 /* #define      DEBUG   */
29
30 #include <common.h>
31 #include <watchdog.h>
32 #include <command.h>
33 #include <fdtdec.h>
34 #include <malloc.h>
35 #include <version.h>
36 #ifdef CONFIG_MODEM_SUPPORT
37 #include <malloc.h>             /* for free() prototype */
38 #endif
39
40 #ifdef CONFIG_SYS_HUSH_PARSER
41 #include <hush.h>
42 #endif
43
44 #ifdef CONFIG_OF_CONTROL
45 #include <fdtdec.h>
46 #endif
47
48 #ifdef CONFIG_OF_LIBFDT
49 #include <fdt_support.h>
50 #endif /* CONFIG_OF_LIBFDT */
51
52 #include <post.h>
53 #include <linux/ctype.h>
54 #include <menu.h>
55
56 #if defined(CONFIG_SILENT_CONSOLE) || defined(CONFIG_POST) || defined(CONFIG_CMDLINE_EDITING)
57 DECLARE_GLOBAL_DATA_PTR;
58 #endif
59
60 /*
61  * Board-specific Platform code can reimplement show_boot_progress () if needed
62  */
63 void inline __show_boot_progress (int val) {}
64 void show_boot_progress (int val) __attribute__((weak, alias("__show_boot_progress")));
65
66 #if defined(CONFIG_UPDATE_TFTP)
67 int update_tftp (ulong addr);
68 #endif /* CONFIG_UPDATE_TFTP */
69
70 #define MAX_DELAY_STOP_STR 32
71
72 #undef DEBUG_PARSER
73
74 char        console_buffer[CONFIG_SYS_CBSIZE + 1];      /* console I/O buffer   */
75
76 static char * delete_char (char *buffer, char *p, int *colp, int *np, int plen);
77 static const char erase_seq[] = "\b \b";                /* erase sequence       */
78 static const char   tab_seq[] = "        ";             /* used to expand TABs  */
79
80 #ifdef CONFIG_BOOT_RETRY_TIME
81 static uint64_t endtime = 0;  /* must be set, default is instant timeout */
82 static int      retry_time = -1; /* -1 so can call readline before main_loop */
83 #endif
84
85 #define endtick(seconds) (get_ticks() + (uint64_t)(seconds) * get_tbclk())
86
87 #ifndef CONFIG_BOOT_RETRY_MIN
88 #define CONFIG_BOOT_RETRY_MIN CONFIG_BOOT_RETRY_TIME
89 #endif
90
91 #ifdef CONFIG_MODEM_SUPPORT
92 int do_mdm_init = 0;
93 extern void mdm_init(void); /* defined in board.c */
94 #endif
95
96 /***************************************************************************
97  * Watch for 'delay' seconds for autoboot stop or autoboot delay string.
98  * returns: 0 -  no key string, allow autoboot 1 - got key string, abort
99  */
100 #if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
101 # if defined(CONFIG_AUTOBOOT_KEYED)
102 #ifndef CONFIG_MENU
103 static inline
104 #endif
105 int abortboot(int bootdelay)
106 {
107         int abort = 0;
108         uint64_t etime = endtick(bootdelay);
109         struct {
110                 char* str;
111                 u_int len;
112                 int retry;
113         }
114         delaykey [] = {
115                 { str: getenv ("bootdelaykey"),  retry: 1 },
116                 { str: getenv ("bootdelaykey2"), retry: 1 },
117                 { str: getenv ("bootstopkey"),   retry: 0 },
118                 { str: getenv ("bootstopkey2"),  retry: 0 },
119         };
120
121         char presskey [MAX_DELAY_STOP_STR];
122         u_int presskey_len = 0;
123         u_int presskey_max = 0;
124         u_int i;
125
126 #ifndef CONFIG_ZERO_BOOTDELAY_CHECK
127         if (bootdelay == 0)
128                 return 0;
129 #endif
130
131 #  ifdef CONFIG_AUTOBOOT_PROMPT
132         printf(CONFIG_AUTOBOOT_PROMPT);
133 #  endif
134
135 #  ifdef CONFIG_AUTOBOOT_DELAY_STR
136         if (delaykey[0].str == NULL)
137                 delaykey[0].str = CONFIG_AUTOBOOT_DELAY_STR;
138 #  endif
139 #  ifdef CONFIG_AUTOBOOT_DELAY_STR2
140         if (delaykey[1].str == NULL)
141                 delaykey[1].str = CONFIG_AUTOBOOT_DELAY_STR2;
142 #  endif
143 #  ifdef CONFIG_AUTOBOOT_STOP_STR
144         if (delaykey[2].str == NULL)
145                 delaykey[2].str = CONFIG_AUTOBOOT_STOP_STR;
146 #  endif
147 #  ifdef CONFIG_AUTOBOOT_STOP_STR2
148         if (delaykey[3].str == NULL)
149                 delaykey[3].str = CONFIG_AUTOBOOT_STOP_STR2;
150 #  endif
151
152         for (i = 0; i < sizeof(delaykey) / sizeof(delaykey[0]); i ++) {
153                 delaykey[i].len = delaykey[i].str == NULL ?
154                                     0 : strlen (delaykey[i].str);
155                 delaykey[i].len = delaykey[i].len > MAX_DELAY_STOP_STR ?
156                                     MAX_DELAY_STOP_STR : delaykey[i].len;
157
158                 presskey_max = presskey_max > delaykey[i].len ?
159                                     presskey_max : delaykey[i].len;
160
161 #  if DEBUG_BOOTKEYS
162                 printf("%s key:<%s>\n",
163                        delaykey[i].retry ? "delay" : "stop",
164                        delaykey[i].str ? delaykey[i].str : "NULL");
165 #  endif
166         }
167
168         /* In order to keep up with incoming data, check timeout only
169          * when catch up.
170          */
171         do {
172                 if (tstc()) {
173                         if (presskey_len < presskey_max) {
174                                 presskey [presskey_len ++] = getc();
175                         }
176                         else {
177                                 for (i = 0; i < presskey_max - 1; i ++)
178                                         presskey [i] = presskey [i + 1];
179
180                                 presskey [i] = getc();
181                         }
182                 }
183
184                 for (i = 0; i < sizeof(delaykey) / sizeof(delaykey[0]); i ++) {
185                         if (delaykey[i].len > 0 &&
186                             presskey_len >= delaykey[i].len &&
187                             memcmp (presskey + presskey_len - delaykey[i].len,
188                                     delaykey[i].str,
189                                     delaykey[i].len) == 0) {
190 #  if DEBUG_BOOTKEYS
191                                 printf("got %skey\n",
192                                        delaykey[i].retry ? "delay" : "stop");
193 #  endif
194
195 #  ifdef CONFIG_BOOT_RETRY_TIME
196                                 /* don't retry auto boot */
197                                 if (! delaykey[i].retry)
198                                         retry_time = -1;
199 #  endif
200                                 abort = 1;
201                         }
202                 }
203         } while (!abort && get_ticks() <= etime);
204
205 #  if DEBUG_BOOTKEYS
206         if (!abort)
207                 puts("key timeout\n");
208 #  endif
209
210 #ifdef CONFIG_SILENT_CONSOLE
211         if (abort)
212                 gd->flags &= ~GD_FLG_SILENT;
213 #endif
214
215         return abort;
216 }
217
218 # else  /* !defined(CONFIG_AUTOBOOT_KEYED) */
219
220 #ifdef CONFIG_MENUKEY
221 static int menukey = 0;
222 #endif
223
224 #ifndef CONFIG_MENU
225 static inline
226 #endif
227 int abortboot(int bootdelay)
228 {
229         int abort = 0;
230
231 #ifdef CONFIG_MENUPROMPT
232         printf(CONFIG_MENUPROMPT);
233 #else
234         if (bootdelay >= 0)
235                 printf("Hit any key to stop autoboot: %2d ", bootdelay);
236 #endif
237
238 #if defined CONFIG_ZERO_BOOTDELAY_CHECK
239         /*
240          * Check if key already pressed
241          * Don't check if bootdelay < 0
242          */
243         if (bootdelay >= 0) {
244                 if (tstc()) {   /* we got a key press   */
245                         (void) getc();  /* consume input        */
246                         puts ("\b\b\b 0");
247                         abort = 1;      /* don't auto boot      */
248                 }
249         }
250 #endif
251
252         while ((bootdelay > 0) && (!abort)) {
253                 int i;
254
255                 --bootdelay;
256                 /* delay 100 * 10ms */
257                 for (i=0; !abort && i<100; ++i) {
258                         if (tstc()) {   /* we got a key press   */
259                                 abort  = 1;     /* don't auto boot      */
260                                 bootdelay = 0;  /* no more delay        */
261 # ifdef CONFIG_MENUKEY
262                                 menukey = getc();
263 # else
264                                 (void) getc();  /* consume input        */
265 # endif
266                                 break;
267                         }
268                         udelay(10000);
269                 }
270
271                 printf("\b\b\b%2d ", bootdelay);
272         }
273
274         putc('\n');
275
276 #ifdef CONFIG_SILENT_CONSOLE
277         if (abort)
278                 gd->flags &= ~GD_FLG_SILENT;
279 #endif
280
281         return abort;
282 }
283 # endif /* CONFIG_AUTOBOOT_KEYED */
284 #endif  /* CONFIG_BOOTDELAY >= 0  */
285
286 /*
287  * Runs the given boot command securely.  Specifically:
288  * - Doesn't run the command with the shell (run_command or parse_string_outer),
289  *   since that's a lot of code surface that an attacker might exploit.
290  *   Because of this, we don't do any argument parsing--the secure boot command
291  *   has to be a full-fledged u-boot command.
292  * - Doesn't check for keypresses before booting, since that could be a
293  *   security hole; also disables Ctrl-C.
294  * - Doesn't allow the command to return.
295  *
296  * Upon any failures, this function will drop into an infinite loop after
297  * printing the error message to console.
298  */
299
300 #if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0) && \
301         defined(CONFIG_OF_CONTROL)
302 static void secure_boot_cmd(char *cmd)
303 {
304         cmd_tbl_t *cmdtp;
305         int rc;
306
307         if (!cmd) {
308                 printf("## Error: Secure boot command not specified\n");
309                 goto err;
310         }
311
312         /* Disable Ctrl-C just in case some command is used that checks it. */
313         disable_ctrlc(1);
314
315         /* Find the command directly. */
316         cmdtp = find_cmd(cmd);
317         if (!cmdtp) {
318                 printf("## Error: \"%s\" not defined\n", cmd);
319                 goto err;
320         }
321
322         /* Run the command, forcing no flags and faking argc and argv. */
323         rc = (cmdtp->cmd)(cmdtp, 0, 1, &cmd);
324
325         /* Shouldn't ever return from boot command. */
326         printf("## Error: \"%s\" returned (code %d)\n", cmd, rc);
327
328 err:
329         /*
330          * Not a whole lot to do here.  Rebooting won't help much, since we'll
331          * just end up right back here.  Just loop.
332          */
333         hang();
334 }
335
336 #endif /* CONFIG_OF_CONTROL */
337
338
339 /****************************************************************************/
340
341 void main_loop (void)
342 {
343 #ifndef CONFIG_SYS_HUSH_PARSER
344         static char lastcommand[CONFIG_SYS_CBSIZE] = { 0, };
345         int len;
346         int rc = 1;
347         int flag;
348 #endif
349 #if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0) && \
350                 defined(CONFIG_OF_CONTROL)
351         char *env;
352 #endif
353 #if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
354         char *s;
355         int bootdelay;
356 #endif
357 #ifdef CONFIG_PREBOOT
358         char *p;
359 #endif
360 #ifdef CONFIG_BOOTCOUNT_LIMIT
361         unsigned long bootcount = 0;
362         unsigned long bootlimit = 0;
363         char *bcs;
364         char bcs_set[16];
365 #endif /* CONFIG_BOOTCOUNT_LIMIT */
366
367 #ifdef CONFIG_BOOTCOUNT_LIMIT
368         bootcount = bootcount_load();
369         bootcount++;
370         bootcount_store (bootcount);
371         sprintf (bcs_set, "%lu", bootcount);
372         setenv ("bootcount", bcs_set);
373         bcs = getenv ("bootlimit");
374         bootlimit = bcs ? simple_strtoul (bcs, NULL, 10) : 0;
375 #endif /* CONFIG_BOOTCOUNT_LIMIT */
376
377 #ifdef CONFIG_MODEM_SUPPORT
378         debug ("DEBUG: main_loop:   do_mdm_init=%d\n", do_mdm_init);
379         if (do_mdm_init) {
380                 char *str = strdup(getenv("mdm_cmd"));
381                 setenv ("preboot", str);  /* set or delete definition */
382                 if (str != NULL)
383                         free (str);
384                 mdm_init(); /* wait for modem connection */
385         }
386 #endif  /* CONFIG_MODEM_SUPPORT */
387
388 #ifdef CONFIG_VERSION_VARIABLE
389         {
390                 setenv ("ver", version_string);  /* set version variable */
391         }
392 #endif /* CONFIG_VERSION_VARIABLE */
393
394 #ifdef CONFIG_SYS_HUSH_PARSER
395         u_boot_hush_start ();
396 #endif
397
398 #if defined(CONFIG_HUSH_INIT_VAR)
399         hush_init_var ();
400 #endif
401
402 #ifdef CONFIG_PREBOOT
403         if ((p = getenv ("preboot")) != NULL) {
404 # ifdef CONFIG_AUTOBOOT_KEYED
405                 int prev = disable_ctrlc(1);    /* disable Control C checking */
406 # endif
407
408                 run_command_list(p, -1, 0);
409
410 # ifdef CONFIG_AUTOBOOT_KEYED
411                 disable_ctrlc(prev);    /* restore Control C checking */
412 # endif
413         }
414 #endif /* CONFIG_PREBOOT */
415
416 #if defined(CONFIG_UPDATE_TFTP)
417         update_tftp (0UL);
418 #endif /* CONFIG_UPDATE_TFTP */
419
420 #if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
421         s = getenv ("bootdelay");
422         bootdelay = s ? (int)simple_strtol(s, NULL, 10) : CONFIG_BOOTDELAY;
423
424         debug ("### main_loop entered: bootdelay=%d\n\n", bootdelay);
425
426 #if defined(CONFIG_MENU_SHOW)
427         bootdelay = menu_show(bootdelay);
428 #endif
429 # ifdef CONFIG_BOOT_RETRY_TIME
430         init_cmd_timeout ();
431 # endif /* CONFIG_BOOT_RETRY_TIME */
432
433 #ifdef CONFIG_POST
434         if (gd->flags & GD_FLG_POSTFAIL) {
435                 s = getenv("failbootcmd");
436         }
437         else
438 #endif /* CONFIG_POST */
439 #ifdef CONFIG_BOOTCOUNT_LIMIT
440         if (bootlimit && (bootcount > bootlimit)) {
441                 printf ("Warning: Bootlimit (%u) exceeded. Using altbootcmd.\n",
442                         (unsigned)bootlimit);
443                 s = getenv ("altbootcmd");
444         }
445         else
446 #endif /* CONFIG_BOOTCOUNT_LIMIT */
447                 s = getenv ("bootcmd");
448 #ifdef CONFIG_OF_CONTROL
449         /* Allow the fdt to override the boot command */
450         env = fdtdec_get_config_string(gd->fdt_blob, "bootcmd");
451         if (env)
452                 s = env;
453
454         /*
455          * If the bootsecure option was chosen, use secure_boot_cmd().
456          * Always use 'env' in this case, since bootsecure requres that the
457          * bootcmd was specified in the FDT too.
458          */
459         if (fdtdec_get_config_int(gd->fdt_blob, "bootsecure", 0))
460                 secure_boot_cmd(env);
461
462 #endif /* CONFIG_OF_CONTROL */
463
464         debug ("### main_loop: bootcmd=\"%s\"\n", s ? s : "<UNDEFINED>");
465
466         if (bootdelay != -1 && s && !abortboot(bootdelay)) {
467 # ifdef CONFIG_AUTOBOOT_KEYED
468                 int prev = disable_ctrlc(1);    /* disable Control C checking */
469 # endif
470
471                 run_command_list(s, -1, 0);
472
473 # ifdef CONFIG_AUTOBOOT_KEYED
474                 disable_ctrlc(prev);    /* restore Control C checking */
475 # endif
476         }
477
478 # ifdef CONFIG_MENUKEY
479         if (menukey == CONFIG_MENUKEY) {
480                 s = getenv("menucmd");
481                 if (s)
482                         run_command_list(s, -1, 0);
483         }
484 #endif /* CONFIG_MENUKEY */
485 #endif /* CONFIG_BOOTDELAY */
486
487 #if defined CONFIG_OF_CONTROL
488         set_working_fdt_addr((void *)gd->fdt_blob);
489 #endif /* CONFIG_OF_CONTROL */
490
491         /*
492          * Main Loop for Monitor Command Processing
493          */
494 #ifdef CONFIG_SYS_HUSH_PARSER
495         parse_file_outer();
496         /* This point is never reached */
497         for (;;);
498 #else
499         for (;;) {
500 #ifdef CONFIG_BOOT_RETRY_TIME
501                 if (rc >= 0) {
502                         /* Saw enough of a valid command to
503                          * restart the timeout.
504                          */
505                         reset_cmd_timeout();
506                 }
507 #endif
508                 len = readline (CONFIG_SYS_PROMPT);
509
510                 flag = 0;       /* assume no special flags for now */
511                 if (len > 0)
512                         strcpy (lastcommand, console_buffer);
513                 else if (len == 0)
514                         flag |= CMD_FLAG_REPEAT;
515 #ifdef CONFIG_BOOT_RETRY_TIME
516                 else if (len == -2) {
517                         /* -2 means timed out, retry autoboot
518                          */
519                         puts ("\nTimed out waiting for command\n");
520 # ifdef CONFIG_RESET_TO_RETRY
521                         /* Reinit board to run initialization code again */
522                         do_reset (NULL, 0, 0, NULL);
523 # else
524                         return;         /* retry autoboot */
525 # endif
526                 }
527 #endif
528
529                 if (len == -1)
530                         puts ("<INTERRUPT>\n");
531                 else
532                         rc = run_command(lastcommand, flag);
533
534                 if (rc <= 0) {
535                         /* invalid command or not repeatable, forget it */
536                         lastcommand[0] = 0;
537                 }
538         }
539 #endif /*CONFIG_SYS_HUSH_PARSER*/
540 }
541
542 #ifdef CONFIG_BOOT_RETRY_TIME
543 /***************************************************************************
544  * initialize command line timeout
545  */
546 void init_cmd_timeout(void)
547 {
548         char *s = getenv ("bootretry");
549
550         if (s != NULL)
551                 retry_time = (int)simple_strtol(s, NULL, 10);
552         else
553                 retry_time =  CONFIG_BOOT_RETRY_TIME;
554
555         if (retry_time >= 0 && retry_time < CONFIG_BOOT_RETRY_MIN)
556                 retry_time = CONFIG_BOOT_RETRY_MIN;
557 }
558
559 /***************************************************************************
560  * reset command line timeout to retry_time seconds
561  */
562 void reset_cmd_timeout(void)
563 {
564         endtime = endtick(retry_time);
565 }
566 #endif
567
568 #ifdef CONFIG_CMDLINE_EDITING
569
570 /*
571  * cmdline-editing related codes from vivi.
572  * Author: Janghoon Lyu <nandy@mizi.com>
573  */
574
575 #define putnstr(str,n)  do {                    \
576                 printf ("%.*s", (int)n, str);   \
577         } while (0)
578
579 #define CTL_CH(c)               ((c) - 'a' + 1)
580 #define CTL_BACKSPACE           ('\b')
581 #define DEL                     ((char)255)
582 #define DEL7                    ((char)127)
583 #define CREAD_HIST_CHAR         ('!')
584
585 #define getcmd_putch(ch)        putc(ch)
586 #define getcmd_getch()          getc()
587 #define getcmd_cbeep()          getcmd_putch('\a')
588
589 #define HIST_MAX                20
590 #define HIST_SIZE               CONFIG_SYS_CBSIZE
591
592 static int hist_max;
593 static int hist_add_idx;
594 static int hist_cur = -1;
595 static unsigned hist_num;
596
597 static char *hist_list[HIST_MAX];
598 static char hist_lines[HIST_MAX][HIST_SIZE + 1];        /* Save room for NULL */
599
600 #define add_idx_minus_one() ((hist_add_idx == 0) ? hist_max : hist_add_idx-1)
601
602 static void hist_init(void)
603 {
604         int i;
605
606         hist_max = 0;
607         hist_add_idx = 0;
608         hist_cur = -1;
609         hist_num = 0;
610
611         for (i = 0; i < HIST_MAX; i++) {
612                 hist_list[i] = hist_lines[i];
613                 hist_list[i][0] = '\0';
614         }
615 }
616
617 static void cread_add_to_hist(char *line)
618 {
619         strcpy(hist_list[hist_add_idx], line);
620
621         if (++hist_add_idx >= HIST_MAX)
622                 hist_add_idx = 0;
623
624         if (hist_add_idx > hist_max)
625                 hist_max = hist_add_idx;
626
627         hist_num++;
628 }
629
630 static char* hist_prev(void)
631 {
632         char *ret;
633         int old_cur;
634
635         if (hist_cur < 0)
636                 return NULL;
637
638         old_cur = hist_cur;
639         if (--hist_cur < 0)
640                 hist_cur = hist_max;
641
642         if (hist_cur == hist_add_idx) {
643                 hist_cur = old_cur;
644                 ret = NULL;
645         } else
646                 ret = hist_list[hist_cur];
647
648         return (ret);
649 }
650
651 static char* hist_next(void)
652 {
653         char *ret;
654
655         if (hist_cur < 0)
656                 return NULL;
657
658         if (hist_cur == hist_add_idx)
659                 return NULL;
660
661         if (++hist_cur > hist_max)
662                 hist_cur = 0;
663
664         if (hist_cur == hist_add_idx) {
665                 ret = "";
666         } else
667                 ret = hist_list[hist_cur];
668
669         return (ret);
670 }
671
672 #ifndef CONFIG_CMDLINE_EDITING
673 static void cread_print_hist_list(void)
674 {
675         int i;
676         unsigned long n;
677
678         n = hist_num - hist_max;
679
680         i = hist_add_idx + 1;
681         while (1) {
682                 if (i > hist_max)
683                         i = 0;
684                 if (i == hist_add_idx)
685                         break;
686                 printf("%s\n", hist_list[i]);
687                 n++;
688                 i++;
689         }
690 }
691 #endif /* CONFIG_CMDLINE_EDITING */
692
693 #define BEGINNING_OF_LINE() {                   \
694         while (num) {                           \
695                 getcmd_putch(CTL_BACKSPACE);    \
696                 num--;                          \
697         }                                       \
698 }
699
700 #define ERASE_TO_EOL() {                                \
701         if (num < eol_num) {                            \
702                 printf("%*s", (int)(eol_num - num), ""); \
703                 do {                                    \
704                         getcmd_putch(CTL_BACKSPACE);    \
705                 } while (--eol_num > num);              \
706         }                                               \
707 }
708
709 #define REFRESH_TO_EOL() {                      \
710         if (num < eol_num) {                    \
711                 wlen = eol_num - num;           \
712                 putnstr(buf + num, wlen);       \
713                 num = eol_num;                  \
714         }                                       \
715 }
716
717 static void cread_add_char(char ichar, int insert, unsigned long *num,
718                unsigned long *eol_num, char *buf, unsigned long len)
719 {
720         unsigned long wlen;
721
722         /* room ??? */
723         if (insert || *num == *eol_num) {
724                 if (*eol_num > len - 1) {
725                         getcmd_cbeep();
726                         return;
727                 }
728                 (*eol_num)++;
729         }
730
731         if (insert) {
732                 wlen = *eol_num - *num;
733                 if (wlen > 1) {
734                         memmove(&buf[*num+1], &buf[*num], wlen-1);
735                 }
736
737                 buf[*num] = ichar;
738                 putnstr(buf + *num, wlen);
739                 (*num)++;
740                 while (--wlen) {
741                         getcmd_putch(CTL_BACKSPACE);
742                 }
743         } else {
744                 /* echo the character */
745                 wlen = 1;
746                 buf[*num] = ichar;
747                 putnstr(buf + *num, wlen);
748                 (*num)++;
749         }
750 }
751
752 static void cread_add_str(char *str, int strsize, int insert, unsigned long *num,
753               unsigned long *eol_num, char *buf, unsigned long len)
754 {
755         while (strsize--) {
756                 cread_add_char(*str, insert, num, eol_num, buf, len);
757                 str++;
758         }
759 }
760
761 static int cread_line(const char *const prompt, char *buf, unsigned int *len,
762                 int timeout)
763 {
764         unsigned long num = 0;
765         unsigned long eol_num = 0;
766         unsigned long wlen;
767         char ichar;
768         int insert = 1;
769         int esc_len = 0;
770         char esc_save[8];
771         int init_len = strlen(buf);
772         int first = 1;
773
774         if (init_len)
775                 cread_add_str(buf, init_len, 1, &num, &eol_num, buf, *len);
776
777         while (1) {
778 #ifdef CONFIG_BOOT_RETRY_TIME
779                 while (!tstc()) {       /* while no incoming data */
780                         if (retry_time >= 0 && get_ticks() > endtime)
781                                 return (-2);    /* timed out */
782                         WATCHDOG_RESET();
783                 }
784 #endif
785                 if (first && timeout) {
786                         uint64_t etime = endtick(timeout);
787
788                         while (!tstc()) {       /* while no incoming data */
789                                 if (get_ticks() >= etime)
790                                         return -2;      /* timed out */
791                                 WATCHDOG_RESET();
792                         }
793                         first = 0;
794                 }
795
796                 ichar = getcmd_getch();
797
798                 if ((ichar == '\n') || (ichar == '\r')) {
799                         putc('\n');
800                         break;
801                 }
802
803                 /*
804                  * handle standard linux xterm esc sequences for arrow key, etc.
805                  */
806                 if (esc_len != 0) {
807                         if (esc_len == 1) {
808                                 if (ichar == '[') {
809                                         esc_save[esc_len] = ichar;
810                                         esc_len = 2;
811                                 } else {
812                                         cread_add_str(esc_save, esc_len, insert,
813                                                       &num, &eol_num, buf, *len);
814                                         esc_len = 0;
815                                 }
816                                 continue;
817                         }
818
819                         switch (ichar) {
820
821                         case 'D':       /* <- key */
822                                 ichar = CTL_CH('b');
823                                 esc_len = 0;
824                                 break;
825                         case 'C':       /* -> key */
826                                 ichar = CTL_CH('f');
827                                 esc_len = 0;
828                                 break;  /* pass off to ^F handler */
829                         case 'H':       /* Home key */
830                                 ichar = CTL_CH('a');
831                                 esc_len = 0;
832                                 break;  /* pass off to ^A handler */
833                         case 'A':       /* up arrow */
834                                 ichar = CTL_CH('p');
835                                 esc_len = 0;
836                                 break;  /* pass off to ^P handler */
837                         case 'B':       /* down arrow */
838                                 ichar = CTL_CH('n');
839                                 esc_len = 0;
840                                 break;  /* pass off to ^N handler */
841                         default:
842                                 esc_save[esc_len++] = ichar;
843                                 cread_add_str(esc_save, esc_len, insert,
844                                               &num, &eol_num, buf, *len);
845                                 esc_len = 0;
846                                 continue;
847                         }
848                 }
849
850                 switch (ichar) {
851                 case 0x1b:
852                         if (esc_len == 0) {
853                                 esc_save[esc_len] = ichar;
854                                 esc_len = 1;
855                         } else {
856                                 puts("impossible condition #876\n");
857                                 esc_len = 0;
858                         }
859                         break;
860
861                 case CTL_CH('a'):
862                         BEGINNING_OF_LINE();
863                         break;
864                 case CTL_CH('c'):       /* ^C - break */
865                         *buf = '\0';    /* discard input */
866                         return (-1);
867                 case CTL_CH('f'):
868                         if (num < eol_num) {
869                                 getcmd_putch(buf[num]);
870                                 num++;
871                         }
872                         break;
873                 case CTL_CH('b'):
874                         if (num) {
875                                 getcmd_putch(CTL_BACKSPACE);
876                                 num--;
877                         }
878                         break;
879                 case CTL_CH('d'):
880                         if (num < eol_num) {
881                                 wlen = eol_num - num - 1;
882                                 if (wlen) {
883                                         memmove(&buf[num], &buf[num+1], wlen);
884                                         putnstr(buf + num, wlen);
885                                 }
886
887                                 getcmd_putch(' ');
888                                 do {
889                                         getcmd_putch(CTL_BACKSPACE);
890                                 } while (wlen--);
891                                 eol_num--;
892                         }
893                         break;
894                 case CTL_CH('k'):
895                         ERASE_TO_EOL();
896                         break;
897                 case CTL_CH('e'):
898                         REFRESH_TO_EOL();
899                         break;
900                 case CTL_CH('o'):
901                         insert = !insert;
902                         break;
903                 case CTL_CH('x'):
904                 case CTL_CH('u'):
905                         BEGINNING_OF_LINE();
906                         ERASE_TO_EOL();
907                         break;
908                 case DEL:
909                 case DEL7:
910                 case 8:
911                         if (num) {
912                                 wlen = eol_num - num;
913                                 num--;
914                                 memmove(&buf[num], &buf[num+1], wlen);
915                                 getcmd_putch(CTL_BACKSPACE);
916                                 putnstr(buf + num, wlen);
917                                 getcmd_putch(' ');
918                                 do {
919                                         getcmd_putch(CTL_BACKSPACE);
920                                 } while (wlen--);
921                                 eol_num--;
922                         }
923                         break;
924                 case CTL_CH('p'):
925                 case CTL_CH('n'):
926                 {
927                         char * hline;
928
929                         esc_len = 0;
930
931                         if (ichar == CTL_CH('p'))
932                                 hline = hist_prev();
933                         else
934                                 hline = hist_next();
935
936                         if (!hline) {
937                                 getcmd_cbeep();
938                                 continue;
939                         }
940
941                         /* nuke the current line */
942                         /* first, go home */
943                         BEGINNING_OF_LINE();
944
945                         /* erase to end of line */
946                         ERASE_TO_EOL();
947
948                         /* copy new line into place and display */
949                         strcpy(buf, hline);
950                         eol_num = strlen(buf);
951                         REFRESH_TO_EOL();
952                         continue;
953                 }
954 #ifdef CONFIG_AUTO_COMPLETE
955                 case '\t': {
956                         int num2, col;
957
958                         /* do not autocomplete when in the middle */
959                         if (num < eol_num) {
960                                 getcmd_cbeep();
961                                 break;
962                         }
963
964                         buf[num] = '\0';
965                         col = strlen(prompt) + eol_num;
966                         num2 = num;
967                         if (cmd_auto_complete(prompt, buf, &num2, &col)) {
968                                 col = num2 - num;
969                                 num += col;
970                                 eol_num += col;
971                         }
972                         break;
973                 }
974 #endif
975                 default:
976                         cread_add_char(ichar, insert, &num, &eol_num, buf, *len);
977                         break;
978                 }
979         }
980         *len = eol_num;
981         buf[eol_num] = '\0';    /* lose the newline */
982
983         if (buf[0] && buf[0] != CREAD_HIST_CHAR)
984                 cread_add_to_hist(buf);
985         hist_cur = hist_add_idx;
986
987         return 0;
988 }
989
990 #endif /* CONFIG_CMDLINE_EDITING */
991
992 /****************************************************************************/
993
994 /*
995  * Prompt for input and read a line.
996  * If  CONFIG_BOOT_RETRY_TIME is defined and retry_time >= 0,
997  * time out when time goes past endtime (timebase time in ticks).
998  * Return:      number of read characters
999  *              -1 if break
1000  *              -2 if timed out
1001  */
1002 int readline (const char *const prompt)
1003 {
1004         /*
1005          * If console_buffer isn't 0-length the user will be prompted to modify
1006          * it instead of entering it from scratch as desired.
1007          */
1008         console_buffer[0] = '\0';
1009
1010         return readline_into_buffer(prompt, console_buffer, 0);
1011 }
1012
1013
1014 int readline_into_buffer(const char *const prompt, char *buffer, int timeout)
1015 {
1016         char *p = buffer;
1017 #ifdef CONFIG_CMDLINE_EDITING
1018         unsigned int len = CONFIG_SYS_CBSIZE;
1019         int rc;
1020         static int initted = 0;
1021
1022         /*
1023          * History uses a global array which is not
1024          * writable until after relocation to RAM.
1025          * Revert to non-history version if still
1026          * running from flash.
1027          */
1028         if (gd->flags & GD_FLG_RELOC) {
1029                 if (!initted) {
1030                         hist_init();
1031                         initted = 1;
1032                 }
1033
1034                 if (prompt)
1035                         puts (prompt);
1036
1037                 rc = cread_line(prompt, p, &len, timeout);
1038                 return rc < 0 ? rc : len;
1039
1040         } else {
1041 #endif  /* CONFIG_CMDLINE_EDITING */
1042         char * p_buf = p;
1043         int     n = 0;                          /* buffer index         */
1044         int     plen = 0;                       /* prompt length        */
1045         int     col;                            /* output column cnt    */
1046         char    c;
1047
1048         /* print prompt */
1049         if (prompt) {
1050                 plen = strlen (prompt);
1051                 puts (prompt);
1052         }
1053         col = plen;
1054
1055         for (;;) {
1056 #ifdef CONFIG_BOOT_RETRY_TIME
1057                 while (!tstc()) {       /* while no incoming data */
1058                         if (retry_time >= 0 && get_ticks() > endtime)
1059                                 return (-2);    /* timed out */
1060                         WATCHDOG_RESET();
1061                 }
1062 #endif
1063                 WATCHDOG_RESET();               /* Trigger watchdog, if needed */
1064
1065 #ifdef CONFIG_SHOW_ACTIVITY
1066                 while (!tstc()) {
1067                         show_activity(0);
1068                         WATCHDOG_RESET();
1069                 }
1070 #endif
1071                 c = getc();
1072
1073                 /*
1074                  * Special character handling
1075                  */
1076                 switch (c) {
1077                 case '\r':                              /* Enter                */
1078                 case '\n':
1079                         *p = '\0';
1080                         puts ("\r\n");
1081                         return (p - p_buf);
1082
1083                 case '\0':                              /* nul                  */
1084                         continue;
1085
1086                 case 0x03:                              /* ^C - break           */
1087                         p_buf[0] = '\0';        /* discard input */
1088                         return (-1);
1089
1090                 case 0x15:                              /* ^U - erase line      */
1091                         while (col > plen) {
1092                                 puts (erase_seq);
1093                                 --col;
1094                         }
1095                         p = p_buf;
1096                         n = 0;
1097                         continue;
1098
1099                 case 0x17:                              /* ^W - erase word      */
1100                         p=delete_char(p_buf, p, &col, &n, plen);
1101                         while ((n > 0) && (*p != ' ')) {
1102                                 p=delete_char(p_buf, p, &col, &n, plen);
1103                         }
1104                         continue;
1105
1106                 case 0x08:                              /* ^H  - backspace      */
1107                 case 0x7F:                              /* DEL - backspace      */
1108                         p=delete_char(p_buf, p, &col, &n, plen);
1109                         continue;
1110
1111                 default:
1112                         /*
1113                          * Must be a normal character then
1114                          */
1115                         if (n < CONFIG_SYS_CBSIZE-2) {
1116                                 if (c == '\t') {        /* expand TABs          */
1117 #ifdef CONFIG_AUTO_COMPLETE
1118                                         /* if auto completion triggered just continue */
1119                                         *p = '\0';
1120                                         if (cmd_auto_complete(prompt, console_buffer, &n, &col)) {
1121                                                 p = p_buf + n;  /* reset */
1122                                                 continue;
1123                                         }
1124 #endif
1125                                         puts (tab_seq+(col&07));
1126                                         col += 8 - (col&07);
1127                                 } else {
1128                                         ++col;          /* echo input           */
1129                                         putc (c);
1130                                 }
1131                                 *p++ = c;
1132                                 ++n;
1133                         } else {                        /* Buffer full          */
1134                                 putc ('\a');
1135                         }
1136                 }
1137         }
1138 #ifdef CONFIG_CMDLINE_EDITING
1139         }
1140 #endif
1141 }
1142
1143 /****************************************************************************/
1144
1145 static char * delete_char (char *buffer, char *p, int *colp, int *np, int plen)
1146 {
1147         char *s;
1148
1149         if (*np == 0) {
1150                 return (p);
1151         }
1152
1153         if (*(--p) == '\t') {                   /* will retype the whole line   */
1154                 while (*colp > plen) {
1155                         puts (erase_seq);
1156                         (*colp)--;
1157                 }
1158                 for (s=buffer; s<p; ++s) {
1159                         if (*s == '\t') {
1160                                 puts (tab_seq+((*colp) & 07));
1161                                 *colp += 8 - ((*colp) & 07);
1162                         } else {
1163                                 ++(*colp);
1164                                 putc (*s);
1165                         }
1166                 }
1167         } else {
1168                 puts (erase_seq);
1169                 (*colp)--;
1170         }
1171         (*np)--;
1172         return (p);
1173 }
1174
1175 /****************************************************************************/
1176
1177 int parse_line (char *line, char *argv[])
1178 {
1179         int nargs = 0;
1180
1181 #ifdef DEBUG_PARSER
1182         printf ("parse_line: \"%s\"\n", line);
1183 #endif
1184         while (nargs < CONFIG_SYS_MAXARGS) {
1185
1186                 /* skip any white space */
1187                 while (isblank(*line))
1188                         ++line;
1189
1190                 if (*line == '\0') {    /* end of line, no more args    */
1191                         argv[nargs] = NULL;
1192 #ifdef DEBUG_PARSER
1193                 printf ("parse_line: nargs=%d\n", nargs);
1194 #endif
1195                         return (nargs);
1196                 }
1197
1198                 argv[nargs++] = line;   /* begin of argument string     */
1199
1200                 /* find end of string */
1201                 while (*line && !isblank(*line))
1202                         ++line;
1203
1204                 if (*line == '\0') {    /* end of line, no more args    */
1205                         argv[nargs] = NULL;
1206 #ifdef DEBUG_PARSER
1207                 printf ("parse_line: nargs=%d\n", nargs);
1208 #endif
1209                         return (nargs);
1210                 }
1211
1212                 *line++ = '\0';         /* terminate current arg         */
1213         }
1214
1215         printf ("** Too many args (max. %d) **\n", CONFIG_SYS_MAXARGS);
1216
1217 #ifdef DEBUG_PARSER
1218         printf ("parse_line: nargs=%d\n", nargs);
1219 #endif
1220         return (nargs);
1221 }
1222
1223 /****************************************************************************/
1224
1225 #ifndef CONFIG_SYS_HUSH_PARSER
1226 static void process_macros (const char *input, char *output)
1227 {
1228         char c, prev;
1229         const char *varname_start = NULL;
1230         int inputcnt = strlen (input);
1231         int outputcnt = CONFIG_SYS_CBSIZE;
1232         int state = 0;          /* 0 = waiting for '$'  */
1233
1234         /* 1 = waiting for '(' or '{' */
1235         /* 2 = waiting for ')' or '}' */
1236         /* 3 = waiting for '''  */
1237 #ifdef DEBUG_PARSER
1238         char *output_start = output;
1239
1240         printf ("[PROCESS_MACROS] INPUT len %d: \"%s\"\n", strlen (input),
1241                 input);
1242 #endif
1243
1244         prev = '\0';            /* previous character   */
1245
1246         while (inputcnt && outputcnt) {
1247                 c = *input++;
1248                 inputcnt--;
1249
1250                 if (state != 3) {
1251                         /* remove one level of escape characters */
1252                         if ((c == '\\') && (prev != '\\')) {
1253                                 if (inputcnt-- == 0)
1254                                         break;
1255                                 prev = c;
1256                                 c = *input++;
1257                         }
1258                 }
1259
1260                 switch (state) {
1261                 case 0: /* Waiting for (unescaped) $    */
1262                         if ((c == '\'') && (prev != '\\')) {
1263                                 state = 3;
1264                                 break;
1265                         }
1266                         if ((c == '$') && (prev != '\\')) {
1267                                 state++;
1268                         } else {
1269                                 *(output++) = c;
1270                                 outputcnt--;
1271                         }
1272                         break;
1273                 case 1: /* Waiting for (        */
1274                         if (c == '(' || c == '{') {
1275                                 state++;
1276                                 varname_start = input;
1277                         } else {
1278                                 state = 0;
1279                                 *(output++) = '$';
1280                                 outputcnt--;
1281
1282                                 if (outputcnt) {
1283                                         *(output++) = c;
1284                                         outputcnt--;
1285                                 }
1286                         }
1287                         break;
1288                 case 2: /* Waiting for )        */
1289                         if (c == ')' || c == '}') {
1290                                 int i;
1291                                 char envname[CONFIG_SYS_CBSIZE], *envval;
1292                                 int envcnt = input - varname_start - 1; /* Varname # of chars */
1293
1294                                 /* Get the varname */
1295                                 for (i = 0; i < envcnt; i++) {
1296                                         envname[i] = varname_start[i];
1297                                 }
1298                                 envname[i] = 0;
1299
1300                                 /* Get its value */
1301                                 envval = getenv (envname);
1302
1303                                 /* Copy into the line if it exists */
1304                                 if (envval != NULL)
1305                                         while ((*envval) && outputcnt) {
1306                                                 *(output++) = *(envval++);
1307                                                 outputcnt--;
1308                                         }
1309                                 /* Look for another '$' */
1310                                 state = 0;
1311                         }
1312                         break;
1313                 case 3: /* Waiting for '        */
1314                         if ((c == '\'') && (prev != '\\')) {
1315                                 state = 0;
1316                         } else {
1317                                 *(output++) = c;
1318                                 outputcnt--;
1319                         }
1320                         break;
1321                 }
1322                 prev = c;
1323         }
1324
1325         if (outputcnt)
1326                 *output = 0;
1327         else
1328                 *(output - 1) = 0;
1329
1330 #ifdef DEBUG_PARSER
1331         printf ("[PROCESS_MACROS] OUTPUT len %d: \"%s\"\n",
1332                 strlen (output_start), output_start);
1333 #endif
1334 }
1335
1336 /****************************************************************************
1337  * returns:
1338  *      1  - command executed, repeatable
1339  *      0  - command executed but not repeatable, interrupted commands are
1340  *           always considered not repeatable
1341  *      -1 - not executed (unrecognized, bootd recursion or too many args)
1342  *           (If cmd is NULL or "" or longer than CONFIG_SYS_CBSIZE-1 it is
1343  *           considered unrecognized)
1344  *
1345  * WARNING:
1346  *
1347  * We must create a temporary copy of the command since the command we get
1348  * may be the result from getenv(), which returns a pointer directly to
1349  * the environment data, which may change magicly when the command we run
1350  * creates or modifies environment variables (like "bootp" does).
1351  */
1352 static int builtin_run_command(const char *cmd, int flag)
1353 {
1354         char cmdbuf[CONFIG_SYS_CBSIZE]; /* working copy of cmd          */
1355         char *token;                    /* start of token in cmdbuf     */
1356         char *sep;                      /* end of token (separator) in cmdbuf */
1357         char finaltoken[CONFIG_SYS_CBSIZE];
1358         char *str = cmdbuf;
1359         char *argv[CONFIG_SYS_MAXARGS + 1];     /* NULL terminated      */
1360         int argc, inquotes;
1361         int repeatable = 1;
1362         int rc = 0;
1363
1364 #ifdef DEBUG_PARSER
1365         printf ("[RUN_COMMAND] cmd[%p]=\"", cmd);
1366         puts (cmd ? cmd : "NULL");      /* use puts - string may be loooong */
1367         puts ("\"\n");
1368 #endif
1369
1370         clear_ctrlc();          /* forget any previous Control C */
1371
1372         if (!cmd || !*cmd) {
1373                 return -1;      /* empty command */
1374         }
1375
1376         if (strlen(cmd) >= CONFIG_SYS_CBSIZE) {
1377                 puts ("## Command too long!\n");
1378                 return -1;
1379         }
1380
1381         strcpy (cmdbuf, cmd);
1382
1383         /* Process separators and check for invalid
1384          * repeatable commands
1385          */
1386
1387 #ifdef DEBUG_PARSER
1388         printf ("[PROCESS_SEPARATORS] %s\n", cmd);
1389 #endif
1390         while (*str) {
1391
1392                 /*
1393                  * Find separator, or string end
1394                  * Allow simple escape of ';' by writing "\;"
1395                  */
1396                 for (inquotes = 0, sep = str; *sep; sep++) {
1397                         if ((*sep=='\'') &&
1398                             (*(sep-1) != '\\'))
1399                                 inquotes=!inquotes;
1400
1401                         if (!inquotes &&
1402                             (*sep == ';') &&    /* separator            */
1403                             ( sep != str) &&    /* past string start    */
1404                             (*(sep-1) != '\\')) /* and NOT escaped      */
1405                                 break;
1406                 }
1407
1408                 /*
1409                  * Limit the token to data between separators
1410                  */
1411                 token = str;
1412                 if (*sep) {
1413                         str = sep + 1;  /* start of command for next pass */
1414                         *sep = '\0';
1415                 }
1416                 else
1417                         str = sep;      /* no more commands for next pass */
1418 #ifdef DEBUG_PARSER
1419                 printf ("token: \"%s\"\n", token);
1420 #endif
1421
1422                 /* find macros in this token and replace them */
1423                 process_macros (token, finaltoken);
1424
1425                 /* Extract arguments */
1426                 if ((argc = parse_line (finaltoken, argv)) == 0) {
1427                         rc = -1;        /* no command at all */
1428                         continue;
1429                 }
1430
1431                 if (cmd_process(flag, argc, argv, &repeatable))
1432                         rc = -1;
1433
1434                 /* Did the user stop this? */
1435                 if (had_ctrlc ())
1436                         return -1;      /* if stopped then not repeatable */
1437         }
1438
1439         return rc ? rc : repeatable;
1440 }
1441 #endif
1442
1443 /*
1444  * Run a command using the selected parser.
1445  *
1446  * @param cmd   Command to run
1447  * @param flag  Execution flags (CMD_FLAG_...)
1448  * @return 0 on success, or != 0 on error.
1449  */
1450 int run_command(const char *cmd, int flag)
1451 {
1452 #ifndef CONFIG_SYS_HUSH_PARSER
1453         /*
1454          * builtin_run_command can return 0 or 1 for success, so clean up
1455          * its result.
1456          */
1457         if (builtin_run_command(cmd, flag) == -1)
1458                 return 1;
1459
1460         return 0;
1461 #else
1462         return parse_string_outer(cmd,
1463                         FLAG_PARSE_SEMICOLON | FLAG_EXIT_FROM_LOOP);
1464 #endif
1465 }
1466
1467 #ifndef CONFIG_SYS_HUSH_PARSER
1468 /**
1469  * Execute a list of command separated by ; or \n using the built-in parser.
1470  *
1471  * This function cannot take a const char * for the command, since if it
1472  * finds newlines in the string, it replaces them with \0.
1473  *
1474  * @param cmd   String containing list of commands
1475  * @param flag  Execution flags (CMD_FLAG_...)
1476  * @return 0 on success, or != 0 on error.
1477  */
1478 static int builtin_run_command_list(char *cmd, int flag)
1479 {
1480         char *line, *next;
1481         int rcode = 0;
1482
1483         /*
1484          * Break into individual lines, and execute each line; terminate on
1485          * error.
1486          */
1487         line = next = cmd;
1488         while (*next) {
1489                 if (*next == '\n') {
1490                         *next = '\0';
1491                         /* run only non-empty commands */
1492                         if (*line) {
1493                                 debug("** exec: \"%s\"\n", line);
1494                                 if (builtin_run_command(line, 0) < 0) {
1495                                         rcode = 1;
1496                                         break;
1497                                 }
1498                         }
1499                         line = next + 1;
1500                 }
1501                 ++next;
1502         }
1503         if (rcode == 0 && *line)
1504                 rcode = (builtin_run_command(line, 0) >= 0);
1505
1506         return rcode;
1507 }
1508 #endif
1509
1510 int run_command_list(const char *cmd, int len, int flag)
1511 {
1512         int need_buff = 1;
1513         char *buff = (char *)cmd;       /* cast away const */
1514         int rcode = 0;
1515
1516         if (len == -1) {
1517                 len = strlen(cmd);
1518 #ifdef CONFIG_SYS_HUSH_PARSER
1519                 /* hush will never change our string */
1520                 need_buff = 0;
1521 #else
1522                 /* the built-in parser will change our string if it sees \n */
1523                 need_buff = strchr(cmd, '\n') != NULL;
1524 #endif
1525         }
1526         if (need_buff) {
1527                 buff = malloc(len + 1);
1528                 if (!buff)
1529                         return 1;
1530                 memcpy(buff, cmd, len);
1531                 buff[len] = '\0';
1532         }
1533 #ifdef CONFIG_SYS_HUSH_PARSER
1534         rcode = parse_string_outer(buff, FLAG_PARSE_SEMICOLON);
1535 #else
1536         /*
1537          * This function will overwrite any \n it sees with a \0, which
1538          * is why it can't work with a const char *. Here we are making
1539          * using of internal knowledge of this function, to avoid always
1540          * doing a malloc() which is actually required only in a case that
1541          * is pretty rare.
1542          */
1543         rcode = builtin_run_command_list(buff, flag);
1544         if (need_buff)
1545                 free(buff);
1546 #endif
1547
1548         return rcode;
1549 }
1550
1551 /****************************************************************************/
1552
1553 #if defined(CONFIG_CMD_RUN)
1554 int do_run (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
1555 {
1556         int i;
1557
1558         if (argc < 2)
1559                 return CMD_RET_USAGE;
1560
1561         for (i=1; i<argc; ++i) {
1562                 char *arg;
1563
1564                 if ((arg = getenv (argv[i])) == NULL) {
1565                         printf ("## Error: \"%s\" not defined\n", argv[i]);
1566                         return 1;
1567                 }
1568
1569                 if (run_command(arg, flag) != 0)
1570                         return 1;
1571         }
1572         return 0;
1573 }
1574 #endif