script_debug(): improve types
[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 /* nice short description of source file */
166 #define __THIS__FILE__ "command.c"
167
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)
169 {
170         command_t *c, *p;
171
172         if (!context || !name)
173                 return NULL;
174
175         c = malloc(sizeof(command_t));
176
177         c->name = strdup(name);
178         c->parent = parent;
179         c->children = NULL;
180         c->handler = handler;
181         c->mode = mode;
182         if (!help)
183                 help="";
184         c->next = NULL;
185
186         /* place command in tree */
187         if (parent)
188         {
189                 if (parent->children)
190                 {
191                         /* find last child */
192                         for (p = parent->children; p && p->next; p = p->next);
193                         if (p)
194                                 p->next = c;
195                 }
196                 else
197                 {
198                         parent->children = c;
199                 }
200         }
201         else
202         {
203                 if (context->commands)
204                 {
205                         /* find last command */
206                         for (p = context->commands; p && p->next; p = p->next);
207                         if (p)
208                                 p->next = c;
209                 }
210                 else
211                 {
212                         context->commands = c;
213                 }
214         }
215
216         /* just a placeholder, no handler */
217         if (c->handler == NULL)
218                 return c;
219
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.
222          *
223          * "flash banks" is translated by "unknown" to "flash_banks"
224          * if such a proc exists
225          */
226         /* Print help for command */
227         const char *t1="";
228         const char *t2="";
229         const char *t3="";
230         /* maximum of two levels :-) */
231         if (c->parent != NULL)
232         {
233                 t1 = c->parent->name;
234                 t2="_";
235         }
236         t3 = c->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);
240
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);
245
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);
251
252         Jim_Obj *cmd_list = Jim_NewListObj(interp, NULL, 0);
253
254         /* maximum of two levels :-) */
255         if (c->parent != NULL)
256         {
257                 Jim_ListAppendElement(interp, cmd_list, Jim_NewStringObj(interp, c->parent->name, -1));
258         }
259         Jim_ListAppendElement(interp, cmd_list, Jim_NewStringObj(interp, c->name, -1));
260
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);
264         return c;
265 }
266
267 int unregister_all_commands(command_context_t *context)
268 {
269         command_t *c, *c2;
270
271         if (context == NULL)
272                 return ERROR_OK;
273
274         while (NULL != context->commands)
275         {
276                 c = context->commands;
277
278                 while (NULL != c->children)
279                 {
280                         c2 = c->children;
281                         c->children = c->children->next;
282                         free(c2->name);
283                         c2->name = NULL;
284                         free(c2);
285                         c2 = NULL;
286                 }
287
288                 context->commands = context->commands->next;
289
290                 free(c->name);
291                 c->name = NULL;
292                 free(c);
293                 c = NULL;
294         }
295
296         return ERROR_OK;
297 }
298
299 int unregister_command(command_context_t *context, char *name)
300 {
301         command_t *c, *p = NULL, *c2;
302
303         if ((!context) || (!name))
304                 return ERROR_INVALID_ARGUMENTS;
305
306         /* find command */
307         c = context->commands;
308
309         while (NULL != c)
310         {
311                 if (strcmp(name, c->name) == 0)
312                 {
313                         /* unlink command */
314                         if (p)
315                         {
316                                 p->next = c->next;
317                         }
318                         else
319                         {
320                                 /* first element in command list */
321                                 context->commands = c->next;
322                         }
323
324                         /* unregister children */
325                         while (NULL != c->children)
326                         {
327                                 c2 = c->children;
328                                 c->children = c->children->next;
329                                 free(c2->name);
330                                 c2->name = NULL;
331                                 free(c2);
332                                 c2 = NULL;
333                         }
334
335                         /* delete command */
336                         free(c->name);
337                         c->name = NULL;
338                         free(c);
339                         c = NULL;
340                         return ERROR_OK;
341                 }
342
343                 /* remember the last command for unlinking */
344                 p = c;
345                 c = c->next;
346         }
347
348         return ERROR_OK;
349 }
350
351 void command_output_text(command_context_t *context, const char *data)
352 {
353         if (context && context->output_handler && data) {
354                 context->output_handler(context, data);
355         }
356 }
357
358 void command_print_sameline(command_context_t *context, const char *format, ...)
359 {
360         char *string;
361
362         va_list ap;
363         va_start(ap, format);
364
365         string = alloc_vprintf(format, ap);
366         if (string != NULL)
367         {
368                 /* we want this collected in the log + we also want to pick it up as a tcl return
369                  * value.
370                  *
371                  * The latter bit isn't precisely neat, but will do for now.
372                  */
373                 LOG_USER_N("%s", string);
374                 /* We already printed it above */
375                 /* command_output_text(context, string); */
376                 free(string);
377         }
378
379         va_end(ap);
380 }
381
382 void command_print(command_context_t *context, const char *format, ...)
383 {
384         char *string;
385
386         va_list ap;
387         va_start(ap, format);
388
389         string = alloc_vprintf(format, ap);
390         if (string != NULL)
391         {
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
394                  * value.
395                  *
396                  * The latter bit isn't precisely neat, but will do for now.
397                  */
398                 LOG_USER_N("%s", string);
399                 /* We already printed it above */
400                 /* command_output_text(context, string); */
401                 free(string);
402         }
403
404         va_end(ap);
405 }
406
407 static int run_command(command_context_t *context,
408                 command_t *c, char *words[], unsigned num_words)
409 {
410         int start_word = 0;
411         if (!((context->mode == COMMAND_CONFIG) || (c->mode == COMMAND_ANY) || (c->mode == context->mode)))
412         {
413                 /* Config commands can not run after the config stage */
414                 LOG_ERROR("Command '%s' only runs during configuration stage", c->name);
415                 return ERROR_FAIL;
416         }
417
418         int retval = c->handler(context, c->name, words + start_word + 1, num_words - start_word - 1);
419         if (retval == ERROR_COMMAND_SYNTAX_ERROR)
420         {
421                 /* Print help for command */
422                 const char *t1="";
423                 const char *t2="";
424                 const char *t3="";
425                 /* maximum of two levels :-) */
426                 if (c->parent != NULL)
427                 {
428                         t1 = c->parent->name;
429                         t2=" ";
430                 }
431                 t3 = c->name;
432                 command_run_linef(context, "help {%s%s%s}", t1, t2, t3);
433         }
434         else if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
435         {
436                 /* just fall through for a shutdown request */
437         }
438         else if (retval != ERROR_OK)
439         {
440                 /* we do not print out an error message because the command *should*
441                  * have printed out an error
442                  */
443                 LOG_DEBUG("Command failed with error code %d", retval);
444         }
445
446         return retval;
447 }
448
449 int command_run_line(command_context_t *context, char *line)
450 {
451         /* all the parent commands have been registered with the interpreter
452          * so, can just evaluate the line as a script and check for
453          * results
454          */
455         /* run the line thru a script engine */
456         int retval = ERROR_FAIL;
457         int retcode;
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
461          * instance.
462          */
463         Jim_DeleteAssocData(interp, "context");
464         retcode = Jim_SetAssocData(interp, "context", NULL, context);
465         if (retcode == JIM_OK)
466         {
467                 /* associated the return value */
468                 Jim_DeleteAssocData(interp, "retval");
469                 retcode = Jim_SetAssocData(interp, "retval", NULL, &retval);
470                 if (retcode == JIM_OK)
471                 {
472                         retcode = Jim_Eval_Named(interp, line, __THIS__FILE__, __LINE__);
473
474                         Jim_DeleteAssocData(interp, "retval");
475                 }
476                 Jim_DeleteAssocData(interp, "context");
477         }
478         if (retcode == JIM_ERR) {
479                 if (retval != ERROR_COMMAND_CLOSE_CONNECTION)
480                 {
481                         /* We do not print the connection closed error message */
482                         Jim_PrintErrorMessage(interp);
483                 }
484                 if (retval == ERROR_OK)
485                 {
486                         /* It wasn't a low level OpenOCD command that failed */
487                         return ERROR_FAIL;
488                 }
489                 return retval;
490         } else if (retcode == JIM_EXIT) {
491                 /* ignore. */
492                 /* exit(Jim_GetExitCode(interp)); */
493         } else {
494                 const char *result;
495                 int reslen;
496
497                 result = Jim_GetString(Jim_GetResult(interp), &reslen);
498                 if (reslen > 0)
499                 {
500                         int i;
501                         char buff[256 + 1];
502                         for (i = 0; i < reslen; i += 256)
503                         {
504                                 int chunk;
505                                 chunk = reslen - i;
506                                 if (chunk > 256)
507                                         chunk = 256;
508                                 strncpy(buff, result + i, chunk);
509                                 buff[chunk] = 0;
510                                 LOG_USER_N("%s", buff);
511                         }
512                         LOG_USER_N("%s", "\n");
513                 }
514                 retval = ERROR_OK;
515         }
516         return retval;
517 }
518
519 int command_run_linef(command_context_t *context, const char *format, ...)
520 {
521         int retval = ERROR_FAIL;
522         char *string;
523         va_list ap;
524         va_start(ap, format);
525         string = alloc_vprintf(format, ap);
526         if (string != NULL)
527         {
528                 retval = command_run_line(context, string);
529         }
530         va_end(ap);
531         return retval;
532 }
533
534 void command_set_output_handler(command_context_t* context, int (*output_handler)(struct command_context_s *context, const char* line), void *priv)
535 {
536         context->output_handler = output_handler;
537         context->output_handler_priv = priv;
538 }
539
540 command_context_t* copy_command_context(command_context_t* context)
541 {
542         command_context_t* copy_context = malloc(sizeof(command_context_t));
543
544         *copy_context = *context;
545
546         return copy_context;
547 }
548
549 int command_done(command_context_t *context)
550 {
551         free(context);
552         context = NULL;
553
554         return ERROR_OK;
555 }
556
557 /* find full path to file */
558 static int jim_find(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
559 {
560         if (argc != 2)
561                 return JIM_ERR;
562         const char *file = Jim_GetString(argv[1], NULL);
563         char *full_path = find_file(file);
564         if (full_path == NULL)
565                 return JIM_ERR;
566         Jim_Obj *result = Jim_NewStringObj(interp, full_path, strlen(full_path));
567         free(full_path);
568
569         Jim_SetResult(interp, result);
570         return JIM_OK;
571 }
572
573 static int jim_echo(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
574 {
575         if (argc != 2)
576                 return JIM_ERR;
577         const char *str = Jim_GetString(argv[1], NULL);
578         LOG_USER("%s", str);
579         return JIM_OK;
580 }
581
582 static size_t openocd_jim_fwrite(const void *_ptr, size_t size, size_t n, void *cookie)
583 {
584         size_t nbytes;
585         const char *ptr;
586         Jim_Interp *interp;
587
588         /* make it a char easier to read code */
589         ptr = _ptr;
590         interp = cookie;
591         nbytes = size * n;
592         if (ptr == NULL || interp == NULL || nbytes == 0) {
593                 return 0;
594         }
595
596         /* do we have to chunk it? */
597         if (ptr[nbytes] == 0)
598         {
599                 /* no it is a C style string */
600                 LOG_USER_N("%s", ptr);
601                 return strlen(ptr);
602         }
603         /* GRR we must chunk - not null terminated */
604         while (nbytes) {
605                 char chunk[128 + 1];
606                 int x;
607
608                 x = nbytes;
609                 if (x > 128) {
610                         x = 128;
611                 }
612                 /* copy it */
613                 memcpy(chunk, ptr, x);
614                 /* terminate it */
615                 chunk[n] = 0;
616                 /* output it */
617                 LOG_USER_N("%s", chunk);
618                 ptr += x;
619                 nbytes -= x;
620         }
621
622         return n;
623 }
624
625 static size_t openocd_jim_fread(void *ptr, size_t size, size_t n, void *cookie)
626 {
627         /* TCL wants to read... tell him no */
628         return 0;
629 }
630
631 static int openocd_jim_vfprintf(void *cookie, const char *fmt, va_list ap)
632 {
633         char *cp;
634         int n;
635         Jim_Interp *interp;
636
637         n = -1;
638         interp = cookie;
639         if (interp == NULL)
640                 return n;
641
642         cp = alloc_vprintf(fmt, ap);
643         if (cp)
644         {
645                 LOG_USER_N("%s", cp);
646                 n = strlen(cp);
647                 free(cp);
648         }
649         return n;
650 }
651
652 static int openocd_jim_fflush(void *cookie)
653 {
654         /* nothing to flush */
655         return 0;
656 }
657
658 static char* openocd_jim_fgets(char *s, int size, void *cookie)
659 {
660         /* not supported */
661         errno = ENOTSUP;
662         return NULL;
663 }
664
665 static int jim_capture(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
666 {
667         if (argc != 2)
668                 return JIM_ERR;
669         int retcode;
670         const char *str = Jim_GetString(argv[1], NULL);
671
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);
676
677         log_add_callback(tcl_output, tclOutput);
678
679         retcode = Jim_Eval_Named(interp, str, __THIS__FILE__, __LINE__);
680
681         log_remove_callback(tcl_output, tclOutput);
682
683         /* We dump output into this local variable */
684         Jim_SetResult(interp, tclOutput);
685         Jim_DecrRefCount(interp, tclOutput);
686
687         return retcode;
688 }
689
690 /* sleep command sleeps for <n> miliseconds
691  * this is useful in target startup scripts
692  */
693 static int handle_sleep_command(struct command_context_s *cmd_ctx,
694                 char *cmd, char **args, int argc)
695 {
696         bool busy = false;
697         if (argc == 2)
698         {
699                 if (strcmp(args[1], "busy") == 0)
700                         busy = true;
701                 else
702                         return ERROR_COMMAND_SYNTAX_ERROR;
703         }
704         else if (argc < 1 || argc > 2)
705                 return ERROR_COMMAND_SYNTAX_ERROR;
706
707         unsigned long duration = 0;
708         int retval = parse_ulong(args[0], &duration);
709         if (ERROR_OK != retval)
710                 return retval;
711
712         if (!busy)
713         {
714                 long long then = timeval_ms();
715                 while (timeval_ms() - then < (long long)duration)
716                 {
717                         target_call_timer_callbacks_now();
718                         usleep(1000);
719                 }
720         }
721         else
722                 busy_sleep(duration);
723
724         return ERROR_OK;
725 }
726
727 static int handle_fast_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
728 {
729         if (argc != 1)
730                 return ERROR_COMMAND_SYNTAX_ERROR;
731
732         fast_and_dangerous = strcmp("enable", args[0]) == 0;
733
734         return ERROR_OK;
735 }
736
737
738 command_context_t* command_init()
739 {
740         command_context_t* context = malloc(sizeof(command_context_t));
741         extern const char startup_tcl[];
742         const char *HostOs;
743
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;
749
750 #if !BUILD_ECOSBOARD
751         Jim_InitEmbedded();
752         /* Create an interpreter */
753         interp = Jim_CreateInterp();
754         /* Add all the Jim core commands */
755         Jim_RegisterCoreCommands(interp);
756 #endif
757
758 #if defined(_MSC_VER)
759         /* WinXX - is generic, the forward
760          * looking problem is this:
761          *
762          *   "win32" or "win64"
763          *
764          * "winxx" is generic.
765          */
766         HostOs = "winxx";
767 #elif defined(__linux__)
768         HostOs = "linux";
769 #elif defined(__DARWIN__)
770         HostOs = "darwin";
771 #elif defined(__CYGWIN__)
772         HostOs = "cygwin";
773 #elif defined(__MINGW32__)
774         HostOs = "mingw32";
775 #elif defined(__ECOS)
776         HostOs = "ecos";
777 #else
778 #warn unrecognized host OS...
779         HostOs = "other";
780 #endif
781         Jim_SetGlobalVariableStr(interp, "ocd_HOSTOS",
782                         Jim_NewStringObj(interp, HostOs , strlen(HostOs)));
783
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);
787
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;
797
798 #if !BUILD_ECOSBOARD
799         Jim_EventLoopOnLoad(interp);
800 #endif
801         if (Jim_Eval_Named(interp, startup_tcl, "embedded:startup.tcl",1) == JIM_ERR)
802         {
803                 LOG_ERROR("Failed to run startup.tcl (embedded into OpenOCD)");
804                 Jim_PrintErrorMessage(interp);
805                 exit(-1);
806         }
807
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.");
816
817         return context;
818 }
819
820 int command_context_mode(command_context_t *cmd_ctx, enum command_mode mode)
821 {
822         if (!cmd_ctx)
823                 return ERROR_INVALID_ARGUMENTS;
824
825         cmd_ctx->mode = mode;
826         return ERROR_OK;
827 }
828
829 void process_jim_events(void)
830 {
831 #if !BUILD_ECOSBOARD
832         static int recursion = 0;
833
834         if (!recursion)
835         {
836                 recursion++;
837                 Jim_ProcessEvents (interp, JIM_ALL_EVENTS | JIM_DONT_WAIT);
838                 recursion--;
839         }
840 #endif
841 }
842
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)
844 {
845         Jim_CreateCommand(interp, name, cmd, NULL, NULL);
846
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);
852
853         Jim_Obj *cmd_entry = Jim_NewListObj(interp, NULL, 0);
854
855         Jim_Obj *cmd_list = Jim_NewListObj(interp, NULL, 0);
856         Jim_ListAppendElement(interp, cmd_list, Jim_NewStringObj(interp, name, -1));
857
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);
861 }
862
863 /* return global variable long value or 0 upon failure */
864 long jim_global_long(const char *variable)
865 {
866         Jim_Obj *objPtr = Jim_GetGlobalVariableStr(interp, variable, JIM_ERRMSG);
867         long t;
868         if (Jim_GetLong(interp, objPtr, &t) == JIM_OK)
869         {
870                 return t;
871         }
872         return 0;
873 }
874
875 #define DEFINE_PARSE_NUM_TYPE(name, type, func, min, max) \
876         int parse##name(const char *str, type *ul) \
877         { \
878                 if (!*str) \
879                 { \
880                         LOG_ERROR("Invalid command argument"); \
881                         return ERROR_COMMAND_ARGUMENT_INVALID; \
882                 } \
883                 char *end; \
884                 *ul = func(str, &end, 0); \
885                 if (*end) \
886                 { \
887                         LOG_ERROR("Invalid command argument"); \
888                         return ERROR_COMMAND_ARGUMENT_INVALID; \
889                 } \
890                 if ((max == *ul) && (ERANGE == errno)) \
891                 { \
892                         LOG_ERROR("Argument overflow"); \
893                         return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
894                 } \
895                 if (min && (min == *ul) && (ERANGE == errno)) \
896                 { \
897                         LOG_ERROR("Argument underflow"); \
898                         return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
899                 } \
900                 return ERROR_OK; \
901         }
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)
906
907 #define DEFINE_PARSE_WRAPPER(name, type, min, max, functype, funcname) \
908         int parse##name(const char *str, type *ul) \
909         { \
910                 functype n; \
911                 int retval = parse##funcname(str, &n); \
912                 if (ERROR_OK != retval) \
913                         return retval; \
914                 if (n > max) \
915                         return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
916                 if (min) \
917                         return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
918                 *ul = n; \
919                 return ERROR_OK; \
920         }
921
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)
928
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)