jtag/drivers/ftdi: Use correct command error
[openocd.git] / src / helper / command.c
blobef50ab5bd0efcb2382298e7561e49e94f229f994
1 // SPDX-License-Identifier: GPL-2.0-or-later
3 /***************************************************************************
4 * Copyright (C) 2005 by Dominic Rath *
5 * Dominic.Rath@gmx.de *
6 * *
7 * Copyright (C) 2007,2008 Øyvind Harboe *
8 * oyvind.harboe@zylin.com *
9 * *
10 * Copyright (C) 2008, Duane Ellis *
11 * openocd@duaneeellis.com *
12 * *
13 * part of this file is taken from libcli (libcli.sourceforge.net) *
14 * Copyright (C) David Parrish (david@dparrish.com) *
15 ***************************************************************************/
17 #ifdef HAVE_CONFIG_H
18 #include "config.h"
19 #endif
21 /* @todo the inclusion of target.h here is a layering violation */
22 #include <jtag/jtag.h>
23 #include <target/target.h>
24 #include "command.h"
25 #include "configuration.h"
26 #include "log.h"
27 #include "time_support.h"
28 #include "jim-eventloop.h"
30 /* nice short description of source file */
31 #define __THIS__FILE__ "command.c"
33 struct log_capture_state {
34 Jim_Interp *interp;
35 Jim_Obj *output;
38 static int unregister_command(struct command_context *context,
39 const char *cmd_prefix, const char *name);
40 static int jim_command_dispatch(Jim_Interp *interp, int argc, Jim_Obj * const *argv);
41 static int help_add_command(struct command_context *cmd_ctx,
42 const char *cmd_name, const char *help_text, const char *usage_text);
43 static int help_del_command(struct command_context *cmd_ctx, const char *cmd_name);
45 /* set of functions to wrap jimtcl internal data */
46 static inline bool jimcmd_is_proc(Jim_Cmd *cmd)
48 return cmd->isproc;
51 bool jimcmd_is_oocd_command(Jim_Cmd *cmd)
53 return !cmd->isproc && cmd->u.native.cmdProc == jim_command_dispatch;
56 void *jimcmd_privdata(Jim_Cmd *cmd)
58 return cmd->isproc ? NULL : cmd->u.native.privData;
61 static void tcl_output(void *privData, const char *file, unsigned line,
62 const char *function, const char *string)
64 struct log_capture_state *state = privData;
65 Jim_AppendString(state->interp, state->output, string, strlen(string));
68 static struct log_capture_state *command_log_capture_start(Jim_Interp *interp)
70 /* capture log output and return it. A garbage collect can
71 * happen, so we need a reference count to this object */
72 Jim_Obj *jim_output = Jim_NewStringObj(interp, "", 0);
73 if (!jim_output)
74 return NULL;
76 Jim_IncrRefCount(jim_output);
78 struct log_capture_state *state = malloc(sizeof(*state));
79 if (!state) {
80 LOG_ERROR("Out of memory");
81 Jim_DecrRefCount(interp, jim_output);
82 return NULL;
85 state->interp = interp;
86 state->output = jim_output;
88 log_add_callback(tcl_output, state);
90 return state;
93 /* Classic openocd commands provide progress output which we
94 * will capture and return as a Tcl return value.
96 * However, if a non-openocd command has been invoked, then it
97 * makes sense to return the tcl return value from that command.
99 * The tcl return value is empty for openocd commands that provide
100 * progress output.
102 * For other commands, we prepend the logs to the tcl return value.
104 static void command_log_capture_finish(struct log_capture_state *state)
106 if (!state)
107 return;
109 log_remove_callback(tcl_output, state);
111 int loglen;
112 const char *log_result = Jim_GetString(state->output, &loglen);
113 int reslen;
114 const char *cmd_result = Jim_GetString(Jim_GetResult(state->interp), &reslen);
116 // Just in case the log doesn't end with a newline, we add it
117 if (loglen != 0 && reslen != 0 && log_result[loglen - 1] != '\n')
118 Jim_AppendString(state->interp, state->output, "\n", 1);
120 Jim_AppendString(state->interp, state->output, cmd_result, reslen);
122 Jim_SetResult(state->interp, state->output);
123 Jim_DecrRefCount(state->interp, state->output);
125 free(state);
128 static int command_retval_set(Jim_Interp *interp, int retval)
130 int *return_retval = Jim_GetAssocData(interp, "retval");
131 if (return_retval)
132 *return_retval = retval;
134 return (retval == ERROR_OK) ? JIM_OK : retval;
137 extern struct command_context *global_cmd_ctx;
139 /* dump a single line to the log for the command.
140 * Do nothing in case we are not at debug level 3 */
141 static void script_debug(Jim_Interp *interp, unsigned int argc, Jim_Obj * const *argv)
143 if (debug_level < LOG_LVL_DEBUG)
144 return;
146 char *dbg = alloc_printf("command -");
147 for (unsigned i = 0; i < argc; i++) {
148 int len;
149 const char *w = Jim_GetString(argv[i], &len);
150 char *t = alloc_printf("%s %s", dbg, w);
151 free(dbg);
152 dbg = t;
154 LOG_DEBUG("%s", dbg);
155 free(dbg);
158 static void script_command_args_free(char **words, unsigned nwords)
160 for (unsigned i = 0; i < nwords; i++)
161 free(words[i]);
162 free(words);
165 static char **script_command_args_alloc(
166 unsigned argc, Jim_Obj * const *argv, unsigned *nwords)
168 char **words = malloc(argc * sizeof(char *));
169 if (!words)
170 return NULL;
172 unsigned i;
173 for (i = 0; i < argc; i++) {
174 int len;
175 const char *w = Jim_GetString(argv[i], &len);
176 words[i] = strdup(w);
177 if (!words[i]) {
178 script_command_args_free(words, i);
179 return NULL;
182 *nwords = i;
183 return words;
186 struct command_context *current_command_context(Jim_Interp *interp)
188 /* grab the command context from the associated data */
189 struct command_context *cmd_ctx = Jim_GetAssocData(interp, "context");
190 if (!cmd_ctx) {
191 /* Tcl can invoke commands directly instead of via command_run_line(). This would
192 * happen when the Jim Tcl interpreter is provided by eCos or if we are running
193 * commands in a startup script.
195 * A telnet or gdb server would provide a non-default command context to
196 * handle piping of error output, have a separate current target, etc.
198 cmd_ctx = global_cmd_ctx;
200 return cmd_ctx;
204 * Find a openocd command from fullname.
205 * @returns Returns the named command if it is registred in interp.
206 * Returns NULL otherwise.
208 static struct command *command_find_from_name(Jim_Interp *interp, const char *name)
210 if (!name)
211 return NULL;
213 Jim_Obj *jim_name = Jim_NewStringObj(interp, name, -1);
214 Jim_IncrRefCount(jim_name);
215 Jim_Cmd *cmd = Jim_GetCommand(interp, jim_name, JIM_NONE);
216 Jim_DecrRefCount(interp, jim_name);
217 if (!cmd || jimcmd_is_proc(cmd) || !jimcmd_is_oocd_command(cmd))
218 return NULL;
220 return jimcmd_privdata(cmd);
223 static struct command *command_new(struct command_context *cmd_ctx,
224 const char *full_name, const struct command_registration *cr)
226 assert(cr->name);
229 * If it is a non-jim command with no .usage specified,
230 * log an error.
232 * strlen(.usage) == 0 means that the command takes no
233 * arguments.
235 if (!cr->jim_handler && !cr->usage)
236 LOG_ERROR("BUG: command '%s' does not have the "
237 "'.usage' field filled out",
238 full_name);
240 struct command *c = calloc(1, sizeof(struct command));
241 if (!c)
242 return NULL;
244 c->name = strdup(cr->name);
245 if (!c->name) {
246 free(c);
247 return NULL;
250 c->handler = cr->handler;
251 c->jim_handler = cr->jim_handler;
252 c->mode = cr->mode;
254 if (cr->help || cr->usage)
255 help_add_command(cmd_ctx, full_name, cr->help, cr->usage);
257 return c;
260 static void command_free(struct Jim_Interp *interp, void *priv)
262 struct command *c = priv;
264 free(c->name);
265 free(c);
268 static struct command *register_command(struct command_context *context,
269 const char *cmd_prefix, const struct command_registration *cr)
271 char *full_name;
273 if (!context || !cr->name)
274 return NULL;
276 if (cmd_prefix)
277 full_name = alloc_printf("%s %s", cmd_prefix, cr->name);
278 else
279 full_name = strdup(cr->name);
280 if (!full_name)
281 return NULL;
283 struct command *c = command_find_from_name(context->interp, full_name);
284 if (c) {
285 /* TODO: originally we treated attempting to register a cmd twice as an error
286 * Sometimes we need this behaviour, such as with flash banks.
287 * http://www.mail-archive.com/openocd-development@lists.berlios.de/msg11152.html */
288 LOG_DEBUG("command '%s' is already registered", full_name);
289 free(full_name);
290 return c;
293 c = command_new(context, full_name, cr);
294 if (!c) {
295 free(full_name);
296 return NULL;
299 if (false) /* too noisy with debug_level 3 */
300 LOG_DEBUG("registering '%s'...", full_name);
301 int retval = Jim_CreateCommand(context->interp, full_name,
302 jim_command_dispatch, c, command_free);
303 if (retval != JIM_OK) {
304 command_run_linef(context, "del_help_text {%s}", full_name);
305 command_run_linef(context, "del_usage_text {%s}", full_name);
306 free(c);
307 free(full_name);
308 return NULL;
311 free(full_name);
312 return c;
315 int __register_commands(struct command_context *cmd_ctx, const char *cmd_prefix,
316 const struct command_registration *cmds, void *data,
317 struct target *override_target)
319 int retval = ERROR_OK;
320 unsigned i;
321 for (i = 0; cmds[i].name || cmds[i].chain; i++) {
322 const struct command_registration *cr = cmds + i;
324 struct command *c = NULL;
325 if (cr->name) {
326 c = register_command(cmd_ctx, cmd_prefix, cr);
327 if (!c) {
328 retval = ERROR_FAIL;
329 break;
331 c->jim_handler_data = data;
332 c->jim_override_target = override_target;
334 if (cr->chain) {
335 if (cr->name) {
336 if (cmd_prefix) {
337 char *new_prefix = alloc_printf("%s %s", cmd_prefix, cr->name);
338 if (!new_prefix) {
339 retval = ERROR_FAIL;
340 break;
342 retval = __register_commands(cmd_ctx, new_prefix, cr->chain, data, override_target);
343 free(new_prefix);
344 } else {
345 retval = __register_commands(cmd_ctx, cr->name, cr->chain, data, override_target);
347 } else {
348 retval = __register_commands(cmd_ctx, cmd_prefix, cr->chain, data, override_target);
350 if (retval != ERROR_OK)
351 break;
354 if (retval != ERROR_OK) {
355 for (unsigned j = 0; j < i; j++)
356 unregister_command(cmd_ctx, cmd_prefix, cmds[j].name);
358 return retval;
361 static __attribute__ ((format (PRINTF_ATTRIBUTE_FORMAT, 2, 3)))
362 int unregister_commands_match(struct command_context *cmd_ctx, const char *format, ...)
364 Jim_Interp *interp = cmd_ctx->interp;
365 va_list ap;
367 va_start(ap, format);
368 char *query = alloc_vprintf(format, ap);
369 va_end(ap);
370 if (!query)
371 return ERROR_FAIL;
373 char *query_cmd = alloc_printf("info commands {%s}", query);
374 free(query);
375 if (!query_cmd)
376 return ERROR_FAIL;
378 int retval = Jim_EvalSource(interp, __THIS__FILE__, __LINE__, query_cmd);
379 free(query_cmd);
380 if (retval != JIM_OK)
381 return ERROR_FAIL;
383 Jim_Obj *list = Jim_GetResult(interp);
384 Jim_IncrRefCount(list);
386 int len = Jim_ListLength(interp, list);
387 for (int i = 0; i < len; i++) {
388 Jim_Obj *elem = Jim_ListGetIndex(interp, list, i);
389 Jim_IncrRefCount(elem);
391 const char *name = Jim_GetString(elem, NULL);
392 struct command *c = command_find_from_name(interp, name);
393 if (!c) {
394 /* not openocd command */
395 Jim_DecrRefCount(interp, elem);
396 continue;
398 if (false) /* too noisy with debug_level 3 */
399 LOG_DEBUG("delete command \"%s\"", name);
400 #if JIM_VERSION >= 80
401 Jim_DeleteCommand(interp, elem);
402 #else
403 Jim_DeleteCommand(interp, name);
404 #endif
406 help_del_command(cmd_ctx, name);
408 Jim_DecrRefCount(interp, elem);
411 Jim_DecrRefCount(interp, list);
412 return ERROR_OK;
415 int unregister_all_commands(struct command_context *context,
416 const char *cmd_prefix)
418 if (!context)
419 return ERROR_OK;
421 if (!cmd_prefix || !*cmd_prefix)
422 return unregister_commands_match(context, "*");
424 int retval = unregister_commands_match(context, "%s *", cmd_prefix);
425 if (retval != ERROR_OK)
426 return retval;
428 return unregister_commands_match(context, "%s", cmd_prefix);
431 static int unregister_command(struct command_context *context,
432 const char *cmd_prefix, const char *name)
434 if (!context || !name)
435 return ERROR_COMMAND_SYNTAX_ERROR;
437 if (!cmd_prefix || !*cmd_prefix)
438 return unregister_commands_match(context, "%s", name);
440 return unregister_commands_match(context, "%s %s", cmd_prefix, name);
443 void command_output_text(struct command_context *context, const char *data)
445 if (context && context->output_handler && data)
446 context->output_handler(context, data);
449 void command_print_sameline(struct command_invocation *cmd, const char *format, ...)
451 char *string;
453 va_list ap;
454 va_start(ap, format);
456 string = alloc_vprintf(format, ap);
457 if (string && cmd) {
458 /* we want this collected in the log + we also want to pick it up as a tcl return
459 * value.
461 * The latter bit isn't precisely neat, but will do for now.
463 Jim_AppendString(cmd->ctx->interp, cmd->output, string, -1);
464 /* We already printed it above
465 * command_output_text(context, string); */
466 free(string);
469 va_end(ap);
472 void command_print(struct command_invocation *cmd, const char *format, ...)
474 char *string;
476 va_list ap;
477 va_start(ap, format);
479 string = alloc_vprintf(format, ap);
480 if (string && cmd) {
481 strcat(string, "\n"); /* alloc_vprintf guaranteed the buffer to be at least one
482 *char longer */
483 /* we want this collected in the log + we also want to pick it up as a tcl return
484 * value.
486 * The latter bit isn't precisely neat, but will do for now.
488 Jim_AppendString(cmd->ctx->interp, cmd->output, string, -1);
489 /* We already printed it above
490 * command_output_text(context, string); */
491 free(string);
494 va_end(ap);
497 static bool command_can_run(struct command_context *cmd_ctx, struct command *c, const char *full_name)
499 if (c->mode == COMMAND_ANY || c->mode == cmd_ctx->mode)
500 return true;
502 /* Many commands may be run only before/after 'init' */
503 const char *when;
504 switch (c->mode) {
505 case COMMAND_CONFIG:
506 when = "before";
507 break;
508 case COMMAND_EXEC:
509 when = "after";
510 break;
511 /* handle the impossible with humor; it guarantees a bug report! */
512 default:
513 when = "if Cthulhu is summoned by";
514 break;
516 LOG_ERROR("The '%s' command must be used %s 'init'.",
517 full_name ? full_name : c->name, when);
518 return false;
521 static int run_command(struct command_context *context,
522 struct command *c, const char **words, unsigned num_words)
524 struct command_invocation cmd = {
525 .ctx = context,
526 .current = c,
527 .name = c->name,
528 .argc = num_words - 1,
529 .argv = words + 1,
532 cmd.output = Jim_NewEmptyStringObj(context->interp);
533 Jim_IncrRefCount(cmd.output);
535 int retval = c->handler(&cmd);
536 if (retval == ERROR_COMMAND_SYNTAX_ERROR) {
537 /* Print help for command */
538 command_run_linef(context, "usage %s", words[0]);
539 } else if (retval == ERROR_COMMAND_CLOSE_CONNECTION) {
540 /* just fall through for a shutdown request */
541 } else {
542 if (retval != ERROR_OK)
543 LOG_DEBUG("Command '%s' failed with error code %d",
544 words[0], retval);
546 * Use the command output as the Tcl result.
547 * Drop last '\n' to allow command output concatenation
548 * while keep using command_print() everywhere.
550 const char *output_txt = Jim_String(cmd.output);
551 int len = strlen(output_txt);
552 if (len && output_txt[len - 1] == '\n')
553 --len;
554 Jim_SetResultString(context->interp, output_txt, len);
556 Jim_DecrRefCount(context->interp, cmd.output);
558 return retval;
561 int command_run_line(struct command_context *context, char *line)
563 /* all the parent commands have been registered with the interpreter
564 * so, can just evaluate the line as a script and check for
565 * results
567 /* run the line thru a script engine */
568 int retval = ERROR_FAIL;
569 int retcode;
570 /* Beware! This code needs to be reentrant. It is also possible
571 * for OpenOCD commands to be invoked directly from Tcl. This would
572 * happen when the Jim Tcl interpreter is provided by eCos for
573 * instance.
575 struct target *saved_target_override = context->current_target_override;
576 context->current_target_override = NULL;
578 Jim_Interp *interp = context->interp;
579 struct command_context *old_context = Jim_GetAssocData(interp, "context");
580 Jim_DeleteAssocData(interp, "context");
581 retcode = Jim_SetAssocData(interp, "context", NULL, context);
582 if (retcode == JIM_OK) {
583 /* associated the return value */
584 Jim_DeleteAssocData(interp, "retval");
585 retcode = Jim_SetAssocData(interp, "retval", NULL, &retval);
586 if (retcode == JIM_OK) {
587 retcode = Jim_Eval_Named(interp, line, NULL, 0);
589 Jim_DeleteAssocData(interp, "retval");
591 Jim_DeleteAssocData(interp, "context");
592 int inner_retcode = Jim_SetAssocData(interp, "context", NULL, old_context);
593 if (retcode == JIM_OK)
594 retcode = inner_retcode;
596 context->current_target_override = saved_target_override;
597 if (retcode == JIM_OK) {
598 const char *result;
599 int reslen;
601 result = Jim_GetString(Jim_GetResult(interp), &reslen);
602 if (reslen > 0) {
603 command_output_text(context, result);
604 command_output_text(context, "\n");
606 retval = ERROR_OK;
607 } else if (retcode == JIM_EXIT) {
608 /* ignore.
609 * exit(Jim_GetExitCode(interp)); */
610 } else if (retcode == ERROR_COMMAND_CLOSE_CONNECTION) {
611 return retcode;
612 } else {
613 Jim_MakeErrorMessage(interp);
614 /* error is broadcast */
615 LOG_USER("%s", Jim_GetString(Jim_GetResult(interp), NULL));
617 if (retval == ERROR_OK) {
618 /* It wasn't a low level OpenOCD command that failed */
619 return ERROR_FAIL;
621 return retval;
624 return retval;
627 int command_run_linef(struct command_context *context, const char *format, ...)
629 int retval = ERROR_FAIL;
630 char *string;
631 va_list ap;
632 va_start(ap, format);
633 string = alloc_vprintf(format, ap);
634 if (string) {
635 retval = command_run_line(context, string);
636 free(string);
638 va_end(ap);
639 return retval;
642 void command_set_output_handler(struct command_context *context,
643 command_output_handler_t output_handler, void *priv)
645 context->output_handler = output_handler;
646 context->output_handler_priv = priv;
649 struct command_context *copy_command_context(struct command_context *context)
651 struct command_context *copy_context = malloc(sizeof(struct command_context));
653 *copy_context = *context;
655 return copy_context;
658 void command_done(struct command_context *cmd_ctx)
660 if (!cmd_ctx)
661 return;
663 free(cmd_ctx);
666 /* find full path to file */
667 COMMAND_HANDLER(handle_find)
669 if (CMD_ARGC != 1)
670 return ERROR_COMMAND_SYNTAX_ERROR;
672 char *full_path = find_file(CMD_ARGV[0]);
673 if (!full_path)
674 return ERROR_COMMAND_ARGUMENT_INVALID;
676 command_print(CMD, "%s", full_path);
677 free(full_path);
679 return ERROR_OK;
682 COMMAND_HANDLER(handle_echo)
684 if (CMD_ARGC == 2 && !strcmp(CMD_ARGV[0], "-n")) {
685 LOG_USER_N("%s", CMD_ARGV[1]);
686 return ERROR_OK;
689 if (CMD_ARGC != 1)
690 return ERROR_FAIL;
692 LOG_USER("%s", CMD_ARGV[0]);
693 return ERROR_OK;
696 /* Return both the progress output (LOG_INFO and higher)
697 * and the tcl return value of a command.
699 static int jim_capture(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
701 if (argc != 2)
702 return JIM_ERR;
704 struct log_capture_state *state = command_log_capture_start(interp);
706 /* disable polling during capture. This avoids capturing output
707 * from polling.
709 * This is necessary in order to avoid accidentally getting a non-empty
710 * string for tcl fn's.
712 bool save_poll_mask = jtag_poll_mask();
714 const char *str = Jim_GetString(argv[1], NULL);
715 int retcode = Jim_Eval_Named(interp, str, __THIS__FILE__, __LINE__);
717 jtag_poll_unmask(save_poll_mask);
719 command_log_capture_finish(state);
721 return retcode;
724 struct help_entry {
725 struct list_head lh;
726 char *cmd_name;
727 char *help;
728 char *usage;
731 static COMMAND_HELPER(command_help_show, struct help_entry *c,
732 bool show_help, const char *cmd_match);
734 static COMMAND_HELPER(command_help_show_list, bool show_help, const char *cmd_match)
736 struct help_entry *entry;
738 list_for_each_entry(entry, CMD_CTX->help_list, lh)
739 CALL_COMMAND_HANDLER(command_help_show, entry, show_help, cmd_match);
740 return ERROR_OK;
743 #define HELP_LINE_WIDTH(_n) (int)(76 - (2 * _n))
745 static void command_help_show_indent(unsigned n)
747 for (unsigned i = 0; i < n; i++)
748 LOG_USER_N(" ");
750 static void command_help_show_wrap(const char *str, unsigned n, unsigned n2)
752 const char *cp = str, *last = str;
753 while (*cp) {
754 const char *next = last;
755 do {
756 cp = next;
757 do {
758 next++;
759 } while (*next != ' ' && *next != '\t' && *next != '\0');
760 } while ((next - last < HELP_LINE_WIDTH(n)) && *next != '\0');
761 if (next - last < HELP_LINE_WIDTH(n))
762 cp = next;
763 command_help_show_indent(n);
764 LOG_USER("%.*s", (int)(cp - last), last);
765 last = cp + 1;
766 n = n2;
770 static COMMAND_HELPER(command_help_show, struct help_entry *c,
771 bool show_help, const char *cmd_match)
773 unsigned int n = 0;
774 for (const char *s = strchr(c->cmd_name, ' '); s; s = strchr(s + 1, ' '))
775 n++;
777 /* If the match string occurs anywhere, we print out
778 * stuff for this command. */
779 bool is_match = strstr(c->cmd_name, cmd_match) ||
780 (c->usage && strstr(c->usage, cmd_match)) ||
781 (c->help && strstr(c->help, cmd_match));
783 if (is_match) {
784 if (c->usage && strlen(c->usage) > 0) {
785 char *msg = alloc_printf("%s %s", c->cmd_name, c->usage);
786 command_help_show_wrap(msg, n, n + 5);
787 free(msg);
788 } else {
789 command_help_show_wrap(c->cmd_name, n, n + 5);
793 if (is_match && show_help) {
794 char *msg;
796 /* TODO: factorize jim_command_mode() to avoid running jim command here */
797 char *request = alloc_printf("command mode %s", c->cmd_name);
798 if (!request) {
799 LOG_ERROR("Out of memory");
800 return ERROR_FAIL;
802 int retval = Jim_Eval(CMD_CTX->interp, request);
803 free(request);
804 enum command_mode mode = COMMAND_UNKNOWN;
805 if (retval != JIM_ERR) {
806 const char *result = Jim_GetString(Jim_GetResult(CMD_CTX->interp), NULL);
807 if (!strcmp(result, "any"))
808 mode = COMMAND_ANY;
809 else if (!strcmp(result, "config"))
810 mode = COMMAND_CONFIG;
811 else if (!strcmp(result, "exec"))
812 mode = COMMAND_EXEC;
815 /* Normal commands are runtime-only; highlight exceptions */
816 if (mode != COMMAND_EXEC) {
817 const char *stage_msg = "";
819 switch (mode) {
820 case COMMAND_CONFIG:
821 stage_msg = " (configuration command)";
822 break;
823 case COMMAND_ANY:
824 stage_msg = " (command valid any time)";
825 break;
826 default:
827 stage_msg = " (?mode error?)";
828 break;
830 msg = alloc_printf("%s%s", c->help ? c->help : "", stage_msg);
831 } else
832 msg = alloc_printf("%s", c->help ? c->help : "");
834 if (msg) {
835 command_help_show_wrap(msg, n + 3, n + 3);
836 free(msg);
837 } else
838 return -ENOMEM;
841 return ERROR_OK;
844 COMMAND_HANDLER(handle_help_command)
846 bool full = strcmp(CMD_NAME, "help") == 0;
847 int retval;
848 char *cmd_match;
850 if (CMD_ARGC <= 0)
851 cmd_match = strdup("");
853 else {
854 cmd_match = strdup(CMD_ARGV[0]);
856 for (unsigned int i = 1; i < CMD_ARGC && cmd_match; ++i) {
857 char *prev = cmd_match;
858 cmd_match = alloc_printf("%s %s", prev, CMD_ARGV[i]);
859 free(prev);
863 if (!cmd_match) {
864 LOG_ERROR("unable to build search string");
865 return -ENOMEM;
867 retval = CALL_COMMAND_HANDLER(command_help_show_list, full, cmd_match);
869 free(cmd_match);
870 return retval;
873 static char *alloc_concatenate_strings(int argc, Jim_Obj * const *argv)
875 char *prev, *all;
876 int i;
878 assert(argc >= 1);
880 all = strdup(Jim_GetString(argv[0], NULL));
881 if (!all) {
882 LOG_ERROR("Out of memory");
883 return NULL;
886 for (i = 1; i < argc; ++i) {
887 prev = all;
888 all = alloc_printf("%s %s", all, Jim_GetString(argv[i], NULL));
889 free(prev);
890 if (!all) {
891 LOG_ERROR("Out of memory");
892 return NULL;
896 return all;
899 static int exec_command(Jim_Interp *interp, struct command_context *cmd_ctx,
900 struct command *c, int argc, Jim_Obj * const *argv)
902 if (c->jim_handler)
903 return c->jim_handler(interp, argc, argv);
905 /* use c->handler */
906 unsigned int nwords;
907 char **words = script_command_args_alloc(argc, argv, &nwords);
908 if (!words)
909 return JIM_ERR;
911 int retval = run_command(cmd_ctx, c, (const char **)words, nwords);
912 script_command_args_free(words, nwords);
913 return command_retval_set(interp, retval);
916 static int jim_command_dispatch(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
918 /* check subcommands */
919 if (argc > 1) {
920 char *s = alloc_printf("%s %s", Jim_GetString(argv[0], NULL), Jim_GetString(argv[1], NULL));
921 Jim_Obj *js = Jim_NewStringObj(interp, s, -1);
922 Jim_IncrRefCount(js);
923 free(s);
924 Jim_Cmd *cmd = Jim_GetCommand(interp, js, JIM_NONE);
925 if (cmd) {
926 int retval = Jim_EvalObjPrefix(interp, js, argc - 2, argv + 2);
927 Jim_DecrRefCount(interp, js);
928 return retval;
930 Jim_DecrRefCount(interp, js);
933 script_debug(interp, argc, argv);
935 struct command *c = jim_to_command(interp);
936 if (!c->jim_handler && !c->handler) {
937 Jim_EvalObjPrefix(interp, Jim_NewStringObj(interp, "usage", -1), 1, argv);
938 return JIM_ERR;
941 struct command_context *cmd_ctx = current_command_context(interp);
943 if (!command_can_run(cmd_ctx, c, Jim_GetString(argv[0], NULL)))
944 return JIM_ERR;
946 target_call_timer_callbacks();
949 * Black magic of overridden current target:
950 * If the command we are going to handle has a target prefix,
951 * override the current target temporarily for the time
952 * of processing the command.
953 * current_target_override is used also for event handlers
954 * therefore we prevent touching it if command has no prefix.
955 * Previous override is saved and restored back to ensure
956 * correct work when jim_command_dispatch() is re-entered.
958 struct target *saved_target_override = cmd_ctx->current_target_override;
959 if (c->jim_override_target)
960 cmd_ctx->current_target_override = c->jim_override_target;
962 int retval = exec_command(interp, cmd_ctx, c, argc, argv);
964 if (c->jim_override_target)
965 cmd_ctx->current_target_override = saved_target_override;
967 return retval;
970 static int jim_command_mode(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
972 struct command_context *cmd_ctx = current_command_context(interp);
973 enum command_mode mode;
975 if (argc > 1) {
976 char *full_name = alloc_concatenate_strings(argc - 1, argv + 1);
977 if (!full_name)
978 return JIM_ERR;
979 Jim_Obj *s = Jim_NewStringObj(interp, full_name, -1);
980 Jim_IncrRefCount(s);
981 Jim_Cmd *cmd = Jim_GetCommand(interp, s, JIM_NONE);
982 Jim_DecrRefCount(interp, s);
983 free(full_name);
984 if (!cmd || !(jimcmd_is_proc(cmd) || jimcmd_is_oocd_command(cmd))) {
985 Jim_SetResultString(interp, "unknown", -1);
986 return JIM_OK;
989 if (jimcmd_is_proc(cmd)) {
990 /* tcl proc */
991 mode = COMMAND_ANY;
992 } else {
993 struct command *c = jimcmd_privdata(cmd);
995 mode = c->mode;
997 } else
998 mode = cmd_ctx->mode;
1000 const char *mode_str;
1001 switch (mode) {
1002 case COMMAND_ANY:
1003 mode_str = "any";
1004 break;
1005 case COMMAND_CONFIG:
1006 mode_str = "config";
1007 break;
1008 case COMMAND_EXEC:
1009 mode_str = "exec";
1010 break;
1011 default:
1012 mode_str = "unknown";
1013 break;
1015 Jim_SetResultString(interp, mode_str, -1);
1016 return JIM_OK;
1019 int help_del_all_commands(struct command_context *cmd_ctx)
1021 struct help_entry *curr, *n;
1023 list_for_each_entry_safe(curr, n, cmd_ctx->help_list, lh) {
1024 list_del(&curr->lh);
1025 free(curr->cmd_name);
1026 free(curr->help);
1027 free(curr->usage);
1028 free(curr);
1030 return ERROR_OK;
1033 static int help_del_command(struct command_context *cmd_ctx, const char *cmd_name)
1035 struct help_entry *curr;
1037 list_for_each_entry(curr, cmd_ctx->help_list, lh) {
1038 if (!strcmp(cmd_name, curr->cmd_name)) {
1039 list_del(&curr->lh);
1040 free(curr->cmd_name);
1041 free(curr->help);
1042 free(curr->usage);
1043 free(curr);
1044 break;
1048 return ERROR_OK;
1051 static int help_add_command(struct command_context *cmd_ctx,
1052 const char *cmd_name, const char *help_text, const char *usage_text)
1054 int cmp = -1; /* add after curr */
1055 struct help_entry *curr;
1057 list_for_each_entry_reverse(curr, cmd_ctx->help_list, lh) {
1058 cmp = strcmp(cmd_name, curr->cmd_name);
1059 if (cmp >= 0)
1060 break;
1063 struct help_entry *entry;
1064 if (cmp) {
1065 entry = calloc(1, sizeof(*entry));
1066 if (!entry) {
1067 LOG_ERROR("Out of memory");
1068 return ERROR_FAIL;
1070 entry->cmd_name = strdup(cmd_name);
1071 if (!entry->cmd_name) {
1072 LOG_ERROR("Out of memory");
1073 free(entry);
1074 return ERROR_FAIL;
1076 list_add(&entry->lh, &curr->lh);
1077 } else {
1078 entry = curr;
1081 if (help_text) {
1082 char *text = strdup(help_text);
1083 if (!text) {
1084 LOG_ERROR("Out of memory");
1085 return ERROR_FAIL;
1087 free(entry->help);
1088 entry->help = text;
1091 if (usage_text) {
1092 char *text = strdup(usage_text);
1093 if (!text) {
1094 LOG_ERROR("Out of memory");
1095 return ERROR_FAIL;
1097 free(entry->usage);
1098 entry->usage = text;
1101 return ERROR_OK;
1104 COMMAND_HANDLER(handle_help_add_command)
1106 if (CMD_ARGC != 2)
1107 return ERROR_COMMAND_SYNTAX_ERROR;
1109 const char *help = !strcmp(CMD_NAME, "add_help_text") ? CMD_ARGV[1] : NULL;
1110 const char *usage = !strcmp(CMD_NAME, "add_usage_text") ? CMD_ARGV[1] : NULL;
1111 if (!help && !usage) {
1112 LOG_ERROR("command name '%s' is unknown", CMD_NAME);
1113 return ERROR_COMMAND_SYNTAX_ERROR;
1115 const char *cmd_name = CMD_ARGV[0];
1116 return help_add_command(CMD_CTX, cmd_name, help, usage);
1119 /* sleep command sleeps for <n> milliseconds
1120 * this is useful in target startup scripts
1122 COMMAND_HANDLER(handle_sleep_command)
1124 bool busy = false;
1125 if (CMD_ARGC == 2) {
1126 if (strcmp(CMD_ARGV[1], "busy") == 0)
1127 busy = true;
1128 else
1129 return ERROR_COMMAND_SYNTAX_ERROR;
1130 } else if (CMD_ARGC < 1 || CMD_ARGC > 2)
1131 return ERROR_COMMAND_SYNTAX_ERROR;
1133 unsigned long duration = 0;
1134 int retval = parse_ulong(CMD_ARGV[0], &duration);
1135 if (retval != ERROR_OK)
1136 return retval;
1138 if (!busy) {
1139 int64_t then = timeval_ms();
1140 while (timeval_ms() - then < (int64_t)duration) {
1141 target_call_timer_callbacks_now();
1142 keep_alive();
1143 usleep(1000);
1145 } else
1146 busy_sleep(duration);
1148 return ERROR_OK;
1151 static const struct command_registration command_subcommand_handlers[] = {
1153 .name = "mode",
1154 .mode = COMMAND_ANY,
1155 .jim_handler = jim_command_mode,
1156 .usage = "[command_name ...]",
1157 .help = "Returns the command modes allowed by a command: "
1158 "'any', 'config', or 'exec'. If no command is "
1159 "specified, returns the current command mode. "
1160 "Returns 'unknown' if an unknown command is given. "
1161 "Command can be multiple tokens.",
1163 COMMAND_REGISTRATION_DONE
1166 static const struct command_registration command_builtin_handlers[] = {
1168 .name = "ocd_find",
1169 .mode = COMMAND_ANY,
1170 .handler = handle_find,
1171 .help = "find full path to file",
1172 .usage = "file",
1175 .name = "capture",
1176 .mode = COMMAND_ANY,
1177 .jim_handler = jim_capture,
1178 .help = "Capture progress output and return as tcl return value. If the "
1179 "progress output was empty, return tcl return value.",
1180 .usage = "command",
1183 .name = "echo",
1184 .handler = handle_echo,
1185 .mode = COMMAND_ANY,
1186 .help = "Logs a message at \"user\" priority. "
1187 "Option \"-n\" suppresses trailing newline",
1188 .usage = "[-n] string",
1191 .name = "add_help_text",
1192 .handler = handle_help_add_command,
1193 .mode = COMMAND_ANY,
1194 .help = "Add new command help text; "
1195 "Command can be multiple tokens.",
1196 .usage = "command_name helptext_string",
1199 .name = "add_usage_text",
1200 .handler = handle_help_add_command,
1201 .mode = COMMAND_ANY,
1202 .help = "Add new command usage text; "
1203 "command can be multiple tokens.",
1204 .usage = "command_name usage_string",
1207 .name = "sleep",
1208 .handler = handle_sleep_command,
1209 .mode = COMMAND_ANY,
1210 .help = "Sleep for specified number of milliseconds. "
1211 "\"busy\" will busy wait instead (avoid this).",
1212 .usage = "milliseconds ['busy']",
1215 .name = "help",
1216 .handler = handle_help_command,
1217 .mode = COMMAND_ANY,
1218 .help = "Show full command help; "
1219 "command can be multiple tokens.",
1220 .usage = "[command_name]",
1223 .name = "usage",
1224 .handler = handle_help_command,
1225 .mode = COMMAND_ANY,
1226 .help = "Show basic command usage; "
1227 "command can be multiple tokens.",
1228 .usage = "[command_name]",
1231 .name = "command",
1232 .mode = COMMAND_ANY,
1233 .help = "core command group (introspection)",
1234 .chain = command_subcommand_handlers,
1235 .usage = "",
1237 COMMAND_REGISTRATION_DONE
1240 struct command_context *command_init(const char *startup_tcl, Jim_Interp *interp)
1242 struct command_context *context = calloc(1, sizeof(struct command_context));
1244 context->mode = COMMAND_EXEC;
1246 /* context can be duplicated. Put list head on separate mem-chunk to keep list consistent */
1247 context->help_list = malloc(sizeof(*context->help_list));
1248 INIT_LIST_HEAD(context->help_list);
1250 /* Create a jim interpreter if we were not handed one */
1251 if (!interp) {
1252 /* Create an interpreter */
1253 interp = Jim_CreateInterp();
1254 /* Add all the Jim core commands */
1255 Jim_RegisterCoreCommands(interp);
1256 Jim_InitStaticExtensions(interp);
1259 context->interp = interp;
1261 register_commands(context, NULL, command_builtin_handlers);
1263 Jim_SetAssocData(interp, "context", NULL, context);
1264 if (Jim_Eval_Named(interp, startup_tcl, "embedded:startup.tcl", 1) == JIM_ERR) {
1265 LOG_ERROR("Failed to run startup.tcl (embedded into OpenOCD)");
1266 Jim_MakeErrorMessage(interp);
1267 LOG_USER_N("%s", Jim_GetString(Jim_GetResult(interp), NULL));
1268 exit(-1);
1270 Jim_DeleteAssocData(interp, "context");
1272 return context;
1275 void command_exit(struct command_context *context)
1277 if (!context)
1278 return;
1280 Jim_FreeInterp(context->interp);
1281 free(context->help_list);
1282 command_done(context);
1285 int command_context_mode(struct command_context *cmd_ctx, enum command_mode mode)
1287 if (!cmd_ctx)
1288 return ERROR_COMMAND_SYNTAX_ERROR;
1290 cmd_ctx->mode = mode;
1291 return ERROR_OK;
1294 void process_jim_events(struct command_context *cmd_ctx)
1296 static int recursion;
1297 if (recursion)
1298 return;
1300 recursion++;
1301 Jim_ProcessEvents(cmd_ctx->interp, JIM_ALL_EVENTS | JIM_DONT_WAIT);
1302 recursion--;
1305 #define DEFINE_PARSE_NUM_TYPE(name, type, func, min, max) \
1306 int parse ## name(const char *str, type * ul) \
1308 if (!*str) { \
1309 LOG_ERROR("Invalid command argument"); \
1310 return ERROR_COMMAND_ARGUMENT_INVALID; \
1312 char *end; \
1313 errno = 0; \
1314 *ul = func(str, &end, 0); \
1315 if (*end) { \
1316 LOG_ERROR("Invalid command argument"); \
1317 return ERROR_COMMAND_ARGUMENT_INVALID; \
1319 if ((max == *ul) && (errno == ERANGE)) { \
1320 LOG_ERROR("Argument overflow"); \
1321 return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
1323 if (min && (min == *ul) && (errno == ERANGE)) { \
1324 LOG_ERROR("Argument underflow"); \
1325 return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
1327 return ERROR_OK; \
1329 DEFINE_PARSE_NUM_TYPE(_ulong, unsigned long, strtoul, 0, ULONG_MAX)
1330 DEFINE_PARSE_NUM_TYPE(_ullong, unsigned long long, strtoull, 0, ULLONG_MAX)
1331 DEFINE_PARSE_NUM_TYPE(_long, long, strtol, LONG_MIN, LONG_MAX)
1332 DEFINE_PARSE_NUM_TYPE(_llong, long long, strtoll, LLONG_MIN, LLONG_MAX)
1334 #define DEFINE_PARSE_WRAPPER(name, type, min, max, functype, funcname) \
1335 int parse ## name(const char *str, type * ul) \
1337 functype n; \
1338 int retval = parse ## funcname(str, &n); \
1339 if (retval != ERROR_OK) \
1340 return retval; \
1341 if (n > max) \
1342 return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
1343 if (min) \
1344 return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
1345 *ul = n; \
1346 return ERROR_OK; \
1349 #define DEFINE_PARSE_ULONGLONG(name, type, min, max) \
1350 DEFINE_PARSE_WRAPPER(name, type, min, max, unsigned long long, _ullong)
1351 DEFINE_PARSE_ULONGLONG(_uint, unsigned, 0, UINT_MAX)
1352 DEFINE_PARSE_ULONGLONG(_u64, uint64_t, 0, UINT64_MAX)
1353 DEFINE_PARSE_ULONGLONG(_u32, uint32_t, 0, UINT32_MAX)
1354 DEFINE_PARSE_ULONGLONG(_u16, uint16_t, 0, UINT16_MAX)
1355 DEFINE_PARSE_ULONGLONG(_u8, uint8_t, 0, UINT8_MAX)
1357 DEFINE_PARSE_ULONGLONG(_target_addr, target_addr_t, 0, TARGET_ADDR_MAX)
1359 #define DEFINE_PARSE_LONGLONG(name, type, min, max) \
1360 DEFINE_PARSE_WRAPPER(name, type, min, max, long long, _llong)
1361 DEFINE_PARSE_LONGLONG(_int, int, n < INT_MIN, INT_MAX)
1362 DEFINE_PARSE_LONGLONG(_s64, int64_t, n < INT64_MIN, INT64_MAX)
1363 DEFINE_PARSE_LONGLONG(_s32, int32_t, n < INT32_MIN, INT32_MAX)
1364 DEFINE_PARSE_LONGLONG(_s16, int16_t, n < INT16_MIN, INT16_MAX)
1365 DEFINE_PARSE_LONGLONG(_s8, int8_t, n < INT8_MIN, INT8_MAX)
1367 static int command_parse_bool(const char *in, bool *out,
1368 const char *on, const char *off)
1370 if (strcasecmp(in, on) == 0)
1371 *out = true;
1372 else if (strcasecmp(in, off) == 0)
1373 *out = false;
1374 else
1375 return ERROR_COMMAND_SYNTAX_ERROR;
1376 return ERROR_OK;
1379 int command_parse_bool_arg(const char *in, bool *out)
1381 if (command_parse_bool(in, out, "on", "off") == ERROR_OK)
1382 return ERROR_OK;
1383 if (command_parse_bool(in, out, "enable", "disable") == ERROR_OK)
1384 return ERROR_OK;
1385 if (command_parse_bool(in, out, "true", "false") == ERROR_OK)
1386 return ERROR_OK;
1387 if (command_parse_bool(in, out, "yes", "no") == ERROR_OK)
1388 return ERROR_OK;
1389 if (command_parse_bool(in, out, "1", "0") == ERROR_OK)
1390 return ERROR_OK;
1391 return ERROR_COMMAND_SYNTAX_ERROR;
1394 COMMAND_HELPER(handle_command_parse_bool, bool *out, const char *label)
1396 switch (CMD_ARGC) {
1397 case 1: {
1398 const char *in = CMD_ARGV[0];
1399 if (command_parse_bool_arg(in, out) != ERROR_OK) {
1400 LOG_ERROR("%s: argument '%s' is not valid", CMD_NAME, in);
1401 return ERROR_COMMAND_SYNTAX_ERROR;
1404 /* fallthrough */
1405 case 0:
1406 LOG_INFO("%s is %s", label, *out ? "enabled" : "disabled");
1407 break;
1408 default:
1409 return ERROR_COMMAND_SYNTAX_ERROR;
1411 return ERROR_OK;