You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1312 lines
32 KiB

  1. /***************************************************************************
  2. * Copyright (C) 2005 by Dominic Rath *
  3. * Dominic.Rath@gmx.de *
  4. * *
  5. * Copyright (C) 2007,2008 Øyvind Harboe *
  6. * oyvind.harboe@zylin.com *
  7. * *
  8. * Copyright (C) 2008, Duane Ellis *
  9. * openocd@duaneeellis.com *
  10. * *
  11. * part of this file is taken from libcli (libcli.sourceforge.net) *
  12. * Copyright (C) David Parrish (david@dparrish.com) *
  13. * *
  14. * This program is free software; you can redistribute it and/or modify *
  15. * it under the terms of the GNU General Public License as published by *
  16. * the Free Software Foundation; either version 2 of the License, or *
  17. * (at your option) any later version. *
  18. * *
  19. * This program is distributed in the hope that it will be useful, *
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of *
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
  22. * GNU General Public License for more details. *
  23. * *
  24. * You should have received a copy of the GNU General Public License *
  25. * along with this program; if not, write to the *
  26. * Free Software Foundation, Inc., *
  27. * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
  28. ***************************************************************************/
  29. #ifdef HAVE_CONFIG_H
  30. #include "config.h"
  31. #endif
  32. #if !BUILD_ECOSBOARD
  33. /* see Embedder-HOWTO.txt in Jim Tcl project hosted on BerliOS*/
  34. #define JIM_EMBEDDED
  35. #endif
  36. // @todo the inclusion of target.h here is a layering violation
  37. #include "target.h"
  38. #include "command.h"
  39. #include "configuration.h"
  40. #include "log.h"
  41. #include "time_support.h"
  42. #include "jim-eventloop.h"
  43. Jim_Interp *interp = NULL;
  44. static int run_command(struct command_context *context,
  45. struct command *c, const char *words[], unsigned num_words);
  46. static void tcl_output(void *privData, const char *file, unsigned line,
  47. const char *function, const char *string)
  48. {
  49. Jim_Obj *tclOutput = (Jim_Obj *)privData;
  50. Jim_AppendString(interp, tclOutput, string, strlen(string));
  51. }
  52. static Jim_Obj *command_log_capture_start(Jim_Interp *interp)
  53. {
  54. /* capture log output and return it. A garbage collect can
  55. * happen, so we need a reference count to this object */
  56. Jim_Obj *tclOutput = Jim_NewStringObj(interp, "", 0);
  57. if (NULL == tclOutput)
  58. return NULL;
  59. Jim_IncrRefCount(tclOutput);
  60. log_add_callback(tcl_output, tclOutput);
  61. return tclOutput;
  62. }
  63. static void command_log_capture_finish(Jim_Interp *interp, Jim_Obj *tclOutput)
  64. {
  65. log_remove_callback(tcl_output, tclOutput);
  66. Jim_SetResult(interp, tclOutput);
  67. Jim_DecrRefCount(interp, tclOutput);
  68. }
  69. static int command_retval_set(Jim_Interp *interp, int retval)
  70. {
  71. int *return_retval = Jim_GetAssocData(interp, "retval");
  72. if (return_retval != NULL)
  73. *return_retval = retval;
  74. return (retval == ERROR_OK) ? JIM_OK : JIM_ERR;
  75. }
  76. extern struct command_context *global_cmd_ctx;
  77. void script_debug(Jim_Interp *interp, const char *name,
  78. unsigned argc, Jim_Obj *const *argv)
  79. {
  80. LOG_DEBUG("command - %s", name);
  81. for (unsigned i = 0; i < argc; i++)
  82. {
  83. int len;
  84. const char *w = Jim_GetString(argv[i], &len);
  85. /* end of line comment? */
  86. if (*w == '#')
  87. break;
  88. LOG_DEBUG("%s - argv[%d]=%s", name, i, w);
  89. }
  90. }
  91. static void script_command_args_free(const char **words, unsigned nwords)
  92. {
  93. for (unsigned i = 0; i < nwords; i++)
  94. free((void *)words[i]);
  95. free(words);
  96. }
  97. static const char **script_command_args_alloc(
  98. unsigned argc, Jim_Obj *const *argv, unsigned *nwords)
  99. {
  100. const char **words = malloc(argc * sizeof(char *));
  101. if (NULL == words)
  102. return NULL;
  103. unsigned i;
  104. for (i = 0; i < argc; i++)
  105. {
  106. int len;
  107. const char *w = Jim_GetString(argv[i], &len);
  108. /* a comment may end the line early */
  109. if (*w == '#')
  110. break;
  111. words[i] = strdup(w);
  112. if (words[i] == NULL)
  113. {
  114. script_command_args_free(words, i);
  115. return NULL;
  116. }
  117. }
  118. *nwords = i;
  119. return words;
  120. }
  121. static struct command_context *current_command_context(void)
  122. {
  123. /* grab the command context from the associated data */
  124. struct command_context *cmd_ctx = Jim_GetAssocData(interp, "context");
  125. if (NULL == cmd_ctx)
  126. {
  127. /* Tcl can invoke commands directly instead of via command_run_line(). This would
  128. * happen when the Jim Tcl interpreter is provided by eCos.
  129. */
  130. cmd_ctx = global_cmd_ctx;
  131. }
  132. return cmd_ctx;
  133. }
  134. static int script_command(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  135. {
  136. /* the private data is stashed in the interp structure */
  137. struct command *c = interp->cmdPrivData;
  138. assert(c);
  139. target_call_timer_callbacks_now();
  140. LOG_USER_N("%s", ""); /* Keep GDB connection alive*/
  141. script_debug(interp, c->name, argc, argv);
  142. unsigned nwords;
  143. const char **words = script_command_args_alloc(argc, argv, &nwords);
  144. if (NULL == words)
  145. return JIM_ERR;
  146. Jim_Obj *tclOutput = command_log_capture_start(interp);
  147. struct command_context *cmd_ctx = current_command_context();
  148. int retval = run_command(cmd_ctx, c, (const char **)words, nwords);
  149. command_log_capture_finish(interp, tclOutput);
  150. script_command_args_free(words, nwords);
  151. return command_retval_set(interp, retval);
  152. }
  153. /* nice short description of source file */
  154. #define __THIS__FILE__ "command.c"
  155. /**
  156. * Find a command by name from a list of commands.
  157. * @returns Returns the named command if it exists in the list.
  158. * Returns NULL otherwise.
  159. */
  160. static struct command *command_find(struct command *head, const char *name)
  161. {
  162. for (struct command *cc = head; cc; cc = cc->next)
  163. {
  164. if (strcmp(cc->name, name) == 0)
  165. return cc;
  166. }
  167. return NULL;
  168. }
  169. struct command *command_find_in_context(struct command_context *cmd_ctx,
  170. const char *name)
  171. {
  172. return command_find(cmd_ctx->commands, name);
  173. }
  174. struct command *command_find_in_parent(struct command *parent,
  175. const char *name)
  176. {
  177. return command_find(parent->children, name);
  178. }
  179. /**
  180. * Add the command into the linked list, sorted by name.
  181. * @param head Address to head of command list pointer, which may be
  182. * updated if @c c gets inserted at the beginning of the list.
  183. * @param c The command to add to the list pointed to by @c head.
  184. */
  185. static void command_add_child(struct command **head, struct command *c)
  186. {
  187. assert(head);
  188. if (NULL == *head)
  189. {
  190. *head = c;
  191. return;
  192. }
  193. while ((*head)->next && (strcmp(c->name, (*head)->name) > 0))
  194. head = &(*head)->next;
  195. if (strcmp(c->name, (*head)->name) > 0) {
  196. c->next = (*head)->next;
  197. (*head)->next = c;
  198. } else {
  199. c->next = *head;
  200. *head = c;
  201. }
  202. }
  203. static struct command **command_list_for_parent(
  204. struct command_context *cmd_ctx, struct command *parent)
  205. {
  206. return parent ? &parent->children : &cmd_ctx->commands;
  207. }
  208. static struct command *command_new(struct command_context *cmd_ctx,
  209. struct command *parent, const struct command_registration *cr)
  210. {
  211. assert(cr->name);
  212. struct command *c = malloc(sizeof(struct command));
  213. memset(c, 0, sizeof(struct command));
  214. c->name = strdup(cr->name);
  215. if (cr->help)
  216. c->help = strdup(cr->help);
  217. if (cr->usage)
  218. c->usage = strdup(cr->usage);
  219. c->parent = parent;
  220. c->handler = cr->handler;
  221. c->jim_handler = cr->jim_handler;
  222. c->jim_handler_data = cr->jim_handler_data;
  223. c->mode = cr->mode;
  224. command_add_child(command_list_for_parent(cmd_ctx, parent), c);
  225. return c;
  226. }
  227. static void command_free(struct command *c)
  228. {
  229. /// @todo if command has a handler, unregister its jim command!
  230. while (NULL != c->children)
  231. {
  232. struct command *tmp = c->children;
  233. c->children = tmp->next;
  234. command_free(tmp);
  235. }
  236. if (c->name)
  237. free(c->name);
  238. if (c->help)
  239. free((void*)c->help);
  240. if (c->usage)
  241. free((void*)c->usage);
  242. free(c);
  243. }
  244. static int register_command_handler(struct command *c)
  245. {
  246. int retval = -ENOMEM;
  247. const char *full_name = command_name(c, '_');
  248. if (NULL == full_name)
  249. return retval;
  250. const char *ocd_name = alloc_printf("ocd_%s", full_name);
  251. if (NULL == full_name)
  252. goto free_full_name;
  253. Jim_CreateCommand(interp, ocd_name, script_command, c, NULL);
  254. free((void *)ocd_name);
  255. /* we now need to add an overrideable proc */
  256. const char *override_name = alloc_printf("proc %s {args} {"
  257. "if {[catch {eval ocd_%s $args}] == 0} "
  258. "{return \"\"} else {return -code error}}",
  259. full_name, full_name);
  260. if (NULL == full_name)
  261. goto free_full_name;
  262. Jim_Eval_Named(interp, override_name, __THIS__FILE__, __LINE__);
  263. free((void *)override_name);
  264. retval = ERROR_OK;
  265. free_full_name:
  266. free((void *)full_name);
  267. return retval;
  268. }
  269. struct command* register_command(struct command_context *context,
  270. struct command *parent, const struct command_registration *cr)
  271. {
  272. if (!context || !cr->name)
  273. return NULL;
  274. const char *name = cr->name;
  275. struct command **head = command_list_for_parent(context, parent);
  276. struct command *c = command_find(*head, name);
  277. if (NULL != c)
  278. {
  279. LOG_ERROR("command '%s' is already registered in '%s' context",
  280. name, parent ? parent->name : "<global>");
  281. return c;
  282. }
  283. c = command_new(context, parent, cr);
  284. if (NULL == c)
  285. return NULL;
  286. if (NULL != c->handler)
  287. {
  288. int retval = register_command_handler(c);
  289. if (ERROR_OK != retval)
  290. {
  291. unregister_command(context, parent, name);
  292. return NULL;
  293. }
  294. }
  295. if (NULL != cr->jim_handler && NULL == parent)
  296. Jim_CreateCommand(interp, cr->name, cr->jim_handler, cr->jim_handler_data, NULL);
  297. return c;
  298. }
  299. int register_commands(struct command_context *cmd_ctx, struct command *parent,
  300. const struct command_registration *cmds)
  301. {
  302. int retval = ERROR_OK;
  303. unsigned i;
  304. for (i = 0; cmds[i].name || cmds[i].chain; i++)
  305. {
  306. const struct command_registration *cr = cmds + i;
  307. struct command *c = NULL;
  308. if (NULL != cr->name)
  309. {
  310. c = register_command(cmd_ctx, parent, cr);
  311. if (NULL == c)
  312. {
  313. retval = ERROR_FAIL;
  314. break;
  315. }
  316. }
  317. if (NULL != cr->chain)
  318. {
  319. struct command *p = c ? : parent;
  320. retval = register_commands(cmd_ctx, p, cr->chain);
  321. if (ERROR_OK != retval)
  322. break;
  323. }
  324. }
  325. if (ERROR_OK != retval)
  326. {
  327. for (unsigned j = 0; j < i; j++)
  328. unregister_command(cmd_ctx, parent, cmds[j].name);
  329. }
  330. return retval;
  331. }
  332. int unregister_all_commands(struct command_context *context,
  333. struct command *parent)
  334. {
  335. if (context == NULL)
  336. return ERROR_OK;
  337. struct command **head = command_list_for_parent(context, parent);
  338. while (NULL != *head)
  339. {
  340. struct command *tmp = *head;
  341. *head = tmp->next;
  342. command_free(tmp);
  343. }
  344. return ERROR_OK;
  345. }
  346. int unregister_command(struct command_context *context,
  347. struct command *parent, const char *name)
  348. {
  349. if ((!context) || (!name))
  350. return ERROR_INVALID_ARGUMENTS;
  351. struct command *p = NULL;
  352. struct command **head = command_list_for_parent(context, parent);
  353. for (struct command *c = *head; NULL != c; p = c, c = c->next)
  354. {
  355. if (strcmp(name, c->name) != 0)
  356. continue;
  357. if (p)
  358. p->next = c->next;
  359. else
  360. *head = c->next;
  361. command_free(c);
  362. return ERROR_OK;
  363. }
  364. return ERROR_OK;
  365. }
  366. void command_output_text(struct command_context *context, const char *data)
  367. {
  368. if (context && context->output_handler && data) {
  369. context->output_handler(context, data);
  370. }
  371. }
  372. void command_print_sameline(struct command_context *context, const char *format, ...)
  373. {
  374. char *string;
  375. va_list ap;
  376. va_start(ap, format);
  377. string = alloc_vprintf(format, ap);
  378. if (string != NULL)
  379. {
  380. /* we want this collected in the log + we also want to pick it up as a tcl return
  381. * value.
  382. *
  383. * The latter bit isn't precisely neat, but will do for now.
  384. */
  385. LOG_USER_N("%s", string);
  386. /* We already printed it above */
  387. /* command_output_text(context, string); */
  388. free(string);
  389. }
  390. va_end(ap);
  391. }
  392. void command_print(struct command_context *context, const char *format, ...)
  393. {
  394. char *string;
  395. va_list ap;
  396. va_start(ap, format);
  397. string = alloc_vprintf(format, ap);
  398. if (string != NULL)
  399. {
  400. strcat(string, "\n"); /* alloc_vprintf guaranteed the buffer to be at least one char longer */
  401. /* we want this collected in the log + we also want to pick it up as a tcl return
  402. * value.
  403. *
  404. * The latter bit isn't precisely neat, but will do for now.
  405. */
  406. LOG_USER_N("%s", string);
  407. /* We already printed it above */
  408. /* command_output_text(context, string); */
  409. free(string);
  410. }
  411. va_end(ap);
  412. }
  413. static char *__command_name(struct command *c, char delim, unsigned extra)
  414. {
  415. char *name;
  416. unsigned len = strlen(c->name);
  417. if (NULL == c->parent) {
  418. // allocate enough for the name, child names, and '\0'
  419. name = malloc(len + extra + 1);
  420. strcpy(name, c->name);
  421. } else {
  422. // parent's extra must include both the space and name
  423. name = __command_name(c->parent, delim, 1 + len + extra);
  424. char dstr[2] = { delim, 0 };
  425. strcat(name, dstr);
  426. strcat(name, c->name);
  427. }
  428. return name;
  429. }
  430. char *command_name(struct command *c, char delim)
  431. {
  432. return __command_name(c, delim, 0);
  433. }
  434. static int run_command(struct command_context *context,
  435. struct command *c, const char *words[], unsigned num_words)
  436. {
  437. if (!((context->mode == COMMAND_CONFIG) || (c->mode == COMMAND_ANY) || (c->mode == context->mode)))
  438. {
  439. /* Config commands can not run after the config stage */
  440. LOG_ERROR("Command '%s' only runs during configuration stage", c->name);
  441. return ERROR_FAIL;
  442. }
  443. struct command_invocation cmd = {
  444. .ctx = context,
  445. .name = c->name,
  446. .argc = num_words - 1,
  447. .argv = words + 1,
  448. };
  449. int retval = c->handler(&cmd);
  450. if (retval == ERROR_COMMAND_SYNTAX_ERROR)
  451. {
  452. /* Print help for command */
  453. char *full_name = command_name(c, ' ');
  454. if (NULL != full_name) {
  455. command_run_linef(context, "help %s", full_name);
  456. free(full_name);
  457. } else
  458. retval = -ENOMEM;
  459. }
  460. else if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
  461. {
  462. /* just fall through for a shutdown request */
  463. }
  464. else if (retval != ERROR_OK)
  465. {
  466. /* we do not print out an error message because the command *should*
  467. * have printed out an error
  468. */
  469. LOG_DEBUG("Command failed with error code %d", retval);
  470. }
  471. return retval;
  472. }
  473. int command_run_line(struct command_context *context, char *line)
  474. {
  475. /* all the parent commands have been registered with the interpreter
  476. * so, can just evaluate the line as a script and check for
  477. * results
  478. */
  479. /* run the line thru a script engine */
  480. int retval = ERROR_FAIL;
  481. int retcode;
  482. /* Beware! This code needs to be reentrant. It is also possible
  483. * for OpenOCD commands to be invoked directly from Tcl. This would
  484. * happen when the Jim Tcl interpreter is provided by eCos for
  485. * instance.
  486. */
  487. Jim_DeleteAssocData(interp, "context");
  488. retcode = Jim_SetAssocData(interp, "context", NULL, context);
  489. if (retcode == JIM_OK)
  490. {
  491. /* associated the return value */
  492. Jim_DeleteAssocData(interp, "retval");
  493. retcode = Jim_SetAssocData(interp, "retval", NULL, &retval);
  494. if (retcode == JIM_OK)
  495. {
  496. retcode = Jim_Eval_Named(interp, line, __THIS__FILE__, __LINE__);
  497. Jim_DeleteAssocData(interp, "retval");
  498. }
  499. Jim_DeleteAssocData(interp, "context");
  500. }
  501. if (retcode == JIM_ERR) {
  502. if (retval != ERROR_COMMAND_CLOSE_CONNECTION)
  503. {
  504. /* We do not print the connection closed error message */
  505. Jim_PrintErrorMessage(interp);
  506. }
  507. if (retval == ERROR_OK)
  508. {
  509. /* It wasn't a low level OpenOCD command that failed */
  510. return ERROR_FAIL;
  511. }
  512. return retval;
  513. } else if (retcode == JIM_EXIT) {
  514. /* ignore. */
  515. /* exit(Jim_GetExitCode(interp)); */
  516. } else {
  517. const char *result;
  518. int reslen;
  519. result = Jim_GetString(Jim_GetResult(interp), &reslen);
  520. if (reslen > 0)
  521. {
  522. int i;
  523. char buff[256 + 1];
  524. for (i = 0; i < reslen; i += 256)
  525. {
  526. int chunk;
  527. chunk = reslen - i;
  528. if (chunk > 256)
  529. chunk = 256;
  530. strncpy(buff, result + i, chunk);
  531. buff[chunk] = 0;
  532. LOG_USER_N("%s", buff);
  533. }
  534. LOG_USER_N("%s", "\n");
  535. }
  536. retval = ERROR_OK;
  537. }
  538. return retval;
  539. }
  540. int command_run_linef(struct command_context *context, const char *format, ...)
  541. {
  542. int retval = ERROR_FAIL;
  543. char *string;
  544. va_list ap;
  545. va_start(ap, format);
  546. string = alloc_vprintf(format, ap);
  547. if (string != NULL)
  548. {
  549. retval = command_run_line(context, string);
  550. }
  551. va_end(ap);
  552. return retval;
  553. }
  554. void command_set_output_handler(struct command_context* context,
  555. command_output_handler_t output_handler, void *priv)
  556. {
  557. context->output_handler = output_handler;
  558. context->output_handler_priv = priv;
  559. }
  560. struct command_context* copy_command_context(struct command_context* context)
  561. {
  562. struct command_context* copy_context = malloc(sizeof(struct command_context));
  563. *copy_context = *context;
  564. return copy_context;
  565. }
  566. int command_done(struct command_context *context)
  567. {
  568. free(context);
  569. context = NULL;
  570. return ERROR_OK;
  571. }
  572. /* find full path to file */
  573. static int jim_find(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  574. {
  575. if (argc != 2)
  576. return JIM_ERR;
  577. const char *file = Jim_GetString(argv[1], NULL);
  578. char *full_path = find_file(file);
  579. if (full_path == NULL)
  580. return JIM_ERR;
  581. Jim_Obj *result = Jim_NewStringObj(interp, full_path, strlen(full_path));
  582. free(full_path);
  583. Jim_SetResult(interp, result);
  584. return JIM_OK;
  585. }
  586. static int jim_echo(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  587. {
  588. if (argc != 2)
  589. return JIM_ERR;
  590. const char *str = Jim_GetString(argv[1], NULL);
  591. LOG_USER("%s", str);
  592. return JIM_OK;
  593. }
  594. static size_t openocd_jim_fwrite(const void *_ptr, size_t size, size_t n, void *cookie)
  595. {
  596. size_t nbytes;
  597. const char *ptr;
  598. Jim_Interp *interp;
  599. /* make it a char easier to read code */
  600. ptr = _ptr;
  601. interp = cookie;
  602. nbytes = size * n;
  603. if (ptr == NULL || interp == NULL || nbytes == 0) {
  604. return 0;
  605. }
  606. /* do we have to chunk it? */
  607. if (ptr[nbytes] == 0)
  608. {
  609. /* no it is a C style string */
  610. LOG_USER_N("%s", ptr);
  611. return strlen(ptr);
  612. }
  613. /* GRR we must chunk - not null terminated */
  614. while (nbytes) {
  615. char chunk[128 + 1];
  616. int x;
  617. x = nbytes;
  618. if (x > 128) {
  619. x = 128;
  620. }
  621. /* copy it */
  622. memcpy(chunk, ptr, x);
  623. /* terminate it */
  624. chunk[n] = 0;
  625. /* output it */
  626. LOG_USER_N("%s", chunk);
  627. ptr += x;
  628. nbytes -= x;
  629. }
  630. return n;
  631. }
  632. static size_t openocd_jim_fread(void *ptr, size_t size, size_t n, void *cookie)
  633. {
  634. /* TCL wants to read... tell him no */
  635. return 0;
  636. }
  637. static int openocd_jim_vfprintf(void *cookie, const char *fmt, va_list ap)
  638. {
  639. char *cp;
  640. int n;
  641. Jim_Interp *interp;
  642. n = -1;
  643. interp = cookie;
  644. if (interp == NULL)
  645. return n;
  646. cp = alloc_vprintf(fmt, ap);
  647. if (cp)
  648. {
  649. LOG_USER_N("%s", cp);
  650. n = strlen(cp);
  651. free(cp);
  652. }
  653. return n;
  654. }
  655. static int openocd_jim_fflush(void *cookie)
  656. {
  657. /* nothing to flush */
  658. return 0;
  659. }
  660. static char* openocd_jim_fgets(char *s, int size, void *cookie)
  661. {
  662. /* not supported */
  663. errno = ENOTSUP;
  664. return NULL;
  665. }
  666. static int jim_capture(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  667. {
  668. if (argc != 2)
  669. return JIM_ERR;
  670. Jim_Obj *tclOutput = command_log_capture_start(interp);
  671. const char *str = Jim_GetString(argv[1], NULL);
  672. int retcode = Jim_Eval_Named(interp, str, __THIS__FILE__, __LINE__);
  673. command_log_capture_finish(interp, tclOutput);
  674. return retcode;
  675. }
  676. static COMMAND_HELPER(command_help_find, struct command *head,
  677. struct command **out)
  678. {
  679. if (0 == CMD_ARGC)
  680. return ERROR_INVALID_ARGUMENTS;
  681. *out = command_find(head, CMD_ARGV[0]);
  682. if (NULL == *out)
  683. return ERROR_INVALID_ARGUMENTS;
  684. if (--CMD_ARGC == 0)
  685. return ERROR_OK;
  686. CMD_ARGV++;
  687. return CALL_COMMAND_HANDLER(command_help_find, (*out)->children, out);
  688. }
  689. static COMMAND_HELPER(command_help_show, struct command *c, unsigned n,
  690. bool show_help);
  691. static COMMAND_HELPER(command_help_show_list, struct command *head, unsigned n,
  692. bool show_help)
  693. {
  694. for (struct command *c = head; NULL != c; c = c->next)
  695. CALL_COMMAND_HANDLER(command_help_show, c, n, show_help);
  696. return ERROR_OK;
  697. }
  698. #define HELP_LINE_WIDTH(_n) (int)(76 - (2 * _n))
  699. static void command_help_show_indent(unsigned n)
  700. {
  701. for (unsigned i = 0; i < n; i++)
  702. LOG_USER_N(" ");
  703. }
  704. static void command_help_show_wrap(const char *str, unsigned n, unsigned n2)
  705. {
  706. const char *cp = str, *last = str;
  707. while (*cp)
  708. {
  709. const char *next = last;
  710. do {
  711. cp = next;
  712. do {
  713. next++;
  714. } while (*next != ' ' && *next != '\t' && *next != '\0');
  715. } while ((next - last < HELP_LINE_WIDTH(n)) && *next != '\0');
  716. if (next - last < HELP_LINE_WIDTH(n))
  717. cp = next;
  718. command_help_show_indent(n);
  719. LOG_USER_N("%.*s", (int)(cp - last), last);
  720. LOG_USER_N("\n");
  721. last = cp + 1;
  722. n = n2;
  723. }
  724. }
  725. static COMMAND_HELPER(command_help_show, struct command *c, unsigned n,
  726. bool show_help)
  727. {
  728. command_help_show_indent(n);
  729. LOG_USER_N("%s", command_name(c, ' '));
  730. if (c->usage) {
  731. LOG_USER_N(" ");
  732. command_help_show_wrap(c->usage, 0, n + 5);
  733. }
  734. else
  735. LOG_USER_N("\n");
  736. if (show_help && c->help)
  737. command_help_show_wrap(c->help, n + 3, n + 3);
  738. if (++n >= 2)
  739. return ERROR_OK;
  740. return CALL_COMMAND_HANDLER(command_help_show_list,
  741. c->children, n, show_help);
  742. }
  743. COMMAND_HANDLER(handle_help_command)
  744. {
  745. bool full = strcmp(CMD_NAME, "help") == 0;
  746. struct command *c = CMD_CTX->commands;
  747. if (0 == CMD_ARGC)
  748. return CALL_COMMAND_HANDLER(command_help_show_list, c, 0, full);
  749. int retval = CALL_COMMAND_HANDLER(command_help_find, c, &c);
  750. if (ERROR_OK != retval)
  751. return retval;
  752. return CALL_COMMAND_HANDLER(command_help_show, c, 0, full);
  753. }
  754. static int command_unknown_find(unsigned argc, Jim_Obj *const *argv,
  755. struct command *head, struct command **out)
  756. {
  757. if (0 == argc)
  758. return argc;
  759. struct command *c = command_find(head, Jim_GetString(argv[0], NULL));
  760. if (NULL == c)
  761. return argc;
  762. *out = c;
  763. return command_unknown_find(--argc, ++argv, (*out)->children, out);
  764. }
  765. static int command_unknown(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  766. {
  767. const char *cmd_name = Jim_GetString(argv[0], NULL);
  768. script_debug(interp, cmd_name, argc - 1, argv + 1);
  769. struct command_context *cmd_ctx = current_command_context();
  770. struct command *c = cmd_ctx->commands;
  771. int remaining = command_unknown_find(argc - 1, argv + 1, c, &c);
  772. // if nothing could be consumed, then it's really an unknown command
  773. if (remaining == argc - 1)
  774. {
  775. const char *cmd = Jim_GetString(argv[1], NULL);
  776. LOG_ERROR("Unknown command:\n %s", cmd);
  777. return JIM_OK;
  778. }
  779. bool found = true;
  780. Jim_Obj *const *start;
  781. unsigned count;
  782. if (c->handler || c->jim_handler)
  783. {
  784. // include the command name in the list
  785. count = remaining + 1;
  786. start = argv + (argc - remaining - 1);
  787. }
  788. else
  789. {
  790. c = command_find(cmd_ctx->commands, "help");
  791. if (NULL == c)
  792. {
  793. LOG_ERROR("unknown command, but help is missing too");
  794. return JIM_ERR;
  795. }
  796. count = argc - remaining;
  797. start = argv;
  798. found = false;
  799. }
  800. // pass the command through to the intended handler
  801. if (c->jim_handler)
  802. {
  803. interp->cmdPrivData = c->jim_handler_data;
  804. return (*c->jim_handler)(interp, count, start);
  805. }
  806. unsigned nwords;
  807. const char **words = script_command_args_alloc(count, start, &nwords);
  808. if (NULL == words)
  809. return JIM_ERR;
  810. Jim_Obj *tclOutput = command_log_capture_start(interp);
  811. int retval = run_command(cmd_ctx, c, words, nwords);
  812. command_log_capture_finish(interp, tclOutput);
  813. script_command_args_free(words, nwords);
  814. if (!found && ERROR_OK == retval)
  815. retval = ERROR_FAIL;
  816. return command_retval_set(interp, retval);
  817. }
  818. int help_add_command(struct command_context *cmd_ctx, struct command *parent,
  819. const char *cmd_name, const char *help_text, const char *usage)
  820. {
  821. struct command **head = command_list_for_parent(cmd_ctx, parent);
  822. struct command *nc = command_find(*head, cmd_name);
  823. if (NULL == nc)
  824. {
  825. // add a new command with help text
  826. struct command_registration cr = {
  827. .name = cmd_name,
  828. .mode = COMMAND_ANY,
  829. .help = help_text,
  830. .usage = usage,
  831. };
  832. nc = register_command(cmd_ctx, parent, &cr);
  833. if (NULL == nc)
  834. {
  835. LOG_ERROR("failed to add '%s' help text", cmd_name);
  836. return ERROR_FAIL;
  837. }
  838. LOG_DEBUG("added '%s' help text", cmd_name);
  839. return ERROR_OK;
  840. }
  841. if (help_text)
  842. {
  843. bool replaced = false;
  844. if (nc->help)
  845. {
  846. free((void *)nc->help);
  847. replaced = true;
  848. }
  849. nc->help = strdup(help_text);
  850. if (replaced)
  851. LOG_INFO("replaced existing '%s' help", cmd_name);
  852. else
  853. LOG_DEBUG("added '%s' help text", cmd_name);
  854. }
  855. if (usage)
  856. {
  857. bool replaced = false;
  858. if (nc->usage)
  859. {
  860. free((void *)nc->usage);
  861. replaced = true;
  862. }
  863. nc->usage = strdup(usage);
  864. if (replaced)
  865. LOG_INFO("replaced existing '%s' usage", cmd_name);
  866. else
  867. LOG_DEBUG("added '%s' usage text", cmd_name);
  868. }
  869. return ERROR_OK;
  870. }
  871. COMMAND_HANDLER(handle_help_add_command)
  872. {
  873. if (CMD_ARGC < 2)
  874. {
  875. LOG_ERROR("%s: insufficient arguments", CMD_NAME);
  876. return ERROR_INVALID_ARGUMENTS;
  877. }
  878. // save help text and remove it from argument list
  879. const char *str = CMD_ARGV[--CMD_ARGC];
  880. const char *help = !strcmp(CMD_NAME, "add_help_text") ? str : NULL;
  881. const char *usage = !strcmp(CMD_NAME, "add_usage_text") ? str : NULL;
  882. if (!help && !usage)
  883. {
  884. LOG_ERROR("command name '%s' is unknown", CMD_NAME);
  885. return ERROR_INVALID_ARGUMENTS;
  886. }
  887. // likewise for the leaf command name
  888. const char *cmd_name = CMD_ARGV[--CMD_ARGC];
  889. struct command *c = NULL;
  890. if (CMD_ARGC > 0)
  891. {
  892. c = CMD_CTX->commands;
  893. int retval = CALL_COMMAND_HANDLER(command_help_find, c, &c);
  894. if (ERROR_OK != retval)
  895. return retval;
  896. }
  897. return help_add_command(CMD_CTX, c, cmd_name, help, usage);
  898. }
  899. /* sleep command sleeps for <n> miliseconds
  900. * this is useful in target startup scripts
  901. */
  902. COMMAND_HANDLER(handle_sleep_command)
  903. {
  904. bool busy = false;
  905. if (CMD_ARGC == 2)
  906. {
  907. if (strcmp(CMD_ARGV[1], "busy") == 0)
  908. busy = true;
  909. else
  910. return ERROR_COMMAND_SYNTAX_ERROR;
  911. }
  912. else if (CMD_ARGC < 1 || CMD_ARGC > 2)
  913. return ERROR_COMMAND_SYNTAX_ERROR;
  914. unsigned long duration = 0;
  915. int retval = parse_ulong(CMD_ARGV[0], &duration);
  916. if (ERROR_OK != retval)
  917. return retval;
  918. if (!busy)
  919. {
  920. long long then = timeval_ms();
  921. while (timeval_ms() - then < (long long)duration)
  922. {
  923. target_call_timer_callbacks_now();
  924. usleep(1000);
  925. }
  926. }
  927. else
  928. busy_sleep(duration);
  929. return ERROR_OK;
  930. }
  931. static const struct command_registration command_builtin_handlers[] = {
  932. {
  933. .name = "add_help_text",
  934. .handler = &handle_help_add_command,
  935. .mode = COMMAND_ANY,
  936. .help = "add new command help text",
  937. .usage = "<command> [...] <help_text>]",
  938. },
  939. {
  940. .name = "add_usage_text",
  941. .handler = &handle_help_add_command,
  942. .mode = COMMAND_ANY,
  943. .help = "add new command usage text",
  944. .usage = "<command> [...] <usage_text>]",
  945. },
  946. {
  947. .name = "sleep",
  948. .handler = &handle_sleep_command,
  949. .mode = COMMAND_ANY,
  950. .help = "sleep for n milliseconds. "
  951. "\"busy\" will busy wait",
  952. .usage = "<n> [busy]",
  953. },
  954. {
  955. .name = "help",
  956. .handler = &handle_help_command,
  957. .mode = COMMAND_ANY,
  958. .help = "show full command help",
  959. .usage = "[<command> ...]",
  960. },
  961. {
  962. .name = "usage",
  963. .handler = &handle_help_command,
  964. .mode = COMMAND_ANY,
  965. .help = "show basic command usage",
  966. .usage = "[<command> ...]",
  967. },
  968. COMMAND_REGISTRATION_DONE
  969. };
  970. struct command_context* command_init(const char *startup_tcl)
  971. {
  972. struct command_context* context = malloc(sizeof(struct command_context));
  973. const char *HostOs;
  974. context->mode = COMMAND_EXEC;
  975. context->commands = NULL;
  976. context->current_target = 0;
  977. context->output_handler = NULL;
  978. context->output_handler_priv = NULL;
  979. #if !BUILD_ECOSBOARD
  980. Jim_InitEmbedded();
  981. /* Create an interpreter */
  982. interp = Jim_CreateInterp();
  983. /* Add all the Jim core commands */
  984. Jim_RegisterCoreCommands(interp);
  985. #endif
  986. #if defined(_MSC_VER)
  987. /* WinXX - is generic, the forward
  988. * looking problem is this:
  989. *
  990. * "win32" or "win64"
  991. *
  992. * "winxx" is generic.
  993. */
  994. HostOs = "winxx";
  995. #elif defined(__linux__)
  996. HostOs = "linux";
  997. #elif defined(__DARWIN__)
  998. HostOs = "darwin";
  999. #elif defined(__CYGWIN__)
  1000. HostOs = "cygwin";
  1001. #elif defined(__MINGW32__)
  1002. HostOs = "mingw32";
  1003. #elif defined(__ECOS)
  1004. HostOs = "ecos";
  1005. #else
  1006. #warn unrecognized host OS...
  1007. HostOs = "other";
  1008. #endif
  1009. Jim_SetGlobalVariableStr(interp, "ocd_HOSTOS",
  1010. Jim_NewStringObj(interp, HostOs , strlen(HostOs)));
  1011. Jim_CreateCommand(interp, "unknown", &command_unknown, NULL, NULL);
  1012. Jim_CreateCommand(interp, "ocd_find", jim_find, NULL, NULL);
  1013. Jim_CreateCommand(interp, "echo", jim_echo, NULL, NULL);
  1014. Jim_CreateCommand(interp, "capture", jim_capture, NULL, NULL);
  1015. /* Set Jim's STDIO */
  1016. interp->cookie_stdin = interp;
  1017. interp->cookie_stdout = interp;
  1018. interp->cookie_stderr = interp;
  1019. interp->cb_fwrite = openocd_jim_fwrite;
  1020. interp->cb_fread = openocd_jim_fread ;
  1021. interp->cb_vfprintf = openocd_jim_vfprintf;
  1022. interp->cb_fflush = openocd_jim_fflush;
  1023. interp->cb_fgets = openocd_jim_fgets;
  1024. register_commands(context, NULL, command_builtin_handlers);
  1025. #if !BUILD_ECOSBOARD
  1026. Jim_EventLoopOnLoad(interp);
  1027. #endif
  1028. Jim_SetAssocData(interp, "context", NULL, context);
  1029. if (Jim_Eval_Named(interp, startup_tcl, "embedded:startup.tcl",1) == JIM_ERR)
  1030. {
  1031. LOG_ERROR("Failed to run startup.tcl (embedded into OpenOCD)");
  1032. Jim_PrintErrorMessage(interp);
  1033. exit(-1);
  1034. }
  1035. Jim_DeleteAssocData(interp, "context");
  1036. return context;
  1037. }
  1038. int command_context_mode(struct command_context *cmd_ctx, enum command_mode mode)
  1039. {
  1040. if (!cmd_ctx)
  1041. return ERROR_INVALID_ARGUMENTS;
  1042. cmd_ctx->mode = mode;
  1043. return ERROR_OK;
  1044. }
  1045. void process_jim_events(void)
  1046. {
  1047. #if !BUILD_ECOSBOARD
  1048. static int recursion = 0;
  1049. if (!recursion)
  1050. {
  1051. recursion++;
  1052. Jim_ProcessEvents (interp, JIM_ALL_EVENTS | JIM_DONT_WAIT);
  1053. recursion--;
  1054. }
  1055. #endif
  1056. }
  1057. #define DEFINE_PARSE_NUM_TYPE(name, type, func, min, max) \
  1058. int parse##name(const char *str, type *ul) \
  1059. { \
  1060. if (!*str) \
  1061. { \
  1062. LOG_ERROR("Invalid command argument"); \
  1063. return ERROR_COMMAND_ARGUMENT_INVALID; \
  1064. } \
  1065. char *end; \
  1066. *ul = func(str, &end, 0); \
  1067. if (*end) \
  1068. { \
  1069. LOG_ERROR("Invalid command argument"); \
  1070. return ERROR_COMMAND_ARGUMENT_INVALID; \
  1071. } \
  1072. if ((max == *ul) && (ERANGE == errno)) \
  1073. { \
  1074. LOG_ERROR("Argument overflow"); \
  1075. return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
  1076. } \
  1077. if (min && (min == *ul) && (ERANGE == errno)) \
  1078. { \
  1079. LOG_ERROR("Argument underflow"); \
  1080. return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
  1081. } \
  1082. return ERROR_OK; \
  1083. }
  1084. DEFINE_PARSE_NUM_TYPE(_ulong, unsigned long , strtoul, 0, ULONG_MAX)
  1085. DEFINE_PARSE_NUM_TYPE(_ullong, unsigned long long, strtoull, 0, ULLONG_MAX)
  1086. DEFINE_PARSE_NUM_TYPE(_long, long , strtol, LONG_MIN, LONG_MAX)
  1087. DEFINE_PARSE_NUM_TYPE(_llong, long long, strtoll, LLONG_MIN, LLONG_MAX)
  1088. #define DEFINE_PARSE_WRAPPER(name, type, min, max, functype, funcname) \
  1089. int parse##name(const char *str, type *ul) \
  1090. { \
  1091. functype n; \
  1092. int retval = parse##funcname(str, &n); \
  1093. if (ERROR_OK != retval) \
  1094. return retval; \
  1095. if (n > max) \
  1096. return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
  1097. if (min) \
  1098. return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
  1099. *ul = n; \
  1100. return ERROR_OK; \
  1101. }
  1102. #define DEFINE_PARSE_ULONG(name, type, min, max) \
  1103. DEFINE_PARSE_WRAPPER(name, type, min, max, unsigned long, _ulong)
  1104. DEFINE_PARSE_ULONG(_uint, unsigned, 0, UINT_MAX)
  1105. DEFINE_PARSE_ULONG(_u32, uint32_t, 0, UINT32_MAX)
  1106. DEFINE_PARSE_ULONG(_u16, uint16_t, 0, UINT16_MAX)
  1107. DEFINE_PARSE_ULONG(_u8, uint8_t, 0, UINT8_MAX)
  1108. #define DEFINE_PARSE_LONG(name, type, min, max) \
  1109. DEFINE_PARSE_WRAPPER(name, type, min, max, long, _long)
  1110. DEFINE_PARSE_LONG(_int, int, n < INT_MIN, INT_MAX)
  1111. DEFINE_PARSE_LONG(_s32, int32_t, n < INT32_MIN, INT32_MAX)
  1112. DEFINE_PARSE_LONG(_s16, int16_t, n < INT16_MIN, INT16_MAX)
  1113. DEFINE_PARSE_LONG(_s8, int8_t, n < INT8_MIN, INT8_MAX)
  1114. static int command_parse_bool(const char *in, bool *out,
  1115. const char *on, const char *off)
  1116. {
  1117. if (strcasecmp(in, on) == 0)
  1118. *out = true;
  1119. else if (strcasecmp(in, off) == 0)
  1120. *out = false;
  1121. else
  1122. return ERROR_COMMAND_SYNTAX_ERROR;
  1123. return ERROR_OK;
  1124. }
  1125. int command_parse_bool_arg(const char *in, bool *out)
  1126. {
  1127. if (command_parse_bool(in, out, "on", "off") == ERROR_OK)
  1128. return ERROR_OK;
  1129. if (command_parse_bool(in, out, "enable", "disable") == ERROR_OK)
  1130. return ERROR_OK;
  1131. if (command_parse_bool(in, out, "true", "false") == ERROR_OK)
  1132. return ERROR_OK;
  1133. if (command_parse_bool(in, out, "yes", "no") == ERROR_OK)
  1134. return ERROR_OK;
  1135. if (command_parse_bool(in, out, "1", "0") == ERROR_OK)
  1136. return ERROR_OK;
  1137. return ERROR_INVALID_ARGUMENTS;
  1138. }
  1139. COMMAND_HELPER(handle_command_parse_bool, bool *out, const char *label)
  1140. {
  1141. switch (CMD_ARGC) {
  1142. case 1: {
  1143. const char *in = CMD_ARGV[0];
  1144. if (command_parse_bool_arg(in, out) != ERROR_OK)
  1145. {
  1146. LOG_ERROR("%s: argument '%s' is not valid", CMD_NAME, in);
  1147. return ERROR_INVALID_ARGUMENTS;
  1148. }
  1149. // fall through
  1150. }
  1151. case 0:
  1152. LOG_INFO("%s is %s", label, *out ? "enabled" : "disabled");
  1153. break;
  1154. default:
  1155. return ERROR_INVALID_ARGUMENTS;
  1156. }
  1157. return ERROR_OK;
  1158. }