1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
5 * Copyright (C) 2007,2008 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
8 * Copyright (C) 2008, Duane Ellis *
9 * openocd@duaneeellis.com *
11 * part of this file is taken from libcli (libcli.sourceforge.net) *
12 * Copyright (C) David Parrish (david@dparrish.com) *
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. *
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. *
24 * You should have received a copy of the GNU General Public License *
25 * along with this program. If not, see <http://www.gnu.org/licenses/>. *
26 ***************************************************************************/
32 /* see Embedded-HOWTO.txt in Jim Tcl project hosted on BerliOS*/
35 /* @todo the inclusion of target.h here is a layering violation */
36 #include <jtag/jtag.h>
37 #include <target/target.h>
39 #include "configuration.h"
41 #include "time_support.h"
42 #include "jim-eventloop.h"
44 /* nice short description of source file */
45 #define __THIS__FILE__ "command.c"
47 struct log_capture_state {
52 static int unregister_command(struct command_context *context,
53 const char *cmd_prefix, const char *name);
54 static int jim_command_dispatch(Jim_Interp *interp, int argc, Jim_Obj * const *argv);
55 static int help_add_command(struct command_context *cmd_ctx,
56 const char *cmd_name, const char *help_text, const char *usage_text);
57 static int help_del_command(struct command_context *cmd_ctx, const char *cmd_name);
59 /* set of functions to wrap jimtcl internal data */
60 static inline bool jimcmd_is_proc(Jim_Cmd *cmd)
65 static inline bool jimcmd_is_ocd_command(Jim_Cmd *cmd)
67 return !cmd->isproc && cmd->u.native.cmdProc == jim_command_dispatch;
70 static inline void *jimcmd_privdata(Jim_Cmd *cmd)
72 return cmd->isproc ? NULL : cmd->u.native.privData;
75 static void tcl_output(void *privData, const char *file, unsigned line,
76 const char *function, const char *string)
78 struct log_capture_state *state = privData;
79 Jim_AppendString(state->interp, state->output, string, strlen(string));
82 static struct log_capture_state *command_log_capture_start(Jim_Interp *interp)
84 /* capture log output and return it. A garbage collect can
85 * happen, so we need a reference count to this object */
86 Jim_Obj *tclOutput = Jim_NewStringObj(interp, "", 0);
87 if (NULL == tclOutput)
90 struct log_capture_state *state = malloc(sizeof(*state));
94 state->interp = interp;
95 Jim_IncrRefCount(tclOutput);
96 state->output = tclOutput;
98 log_add_callback(tcl_output, state);
103 /* Classic openocd commands provide progress output which we
104 * will capture and return as a Tcl return value.
106 * However, if a non-openocd command has been invoked, then it
107 * makes sense to return the tcl return value from that command.
109 * The tcl return value is empty for openocd commands that provide
112 * Therefore we set the tcl return value only if we actually
115 static void command_log_capture_finish(struct log_capture_state *state)
120 log_remove_callback(tcl_output, state);
123 Jim_GetString(state->output, &length);
126 Jim_SetResult(state->interp, state->output);
128 /* No output captured, use tcl return value (which could
131 Jim_DecrRefCount(state->interp, state->output);
137 * FIXME: workaround for memory leak in jimtcl 0.80
138 * Jim API Jim_CreateCommand() converts the command name in a Jim object and
139 * does not free the object. Fixed for jimtcl 0.81 by e4416cf86f0b
140 * Use the internal jimtcl API Jim_CreateCommandObj, not exported by jim.h,
141 * and override the bugged API through preprocessor's macro.
142 * This workaround works only when jimtcl is compiled as OpenOCD submodule.
143 * If jimtcl is linked-in from a precompiled library, either static or dynamic,
144 * the symbol Jim_CreateCommandObj is not exported and the build will use the
146 * To be removed when OpenOCD will switch to jimtcl 0.81
148 #if JIM_VERSION == 80
149 static int workaround_createcommand(Jim_Interp *interp, const char *cmdName,
150 Jim_CmdProc *cmdProc, void *privData, Jim_DelCmdProc *delProc);
151 int Jim_CreateCommandObj(Jim_Interp *interp, Jim_Obj *cmdNameObj,
152 Jim_CmdProc *cmdProc, void *privData, Jim_DelCmdProc *delProc)
153 __attribute__((weak, alias("workaround_createcommand")));
154 static int workaround_createcommand(Jim_Interp *interp, const char *cmdName,
155 Jim_CmdProc *cmdProc, void *privData, Jim_DelCmdProc *delProc)
157 if ((void *)Jim_CreateCommandObj == (void *)workaround_createcommand)
158 return Jim_CreateCommand(interp, cmdName, cmdProc, privData, delProc);
160 Jim_Obj *cmd_name = Jim_NewStringObj(interp, cmdName, -1);
161 Jim_IncrRefCount(cmd_name);
162 int retval = Jim_CreateCommandObj(interp, cmd_name, cmdProc, privData, delProc);
163 Jim_DecrRefCount(interp, cmd_name);
166 #define Jim_CreateCommand workaround_createcommand
167 #endif /* JIM_VERSION == 80 */
168 /* FIXME: end of workaround for memory leak in jimtcl 0.80 */
170 static int command_retval_set(Jim_Interp *interp, int retval)
172 int *return_retval = Jim_GetAssocData(interp, "retval");
173 if (return_retval != NULL)
174 *return_retval = retval;
176 return (retval == ERROR_OK) ? JIM_OK : retval;
179 extern struct command_context *global_cmd_ctx;
181 /* dump a single line to the log for the command.
182 * Do nothing in case we are not at debug level 3 */
183 static void script_debug(Jim_Interp *interp, unsigned int argc, Jim_Obj * const *argv)
185 if (debug_level < LOG_LVL_DEBUG)
188 char *dbg = alloc_printf("command -");
189 for (unsigned i = 0; i < argc; i++) {
191 const char *w = Jim_GetString(argv[i], &len);
192 char *t = alloc_printf("%s %s", dbg, w);
196 LOG_DEBUG("%s", dbg);
200 static void script_command_args_free(char **words, unsigned nwords)
202 for (unsigned i = 0; i < nwords; i++)
207 static char **script_command_args_alloc(
208 unsigned argc, Jim_Obj * const *argv, unsigned *nwords)
210 char **words = malloc(argc * sizeof(char *));
215 for (i = 0; i < argc; i++) {
217 const char *w = Jim_GetString(argv[i], &len);
218 words[i] = strdup(w);
219 if (words[i] == NULL) {
220 script_command_args_free(words, i);
228 struct command_context *current_command_context(Jim_Interp *interp)
230 /* grab the command context from the associated data */
231 struct command_context *cmd_ctx = Jim_GetAssocData(interp, "context");
232 if (NULL == cmd_ctx) {
233 /* Tcl can invoke commands directly instead of via command_run_line(). This would
234 * happen when the Jim Tcl interpreter is provided by eCos or if we are running
235 * commands in a startup script.
237 * A telnet or gdb server would provide a non-default command context to
238 * handle piping of error output, have a separate current target, etc.
240 cmd_ctx = global_cmd_ctx;
246 * Find a openocd command from fullname.
247 * @returns Returns the named command if it is registred in interp.
248 * Returns NULL otherwise.
250 static struct command *command_find_from_name(Jim_Interp *interp, const char *name)
255 Jim_Obj *jim_name = Jim_NewStringObj(interp, name, -1);
256 Jim_IncrRefCount(jim_name);
257 Jim_Cmd *cmd = Jim_GetCommand(interp, jim_name, JIM_NONE);
258 Jim_DecrRefCount(interp, jim_name);
259 if (!cmd || jimcmd_is_proc(cmd) || !jimcmd_is_ocd_command(cmd))
262 return jimcmd_privdata(cmd);
265 static struct command *command_new(struct command_context *cmd_ctx,
266 const char *full_name, const struct command_registration *cr)
271 * If it is a non-jim command with no .usage specified,
274 * strlen(.usage) == 0 means that the command takes no
277 if (!cr->jim_handler && !cr->usage)
278 LOG_ERROR("BUG: command '%s' does not have the "
279 "'.usage' field filled out",
282 struct command *c = calloc(1, sizeof(struct command));
286 c->name = strdup(cr->name);
292 c->handler = cr->handler;
293 c->jim_handler = cr->jim_handler;
296 if (cr->help || cr->usage)
297 help_add_command(cmd_ctx, full_name, cr->help, cr->usage);
302 static void command_free(struct Jim_Interp *interp, void *priv)
304 struct command *c = priv;
310 static struct command *register_command(struct command_context *context,
311 const char *cmd_prefix, const struct command_registration *cr)
315 if (!context || !cr->name)
319 full_name = alloc_printf("%s %s", cmd_prefix, cr->name);
321 full_name = strdup(cr->name);
325 struct command *c = command_find_from_name(context->interp, full_name);
327 /* TODO: originally we treated attempting to register a cmd twice as an error
328 * Sometimes we need this behaviour, such as with flash banks.
329 * http://www.mail-archive.com/openocd-development@lists.berlios.de/msg11152.html */
330 LOG_DEBUG("command '%s' is already registered", full_name);
335 c = command_new(context, full_name, cr);
341 LOG_DEBUG("registering '%s'...", full_name);
342 int retval = Jim_CreateCommand(context->interp, full_name,
343 jim_command_dispatch, c, command_free);
344 if (retval != JIM_OK) {
345 command_run_linef(context, "del_help_text {%s}", full_name);
346 command_run_linef(context, "del_usage_text {%s}", full_name);
356 int __register_commands(struct command_context *cmd_ctx, const char *cmd_prefix,
357 const struct command_registration *cmds, void *data,
358 struct target *override_target)
360 int retval = ERROR_OK;
362 for (i = 0; cmds[i].name || cmds[i].chain; i++) {
363 const struct command_registration *cr = cmds + i;
365 struct command *c = NULL;
366 if (NULL != cr->name) {
367 c = register_command(cmd_ctx, cmd_prefix, cr);
372 c->jim_handler_data = data;
373 c->jim_override_target = override_target;
375 if (NULL != cr->chain) {
378 char *new_prefix = alloc_printf("%s %s", cmd_prefix, cr->name);
383 retval = __register_commands(cmd_ctx, new_prefix, cr->chain, data, override_target);
386 retval = __register_commands(cmd_ctx, cr->name, cr->chain, data, override_target);
389 retval = __register_commands(cmd_ctx, cmd_prefix, cr->chain, data, override_target);
391 if (ERROR_OK != retval)
395 if (ERROR_OK != retval) {
396 for (unsigned j = 0; j < i; j++)
397 unregister_command(cmd_ctx, cmd_prefix, cmds[j].name);
402 static __attribute__ ((format (PRINTF_ATTRIBUTE_FORMAT, 2, 3)))
403 int unregister_commands_match(struct command_context *cmd_ctx, const char *format, ...)
405 Jim_Interp *interp = cmd_ctx->interp;
408 va_start(ap, format);
409 char *query = alloc_vprintf(format, ap);
414 char *query_cmd = alloc_printf("info commands {%s}", query);
419 int retval = Jim_EvalSource(interp, __THIS__FILE__, __LINE__, query_cmd);
421 if (retval != JIM_OK)
424 Jim_Obj *list = Jim_GetResult(interp);
425 Jim_IncrRefCount(list);
427 int len = Jim_ListLength(interp, list);
428 for (int i = 0; i < len; i++) {
429 Jim_Obj *elem = Jim_ListGetIndex(interp, list, i);
430 Jim_IncrRefCount(elem);
432 const char *name = Jim_GetString(elem, NULL);
433 struct command *c = command_find_from_name(interp, name);
435 /* not openocd command */
436 Jim_DecrRefCount(interp, elem);
439 LOG_DEBUG("delete command \"%s\"", name);
440 Jim_DeleteCommand(interp, elem);
442 help_del_command(cmd_ctx, name);
444 Jim_DecrRefCount(interp, elem);
447 Jim_DecrRefCount(interp, list);
451 int unregister_all_commands(struct command_context *context,
452 const char *cmd_prefix)
457 if (!cmd_prefix || !*cmd_prefix)
458 return unregister_commands_match(context, "*");
460 int retval = unregister_commands_match(context, "%s *", cmd_prefix);
461 if (retval != ERROR_OK)
464 return unregister_commands_match(context, "%s", cmd_prefix);
467 static int unregister_command(struct command_context *context,
468 const char *cmd_prefix, const char *name)
470 if (!context || !name)
471 return ERROR_COMMAND_SYNTAX_ERROR;
473 if (!cmd_prefix || !*cmd_prefix)
474 return unregister_commands_match(context, "%s", name);
476 return unregister_commands_match(context, "%s %s", cmd_prefix, name);
479 void command_output_text(struct command_context *context, const char *data)
481 if (context && context->output_handler && data)
482 context->output_handler(context, data);
485 void command_print_sameline(struct command_invocation *cmd, const char *format, ...)
490 va_start(ap, format);
492 string = alloc_vprintf(format, ap);
493 if (string != NULL && cmd) {
494 /* we want this collected in the log + we also want to pick it up as a tcl return
497 * The latter bit isn't precisely neat, but will do for now.
499 Jim_AppendString(cmd->ctx->interp, cmd->output, string, -1);
500 /* We already printed it above
501 * command_output_text(context, string); */
508 void command_print(struct command_invocation *cmd, const char *format, ...)
513 va_start(ap, format);
515 string = alloc_vprintf(format, ap);
516 if (string != NULL && cmd) {
517 strcat(string, "\n"); /* alloc_vprintf guaranteed the buffer to be at least one
519 /* we want this collected in the log + we also want to pick it up as a tcl return
522 * The latter bit isn't precisely neat, but will do for now.
524 Jim_AppendString(cmd->ctx->interp, cmd->output, string, -1);
525 /* We already printed it above
526 * command_output_text(context, string); */
533 static bool command_can_run(struct command_context *cmd_ctx, struct command *c, const char *full_name)
535 if (c->mode == COMMAND_ANY || c->mode == cmd_ctx->mode)
538 /* Many commands may be run only before/after 'init' */
547 /* handle the impossible with humor; it guarantees a bug report! */
549 when = "if Cthulhu is summoned by";
552 LOG_ERROR("The '%s' command must be used %s 'init'.",
553 full_name ? full_name : c->name, when);
557 static int run_command(struct command_context *context,
558 struct command *c, const char **words, unsigned num_words)
560 struct command_invocation cmd = {
564 .argc = num_words - 1,
568 cmd.output = Jim_NewEmptyStringObj(context->interp);
569 Jim_IncrRefCount(cmd.output);
571 int retval = c->handler(&cmd);
572 if (retval == ERROR_COMMAND_SYNTAX_ERROR) {
573 /* Print help for command */
574 command_run_linef(context, "usage %s", words[0]);
575 } else if (retval == ERROR_COMMAND_CLOSE_CONNECTION) {
576 /* just fall through for a shutdown request */
578 if (retval != ERROR_OK)
579 LOG_DEBUG("Command '%s' failed with error code %d",
581 /* Use the command output as the Tcl result */
582 Jim_SetResult(context->interp, cmd.output);
584 Jim_DecrRefCount(context->interp, cmd.output);
589 int command_run_line(struct command_context *context, char *line)
591 /* all the parent commands have been registered with the interpreter
592 * so, can just evaluate the line as a script and check for
595 /* run the line thru a script engine */
596 int retval = ERROR_FAIL;
598 /* Beware! This code needs to be reentrant. It is also possible
599 * for OpenOCD commands to be invoked directly from Tcl. This would
600 * happen when the Jim Tcl interpreter is provided by eCos for
603 struct target *saved_target_override = context->current_target_override;
604 context->current_target_override = NULL;
606 Jim_Interp *interp = context->interp;
607 struct command_context *old_context = Jim_GetAssocData(interp, "context");
608 Jim_DeleteAssocData(interp, "context");
609 retcode = Jim_SetAssocData(interp, "context", NULL, context);
610 if (retcode == JIM_OK) {
611 /* associated the return value */
612 Jim_DeleteAssocData(interp, "retval");
613 retcode = Jim_SetAssocData(interp, "retval", NULL, &retval);
614 if (retcode == JIM_OK) {
615 retcode = Jim_Eval_Named(interp, line, 0, 0);
617 Jim_DeleteAssocData(interp, "retval");
619 Jim_DeleteAssocData(interp, "context");
620 int inner_retcode = Jim_SetAssocData(interp, "context", NULL, old_context);
621 if (retcode == JIM_OK)
622 retcode = inner_retcode;
624 context->current_target_override = saved_target_override;
625 if (retcode == JIM_OK) {
629 result = Jim_GetString(Jim_GetResult(interp), &reslen);
631 command_output_text(context, result);
632 command_output_text(context, "\n");
635 } else if (retcode == JIM_EXIT) {
637 * exit(Jim_GetExitCode(interp)); */
638 } else if (retcode == ERROR_COMMAND_CLOSE_CONNECTION) {
641 Jim_MakeErrorMessage(interp);
642 /* error is broadcast */
643 LOG_USER("%s", Jim_GetString(Jim_GetResult(interp), NULL));
645 if (retval == ERROR_OK) {
646 /* It wasn't a low level OpenOCD command that failed */
655 int command_run_linef(struct command_context *context, const char *format, ...)
657 int retval = ERROR_FAIL;
660 va_start(ap, format);
661 string = alloc_vprintf(format, ap);
662 if (string != NULL) {
663 retval = command_run_line(context, string);
670 void command_set_output_handler(struct command_context *context,
671 command_output_handler_t output_handler, void *priv)
673 context->output_handler = output_handler;
674 context->output_handler_priv = priv;
677 struct command_context *copy_command_context(struct command_context *context)
679 struct command_context *copy_context = malloc(sizeof(struct command_context));
681 *copy_context = *context;
686 void command_done(struct command_context *cmd_ctx)
694 /* find full path to file */
695 static int jim_find(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
699 const char *file = Jim_GetString(argv[1], NULL);
700 char *full_path = find_file(file);
701 if (full_path == NULL)
703 Jim_Obj *result = Jim_NewStringObj(interp, full_path, strlen(full_path));
706 Jim_SetResult(interp, result);
710 COMMAND_HANDLER(jim_echo)
712 if (CMD_ARGC == 2 && !strcmp(CMD_ARGV[0], "-n")) {
713 LOG_USER_N("%s", CMD_ARGV[1]);
718 LOG_USER("%s", CMD_ARGV[0]);
722 /* Capture progress output and return as tcl return value. If the
723 * progress output was empty, return tcl return value.
725 static int jim_capture(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
730 struct log_capture_state *state = command_log_capture_start(interp);
732 /* disable polling during capture. This avoids capturing output
735 * This is necessary in order to avoid accidentally getting a non-empty
736 * string for tcl fn's.
738 bool save_poll = jtag_poll_get_enabled();
740 jtag_poll_set_enabled(false);
742 const char *str = Jim_GetString(argv[1], NULL);
743 int retcode = Jim_Eval_Named(interp, str, __THIS__FILE__, __LINE__);
745 jtag_poll_set_enabled(save_poll);
747 command_log_capture_finish(state);
759 static COMMAND_HELPER(command_help_show, struct help_entry *c,
760 bool show_help, const char *cmd_match);
762 static COMMAND_HELPER(command_help_show_list, bool show_help, const char *cmd_match)
764 struct help_entry *entry;
766 list_for_each_entry(entry, CMD_CTX->help_list, lh)
767 CALL_COMMAND_HANDLER(command_help_show, entry, show_help, cmd_match);
771 #define HELP_LINE_WIDTH(_n) (int)(76 - (2 * _n))
773 static void command_help_show_indent(unsigned n)
775 for (unsigned i = 0; i < n; i++)
778 static void command_help_show_wrap(const char *str, unsigned n, unsigned n2)
780 const char *cp = str, *last = str;
782 const char *next = last;
787 } while (*next != ' ' && *next != '\t' && *next != '\0');
788 } while ((next - last < HELP_LINE_WIDTH(n)) && *next != '\0');
789 if (next - last < HELP_LINE_WIDTH(n))
791 command_help_show_indent(n);
792 LOG_USER("%.*s", (int)(cp - last), last);
798 static COMMAND_HELPER(command_help_show, struct help_entry *c,
799 bool show_help, const char *cmd_match)
802 for (const char *s = strchr(c->cmd_name, ' '); s; s = strchr(s + 1, ' '))
805 /* If the match string occurs anywhere, we print out
806 * stuff for this command. */
807 bool is_match = (strstr(c->cmd_name, cmd_match) != NULL) ||
808 ((c->usage != NULL) && (strstr(c->usage, cmd_match) != NULL)) ||
809 ((c->help != NULL) && (strstr(c->help, cmd_match) != NULL));
812 command_help_show_indent(n);
813 LOG_USER_N("%s", c->cmd_name);
815 if (c->usage && strlen(c->usage) > 0) {
817 command_help_show_wrap(c->usage, 0, n + 5);
822 if (is_match && show_help) {
825 /* TODO: factorize jim_command_mode() to avoid running jim command here */
826 char *request = alloc_printf("command mode %s", c->cmd_name);
828 LOG_ERROR("Out of memory");
831 int retval = Jim_Eval(CMD_CTX->interp, request);
833 enum command_mode mode = COMMAND_UNKNOWN;
834 if (retval != JIM_ERR) {
835 const char *result = Jim_GetString(Jim_GetResult(CMD_CTX->interp), NULL);
836 if (!strcmp(result, "any"))
838 else if (!strcmp(result, "config"))
839 mode = COMMAND_CONFIG;
840 else if (!strcmp(result, "exec"))
844 /* Normal commands are runtime-only; highlight exceptions */
845 if (mode != COMMAND_EXEC) {
846 const char *stage_msg = "";
850 stage_msg = " (configuration command)";
853 stage_msg = " (command valid any time)";
856 stage_msg = " (?mode error?)";
859 msg = alloc_printf("%s%s", c->help ? : "", stage_msg);
861 msg = alloc_printf("%s", c->help ? : "");
864 command_help_show_wrap(msg, n + 3, n + 3);
873 COMMAND_HANDLER(handle_help_command)
875 bool full = strcmp(CMD_NAME, "help") == 0;
880 cmd_match = strdup("");
883 cmd_match = strdup(CMD_ARGV[0]);
885 for (unsigned int i = 1; i < CMD_ARGC && cmd_match; ++i) {
886 char *prev = cmd_match;
887 cmd_match = alloc_printf("%s %s", prev, CMD_ARGV[i]);
892 if (cmd_match == NULL) {
893 LOG_ERROR("unable to build search string");
896 retval = CALL_COMMAND_HANDLER(command_help_show_list, full, cmd_match);
902 static char *alloc_concatenate_strings(int argc, Jim_Obj * const *argv)
909 all = strdup(Jim_GetString(argv[0], NULL));
911 LOG_ERROR("Out of memory");
915 for (i = 1; i < argc; ++i) {
917 all = alloc_printf("%s %s", all, Jim_GetString(argv[i], NULL));
920 LOG_ERROR("Out of memory");
928 static int exec_command(Jim_Interp *interp, struct command_context *cmd_ctx,
929 struct command *c, int argc, Jim_Obj * const *argv)
932 return c->jim_handler(interp, argc, argv);
936 char **words = script_command_args_alloc(argc, argv, &nwords);
940 int retval = run_command(cmd_ctx, c, (const char **)words, nwords);
941 script_command_args_free(words, nwords);
942 return command_retval_set(interp, retval);
945 static int jim_command_dispatch(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
947 script_debug(interp, argc, argv);
949 /* check subcommands */
951 char *s = alloc_printf("%s %s", Jim_GetString(argv[0], NULL), Jim_GetString(argv[1], NULL));
952 Jim_Obj *js = Jim_NewStringObj(interp, s, -1);
953 Jim_IncrRefCount(js);
955 Jim_Cmd *cmd = Jim_GetCommand(interp, js, JIM_NONE);
957 int retval = Jim_EvalObjPrefix(interp, js, argc - 2, argv + 2);
958 Jim_DecrRefCount(interp, js);
961 Jim_DecrRefCount(interp, js);
964 struct command *c = jim_to_command(interp);
965 if (!c->jim_handler && !c->handler) {
966 Jim_EvalObjPrefix(interp, Jim_NewStringObj(interp, "usage", -1), 1, argv);
970 struct command_context *cmd_ctx = current_command_context(interp);
972 if (!command_can_run(cmd_ctx, c, Jim_GetString(argv[0], NULL)))
975 target_call_timer_callbacks_now();
978 * Black magic of overridden current target:
979 * If the command we are going to handle has a target prefix,
980 * override the current target temporarily for the time
981 * of processing the command.
982 * current_target_override is used also for event handlers
983 * therefore we prevent touching it if command has no prefix.
984 * Previous override is saved and restored back to ensure
985 * correct work when jim_command_dispatch() is re-entered.
987 struct target *saved_target_override = cmd_ctx->current_target_override;
988 if (c->jim_override_target)
989 cmd_ctx->current_target_override = c->jim_override_target;
991 int retval = exec_command(interp, cmd_ctx, c, argc, argv);
993 if (c->jim_override_target)
994 cmd_ctx->current_target_override = saved_target_override;
999 static int jim_command_mode(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
1001 struct command_context *cmd_ctx = current_command_context(interp);
1002 enum command_mode mode;
1005 char *full_name = alloc_concatenate_strings(argc - 1, argv + 1);
1008 Jim_Obj *s = Jim_NewStringObj(interp, full_name, -1);
1009 Jim_IncrRefCount(s);
1010 Jim_Cmd *cmd = Jim_GetCommand(interp, s, JIM_NONE);
1011 Jim_DecrRefCount(interp, s);
1013 if (!cmd || !(jimcmd_is_proc(cmd) || jimcmd_is_ocd_command(cmd))) {
1014 Jim_SetResultString(interp, "unknown", -1);
1018 if (jimcmd_is_proc(cmd)) {
1022 struct command *c = jimcmd_privdata(cmd);
1027 mode = cmd_ctx->mode;
1029 const char *mode_str;
1034 case COMMAND_CONFIG:
1035 mode_str = "config";
1041 mode_str = "unknown";
1044 Jim_SetResultString(interp, mode_str, -1);
1048 int help_del_all_commands(struct command_context *cmd_ctx)
1050 struct help_entry *curr, *n;
1052 list_for_each_entry_safe(curr, n, cmd_ctx->help_list, lh) {
1053 list_del(&curr->lh);
1054 free(curr->cmd_name);
1062 static int help_del_command(struct command_context *cmd_ctx, const char *cmd_name)
1064 struct help_entry *curr;
1066 list_for_each_entry(curr, cmd_ctx->help_list, lh) {
1067 if (!strcmp(cmd_name, curr->cmd_name)) {
1068 list_del(&curr->lh);
1069 free(curr->cmd_name);
1080 static int help_add_command(struct command_context *cmd_ctx,
1081 const char *cmd_name, const char *help_text, const char *usage_text)
1083 int cmp = -1; /* add after curr */
1084 struct help_entry *curr;
1086 list_for_each_entry_reverse(curr, cmd_ctx->help_list, lh) {
1087 cmp = strcmp(cmd_name, curr->cmd_name);
1092 struct help_entry *entry;
1094 entry = calloc(1, sizeof(*entry));
1096 LOG_ERROR("Out of memory");
1099 entry->cmd_name = strdup(cmd_name);
1100 if (!entry->cmd_name) {
1101 LOG_ERROR("Out of memory");
1105 list_add(&entry->lh, &curr->lh);
1111 char *text = strdup(help_text);
1113 LOG_ERROR("Out of memory");
1121 char *text = strdup(usage_text);
1123 LOG_ERROR("Out of memory");
1127 entry->usage = text;
1133 COMMAND_HANDLER(handle_help_add_command)
1136 return ERROR_COMMAND_SYNTAX_ERROR;
1138 const char *help = !strcmp(CMD_NAME, "add_help_text") ? CMD_ARGV[1] : NULL;
1139 const char *usage = !strcmp(CMD_NAME, "add_usage_text") ? CMD_ARGV[1] : NULL;
1140 if (!help && !usage) {
1141 LOG_ERROR("command name '%s' is unknown", CMD_NAME);
1142 return ERROR_COMMAND_SYNTAX_ERROR;
1144 const char *cmd_name = CMD_ARGV[0];
1145 return help_add_command(CMD_CTX, cmd_name, help, usage);
1148 /* sleep command sleeps for <n> milliseconds
1149 * this is useful in target startup scripts
1151 COMMAND_HANDLER(handle_sleep_command)
1154 if (CMD_ARGC == 2) {
1155 if (strcmp(CMD_ARGV[1], "busy") == 0)
1158 return ERROR_COMMAND_SYNTAX_ERROR;
1159 } else if (CMD_ARGC < 1 || CMD_ARGC > 2)
1160 return ERROR_COMMAND_SYNTAX_ERROR;
1162 unsigned long duration = 0;
1163 int retval = parse_ulong(CMD_ARGV[0], &duration);
1164 if (ERROR_OK != retval)
1168 int64_t then = timeval_ms();
1169 while (timeval_ms() - then < (int64_t)duration) {
1170 target_call_timer_callbacks_now();
1174 busy_sleep(duration);
1179 static const struct command_registration command_subcommand_handlers[] = {
1182 .mode = COMMAND_ANY,
1183 .jim_handler = jim_command_mode,
1184 .usage = "[command_name ...]",
1185 .help = "Returns the command modes allowed by a command: "
1186 "'any', 'config', or 'exec'. If no command is "
1187 "specified, returns the current command mode. "
1188 "Returns 'unknown' if an unknown command is given. "
1189 "Command can be multiple tokens.",
1191 COMMAND_REGISTRATION_DONE
1194 static const struct command_registration command_builtin_handlers[] = {
1197 .mode = COMMAND_ANY,
1198 .jim_handler = jim_find,
1199 .help = "find full path to file",
1204 .mode = COMMAND_ANY,
1205 .jim_handler = jim_capture,
1206 .help = "Capture progress output and return as tcl return value. If the "
1207 "progress output was empty, return tcl return value.",
1212 .handler = jim_echo,
1213 .mode = COMMAND_ANY,
1214 .help = "Logs a message at \"user\" priority. "
1215 "Output message to stdout. "
1216 "Option \"-n\" suppresses trailing newline",
1217 .usage = "[-n] string",
1220 .name = "add_help_text",
1221 .handler = handle_help_add_command,
1222 .mode = COMMAND_ANY,
1223 .help = "Add new command help text; "
1224 "Command can be multiple tokens.",
1225 .usage = "command_name helptext_string",
1228 .name = "add_usage_text",
1229 .handler = handle_help_add_command,
1230 .mode = COMMAND_ANY,
1231 .help = "Add new command usage text; "
1232 "command can be multiple tokens.",
1233 .usage = "command_name usage_string",
1237 .handler = handle_sleep_command,
1238 .mode = COMMAND_ANY,
1239 .help = "Sleep for specified number of milliseconds. "
1240 "\"busy\" will busy wait instead (avoid this).",
1241 .usage = "milliseconds ['busy']",
1245 .handler = handle_help_command,
1246 .mode = COMMAND_ANY,
1247 .help = "Show full command help; "
1248 "command can be multiple tokens.",
1249 .usage = "[command_name]",
1253 .handler = handle_help_command,
1254 .mode = COMMAND_ANY,
1255 .help = "Show basic command usage; "
1256 "command can be multiple tokens.",
1257 .usage = "[command_name]",
1261 .mode = COMMAND_ANY,
1262 .help = "core command group (introspection)",
1263 .chain = command_subcommand_handlers,
1266 COMMAND_REGISTRATION_DONE
1269 struct command_context *command_init(const char *startup_tcl, Jim_Interp *interp)
1271 struct command_context *context = calloc(1, sizeof(struct command_context));
1274 context->mode = COMMAND_EXEC;
1276 /* context can be duplicated. Put list head on separate mem-chunk to keep list consistent */
1277 context->help_list = malloc(sizeof(*context->help_list));
1278 INIT_LIST_HEAD(context->help_list);
1280 /* Create a jim interpreter if we were not handed one */
1281 if (interp == NULL) {
1282 /* Create an interpreter */
1283 interp = Jim_CreateInterp();
1284 /* Add all the Jim core commands */
1285 Jim_RegisterCoreCommands(interp);
1286 Jim_InitStaticExtensions(interp);
1289 context->interp = interp;
1291 /* Stick to lowercase for HostOS strings. */
1292 #if defined(_MSC_VER)
1293 /* WinXX - is generic, the forward
1294 * looking problem is this:
1296 * "win32" or "win64"
1298 * "winxx" is generic.
1301 #elif defined(__linux__)
1303 #elif defined(__APPLE__) || defined(__DARWIN__)
1305 #elif defined(__CYGWIN__)
1307 #elif defined(__MINGW32__)
1309 #elif defined(__ECOS)
1311 #elif defined(__FreeBSD__)
1313 #elif defined(__NetBSD__)
1315 #elif defined(__OpenBSD__)
1318 #warning "Unrecognized host OS..."
1321 Jim_SetGlobalVariableStr(interp, "ocd_HOSTOS",
1322 Jim_NewStringObj(interp, HostOs, strlen(HostOs)));
1324 register_commands(context, NULL, command_builtin_handlers);
1326 Jim_SetAssocData(interp, "context", NULL, context);
1327 if (Jim_Eval_Named(interp, startup_tcl, "embedded:startup.tcl", 1) == JIM_ERR) {
1328 LOG_ERROR("Failed to run startup.tcl (embedded into OpenOCD)");
1329 Jim_MakeErrorMessage(interp);
1330 LOG_USER_N("%s", Jim_GetString(Jim_GetResult(interp), NULL));
1333 Jim_DeleteAssocData(interp, "context");
1338 void command_exit(struct command_context *context)
1343 Jim_FreeInterp(context->interp);
1344 free(context->help_list);
1345 command_done(context);
1348 int command_context_mode(struct command_context *cmd_ctx, enum command_mode mode)
1351 return ERROR_COMMAND_SYNTAX_ERROR;
1353 cmd_ctx->mode = mode;
1357 void process_jim_events(struct command_context *cmd_ctx)
1359 static int recursion;
1364 Jim_ProcessEvents(cmd_ctx->interp, JIM_ALL_EVENTS | JIM_DONT_WAIT);
1368 #define DEFINE_PARSE_NUM_TYPE(name, type, func, min, max) \
1369 int parse ## name(const char *str, type * ul) \
1372 LOG_ERROR("Invalid command argument"); \
1373 return ERROR_COMMAND_ARGUMENT_INVALID; \
1377 *ul = func(str, &end, 0); \
1379 LOG_ERROR("Invalid command argument"); \
1380 return ERROR_COMMAND_ARGUMENT_INVALID; \
1382 if ((max == *ul) && (ERANGE == errno)) { \
1383 LOG_ERROR("Argument overflow"); \
1384 return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
1386 if (min && (min == *ul) && (ERANGE == errno)) { \
1387 LOG_ERROR("Argument underflow"); \
1388 return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
1392 DEFINE_PARSE_NUM_TYPE(_ulong, unsigned long, strtoul, 0, ULONG_MAX)
1393 DEFINE_PARSE_NUM_TYPE(_ullong, unsigned long long, strtoull, 0, ULLONG_MAX)
1394 DEFINE_PARSE_NUM_TYPE(_long, long, strtol, LONG_MIN, LONG_MAX)
1395 DEFINE_PARSE_NUM_TYPE(_llong, long long, strtoll, LLONG_MIN, LLONG_MAX)
1397 #define DEFINE_PARSE_WRAPPER(name, type, min, max, functype, funcname) \
1398 int parse ## name(const char *str, type * ul) \
1401 int retval = parse ## funcname(str, &n); \
1402 if (ERROR_OK != retval) \
1405 return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
1407 return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
1412 #define DEFINE_PARSE_ULONGLONG(name, type, min, max) \
1413 DEFINE_PARSE_WRAPPER(name, type, min, max, unsigned long long, _ullong)
1414 DEFINE_PARSE_ULONGLONG(_uint, unsigned, 0, UINT_MAX)
1415 DEFINE_PARSE_ULONGLONG(_u64, uint64_t, 0, UINT64_MAX)
1416 DEFINE_PARSE_ULONGLONG(_u32, uint32_t, 0, UINT32_MAX)
1417 DEFINE_PARSE_ULONGLONG(_u16, uint16_t, 0, UINT16_MAX)
1418 DEFINE_PARSE_ULONGLONG(_u8, uint8_t, 0, UINT8_MAX)
1420 DEFINE_PARSE_ULONGLONG(_target_addr, target_addr_t, 0, TARGET_ADDR_MAX)
1422 #define DEFINE_PARSE_LONGLONG(name, type, min, max) \
1423 DEFINE_PARSE_WRAPPER(name, type, min, max, long long, _llong)
1424 DEFINE_PARSE_LONGLONG(_int, int, n < INT_MIN, INT_MAX)
1425 DEFINE_PARSE_LONGLONG(_s64, int64_t, n < INT64_MIN, INT64_MAX)
1426 DEFINE_PARSE_LONGLONG(_s32, int32_t, n < INT32_MIN, INT32_MAX)
1427 DEFINE_PARSE_LONGLONG(_s16, int16_t, n < INT16_MIN, INT16_MAX)
1428 DEFINE_PARSE_LONGLONG(_s8, int8_t, n < INT8_MIN, INT8_MAX)
1430 static int command_parse_bool(const char *in, bool *out,
1431 const char *on, const char *off)
1433 if (strcasecmp(in, on) == 0)
1435 else if (strcasecmp(in, off) == 0)
1438 return ERROR_COMMAND_SYNTAX_ERROR;
1442 int command_parse_bool_arg(const char *in, bool *out)
1444 if (command_parse_bool(in, out, "on", "off") == ERROR_OK)
1446 if (command_parse_bool(in, out, "enable", "disable") == ERROR_OK)
1448 if (command_parse_bool(in, out, "true", "false") == ERROR_OK)
1450 if (command_parse_bool(in, out, "yes", "no") == ERROR_OK)
1452 if (command_parse_bool(in, out, "1", "0") == ERROR_OK)
1454 return ERROR_COMMAND_SYNTAX_ERROR;
1457 COMMAND_HELPER(handle_command_parse_bool, bool *out, const char *label)
1461 const char *in = CMD_ARGV[0];
1462 if (command_parse_bool_arg(in, out) != ERROR_OK) {
1463 LOG_ERROR("%s: argument '%s' is not valid", CMD_NAME, in);
1464 return ERROR_COMMAND_SYNTAX_ERROR;
1469 LOG_INFO("%s is %s", label, *out ? "enabled" : "disabled");
1472 return ERROR_COMMAND_SYNTAX_ERROR;