main.c 34 KB

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