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 static int run_command(command_context_t *context,
51 command_t *c, char *words[], unsigned num_words);
53 static void tcl_output(void *privData, const char *file, unsigned line,
54 const char *function, const char *string)
56 Jim_Obj *tclOutput = (Jim_Obj *)privData;
57 Jim_AppendString(interp, tclOutput, string, strlen(string));
60 extern command_context_t *global_cmd_ctx;
62 void script_debug(Jim_Interp *interp, const char *name,
63 unsigned argc, Jim_Obj *const *argv)
65 LOG_DEBUG("command - %s", name);
66 for (unsigned i = 0; i < argc; i++)
69 const char *w = Jim_GetString(argv[i], &len);
71 /* end of line comment? */
75 LOG_DEBUG("%s - argv[%d]=%s", name, i, w);
79 static int script_command(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
81 /* the private data is stashed in the interp structure */
83 command_context_t *context;
89 /* DANGER!!!! be careful what we invoke here, since interp->cmdPrivData might
90 * get overwritten by running other Jim commands! Treat it as an
91 * emphemeral global variable that is used in lieu of an argument
92 * to the fn and fish it out manually.
94 c = interp->cmdPrivData;
97 LOG_ERROR("BUG: interp->cmdPrivData == NULL");
100 target_call_timer_callbacks_now();
101 LOG_USER_N("%s", ""); /* Keep GDB connection alive*/
103 script_debug(interp, c->name, argc, argv);
105 words = malloc(sizeof(char *) * argc);
106 for (i = 0; i < argc; i++)
109 const char *w = Jim_GetString(argv[i], &len);
112 /* hit an end of line comment */
115 words[i] = strdup(w);
116 if (words[i] == NULL)
119 for (j = 0; j < i; j++)
127 /* grab the command context from the associated data */
128 context = Jim_GetAssocData(interp, "context");
131 /* Tcl can invoke commands directly instead of via command_run_line(). This would
132 * happen when the Jim Tcl interpreter is provided by eCos.
134 context = global_cmd_ctx;
137 /* capture log output and return it */
138 Jim_Obj *tclOutput = Jim_NewStringObj(interp, "", 0);
139 /* a garbage collect can happen, so we need a reference count to this object */
140 Jim_IncrRefCount(tclOutput);
142 log_add_callback(tcl_output, tclOutput);
144 retval = run_command(context, c, words, nwords);
146 log_remove_callback(tcl_output, tclOutput);
148 /* We dump output into this local variable */
149 Jim_SetResult(interp, tclOutput);
150 Jim_DecrRefCount(interp, tclOutput);
152 for (i = 0; i < nwords; i++)
156 int *return_retval = Jim_GetAssocData(interp, "retval");
157 if (return_retval != NULL)
159 *return_retval = retval;
162 return (retval == ERROR_OK)?JIM_OK:JIM_ERR;
165 /* nice short description of source file */
166 #define __THIS__FILE__ "command.c"
168 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)
172 if (!context || !name)
175 c = malloc(sizeof(command_t));
177 c->name = strdup(name);
180 c->handler = handler;
186 /* place command in tree */
189 if (parent->children)
191 /* find last child */
192 for (p = parent->children; p && p->next; p = p->next);
198 parent->children = c;
203 if (context->commands)
205 /* find last command */
206 for (p = context->commands; p && p->next; p = p->next);
212 context->commands = c;
216 /* just a placeholder, no handler */
217 if (c->handler == NULL)
220 const char *full_name = command_name(c, '_');
222 const char *ocd_name = alloc_printf("ocd_%s", full_name);
223 Jim_CreateCommand(interp, ocd_name, script_command, c, NULL);
224 free((void *)ocd_name);
226 /* we now need to add an overrideable proc */
227 const char *override_name = alloc_printf("proc %s {args} {"
228 "if {[catch {eval ocd_%s $args}] == 0} "
229 "{return \"\"} else {return -code error}}",
230 full_name, full_name);
231 Jim_Eval_Named(interp, override_name, __THIS__FILE__, __LINE__);
232 free((void *)override_name);
234 free((void *)full_name);
236 /* accumulate help text in Tcl helptext list. */
237 Jim_Obj *helptext = Jim_GetGlobalVariableStr(interp, "ocd_helptext", JIM_ERRMSG);
238 if (Jim_IsShared(helptext))
239 helptext = Jim_DuplicateObj(interp, helptext);
240 Jim_Obj *cmd_entry = Jim_NewListObj(interp, NULL, 0);
242 Jim_Obj *cmd_list = Jim_NewListObj(interp, NULL, 0);
244 /* maximum of two levels :-) */
245 if (c->parent != NULL)
247 Jim_ListAppendElement(interp, cmd_list, Jim_NewStringObj(interp, c->parent->name, -1));
249 Jim_ListAppendElement(interp, cmd_list, Jim_NewStringObj(interp, c->name, -1));
251 Jim_ListAppendElement(interp, cmd_entry, cmd_list);
252 Jim_ListAppendElement(interp, cmd_entry, Jim_NewStringObj(interp, help, -1));
253 Jim_ListAppendElement(interp, helptext, cmd_entry);
257 int unregister_all_commands(command_context_t *context)
264 while (NULL != context->commands)
266 c = context->commands;
268 while (NULL != c->children)
271 c->children = c->children->next;
278 context->commands = context->commands->next;
289 int unregister_command(command_context_t *context, char *name)
291 command_t *c, *p = NULL, *c2;
293 if ((!context) || (!name))
294 return ERROR_INVALID_ARGUMENTS;
297 c = context->commands;
301 if (strcmp(name, c->name) == 0)
310 /* first element in command list */
311 context->commands = c->next;
314 /* unregister children */
315 while (NULL != c->children)
318 c->children = c->children->next;
333 /* remember the last command for unlinking */
341 void command_output_text(command_context_t *context, const char *data)
343 if (context && context->output_handler && data) {
344 context->output_handler(context, data);
348 void command_print_sameline(command_context_t *context, const char *format, ...)
353 va_start(ap, format);
355 string = alloc_vprintf(format, ap);
358 /* we want this collected in the log + we also want to pick it up as a tcl return
361 * The latter bit isn't precisely neat, but will do for now.
363 LOG_USER_N("%s", string);
364 /* We already printed it above */
365 /* command_output_text(context, string); */
372 void command_print(command_context_t *context, const char *format, ...)
377 va_start(ap, format);
379 string = alloc_vprintf(format, ap);
382 strcat(string, "\n"); /* alloc_vprintf guaranteed the buffer to be at least one char longer */
383 /* we want this collected in the log + we also want to pick it up as a tcl return
386 * The latter bit isn't precisely neat, but will do for now.
388 LOG_USER_N("%s", string);
389 /* We already printed it above */
390 /* command_output_text(context, string); */
397 static char *__command_name(struct command_s *c, char delim, unsigned extra)
400 unsigned len = strlen(c->name);
401 if (NULL == c->parent) {
402 // allocate enough for the name, child names, and '\0'
403 name = malloc(len + extra + 1);
404 strcpy(name, c->name);
406 // parent's extra must include both the space and name
407 name = __command_name(c->parent, delim, 1 + len + extra);
408 char dstr[2] = { delim, 0 };
410 strcat(name, c->name);
414 char *command_name(struct command_s *c, char delim)
416 return __command_name(c, delim, 0);
419 static int run_command(command_context_t *context,
420 command_t *c, char *words[], unsigned num_words)
423 if (!((context->mode == COMMAND_CONFIG) || (c->mode == COMMAND_ANY) || (c->mode == context->mode)))
425 /* Config commands can not run after the config stage */
426 LOG_ERROR("Command '%s' only runs during configuration stage", c->name);
430 int retval = c->handler(context, c->name, words + start_word + 1, num_words - start_word - 1);
431 if (retval == ERROR_COMMAND_SYNTAX_ERROR)
433 /* Print help for command */
434 char *full_name = command_name(c, ' ');
435 if (NULL != full_name) {
436 command_run_linef(context, "help %s", full_name);
441 else if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
443 /* just fall through for a shutdown request */
445 else if (retval != ERROR_OK)
447 /* we do not print out an error message because the command *should*
448 * have printed out an error
450 LOG_DEBUG("Command failed with error code %d", retval);
456 int command_run_line(command_context_t *context, char *line)
458 /* all the parent commands have been registered with the interpreter
459 * so, can just evaluate the line as a script and check for
462 /* run the line thru a script engine */
463 int retval = ERROR_FAIL;
465 /* Beware! This code needs to be reentrant. It is also possible
466 * for OpenOCD commands to be invoked directly from Tcl. This would
467 * happen when the Jim Tcl interpreter is provided by eCos for
470 Jim_DeleteAssocData(interp, "context");
471 retcode = Jim_SetAssocData(interp, "context", NULL, context);
472 if (retcode == JIM_OK)
474 /* associated the return value */
475 Jim_DeleteAssocData(interp, "retval");
476 retcode = Jim_SetAssocData(interp, "retval", NULL, &retval);
477 if (retcode == JIM_OK)
479 retcode = Jim_Eval_Named(interp, line, __THIS__FILE__, __LINE__);
481 Jim_DeleteAssocData(interp, "retval");
483 Jim_DeleteAssocData(interp, "context");
485 if (retcode == JIM_ERR) {
486 if (retval != ERROR_COMMAND_CLOSE_CONNECTION)
488 /* We do not print the connection closed error message */
489 Jim_PrintErrorMessage(interp);
491 if (retval == ERROR_OK)
493 /* It wasn't a low level OpenOCD command that failed */
497 } else if (retcode == JIM_EXIT) {
499 /* exit(Jim_GetExitCode(interp)); */
504 result = Jim_GetString(Jim_GetResult(interp), &reslen);
509 for (i = 0; i < reslen; i += 256)
515 strncpy(buff, result + i, chunk);
517 LOG_USER_N("%s", buff);
519 LOG_USER_N("%s", "\n");
526 int command_run_linef(command_context_t *context, const char *format, ...)
528 int retval = ERROR_FAIL;
531 va_start(ap, format);
532 string = alloc_vprintf(format, ap);
535 retval = command_run_line(context, string);
541 void command_set_output_handler(command_context_t* context, int (*output_handler)(struct command_context_s *context, const char* line), void *priv)
543 context->output_handler = output_handler;
544 context->output_handler_priv = priv;
547 command_context_t* copy_command_context(command_context_t* context)
549 command_context_t* copy_context = malloc(sizeof(command_context_t));
551 *copy_context = *context;
556 int command_done(command_context_t *context)
564 /* find full path to file */
565 static int jim_find(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
569 const char *file = Jim_GetString(argv[1], NULL);
570 char *full_path = find_file(file);
571 if (full_path == NULL)
573 Jim_Obj *result = Jim_NewStringObj(interp, full_path, strlen(full_path));
576 Jim_SetResult(interp, result);
580 static int jim_echo(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
584 const char *str = Jim_GetString(argv[1], NULL);
589 static size_t openocd_jim_fwrite(const void *_ptr, size_t size, size_t n, void *cookie)
595 /* make it a char easier to read code */
599 if (ptr == NULL || interp == NULL || nbytes == 0) {
603 /* do we have to chunk it? */
604 if (ptr[nbytes] == 0)
606 /* no it is a C style string */
607 LOG_USER_N("%s", ptr);
610 /* GRR we must chunk - not null terminated */
620 memcpy(chunk, ptr, x);
624 LOG_USER_N("%s", chunk);
632 static size_t openocd_jim_fread(void *ptr, size_t size, size_t n, void *cookie)
634 /* TCL wants to read... tell him no */
638 static int openocd_jim_vfprintf(void *cookie, const char *fmt, va_list ap)
649 cp = alloc_vprintf(fmt, ap);
652 LOG_USER_N("%s", cp);
659 static int openocd_jim_fflush(void *cookie)
661 /* nothing to flush */
665 static char* openocd_jim_fgets(char *s, int size, void *cookie)
672 static int jim_capture(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
677 const char *str = Jim_GetString(argv[1], NULL);
679 /* capture log output and return it */
680 Jim_Obj *tclOutput = Jim_NewStringObj(interp, "", 0);
681 /* a garbage collect can happen, so we need a reference count to this object */
682 Jim_IncrRefCount(tclOutput);
684 log_add_callback(tcl_output, tclOutput);
686 retcode = Jim_Eval_Named(interp, str, __THIS__FILE__, __LINE__);
688 log_remove_callback(tcl_output, tclOutput);
690 /* We dump output into this local variable */
691 Jim_SetResult(interp, tclOutput);
692 Jim_DecrRefCount(interp, tclOutput);
697 /* sleep command sleeps for <n> miliseconds
698 * this is useful in target startup scripts
700 static int handle_sleep_command(struct command_context_s *cmd_ctx,
701 char *cmd, char **args, int argc)
706 if (strcmp(args[1], "busy") == 0)
709 return ERROR_COMMAND_SYNTAX_ERROR;
711 else if (argc < 1 || argc > 2)
712 return ERROR_COMMAND_SYNTAX_ERROR;
714 unsigned long duration = 0;
715 int retval = parse_ulong(args[0], &duration);
716 if (ERROR_OK != retval)
721 long long then = timeval_ms();
722 while (timeval_ms() - then < (long long)duration)
724 target_call_timer_callbacks_now();
729 busy_sleep(duration);
734 static int handle_fast_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
737 return ERROR_COMMAND_SYNTAX_ERROR;
739 fast_and_dangerous = strcmp("enable", args[0]) == 0;
745 command_context_t* command_init()
747 command_context_t* context = malloc(sizeof(command_context_t));
748 extern const char startup_tcl[];
751 context->mode = COMMAND_EXEC;
752 context->commands = NULL;
753 context->current_target = 0;
754 context->output_handler = NULL;
755 context->output_handler_priv = NULL;
759 /* Create an interpreter */
760 interp = Jim_CreateInterp();
761 /* Add all the Jim core commands */
762 Jim_RegisterCoreCommands(interp);
765 #if defined(_MSC_VER)
766 /* WinXX - is generic, the forward
767 * looking problem is this:
771 * "winxx" is generic.
774 #elif defined(__linux__)
776 #elif defined(__DARWIN__)
778 #elif defined(__CYGWIN__)
780 #elif defined(__MINGW32__)
782 #elif defined(__ECOS)
785 #warn unrecognized host OS...
788 Jim_SetGlobalVariableStr(interp, "ocd_HOSTOS",
789 Jim_NewStringObj(interp, HostOs , strlen(HostOs)));
791 Jim_CreateCommand(interp, "ocd_find", jim_find, NULL, NULL);
792 Jim_CreateCommand(interp, "echo", jim_echo, NULL, NULL);
793 Jim_CreateCommand(interp, "capture", jim_capture, NULL, NULL);
795 /* Set Jim's STDIO */
796 interp->cookie_stdin = interp;
797 interp->cookie_stdout = interp;
798 interp->cookie_stderr = interp;
799 interp->cb_fwrite = openocd_jim_fwrite;
800 interp->cb_fread = openocd_jim_fread ;
801 interp->cb_vfprintf = openocd_jim_vfprintf;
802 interp->cb_fflush = openocd_jim_fflush;
803 interp->cb_fgets = openocd_jim_fgets;
806 Jim_EventLoopOnLoad(interp);
808 if (Jim_Eval_Named(interp, startup_tcl, "embedded:startup.tcl",1) == JIM_ERR)
810 LOG_ERROR("Failed to run startup.tcl (embedded into OpenOCD)");
811 Jim_PrintErrorMessage(interp);
815 register_command(context, NULL, "sleep",
816 handle_sleep_command, COMMAND_ANY,
817 "<n> [busy] - sleep for n milliseconds. "
818 "\"busy\" means busy wait");
819 register_command(context, NULL, "fast",
820 handle_fast_command, COMMAND_ANY,
821 "fast <enable/disable> - place at beginning of "
822 "config files. Sets defaults to fast and dangerous.");
827 int command_context_mode(command_context_t *cmd_ctx, enum command_mode mode)
830 return ERROR_INVALID_ARGUMENTS;
832 cmd_ctx->mode = mode;
836 void process_jim_events(void)
839 static int recursion = 0;
844 Jim_ProcessEvents (interp, JIM_ALL_EVENTS | JIM_DONT_WAIT);
850 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)
852 Jim_CreateCommand(interp, name, cmd, NULL, NULL);
854 /* FIX!!! it would be prettier to invoke add_help_text...
855 * accumulate help text in Tcl helptext list. */
856 Jim_Obj *helptext = Jim_GetGlobalVariableStr(interp, "ocd_helptext", JIM_ERRMSG);
857 if (Jim_IsShared(helptext))
858 helptext = Jim_DuplicateObj(interp, helptext);
860 Jim_Obj *cmd_entry = Jim_NewListObj(interp, NULL, 0);
862 Jim_Obj *cmd_list = Jim_NewListObj(interp, NULL, 0);
863 Jim_ListAppendElement(interp, cmd_list, Jim_NewStringObj(interp, name, -1));
865 Jim_ListAppendElement(interp, cmd_entry, cmd_list);
866 Jim_ListAppendElement(interp, cmd_entry, Jim_NewStringObj(interp, help, -1));
867 Jim_ListAppendElement(interp, helptext, cmd_entry);
870 /* return global variable long value or 0 upon failure */
871 long jim_global_long(const char *variable)
873 Jim_Obj *objPtr = Jim_GetGlobalVariableStr(interp, variable, JIM_ERRMSG);
875 if (Jim_GetLong(interp, objPtr, &t) == JIM_OK)
882 #define DEFINE_PARSE_NUM_TYPE(name, type, func, min, max) \
883 int parse##name(const char *str, type *ul) \
887 LOG_ERROR("Invalid command argument"); \
888 return ERROR_COMMAND_ARGUMENT_INVALID; \
891 *ul = func(str, &end, 0); \
894 LOG_ERROR("Invalid command argument"); \
895 return ERROR_COMMAND_ARGUMENT_INVALID; \
897 if ((max == *ul) && (ERANGE == errno)) \
899 LOG_ERROR("Argument overflow"); \
900 return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
902 if (min && (min == *ul) && (ERANGE == errno)) \
904 LOG_ERROR("Argument underflow"); \
905 return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
909 DEFINE_PARSE_NUM_TYPE(_ulong, unsigned long , strtoul, 0, ULONG_MAX)
910 DEFINE_PARSE_NUM_TYPE(_ullong, unsigned long long, strtoull, 0, ULLONG_MAX)
911 DEFINE_PARSE_NUM_TYPE(_long, long , strtol, LONG_MIN, LONG_MAX)
912 DEFINE_PARSE_NUM_TYPE(_llong, long long, strtoll, LLONG_MIN, LLONG_MAX)
914 #define DEFINE_PARSE_WRAPPER(name, type, min, max, functype, funcname) \
915 int parse##name(const char *str, type *ul) \
918 int retval = parse##funcname(str, &n); \
919 if (ERROR_OK != retval) \
922 return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
924 return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
929 #define DEFINE_PARSE_ULONG(name, type, min, max) \
930 DEFINE_PARSE_WRAPPER(name, type, min, max, unsigned long, _ulong)
931 DEFINE_PARSE_ULONG(_uint, unsigned, 0, UINT_MAX)
932 DEFINE_PARSE_ULONG(_u32, uint32_t, 0, UINT32_MAX)
933 DEFINE_PARSE_ULONG(_u16, uint16_t, 0, UINT16_MAX)
934 DEFINE_PARSE_ULONG(_u8, uint8_t, 0, UINT8_MAX)
936 #define DEFINE_PARSE_LONG(name, type, min, max) \
937 DEFINE_PARSE_WRAPPER(name, type, min, max, long, _long)
938 DEFINE_PARSE_LONG(_int, int, n < INT_MIN, INT_MAX)
939 DEFINE_PARSE_LONG(_s32, int32_t, n < INT32_MIN, INT32_MAX)
940 DEFINE_PARSE_LONG(_s16, int16_t, n < INT16_MIN, INT16_MAX)
941 DEFINE_PARSE_LONG(_s8, int8_t, n < INT8_MIN, INT8_MAX)