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, const 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, (const char **)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 static Jim_Obj *command_name_list(struct command_s *c)
167 Jim_Obj *cmd_list = c->parent ?
168 command_name_list(c->parent) :
169 Jim_NewListObj(interp, NULL, 0);
170 Jim_ListAppendElement(interp, cmd_list,
171 Jim_NewStringObj(interp, c->name, -1));
176 static void command_helptext_add(Jim_Obj *cmd_list, const char *help)
178 Jim_Obj *cmd_entry = Jim_NewListObj(interp, NULL, 0);
179 Jim_ListAppendElement(interp, cmd_entry, cmd_list);
180 Jim_ListAppendElement(interp, cmd_entry,
181 Jim_NewStringObj(interp, help ? : "", -1));
183 /* accumulate help text in Tcl helptext list. */
184 Jim_Obj *helptext = Jim_GetGlobalVariableStr(interp,
185 "ocd_helptext", JIM_ERRMSG);
186 if (Jim_IsShared(helptext))
187 helptext = Jim_DuplicateObj(interp, helptext);
188 Jim_ListAppendElement(interp, helptext, cmd_entry);
191 /* nice short description of source file */
192 #define __THIS__FILE__ "command.c"
195 * Find a command by name from a list of commands.
196 * @returns The named command if found, or NULL.
198 static struct command_s *command_find(struct command_s **head, const char *name)
201 for (struct command_s *cc = *head; cc; cc = cc->next)
203 if (strcmp(cc->name, name) == 0)
210 * Add the command to the end of linked list.
211 * @returns Returns false if the named command already exists in the list.
212 * Returns true otherwise.
214 static void command_add_child(struct command_s **head, struct command_s *c)
222 struct command_s *cc = *head;
223 while (cc->next) cc = cc->next;
227 command_t* register_command(command_context_t *context,
228 command_t *parent, char *name, command_handler_t handler,
229 enum command_mode mode, char *help)
231 if (!context || !name)
234 struct command_s **head = parent ? &parent->children : &context->commands;
235 struct command_s *c = command_find(head, name);
239 c = malloc(sizeof(command_t));
241 c->name = strdup(name);
244 c->handler = handler;
248 command_add_child(head, c);
250 command_helptext_add(command_name_list(c), help);
252 /* just a placeholder, no handler */
253 if (c->handler == NULL)
256 const char *full_name = command_name(c, '_');
258 const char *ocd_name = alloc_printf("ocd_%s", full_name);
259 Jim_CreateCommand(interp, ocd_name, script_command, c, NULL);
260 free((void *)ocd_name);
262 /* we now need to add an overrideable proc */
263 const char *override_name = alloc_printf("proc %s {args} {"
264 "if {[catch {eval ocd_%s $args}] == 0} "
265 "{return \"\"} else {return -code error}}",
266 full_name, full_name);
267 Jim_Eval_Named(interp, override_name, __THIS__FILE__, __LINE__);
268 free((void *)override_name);
270 free((void *)full_name);
275 int unregister_all_commands(command_context_t *context)
282 while (NULL != context->commands)
284 c = context->commands;
286 while (NULL != c->children)
289 c->children = c->children->next;
296 context->commands = context->commands->next;
307 int unregister_command(command_context_t *context, char *name)
309 command_t *c, *p = NULL, *c2;
311 if ((!context) || (!name))
312 return ERROR_INVALID_ARGUMENTS;
315 c = context->commands;
319 if (strcmp(name, c->name) == 0)
328 /* first element in command list */
329 context->commands = c->next;
332 /* unregister children */
333 while (NULL != c->children)
336 c->children = c->children->next;
351 /* remember the last command for unlinking */
359 void command_output_text(command_context_t *context, const char *data)
361 if (context && context->output_handler && data) {
362 context->output_handler(context, data);
366 void command_print_sameline(command_context_t *context, const char *format, ...)
371 va_start(ap, format);
373 string = alloc_vprintf(format, ap);
376 /* we want this collected in the log + we also want to pick it up as a tcl return
379 * The latter bit isn't precisely neat, but will do for now.
381 LOG_USER_N("%s", string);
382 /* We already printed it above */
383 /* command_output_text(context, string); */
390 void command_print(command_context_t *context, const char *format, ...)
395 va_start(ap, format);
397 string = alloc_vprintf(format, ap);
400 strcat(string, "\n"); /* alloc_vprintf guaranteed the buffer to be at least one char longer */
401 /* we want this collected in the log + we also want to pick it up as a tcl return
404 * The latter bit isn't precisely neat, but will do for now.
406 LOG_USER_N("%s", string);
407 /* We already printed it above */
408 /* command_output_text(context, string); */
415 static char *__command_name(struct command_s *c, char delim, unsigned extra)
418 unsigned len = strlen(c->name);
419 if (NULL == c->parent) {
420 // allocate enough for the name, child names, and '\0'
421 name = malloc(len + extra + 1);
422 strcpy(name, c->name);
424 // parent's extra must include both the space and name
425 name = __command_name(c->parent, delim, 1 + len + extra);
426 char dstr[2] = { delim, 0 };
428 strcat(name, c->name);
432 char *command_name(struct command_s *c, char delim)
434 return __command_name(c, delim, 0);
437 static int run_command(command_context_t *context,
438 command_t *c, const char *words[], unsigned num_words)
441 if (!((context->mode == COMMAND_CONFIG) || (c->mode == COMMAND_ANY) || (c->mode == context->mode)))
443 /* Config commands can not run after the config stage */
444 LOG_ERROR("Command '%s' only runs during configuration stage", c->name);
448 unsigned argc = num_words - start_word - 1;
449 const char **args = words + start_word + 1;
450 int retval = c->handler(context, c->name, args, argc);
451 if (retval == ERROR_COMMAND_SYNTAX_ERROR)
453 /* Print help for command */
454 char *full_name = command_name(c, ' ');
455 if (NULL != full_name) {
456 command_run_linef(context, "help %s", full_name);
461 else if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
463 /* just fall through for a shutdown request */
465 else if (retval != ERROR_OK)
467 /* we do not print out an error message because the command *should*
468 * have printed out an error
470 LOG_DEBUG("Command failed with error code %d", retval);
476 int command_run_line(command_context_t *context, char *line)
478 /* all the parent commands have been registered with the interpreter
479 * so, can just evaluate the line as a script and check for
482 /* run the line thru a script engine */
483 int retval = ERROR_FAIL;
485 /* Beware! This code needs to be reentrant. It is also possible
486 * for OpenOCD commands to be invoked directly from Tcl. This would
487 * happen when the Jim Tcl interpreter is provided by eCos for
490 Jim_DeleteAssocData(interp, "context");
491 retcode = Jim_SetAssocData(interp, "context", NULL, context);
492 if (retcode == JIM_OK)
494 /* associated the return value */
495 Jim_DeleteAssocData(interp, "retval");
496 retcode = Jim_SetAssocData(interp, "retval", NULL, &retval);
497 if (retcode == JIM_OK)
499 retcode = Jim_Eval_Named(interp, line, __THIS__FILE__, __LINE__);
501 Jim_DeleteAssocData(interp, "retval");
503 Jim_DeleteAssocData(interp, "context");
505 if (retcode == JIM_ERR) {
506 if (retval != ERROR_COMMAND_CLOSE_CONNECTION)
508 /* We do not print the connection closed error message */
509 Jim_PrintErrorMessage(interp);
511 if (retval == ERROR_OK)
513 /* It wasn't a low level OpenOCD command that failed */
517 } else if (retcode == JIM_EXIT) {
519 /* exit(Jim_GetExitCode(interp)); */
524 result = Jim_GetString(Jim_GetResult(interp), &reslen);
529 for (i = 0; i < reslen; i += 256)
535 strncpy(buff, result + i, chunk);
537 LOG_USER_N("%s", buff);
539 LOG_USER_N("%s", "\n");
546 int command_run_linef(command_context_t *context, const char *format, ...)
548 int retval = ERROR_FAIL;
551 va_start(ap, format);
552 string = alloc_vprintf(format, ap);
555 retval = command_run_line(context, string);
561 void command_set_output_handler(command_context_t* context,
562 command_output_handler_t output_handler, void *priv)
564 context->output_handler = output_handler;
565 context->output_handler_priv = priv;
568 command_context_t* copy_command_context(command_context_t* context)
570 command_context_t* copy_context = malloc(sizeof(command_context_t));
572 *copy_context = *context;
577 int command_done(command_context_t *context)
585 /* find full path to file */
586 static int jim_find(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
590 const char *file = Jim_GetString(argv[1], NULL);
591 char *full_path = find_file(file);
592 if (full_path == NULL)
594 Jim_Obj *result = Jim_NewStringObj(interp, full_path, strlen(full_path));
597 Jim_SetResult(interp, result);
601 static int jim_echo(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
605 const char *str = Jim_GetString(argv[1], NULL);
610 static size_t openocd_jim_fwrite(const void *_ptr, size_t size, size_t n, void *cookie)
616 /* make it a char easier to read code */
620 if (ptr == NULL || interp == NULL || nbytes == 0) {
624 /* do we have to chunk it? */
625 if (ptr[nbytes] == 0)
627 /* no it is a C style string */
628 LOG_USER_N("%s", ptr);
631 /* GRR we must chunk - not null terminated */
641 memcpy(chunk, ptr, x);
645 LOG_USER_N("%s", chunk);
653 static size_t openocd_jim_fread(void *ptr, size_t size, size_t n, void *cookie)
655 /* TCL wants to read... tell him no */
659 static int openocd_jim_vfprintf(void *cookie, const char *fmt, va_list ap)
670 cp = alloc_vprintf(fmt, ap);
673 LOG_USER_N("%s", cp);
680 static int openocd_jim_fflush(void *cookie)
682 /* nothing to flush */
686 static char* openocd_jim_fgets(char *s, int size, void *cookie)
693 static int jim_capture(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
698 const char *str = Jim_GetString(argv[1], NULL);
700 /* capture log output and return it */
701 Jim_Obj *tclOutput = Jim_NewStringObj(interp, "", 0);
702 /* a garbage collect can happen, so we need a reference count to this object */
703 Jim_IncrRefCount(tclOutput);
705 log_add_callback(tcl_output, tclOutput);
707 retcode = Jim_Eval_Named(interp, str, __THIS__FILE__, __LINE__);
709 log_remove_callback(tcl_output, tclOutput);
711 /* We dump output into this local variable */
712 Jim_SetResult(interp, tclOutput);
713 Jim_DecrRefCount(interp, tclOutput);
718 /* sleep command sleeps for <n> miliseconds
719 * this is useful in target startup scripts
721 COMMAND_HANDLER(handle_sleep_command)
726 if (strcmp(args[1], "busy") == 0)
729 return ERROR_COMMAND_SYNTAX_ERROR;
731 else if (argc < 1 || argc > 2)
732 return ERROR_COMMAND_SYNTAX_ERROR;
734 unsigned long duration = 0;
735 int retval = parse_ulong(args[0], &duration);
736 if (ERROR_OK != retval)
741 long long then = timeval_ms();
742 while (timeval_ms() - then < (long long)duration)
744 target_call_timer_callbacks_now();
749 busy_sleep(duration);
754 COMMAND_HANDLER(handle_fast_command)
757 return ERROR_COMMAND_SYNTAX_ERROR;
759 fast_and_dangerous = strcmp("enable", args[0]) == 0;
765 command_context_t* command_init()
767 command_context_t* context = malloc(sizeof(command_context_t));
768 extern const char startup_tcl[];
771 context->mode = COMMAND_EXEC;
772 context->commands = NULL;
773 context->current_target = 0;
774 context->output_handler = NULL;
775 context->output_handler_priv = NULL;
779 /* Create an interpreter */
780 interp = Jim_CreateInterp();
781 /* Add all the Jim core commands */
782 Jim_RegisterCoreCommands(interp);
785 #if defined(_MSC_VER)
786 /* WinXX - is generic, the forward
787 * looking problem is this:
791 * "winxx" is generic.
794 #elif defined(__linux__)
796 #elif defined(__DARWIN__)
798 #elif defined(__CYGWIN__)
800 #elif defined(__MINGW32__)
802 #elif defined(__ECOS)
805 #warn unrecognized host OS...
808 Jim_SetGlobalVariableStr(interp, "ocd_HOSTOS",
809 Jim_NewStringObj(interp, HostOs , strlen(HostOs)));
811 Jim_CreateCommand(interp, "ocd_find", jim_find, NULL, NULL);
812 Jim_CreateCommand(interp, "echo", jim_echo, NULL, NULL);
813 Jim_CreateCommand(interp, "capture", jim_capture, NULL, NULL);
815 /* Set Jim's STDIO */
816 interp->cookie_stdin = interp;
817 interp->cookie_stdout = interp;
818 interp->cookie_stderr = interp;
819 interp->cb_fwrite = openocd_jim_fwrite;
820 interp->cb_fread = openocd_jim_fread ;
821 interp->cb_vfprintf = openocd_jim_vfprintf;
822 interp->cb_fflush = openocd_jim_fflush;
823 interp->cb_fgets = openocd_jim_fgets;
826 Jim_EventLoopOnLoad(interp);
828 if (Jim_Eval_Named(interp, startup_tcl, "embedded:startup.tcl",1) == JIM_ERR)
830 LOG_ERROR("Failed to run startup.tcl (embedded into OpenOCD)");
831 Jim_PrintErrorMessage(interp);
835 register_command(context, NULL, "sleep",
836 handle_sleep_command, COMMAND_ANY,
837 "<n> [busy] - sleep for n milliseconds. "
838 "\"busy\" means busy wait");
839 register_command(context, NULL, "fast",
840 handle_fast_command, COMMAND_ANY,
841 "fast <enable/disable> - place at beginning of "
842 "config files. Sets defaults to fast and dangerous.");
847 int command_context_mode(command_context_t *cmd_ctx, enum command_mode mode)
850 return ERROR_INVALID_ARGUMENTS;
852 cmd_ctx->mode = mode;
856 void process_jim_events(void)
859 static int recursion = 0;
864 Jim_ProcessEvents (interp, JIM_ALL_EVENTS | JIM_DONT_WAIT);
870 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)
872 Jim_CreateCommand(interp, name, cmd, NULL, NULL);
874 Jim_Obj *cmd_list = Jim_NewListObj(interp, NULL, 0);
875 Jim_ListAppendElement(interp, cmd_list,
876 Jim_NewStringObj(interp, name, -1));
878 command_helptext_add(cmd_list, help);
881 /* return global variable long value or 0 upon failure */
882 long jim_global_long(const char *variable)
884 Jim_Obj *objPtr = Jim_GetGlobalVariableStr(interp, variable, JIM_ERRMSG);
886 if (Jim_GetLong(interp, objPtr, &t) == JIM_OK)
893 #define DEFINE_PARSE_NUM_TYPE(name, type, func, min, max) \
894 int parse##name(const char *str, type *ul) \
898 LOG_ERROR("Invalid command argument"); \
899 return ERROR_COMMAND_ARGUMENT_INVALID; \
902 *ul = func(str, &end, 0); \
905 LOG_ERROR("Invalid command argument"); \
906 return ERROR_COMMAND_ARGUMENT_INVALID; \
908 if ((max == *ul) && (ERANGE == errno)) \
910 LOG_ERROR("Argument overflow"); \
911 return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
913 if (min && (min == *ul) && (ERANGE == errno)) \
915 LOG_ERROR("Argument underflow"); \
916 return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
920 DEFINE_PARSE_NUM_TYPE(_ulong, unsigned long , strtoul, 0, ULONG_MAX)
921 DEFINE_PARSE_NUM_TYPE(_ullong, unsigned long long, strtoull, 0, ULLONG_MAX)
922 DEFINE_PARSE_NUM_TYPE(_long, long , strtol, LONG_MIN, LONG_MAX)
923 DEFINE_PARSE_NUM_TYPE(_llong, long long, strtoll, LLONG_MIN, LLONG_MAX)
925 #define DEFINE_PARSE_WRAPPER(name, type, min, max, functype, funcname) \
926 int parse##name(const char *str, type *ul) \
929 int retval = parse##funcname(str, &n); \
930 if (ERROR_OK != retval) \
933 return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
935 return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
940 #define DEFINE_PARSE_ULONG(name, type, min, max) \
941 DEFINE_PARSE_WRAPPER(name, type, min, max, unsigned long, _ulong)
942 DEFINE_PARSE_ULONG(_uint, unsigned, 0, UINT_MAX)
943 DEFINE_PARSE_ULONG(_u32, uint32_t, 0, UINT32_MAX)
944 DEFINE_PARSE_ULONG(_u16, uint16_t, 0, UINT16_MAX)
945 DEFINE_PARSE_ULONG(_u8, uint8_t, 0, UINT8_MAX)
947 #define DEFINE_PARSE_LONG(name, type, min, max) \
948 DEFINE_PARSE_WRAPPER(name, type, min, max, long, _long)
949 DEFINE_PARSE_LONG(_int, int, n < INT_MIN, INT_MAX)
950 DEFINE_PARSE_LONG(_s32, int32_t, n < INT32_MIN, INT32_MAX)
951 DEFINE_PARSE_LONG(_s16, int16_t, n < INT16_MIN, INT16_MAX)
952 DEFINE_PARSE_LONG(_s8, int8_t, n < INT8_MIN, INT8_MAX)