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, int argc, Jim_Obj *const *argv)
66 LOG_DEBUG("command - %s", name);
67 for (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 /* If this is a two level command, e.g. "flash banks", then the
221 * "unknown" proc in startup.tcl must redirect to this command.
223 * "flash banks" is translated by "unknown" to "flash_banks"
224 * if such a proc exists
226 /* Print help for command */
230 /* maximum of two levels :-) */
231 if (c->parent != NULL)
233 t1 = c->parent->name;
237 const char *full_name = alloc_printf("ocd_%s%s%s", t1, t2, t3);
238 Jim_CreateCommand(interp, full_name, script_command, c, NULL);
239 free((void *)full_name);
241 /* we now need to add an overrideable proc */
242 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);
243 Jim_Eval_Named(interp, override_name, __THIS__FILE__, __LINE__);
244 free((void *)override_name);
246 /* accumulate help text in Tcl helptext list. */
247 Jim_Obj *helptext = Jim_GetGlobalVariableStr(interp, "ocd_helptext", JIM_ERRMSG);
248 if (Jim_IsShared(helptext))
249 helptext = Jim_DuplicateObj(interp, helptext);
250 Jim_Obj *cmd_entry = Jim_NewListObj(interp, NULL, 0);
252 Jim_Obj *cmd_list = Jim_NewListObj(interp, NULL, 0);
254 /* maximum of two levels :-) */
255 if (c->parent != NULL)
257 Jim_ListAppendElement(interp, cmd_list, Jim_NewStringObj(interp, c->parent->name, -1));
259 Jim_ListAppendElement(interp, cmd_list, Jim_NewStringObj(interp, c->name, -1));
261 Jim_ListAppendElement(interp, cmd_entry, cmd_list);
262 Jim_ListAppendElement(interp, cmd_entry, Jim_NewStringObj(interp, help, -1));
263 Jim_ListAppendElement(interp, helptext, cmd_entry);
267 int unregister_all_commands(command_context_t *context)
274 while (NULL != context->commands)
276 c = context->commands;
278 while (NULL != c->children)
281 c->children = c->children->next;
288 context->commands = context->commands->next;
299 int unregister_command(command_context_t *context, char *name)
301 command_t *c, *p = NULL, *c2;
303 if ((!context) || (!name))
304 return ERROR_INVALID_ARGUMENTS;
307 c = context->commands;
311 if (strcmp(name, c->name) == 0)
320 /* first element in command list */
321 context->commands = c->next;
324 /* unregister children */
325 while (NULL != c->children)
328 c->children = c->children->next;
343 /* remember the last command for unlinking */
351 void command_output_text(command_context_t *context, const char *data)
353 if (context && context->output_handler && data) {
354 context->output_handler(context, data);
358 void command_print_sameline(command_context_t *context, const char *format, ...)
363 va_start(ap, format);
365 string = alloc_vprintf(format, ap);
368 /* we want this collected in the log + we also want to pick it up as a tcl return
371 * The latter bit isn't precisely neat, but will do for now.
373 LOG_USER_N("%s", string);
374 /* We already printed it above */
375 /* command_output_text(context, string); */
382 void command_print(command_context_t *context, const char *format, ...)
387 va_start(ap, format);
389 string = alloc_vprintf(format, ap);
392 strcat(string, "\n"); /* alloc_vprintf guaranteed the buffer to be at least one char longer */
393 /* we want this collected in the log + we also want to pick it up as a tcl return
396 * The latter bit isn't precisely neat, but will do for now.
398 LOG_USER_N("%s", string);
399 /* We already printed it above */
400 /* command_output_text(context, string); */
407 static int run_command(command_context_t *context,
408 command_t *c, char *words[], unsigned num_words)
411 if (!((context->mode == COMMAND_CONFIG) || (c->mode == COMMAND_ANY) || (c->mode == context->mode)))
413 /* Config commands can not run after the config stage */
414 LOG_ERROR("Command '%s' only runs during configuration stage", c->name);
418 int retval = c->handler(context, c->name, words + start_word + 1, num_words - start_word - 1);
419 if (retval == ERROR_COMMAND_SYNTAX_ERROR)
421 /* Print help for command */
425 /* maximum of two levels :-) */
426 if (c->parent != NULL)
428 t1 = c->parent->name;
432 command_run_linef(context, "help {%s%s%s}", t1, t2, t3);
434 else if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
436 /* just fall through for a shutdown request */
438 else if (retval != ERROR_OK)
440 /* we do not print out an error message because the command *should*
441 * have printed out an error
443 LOG_DEBUG("Command failed with error code %d", retval);
449 int command_run_line(command_context_t *context, char *line)
451 /* all the parent commands have been registered with the interpreter
452 * so, can just evaluate the line as a script and check for
455 /* run the line thru a script engine */
456 int retval = ERROR_FAIL;
458 /* Beware! This code needs to be reentrant. It is also possible
459 * for OpenOCD commands to be invoked directly from Tcl. This would
460 * happen when the Jim Tcl interpreter is provided by eCos for
463 Jim_DeleteAssocData(interp, "context");
464 retcode = Jim_SetAssocData(interp, "context", NULL, context);
465 if (retcode == JIM_OK)
467 /* associated the return value */
468 Jim_DeleteAssocData(interp, "retval");
469 retcode = Jim_SetAssocData(interp, "retval", NULL, &retval);
470 if (retcode == JIM_OK)
472 retcode = Jim_Eval_Named(interp, line, __THIS__FILE__, __LINE__);
474 Jim_DeleteAssocData(interp, "retval");
476 Jim_DeleteAssocData(interp, "context");
478 if (retcode == JIM_ERR) {
479 if (retval != ERROR_COMMAND_CLOSE_CONNECTION)
481 /* We do not print the connection closed error message */
482 Jim_PrintErrorMessage(interp);
484 if (retval == ERROR_OK)
486 /* It wasn't a low level OpenOCD command that failed */
490 } else if (retcode == JIM_EXIT) {
492 /* exit(Jim_GetExitCode(interp)); */
497 result = Jim_GetString(Jim_GetResult(interp), &reslen);
502 for (i = 0; i < reslen; i += 256)
508 strncpy(buff, result + i, chunk);
510 LOG_USER_N("%s", buff);
512 LOG_USER_N("%s", "\n");
519 int command_run_linef(command_context_t *context, const char *format, ...)
521 int retval = ERROR_FAIL;
524 va_start(ap, format);
525 string = alloc_vprintf(format, ap);
528 retval = command_run_line(context, string);
534 void command_set_output_handler(command_context_t* context, int (*output_handler)(struct command_context_s *context, const char* line), void *priv)
536 context->output_handler = output_handler;
537 context->output_handler_priv = priv;
540 command_context_t* copy_command_context(command_context_t* context)
542 command_context_t* copy_context = malloc(sizeof(command_context_t));
544 *copy_context = *context;
549 int command_done(command_context_t *context)
557 /* find full path to file */
558 static int jim_find(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
562 const char *file = Jim_GetString(argv[1], NULL);
563 char *full_path = find_file(file);
564 if (full_path == NULL)
566 Jim_Obj *result = Jim_NewStringObj(interp, full_path, strlen(full_path));
569 Jim_SetResult(interp, result);
573 static int jim_echo(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
577 const char *str = Jim_GetString(argv[1], NULL);
582 static size_t openocd_jim_fwrite(const void *_ptr, size_t size, size_t n, void *cookie)
588 /* make it a char easier to read code */
592 if (ptr == NULL || interp == NULL || nbytes == 0) {
596 /* do we have to chunk it? */
597 if (ptr[nbytes] == 0)
599 /* no it is a C style string */
600 LOG_USER_N("%s", ptr);
603 /* GRR we must chunk - not null terminated */
613 memcpy(chunk, ptr, x);
617 LOG_USER_N("%s", chunk);
625 static size_t openocd_jim_fread(void *ptr, size_t size, size_t n, void *cookie)
627 /* TCL wants to read... tell him no */
631 static int openocd_jim_vfprintf(void *cookie, const char *fmt, va_list ap)
642 cp = alloc_vprintf(fmt, ap);
645 LOG_USER_N("%s", cp);
652 static int openocd_jim_fflush(void *cookie)
654 /* nothing to flush */
658 static char* openocd_jim_fgets(char *s, int size, void *cookie)
665 static int jim_capture(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
670 const char *str = Jim_GetString(argv[1], NULL);
672 /* capture log output and return it */
673 Jim_Obj *tclOutput = Jim_NewStringObj(interp, "", 0);
674 /* a garbage collect can happen, so we need a reference count to this object */
675 Jim_IncrRefCount(tclOutput);
677 log_add_callback(tcl_output, tclOutput);
679 retcode = Jim_Eval_Named(interp, str, __THIS__FILE__, __LINE__);
681 log_remove_callback(tcl_output, tclOutput);
683 /* We dump output into this local variable */
684 Jim_SetResult(interp, tclOutput);
685 Jim_DecrRefCount(interp, tclOutput);
690 /* sleep command sleeps for <n> miliseconds
691 * this is useful in target startup scripts
693 static int handle_sleep_command(struct command_context_s *cmd_ctx,
694 char *cmd, char **args, int argc)
699 if (strcmp(args[1], "busy") == 0)
702 return ERROR_COMMAND_SYNTAX_ERROR;
704 else if (argc < 1 || argc > 2)
705 return ERROR_COMMAND_SYNTAX_ERROR;
707 unsigned long duration = 0;
708 int retval = parse_ulong(args[0], &duration);
709 if (ERROR_OK != retval)
714 long long then = timeval_ms();
715 while (timeval_ms() - then < (long long)duration)
717 target_call_timer_callbacks_now();
722 busy_sleep(duration);
727 static int handle_fast_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
730 return ERROR_COMMAND_SYNTAX_ERROR;
732 fast_and_dangerous = strcmp("enable", args[0]) == 0;
738 command_context_t* command_init()
740 command_context_t* context = malloc(sizeof(command_context_t));
741 extern const char startup_tcl[];
744 context->mode = COMMAND_EXEC;
745 context->commands = NULL;
746 context->current_target = 0;
747 context->output_handler = NULL;
748 context->output_handler_priv = NULL;
752 /* Create an interpreter */
753 interp = Jim_CreateInterp();
754 /* Add all the Jim core commands */
755 Jim_RegisterCoreCommands(interp);
758 #if defined(_MSC_VER)
759 /* WinXX - is generic, the forward
760 * looking problem is this:
764 * "winxx" is generic.
767 #elif defined(__linux__)
769 #elif defined(__DARWIN__)
771 #elif defined(__CYGWIN__)
773 #elif defined(__MINGW32__)
775 #elif defined(__ECOS)
778 #warn unrecognized host OS...
781 Jim_SetGlobalVariableStr(interp, "ocd_HOSTOS",
782 Jim_NewStringObj(interp, HostOs , strlen(HostOs)));
784 Jim_CreateCommand(interp, "ocd_find", jim_find, NULL, NULL);
785 Jim_CreateCommand(interp, "echo", jim_echo, NULL, NULL);
786 Jim_CreateCommand(interp, "capture", jim_capture, NULL, NULL);
788 /* Set Jim's STDIO */
789 interp->cookie_stdin = interp;
790 interp->cookie_stdout = interp;
791 interp->cookie_stderr = interp;
792 interp->cb_fwrite = openocd_jim_fwrite;
793 interp->cb_fread = openocd_jim_fread ;
794 interp->cb_vfprintf = openocd_jim_vfprintf;
795 interp->cb_fflush = openocd_jim_fflush;
796 interp->cb_fgets = openocd_jim_fgets;
799 Jim_EventLoopOnLoad(interp);
801 if (Jim_Eval_Named(interp, startup_tcl, "embedded:startup.tcl",1) == JIM_ERR)
803 LOG_ERROR("Failed to run startup.tcl (embedded into OpenOCD)");
804 Jim_PrintErrorMessage(interp);
808 register_command(context, NULL, "sleep",
809 handle_sleep_command, COMMAND_ANY,
810 "<n> [busy] - sleep for n milliseconds. "
811 "\"busy\" means busy wait");
812 register_command(context, NULL, "fast",
813 handle_fast_command, COMMAND_ANY,
814 "fast <enable/disable> - place at beginning of "
815 "config files. Sets defaults to fast and dangerous.");
820 int command_context_mode(command_context_t *cmd_ctx, enum command_mode mode)
823 return ERROR_INVALID_ARGUMENTS;
825 cmd_ctx->mode = mode;
829 void process_jim_events(void)
832 static int recursion = 0;
837 Jim_ProcessEvents (interp, JIM_ALL_EVENTS | JIM_DONT_WAIT);
843 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)
845 Jim_CreateCommand(interp, name, cmd, NULL, NULL);
847 /* FIX!!! it would be prettier to invoke add_help_text...
848 * accumulate help text in Tcl helptext list. */
849 Jim_Obj *helptext = Jim_GetGlobalVariableStr(interp, "ocd_helptext", JIM_ERRMSG);
850 if (Jim_IsShared(helptext))
851 helptext = Jim_DuplicateObj(interp, helptext);
853 Jim_Obj *cmd_entry = Jim_NewListObj(interp, NULL, 0);
855 Jim_Obj *cmd_list = Jim_NewListObj(interp, NULL, 0);
856 Jim_ListAppendElement(interp, cmd_list, Jim_NewStringObj(interp, name, -1));
858 Jim_ListAppendElement(interp, cmd_entry, cmd_list);
859 Jim_ListAppendElement(interp, cmd_entry, Jim_NewStringObj(interp, help, -1));
860 Jim_ListAppendElement(interp, helptext, cmd_entry);
863 /* return global variable long value or 0 upon failure */
864 long jim_global_long(const char *variable)
866 Jim_Obj *objPtr = Jim_GetGlobalVariableStr(interp, variable, JIM_ERRMSG);
868 if (Jim_GetLong(interp, objPtr, &t) == JIM_OK)
875 #define DEFINE_PARSE_NUM_TYPE(name, type, func, min, max) \
876 int parse##name(const char *str, type *ul) \
880 LOG_ERROR("Invalid command argument"); \
881 return ERROR_COMMAND_ARGUMENT_INVALID; \
884 *ul = func(str, &end, 0); \
887 LOG_ERROR("Invalid command argument"); \
888 return ERROR_COMMAND_ARGUMENT_INVALID; \
890 if ((max == *ul) && (ERANGE == errno)) \
892 LOG_ERROR("Argument overflow"); \
893 return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
895 if (min && (min == *ul) && (ERANGE == errno)) \
897 LOG_ERROR("Argument underflow"); \
898 return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
902 DEFINE_PARSE_NUM_TYPE(_ulong, unsigned long , strtoul, 0, ULONG_MAX)
903 DEFINE_PARSE_NUM_TYPE(_ullong, unsigned long long, strtoull, 0, ULLONG_MAX)
904 DEFINE_PARSE_NUM_TYPE(_long, long , strtol, LONG_MIN, LONG_MAX)
905 DEFINE_PARSE_NUM_TYPE(_llong, long long, strtoll, LLONG_MIN, LLONG_MAX)
907 #define DEFINE_PARSE_WRAPPER(name, type, min, max, functype, funcname) \
908 int parse##name(const char *str, type *ul) \
911 int retval = parse##funcname(str, &n); \
912 if (ERROR_OK != retval) \
915 return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
917 return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
922 #define DEFINE_PARSE_ULONG(name, type, min, max) \
923 DEFINE_PARSE_WRAPPER(name, type, min, max, unsigned long, _ulong)
924 DEFINE_PARSE_ULONG(_uint, unsigned, 0, UINT_MAX)
925 DEFINE_PARSE_ULONG(_u32, uint32_t, 0, UINT32_MAX)
926 DEFINE_PARSE_ULONG(_u16, uint16_t, 0, UINT16_MAX)
927 DEFINE_PARSE_ULONG(_u8, uint8_t, 0, UINT8_MAX)
929 #define DEFINE_PARSE_LONG(name, type, min, max) \
930 DEFINE_PARSE_WRAPPER(name, type, min, max, long, _long)
931 DEFINE_PARSE_LONG(_int, int, n < INT_MIN, INT_MAX)
932 DEFINE_PARSE_LONG(_s32, int32_t, n < INT32_MIN, INT32_MAX)
933 DEFINE_PARSE_LONG(_s16, int16_t, n < INT16_MIN, INT16_MAX)
934 DEFINE_PARSE_LONG(_s8, int8_t, n < INT8_MIN, INT8_MAX)