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 handle_sleep_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
51 int handle_fast_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
53 int run_command(command_context_t *context, command_t *c, char *words[], int num_words);
55 static void tcl_output(void *privData, const char *file, int line, const char *function, const char *string)
57 Jim_Obj *tclOutput = (Jim_Obj *)privData;
59 Jim_AppendString(interp, tclOutput, string, strlen(string));
62 extern command_context_t *global_cmd_ctx;
64 void script_debug(Jim_Interp *interp, const char *name, int argc, Jim_Obj *const *argv)
68 LOG_DEBUG("command - %s", name);
69 for (i = 0; i < argc; i++) {
71 const char *w = Jim_GetString(argv[i], &len);
73 /* end of line comment? */
77 LOG_DEBUG("%s - argv[%d]=%s", name, i, w);
81 static int script_command(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
83 /* the private data is stashed in the interp structure */
85 command_context_t *context;
91 /* DANGER!!!! be careful what we invoke here, since interp->cmdPrivData might
92 * get overwritten by running other Jim commands! Treat it as an
93 * emphemeral global variable that is used in lieu of an argument
94 * to the fn and fish it out manually.
96 c = interp->cmdPrivData;
99 LOG_ERROR("BUG: interp->cmdPrivData == NULL");
102 target_call_timer_callbacks_now();
103 LOG_USER_N("%s", ""); /* Keep GDB connection alive*/
105 script_debug(interp, c->name, argc, argv);
107 words = malloc(sizeof(char *) * argc);
108 for (i = 0; i < argc; i++)
111 const char *w = Jim_GetString(argv[i], &len);
114 /* hit an end of line comment */
117 words[i] = strdup(w);
118 if (words[i] == NULL)
121 for (j = 0; j < i; j++)
129 /* grab the command context from the associated data */
130 context = Jim_GetAssocData(interp, "context");
133 /* Tcl can invoke commands directly instead of via command_run_line(). This would
134 * happen when the Jim Tcl interpreter is provided by eCos.
136 context = global_cmd_ctx;
139 /* capture log output and return it */
140 Jim_Obj *tclOutput = Jim_NewStringObj(interp, "", 0);
141 /* a garbage collect can happen, so we need a reference count to this object */
142 Jim_IncrRefCount(tclOutput);
144 log_add_callback(tcl_output, tclOutput);
146 retval = run_command(context, c, words, nwords);
148 log_remove_callback(tcl_output, tclOutput);
150 /* We dump output into this local variable */
151 Jim_SetResult(interp, tclOutput);
152 Jim_DecrRefCount(interp, tclOutput);
154 for (i = 0; i < nwords; i++)
158 int *return_retval = Jim_GetAssocData(interp, "retval");
159 if (return_retval != NULL)
161 *return_retval = retval;
164 return (retval == ERROR_OK)?JIM_OK:JIM_ERR;
167 /* nice short description of source file */
168 #define __THIS__FILE__ "command.c"
170 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)
174 if (!context || !name)
177 c = malloc(sizeof(command_t));
179 c->name = strdup(name);
182 c->handler = handler;
188 /* place command in tree */
191 if (parent->children)
193 /* find last child */
194 for (p = parent->children; p && p->next; p = p->next);
200 parent->children = c;
205 if (context->commands)
207 /* find last command */
208 for (p = context->commands; p && p->next; p = p->next);
214 context->commands = c;
218 /* just a placeholder, no handler */
219 if (c->handler == NULL)
222 /* If this is a two level command, e.g. "flash banks", then the
223 * "unknown" proc in startup.tcl must redirect to this command.
225 * "flash banks" is translated by "unknown" to "flash_banks"
226 * if such a proc exists
228 /* Print help for command */
232 /* maximum of two levels :-) */
233 if (c->parent != NULL)
235 t1 = c->parent->name;
239 const char *full_name = alloc_printf("ocd_%s%s%s", t1, t2, t3);
240 Jim_CreateCommand(interp, full_name, script_command, c, NULL);
241 free((void *)full_name);
243 /* we now need to add an overrideable proc */
244 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);
245 Jim_Eval_Named(interp, override_name, __THIS__FILE__, __LINE__);
246 free((void *)override_name);
248 /* accumulate help text in Tcl helptext list. */
249 Jim_Obj *helptext = Jim_GetGlobalVariableStr(interp, "ocd_helptext", JIM_ERRMSG);
250 if (Jim_IsShared(helptext))
251 helptext = Jim_DuplicateObj(interp, helptext);
252 Jim_Obj *cmd_entry = Jim_NewListObj(interp, NULL, 0);
254 Jim_Obj *cmd_list = Jim_NewListObj(interp, NULL, 0);
256 /* maximum of two levels :-) */
257 if (c->parent != NULL)
259 Jim_ListAppendElement(interp, cmd_list, Jim_NewStringObj(interp, c->parent->name, -1));
261 Jim_ListAppendElement(interp, cmd_list, Jim_NewStringObj(interp, c->name, -1));
263 Jim_ListAppendElement(interp, cmd_entry, cmd_list);
264 Jim_ListAppendElement(interp, cmd_entry, Jim_NewStringObj(interp, help, -1));
265 Jim_ListAppendElement(interp, helptext, cmd_entry);
269 int unregister_all_commands(command_context_t *context)
276 while (NULL != context->commands)
278 c = context->commands;
280 while (NULL != c->children)
283 c->children = c->children->next;
290 context->commands = context->commands->next;
301 int unregister_command(command_context_t *context, char *name)
303 command_t *c, *p = NULL, *c2;
305 if ((!context) || (!name))
306 return ERROR_INVALID_ARGUMENTS;
309 c = context->commands;
313 if (strcmp(name, c->name) == 0)
322 /* first element in command list */
323 context->commands = c->next;
326 /* unregister children */
327 while (NULL != c->children)
330 c->children = c->children->next;
345 /* remember the last command for unlinking */
353 void command_output_text(command_context_t *context, const char *data)
355 if (context && context->output_handler && data) {
356 context->output_handler(context, data);
360 void command_print_sameline(command_context_t *context, const char *format, ...)
365 va_start(ap, format);
367 string = alloc_vprintf(format, ap);
370 /* we want this collected in the log + we also want to pick it up as a tcl return
373 * The latter bit isn't precisely neat, but will do for now.
375 LOG_USER_N("%s", string);
376 /* We already printed it above */
377 /* command_output_text(context, string); */
384 void command_print(command_context_t *context, const char *format, ...)
389 va_start(ap, format);
391 string = alloc_vprintf(format, ap);
394 strcat(string, "\n"); /* alloc_vprintf guaranteed the buffer to be at least one char longer */
395 /* we want this collected in the log + we also want to pick it up as a tcl return
398 * The latter bit isn't precisely neat, but will do for now.
400 LOG_USER_N("%s", string);
401 /* We already printed it above */
402 /* command_output_text(context, string); */
409 int run_command(command_context_t *context, command_t *c, char *words[], int num_words)
412 if (!((context->mode == COMMAND_CONFIG) || (c->mode == COMMAND_ANY) || (c->mode == context->mode)))
414 /* Config commands can not run after the config stage */
415 LOG_ERROR("Command '%s' only runs during configuration stage", c->name);
419 int retval = c->handler(context, c->name, words + start_word + 1, num_words - start_word - 1);
420 if (retval == ERROR_COMMAND_SYNTAX_ERROR)
422 /* Print help for command */
426 /* maximum of two levels :-) */
427 if (c->parent != NULL)
429 t1 = c->parent->name;
433 command_run_linef(context, "help {%s%s%s}", t1, t2, t3);
435 else if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
437 /* just fall through for a shutdown request */
439 else if (retval != ERROR_OK)
441 /* we do not print out an error message because the command *should*
442 * have printed out an error
444 LOG_DEBUG("Command failed with error code %d", retval);
450 int command_run_line(command_context_t *context, char *line)
452 /* all the parent commands have been registered with the interpreter
453 * so, can just evaluate the line as a script and check for
456 /* run the line thru a script engine */
457 int retval = ERROR_FAIL;
459 /* Beware! This code needs to be reentrant. It is also possible
460 * for OpenOCD commands to be invoked directly from Tcl. This would
461 * happen when the Jim Tcl interpreter is provided by eCos for
464 Jim_DeleteAssocData(interp, "context");
465 retcode = Jim_SetAssocData(interp, "context", NULL, context);
466 if (retcode == JIM_OK)
468 /* associated the return value */
469 Jim_DeleteAssocData(interp, "retval");
470 retcode = Jim_SetAssocData(interp, "retval", NULL, &retval);
471 if (retcode == JIM_OK)
473 retcode = Jim_Eval_Named(interp, line, __THIS__FILE__, __LINE__);
475 Jim_DeleteAssocData(interp, "retval");
477 Jim_DeleteAssocData(interp, "context");
479 if (retcode == JIM_ERR) {
480 if (retval != ERROR_COMMAND_CLOSE_CONNECTION)
482 /* We do not print the connection closed error message */
483 Jim_PrintErrorMessage(interp);
485 if (retval == ERROR_OK)
487 /* It wasn't a low level OpenOCD command that failed */
491 } else if (retcode == JIM_EXIT) {
493 /* exit(Jim_GetExitCode(interp)); */
498 result = Jim_GetString(Jim_GetResult(interp), &reslen);
503 for (i = 0; i < reslen; i += 256)
509 strncpy(buff, result + i, chunk);
511 LOG_USER_N("%s", buff);
513 LOG_USER_N("%s", "\n");
520 int command_run_linef(command_context_t *context, const char *format, ...)
522 int retval = ERROR_FAIL;
525 va_start(ap, format);
526 string = alloc_vprintf(format, ap);
529 retval = command_run_line(context, string);
535 void command_set_output_handler(command_context_t* context, int (*output_handler)(struct command_context_s *context, const char* line), void *priv)
537 context->output_handler = output_handler;
538 context->output_handler_priv = priv;
541 command_context_t* copy_command_context(command_context_t* context)
543 command_context_t* copy_context = malloc(sizeof(command_context_t));
545 *copy_context = *context;
550 int command_done(command_context_t *context)
558 /* find full path to file */
559 static int jim_find(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
563 const char *file = Jim_GetString(argv[1], NULL);
564 char *full_path = find_file(file);
565 if (full_path == NULL)
567 Jim_Obj *result = Jim_NewStringObj(interp, full_path, strlen(full_path));
570 Jim_SetResult(interp, result);
574 static int jim_echo(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
578 const char *str = Jim_GetString(argv[1], NULL);
583 static size_t openocd_jim_fwrite(const void *_ptr, size_t size, size_t n, void *cookie)
589 /* make it a char easier to read code */
593 if (ptr == NULL || interp == NULL || nbytes == 0) {
597 /* do we have to chunk it? */
598 if (ptr[nbytes] == 0)
600 /* no it is a C style string */
601 LOG_USER_N("%s", ptr);
604 /* GRR we must chunk - not null terminated */
614 memcpy(chunk, ptr, x);
618 LOG_USER_N("%s", chunk);
626 static size_t openocd_jim_fread(void *ptr, size_t size, size_t n, void *cookie)
628 /* TCL wants to read... tell him no */
632 static int openocd_jim_vfprintf(void *cookie, const char *fmt, va_list ap)
643 cp = alloc_vprintf(fmt, ap);
646 LOG_USER_N("%s", cp);
653 static int openocd_jim_fflush(void *cookie)
655 /* nothing to flush */
659 static char* openocd_jim_fgets(char *s, int size, void *cookie)
666 static int jim_capture(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
671 const char *str = Jim_GetString(argv[1], NULL);
673 /* capture log output and return it */
674 Jim_Obj *tclOutput = Jim_NewStringObj(interp, "", 0);
675 /* a garbage collect can happen, so we need a reference count to this object */
676 Jim_IncrRefCount(tclOutput);
678 log_add_callback(tcl_output, tclOutput);
680 retcode = Jim_Eval_Named(interp, str, __THIS__FILE__, __LINE__);
682 log_remove_callback(tcl_output, tclOutput);
684 /* We dump output into this local variable */
685 Jim_SetResult(interp, tclOutput);
686 Jim_DecrRefCount(interp, tclOutput);
691 command_context_t* command_init()
693 command_context_t* context = malloc(sizeof(command_context_t));
694 extern const char startup_tcl[];
697 context->mode = COMMAND_EXEC;
698 context->commands = NULL;
699 context->current_target = 0;
700 context->output_handler = NULL;
701 context->output_handler_priv = NULL;
705 /* Create an interpreter */
706 interp = Jim_CreateInterp();
707 /* Add all the Jim core commands */
708 Jim_RegisterCoreCommands(interp);
711 #if defined(_MSC_VER)
712 /* WinXX - is generic, the forward
713 * looking problem is this:
717 * "winxx" is generic.
720 #elif defined(__LINUX__)
722 #elif defined(__DARWIN__)
724 #elif defined(__CYGWIN__)
726 #elif defined(__MINGW32__)
731 Jim_SetGlobalVariableStr(interp, "ocd_HOSTOS", Jim_NewStringObj(interp, HostOs , strlen(HostOs)));
733 Jim_CreateCommand(interp, "ocd_find", jim_find, NULL, NULL);
734 Jim_CreateCommand(interp, "echo", jim_echo, NULL, NULL);
735 Jim_CreateCommand(interp, "capture", jim_capture, NULL, NULL);
737 /* Set Jim's STDIO */
738 interp->cookie_stdin = interp;
739 interp->cookie_stdout = interp;
740 interp->cookie_stderr = interp;
741 interp->cb_fwrite = openocd_jim_fwrite;
742 interp->cb_fread = openocd_jim_fread ;
743 interp->cb_vfprintf = openocd_jim_vfprintf;
744 interp->cb_fflush = openocd_jim_fflush;
745 interp->cb_fgets = openocd_jim_fgets;
750 Jim_EventLoopOnLoad(interp);
752 if (Jim_Eval_Named(interp, startup_tcl, "embedded:startup.tcl",1) == JIM_ERR)
754 LOG_ERROR("Failed to run startup.tcl (embedded into OpenOCD compile time)");
755 Jim_PrintErrorMessage(interp);
759 register_command(context, NULL, "sleep", handle_sleep_command,
760 COMMAND_ANY, "<n> [busy] - sleep for n milliseconds. \"busy\" means busy wait");
762 register_command(context, NULL, "fast", handle_fast_command,
763 COMMAND_ANY, "fast <enable/disable> - place at beginning of config files. Sets defaults to fast and dangerous.");
768 int command_context_mode(command_context_t *cmd_ctx, enum command_mode mode)
771 return ERROR_INVALID_ARGUMENTS;
773 cmd_ctx->mode = mode;
777 /* sleep command sleeps for <n> miliseconds
778 * this is useful in target startup scripts
780 int handle_sleep_command(struct command_context_s *cmd_ctx,
781 char *cmd, char **args, int argc)
786 if (strcmp(args[1], "busy") == 0)
789 return ERROR_COMMAND_SYNTAX_ERROR;
791 else if (argc < 1 || argc > 2)
792 return ERROR_COMMAND_SYNTAX_ERROR;
794 unsigned long duration = 0;
795 int retval = parse_ulong(args[0], &duration);
796 if (ERROR_OK != retval)
801 long long then = timeval_ms();
802 while (timeval_ms() - then < (long long)duration)
804 target_call_timer_callbacks_now();
809 busy_sleep(duration);
814 int handle_fast_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
817 return ERROR_COMMAND_SYNTAX_ERROR;
819 fast_and_dangerous = strcmp("enable", args[0]) == 0;
824 void process_jim_events(void)
827 static int recursion = 0;
832 Jim_ProcessEvents (interp, JIM_ALL_EVENTS | JIM_DONT_WAIT);
838 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)
840 Jim_CreateCommand(interp, name, cmd, NULL, NULL);
842 /* FIX!!! it would be prettier to invoke add_help_text...
843 * accumulate help text in Tcl helptext list. */
844 Jim_Obj *helptext = Jim_GetGlobalVariableStr(interp, "ocd_helptext", JIM_ERRMSG);
845 if (Jim_IsShared(helptext))
846 helptext = Jim_DuplicateObj(interp, helptext);
848 Jim_Obj *cmd_entry = Jim_NewListObj(interp, NULL, 0);
850 Jim_Obj *cmd_list = Jim_NewListObj(interp, NULL, 0);
851 Jim_ListAppendElement(interp, cmd_list, Jim_NewStringObj(interp, name, -1));
853 Jim_ListAppendElement(interp, cmd_entry, cmd_list);
854 Jim_ListAppendElement(interp, cmd_entry, Jim_NewStringObj(interp, help, -1));
855 Jim_ListAppendElement(interp, helptext, cmd_entry);
858 /* return global variable long value or 0 upon failure */
859 long jim_global_long(const char *variable)
861 Jim_Obj *objPtr = Jim_GetGlobalVariableStr(interp, variable, JIM_ERRMSG);
863 if (Jim_GetLong(interp, objPtr, &t) == JIM_OK)
870 #define DEFINE_PARSE_NUM_TYPE(name, type, func, min, max) \
871 int parse##name(const char *str, type *ul) \
875 LOG_ERROR("Invalid command argument"); \
876 return ERROR_COMMAND_ARGUMENT_INVALID; \
879 *ul = func(str, &end, 0); \
882 LOG_ERROR("Invalid command argument"); \
883 return ERROR_COMMAND_ARGUMENT_INVALID; \
885 if ((max == *ul) && (ERANGE == errno)) \
887 LOG_ERROR("Argument overflow"); \
888 return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
890 if (min && (min == *ul) && (ERANGE == errno)) \
892 LOG_ERROR("Argument underflow"); \
893 return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
897 DEFINE_PARSE_NUM_TYPE(_ulong, unsigned long , strtoul, 0, ULONG_MAX)
898 DEFINE_PARSE_NUM_TYPE(_ullong, unsigned long long, strtoull, 0, ULLONG_MAX)
899 DEFINE_PARSE_NUM_TYPE(_long, long , strtol, LONG_MIN, LONG_MAX)
900 DEFINE_PARSE_NUM_TYPE(_llong, long long, strtoll, LLONG_MIN, LLONG_MAX)
902 #define DEFINE_PARSE_WRAPPER(name, type, min, max, functype, funcname) \
903 int parse##name(const char *str, type *ul) \
906 int retval = parse##funcname(str, &n); \
907 if (ERROR_OK != retval) \
910 return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
912 return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
917 #define DEFINE_PARSE_ULONG(name, type, min, max) \
918 DEFINE_PARSE_WRAPPER(name, type, min, max, unsigned long, _ulong)
919 DEFINE_PARSE_ULONG(_uint, unsigned, 0, UINT_MAX)
920 DEFINE_PARSE_ULONG(_u32, uint32_t, 0, UINT32_MAX)
921 DEFINE_PARSE_ULONG(_u16, uint16_t, 0, UINT16_MAX)
922 DEFINE_PARSE_ULONG(_u8, uint8_t, 0, UINT8_MAX)
924 #define DEFINE_PARSE_LONG(name, type, min, max) \
925 DEFINE_PARSE_WRAPPER(name, type, min, max, long, _long)
926 DEFINE_PARSE_LONG(_int, int, n < INT_MIN, INT_MAX)
927 DEFINE_PARSE_LONG(_s32, int32_t, n < INT32_MIN, INT32_MAX)
928 DEFINE_PARSE_LONG(_s16, int16_t, n < INT16_MIN, INT16_MAX)
929 DEFINE_PARSE_LONG(_s8, int8_t, n < INT8_MIN, INT8_MAX)