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, write to the *
26 * Free Software Foundation, Inc., *
27 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
28 ***************************************************************************/
34 /* see Embedder-HOWTO.txt in Jim Tcl project hosted on BerliOS*/
38 // @todo the inclusion of target.h here is a layering violation
41 #include "configuration.h"
43 #include "time_support.h"
44 #include "jim-eventloop.h"
47 int fast_and_dangerous = 0;
48 Jim_Interp *interp = NULL;
50 int run_command(command_context_t *context, command_t *c, char *words[], int num_words);
52 static void tcl_output(void *privData, const char *file, int line, const char *function, const char *string)
54 Jim_Obj *tclOutput = (Jim_Obj *)privData;
56 Jim_AppendString(interp, tclOutput, string, strlen(string));
59 extern command_context_t *global_cmd_ctx;
61 void script_debug(Jim_Interp *interp, const char *name, int argc, Jim_Obj *const *argv)
65 LOG_DEBUG("command - %s", name);
66 for (i = 0; i < argc; i++) {
68 const char *w = Jim_GetString(argv[i], &len);
70 /* end of line comment? */
74 LOG_DEBUG("%s - argv[%d]=%s", name, i, w);
78 static int script_command(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
80 /* the private data is stashed in the interp structure */
82 command_context_t *context;
88 /* DANGER!!!! be careful what we invoke here, since interp->cmdPrivData might
89 * get overwritten by running other Jim commands! Treat it as an
90 * emphemeral global variable that is used in lieu of an argument
91 * to the fn and fish it out manually.
93 c = interp->cmdPrivData;
96 LOG_ERROR("BUG: interp->cmdPrivData == NULL");
99 target_call_timer_callbacks_now();
100 LOG_USER_N("%s", ""); /* Keep GDB connection alive*/
102 script_debug(interp, c->name, argc, argv);
104 words = malloc(sizeof(char *) * argc);
105 for (i = 0; i < argc; i++)
108 const char *w = Jim_GetString(argv[i], &len);
111 /* hit an end of line comment */
114 words[i] = strdup(w);
115 if (words[i] == NULL)
118 for (j = 0; j < i; j++)
126 /* grab the command context from the associated data */
127 context = Jim_GetAssocData(interp, "context");
130 /* Tcl can invoke commands directly instead of via command_run_line(). This would
131 * happen when the Jim Tcl interpreter is provided by eCos.
133 context = global_cmd_ctx;
136 /* capture log output and return it */
137 Jim_Obj *tclOutput = Jim_NewStringObj(interp, "", 0);
138 /* a garbage collect can happen, so we need a reference count to this object */
139 Jim_IncrRefCount(tclOutput);
141 log_add_callback(tcl_output, tclOutput);
143 retval = run_command(context, c, words, nwords);
145 log_remove_callback(tcl_output, tclOutput);
147 /* We dump output into this local variable */
148 Jim_SetResult(interp, tclOutput);
149 Jim_DecrRefCount(interp, tclOutput);
151 for (i = 0; i < nwords; i++)
155 int *return_retval = Jim_GetAssocData(interp, "retval");
156 if (return_retval != NULL)
158 *return_retval = retval;
161 return (retval == ERROR_OK)?JIM_OK:JIM_ERR;
164 /* nice short description of source file */
165 #define __THIS__FILE__ "command.c"
167 command_t* register_command(command_context_t *context, command_t *parent, char *name, int (*handler)(struct command_context_s *context, char* name, char** args, int argc), enum command_mode mode, char *help)
171 if (!context || !name)
174 c = malloc(sizeof(command_t));
176 c->name = strdup(name);
179 c->handler = handler;
185 /* place command in tree */
188 if (parent->children)
190 /* find last child */
191 for (p = parent->children; p && p->next; p = p->next);
197 parent->children = c;
202 if (context->commands)
204 /* find last command */
205 for (p = context->commands; p && p->next; p = p->next);
211 context->commands = c;
215 /* just a placeholder, no handler */
216 if (c->handler == NULL)
219 /* If this is a two level command, e.g. "flash banks", then the
220 * "unknown" proc in startup.tcl must redirect to this command.
222 * "flash banks" is translated by "unknown" to "flash_banks"
223 * if such a proc exists
225 /* Print help for command */
229 /* maximum of two levels :-) */
230 if (c->parent != NULL)
232 t1 = c->parent->name;
236 const char *full_name = alloc_printf("ocd_%s%s%s", t1, t2, t3);
237 Jim_CreateCommand(interp, full_name, script_command, c, NULL);
238 free((void *)full_name);
240 /* we now need to add an overrideable proc */
241 const char *override_name = alloc_printf("proc %s%s%s {args} {if {[catch {eval ocd_%s%s%s $args}]==0} {return \"\"} else { return -code error }", t1, t2, t3, t1, t2, t3);
242 Jim_Eval_Named(interp, override_name, __THIS__FILE__, __LINE__);
243 free((void *)override_name);
245 /* accumulate help text in Tcl helptext list. */
246 Jim_Obj *helptext = Jim_GetGlobalVariableStr(interp, "ocd_helptext", JIM_ERRMSG);
247 if (Jim_IsShared(helptext))
248 helptext = Jim_DuplicateObj(interp, helptext);
249 Jim_Obj *cmd_entry = Jim_NewListObj(interp, NULL, 0);
251 Jim_Obj *cmd_list = Jim_NewListObj(interp, NULL, 0);
253 /* maximum of two levels :-) */
254 if (c->parent != NULL)
256 Jim_ListAppendElement(interp, cmd_list, Jim_NewStringObj(interp, c->parent->name, -1));
258 Jim_ListAppendElement(interp, cmd_list, Jim_NewStringObj(interp, c->name, -1));
260 Jim_ListAppendElement(interp, cmd_entry, cmd_list);
261 Jim_ListAppendElement(interp, cmd_entry, Jim_NewStringObj(interp, help, -1));
262 Jim_ListAppendElement(interp, helptext, cmd_entry);
266 int unregister_all_commands(command_context_t *context)
273 while (NULL != context->commands)
275 c = context->commands;
277 while (NULL != c->children)
280 c->children = c->children->next;
287 context->commands = context->commands->next;
298 int unregister_command(command_context_t *context, char *name)
300 command_t *c, *p = NULL, *c2;
302 if ((!context) || (!name))
303 return ERROR_INVALID_ARGUMENTS;
306 c = context->commands;
310 if (strcmp(name, c->name) == 0)
319 /* first element in command list */
320 context->commands = c->next;
323 /* unregister children */
324 while (NULL != c->children)
327 c->children = c->children->next;
342 /* remember the last command for unlinking */
350 void command_output_text(command_context_t *context, const char *data)
352 if (context && context->output_handler && data) {
353 context->output_handler(context, data);
357 void command_print_sameline(command_context_t *context, const char *format, ...)
362 va_start(ap, format);
364 string = alloc_vprintf(format, ap);
367 /* we want this collected in the log + we also want to pick it up as a tcl return
370 * The latter bit isn't precisely neat, but will do for now.
372 LOG_USER_N("%s", string);
373 /* We already printed it above */
374 /* command_output_text(context, string); */
381 void command_print(command_context_t *context, const char *format, ...)
386 va_start(ap, format);
388 string = alloc_vprintf(format, ap);
391 strcat(string, "\n"); /* alloc_vprintf guaranteed the buffer to be at least one char longer */
392 /* we want this collected in the log + we also want to pick it up as a tcl return
395 * The latter bit isn't precisely neat, but will do for now.
397 LOG_USER_N("%s", string);
398 /* We already printed it above */
399 /* command_output_text(context, string); */
406 int run_command(command_context_t *context, command_t *c, char *words[], int num_words)
409 if (!((context->mode == COMMAND_CONFIG) || (c->mode == COMMAND_ANY) || (c->mode == context->mode)))
411 /* Config commands can not run after the config stage */
412 LOG_ERROR("Command '%s' only runs during configuration stage", c->name);
416 int retval = c->handler(context, c->name, words + start_word + 1, num_words - start_word - 1);
417 if (retval == ERROR_COMMAND_SYNTAX_ERROR)
419 /* Print help for command */
423 /* maximum of two levels :-) */
424 if (c->parent != NULL)
426 t1 = c->parent->name;
430 command_run_linef(context, "help {%s%s%s}", t1, t2, t3);
432 else if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
434 /* just fall through for a shutdown request */
436 else if (retval != ERROR_OK)
438 /* we do not print out an error message because the command *should*
439 * have printed out an error
441 LOG_DEBUG("Command failed with error code %d", retval);
447 int command_run_line(command_context_t *context, char *line)
449 /* all the parent commands have been registered with the interpreter
450 * so, can just evaluate the line as a script and check for
453 /* run the line thru a script engine */
454 int retval = ERROR_FAIL;
456 /* Beware! This code needs to be reentrant. It is also possible
457 * for OpenOCD commands to be invoked directly from Tcl. This would
458 * happen when the Jim Tcl interpreter is provided by eCos for
461 Jim_DeleteAssocData(interp, "context");
462 retcode = Jim_SetAssocData(interp, "context", NULL, context);
463 if (retcode == JIM_OK)
465 /* associated the return value */
466 Jim_DeleteAssocData(interp, "retval");
467 retcode = Jim_SetAssocData(interp, "retval", NULL, &retval);
468 if (retcode == JIM_OK)
470 retcode = Jim_Eval_Named(interp, line, __THIS__FILE__, __LINE__);
472 Jim_DeleteAssocData(interp, "retval");
474 Jim_DeleteAssocData(interp, "context");
476 if (retcode == JIM_ERR) {
477 if (retval != ERROR_COMMAND_CLOSE_CONNECTION)
479 /* We do not print the connection closed error message */
480 Jim_PrintErrorMessage(interp);
482 if (retval == ERROR_OK)
484 /* It wasn't a low level OpenOCD command that failed */
488 } else if (retcode == JIM_EXIT) {
490 /* exit(Jim_GetExitCode(interp)); */
495 result = Jim_GetString(Jim_GetResult(interp), &reslen);
500 for (i = 0; i < reslen; i += 256)
506 strncpy(buff, result + i, chunk);
508 LOG_USER_N("%s", buff);
510 LOG_USER_N("%s", "\n");
517 int command_run_linef(command_context_t *context, const char *format, ...)
519 int retval = ERROR_FAIL;
522 va_start(ap, format);
523 string = alloc_vprintf(format, ap);
526 retval = command_run_line(context, string);
532 void command_set_output_handler(command_context_t* context, int (*output_handler)(struct command_context_s *context, const char* line), void *priv)
534 context->output_handler = output_handler;
535 context->output_handler_priv = priv;
538 command_context_t* copy_command_context(command_context_t* context)
540 command_context_t* copy_context = malloc(sizeof(command_context_t));
542 *copy_context = *context;
547 int command_done(command_context_t *context)
555 /* find full path to file */
556 static int jim_find(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
560 const char *file = Jim_GetString(argv[1], NULL);
561 char *full_path = find_file(file);
562 if (full_path == NULL)
564 Jim_Obj *result = Jim_NewStringObj(interp, full_path, strlen(full_path));
567 Jim_SetResult(interp, result);
571 static int jim_echo(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
575 const char *str = Jim_GetString(argv[1], NULL);
580 static size_t openocd_jim_fwrite(const void *_ptr, size_t size, size_t n, void *cookie)
586 /* make it a char easier to read code */
590 if (ptr == NULL || interp == NULL || nbytes == 0) {
594 /* do we have to chunk it? */
595 if (ptr[nbytes] == 0)
597 /* no it is a C style string */
598 LOG_USER_N("%s", ptr);
601 /* GRR we must chunk - not null terminated */
611 memcpy(chunk, ptr, x);
615 LOG_USER_N("%s", chunk);
623 static size_t openocd_jim_fread(void *ptr, size_t size, size_t n, void *cookie)
625 /* TCL wants to read... tell him no */
629 static int openocd_jim_vfprintf(void *cookie, const char *fmt, va_list ap)
640 cp = alloc_vprintf(fmt, ap);
643 LOG_USER_N("%s", cp);
650 static int openocd_jim_fflush(void *cookie)
652 /* nothing to flush */
656 static char* openocd_jim_fgets(char *s, int size, void *cookie)
663 static int jim_capture(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
668 const char *str = Jim_GetString(argv[1], NULL);
670 /* capture log output and return it */
671 Jim_Obj *tclOutput = Jim_NewStringObj(interp, "", 0);
672 /* a garbage collect can happen, so we need a reference count to this object */
673 Jim_IncrRefCount(tclOutput);
675 log_add_callback(tcl_output, tclOutput);
677 retcode = Jim_Eval_Named(interp, str, __THIS__FILE__, __LINE__);
679 log_remove_callback(tcl_output, tclOutput);
681 /* We dump output into this local variable */
682 Jim_SetResult(interp, tclOutput);
683 Jim_DecrRefCount(interp, tclOutput);
688 /* sleep command sleeps for <n> miliseconds
689 * this is useful in target startup scripts
691 static int handle_sleep_command(struct command_context_s *cmd_ctx,
692 char *cmd, char **args, int argc)
697 if (strcmp(args[1], "busy") == 0)
700 return ERROR_COMMAND_SYNTAX_ERROR;
702 else if (argc < 1 || argc > 2)
703 return ERROR_COMMAND_SYNTAX_ERROR;
705 unsigned long duration = 0;
706 int retval = parse_ulong(args[0], &duration);
707 if (ERROR_OK != retval)
712 long long then = timeval_ms();
713 while (timeval_ms() - then < (long long)duration)
715 target_call_timer_callbacks_now();
720 busy_sleep(duration);
725 static int handle_fast_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
728 return ERROR_COMMAND_SYNTAX_ERROR;
730 fast_and_dangerous = strcmp("enable", args[0]) == 0;
736 command_context_t* command_init()
738 command_context_t* context = malloc(sizeof(command_context_t));
739 extern const char startup_tcl[];
742 context->mode = COMMAND_EXEC;
743 context->commands = NULL;
744 context->current_target = 0;
745 context->output_handler = NULL;
746 context->output_handler_priv = NULL;
750 /* Create an interpreter */
751 interp = Jim_CreateInterp();
752 /* Add all the Jim core commands */
753 Jim_RegisterCoreCommands(interp);
756 #if defined(_MSC_VER)
757 /* WinXX - is generic, the forward
758 * looking problem is this:
762 * "winxx" is generic.
765 #elif defined(__linux__)
767 #elif defined(__DARWIN__)
769 #elif defined(__CYGWIN__)
771 #elif defined(__MINGW32__)
774 #warn unrecognized host OS...
777 Jim_SetGlobalVariableStr(interp, "ocd_HOSTOS",
778 Jim_NewStringObj(interp, HostOs , strlen(HostOs)));
780 Jim_CreateCommand(interp, "ocd_find", jim_find, NULL, NULL);
781 Jim_CreateCommand(interp, "echo", jim_echo, NULL, NULL);
782 Jim_CreateCommand(interp, "capture", jim_capture, NULL, NULL);
784 /* Set Jim's STDIO */
785 interp->cookie_stdin = interp;
786 interp->cookie_stdout = interp;
787 interp->cookie_stderr = interp;
788 interp->cb_fwrite = openocd_jim_fwrite;
789 interp->cb_fread = openocd_jim_fread ;
790 interp->cb_vfprintf = openocd_jim_vfprintf;
791 interp->cb_fflush = openocd_jim_fflush;
792 interp->cb_fgets = openocd_jim_fgets;
795 Jim_EventLoopOnLoad(interp);
797 if (Jim_Eval_Named(interp, startup_tcl, "embedded:startup.tcl",1) == JIM_ERR)
799 LOG_ERROR("Failed to run startup.tcl (embedded into OpenOCD)");
800 Jim_PrintErrorMessage(interp);
804 register_command(context, NULL, "sleep",
805 handle_sleep_command, COMMAND_ANY,
806 "<n> [busy] - sleep for n milliseconds. "
807 "\"busy\" means busy wait");
808 register_command(context, NULL, "fast",
809 handle_fast_command, COMMAND_ANY,
810 "fast <enable/disable> - place at beginning of "
811 "config files. Sets defaults to fast and dangerous.");
816 int command_context_mode(command_context_t *cmd_ctx, enum command_mode mode)
819 return ERROR_INVALID_ARGUMENTS;
821 cmd_ctx->mode = mode;
825 void process_jim_events(void)
828 static int recursion = 0;
833 Jim_ProcessEvents (interp, JIM_ALL_EVENTS | JIM_DONT_WAIT);
839 void register_jim(struct command_context_s *cmd_ctx, const char *name, int (*cmd)(Jim_Interp *interp, int argc, Jim_Obj *const *argv), const char *help)
841 Jim_CreateCommand(interp, name, cmd, NULL, NULL);
843 /* FIX!!! it would be prettier to invoke add_help_text...
844 * accumulate help text in Tcl helptext list. */
845 Jim_Obj *helptext = Jim_GetGlobalVariableStr(interp, "ocd_helptext", JIM_ERRMSG);
846 if (Jim_IsShared(helptext))
847 helptext = Jim_DuplicateObj(interp, helptext);
849 Jim_Obj *cmd_entry = Jim_NewListObj(interp, NULL, 0);
851 Jim_Obj *cmd_list = Jim_NewListObj(interp, NULL, 0);
852 Jim_ListAppendElement(interp, cmd_list, Jim_NewStringObj(interp, name, -1));
854 Jim_ListAppendElement(interp, cmd_entry, cmd_list);
855 Jim_ListAppendElement(interp, cmd_entry, Jim_NewStringObj(interp, help, -1));
856 Jim_ListAppendElement(interp, helptext, cmd_entry);
859 /* return global variable long value or 0 upon failure */
860 long jim_global_long(const char *variable)
862 Jim_Obj *objPtr = Jim_GetGlobalVariableStr(interp, variable, JIM_ERRMSG);
864 if (Jim_GetLong(interp, objPtr, &t) == JIM_OK)
871 #define DEFINE_PARSE_NUM_TYPE(name, type, func, min, max) \
872 int parse##name(const char *str, type *ul) \
876 LOG_ERROR("Invalid command argument"); \
877 return ERROR_COMMAND_ARGUMENT_INVALID; \
880 *ul = func(str, &end, 0); \
883 LOG_ERROR("Invalid command argument"); \
884 return ERROR_COMMAND_ARGUMENT_INVALID; \
886 if ((max == *ul) && (ERANGE == errno)) \
888 LOG_ERROR("Argument overflow"); \
889 return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
891 if (min && (min == *ul) && (ERANGE == errno)) \
893 LOG_ERROR("Argument underflow"); \
894 return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
898 DEFINE_PARSE_NUM_TYPE(_ulong, unsigned long , strtoul, 0, ULONG_MAX)
899 DEFINE_PARSE_NUM_TYPE(_ullong, unsigned long long, strtoull, 0, ULLONG_MAX)
900 DEFINE_PARSE_NUM_TYPE(_long, long , strtol, LONG_MIN, LONG_MAX)
901 DEFINE_PARSE_NUM_TYPE(_llong, long long, strtoll, LLONG_MIN, LLONG_MAX)
903 #define DEFINE_PARSE_WRAPPER(name, type, min, max, functype, funcname) \
904 int parse##name(const char *str, type *ul) \
907 int retval = parse##funcname(str, &n); \
908 if (ERROR_OK != retval) \
911 return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
913 return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
918 #define DEFINE_PARSE_ULONG(name, type, min, max) \
919 DEFINE_PARSE_WRAPPER(name, type, min, max, unsigned long, _ulong)
920 DEFINE_PARSE_ULONG(_uint, unsigned, 0, UINT_MAX)
921 DEFINE_PARSE_ULONG(_u32, uint32_t, 0, UINT32_MAX)
922 DEFINE_PARSE_ULONG(_u16, uint16_t, 0, UINT16_MAX)
923 DEFINE_PARSE_ULONG(_u8, uint8_t, 0, UINT8_MAX)
925 #define DEFINE_PARSE_LONG(name, type, min, max) \
926 DEFINE_PARSE_WRAPPER(name, type, min, max, long, _long)
927 DEFINE_PARSE_LONG(_int, int, n < INT_MIN, INT_MAX)
928 DEFINE_PARSE_LONG(_s32, int32_t, n < INT32_MIN, INT32_MAX)
929 DEFINE_PARSE_LONG(_s16, int16_t, n < INT16_MIN, INT16_MAX)
930 DEFINE_PARSE_LONG(_s8, int8_t, n < INT8_MIN, INT8_MAX)