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 ***************************************************************************/
33 #include "replacements.h"
36 #include "configuration.h"
39 #include "time_support.h"
40 #include "jim-eventloop.h"
50 int fast_and_dangerous = 0;
51 Jim_Interp *interp = NULL;
53 int handle_sleep_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
54 int handle_fast_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
56 int run_command(command_context_t *context, command_t *c, char *words[], int num_words);
58 static void tcl_output(void *privData, const char *file, int line, const char *function, const char *string)
60 Jim_Obj *tclOutput=(Jim_Obj *)privData;
62 Jim_AppendString(interp, tclOutput, string, strlen(string));
65 extern command_context_t *global_cmd_ctx;
68 static int script_command(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
70 /* the private data is stashed in the interp structure */
72 command_context_t *context;
78 target_call_timer_callbacks_now();
79 LOG_USER_N("%s", ""); /* Keep GDB connection alive*/
81 c = interp->cmdPrivData;
82 LOG_DEBUG("script_command - %s", c->name);
84 words = malloc(sizeof(char *) * argc);
85 for (i = 0; i < argc; i++)
88 const char *w=Jim_GetString(argv[i], &len);
91 /* hit an end of line comment */
99 LOG_DEBUG("script_command - %s, argv[%u]=%s", c->name, i, words[i]);
103 /* grab the command context from the associated data */
104 context = Jim_GetAssocData(interp, "context");
107 /* Tcl can invoke commands directly instead of via command_run_line(). This would
108 * happen when the Jim Tcl interpreter is provided by eCos.
110 context = global_cmd_ctx;
113 /* capture log output and return it */
114 Jim_Obj *tclOutput = Jim_NewStringObj(interp, "", 0);
115 /* a garbage collect can happen, so we need a reference count to this object */
116 Jim_IncrRefCount(tclOutput);
118 log_add_callback(tcl_output, tclOutput);
120 retval = run_command(context, c, words, nwords);
122 log_remove_callback(tcl_output, tclOutput);
124 /* We dump output into this local variable */
125 Jim_SetResult(interp, tclOutput);
126 Jim_DecrRefCount(interp, tclOutput);
128 for (i = 0; i < nwords; i++)
132 int *return_retval = Jim_GetAssocData(interp, "retval");
133 if (return_retval != NULL)
135 *return_retval = retval;
138 return (retval==ERROR_OK)?JIM_OK:JIM_ERR;
141 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)
145 if (!context || !name)
148 c = malloc(sizeof(command_t));
150 c->name = strdup(name);
153 c->handler = handler;
159 /* place command in tree */
162 if (parent->children)
164 /* find last child */
165 for (p = parent->children; p && p->next; p = p->next);
171 parent->children = c;
176 if (context->commands)
178 /* find last command */
179 for (p = context->commands; p && p->next; p = p->next);
185 context->commands = c;
189 /* just a placeholder, no handler */
190 if (c->handler==NULL)
193 /* If this is a two level command, e.g. "flash banks", then the
194 * "unknown" proc in startup.tcl must redirect to this command.
196 * "flash banks" is translated by "unknown" to "flash_banks"
197 * if such a proc exists
199 /* Print help for command */
203 /* maximum of two levels :-) */
210 const char *full_name=alloc_printf("ocd_%s%s%s", t1, t2, t3);
211 Jim_CreateCommand(interp, full_name, script_command, c, NULL);
212 free((void *)full_name);
214 /* we now need to add an overrideable proc */
215 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);
216 Jim_Eval_Named(interp, override_name, __FILE__, __LINE__ );
217 free((void *)override_name);
219 /* accumulate help text in Tcl helptext list. */
220 Jim_Obj *helptext=Jim_GetGlobalVariableStr(interp, "ocd_helptext", JIM_ERRMSG);
221 if (Jim_IsShared(helptext))
222 helptext = Jim_DuplicateObj(interp, helptext);
223 Jim_Obj *cmd_entry=Jim_NewListObj(interp, NULL, 0);
225 Jim_Obj *cmd_list=Jim_NewListObj(interp, NULL, 0);
227 /* maximum of two levels :-) */
230 Jim_ListAppendElement(interp, cmd_list, Jim_NewStringObj(interp, c->parent->name, -1));
232 Jim_ListAppendElement(interp, cmd_list, Jim_NewStringObj(interp, c->name, -1));
234 Jim_ListAppendElement(interp, cmd_entry, cmd_list);
235 Jim_ListAppendElement(interp, cmd_entry, Jim_NewStringObj(interp, help, -1));
236 Jim_ListAppendElement(interp, helptext, cmd_entry);
240 int unregister_all_commands(command_context_t *context)
247 while(NULL != context->commands)
249 c = context->commands;
251 while(NULL != c->children)
254 c->children = c->children->next;
261 context->commands = context->commands->next;
272 int unregister_command(command_context_t *context, char *name)
274 command_t *c, *p = NULL, *c2;
276 if ((!context) || (!name))
277 return ERROR_INVALID_ARGUMENTS;
280 for (c = context->commands; c; c = c->next)
282 if (strcmp(name, c->name) == 0)
291 context->commands = c->next;
294 /* unregister children */
297 for (c2 = c->children; c2; c2 = c2->next)
309 /* remember the last command for unlinking */
316 void command_output_text(command_context_t *context, const char *data)
318 if( context && context->output_handler && data ){
319 context->output_handler( context, data );
323 void command_print_n(command_context_t *context, char *format, ...)
328 va_start(ap, format);
330 string = alloc_vprintf(format, ap);
333 /* we want this collected in the log + we also want to pick it up as a tcl return
336 * The latter bit isn't precisely neat, but will do for now.
338 LOG_USER_N("%s", string);
339 // We already printed it above
340 //command_output_text(context, string);
347 void command_print(command_context_t *context, char *format, ...)
352 va_start(ap, format);
354 string = alloc_vprintf(format, ap);
357 strcat(string, "\n"); /* alloc_vprintf guaranteed the buffer to be at least one char longer */
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 int run_command(command_context_t *context, command_t *c, char *words[], int num_words)
375 if (!((context->mode == COMMAND_CONFIG) || (c->mode == COMMAND_ANY) || (c->mode == context->mode) ))
377 /* Config commands can not run after the config stage */
378 LOG_ERROR("Illegal mode for command");
382 int retval = c->handler(context, c->name, words + start_word + 1, num_words - start_word - 1);
383 if (retval == ERROR_COMMAND_SYNTAX_ERROR)
385 /* Print help for command */
389 /* maximum of two levels :-) */
396 command_run_linef(context, "help {%s%s%s}", t1, t2, t3);
398 else if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
400 /* just fall through for a shutdown request */
402 else if (retval != ERROR_OK)
404 /* we do not print out an error message because the command *should*
405 * have printed out an error
407 LOG_DEBUG("Command failed with error code %d", retval);
413 int command_run_line(command_context_t *context, char *line)
415 /* all the parent commands have been registered with the interpreter
416 * so, can just evaluate the line as a script and check for
419 /* run the line thru a script engine */
420 int retval=ERROR_FAIL;
422 /* Beware! This code needs to be reentrant. It is also possible
423 * for OpenOCD commands to be invoked directly from Tcl. This would
424 * happen when the Jim Tcl interpreter is provided by eCos for
427 Jim_DeleteAssocData(interp, "context");
428 retcode = Jim_SetAssocData(interp, "context", NULL, context);
429 if (retcode == JIM_OK)
431 /* associated the return value */
432 Jim_DeleteAssocData(interp, "retval");
433 retcode = Jim_SetAssocData(interp, "retval", NULL, &retval);
434 if (retcode == JIM_OK)
436 retcode = Jim_Eval_Named(interp, line, __FILE__, __LINE__ );
438 Jim_DeleteAssocData(interp, "retval");
440 Jim_DeleteAssocData(interp, "context");
442 if (retcode == JIM_ERR) {
443 if (retval!=ERROR_COMMAND_CLOSE_CONNECTION)
445 /* We do not print the connection closed error message */
446 Jim_PrintErrorMessage(interp);
448 if (retval==ERROR_OK)
450 /* It wasn't a low level OpenOCD command that failed */
454 } else if (retcode == JIM_EXIT) {
456 /* exit(Jim_GetExitCode(interp)); */
461 result = Jim_GetString(Jim_GetResult(interp), &reslen);
465 for (i = 0; i < reslen; i += 256)
471 strncpy(buff, result+i, chunk);
473 LOG_USER_N("%s", buff);
475 LOG_USER_N("%s", "\n");
481 int command_run_linef(command_context_t *context, char *format, ...)
483 int retval=ERROR_FAIL;
486 va_start(ap, format);
487 string = alloc_vprintf(format, ap);
490 retval=command_run_line(context, string);
496 void command_set_output_handler(command_context_t* context, int (*output_handler)(struct command_context_s *context, const char* line), void *priv)
498 context->output_handler = output_handler;
499 context->output_handler_priv = priv;
502 command_context_t* copy_command_context(command_context_t* context)
504 command_context_t* copy_context = malloc(sizeof(command_context_t));
506 *copy_context = *context;
511 int command_done(command_context_t *context)
519 /* find full path to file */
520 static int jim_find(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
524 const char *file = Jim_GetString(argv[1], NULL);
525 char *full_path = find_file(file);
526 if (full_path == NULL)
528 Jim_Obj *result = Jim_NewStringObj(interp, full_path, strlen(full_path));
531 Jim_SetResult(interp, result);
535 static int jim_echo(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
539 const char *str = Jim_GetString(argv[1], NULL);
544 static size_t openocd_jim_fwrite(const void *_ptr, size_t size, size_t n, void *cookie)
550 /* make it a char easier to read code */
554 if (ptr == NULL || interp == NULL || nbytes == 0) {
558 /* do we have to chunk it? */
559 if (ptr[nbytes] == 0)
561 /* no it is a C style string */
562 LOG_USER_N("%s", ptr);
565 /* GRR we must chunk - not null terminated */
575 memcpy(chunk, ptr, x);
579 LOG_USER_N("%s", chunk);
587 static size_t openocd_jim_fread(void *ptr, size_t size, size_t n, void *cookie)
589 /* TCL wants to read... tell him no */
593 static int openocd_jim_vfprintf(void *cookie, const char *fmt, va_list ap)
604 cp = alloc_vprintf(fmt, ap);
607 LOG_USER_N("%s", cp);
614 static int openocd_jim_fflush(void *cookie)
616 /* nothing to flush */
620 static char* openocd_jim_fgets(char *s, int size, void *cookie)
627 command_context_t* command_init()
629 command_context_t* context = malloc(sizeof(command_context_t));
630 extern unsigned const char startup_tcl[];
632 context->mode = COMMAND_EXEC;
633 context->commands = NULL;
634 context->current_target = 0;
635 context->output_handler = NULL;
636 context->output_handler_priv = NULL;
640 /* Create an interpreter */
641 interp = Jim_CreateInterp();
642 /* Add all the Jim core commands */
643 Jim_RegisterCoreCommands(interp);
646 Jim_CreateCommand(interp, "ocd_find", jim_find, NULL, NULL);
647 Jim_CreateCommand(interp, "echo", jim_echo, NULL, NULL);
649 /* Set Jim's STDIO */
650 interp->cookie_stdin = interp;
651 interp->cookie_stdout = interp;
652 interp->cookie_stderr = interp;
653 interp->cb_fwrite = openocd_jim_fwrite;
654 interp->cb_fread = openocd_jim_fread ;
655 interp->cb_vfprintf = openocd_jim_vfprintf;
656 interp->cb_fflush = openocd_jim_fflush;
657 interp->cb_fgets = openocd_jim_fgets;
662 Jim_EventLoopOnLoad(interp);
664 if (Jim_Eval_Named(interp, startup_tcl, "embedded:startup.tcl",1)==JIM_ERR)
666 LOG_ERROR("Failed to run startup.tcl (embedded into OpenOCD compile time)");
667 Jim_PrintErrorMessage(interp);
671 register_command(context, NULL, "sleep", handle_sleep_command,
672 COMMAND_ANY, "sleep for <n> milliseconds");
674 register_command(context, NULL, "fast", handle_fast_command,
675 COMMAND_ANY, "fast <enable/disable> - place at beginning of config files. Sets defaults to fast and dangerous.");
680 int command_context_mode(command_context_t *cmd_ctx, enum command_mode mode)
683 return ERROR_INVALID_ARGUMENTS;
685 cmd_ctx->mode = mode;
689 /* sleep command sleeps for <n> miliseconds
690 * this is useful in target startup scripts
692 int handle_sleep_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
694 unsigned long duration = 0;
698 duration = strtoul(args[0], NULL, 0);
699 alive_sleep(duration);
705 int handle_fast_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
708 return ERROR_COMMAND_SYNTAX_ERROR;
710 fast_and_dangerous = strcmp("enable", args[0])==0;
715 void process_jim_events(void)
718 static int recursion = 0;
723 Jim_ProcessEvents (interp, JIM_ALL_EVENTS|JIM_DONT_WAIT);
729 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)
731 Jim_CreateCommand(interp, name, cmd, NULL, NULL);
733 /* FIX!!! it would be prettier to invoke add_help_text...
734 accumulate help text in Tcl helptext list. */
735 Jim_Obj *helptext=Jim_GetGlobalVariableStr(interp, "ocd_helptext", JIM_ERRMSG);
736 if (Jim_IsShared(helptext))
737 helptext = Jim_DuplicateObj(interp, helptext);
739 Jim_Obj *cmd_entry=Jim_NewListObj(interp, NULL, 0);
741 Jim_Obj *cmd_list=Jim_NewListObj(interp, NULL, 0);
742 Jim_ListAppendElement(interp, cmd_list, Jim_NewStringObj(interp, name, -1));
744 Jim_ListAppendElement(interp, cmd_entry, cmd_list);
745 Jim_ListAppendElement(interp, cmd_entry, Jim_NewStringObj(interp, help, -1));
746 Jim_ListAppendElement(interp, helptext, cmd_entry);