e467be0b2d36ad54565fea51a2f0a5f6e19dd131
[fw/openocd] / src / helper / command.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2007,2008 Ã˜yvind Harboe                                 *
6  *   oyvind.harboe@zylin.com                                               *
7  *                                                                         *
8  *   Copyright (C) 2008, Duane Ellis                                       *
9  *   openocd@duaneeellis.com                                               *
10  *                                                                         *
11  *   part of this file is taken from libcli (libcli.sourceforge.net)       *
12  *   Copyright (C) David Parrish (david@dparrish.com)                      *
13  *                                                                         *
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.                                   *
18  *                                                                         *
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.                          *
23  *                                                                         *
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  ***************************************************************************/
29 #ifdef HAVE_CONFIG_H
30 #include "config.h"
31 #endif
32
33 #if !BUILD_ECOSBOARD
34 /* see Embedder-HOWTO.txt in Jim Tcl project hosted on BerliOS*/
35 #define JIM_EMBEDDED
36 #endif
37
38 // @todo the inclusion of target.h here is a layering violation
39 #include "target.h"
40 #include "command.h"
41 #include "configuration.h"
42 #include "log.h"
43 #include "time_support.h"
44 #include "jim-eventloop.h"
45
46
47 int fast_and_dangerous = 0;
48 Jim_Interp *interp = NULL;
49
50 static int run_command(command_context_t *context,
51                 command_t *c, char *words[], unsigned num_words);
52
53 static void tcl_output(void *privData, const char *file, unsigned line,
54                 const char *function, const char *string)
55 {
56         Jim_Obj *tclOutput = (Jim_Obj *)privData;
57         Jim_AppendString(interp, tclOutput, string, strlen(string));
58 }
59
60 extern command_context_t *global_cmd_ctx;
61
62 void script_debug(Jim_Interp *interp, const char *name,
63                 unsigned argc, Jim_Obj *const *argv)
64 {
65         LOG_DEBUG("command - %s", name);
66         for (unsigned i = 0; i < argc; i++)
67         {
68                 int len;
69                 const char *w = Jim_GetString(argv[i], &len);
70
71                 /* end of line comment? */
72                 if (*w == '#')
73                         break;
74
75                 LOG_DEBUG("%s - argv[%d]=%s", name, i, w);
76         }
77 }
78
79 static int script_command(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
80 {
81         /* the private data is stashed in the interp structure */
82         command_t *c;
83         command_context_t *context;
84         int retval;
85         int i;
86         int nwords;
87         char **words;
88
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.
93          */
94         c = interp->cmdPrivData;
95         if (c == NULL)
96         {
97                 LOG_ERROR("BUG: interp->cmdPrivData == NULL");
98                 return JIM_ERR;
99         }
100         target_call_timer_callbacks_now();
101         LOG_USER_N("%s", ""); /* Keep GDB connection alive*/
102
103         script_debug(interp, c->name, argc, argv);
104
105         words = malloc(sizeof(char *) * argc);
106         for (i = 0; i < argc; i++)
107         {
108                 int len;
109                 const char *w = Jim_GetString(argv[i], &len);
110                 if (*w=='#')
111                 {
112                         /* hit an end of line comment */
113                         break;
114                 }
115                 words[i] = strdup(w);
116                 if (words[i] == NULL)
117                 {
118                         int j;
119                         for (j = 0; j < i; j++)
120                                 free(words[j]);
121                         free(words);
122                         return JIM_ERR;
123                 }
124         }
125         nwords = i;
126
127         /* grab the command context from the associated data */
128         context = Jim_GetAssocData(interp, "context");
129         if (context == NULL)
130         {
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.
133                  */
134                 context = global_cmd_ctx;
135         }
136
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);
141
142         log_add_callback(tcl_output, tclOutput);
143
144         retval = run_command(context, c, words, nwords);
145
146         log_remove_callback(tcl_output, tclOutput);
147
148         /* We dump output into this local variable */
149         Jim_SetResult(interp, tclOutput);
150         Jim_DecrRefCount(interp, tclOutput);
151
152         for (i = 0; i < nwords; i++)
153                 free(words[i]);
154         free(words);
155
156         int *return_retval = Jim_GetAssocData(interp, "retval");
157         if (return_retval != NULL)
158         {
159                 *return_retval = retval;
160         }
161
162         return (retval == ERROR_OK)?JIM_OK:JIM_ERR;
163 }
164
165 static Jim_Obj *command_name_list(struct command_s *c)
166 {
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));
172
173         return cmd_list;
174 }
175
176 static void command_helptext_add(Jim_Obj *cmd_list, const char *help)
177 {
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));
182
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);
189 }
190
191 /* nice short description of source file */
192 #define __THIS__FILE__ "command.c"
193
194 /**
195  * Find a command by name from a list of commands.
196  * @returns The named command if found, or NULL.
197  */
198 static struct command_s *command_find(struct command_s **head, const char *name)
199 {
200         assert(head);
201         for (struct command_s *cc = *head; cc; cc = cc->next)
202         {
203                 if (strcmp(cc->name, name) == 0)
204                         return cc;
205         }
206         return NULL;
207 }
208
209 /**
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.
213  */
214 static void command_add_child(struct command_s **head, struct command_s *c)
215 {
216         assert(head);
217         if (NULL == *head)
218         {
219                 *head = c;
220                 return;
221         }
222         struct command_s *cc = *head;
223         while (cc->next) cc = cc->next;
224         cc->next = c;
225 }
226
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)
230 {
231         if (!context || !name)
232                 return NULL;
233
234         struct command_s **head = parent ? &parent->children : &context->commands;
235         struct command_s *c = command_find(head, name);
236         if (NULL != c)
237                 return c;
238
239         c = malloc(sizeof(command_t));
240
241         c->name = strdup(name);
242         c->parent = parent;
243         c->children = NULL;
244         c->handler = handler;
245         c->mode = mode;
246         c->next = NULL;
247
248         command_add_child(head, c);
249
250         command_helptext_add(command_name_list(c), help);
251
252         /* just a placeholder, no handler */
253         if (c->handler == NULL)
254                 return c;
255
256         const char *full_name = command_name(c, '_');
257
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);
261
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);
269
270         free((void *)full_name);
271
272         return c;
273 }
274
275 int unregister_all_commands(command_context_t *context)
276 {
277         command_t *c, *c2;
278
279         if (context == NULL)
280                 return ERROR_OK;
281
282         while (NULL != context->commands)
283         {
284                 c = context->commands;
285
286                 while (NULL != c->children)
287                 {
288                         c2 = c->children;
289                         c->children = c->children->next;
290                         free(c2->name);
291                         c2->name = NULL;
292                         free(c2);
293                         c2 = NULL;
294                 }
295
296                 context->commands = context->commands->next;
297
298                 free(c->name);
299                 c->name = NULL;
300                 free(c);
301                 c = NULL;
302         }
303
304         return ERROR_OK;
305 }
306
307 int unregister_command(command_context_t *context, char *name)
308 {
309         command_t *c, *p = NULL, *c2;
310
311         if ((!context) || (!name))
312                 return ERROR_INVALID_ARGUMENTS;
313
314         /* find command */
315         c = context->commands;
316
317         while (NULL != c)
318         {
319                 if (strcmp(name, c->name) == 0)
320                 {
321                         /* unlink command */
322                         if (p)
323                         {
324                                 p->next = c->next;
325                         }
326                         else
327                         {
328                                 /* first element in command list */
329                                 context->commands = c->next;
330                         }
331
332                         /* unregister children */
333                         while (NULL != c->children)
334                         {
335                                 c2 = c->children;
336                                 c->children = c->children->next;
337                                 free(c2->name);
338                                 c2->name = NULL;
339                                 free(c2);
340                                 c2 = NULL;
341                         }
342
343                         /* delete command */
344                         free(c->name);
345                         c->name = NULL;
346                         free(c);
347                         c = NULL;
348                         return ERROR_OK;
349                 }
350
351                 /* remember the last command for unlinking */
352                 p = c;
353                 c = c->next;
354         }
355
356         return ERROR_OK;
357 }
358
359 void command_output_text(command_context_t *context, const char *data)
360 {
361         if (context && context->output_handler && data) {
362                 context->output_handler(context, data);
363         }
364 }
365
366 void command_print_sameline(command_context_t *context, const char *format, ...)
367 {
368         char *string;
369
370         va_list ap;
371         va_start(ap, format);
372
373         string = alloc_vprintf(format, ap);
374         if (string != NULL)
375         {
376                 /* we want this collected in the log + we also want to pick it up as a tcl return
377                  * value.
378                  *
379                  * The latter bit isn't precisely neat, but will do for now.
380                  */
381                 LOG_USER_N("%s", string);
382                 /* We already printed it above */
383                 /* command_output_text(context, string); */
384                 free(string);
385         }
386
387         va_end(ap);
388 }
389
390 void command_print(command_context_t *context, const char *format, ...)
391 {
392         char *string;
393
394         va_list ap;
395         va_start(ap, format);
396
397         string = alloc_vprintf(format, ap);
398         if (string != NULL)
399         {
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
402                  * value.
403                  *
404                  * The latter bit isn't precisely neat, but will do for now.
405                  */
406                 LOG_USER_N("%s", string);
407                 /* We already printed it above */
408                 /* command_output_text(context, string); */
409                 free(string);
410         }
411
412         va_end(ap);
413 }
414
415 static char *__command_name(struct command_s *c, char delim, unsigned extra)
416 {
417         char *name;
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);
423         } else {
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 };
427                 strcat(name, dstr);
428                 strcat(name, c->name);
429         }
430         return name;
431 }
432 char *command_name(struct command_s *c, char delim)
433 {
434         return __command_name(c, delim, 0);
435 }
436
437 static int run_command(command_context_t *context,
438                 command_t *c, char *words[], unsigned num_words)
439 {
440         int start_word = 0;
441         if (!((context->mode == COMMAND_CONFIG) || (c->mode == COMMAND_ANY) || (c->mode == context->mode)))
442         {
443                 /* Config commands can not run after the config stage */
444                 LOG_ERROR("Command '%s' only runs during configuration stage", c->name);
445                 return ERROR_FAIL;
446         }
447
448         int retval = c->handler(context, c->name, words + start_word + 1, num_words - start_word - 1);
449         if (retval == ERROR_COMMAND_SYNTAX_ERROR)
450         {
451                 /* Print help for command */
452                 char *full_name = command_name(c, ' ');
453                 if (NULL != full_name) {
454                         command_run_linef(context, "help %s", full_name);
455                         free(full_name);
456                 } else
457                         retval = -ENOMEM;
458         }
459         else if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
460         {
461                 /* just fall through for a shutdown request */
462         }
463         else if (retval != ERROR_OK)
464         {
465                 /* we do not print out an error message because the command *should*
466                  * have printed out an error
467                  */
468                 LOG_DEBUG("Command failed with error code %d", retval);
469         }
470
471         return retval;
472 }
473
474 int command_run_line(command_context_t *context, char *line)
475 {
476         /* all the parent commands have been registered with the interpreter
477          * so, can just evaluate the line as a script and check for
478          * results
479          */
480         /* run the line thru a script engine */
481         int retval = ERROR_FAIL;
482         int retcode;
483         /* Beware! This code needs to be reentrant. It is also possible
484          * for OpenOCD commands to be invoked directly from Tcl. This would
485          * happen when the Jim Tcl interpreter is provided by eCos for
486          * instance.
487          */
488         Jim_DeleteAssocData(interp, "context");
489         retcode = Jim_SetAssocData(interp, "context", NULL, context);
490         if (retcode == JIM_OK)
491         {
492                 /* associated the return value */
493                 Jim_DeleteAssocData(interp, "retval");
494                 retcode = Jim_SetAssocData(interp, "retval", NULL, &retval);
495                 if (retcode == JIM_OK)
496                 {
497                         retcode = Jim_Eval_Named(interp, line, __THIS__FILE__, __LINE__);
498
499                         Jim_DeleteAssocData(interp, "retval");
500                 }
501                 Jim_DeleteAssocData(interp, "context");
502         }
503         if (retcode == JIM_ERR) {
504                 if (retval != ERROR_COMMAND_CLOSE_CONNECTION)
505                 {
506                         /* We do not print the connection closed error message */
507                         Jim_PrintErrorMessage(interp);
508                 }
509                 if (retval == ERROR_OK)
510                 {
511                         /* It wasn't a low level OpenOCD command that failed */
512                         return ERROR_FAIL;
513                 }
514                 return retval;
515         } else if (retcode == JIM_EXIT) {
516                 /* ignore. */
517                 /* exit(Jim_GetExitCode(interp)); */
518         } else {
519                 const char *result;
520                 int reslen;
521
522                 result = Jim_GetString(Jim_GetResult(interp), &reslen);
523                 if (reslen > 0)
524                 {
525                         int i;
526                         char buff[256 + 1];
527                         for (i = 0; i < reslen; i += 256)
528                         {
529                                 int chunk;
530                                 chunk = reslen - i;
531                                 if (chunk > 256)
532                                         chunk = 256;
533                                 strncpy(buff, result + i, chunk);
534                                 buff[chunk] = 0;
535                                 LOG_USER_N("%s", buff);
536                         }
537                         LOG_USER_N("%s", "\n");
538                 }
539                 retval = ERROR_OK;
540         }
541         return retval;
542 }
543
544 int command_run_linef(command_context_t *context, const char *format, ...)
545 {
546         int retval = ERROR_FAIL;
547         char *string;
548         va_list ap;
549         va_start(ap, format);
550         string = alloc_vprintf(format, ap);
551         if (string != NULL)
552         {
553                 retval = command_run_line(context, string);
554         }
555         va_end(ap);
556         return retval;
557 }
558
559 void command_set_output_handler(command_context_t* context,
560                 command_output_handler_t output_handler, void *priv)
561 {
562         context->output_handler = output_handler;
563         context->output_handler_priv = priv;
564 }
565
566 command_context_t* copy_command_context(command_context_t* context)
567 {
568         command_context_t* copy_context = malloc(sizeof(command_context_t));
569
570         *copy_context = *context;
571
572         return copy_context;
573 }
574
575 int command_done(command_context_t *context)
576 {
577         free(context);
578         context = NULL;
579
580         return ERROR_OK;
581 }
582
583 /* find full path to file */
584 static int jim_find(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
585 {
586         if (argc != 2)
587                 return JIM_ERR;
588         const char *file = Jim_GetString(argv[1], NULL);
589         char *full_path = find_file(file);
590         if (full_path == NULL)
591                 return JIM_ERR;
592         Jim_Obj *result = Jim_NewStringObj(interp, full_path, strlen(full_path));
593         free(full_path);
594
595         Jim_SetResult(interp, result);
596         return JIM_OK;
597 }
598
599 static int jim_echo(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
600 {
601         if (argc != 2)
602                 return JIM_ERR;
603         const char *str = Jim_GetString(argv[1], NULL);
604         LOG_USER("%s", str);
605         return JIM_OK;
606 }
607
608 static size_t openocd_jim_fwrite(const void *_ptr, size_t size, size_t n, void *cookie)
609 {
610         size_t nbytes;
611         const char *ptr;
612         Jim_Interp *interp;
613
614         /* make it a char easier to read code */
615         ptr = _ptr;
616         interp = cookie;
617         nbytes = size * n;
618         if (ptr == NULL || interp == NULL || nbytes == 0) {
619                 return 0;
620         }
621
622         /* do we have to chunk it? */
623         if (ptr[nbytes] == 0)
624         {
625                 /* no it is a C style string */
626                 LOG_USER_N("%s", ptr);
627                 return strlen(ptr);
628         }
629         /* GRR we must chunk - not null terminated */
630         while (nbytes) {
631                 char chunk[128 + 1];
632                 int x;
633
634                 x = nbytes;
635                 if (x > 128) {
636                         x = 128;
637                 }
638                 /* copy it */
639                 memcpy(chunk, ptr, x);
640                 /* terminate it */
641                 chunk[n] = 0;
642                 /* output it */
643                 LOG_USER_N("%s", chunk);
644                 ptr += x;
645                 nbytes -= x;
646         }
647
648         return n;
649 }
650
651 static size_t openocd_jim_fread(void *ptr, size_t size, size_t n, void *cookie)
652 {
653         /* TCL wants to read... tell him no */
654         return 0;
655 }
656
657 static int openocd_jim_vfprintf(void *cookie, const char *fmt, va_list ap)
658 {
659         char *cp;
660         int n;
661         Jim_Interp *interp;
662
663         n = -1;
664         interp = cookie;
665         if (interp == NULL)
666                 return n;
667
668         cp = alloc_vprintf(fmt, ap);
669         if (cp)
670         {
671                 LOG_USER_N("%s", cp);
672                 n = strlen(cp);
673                 free(cp);
674         }
675         return n;
676 }
677
678 static int openocd_jim_fflush(void *cookie)
679 {
680         /* nothing to flush */
681         return 0;
682 }
683
684 static char* openocd_jim_fgets(char *s, int size, void *cookie)
685 {
686         /* not supported */
687         errno = ENOTSUP;
688         return NULL;
689 }
690
691 static int jim_capture(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
692 {
693         if (argc != 2)
694                 return JIM_ERR;
695         int retcode;
696         const char *str = Jim_GetString(argv[1], NULL);
697
698         /* capture log output and return it */
699         Jim_Obj *tclOutput = Jim_NewStringObj(interp, "", 0);
700         /* a garbage collect can happen, so we need a reference count to this object */
701         Jim_IncrRefCount(tclOutput);
702
703         log_add_callback(tcl_output, tclOutput);
704
705         retcode = Jim_Eval_Named(interp, str, __THIS__FILE__, __LINE__);
706
707         log_remove_callback(tcl_output, tclOutput);
708
709         /* We dump output into this local variable */
710         Jim_SetResult(interp, tclOutput);
711         Jim_DecrRefCount(interp, tclOutput);
712
713         return retcode;
714 }
715
716 /* sleep command sleeps for <n> miliseconds
717  * this is useful in target startup scripts
718  */
719 static int handle_sleep_command(struct command_context_s *cmd_ctx,
720                 char *cmd, char **args, int argc)
721 {
722         bool busy = false;
723         if (argc == 2)
724         {
725                 if (strcmp(args[1], "busy") == 0)
726                         busy = true;
727                 else
728                         return ERROR_COMMAND_SYNTAX_ERROR;
729         }
730         else if (argc < 1 || argc > 2)
731                 return ERROR_COMMAND_SYNTAX_ERROR;
732
733         unsigned long duration = 0;
734         int retval = parse_ulong(args[0], &duration);
735         if (ERROR_OK != retval)
736                 return retval;
737
738         if (!busy)
739         {
740                 long long then = timeval_ms();
741                 while (timeval_ms() - then < (long long)duration)
742                 {
743                         target_call_timer_callbacks_now();
744                         usleep(1000);
745                 }
746         }
747         else
748                 busy_sleep(duration);
749
750         return ERROR_OK;
751 }
752
753 static int handle_fast_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
754 {
755         if (argc != 1)
756                 return ERROR_COMMAND_SYNTAX_ERROR;
757
758         fast_and_dangerous = strcmp("enable", args[0]) == 0;
759
760         return ERROR_OK;
761 }
762
763
764 command_context_t* command_init()
765 {
766         command_context_t* context = malloc(sizeof(command_context_t));
767         extern const char startup_tcl[];
768         const char *HostOs;
769
770         context->mode = COMMAND_EXEC;
771         context->commands = NULL;
772         context->current_target = 0;
773         context->output_handler = NULL;
774         context->output_handler_priv = NULL;
775
776 #if !BUILD_ECOSBOARD
777         Jim_InitEmbedded();
778         /* Create an interpreter */
779         interp = Jim_CreateInterp();
780         /* Add all the Jim core commands */
781         Jim_RegisterCoreCommands(interp);
782 #endif
783
784 #if defined(_MSC_VER)
785         /* WinXX - is generic, the forward
786          * looking problem is this:
787          *
788          *   "win32" or "win64"
789          *
790          * "winxx" is generic.
791          */
792         HostOs = "winxx";
793 #elif defined(__linux__)
794         HostOs = "linux";
795 #elif defined(__DARWIN__)
796         HostOs = "darwin";
797 #elif defined(__CYGWIN__)
798         HostOs = "cygwin";
799 #elif defined(__MINGW32__)
800         HostOs = "mingw32";
801 #elif defined(__ECOS)
802         HostOs = "ecos";
803 #else
804 #warn unrecognized host OS...
805         HostOs = "other";
806 #endif
807         Jim_SetGlobalVariableStr(interp, "ocd_HOSTOS",
808                         Jim_NewStringObj(interp, HostOs , strlen(HostOs)));
809
810         Jim_CreateCommand(interp, "ocd_find", jim_find, NULL, NULL);
811         Jim_CreateCommand(interp, "echo", jim_echo, NULL, NULL);
812         Jim_CreateCommand(interp, "capture", jim_capture, NULL, NULL);
813
814         /* Set Jim's STDIO */
815         interp->cookie_stdin = interp;
816         interp->cookie_stdout = interp;
817         interp->cookie_stderr = interp;
818         interp->cb_fwrite = openocd_jim_fwrite;
819         interp->cb_fread = openocd_jim_fread ;
820         interp->cb_vfprintf = openocd_jim_vfprintf;
821         interp->cb_fflush = openocd_jim_fflush;
822         interp->cb_fgets = openocd_jim_fgets;
823
824 #if !BUILD_ECOSBOARD
825         Jim_EventLoopOnLoad(interp);
826 #endif
827         if (Jim_Eval_Named(interp, startup_tcl, "embedded:startup.tcl",1) == JIM_ERR)
828         {
829                 LOG_ERROR("Failed to run startup.tcl (embedded into OpenOCD)");
830                 Jim_PrintErrorMessage(interp);
831                 exit(-1);
832         }
833
834         register_command(context, NULL, "sleep",
835                         handle_sleep_command, COMMAND_ANY,
836                         "<n> [busy] - sleep for n milliseconds. "
837                         "\"busy\" means busy wait");
838         register_command(context, NULL, "fast",
839                         handle_fast_command, COMMAND_ANY,
840                         "fast <enable/disable> - place at beginning of "
841                         "config files. Sets defaults to fast and dangerous.");
842
843         return context;
844 }
845
846 int command_context_mode(command_context_t *cmd_ctx, enum command_mode mode)
847 {
848         if (!cmd_ctx)
849                 return ERROR_INVALID_ARGUMENTS;
850
851         cmd_ctx->mode = mode;
852         return ERROR_OK;
853 }
854
855 void process_jim_events(void)
856 {
857 #if !BUILD_ECOSBOARD
858         static int recursion = 0;
859
860         if (!recursion)
861         {
862                 recursion++;
863                 Jim_ProcessEvents (interp, JIM_ALL_EVENTS | JIM_DONT_WAIT);
864                 recursion--;
865         }
866 #endif
867 }
868
869 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)
870 {
871         Jim_CreateCommand(interp, name, cmd, NULL, NULL);
872
873         Jim_Obj *cmd_list = Jim_NewListObj(interp, NULL, 0);
874         Jim_ListAppendElement(interp, cmd_list,
875                         Jim_NewStringObj(interp, name, -1));
876
877         command_helptext_add(cmd_list, help);
878 }
879
880 /* return global variable long value or 0 upon failure */
881 long jim_global_long(const char *variable)
882 {
883         Jim_Obj *objPtr = Jim_GetGlobalVariableStr(interp, variable, JIM_ERRMSG);
884         long t;
885         if (Jim_GetLong(interp, objPtr, &t) == JIM_OK)
886         {
887                 return t;
888         }
889         return 0;
890 }
891
892 #define DEFINE_PARSE_NUM_TYPE(name, type, func, min, max) \
893         int parse##name(const char *str, type *ul) \
894         { \
895                 if (!*str) \
896                 { \
897                         LOG_ERROR("Invalid command argument"); \
898                         return ERROR_COMMAND_ARGUMENT_INVALID; \
899                 } \
900                 char *end; \
901                 *ul = func(str, &end, 0); \
902                 if (*end) \
903                 { \
904                         LOG_ERROR("Invalid command argument"); \
905                         return ERROR_COMMAND_ARGUMENT_INVALID; \
906                 } \
907                 if ((max == *ul) && (ERANGE == errno)) \
908                 { \
909                         LOG_ERROR("Argument overflow"); \
910                         return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
911                 } \
912                 if (min && (min == *ul) && (ERANGE == errno)) \
913                 { \
914                         LOG_ERROR("Argument underflow"); \
915                         return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
916                 } \
917                 return ERROR_OK; \
918         }
919 DEFINE_PARSE_NUM_TYPE(_ulong, unsigned long , strtoul, 0, ULONG_MAX)
920 DEFINE_PARSE_NUM_TYPE(_ullong, unsigned long long, strtoull, 0, ULLONG_MAX)
921 DEFINE_PARSE_NUM_TYPE(_long, long , strtol, LONG_MIN, LONG_MAX)
922 DEFINE_PARSE_NUM_TYPE(_llong, long long, strtoll, LLONG_MIN, LLONG_MAX)
923
924 #define DEFINE_PARSE_WRAPPER(name, type, min, max, functype, funcname) \
925         int parse##name(const char *str, type *ul) \
926         { \
927                 functype n; \
928                 int retval = parse##funcname(str, &n); \
929                 if (ERROR_OK != retval) \
930                         return retval; \
931                 if (n > max) \
932                         return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
933                 if (min) \
934                         return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
935                 *ul = n; \
936                 return ERROR_OK; \
937         }
938
939 #define DEFINE_PARSE_ULONG(name, type, min, max) \
940         DEFINE_PARSE_WRAPPER(name, type, min, max, unsigned long, _ulong)
941 DEFINE_PARSE_ULONG(_uint, unsigned, 0, UINT_MAX)
942 DEFINE_PARSE_ULONG(_u32, uint32_t, 0, UINT32_MAX)
943 DEFINE_PARSE_ULONG(_u16, uint16_t, 0, UINT16_MAX)
944 DEFINE_PARSE_ULONG(_u8, uint8_t, 0, UINT8_MAX)
945
946 #define DEFINE_PARSE_LONG(name, type, min, max) \
947         DEFINE_PARSE_WRAPPER(name, type, min, max, long, _long)
948 DEFINE_PARSE_LONG(_int, int, n < INT_MIN, INT_MAX)
949 DEFINE_PARSE_LONG(_s32, int32_t, n < INT32_MIN, INT32_MAX)
950 DEFINE_PARSE_LONG(_s16, int16_t, n < INT16_MIN, INT16_MAX)
951 DEFINE_PARSE_LONG(_s8, int8_t, n < INT8_MIN, INT8_MAX)