]> git.sur5r.net Git - openocd/blob - src/target/target.c
- remove target specific variant and use target->variant member
[openocd] / src / target / target.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  *   Copyright (C) 2008 by Spencer Oliver                                  *
12  *   spen@spen-soft.co.uk                                                  *
13  *                                                                         *
14  *   Copyright (C) 2008 by Rick Altherr                                    *
15  *   kc8apf@kc8apf.net>                                                    *
16  *                                                                         *
17  *   This program is free software; you can redistribute it and/or modify  *
18  *   it under the terms of the GNU General Public License as published by  *
19  *   the Free Software Foundation; either version 2 of the License, or     *
20  *   (at your option) any later version.                                   *
21  *                                                                         *
22  *   This program is distributed in the hope that it will be useful,       *
23  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
24  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
25  *   GNU General Public License for more details.                          *
26  *                                                                         *
27  *   You should have received a copy of the GNU General Public License     *
28  *   along with this program; if not, write to the                         *
29  *   Free Software Foundation, Inc.,                                       *
30  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
31  ***************************************************************************/
32 #ifdef HAVE_CONFIG_H
33 #include "config.h"
34 #endif
35
36 #include "replacements.h"
37 #include "target.h"
38 #include "target_request.h"
39
40 #include "log.h"
41 #include "configuration.h"
42 #include "binarybuffer.h"
43 #include "jtag.h"
44
45 #include <string.h>
46 #include <stdlib.h>
47 #include <inttypes.h>
48
49 #include <sys/types.h>
50 #include <sys/stat.h>
51 #include <unistd.h>
52 #include <errno.h>
53
54 #include <sys/time.h>
55 #include <time.h>
56
57 #include <time_support.h>
58
59 #include <fileio.h>
60 #include <image.h>
61
62 int cli_target_callback_event_handler(struct target_s *target, enum target_event event, void *priv);
63
64 int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
65
66 int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
67 int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
68 int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
69 int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
70 int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
71 int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
72 int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
73 int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
74 int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
75 int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
76 int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
77 int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
78 int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
79 int handle_bp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
80 int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
81 int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
82 int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
83 int handle_virt2phys_command(command_context_t *cmd_ctx, char *cmd, char **args, int argc);
84 int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
85 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
86 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
87 static int jim_target( Jim_Interp *interp, int argc, Jim_Obj *const *argv);
88
89 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv);
90 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv);
91
92 /* targets */
93 extern target_type_t arm7tdmi_target;
94 extern target_type_t arm720t_target;
95 extern target_type_t arm9tdmi_target;
96 extern target_type_t arm920t_target;
97 extern target_type_t arm966e_target;
98 extern target_type_t arm926ejs_target;
99 extern target_type_t feroceon_target;
100 extern target_type_t xscale_target;
101 extern target_type_t cortexm3_target;
102 extern target_type_t arm11_target;
103 extern target_type_t mips_m4k_target;
104
105 target_type_t *target_types[] =
106 {
107         &arm7tdmi_target,
108         &arm9tdmi_target,
109         &arm920t_target,
110         &arm720t_target,
111         &arm966e_target,
112         &arm926ejs_target,
113         &feroceon_target,
114         &xscale_target,
115         &cortexm3_target,
116         &arm11_target,
117         &mips_m4k_target,
118         NULL,
119 };
120
121 target_t *all_targets = NULL;
122 target_event_callback_t *target_event_callbacks = NULL;
123 target_timer_callback_t *target_timer_callbacks = NULL;
124
125 const Jim_Nvp nvp_assert[] = {
126         { .name = "assert", NVP_ASSERT },
127         { .name = "deassert", NVP_DEASSERT },
128         { .name = "T", NVP_ASSERT },
129         { .name = "F", NVP_DEASSERT },
130         { .name = "t", NVP_ASSERT },
131         { .name = "f", NVP_DEASSERT },
132         { .name = NULL, .value = -1 }
133 };
134
135 const Jim_Nvp nvp_error_target[] = {
136         { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
137         { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
138         { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
139         { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
140         { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
141         { .value = ERROR_TARGET_UNALIGNED_ACCESS   , .name = "err-unaligned-access" },
142         { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
143         { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
144         { .value = ERROR_TARGET_TRANSLATION_FAULT  , .name = "err-translation-fault" },
145         { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
146         { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
147         { .value = -1, .name = NULL }
148 };
149
150 const char *target_strerror_safe( int err )
151 {
152         const Jim_Nvp *n;
153
154         n = Jim_Nvp_value2name_simple( nvp_error_target, err );
155         if( n->name == NULL ){
156                 return "unknown";
157         } else {
158                 return n->name;
159         }
160 }
161
162 const Jim_Nvp nvp_target_event[] = {
163         { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
164         { .value = TARGET_EVENT_OLD_pre_resume         , .name = "old-pre_resume" },
165
166         { .value = TARGET_EVENT_EARLY_HALTED, .name = "early-halted" },
167         { .value = TARGET_EVENT_HALTED, .name = "halted" },
168         { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
169         { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
170         { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
171
172         { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
173         { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
174
175         /* historical name */
176
177         { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
178
179         { .value = TARGET_EVENT_RESET_ASSERT_PRE,    .name = "reset-assert-pre" },
180         { .value = TARGET_EVENT_RESET_ASSERT_POST,   .name = "reset-assert-post" },
181         { .value = TARGET_EVENT_RESET_DEASSERT_PRE,  .name = "reset-deassert-pre" },
182         { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
183         { .value = TARGET_EVENT_RESET_HALT_PRE,      .name = "reset-halt-pre" },
184         { .value = TARGET_EVENT_RESET_HALT_POST,     .name = "reset-halt-post" },
185         { .value = TARGET_EVENT_RESET_WAIT_PRE,      .name = "reset-wait-pre" },
186         { .value = TARGET_EVENT_RESET_WAIT_POST,     .name = "reset-wait-post" },
187         { .value = TARGET_EVENT_RESET_INIT , .name = "reset-init" },
188         { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
189
190         { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
191         { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
192
193         { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
194         { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
195
196         { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
197         { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
198
199         { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
200         { .value = TARGET_EVENT_GDB_FLASH_WRITE_END  , .name = "gdb-flash-write-end"   },
201
202         { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
203         { .value = TARGET_EVENT_GDB_FLASH_ERASE_END  , .name = "gdb-flash-erase-end" },
204
205         { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
206         { .value = TARGET_EVENT_RESUMED     , .name = "resume-ok" },
207         { .value = TARGET_EVENT_RESUME_END  , .name = "resume-end" },
208
209         { .name = NULL, .value = -1 }
210 };
211
212 const Jim_Nvp nvp_target_state[] = {
213         { .name = "unknown", .value = TARGET_UNKNOWN },
214         { .name = "running", .value = TARGET_RUNNING },
215         { .name = "halted",  .value = TARGET_HALTED },
216         { .name = "reset",   .value = TARGET_RESET },
217         { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
218         { .name = NULL, .value = -1 },
219 };
220
221 const Jim_Nvp nvp_target_debug_reason [] = {
222         { .name = "debug-request"            , .value = DBG_REASON_DBGRQ },
223         { .name = "breakpoint"               , .value = DBG_REASON_BREAKPOINT },
224         { .name = "watchpoint"               , .value = DBG_REASON_WATCHPOINT },
225         { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
226         { .name = "single-step"              , .value = DBG_REASON_SINGLESTEP },
227         { .name = "target-not-halted"        , .value = DBG_REASON_NOTHALTED  },
228         { .name = "undefined"                , .value = DBG_REASON_UNDEFINED },
229         { .name = NULL, .value = -1 },
230 };
231
232
233 const Jim_Nvp nvp_target_endian[] = {
234         { .name = "big",    .value = TARGET_BIG_ENDIAN },
235         { .name = "little", .value = TARGET_LITTLE_ENDIAN },
236         { .name = "be",     .value = TARGET_BIG_ENDIAN },
237         { .name = "le",     .value = TARGET_LITTLE_ENDIAN },
238         { .name = NULL,     .value = -1 },
239 };
240
241 const Jim_Nvp nvp_reset_modes[] = {
242         { .name = "unknown", .value = RESET_UNKNOWN },
243         { .name = "run"    , .value = RESET_RUN },
244         { .name = "halt"   , .value = RESET_HALT },
245         { .name = "init"   , .value = RESET_INIT },
246         { .name = NULL     , .value = -1 },
247 };
248
249 static int
250 max_target_number( void )
251 {
252         target_t *t;
253         int x;
254
255         x = -1;
256         t = all_targets;
257         while( t ){
258                 if( x < t->target_number ){
259                         x = (t->target_number)+1;
260                 }
261                 t = t->next;
262         }
263         return x;
264 }
265
266 /* determine the number of the new target */
267 static int
268 new_target_number( void )
269 {
270         target_t *t;
271         int x;
272
273         /* number is 0 based */
274         x = -1;
275         t = all_targets;
276         while(t){
277                 if( x < t->target_number ){
278                         x = t->target_number;
279                 }
280                 t = t->next;
281         }
282         return x+1;
283 }
284
285 static int target_continous_poll = 1;
286
287 /* read a u32 from a buffer in target memory endianness */
288 u32 target_buffer_get_u32(target_t *target, u8 *buffer)
289 {
290         if (target->endianness == TARGET_LITTLE_ENDIAN)
291                 return le_to_h_u32(buffer);
292         else
293                 return be_to_h_u32(buffer);
294 }
295
296 /* read a u16 from a buffer in target memory endianness */
297 u16 target_buffer_get_u16(target_t *target, u8 *buffer)
298 {
299         if (target->endianness == TARGET_LITTLE_ENDIAN)
300                 return le_to_h_u16(buffer);
301         else
302                 return be_to_h_u16(buffer);
303 }
304
305 /* read a u8 from a buffer in target memory endianness */
306 u8 target_buffer_get_u8(target_t *target, u8 *buffer)
307 {
308         return *buffer & 0x0ff;
309 }
310
311 /* write a u32 to a buffer in target memory endianness */
312 void target_buffer_set_u32(target_t *target, u8 *buffer, u32 value)
313 {
314         if (target->endianness == TARGET_LITTLE_ENDIAN)
315                 h_u32_to_le(buffer, value);
316         else
317                 h_u32_to_be(buffer, value);
318 }
319
320 /* write a u16 to a buffer in target memory endianness */
321 void target_buffer_set_u16(target_t *target, u8 *buffer, u16 value)
322 {
323         if (target->endianness == TARGET_LITTLE_ENDIAN)
324                 h_u16_to_le(buffer, value);
325         else
326                 h_u16_to_be(buffer, value);
327 }
328
329 /* write a u8 to a buffer in target memory endianness */
330 void target_buffer_set_u8(target_t *target, u8 *buffer, u8 value)
331 {
332         *buffer = value;
333 }
334
335 /* returns a pointer to the n-th configured target */
336 target_t* get_target_by_num(int num)
337 {
338         target_t *target = all_targets;
339
340         while (target){
341                 if( target->target_number == num ){
342                         return target;
343                 }
344                 target = target->next;
345         }
346
347         return NULL;
348 }
349
350 int get_num_by_target(target_t *query_target)
351 {
352         return query_target->target_number;
353 }
354
355 target_t* get_current_target(command_context_t *cmd_ctx)
356 {
357         target_t *target = get_target_by_num(cmd_ctx->current_target);
358
359         if (target == NULL)
360         {
361                 LOG_ERROR("BUG: current_target out of bounds");
362                 exit(-1);
363         }
364
365         return target;
366 }
367
368 int target_poll(struct target_s *target)
369 {
370         /* We can't poll until after examine */
371         if (!target->type->examined)
372         {
373                 /* Fail silently lest we pollute the log */
374                 return ERROR_FAIL;
375         }
376         return target->type->poll(target);
377 }
378
379 int target_halt(struct target_s *target)
380 {
381         /* We can't poll until after examine */
382         if (!target->type->examined)
383         {
384                 LOG_ERROR("Target not examined yet");
385                 return ERROR_FAIL;
386         }
387         return target->type->halt(target);
388 }
389
390 int target_resume(struct target_s *target, int current, u32 address, int handle_breakpoints, int debug_execution)
391 {
392         int retval;
393
394         /* We can't poll until after examine */
395         if (!target->type->examined)
396         {
397                 LOG_ERROR("Target not examined yet");
398                 return ERROR_FAIL;
399         }
400
401         /* note that resume *must* be asynchronous. The CPU can halt before we poll. The CPU can
402          * even halt at the current PC as a result of a software breakpoint being inserted by (a bug?)
403          * the application.
404          */
405         if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
406                 return retval;
407
408         return retval;
409 }
410
411 int target_process_reset(struct command_context_s *cmd_ctx, enum target_reset_mode reset_mode)
412 {
413         char buf[100];
414         int retval;
415         Jim_Nvp *n;
416         n = Jim_Nvp_value2name_simple( nvp_reset_modes, reset_mode );
417         if( n->name == NULL ){
418                 LOG_ERROR("invalid reset mode");
419                 return ERROR_FAIL;
420         }
421
422         sprintf( buf, "ocd_process_reset %s", n->name );
423         retval = Jim_Eval( interp, buf );
424
425         if(retval != JIM_OK) {
426                 Jim_PrintErrorMessage(interp);
427                 return ERROR_FAIL;
428         }
429
430         /* We want any events to be processed before the prompt */
431         retval = target_call_timer_callbacks_now();
432
433         return retval;
434 }
435
436 static int default_virt2phys(struct target_s *target, u32 virtual, u32 *physical)
437 {
438         *physical = virtual;
439         return ERROR_OK;
440 }
441
442 static int default_mmu(struct target_s *target, int *enabled)
443 {
444         *enabled = 0;
445         return ERROR_OK;
446 }
447
448 static int default_examine(struct target_s *target)
449 {
450         target->type->examined = 1;
451         return ERROR_OK;
452 }
453
454 /* Targets that correctly implement init+examine, i.e.
455  * no communication with target during init:
456  *
457  * XScale
458  */
459 int target_examine(void)
460 {
461         int retval = ERROR_OK;
462         target_t *target = all_targets;
463         while (target)
464         {
465                 if ((retval = target->type->examine(target))!=ERROR_OK)
466                         return retval;
467                 target = target->next;
468         }
469         return retval;
470 }
471
472 static int target_write_memory_imp(struct target_s *target, u32 address, u32 size, u32 count, u8 *buffer)
473 {
474         if (!target->type->examined)
475         {
476                 LOG_ERROR("Target not examined yet");
477                 return ERROR_FAIL;
478         }
479         return target->type->write_memory_imp(target, address, size, count, buffer);
480 }
481
482 static int target_read_memory_imp(struct target_s *target, u32 address, u32 size, u32 count, u8 *buffer)
483 {
484         if (!target->type->examined)
485         {
486                 LOG_ERROR("Target not examined yet");
487                 return ERROR_FAIL;
488         }
489         return target->type->read_memory_imp(target, address, size, count, buffer);
490 }
491
492 static int target_soft_reset_halt_imp(struct target_s *target)
493 {
494         if (!target->type->examined)
495         {
496                 LOG_ERROR("Target not examined yet");
497                 return ERROR_FAIL;
498         }
499         return target->type->soft_reset_halt_imp(target);
500 }
501
502 static int target_run_algorithm_imp(struct target_s *target, int num_mem_params, mem_param_t *mem_params, int num_reg_params, reg_param_t *reg_param, u32 entry_point, u32 exit_point, int timeout_ms, void *arch_info)
503 {
504         if (!target->type->examined)
505         {
506                 LOG_ERROR("Target not examined yet");
507                 return ERROR_FAIL;
508         }
509         return target->type->run_algorithm_imp(target, num_mem_params, mem_params, num_reg_params, reg_param, entry_point, exit_point, timeout_ms, arch_info);
510 }
511
512 int target_init(struct command_context_s *cmd_ctx)
513 {
514         target_t *target = all_targets;
515         int retval;
516
517         while (target)
518         {
519                 target->type->examined = 0;
520                 if (target->type->examine == NULL)
521                 {
522                         target->type->examine = default_examine;
523                 }
524
525                 if ((retval = target->type->init_target(cmd_ctx, target)) != ERROR_OK)
526                 {
527                         LOG_ERROR("target '%s' init failed", target->type->name);
528                         return retval;
529                 }
530
531                 /* Set up default functions if none are provided by target */
532                 if (target->type->virt2phys == NULL)
533                 {
534                         target->type->virt2phys = default_virt2phys;
535                 }
536                 target->type->virt2phys = default_virt2phys;
537                 /* a non-invasive way(in terms of patches) to add some code that
538                  * runs before the type->write/read_memory implementation
539                  */
540                 target->type->write_memory_imp = target->type->write_memory;
541                 target->type->write_memory = target_write_memory_imp;
542                 target->type->read_memory_imp = target->type->read_memory;
543                 target->type->read_memory = target_read_memory_imp;
544                 target->type->soft_reset_halt_imp = target->type->soft_reset_halt;
545                 target->type->soft_reset_halt = target_soft_reset_halt_imp;
546                 target->type->run_algorithm_imp = target->type->run_algorithm;
547                 target->type->run_algorithm = target_run_algorithm_imp;
548
549                 if (target->type->mmu == NULL)
550                 {
551                         target->type->mmu = default_mmu;
552                 }
553                 target = target->next;
554         }
555
556         if (all_targets)
557         {
558                 if((retval = target_register_user_commands(cmd_ctx)) != ERROR_OK)
559                         return retval;
560                 if((retval = target_register_timer_callback(handle_target, 100, 1, NULL)) != ERROR_OK)
561                         return retval;
562         }
563
564         return ERROR_OK;
565 }
566
567 int target_register_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
568 {
569         target_event_callback_t **callbacks_p = &target_event_callbacks;
570
571         if (callback == NULL)
572         {
573                 return ERROR_INVALID_ARGUMENTS;
574         }
575
576         if (*callbacks_p)
577         {
578                 while ((*callbacks_p)->next)
579                         callbacks_p = &((*callbacks_p)->next);
580                 callbacks_p = &((*callbacks_p)->next);
581         }
582
583         (*callbacks_p) = malloc(sizeof(target_event_callback_t));
584         (*callbacks_p)->callback = callback;
585         (*callbacks_p)->priv = priv;
586         (*callbacks_p)->next = NULL;
587
588         return ERROR_OK;
589 }
590
591 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
592 {
593         target_timer_callback_t **callbacks_p = &target_timer_callbacks;
594         struct timeval now;
595
596         if (callback == NULL)
597         {
598                 return ERROR_INVALID_ARGUMENTS;
599         }
600
601         if (*callbacks_p)
602         {
603                 while ((*callbacks_p)->next)
604                         callbacks_p = &((*callbacks_p)->next);
605                 callbacks_p = &((*callbacks_p)->next);
606         }
607
608         (*callbacks_p) = malloc(sizeof(target_timer_callback_t));
609         (*callbacks_p)->callback = callback;
610         (*callbacks_p)->periodic = periodic;
611         (*callbacks_p)->time_ms = time_ms;
612
613         gettimeofday(&now, NULL);
614         (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
615         time_ms -= (time_ms % 1000);
616         (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
617         if ((*callbacks_p)->when.tv_usec > 1000000)
618         {
619                 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
620                 (*callbacks_p)->when.tv_sec += 1;
621         }
622
623         (*callbacks_p)->priv = priv;
624         (*callbacks_p)->next = NULL;
625
626         return ERROR_OK;
627 }
628
629 int target_unregister_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
630 {
631         target_event_callback_t **p = &target_event_callbacks;
632         target_event_callback_t *c = target_event_callbacks;
633
634         if (callback == NULL)
635         {
636                 return ERROR_INVALID_ARGUMENTS;
637         }
638
639         while (c)
640         {
641                 target_event_callback_t *next = c->next;
642                 if ((c->callback == callback) && (c->priv == priv))
643                 {
644                         *p = next;
645                         free(c);
646                         return ERROR_OK;
647                 }
648                 else
649                         p = &(c->next);
650                 c = next;
651         }
652
653         return ERROR_OK;
654 }
655
656 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
657 {
658         target_timer_callback_t **p = &target_timer_callbacks;
659         target_timer_callback_t *c = target_timer_callbacks;
660
661         if (callback == NULL)
662         {
663                 return ERROR_INVALID_ARGUMENTS;
664         }
665
666         while (c)
667         {
668                 target_timer_callback_t *next = c->next;
669                 if ((c->callback == callback) && (c->priv == priv))
670                 {
671                         *p = next;
672                         free(c);
673                         return ERROR_OK;
674                 }
675                 else
676                         p = &(c->next);
677                 c = next;
678         }
679
680         return ERROR_OK;
681 }
682
683 int target_call_event_callbacks(target_t *target, enum target_event event)
684 {
685         target_event_callback_t *callback = target_event_callbacks;
686         target_event_callback_t *next_callback;
687
688         if (event == TARGET_EVENT_HALTED)
689         {
690                 /* execute early halted first */
691                 target_call_event_callbacks(target, TARGET_EVENT_EARLY_HALTED);
692         }
693
694         LOG_DEBUG("target event %i (%s)",
695                           event,
696                           Jim_Nvp_value2name_simple( nvp_target_event, event )->name );
697
698         target_handle_event( target, event );
699
700         while (callback)
701         {
702                 next_callback = callback->next;
703                 callback->callback(target, event, callback->priv);
704                 callback = next_callback;
705         }
706
707         return ERROR_OK;
708 }
709
710 static int target_call_timer_callbacks_check_time(int checktime)
711 {
712         target_timer_callback_t *callback = target_timer_callbacks;
713         target_timer_callback_t *next_callback;
714         struct timeval now;
715
716         keep_alive();
717
718         gettimeofday(&now, NULL);
719
720         while (callback)
721         {
722                 next_callback = callback->next;
723
724                 if ((!checktime&&callback->periodic)||
725                                 (((now.tv_sec >= callback->when.tv_sec) && (now.tv_usec >= callback->when.tv_usec))
726                                                 || (now.tv_sec > callback->when.tv_sec)))
727                 {
728                         if(callback->callback != NULL)
729                         {
730                                 callback->callback(callback->priv);
731                                 if (callback->periodic)
732                                 {
733                                         int time_ms = callback->time_ms;
734                                         callback->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
735                                         time_ms -= (time_ms % 1000);
736                                         callback->when.tv_sec = now.tv_sec + time_ms / 1000;
737                                         if (callback->when.tv_usec > 1000000)
738                                         {
739                                                 callback->when.tv_usec = callback->when.tv_usec - 1000000;
740                                                 callback->when.tv_sec += 1;
741                                         }
742                                 }
743                                 else
744                                 {
745                                         int retval;
746                                         if((retval = target_unregister_timer_callback(callback->callback, callback->priv)) != ERROR_OK)
747                                                 return retval;
748                                 }
749                         }
750                 }
751
752                 callback = next_callback;
753         }
754
755         return ERROR_OK;
756 }
757
758 int target_call_timer_callbacks(void)
759 {
760         return target_call_timer_callbacks_check_time(1);
761 }
762
763 /* invoke periodic callbacks immediately */
764 int target_call_timer_callbacks_now(void)
765 {
766         return target_call_timer_callbacks_check_time(0);
767 }
768
769 int target_alloc_working_area(struct target_s *target, u32 size, working_area_t **area)
770 {
771         working_area_t *c = target->working_areas;
772         working_area_t *new_wa = NULL;
773
774         /* Reevaluate working area address based on MMU state*/
775         if (target->working_areas == NULL)
776         {
777                 int retval;
778                 int enabled;
779                 retval = target->type->mmu(target, &enabled);
780                 if (retval != ERROR_OK)
781                 {
782                         return retval;
783                 }
784                 if (enabled)
785                 {
786                         target->working_area = target->working_area_virt;
787                 }
788                 else
789                 {
790                         target->working_area = target->working_area_phys;
791                 }
792         }
793
794         /* only allocate multiples of 4 byte */
795         if (size % 4)
796         {
797                 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes, padding");
798                 size = CEIL(size, 4);
799         }
800
801         /* see if there's already a matching working area */
802         while (c)
803         {
804                 if ((c->free) && (c->size == size))
805                 {
806                         new_wa = c;
807                         break;
808                 }
809                 c = c->next;
810         }
811
812         /* if not, allocate a new one */
813         if (!new_wa)
814         {
815                 working_area_t **p = &target->working_areas;
816                 u32 first_free = target->working_area;
817                 u32 free_size = target->working_area_size;
818
819                 LOG_DEBUG("allocating new working area");
820
821                 c = target->working_areas;
822                 while (c)
823                 {
824                         first_free += c->size;
825                         free_size -= c->size;
826                         p = &c->next;
827                         c = c->next;
828                 }
829
830                 if (free_size < size)
831                 {
832                         LOG_WARNING("not enough working area available(requested %d, free %d)", size, free_size);
833                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
834                 }
835
836                 new_wa = malloc(sizeof(working_area_t));
837                 new_wa->next = NULL;
838                 new_wa->size = size;
839                 new_wa->address = first_free;
840
841                 if (target->backup_working_area)
842                 {
843                         int retval;
844                         new_wa->backup = malloc(new_wa->size);
845                         if((retval = target->type->read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
846                         {
847                                 free(new_wa->backup);
848                                 free(new_wa);
849                                 return retval;
850                         }
851                 }
852                 else
853                 {
854                         new_wa->backup = NULL;
855                 }
856
857                 /* put new entry in list */
858                 *p = new_wa;
859         }
860
861         /* mark as used, and return the new (reused) area */
862         new_wa->free = 0;
863         *area = new_wa;
864
865         /* user pointer */
866         new_wa->user = area;
867
868         return ERROR_OK;
869 }
870
871 int target_free_working_area_restore(struct target_s *target, working_area_t *area, int restore)
872 {
873         if (area->free)
874                 return ERROR_OK;
875
876         if (restore&&target->backup_working_area)
877         {
878                 int retval;
879                 if((retval = target->type->write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
880                         return retval;
881         }
882
883         area->free = 1;
884
885         /* mark user pointer invalid */
886         *area->user = NULL;
887         area->user = NULL;
888
889         return ERROR_OK;
890 }
891
892 int target_free_working_area(struct target_s *target, working_area_t *area)
893 {
894         return target_free_working_area_restore(target, area, 1);
895 }
896
897 /* free resources and restore memory, if restoring memory fails,
898  * free up resources anyway
899  */
900 void target_free_all_working_areas_restore(struct target_s *target, int restore)
901 {
902         working_area_t *c = target->working_areas;
903
904         while (c)
905         {
906                 working_area_t *next = c->next;
907                 target_free_working_area_restore(target, c, restore);
908
909                 if (c->backup)
910                         free(c->backup);
911
912                 free(c);
913
914                 c = next;
915         }
916
917         target->working_areas = NULL;
918 }
919
920 void target_free_all_working_areas(struct target_s *target)
921 {
922         target_free_all_working_areas_restore(target, 1);
923 }
924
925 int target_register_commands(struct command_context_s *cmd_ctx)
926 {
927
928         register_command(cmd_ctx, NULL, "targets", handle_targets_command, COMMAND_EXEC, "change the current command line target (one parameter) or lists targets (with no parameter)");
929         register_command(cmd_ctx, NULL, "virt2phys", handle_virt2phys_command, COMMAND_ANY, "translate a virtual address into a physical address");
930         register_command(cmd_ctx, NULL, "profile", handle_profile_command, COMMAND_EXEC, "profiling samples the CPU PC");
931
932         register_jim(cmd_ctx, "target", jim_target, "configure target" );
933
934
935         /* script procedures */
936         register_jim(cmd_ctx, "ocd_mem2array", jim_mem2array, "read memory and return as a TCL array for script processing");
937         register_jim(cmd_ctx, "ocd_array2mem", jim_array2mem, "convert a TCL array to memory locations and write the values");
938         return ERROR_OK;
939 }
940
941 int target_arch_state(struct target_s *target)
942 {
943         int retval;
944         if (target==NULL)
945         {
946                 LOG_USER("No target has been configured");
947                 return ERROR_OK;
948         }
949
950         LOG_USER("target state: %s",
951                  Jim_Nvp_value2name_simple(nvp_target_state,target->state)->name);
952
953         if (target->state!=TARGET_HALTED)
954                 return ERROR_OK;
955
956         retval=target->type->arch_state(target);
957         return retval;
958 }
959
960 /* Single aligned words are guaranteed to use 16 or 32 bit access
961  * mode respectively, otherwise data is handled as quickly as
962  * possible
963  */
964 int target_write_buffer(struct target_s *target, u32 address, u32 size, u8 *buffer)
965 {
966         int retval;
967         LOG_DEBUG("writing buffer of %i byte at 0x%8.8x", size, address);
968
969         if (!target->type->examined)
970         {
971                 LOG_ERROR("Target not examined yet");
972                 return ERROR_FAIL;
973         }
974
975         if ((address + size - 1) < address)
976         {
977                 /* GDB can request this when e.g. PC is 0xfffffffc*/
978                 LOG_ERROR("address+size wrapped(0x%08x, 0x%08x)", address, size);
979                 return ERROR_FAIL;
980         }
981
982         if (((address % 2) == 0) && (size == 2))
983         {
984                 return target->type->write_memory(target, address, 2, 1, buffer);
985         }
986
987         /* handle unaligned head bytes */
988         if (address % 4)
989         {
990                 int unaligned = 4 - (address % 4);
991
992                 if (unaligned > size)
993                         unaligned = size;
994
995                 if ((retval = target->type->write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
996                         return retval;
997
998                 buffer += unaligned;
999                 address += unaligned;
1000                 size -= unaligned;
1001         }
1002
1003         /* handle aligned words */
1004         if (size >= 4)
1005         {
1006                 int aligned = size - (size % 4);
1007
1008                 /* use bulk writes above a certain limit. This may have to be changed */
1009                 if (aligned > 128)
1010                 {
1011                         if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1012                                 return retval;
1013                 }
1014                 else
1015                 {
1016                         if ((retval = target->type->write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1017                                 return retval;
1018                 }
1019
1020                 buffer += aligned;
1021                 address += aligned;
1022                 size -= aligned;
1023         }
1024
1025         /* handle tail writes of less than 4 bytes */
1026         if (size > 0)
1027         {
1028                 if ((retval = target->type->write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1029                         return retval;
1030         }
1031
1032         return ERROR_OK;
1033 }
1034
1035 /* Single aligned words are guaranteed to use 16 or 32 bit access
1036  * mode respectively, otherwise data is handled as quickly as
1037  * possible
1038  */
1039 int target_read_buffer(struct target_s *target, u32 address, u32 size, u8 *buffer)
1040 {
1041         int retval;
1042         LOG_DEBUG("reading buffer of %i byte at 0x%8.8x", size, address);
1043
1044         if (!target->type->examined)
1045         {
1046                 LOG_ERROR("Target not examined yet");
1047                 return ERROR_FAIL;
1048         }
1049
1050         if ((address + size - 1) < address)
1051         {
1052                 /* GDB can request this when e.g. PC is 0xfffffffc*/
1053                 LOG_ERROR("address+size wrapped(0x%08x, 0x%08x)", address, size);
1054                 return ERROR_FAIL;
1055         }
1056
1057         if (((address % 2) == 0) && (size == 2))
1058         {
1059                 return target->type->read_memory(target, address, 2, 1, buffer);
1060         }
1061
1062         /* handle unaligned head bytes */
1063         if (address % 4)
1064         {
1065                 int unaligned = 4 - (address % 4);
1066
1067                 if (unaligned > size)
1068                         unaligned = size;
1069
1070                 if ((retval = target->type->read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1071                         return retval;
1072
1073                 buffer += unaligned;
1074                 address += unaligned;
1075                 size -= unaligned;
1076         }
1077
1078         /* handle aligned words */
1079         if (size >= 4)
1080         {
1081                 int aligned = size - (size % 4);
1082
1083                 if ((retval = target->type->read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1084                         return retval;
1085
1086                 buffer += aligned;
1087                 address += aligned;
1088                 size -= aligned;
1089         }
1090
1091         /* handle tail writes of less than 4 bytes */
1092         if (size > 0)
1093         {
1094                 if ((retval = target->type->read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1095                         return retval;
1096         }
1097
1098         return ERROR_OK;
1099 }
1100
1101 int target_checksum_memory(struct target_s *target, u32 address, u32 size, u32* crc)
1102 {
1103         u8 *buffer;
1104         int retval;
1105         int i;
1106         u32 checksum = 0;
1107         if (!target->type->examined)
1108         {
1109                 LOG_ERROR("Target not examined yet");
1110                 return ERROR_FAIL;
1111         }
1112
1113         if ((retval = target->type->checksum_memory(target, address,
1114                 size, &checksum)) != ERROR_OK)
1115         {
1116                 buffer = malloc(size);
1117                 if (buffer == NULL)
1118                 {
1119                         LOG_ERROR("error allocating buffer for section (%d bytes)", size);
1120                         return ERROR_INVALID_ARGUMENTS;
1121                 }
1122                 retval = target_read_buffer(target, address, size, buffer);
1123                 if (retval != ERROR_OK)
1124                 {
1125                         free(buffer);
1126                         return retval;
1127                 }
1128
1129                 /* convert to target endianess */
1130                 for (i = 0; i < (size/sizeof(u32)); i++)
1131                 {
1132                         u32 target_data;
1133                         target_data = target_buffer_get_u32(target, &buffer[i*sizeof(u32)]);
1134                         target_buffer_set_u32(target, &buffer[i*sizeof(u32)], target_data);
1135                 }
1136
1137                 retval = image_calculate_checksum( buffer, size, &checksum );
1138                 free(buffer);
1139         }
1140
1141         *crc = checksum;
1142
1143         return retval;
1144 }
1145
1146 int target_blank_check_memory(struct target_s *target, u32 address, u32 size, u32* blank)
1147 {
1148         int retval;
1149         if (!target->type->examined)
1150         {
1151                 LOG_ERROR("Target not examined yet");
1152                 return ERROR_FAIL;
1153         }
1154
1155         if (target->type->blank_check_memory == 0)
1156                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1157
1158         retval = target->type->blank_check_memory(target, address, size, blank);
1159
1160         return retval;
1161 }
1162
1163 int target_read_u32(struct target_s *target, u32 address, u32 *value)
1164 {
1165         u8 value_buf[4];
1166         if (!target->type->examined)
1167         {
1168                 LOG_ERROR("Target not examined yet");
1169                 return ERROR_FAIL;
1170         }
1171
1172         int retval = target->type->read_memory(target, address, 4, 1, value_buf);
1173
1174         if (retval == ERROR_OK)
1175         {
1176                 *value = target_buffer_get_u32(target, value_buf);
1177                 LOG_DEBUG("address: 0x%8.8x, value: 0x%8.8x", address, *value);
1178         }
1179         else
1180         {
1181                 *value = 0x0;
1182                 LOG_DEBUG("address: 0x%8.8x failed", address);
1183         }
1184
1185         return retval;
1186 }
1187
1188 int target_read_u16(struct target_s *target, u32 address, u16 *value)
1189 {
1190         u8 value_buf[2];
1191         if (!target->type->examined)
1192         {
1193                 LOG_ERROR("Target not examined yet");
1194                 return ERROR_FAIL;
1195         }
1196
1197         int retval = target->type->read_memory(target, address, 2, 1, value_buf);
1198
1199         if (retval == ERROR_OK)
1200         {
1201                 *value = target_buffer_get_u16(target, value_buf);
1202                 LOG_DEBUG("address: 0x%8.8x, value: 0x%4.4x", address, *value);
1203         }
1204         else
1205         {
1206                 *value = 0x0;
1207                 LOG_DEBUG("address: 0x%8.8x failed", address);
1208         }
1209
1210         return retval;
1211 }
1212
1213 int target_read_u8(struct target_s *target, u32 address, u8 *value)
1214 {
1215         int retval = target->type->read_memory(target, address, 1, 1, value);
1216         if (!target->type->examined)
1217         {
1218                 LOG_ERROR("Target not examined yet");
1219                 return ERROR_FAIL;
1220         }
1221
1222         if (retval == ERROR_OK)
1223         {
1224                 LOG_DEBUG("address: 0x%8.8x, value: 0x%2.2x", address, *value);
1225         }
1226         else
1227         {
1228                 *value = 0x0;
1229                 LOG_DEBUG("address: 0x%8.8x failed", address);
1230         }
1231
1232         return retval;
1233 }
1234
1235 int target_write_u32(struct target_s *target, u32 address, u32 value)
1236 {
1237         int retval;
1238         u8 value_buf[4];
1239         if (!target->type->examined)
1240         {
1241                 LOG_ERROR("Target not examined yet");
1242                 return ERROR_FAIL;
1243         }
1244
1245         LOG_DEBUG("address: 0x%8.8x, value: 0x%8.8x", address, value);
1246
1247         target_buffer_set_u32(target, value_buf, value);
1248         if ((retval = target->type->write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1249         {
1250                 LOG_DEBUG("failed: %i", retval);
1251         }
1252
1253         return retval;
1254 }
1255
1256 int target_write_u16(struct target_s *target, u32 address, u16 value)
1257 {
1258         int retval;
1259         u8 value_buf[2];
1260         if (!target->type->examined)
1261         {
1262                 LOG_ERROR("Target not examined yet");
1263                 return ERROR_FAIL;
1264         }
1265
1266         LOG_DEBUG("address: 0x%8.8x, value: 0x%8.8x", address, value);
1267
1268         target_buffer_set_u16(target, value_buf, value);
1269         if ((retval = target->type->write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1270         {
1271                 LOG_DEBUG("failed: %i", retval);
1272         }
1273
1274         return retval;
1275 }
1276
1277 int target_write_u8(struct target_s *target, u32 address, u8 value)
1278 {
1279         int retval;
1280         if (!target->type->examined)
1281         {
1282                 LOG_ERROR("Target not examined yet");
1283                 return ERROR_FAIL;
1284         }
1285
1286         LOG_DEBUG("address: 0x%8.8x, value: 0x%2.2x", address, value);
1287
1288         if ((retval = target->type->write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1289         {
1290                 LOG_DEBUG("failed: %i", retval);
1291         }
1292
1293         return retval;
1294 }
1295
1296 int target_register_user_commands(struct command_context_s *cmd_ctx)
1297 {
1298         int retval = ERROR_OK;
1299         register_command(cmd_ctx,  NULL, "reg", handle_reg_command, COMMAND_EXEC, "display or set a register");
1300         register_command(cmd_ctx,  NULL, "poll", handle_poll_command, COMMAND_EXEC, "poll target state");
1301         register_command(cmd_ctx,  NULL, "wait_halt", handle_wait_halt_command, COMMAND_EXEC, "wait for target halt [time (s)]");
1302         register_command(cmd_ctx,  NULL, "halt", handle_halt_command, COMMAND_EXEC, "halt target");
1303         register_command(cmd_ctx,  NULL, "resume", handle_resume_command, COMMAND_EXEC, "resume target [addr]");
1304         register_command(cmd_ctx,  NULL, "step", handle_step_command, COMMAND_EXEC, "step one instruction from current PC or [addr]");
1305         register_command(cmd_ctx,  NULL, "reset", handle_reset_command, COMMAND_EXEC, "reset target [run|halt|init] - default is run");
1306         register_command(cmd_ctx,  NULL, "soft_reset_halt", handle_soft_reset_halt_command, COMMAND_EXEC, "halt the target and do a soft reset");
1307
1308         register_command(cmd_ctx,  NULL, "mdw", handle_md_command, COMMAND_EXEC, "display memory words <addr> [count]");
1309         register_command(cmd_ctx,  NULL, "mdh", handle_md_command, COMMAND_EXEC, "display memory half-words <addr> [count]");
1310         register_command(cmd_ctx,  NULL, "mdb", handle_md_command, COMMAND_EXEC, "display memory bytes <addr> [count]");
1311
1312         register_command(cmd_ctx,  NULL, "mww", handle_mw_command, COMMAND_EXEC, "write memory word <addr> <value> [count]");
1313         register_command(cmd_ctx,  NULL, "mwh", handle_mw_command, COMMAND_EXEC, "write memory half-word <addr> <value> [count]");
1314         register_command(cmd_ctx,  NULL, "mwb", handle_mw_command, COMMAND_EXEC, "write memory byte <addr> <value> [count]");
1315
1316         register_command(cmd_ctx,  NULL, "bp", handle_bp_command, COMMAND_EXEC, "set breakpoint <address> <length> [hw]");
1317         register_command(cmd_ctx,  NULL, "rbp", handle_rbp_command, COMMAND_EXEC, "remove breakpoint <adress>");
1318         register_command(cmd_ctx,  NULL, "wp", handle_wp_command, COMMAND_EXEC, "set watchpoint <address> <length> <r/w/a> [value] [mask]");
1319         register_command(cmd_ctx,  NULL, "rwp", handle_rwp_command, COMMAND_EXEC, "remove watchpoint <adress>");
1320
1321         register_command(cmd_ctx,  NULL, "load_image", handle_load_image_command, COMMAND_EXEC, "load_image <file> <address> ['bin'|'ihex'|'elf'|'s19'] [min_address] [max_length]");
1322         register_command(cmd_ctx,  NULL, "dump_image", handle_dump_image_command, COMMAND_EXEC, "dump_image <file> <address> <size>");
1323         register_command(cmd_ctx,  NULL, "verify_image", handle_verify_image_command, COMMAND_EXEC, "verify_image <file> [offset] [type]");
1324
1325         if((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
1326                 return retval;
1327         if((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
1328                 return retval;
1329
1330         return retval;
1331 }
1332
1333 int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1334 {
1335         char *cp;
1336         target_t *target = all_targets;
1337
1338         if (argc == 1)
1339         {
1340                 /* try as tcltarget name */
1341                 for( target = all_targets ; target ; target = target->next ){
1342                   if( target->cmd_name ){
1343                         if( 0 == strcmp( args[0], target->cmd_name ) ){
1344                                 /* MATCH */
1345                                 goto Match;
1346                         }
1347                   }
1348                 }
1349                 /* no match, try as number */
1350
1351                 int num = strtoul(args[0], &cp, 0 );
1352                 if( *cp != 0 ){
1353                         /* then it was not a number */
1354                         command_print( cmd_ctx, "Target: %s unknown, try one of:\n", args[0] );
1355                         goto DumpTargets;
1356                 }
1357
1358                 target = get_target_by_num( num );
1359                 if( target == NULL ){
1360                         command_print(cmd_ctx,"Target: %s is unknown, try one of:\n", args[0] );
1361                         goto DumpTargets;
1362                 }
1363         Match:
1364                 cmd_ctx->current_target = target->target_number;
1365                 return ERROR_OK;
1366         }
1367 DumpTargets:
1368
1369         target = all_targets;
1370         command_print(cmd_ctx, "    CmdName    Type       Endian     AbsChainPos Name          State     ");
1371         command_print(cmd_ctx, "--  ---------- ---------- ---------- ----------- ------------- ----------");
1372         while (target)
1373         {
1374                 /* XX: abcdefghij abcdefghij abcdefghij abcdefghij */
1375                 command_print(cmd_ctx, "%2d: %-10s %-10s %-10s %10d %14s %s",
1376                                           target->target_number,
1377                                           target->cmd_name,
1378                                           target->type->name,
1379                                           Jim_Nvp_value2name_simple( nvp_target_endian, target->endianness )->name,
1380                                           target->tap->abs_chain_position,
1381                                           target->tap->dotted_name,
1382                                           Jim_Nvp_value2name_simple( nvp_target_state, target->state )->name );
1383                 target = target->next;
1384         }
1385
1386         return ERROR_OK;
1387 }
1388
1389 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1390
1391 static int powerDropout;
1392 static int srstAsserted;
1393
1394 static int runPowerRestore;
1395 static int runPowerDropout;
1396 static int runSrstAsserted;
1397 static int runSrstDeasserted;
1398
1399 static int sense_handler(void)
1400 {
1401         static int prevSrstAsserted = 0;
1402         static int prevPowerdropout = 0;
1403
1404         int retval;
1405         if ((retval=jtag_power_dropout(&powerDropout))!=ERROR_OK)
1406                 return retval;
1407
1408         int powerRestored;
1409         powerRestored = prevPowerdropout && !powerDropout;
1410         if (powerRestored)
1411         {
1412                 runPowerRestore = 1;
1413         }
1414
1415         long long current = timeval_ms();
1416         static long long lastPower = 0;
1417         int waitMore = lastPower + 2000 > current;
1418         if (powerDropout && !waitMore)
1419         {
1420                 runPowerDropout = 1;
1421                 lastPower = current;
1422         }
1423
1424         if ((retval=jtag_srst_asserted(&srstAsserted))!=ERROR_OK)
1425                 return retval;
1426
1427         int srstDeasserted;
1428         srstDeasserted = prevSrstAsserted && !srstAsserted;
1429
1430         static long long lastSrst = 0;
1431         waitMore = lastSrst + 2000 > current;
1432         if (srstDeasserted && !waitMore)
1433         {
1434                 runSrstDeasserted = 1;
1435                 lastSrst = current;
1436         }
1437
1438         if (!prevSrstAsserted && srstAsserted)
1439         {
1440                 runSrstAsserted = 1;
1441         }
1442
1443         prevSrstAsserted = srstAsserted;
1444         prevPowerdropout = powerDropout;
1445
1446         if (srstDeasserted || powerRestored)
1447         {
1448                 /* Other than logging the event we can't do anything here.
1449                  * Issuing a reset is a particularly bad idea as we might
1450                  * be inside a reset already.
1451                  */
1452         }
1453
1454         return ERROR_OK;
1455 }
1456
1457 /* process target state changes */
1458 int handle_target(void *priv)
1459 {
1460         int retval = ERROR_OK;
1461
1462         /* we do not want to recurse here... */
1463         static int recursive = 0;
1464         if (! recursive)
1465         {
1466                 recursive = 1;
1467                 sense_handler();
1468                 /* danger! running these procedures can trigger srst assertions and power dropouts.
1469                  * We need to avoid an infinite loop/recursion here and we do that by
1470                  * clearing the flags after running these events.
1471                  */
1472                 int did_something = 0;
1473                 if (runSrstAsserted)
1474                 {
1475                         Jim_Eval( interp, "srst_asserted");
1476                         did_something = 1;
1477                 }
1478                 if (runSrstDeasserted)
1479                 {
1480                         Jim_Eval( interp, "srst_deasserted");
1481                         did_something = 1;
1482                 }
1483                 if (runPowerDropout)
1484                 {
1485                         Jim_Eval( interp, "power_dropout");
1486                         did_something = 1;
1487                 }
1488                 if (runPowerRestore)
1489                 {
1490                         Jim_Eval( interp, "power_restore");
1491                         did_something = 1;
1492                 }
1493
1494                 if (did_something)
1495                 {
1496                         /* clear detect flags */
1497                         sense_handler();
1498                 }
1499
1500                 /* clear action flags */
1501
1502                 runSrstAsserted=0;
1503                 runSrstDeasserted=0;
1504                 runPowerRestore=0;
1505                 runPowerDropout=0;
1506
1507                 recursive = 0;
1508         }
1509
1510         target_t *target = all_targets;
1511
1512         while (target)
1513         {
1514
1515                 /* only poll target if we've got power and srst isn't asserted */
1516                 if (target_continous_poll&&!powerDropout&&!srstAsserted)
1517                 {
1518                         /* polling may fail silently until the target has been examined */
1519                         if((retval = target_poll(target)) != ERROR_OK)
1520                                 return retval;
1521                 }
1522
1523                 target = target->next;
1524         }
1525
1526         return retval;
1527 }
1528
1529 int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1530 {
1531         target_t *target;
1532         reg_t *reg = NULL;
1533         int count = 0;
1534         char *value;
1535
1536         LOG_DEBUG("-");
1537
1538         target = get_current_target(cmd_ctx);
1539
1540         /* list all available registers for the current target */
1541         if (argc == 0)
1542         {
1543                 reg_cache_t *cache = target->reg_cache;
1544
1545                 count = 0;
1546                 while(cache)
1547                 {
1548                         int i;
1549                         for (i = 0; i < cache->num_regs; i++)
1550                         {
1551                                 value = buf_to_str(cache->reg_list[i].value, cache->reg_list[i].size, 16);
1552                                 command_print(cmd_ctx, "(%i) %s (/%i): 0x%s (dirty: %i, valid: %i)", count++, cache->reg_list[i].name, cache->reg_list[i].size, value, cache->reg_list[i].dirty, cache->reg_list[i].valid);
1553                                 free(value);
1554                         }
1555                         cache = cache->next;
1556                 }
1557
1558                 return ERROR_OK;
1559         }
1560
1561         /* access a single register by its ordinal number */
1562         if ((args[0][0] >= '0') && (args[0][0] <= '9'))
1563         {
1564                 int num = strtoul(args[0], NULL, 0);
1565                 reg_cache_t *cache = target->reg_cache;
1566
1567                 count = 0;
1568                 while(cache)
1569                 {
1570                         int i;
1571                         for (i = 0; i < cache->num_regs; i++)
1572                         {
1573                                 if (count++ == num)
1574                                 {
1575                                         reg = &cache->reg_list[i];
1576                                         break;
1577                                 }
1578                         }
1579                         if (reg)
1580                                 break;
1581                         cache = cache->next;
1582                 }
1583
1584                 if (!reg)
1585                 {
1586                         command_print(cmd_ctx, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1587                         return ERROR_OK;
1588                 }
1589         } else /* access a single register by its name */
1590         {
1591                 reg = register_get_by_name(target->reg_cache, args[0], 1);
1592
1593                 if (!reg)
1594                 {
1595                         command_print(cmd_ctx, "register %s not found in current target", args[0]);
1596                         return ERROR_OK;
1597                 }
1598         }
1599
1600         /* display a register */
1601         if ((argc == 1) || ((argc == 2) && !((args[1][0] >= '0') && (args[1][0] <= '9'))))
1602         {
1603                 if ((argc == 2) && (strcmp(args[1], "force") == 0))
1604                         reg->valid = 0;
1605
1606                 if (reg->valid == 0)
1607                 {
1608                         reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1609                         arch_type->get(reg);
1610                 }
1611                 value = buf_to_str(reg->value, reg->size, 16);
1612                 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, reg->size, value);
1613                 free(value);
1614                 return ERROR_OK;
1615         }
1616
1617         /* set register value */
1618         if (argc == 2)
1619         {
1620                 u8 *buf = malloc(CEIL(reg->size, 8));
1621                 str_to_buf(args[1], strlen(args[1]), buf, reg->size, 0);
1622
1623                 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1624                 arch_type->set(reg, buf);
1625
1626                 value = buf_to_str(reg->value, reg->size, 16);
1627                 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, reg->size, value);
1628                 free(value);
1629
1630                 free(buf);
1631
1632                 return ERROR_OK;
1633         }
1634
1635         command_print(cmd_ctx, "usage: reg <#|name> [value]");
1636
1637         return ERROR_OK;
1638 }
1639
1640 int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1641 {
1642         int retval = ERROR_OK;
1643         target_t *target = get_current_target(cmd_ctx);
1644
1645         if (argc == 0)
1646         {
1647                 if((retval = target_poll(target)) != ERROR_OK)
1648                         return retval;
1649                 if((retval = target_arch_state(target)) != ERROR_OK)
1650                         return retval;
1651
1652         }
1653         else if (argc==1)
1654         {
1655                 if (strcmp(args[0], "on") == 0)
1656                 {
1657                         target_continous_poll = 1;
1658                 }
1659                 else if (strcmp(args[0], "off") == 0)
1660                 {
1661                         target_continous_poll = 0;
1662                 }
1663                 else
1664                 {
1665                         command_print(cmd_ctx, "arg is \"on\" or \"off\"");
1666                 }
1667         } else
1668         {
1669                 return ERROR_COMMAND_SYNTAX_ERROR;
1670         }
1671
1672         return retval;
1673 }
1674
1675 int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1676 {
1677         int ms = 5000;
1678
1679         if (argc > 0)
1680         {
1681                 char *end;
1682
1683                 ms = strtoul(args[0], &end, 0) * 1000;
1684                 if (*end)
1685                 {
1686                         command_print(cmd_ctx, "usage: %s [seconds]", cmd);
1687                         return ERROR_OK;
1688                 }
1689         }
1690         target_t *target = get_current_target(cmd_ctx);
1691
1692         return target_wait_state(target, TARGET_HALTED, ms);
1693 }
1694
1695 int target_wait_state(target_t *target, enum target_state state, int ms)
1696 {
1697         int retval;
1698         struct timeval timeout, now;
1699         int once=1;
1700         gettimeofday(&timeout, NULL);
1701         timeval_add_time(&timeout, 0, ms * 1000);
1702
1703         for (;;)
1704         {
1705                 if ((retval=target_poll(target))!=ERROR_OK)
1706                         return retval;
1707                 keep_alive();
1708                 if (target->state == state)
1709                 {
1710                         break;
1711                 }
1712                 if (once)
1713                 {
1714                         once=0;
1715                         LOG_DEBUG("waiting for target %s...",
1716                                 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
1717                 }
1718
1719                 gettimeofday(&now, NULL);
1720                 if ((now.tv_sec > timeout.tv_sec) || ((now.tv_sec == timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
1721                 {
1722                         LOG_ERROR("timed out while waiting for target %s",
1723                                 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
1724                         return ERROR_FAIL;
1725                 }
1726         }
1727
1728         return ERROR_OK;
1729 }
1730
1731 int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1732 {
1733         int retval;
1734         target_t *target = get_current_target(cmd_ctx);
1735
1736         LOG_DEBUG("-");
1737
1738         if ((retval = target_halt(target)) != ERROR_OK)
1739         {
1740                 return retval;
1741         }
1742
1743         return handle_wait_halt_command(cmd_ctx, cmd, args, argc);
1744 }
1745
1746 int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1747 {
1748         target_t *target = get_current_target(cmd_ctx);
1749
1750         LOG_USER("requesting target halt and executing a soft reset");
1751
1752         target->type->soft_reset_halt(target);
1753
1754         return ERROR_OK;
1755 }
1756
1757 int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1758 {
1759         const Jim_Nvp *n;
1760         enum target_reset_mode reset_mode = RESET_RUN;
1761
1762         if (argc >= 1)
1763         {
1764                 n = Jim_Nvp_name2value_simple( nvp_reset_modes, args[0] );
1765                 if( (n->name == NULL) || (n->value == RESET_UNKNOWN) ){
1766                         return ERROR_COMMAND_SYNTAX_ERROR;
1767                 }
1768                 reset_mode = n->value;
1769         }
1770
1771         /* reset *all* targets */
1772         return target_process_reset(cmd_ctx, reset_mode);
1773 }
1774
1775
1776 int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1777 {
1778         int retval;
1779         target_t *target = get_current_target(cmd_ctx);
1780
1781         target_handle_event( target, TARGET_EVENT_OLD_pre_resume );
1782
1783         if (argc == 0)
1784                 retval = target_resume(target, 1, 0, 1, 0); /* current pc, addr = 0, handle breakpoints, not debugging */
1785         else if (argc == 1)
1786                 retval = target_resume(target, 0, strtoul(args[0], NULL, 0), 1, 0); /* addr = args[0], handle breakpoints, not debugging */
1787         else
1788         {
1789                 retval = ERROR_COMMAND_SYNTAX_ERROR;
1790         }
1791
1792         return retval;
1793 }
1794
1795 int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1796 {
1797         target_t *target = get_current_target(cmd_ctx);
1798
1799         LOG_DEBUG("-");
1800
1801         if (argc == 0)
1802                 return target->type->step(target, 1, 0, 1); /* current pc, addr = 0, handle breakpoints */
1803
1804         if (argc == 1)
1805                 return target->type->step(target, 0, strtoul(args[0], NULL, 0), 1); /* addr = args[0], handle breakpoints */
1806
1807         return ERROR_OK;
1808 }
1809
1810 int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1811 {
1812         const int line_bytecnt = 32;
1813         int count = 1;
1814         int size = 4;
1815         u32 address = 0;
1816         int line_modulo;
1817         int i;
1818
1819         char output[128];
1820         int output_len;
1821
1822         int retval;
1823
1824         u8 *buffer;
1825         target_t *target = get_current_target(cmd_ctx);
1826
1827         if (argc < 1)
1828                 return ERROR_OK;
1829
1830         if (argc == 2)
1831                 count = strtoul(args[1], NULL, 0);
1832
1833         address = strtoul(args[0], NULL, 0);
1834
1835         switch (cmd[2])
1836         {
1837                 case 'w':
1838                         size = 4; line_modulo = line_bytecnt / 4;
1839                         break;
1840                 case 'h':
1841                         size = 2; line_modulo = line_bytecnt / 2;
1842                         break;
1843                 case 'b':
1844                         size = 1; line_modulo = line_bytecnt / 1;
1845                         break;
1846                 default:
1847                         return ERROR_OK;
1848         }
1849
1850         buffer = calloc(count, size);
1851         retval  = target->type->read_memory(target, address, size, count, buffer);
1852         if (retval == ERROR_OK)
1853         {
1854                 output_len = 0;
1855
1856                 for (i = 0; i < count; i++)
1857                 {
1858                         if (i%line_modulo == 0)
1859                                 output_len += snprintf(output + output_len, 128 - output_len, "0x%8.8x: ", address + (i*size));
1860
1861                         switch (size)
1862                         {
1863                                 case 4:
1864                                         output_len += snprintf(output + output_len, 128 - output_len, "%8.8x ", target_buffer_get_u32(target, &buffer[i*4]));
1865                                         break;
1866                                 case 2:
1867                                         output_len += snprintf(output + output_len, 128 - output_len, "%4.4x ", target_buffer_get_u16(target, &buffer[i*2]));
1868                                         break;
1869                                 case 1:
1870                                         output_len += snprintf(output + output_len, 128 - output_len, "%2.2x ", buffer[i*1]);
1871                                         break;
1872                         }
1873
1874                         if ((i%line_modulo == line_modulo-1) || (i == count - 1))
1875                         {
1876                                 command_print(cmd_ctx, output);
1877                                 output_len = 0;
1878                         }
1879                 }
1880         }
1881
1882         free(buffer);
1883
1884         return retval;
1885 }
1886
1887 int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1888 {
1889         u32 address = 0;
1890         u32 value = 0;
1891         int count = 1;
1892         int i;
1893         int wordsize;
1894         target_t *target = get_current_target(cmd_ctx);
1895         u8 value_buf[4];
1896
1897          if ((argc < 2) || (argc > 3))
1898                 return ERROR_COMMAND_SYNTAX_ERROR;
1899
1900         address = strtoul(args[0], NULL, 0);
1901         value = strtoul(args[1], NULL, 0);
1902         if (argc == 3)
1903                 count = strtoul(args[2], NULL, 0);
1904
1905         switch (cmd[2])
1906         {
1907                 case 'w':
1908                         wordsize = 4;
1909                         target_buffer_set_u32(target, value_buf, value);
1910                         break;
1911                 case 'h':
1912                         wordsize = 2;
1913                         target_buffer_set_u16(target, value_buf, value);
1914                         break;
1915                 case 'b':
1916                         wordsize = 1;
1917                         value_buf[0] = value;
1918                         break;
1919                 default:
1920                         return ERROR_COMMAND_SYNTAX_ERROR;
1921         }
1922         for (i=0; i<count; i++)
1923         {
1924                 int retval;
1925                 switch (wordsize)
1926                 {
1927                         case 4:
1928                                 retval = target->type->write_memory(target, address + i*wordsize, 4, 1, value_buf);
1929                                 break;
1930                         case 2:
1931                                 retval = target->type->write_memory(target, address + i*wordsize, 2, 1, value_buf);
1932                                 break;
1933                         case 1:
1934                                 retval = target->type->write_memory(target, address + i*wordsize, 1, 1, value_buf);
1935                         break;
1936                         default:
1937                         return ERROR_OK;
1938                 }
1939                 keep_alive();
1940
1941                 if (retval!=ERROR_OK)
1942                 {
1943                         return retval;
1944                 }
1945         }
1946
1947         return ERROR_OK;
1948
1949 }
1950
1951 int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1952 {
1953         u8 *buffer;
1954         u32 buf_cnt;
1955         u32 image_size;
1956         u32 min_address=0;
1957         u32 max_address=0xffffffff;
1958         int i;
1959         int retval, retvaltemp;
1960
1961         image_t image;
1962
1963         duration_t duration;
1964         char *duration_text;
1965
1966         target_t *target = get_current_target(cmd_ctx);
1967
1968         if ((argc < 1)||(argc > 5))
1969         {
1970                 return ERROR_COMMAND_SYNTAX_ERROR;
1971         }
1972
1973         /* a base address isn't always necessary, default to 0x0 (i.e. don't relocate) */
1974         if (argc >= 2)
1975         {
1976                 image.base_address_set = 1;
1977                 image.base_address = strtoul(args[1], NULL, 0);
1978         }
1979         else
1980         {
1981                 image.base_address_set = 0;
1982         }
1983
1984
1985         image.start_address_set = 0;
1986
1987         if (argc>=4)
1988         {
1989                 min_address=strtoul(args[3], NULL, 0);
1990         }
1991         if (argc>=5)
1992         {
1993                 max_address=strtoul(args[4], NULL, 0)+min_address;
1994         }
1995
1996         if (min_address>max_address)
1997         {
1998                 return ERROR_COMMAND_SYNTAX_ERROR;
1999         }
2000
2001         duration_start_measure(&duration);
2002
2003         if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
2004         {
2005                 return ERROR_OK;
2006         }
2007
2008         image_size = 0x0;
2009         retval = ERROR_OK;
2010         for (i = 0; i < image.num_sections; i++)
2011         {
2012                 buffer = malloc(image.sections[i].size);
2013                 if (buffer == NULL)
2014                 {
2015                         command_print(cmd_ctx, "error allocating buffer for section (%d bytes)", image.sections[i].size);
2016                         break;
2017                 }
2018
2019                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2020                 {
2021                         free(buffer);
2022                         break;
2023                 }
2024
2025                 u32 offset=0;
2026                 u32 length=buf_cnt;
2027
2028                 /* DANGER!!! beware of unsigned comparision here!!! */
2029
2030                 if ((image.sections[i].base_address+buf_cnt>=min_address)&&
2031                                 (image.sections[i].base_address<max_address))
2032                 {
2033                         if (image.sections[i].base_address<min_address)
2034                         {
2035                                 /* clip addresses below */
2036                                 offset+=min_address-image.sections[i].base_address;
2037                                 length-=offset;
2038                         }
2039
2040                         if (image.sections[i].base_address+buf_cnt>max_address)
2041                         {
2042                                 length-=(image.sections[i].base_address+buf_cnt)-max_address;
2043                         }
2044
2045                         if ((retval = target_write_buffer(target, image.sections[i].base_address+offset, length, buffer+offset)) != ERROR_OK)
2046                         {
2047                                 free(buffer);
2048                                 break;
2049                         }
2050                         image_size += length;
2051                         command_print(cmd_ctx, "%u byte written at address 0x%8.8x", length, image.sections[i].base_address+offset);
2052                 }
2053
2054                 free(buffer);
2055         }
2056
2057         if((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2058         {
2059                 image_close(&image);
2060                 return retvaltemp;
2061         }
2062
2063         if (retval==ERROR_OK)
2064         {
2065                 command_print(cmd_ctx, "downloaded %u byte in %s", image_size, duration_text);
2066         }
2067         free(duration_text);
2068
2069         image_close(&image);
2070
2071         return retval;
2072
2073 }
2074
2075 int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2076 {
2077         fileio_t fileio;
2078
2079         u32 address;
2080         u32 size;
2081         u8 buffer[560];
2082         int retval=ERROR_OK, retvaltemp;
2083
2084         duration_t duration;
2085         char *duration_text;
2086
2087         target_t *target = get_current_target(cmd_ctx);
2088
2089         if (argc != 3)
2090         {
2091                 command_print(cmd_ctx, "usage: dump_image <filename> <address> <size>");
2092                 return ERROR_OK;
2093         }
2094
2095         address = strtoul(args[1], NULL, 0);
2096         size = strtoul(args[2], NULL, 0);
2097
2098         if ((address & 3) || (size & 3))
2099         {
2100                 command_print(cmd_ctx, "only 32-bit aligned address and size are supported");
2101                 return ERROR_OK;
2102         }
2103
2104         if (fileio_open(&fileio, args[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2105         {
2106                 return ERROR_OK;
2107         }
2108
2109         duration_start_measure(&duration);
2110
2111         while (size > 0)
2112         {
2113                 u32 size_written;
2114                 u32 this_run_size = (size > 560) ? 560 : size;
2115
2116                 retval = target->type->read_memory(target, address, 4, this_run_size / 4, buffer);
2117                 if (retval != ERROR_OK)
2118                 {
2119                         break;
2120                 }
2121
2122                 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2123                 if (retval != ERROR_OK)
2124                 {
2125                         break;
2126                 }
2127
2128                 size -= this_run_size;
2129                 address += this_run_size;
2130         }
2131
2132         if((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2133                 return retvaltemp;
2134
2135         if((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2136                 return retvaltemp;
2137
2138         if (retval==ERROR_OK)
2139         {
2140                 command_print(cmd_ctx, "dumped %"PRIi64" byte in %s", fileio.size, duration_text);
2141         }
2142         free(duration_text);
2143
2144         return ERROR_OK;
2145 }
2146
2147 int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2148 {
2149         u8 *buffer;
2150         u32 buf_cnt;
2151         u32 image_size;
2152         int i;
2153         int retval, retvaltemp;
2154         u32 checksum = 0;
2155         u32 mem_checksum = 0;
2156
2157         image_t image;
2158
2159         duration_t duration;
2160         char *duration_text;
2161
2162         target_t *target = get_current_target(cmd_ctx);
2163
2164         if (argc < 1)
2165         {
2166                 return ERROR_COMMAND_SYNTAX_ERROR;
2167         }
2168
2169         if (!target)
2170         {
2171                 LOG_ERROR("no target selected");
2172                 return ERROR_FAIL;
2173         }
2174
2175         duration_start_measure(&duration);
2176
2177         if (argc >= 2)
2178         {
2179                 image.base_address_set = 1;
2180                 image.base_address = strtoul(args[1], NULL, 0);
2181         }
2182         else
2183         {
2184                 image.base_address_set = 0;
2185                 image.base_address = 0x0;
2186         }
2187
2188         image.start_address_set = 0;
2189
2190         if ((retval=image_open(&image, args[0], (argc == 3) ? args[2] : NULL)) != ERROR_OK)
2191         {
2192                 return retval;
2193         }
2194
2195         image_size = 0x0;
2196         retval=ERROR_OK;
2197         for (i = 0; i < image.num_sections; i++)
2198         {
2199                 buffer = malloc(image.sections[i].size);
2200                 if (buffer == NULL)
2201                 {
2202                         command_print(cmd_ctx, "error allocating buffer for section (%d bytes)", image.sections[i].size);
2203                         break;
2204                 }
2205                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2206                 {
2207                         free(buffer);
2208                         break;
2209                 }
2210
2211                 /* calculate checksum of image */
2212                 image_calculate_checksum( buffer, buf_cnt, &checksum );
2213
2214                 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2215                 if( retval != ERROR_OK )
2216                 {
2217                         free(buffer);
2218                         break;
2219                 }
2220
2221                 if( checksum != mem_checksum )
2222                 {
2223                         /* failed crc checksum, fall back to a binary compare */
2224                         u8 *data;
2225
2226                         command_print(cmd_ctx, "checksum mismatch - attempting binary compare");
2227
2228                         data = (u8*)malloc(buf_cnt);
2229
2230                         /* Can we use 32bit word accesses? */
2231                         int size = 1;
2232                         int count = buf_cnt;
2233                         if ((count % 4) == 0)
2234                         {
2235                                 size *= 4;
2236                                 count /= 4;
2237                         }
2238                         retval = target->type->read_memory(target, image.sections[i].base_address, size, count, data);
2239                         if (retval == ERROR_OK)
2240                         {
2241                                 int t;
2242                                 for (t = 0; t < buf_cnt; t++)
2243                                 {
2244                                         if (data[t] != buffer[t])
2245                                         {
2246                                                 command_print(cmd_ctx, "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n", t + image.sections[i].base_address, data[t], buffer[t]);
2247                                                 free(data);
2248                                                 free(buffer);
2249                                                 retval=ERROR_FAIL;
2250                                                 goto done;
2251                                         }
2252                                         if ((t%16384)==0)
2253                                         {
2254                                                 keep_alive();
2255                                         }
2256                                 }
2257                         }
2258
2259                         free(data);
2260                 }
2261
2262                 free(buffer);
2263                 image_size += buf_cnt;
2264         }
2265 done:
2266
2267         if((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2268         {
2269                 image_close(&image);
2270                 return retvaltemp;
2271         }
2272
2273         if (retval==ERROR_OK)
2274         {
2275                 command_print(cmd_ctx, "verified %u bytes in %s", image_size, duration_text);
2276         }
2277         free(duration_text);
2278
2279         image_close(&image);
2280
2281         return retval;
2282 }
2283
2284 int handle_bp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2285 {
2286         int retval;
2287         target_t *target = get_current_target(cmd_ctx);
2288
2289         if (argc == 0)
2290         {
2291                 breakpoint_t *breakpoint = target->breakpoints;
2292
2293                 while (breakpoint)
2294                 {
2295                         if (breakpoint->type == BKPT_SOFT)
2296                         {
2297                                 char* buf = buf_to_str(breakpoint->orig_instr, breakpoint->length, 16);
2298                                 command_print(cmd_ctx, "0x%8.8x, 0x%x, %i, 0x%s", breakpoint->address, breakpoint->length, breakpoint->set, buf);
2299                                 free(buf);
2300                         }
2301                         else
2302                         {
2303                                 command_print(cmd_ctx, "0x%8.8x, 0x%x, %i", breakpoint->address, breakpoint->length, breakpoint->set);
2304                         }
2305                         breakpoint = breakpoint->next;
2306                 }
2307         }
2308         else if (argc >= 2)
2309         {
2310                 int hw = BKPT_SOFT;
2311                 u32 length = 0;
2312
2313                 length = strtoul(args[1], NULL, 0);
2314
2315                 if (argc >= 3)
2316                         if (strcmp(args[2], "hw") == 0)
2317                                 hw = BKPT_HARD;
2318
2319                 if ((retval = breakpoint_add(target, strtoul(args[0], NULL, 0), length, hw)) != ERROR_OK)
2320                 {
2321                         LOG_ERROR("Failure setting breakpoints");
2322                 }
2323                 else
2324                 {
2325                         command_print(cmd_ctx, "breakpoint added at address 0x%8.8x", strtoul(args[0], NULL, 0));
2326                 }
2327         }
2328         else
2329         {
2330                 command_print(cmd_ctx, "usage: bp <address> <length> ['hw']");
2331         }
2332
2333         return ERROR_OK;
2334 }
2335
2336 int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2337 {
2338         target_t *target = get_current_target(cmd_ctx);
2339
2340         if (argc > 0)
2341                 breakpoint_remove(target, strtoul(args[0], NULL, 0));
2342
2343         return ERROR_OK;
2344 }
2345
2346 int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2347 {
2348         target_t *target = get_current_target(cmd_ctx);
2349         int retval;
2350
2351         if (argc == 0)
2352         {
2353                 watchpoint_t *watchpoint = target->watchpoints;
2354
2355                 while (watchpoint)
2356                 {
2357                         command_print(cmd_ctx, "address: 0x%8.8x, len: 0x%8.8x, r/w/a: %i, value: 0x%8.8x, mask: 0x%8.8x", watchpoint->address, watchpoint->length, watchpoint->rw, watchpoint->value, watchpoint->mask);
2358                         watchpoint = watchpoint->next;
2359                 }
2360         }
2361         else if (argc >= 2)
2362         {
2363                 enum watchpoint_rw type = WPT_ACCESS;
2364                 u32 data_value = 0x0;
2365                 u32 data_mask = 0xffffffff;
2366
2367                 if (argc >= 3)
2368                 {
2369                         switch(args[2][0])
2370                         {
2371                                 case 'r':
2372                                         type = WPT_READ;
2373                                         break;
2374                                 case 'w':
2375                                         type = WPT_WRITE;
2376                                         break;
2377                                 case 'a':
2378                                         type = WPT_ACCESS;
2379                                         break;
2380                                 default:
2381                                         command_print(cmd_ctx, "usage: wp <address> <length> [r/w/a] [value] [mask]");
2382                                         return ERROR_OK;
2383                         }
2384                 }
2385                 if (argc >= 4)
2386                 {
2387                         data_value = strtoul(args[3], NULL, 0);
2388                 }
2389                 if (argc >= 5)
2390                 {
2391                         data_mask = strtoul(args[4], NULL, 0);
2392                 }
2393
2394                 if ((retval = watchpoint_add(target, strtoul(args[0], NULL, 0),
2395                                 strtoul(args[1], NULL, 0), type, data_value, data_mask)) != ERROR_OK)
2396                 {
2397                         LOG_ERROR("Failure setting breakpoints");
2398                 }
2399         }
2400         else
2401         {
2402                 command_print(cmd_ctx, "usage: wp <address> <length> [r/w/a] [value] [mask]");
2403         }
2404
2405         return ERROR_OK;
2406 }
2407
2408 int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2409 {
2410         target_t *target = get_current_target(cmd_ctx);
2411
2412         if (argc > 0)
2413                 watchpoint_remove(target, strtoul(args[0], NULL, 0));
2414
2415         return ERROR_OK;
2416 }
2417
2418 int handle_virt2phys_command(command_context_t *cmd_ctx, char *cmd, char **args, int argc)
2419 {
2420         int retval;
2421         target_t *target = get_current_target(cmd_ctx);
2422         u32 va;
2423         u32 pa;
2424
2425         if (argc != 1)
2426         {
2427                 return ERROR_COMMAND_SYNTAX_ERROR;
2428         }
2429         va = strtoul(args[0], NULL, 0);
2430
2431         retval = target->type->virt2phys(target, va, &pa);
2432         if (retval == ERROR_OK)
2433         {
2434                 command_print(cmd_ctx, "Physical address 0x%08x", pa);
2435         }
2436         else
2437         {
2438                 /* lower levels will have logged a detailed error which is
2439                  * forwarded to telnet/GDB session.
2440                  */
2441         }
2442         return retval;
2443 }
2444
2445 static void writeLong(FILE *f, int l)
2446 {
2447         int i;
2448         for (i=0; i<4; i++)
2449         {
2450                 char c=(l>>(i*8))&0xff;
2451                 fwrite(&c, 1, 1, f);
2452         }
2453
2454 }
2455
2456 static void writeString(FILE *f, char *s)
2457 {
2458         fwrite(s, 1, strlen(s), f);
2459 }
2460
2461 /* Dump a gmon.out histogram file. */
2462 static void writeGmon(u32 *samples, int sampleNum, char *filename)
2463 {
2464         int i;
2465         FILE *f=fopen(filename, "w");
2466         if (f==NULL)
2467                 return;
2468         fwrite("gmon", 1, 4, f);
2469         writeLong(f, 0x00000001); /* Version */
2470         writeLong(f, 0); /* padding */
2471         writeLong(f, 0); /* padding */
2472         writeLong(f, 0); /* padding */
2473
2474         fwrite("", 1, 1, f);  /* GMON_TAG_TIME_HIST */
2475
2476         /* figure out bucket size */
2477         u32 min=samples[0];
2478         u32 max=samples[0];
2479         for (i=0; i<sampleNum; i++)
2480         {
2481                 if (min>samples[i])
2482                 {
2483                         min=samples[i];
2484                 }
2485                 if (max<samples[i])
2486                 {
2487                         max=samples[i];
2488                 }
2489         }
2490
2491         int addressSpace=(max-min+1);
2492
2493         static int const maxBuckets=256*1024; /* maximum buckets. */
2494         int length=addressSpace;
2495         if (length > maxBuckets)
2496         {
2497                 length=maxBuckets;
2498         }
2499         int *buckets=malloc(sizeof(int)*length);
2500         if (buckets==NULL)
2501         {
2502                 fclose(f);
2503                 return;
2504         }
2505         memset(buckets, 0, sizeof(int)*length);
2506         for (i=0; i<sampleNum;i++)
2507         {
2508                 u32 address=samples[i];
2509                 long long a=address-min;
2510                 long long b=length-1;
2511                 long long c=addressSpace-1;
2512                 int index=(a*b)/c; /* danger!!!! int32 overflows */
2513                 buckets[index]++;
2514         }
2515
2516         /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
2517         writeLong(f, min);                      /* low_pc */
2518         writeLong(f, max);                      /* high_pc */
2519         writeLong(f, length);           /* # of samples */
2520         writeLong(f, 64000000);         /* 64MHz */
2521         writeString(f, "seconds");
2522         for (i=0; i<(15-strlen("seconds")); i++)
2523         {
2524                 fwrite("", 1, 1, f);    /* padding */
2525         }
2526         writeString(f, "s");
2527
2528         /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
2529
2530         char *data=malloc(2*length);
2531         if (data!=NULL)
2532         {
2533                 for (i=0; i<length;i++)
2534                 {
2535                         int val;
2536                         val=buckets[i];
2537                         if (val>65535)
2538                         {
2539                                 val=65535;
2540                         }
2541                         data[i*2]=val&0xff;
2542                         data[i*2+1]=(val>>8)&0xff;
2543                 }
2544                 free(buckets);
2545                 fwrite(data, 1, length*2, f);
2546                 free(data);
2547         } else
2548         {
2549                 free(buckets);
2550         }
2551
2552         fclose(f);
2553 }
2554
2555 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
2556 int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2557 {
2558         target_t *target = get_current_target(cmd_ctx);
2559         struct timeval timeout, now;
2560
2561         gettimeofday(&timeout, NULL);
2562         if (argc!=2)
2563         {
2564                 return ERROR_COMMAND_SYNTAX_ERROR;
2565         }
2566         char *end;
2567         timeval_add_time(&timeout, strtoul(args[0], &end, 0), 0);
2568         if (*end)
2569         {
2570                 return ERROR_OK;
2571         }
2572
2573         command_print(cmd_ctx, "Starting profiling. Halting and resuming the target as often as we can...");
2574
2575         static const int maxSample=10000;
2576         u32 *samples=malloc(sizeof(u32)*maxSample);
2577         if (samples==NULL)
2578                 return ERROR_OK;
2579
2580         int numSamples=0;
2581         int retval=ERROR_OK;
2582         /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2583         reg_t *reg = register_get_by_name(target->reg_cache, "pc", 1);
2584
2585         for (;;)
2586         {
2587                 target_poll(target);
2588                 if (target->state == TARGET_HALTED)
2589                 {
2590                         u32 t=*((u32 *)reg->value);
2591                         samples[numSamples++]=t;
2592                         retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
2593                         target_poll(target);
2594                         alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2595                 } else if (target->state == TARGET_RUNNING)
2596                 {
2597                         /* We want to quickly sample the PC. */
2598                         if((retval = target_halt(target)) != ERROR_OK)
2599                         {
2600                                 free(samples);
2601                                 return retval;
2602                         }
2603                 } else
2604                 {
2605                         command_print(cmd_ctx, "Target not halted or running");
2606                         retval=ERROR_OK;
2607                         break;
2608                 }
2609                 if (retval!=ERROR_OK)
2610                 {
2611                         break;
2612                 }
2613
2614                 gettimeofday(&now, NULL);
2615                 if ((numSamples>=maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
2616                 {
2617                         command_print(cmd_ctx, "Profiling completed. %d samples.", numSamples);
2618                         if((retval = target_poll(target)) != ERROR_OK)
2619                         {
2620                                 free(samples);
2621                                 return retval;
2622                         }
2623                         if (target->state == TARGET_HALTED)
2624                         {
2625                                 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
2626                         }
2627                         if((retval = target_poll(target)) != ERROR_OK)
2628                         {
2629                                 free(samples);
2630                                 return retval;
2631                         }
2632                         writeGmon(samples, numSamples, args[1]);
2633                         command_print(cmd_ctx, "Wrote %s", args[1]);
2634                         break;
2635                 }
2636         }
2637         free(samples);
2638
2639         return ERROR_OK;
2640 }
2641
2642 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, u32 val)
2643 {
2644         char *namebuf;
2645         Jim_Obj *nameObjPtr, *valObjPtr;
2646         int result;
2647
2648         namebuf = alloc_printf("%s(%d)", varname, idx);
2649         if (!namebuf)
2650                 return JIM_ERR;
2651
2652         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
2653         valObjPtr = Jim_NewIntObj(interp, val);
2654         if (!nameObjPtr || !valObjPtr)
2655         {
2656                 free(namebuf);
2657                 return JIM_ERR;
2658         }
2659
2660         Jim_IncrRefCount(nameObjPtr);
2661         Jim_IncrRefCount(valObjPtr);
2662         result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
2663         Jim_DecrRefCount(interp, nameObjPtr);
2664         Jim_DecrRefCount(interp, valObjPtr);
2665         free(namebuf);
2666         /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
2667         return result;
2668 }
2669
2670 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
2671 {
2672         command_context_t *context;
2673         target_t *target;
2674
2675         context = Jim_GetAssocData(interp, "context");
2676         if (context == NULL)
2677         {
2678                 LOG_ERROR("mem2array: no command context");
2679                 return JIM_ERR;
2680         }
2681         target = get_current_target(context);
2682         if (target == NULL)
2683         {
2684                 LOG_ERROR("mem2array: no current target");
2685                 return JIM_ERR;
2686         }
2687
2688         return  target_mem2array(interp, target, argc,argv);
2689 }
2690
2691 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
2692 {
2693         long l;
2694         u32 width;
2695         int len;
2696         u32 addr;
2697         u32 count;
2698         u32 v;
2699         const char *varname;
2700         u8 buffer[4096];
2701         int  i, n, e, retval;
2702
2703         /* argv[1] = name of array to receive the data
2704          * argv[2] = desired width
2705          * argv[3] = memory address
2706          * argv[4] = count of times to read
2707          */
2708         if (argc != 5) {
2709                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
2710                 return JIM_ERR;
2711         }
2712         varname = Jim_GetString(argv[1], &len);
2713         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
2714
2715         e = Jim_GetLong(interp, argv[2], &l);
2716         width = l;
2717         if (e != JIM_OK) {
2718                 return e;
2719         }
2720
2721         e = Jim_GetLong(interp, argv[3], &l);
2722         addr = l;
2723         if (e != JIM_OK) {
2724                 return e;
2725         }
2726         e = Jim_GetLong(interp, argv[4], &l);
2727         len = l;
2728         if (e != JIM_OK) {
2729                 return e;
2730         }
2731         switch (width) {
2732                 case 8:
2733                         width = 1;
2734                         break;
2735                 case 16:
2736                         width = 2;
2737                         break;
2738                 case 32:
2739                         width = 4;
2740                         break;
2741                 default:
2742                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2743                         Jim_AppendStrings( interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL );
2744                         return JIM_ERR;
2745         }
2746         if (len == 0) {
2747                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2748                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
2749                 return JIM_ERR;
2750         }
2751         if ((addr + (len * width)) < addr) {
2752                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2753                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
2754                 return JIM_ERR;
2755         }
2756         /* absurd transfer size? */
2757         if (len > 65536) {
2758                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2759                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
2760                 return JIM_ERR;
2761         }
2762
2763         if ((width == 1) ||
2764                 ((width == 2) && ((addr & 1) == 0)) ||
2765                 ((width == 4) && ((addr & 3) == 0))) {
2766                 /* all is well */
2767         } else {
2768                 char buf[100];
2769                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2770                 sprintf(buf, "mem2array address: 0x%08x is not aligned for %d byte reads", addr, width);
2771                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
2772                 return JIM_ERR;
2773         }
2774
2775         /* Transfer loop */
2776
2777         /* index counter */
2778         n = 0;
2779         /* assume ok */
2780         e = JIM_OK;
2781         while (len) {
2782                 /* Slurp... in buffer size chunks */
2783
2784                 count = len; /* in objects.. */
2785                 if (count > (sizeof(buffer)/width)) {
2786                         count = (sizeof(buffer)/width);
2787                 }
2788
2789                 retval = target->type->read_memory( target, addr, width, count, buffer );
2790                 if (retval != ERROR_OK) {
2791                         /* BOO !*/
2792                         LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed", addr, width, count);
2793                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2794                         Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
2795                         e = JIM_ERR;
2796                         len = 0;
2797                 } else {
2798                         v = 0; /* shut up gcc */
2799                         for (i = 0 ;i < count ;i++, n++) {
2800                                 switch (width) {
2801                                         case 4:
2802                                                 v = target_buffer_get_u32(target, &buffer[i*width]);
2803                                                 break;
2804                                         case 2:
2805                                                 v = target_buffer_get_u16(target, &buffer[i*width]);
2806                                                 break;
2807                                         case 1:
2808                                                 v = buffer[i] & 0x0ff;
2809                                                 break;
2810                                 }
2811                                 new_int_array_element(interp, varname, n, v);
2812                         }
2813                         len -= count;
2814                 }
2815         }
2816
2817         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2818
2819         return JIM_OK;
2820 }
2821
2822 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, u32 *val)
2823 {
2824         char *namebuf;
2825         Jim_Obj *nameObjPtr, *valObjPtr;
2826         int result;
2827         long l;
2828
2829         namebuf = alloc_printf("%s(%d)", varname, idx);
2830         if (!namebuf)
2831                 return JIM_ERR;
2832
2833         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
2834         if (!nameObjPtr)
2835         {
2836                 free(namebuf);
2837                 return JIM_ERR;
2838         }
2839
2840         Jim_IncrRefCount(nameObjPtr);
2841         valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
2842         Jim_DecrRefCount(interp, nameObjPtr);
2843         free(namebuf);
2844         if (valObjPtr == NULL)
2845                 return JIM_ERR;
2846
2847         result = Jim_GetLong(interp, valObjPtr, &l);
2848         /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
2849         *val = l;
2850         return result;
2851 }
2852
2853 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
2854 {
2855         command_context_t *context;
2856         target_t *target;
2857
2858         context = Jim_GetAssocData(interp, "context");
2859         if (context == NULL){
2860                 LOG_ERROR("array2mem: no command context");
2861                 return JIM_ERR;
2862         }
2863         target = get_current_target(context);
2864         if (target == NULL){
2865                 LOG_ERROR("array2mem: no current target");
2866                 return JIM_ERR;
2867         }
2868
2869         return target_array2mem( interp,target, argc, argv );
2870 }
2871
2872 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
2873 {
2874         long l;
2875         u32 width;
2876         int len;
2877         u32 addr;
2878         u32 count;
2879         u32 v;
2880         const char *varname;
2881         u8 buffer[4096];
2882         int  i, n, e, retval;
2883
2884         /* argv[1] = name of array to get the data
2885          * argv[2] = desired width
2886          * argv[3] = memory address
2887          * argv[4] = count to write
2888          */
2889         if (argc != 5) {
2890                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
2891                 return JIM_ERR;
2892         }
2893         varname = Jim_GetString(argv[1], &len);
2894         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
2895
2896         e = Jim_GetLong(interp, argv[2], &l);
2897         width = l;
2898         if (e != JIM_OK) {
2899                 return e;
2900         }
2901
2902         e = Jim_GetLong(interp, argv[3], &l);
2903         addr = l;
2904         if (e != JIM_OK) {
2905                 return e;
2906         }
2907         e = Jim_GetLong(interp, argv[4], &l);
2908         len = l;
2909         if (e != JIM_OK) {
2910                 return e;
2911         }
2912         switch (width) {
2913                 case 8:
2914                         width = 1;
2915                         break;
2916                 case 16:
2917                         width = 2;
2918                         break;
2919                 case 32:
2920                         width = 4;
2921                         break;
2922                 default:
2923                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2924                         Jim_AppendStrings( interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL );
2925                         return JIM_ERR;
2926         }
2927         if (len == 0) {
2928                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2929                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
2930                 return JIM_ERR;
2931         }
2932         if ((addr + (len * width)) < addr) {
2933                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2934                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
2935                 return JIM_ERR;
2936         }
2937         /* absurd transfer size? */
2938         if (len > 65536) {
2939                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2940                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
2941                 return JIM_ERR;
2942         }
2943
2944         if ((width == 1) ||
2945                 ((width == 2) && ((addr & 1) == 0)) ||
2946                 ((width == 4) && ((addr & 3) == 0))) {
2947                 /* all is well */
2948         } else {
2949                 char buf[100];
2950                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2951                 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads", addr, width);
2952                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
2953                 return JIM_ERR;
2954         }
2955
2956         /* Transfer loop */
2957
2958         /* index counter */
2959         n = 0;
2960         /* assume ok */
2961         e = JIM_OK;
2962         while (len) {
2963                 /* Slurp... in buffer size chunks */
2964
2965                 count = len; /* in objects.. */
2966                 if (count > (sizeof(buffer)/width)) {
2967                         count = (sizeof(buffer)/width);
2968                 }
2969
2970                 v = 0; /* shut up gcc */
2971                 for (i = 0 ;i < count ;i++, n++) {
2972                         get_int_array_element(interp, varname, n, &v);
2973                         switch (width) {
2974                         case 4:
2975                                 target_buffer_set_u32(target, &buffer[i*width], v);
2976                                 break;
2977                         case 2:
2978                                 target_buffer_set_u16(target, &buffer[i*width], v);
2979                                 break;
2980                         case 1:
2981                                 buffer[i] = v & 0x0ff;
2982                                 break;
2983                         }
2984                 }
2985                 len -= count;
2986
2987                 retval = target->type->write_memory(target, addr, width, count, buffer);
2988                 if (retval != ERROR_OK) {
2989                         /* BOO !*/
2990                         LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed", addr, width, count);
2991                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2992                         Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
2993                         e = JIM_ERR;
2994                         len = 0;
2995                 }
2996         }
2997
2998         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2999
3000         return JIM_OK;
3001 }
3002
3003 void target_all_handle_event( enum target_event e )
3004 {
3005         target_t *target;
3006
3007         LOG_DEBUG( "**all*targets: event: %d, %s",
3008                         e,
3009                         Jim_Nvp_value2name_simple( nvp_target_event, e )->name );
3010
3011         target = all_targets;
3012         while (target){
3013                 target_handle_event( target, e );
3014                 target = target->next;
3015         }
3016 }
3017
3018 void target_handle_event( target_t *target, enum target_event e )
3019 {
3020         target_event_action_t *teap;
3021         int done;
3022
3023         teap = target->event_action;
3024
3025         done = 0;
3026         while( teap ){
3027                 if( teap->event == e ){
3028                         done = 1;
3029                         LOG_DEBUG( "target: (%d) %s (%s) event: %d (%s) action: %s\n",
3030                                            target->target_number,
3031                                            target->cmd_name,
3032                                            target->type->name,
3033                                            e,
3034                                            Jim_Nvp_value2name_simple( nvp_target_event, e )->name,
3035                                            Jim_GetString( teap->body, NULL ) );
3036                         if (Jim_EvalObj( interp, teap->body )!=JIM_OK)
3037                         {
3038                                 Jim_PrintErrorMessage(interp);
3039                         }
3040                 }
3041                 teap = teap->next;
3042         }
3043         if( !done ){
3044                 LOG_DEBUG( "event: %d %s - no action",
3045                                    e,
3046                                    Jim_Nvp_value2name_simple( nvp_target_event, e )->name );
3047         }
3048 }
3049
3050 enum target_cfg_param {
3051         TCFG_TYPE,
3052         TCFG_EVENT,
3053         TCFG_WORK_AREA_VIRT,
3054         TCFG_WORK_AREA_PHYS,
3055         TCFG_WORK_AREA_SIZE,
3056         TCFG_WORK_AREA_BACKUP,
3057         TCFG_ENDIAN,
3058         TCFG_VARIANT,
3059         TCFG_CHAIN_POSITION,
3060 };
3061
3062 static Jim_Nvp nvp_config_opts[] = {
3063         { .name = "-type",             .value = TCFG_TYPE },
3064         { .name = "-event",            .value = TCFG_EVENT },
3065         { .name = "-work-area-virt",   .value = TCFG_WORK_AREA_VIRT },
3066         { .name = "-work-area-phys",   .value = TCFG_WORK_AREA_PHYS },
3067         { .name = "-work-area-size",   .value = TCFG_WORK_AREA_SIZE },
3068         { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3069         { .name = "-endian" ,          .value = TCFG_ENDIAN },
3070         { .name = "-variant",          .value = TCFG_VARIANT },
3071         { .name = "-chain-position",   .value = TCFG_CHAIN_POSITION },
3072
3073         { .name = NULL, .value = -1 }
3074 };
3075
3076 static int target_configure( Jim_GetOptInfo *goi, target_t *target )
3077 {
3078         Jim_Nvp *n;
3079         Jim_Obj *o;
3080         jim_wide w;
3081         char *cp;
3082         int e;
3083
3084         /* parse config or cget options ... */
3085         while( goi->argc > 0 ){
3086                 Jim_SetEmptyResult( goi->interp );
3087                 /* Jim_GetOpt_Debug( goi ); */
3088
3089                 if( target->type->target_jim_configure ){
3090                         /* target defines a configure function */
3091                         /* target gets first dibs on parameters */
3092                         e = (*(target->type->target_jim_configure))( target, goi );
3093                         if( e == JIM_OK ){
3094                                 /* more? */
3095                                 continue;
3096                         }
3097                         if( e == JIM_ERR ){
3098                                 /* An error */
3099                                 return e;
3100                         }
3101                         /* otherwise we 'continue' below */
3102                 }
3103                 e = Jim_GetOpt_Nvp( goi, nvp_config_opts, &n );
3104                 if( e != JIM_OK ){
3105                         Jim_GetOpt_NvpUnknown( goi, nvp_config_opts, 0 );
3106                         return e;
3107                 }
3108                 switch( n->value ){
3109                 case TCFG_TYPE:
3110                         /* not setable */
3111                         if( goi->isconfigure ){
3112                                 Jim_SetResult_sprintf( goi->interp, "not setable: %s", n->name );
3113                                 return JIM_ERR;
3114                         } else {
3115                         no_params:
3116                                 if( goi->argc != 0 ){
3117                                         Jim_WrongNumArgs( goi->interp, goi->argc, goi->argv, "NO PARAMS");
3118                                         return JIM_ERR;
3119                                 }
3120                         }
3121                         Jim_SetResultString( goi->interp, target->type->name, -1 );
3122                         /* loop for more */
3123                         break;
3124                 case TCFG_EVENT:
3125                         if( goi->argc == 0 ){
3126                                 Jim_WrongNumArgs( goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3127                                 return JIM_ERR;
3128                         }
3129
3130                         e = Jim_GetOpt_Nvp( goi, nvp_target_event, &n );
3131                         if( e != JIM_OK ){
3132                                 Jim_GetOpt_NvpUnknown( goi, nvp_target_event, 1 );
3133                                 return e;
3134                         }
3135
3136                         if( goi->isconfigure ){
3137                                 if( goi->argc != 1 ){
3138                                         Jim_WrongNumArgs( goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3139                                         return JIM_ERR;
3140                                 }
3141                         } else {
3142                                 if( goi->argc != 0 ){
3143                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3144                                         return JIM_ERR;
3145                                 }
3146                         }
3147
3148                         {
3149                                 target_event_action_t *teap;
3150
3151                                 teap = target->event_action;
3152                                 /* replace existing? */
3153                                 while( teap ){
3154                                         if( teap->event == n->value ){
3155                                                 break;
3156                                         }
3157                                         teap = teap->next;
3158                                 }
3159
3160                                 if( goi->isconfigure ){
3161                                         if( teap == NULL ){
3162                                                 /* create new */
3163                                                 teap = calloc( 1, sizeof(*teap) );
3164                                         }
3165                                         teap->event = n->value;
3166                                         Jim_GetOpt_Obj( goi, &o );
3167                                         if( teap->body ){
3168                                                 Jim_DecrRefCount( interp, teap->body );
3169                                         }
3170                                         teap->body  = Jim_DuplicateObj( goi->interp, o );
3171                                         /*
3172                                          * FIXME:
3173                                          *     Tcl/TK - "tk events" have a nice feature.
3174                                          *     See the "BIND" command.
3175                                          *    We should support that here.
3176                                          *     You can specify %X and %Y in the event code.
3177                                          *     The idea is: %T - target name.
3178                                          *     The idea is: %N - target number
3179                                          *     The idea is: %E - event name.
3180                                          */
3181                                         Jim_IncrRefCount( teap->body );
3182
3183                                         /* add to head of event list */
3184                                         teap->next = target->event_action;
3185                                         target->event_action = teap;
3186                                         Jim_SetEmptyResult(goi->interp);
3187                                 } else {
3188                                         /* get */
3189                                         if( teap == NULL ){
3190                                                 Jim_SetEmptyResult( goi->interp );
3191                                         } else {
3192                                                 Jim_SetResult( goi->interp, Jim_DuplicateObj( goi->interp, teap->body ) );
3193                                         }
3194                                 }
3195                         }
3196                         /* loop for more */
3197                         break;
3198
3199                 case TCFG_WORK_AREA_VIRT:
3200                         if( goi->isconfigure ){
3201                                 target_free_all_working_areas(target);
3202                                 e = Jim_GetOpt_Wide( goi, &w );
3203                                 if( e != JIM_OK ){
3204                                         return e;
3205                                 }
3206                                 target->working_area_virt = w;
3207                         } else {
3208                                 if( goi->argc != 0 ){
3209                                         goto no_params;
3210                                 }
3211                         }
3212                         Jim_SetResult( interp, Jim_NewIntObj( goi->interp, target->working_area_virt ) );
3213                         /* loop for more */
3214                         break;
3215
3216                 case TCFG_WORK_AREA_PHYS:
3217                         if( goi->isconfigure ){
3218                                 target_free_all_working_areas(target);
3219                                 e = Jim_GetOpt_Wide( goi, &w );
3220                                 if( e != JIM_OK ){
3221                                         return e;
3222                                 }
3223                                 target->working_area_phys = w;
3224                         } else {
3225                                 if( goi->argc != 0 ){
3226                                         goto no_params;
3227                                 }
3228                         }
3229                         Jim_SetResult( interp, Jim_NewIntObj( goi->interp, target->working_area_phys ) );
3230                         /* loop for more */
3231                         break;
3232
3233                 case TCFG_WORK_AREA_SIZE:
3234                         if( goi->isconfigure ){
3235                                 target_free_all_working_areas(target);
3236                                 e = Jim_GetOpt_Wide( goi, &w );
3237                                 if( e != JIM_OK ){
3238                                         return e;
3239                                 }
3240                                 target->working_area_size = w;
3241                         } else {
3242                                 if( goi->argc != 0 ){
3243                                         goto no_params;
3244                                 }
3245                         }
3246                         Jim_SetResult( interp, Jim_NewIntObj( goi->interp, target->working_area_size ) );
3247                         /* loop for more */
3248                         break;
3249
3250                 case TCFG_WORK_AREA_BACKUP:
3251                         if( goi->isconfigure ){
3252                                 target_free_all_working_areas(target);
3253                                 e = Jim_GetOpt_Wide( goi, &w );
3254                                 if( e != JIM_OK ){
3255                                         return e;
3256                                 }
3257                                 /* make this exactly 1 or 0 */
3258                                 target->backup_working_area = (!!w);
3259                         } else {
3260                                 if( goi->argc != 0 ){
3261                                         goto no_params;
3262                                 }
3263                         }
3264                         Jim_SetResult( interp, Jim_NewIntObj( goi->interp, target->working_area_size ) );
3265                         /* loop for more e*/
3266                         break;
3267
3268                 case TCFG_ENDIAN:
3269                         if( goi->isconfigure ){
3270                                 e = Jim_GetOpt_Nvp( goi, nvp_target_endian, &n );
3271                                 if( e != JIM_OK ){
3272                                         Jim_GetOpt_NvpUnknown( goi, nvp_target_endian, 1 );
3273                                         return e;
3274                                 }
3275                                 target->endianness = n->value;
3276                         } else {
3277                                 if( goi->argc != 0 ){
3278                                         goto no_params;
3279                                 }
3280                         }
3281                         n = Jim_Nvp_value2name_simple( nvp_target_endian, target->endianness );
3282                         if( n->name == NULL ){
3283                                 target->endianness = TARGET_LITTLE_ENDIAN;
3284                                 n = Jim_Nvp_value2name_simple( nvp_target_endian, target->endianness );
3285                         }
3286                         Jim_SetResultString( goi->interp, n->name, -1 );
3287                         /* loop for more */
3288                         break;
3289
3290                 case TCFG_VARIANT:
3291                         if( goi->isconfigure ){
3292                                 if( goi->argc < 1 ){
3293                                         Jim_SetResult_sprintf( goi->interp,
3294                                                                                    "%s ?STRING?",
3295                                                                                    n->name );
3296                                         return JIM_ERR;
3297                                 }
3298                                 if( target->variant ){
3299                                         free((void *)(target->variant));
3300                                 }
3301                                 e = Jim_GetOpt_String( goi, &cp, NULL );
3302                                 target->variant = strdup(cp);
3303                         } else {
3304                                 if( goi->argc != 0 ){
3305                                         goto no_params;
3306                                 }
3307                         }
3308                         Jim_SetResultString( goi->interp, target->variant,-1 );
3309                         /* loop for more */
3310                         break;
3311                 case TCFG_CHAIN_POSITION:
3312                         if( goi->isconfigure ){
3313                                 Jim_Obj *o;
3314                                 jtag_tap_t *tap;
3315                                 target_free_all_working_areas(target);
3316                                 e = Jim_GetOpt_Obj( goi, &o );
3317                                 if( e != JIM_OK ){
3318                                         return e;
3319                                 }
3320                                 tap = jtag_TapByJimObj( goi->interp, o );
3321                                 if( tap == NULL ){
3322                                         return JIM_ERR;
3323                                 }
3324                                 /* make this exactly 1 or 0 */
3325                                 target->tap = tap;
3326                         } else {
3327                                 if( goi->argc != 0 ){
3328                                         goto no_params;
3329                                 }
3330                         }
3331                         Jim_SetResultString( interp, target->tap->dotted_name, -1 );
3332                         /* loop for more e*/
3333                         break;
3334                 }
3335         } /* while( goi->argc ) */
3336                 /* done - we return */
3337         return JIM_OK;
3338 }
3339
3340 /** this is the 'tcl' handler for the target specific command */
3341 static int tcl_target_func( Jim_Interp *interp, int argc, Jim_Obj *const *argv )
3342 {
3343         Jim_GetOptInfo goi;
3344         jim_wide a,b,c;
3345         int x,y,z;
3346         u8  target_buf[32];
3347         Jim_Nvp *n;
3348         target_t *target;
3349         struct command_context_s *cmd_ctx;
3350         int e;
3351
3352         enum {
3353                 TS_CMD_CONFIGURE,
3354                 TS_CMD_CGET,
3355
3356                 TS_CMD_MWW, TS_CMD_MWH, TS_CMD_MWB,
3357                 TS_CMD_MDW, TS_CMD_MDH, TS_CMD_MDB,
3358                 TS_CMD_MRW, TS_CMD_MRH, TS_CMD_MRB,
3359                 TS_CMD_MEM2ARRAY, TS_CMD_ARRAY2MEM,
3360                 TS_CMD_EXAMINE,
3361                 TS_CMD_POLL,
3362                 TS_CMD_RESET,
3363                 TS_CMD_HALT,
3364                 TS_CMD_WAITSTATE,
3365                 TS_CMD_EVENTLIST,
3366                 TS_CMD_CURSTATE,
3367                 TS_CMD_INVOKE_EVENT,
3368         };
3369
3370         static const Jim_Nvp target_options[] = {
3371                 { .name = "configure", .value = TS_CMD_CONFIGURE },
3372                 { .name = "cget", .value = TS_CMD_CGET },
3373                 { .name = "mww", .value = TS_CMD_MWW },
3374                 { .name = "mwh", .value = TS_CMD_MWH },
3375                 { .name = "mwb", .value = TS_CMD_MWB },
3376                 { .name = "mdw", .value = TS_CMD_MDW },
3377                 { .name = "mdh", .value = TS_CMD_MDH },
3378                 { .name = "mdb", .value = TS_CMD_MDB },
3379                 { .name = "mem2array", .value = TS_CMD_MEM2ARRAY },
3380                 { .name = "array2mem", .value = TS_CMD_ARRAY2MEM },
3381                 { .name = "eventlist", .value = TS_CMD_EVENTLIST },
3382                 { .name = "curstate",  .value = TS_CMD_CURSTATE },
3383
3384                 { .name = "arp_examine", .value = TS_CMD_EXAMINE },
3385                 { .name = "arp_poll", .value = TS_CMD_POLL },
3386                 { .name = "arp_reset", .value = TS_CMD_RESET },
3387                 { .name = "arp_halt", .value = TS_CMD_HALT },
3388                 { .name = "arp_waitstate", .value = TS_CMD_WAITSTATE },
3389                 { .name = "invoke-event", .value = TS_CMD_INVOKE_EVENT },
3390
3391                 { .name = NULL, .value = -1 },
3392         };
3393
3394         /* go past the "command" */
3395         Jim_GetOpt_Setup( &goi, interp, argc-1, argv+1 );
3396
3397         target = Jim_CmdPrivData( goi.interp );
3398         cmd_ctx = Jim_GetAssocData(goi.interp, "context");
3399
3400         /* commands here are in an NVP table */
3401         e = Jim_GetOpt_Nvp( &goi, target_options, &n );
3402         if( e != JIM_OK ){
3403                 Jim_GetOpt_NvpUnknown( &goi, target_options, 0 );
3404                 return e;
3405         }
3406         /* Assume blank result */
3407         Jim_SetEmptyResult( goi.interp );
3408
3409         switch( n->value ){
3410         case TS_CMD_CONFIGURE:
3411                 if( goi.argc < 2 ){
3412                         Jim_WrongNumArgs( goi.interp, goi.argc, goi.argv, "missing: -option VALUE ...");
3413                         return JIM_ERR;
3414                 }
3415                 goi.isconfigure = 1;
3416                 return target_configure( &goi, target );
3417         case TS_CMD_CGET:
3418                 // some things take params
3419                 if( goi.argc < 1 ){
3420                         Jim_WrongNumArgs( goi.interp, 0, goi.argv, "missing: ?-option?");
3421                         return JIM_ERR;
3422                 }
3423                 goi.isconfigure = 0;
3424                 return target_configure( &goi, target );
3425                 break;
3426         case TS_CMD_MWW:
3427         case TS_CMD_MWH:
3428         case TS_CMD_MWB:
3429                 /* argv[0] = cmd
3430                  * argv[1] = address
3431                  * argv[2] = data
3432                  * argv[3] = optional count.
3433                  */
3434
3435                 if( (goi.argc == 3) || (goi.argc == 4) ){
3436                         /* all is well */
3437                 } else {
3438                 mwx_error:
3439                         Jim_SetResult_sprintf( goi.interp, "expected: %s ADDR DATA [COUNT]", n->name );
3440                         return JIM_ERR;
3441                 }
3442
3443                 e = Jim_GetOpt_Wide( &goi, &a );
3444                 if( e != JIM_OK ){
3445                         goto mwx_error;
3446                 }
3447
3448                 e = Jim_GetOpt_Wide( &goi, &b );
3449                 if( e != JIM_OK ){
3450                         goto mwx_error;
3451                 }
3452                 if( goi.argc ){
3453                         e = Jim_GetOpt_Wide( &goi, &c );
3454                         if( e != JIM_OK ){
3455                                 goto mwx_error;
3456                         }
3457                 } else {
3458                         c = 1;
3459                 }
3460
3461                 switch( n->value ){
3462                 case TS_CMD_MWW:
3463                         target_buffer_set_u32( target, target_buf, b );
3464                         b = 4;
3465                         break;
3466                 case TS_CMD_MWH:
3467                         target_buffer_set_u16( target, target_buf, b );
3468                         b = 2;
3469                         break;
3470                 case TS_CMD_MWB:
3471                         target_buffer_set_u8( target, target_buf, b );
3472                         b = 1;
3473                         break;
3474                 }
3475                 for( x = 0 ; x < c ; x++ ){
3476                         e = target->type->write_memory( target, a, b, 1, target_buf );
3477                         if( e != ERROR_OK ){
3478                                 Jim_SetResult_sprintf( interp, "Error writing @ 0x%08x: %d\n", (int)(a), e );
3479                                 return JIM_ERR;
3480                         }
3481                         /* b = width */
3482                         a = a + b;
3483                 }
3484                 return JIM_OK;
3485                 break;
3486
3487                 /* display */
3488         case TS_CMD_MDW:
3489         case TS_CMD_MDH:
3490         case TS_CMD_MDB:
3491                 /* argv[0] = command
3492                  * argv[1] = address
3493                  * argv[2] = optional count
3494                  */
3495                 if( (goi.argc == 2) || (goi.argc == 3) ){
3496                         Jim_SetResult_sprintf( goi.interp, "expected: %s ADDR [COUNT]", n->name );
3497                         return JIM_ERR;
3498                 }
3499                 e = Jim_GetOpt_Wide( &goi, &a );
3500                 if( e != JIM_OK ){
3501                         return JIM_ERR;
3502                 }
3503                 if( goi.argc ){
3504                         e = Jim_GetOpt_Wide( &goi, &c );
3505                         if( e != JIM_OK ){
3506                                 return JIM_ERR;
3507                         }
3508                 } else {
3509                         c = 1;
3510                 }
3511                 b = 1; /* shut up gcc */
3512                 switch( n->value ){
3513                 case TS_CMD_MDW:
3514                         b =  4;
3515                         break;
3516                 case TS_CMD_MDH:
3517                         b = 2;
3518                         break;
3519                 case TS_CMD_MDB:
3520                         b = 1;
3521                         break;
3522                 }
3523
3524                 /* convert to "bytes" */
3525                 c = c * b;
3526                 /* count is now in 'BYTES' */
3527                 while( c > 0 ){
3528                         y = c;
3529                         if( y > 16 ){
3530                                 y = 16;
3531                         }
3532                         e = target->type->read_memory( target, a, b, y / b, target_buf );
3533                         if( e != ERROR_OK ){
3534                                 Jim_SetResult_sprintf( interp, "error reading target @ 0x%08lx", (int)(a) );
3535                                 return JIM_ERR;
3536                         }
3537
3538                         Jim_fprintf( interp, interp->cookie_stdout, "0x%08x ", (int)(a) );
3539                         switch( b ){
3540                         case 4:
3541                                 for( x = 0 ; (x < 16) && (x < y) ; x += 4 ){
3542                                         z = target_buffer_get_u32( target, &(target_buf[ x * 4 ]) );
3543                                         Jim_fprintf( interp, interp->cookie_stdout, "%08x ", (int)(z) );
3544                                 }
3545                                 for( ; (x < 16) ; x += 4 ){
3546                                         Jim_fprintf( interp, interp->cookie_stdout, "         " );
3547                                 }
3548                                 break;
3549                         case 2:
3550                                 for( x = 0 ; (x < 16) && (x < y) ; x += 2 ){
3551                                         z = target_buffer_get_u16( target, &(target_buf[ x * 2 ]) );
3552                                         Jim_fprintf( interp, interp->cookie_stdout, "%04x ", (int)(z) );
3553                                 }
3554                                 for( ; (x < 16) ; x += 2 ){
3555                                         Jim_fprintf( interp, interp->cookie_stdout, "     " );
3556                                 }
3557                                 break;
3558                         case 1:
3559                         default:
3560                                 for( x = 0 ; (x < 16) && (x < y) ; x += 1 ){
3561                                         z = target_buffer_get_u8( target, &(target_buf[ x * 4 ]) );
3562                                         Jim_fprintf( interp, interp->cookie_stdout, "%02x ", (int)(z) );
3563                                 }
3564                                 for( ; (x < 16) ; x += 1 ){
3565                                         Jim_fprintf( interp, interp->cookie_stdout, "   " );
3566                                 }
3567                                 break;
3568                         }
3569                         /* ascii-ify the bytes */
3570                         for( x = 0 ; x < y ; x++ ){
3571                                 if( (target_buf[x] >= 0x20) &&
3572                                         (target_buf[x] <= 0x7e) ){
3573                                         /* good */
3574                                 } else {
3575                                         /* smack it */
3576                                         target_buf[x] = '.';
3577                                 }
3578                         }
3579                         /* space pad  */
3580                         while( x < 16 ){
3581                                 target_buf[x] = ' ';
3582                                 x++;
3583                         }
3584                         /* terminate */
3585                         target_buf[16] = 0;
3586                         /* print - with a newline */
3587                         Jim_fprintf( interp, interp->cookie_stdout, "%s\n", target_buf );
3588                         /* NEXT... */
3589                         c -= 16;
3590                         a += 16;
3591                 }
3592                 return JIM_OK;
3593         case TS_CMD_MEM2ARRAY:
3594                 return target_mem2array( goi.interp, target, goi.argc, goi.argv );
3595                 break;
3596         case TS_CMD_ARRAY2MEM:
3597                 return target_array2mem( goi.interp, target, goi.argc, goi.argv );
3598                 break;
3599         case TS_CMD_EXAMINE:
3600                 if( goi.argc ){
3601                         Jim_WrongNumArgs( goi.interp, 2, argv, "[no parameters]");
3602                         return JIM_ERR;
3603                 }
3604                 e = target->type->examine( target );
3605                 if( e != ERROR_OK ){
3606                         Jim_SetResult_sprintf( interp, "examine-fails: %d", e );
3607                         return JIM_ERR;
3608                 }
3609                 return JIM_OK;
3610         case TS_CMD_POLL:
3611                 if( goi.argc ){
3612                         Jim_WrongNumArgs( goi.interp, 2, argv, "[no parameters]");
3613                         return JIM_ERR;
3614                 }
3615                 if( !(target->type->examined) ){
3616                         e = ERROR_TARGET_NOT_EXAMINED;
3617                 } else {
3618                         e = target->type->poll( target );
3619                 }
3620                 if( e != ERROR_OK ){
3621                         Jim_SetResult_sprintf( interp, "poll-fails: %d", e );
3622                         return JIM_ERR;
3623                 } else {
3624                         return JIM_OK;
3625                 }
3626                 break;
3627         case TS_CMD_RESET:
3628                 if( goi.argc != 2 ){
3629                         Jim_WrongNumArgs( interp, 2, argv, "t|f|assert|deassert BOOL");
3630                         return JIM_ERR;
3631                 }
3632                 e = Jim_GetOpt_Nvp( &goi, nvp_assert, &n );
3633                 if( e != JIM_OK ){
3634                         Jim_GetOpt_NvpUnknown( &goi, nvp_assert, 1 );
3635                         return e;
3636                 }
3637                 /* the halt or not param */
3638                 e = Jim_GetOpt_Wide( &goi, &a);
3639                 if( e != JIM_OK ){
3640                         return e;
3641                 }
3642                 /* determine if we should halt or not. */
3643                 target->reset_halt = !!a;
3644                 /* When this happens - all workareas are invalid. */
3645                 target_free_all_working_areas_restore(target, 0);
3646
3647                 /* do the assert */
3648                 if( n->value == NVP_ASSERT ){
3649                         target->type->assert_reset( target );
3650                 } else {
3651                         target->type->deassert_reset( target );
3652                 }
3653                 return JIM_OK;
3654         case TS_CMD_HALT:
3655                 if( goi.argc ){
3656                         Jim_WrongNumArgs( goi.interp, 0, argv, "halt [no parameters]");
3657                         return JIM_ERR;
3658                 }
3659                 target->type->halt( target );
3660                 return JIM_OK;
3661         case TS_CMD_WAITSTATE:
3662                 /* params:  <name>  statename timeoutmsecs */
3663                 if( goi.argc != 2 ){
3664                         Jim_SetResult_sprintf( goi.interp, "%s STATENAME TIMEOUTMSECS", n->name );
3665                         return JIM_ERR;
3666                 }
3667                 e = Jim_GetOpt_Nvp( &goi, nvp_target_state, &n );
3668                 if( e != JIM_OK ){
3669                         Jim_GetOpt_NvpUnknown( &goi, nvp_target_state,1 );
3670                         return e;
3671                 }
3672                 e = Jim_GetOpt_Wide( &goi, &a );
3673                 if( e != JIM_OK ){
3674                         return e;
3675                 }
3676                 e = target_wait_state( target, n->value, a );
3677                 if( e != ERROR_OK ){
3678                         Jim_SetResult_sprintf( goi.interp,
3679                                                                    "target: %s wait %s fails (%d) %s",
3680                                                                    target->cmd_name,
3681                                                                    n->name,
3682                                                                    e, target_strerror_safe(e) );
3683                         return JIM_ERR;
3684                 } else {
3685                         return JIM_OK;
3686                 }
3687         case TS_CMD_EVENTLIST:
3688                 /* List for human, Events defined for this target.
3689                  * scripts/programs should use 'name cget -event NAME'
3690                  */
3691                 {
3692                         target_event_action_t *teap;
3693                         teap = target->event_action;
3694                         command_print( cmd_ctx, "Event actions for target (%d) %s\n",
3695                                                    target->target_number,
3696                                                    target->cmd_name );
3697                         command_print( cmd_ctx, "%-25s | Body", "Event");
3698                         command_print( cmd_ctx, "------------------------- | ----------------------------------------");
3699                         while( teap ){
3700                                 command_print( cmd_ctx,
3701                                                            "%-25s | %s",
3702                                                            Jim_Nvp_value2name_simple( nvp_target_event, teap->event )->name,
3703                                                            Jim_GetString( teap->body, NULL ) );
3704                                 teap = teap->next;
3705                         }
3706                         command_print( cmd_ctx, "***END***");
3707                         return JIM_OK;
3708                 }
3709         case TS_CMD_CURSTATE:
3710                 if( goi.argc != 0 ){
3711                         Jim_WrongNumArgs( goi.interp, 0, argv, "[no parameters]");
3712                         return JIM_ERR;
3713                 }
3714                 Jim_SetResultString( goi.interp,
3715                                                          Jim_Nvp_value2name_simple(nvp_target_state,target->state)->name,-1);
3716                 return JIM_OK;
3717         case TS_CMD_INVOKE_EVENT:
3718                 if( goi.argc != 1 ){
3719                         Jim_SetResult_sprintf( goi.interp, "%s ?EVENTNAME?",n->name);
3720                         return JIM_ERR;
3721                 }
3722                 e = Jim_GetOpt_Nvp( &goi, nvp_target_event, &n );
3723                 if( e != JIM_OK ){
3724                         Jim_GetOpt_NvpUnknown( &goi, nvp_target_event, 1 );
3725                         return e;
3726                 }
3727                 target_handle_event( target, n->value );
3728                 return JIM_OK;
3729         }
3730         return JIM_ERR;
3731 }
3732
3733 static int target_create( Jim_GetOptInfo *goi )
3734 {
3735         Jim_Obj *new_cmd;
3736         Jim_Cmd *cmd;
3737         const char *cp;
3738         char *cp2;
3739         int e;
3740         int x;
3741         target_t *target;
3742         struct command_context_s *cmd_ctx;
3743
3744         cmd_ctx = Jim_GetAssocData(goi->interp, "context");
3745         if( goi->argc < 3 ){
3746                 Jim_WrongNumArgs( goi->interp, 1, goi->argv, "?name? ?type? ..options...");
3747                 return JIM_ERR;
3748         }
3749
3750         /* COMMAND */
3751         Jim_GetOpt_Obj( goi, &new_cmd );
3752         /* does this command exist? */
3753         cmd = Jim_GetCommand( goi->interp, new_cmd, JIM_ERRMSG );
3754         if( cmd ){
3755                 cp = Jim_GetString( new_cmd, NULL );
3756                 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
3757                 return JIM_ERR;
3758         }
3759
3760         /* TYPE */
3761         e = Jim_GetOpt_String( goi, &cp2, NULL );
3762         cp = cp2;
3763         /* now does target type exist */
3764         for( x = 0 ; target_types[x] ; x++ ){
3765                 if( 0 == strcmp( cp, target_types[x]->name ) ){
3766                         /* found */
3767                         break;
3768                 }
3769         }
3770         if( target_types[x] == NULL ){
3771                 Jim_SetResult_sprintf( goi->interp, "Unknown target type %s, try one of ", cp );
3772                 for( x = 0 ; target_types[x] ; x++ ){
3773                         if( target_types[x+1] ){
3774                                 Jim_AppendStrings( goi->interp,
3775                                                                    Jim_GetResult(goi->interp),
3776                                                                    target_types[x]->name,
3777                                                                    ", ", NULL);
3778                         } else {
3779                                 Jim_AppendStrings( goi->interp,
3780                                                                    Jim_GetResult(goi->interp),
3781                                                                    " or ",
3782                                                                    target_types[x]->name,NULL );
3783                         }
3784                 }
3785                 return JIM_ERR;
3786         }
3787
3788         /* Create it */
3789         target = calloc(1,sizeof(target_t));
3790         /* set target number */
3791         target->target_number = new_target_number();
3792
3793         /* allocate memory for each unique target type */
3794         target->type = (target_type_t*)calloc(1,sizeof(target_type_t));
3795
3796         memcpy( target->type, target_types[x], sizeof(target_type_t));
3797
3798         /* will be set by "-endian" */
3799         target->endianness = TARGET_ENDIAN_UNKNOWN;
3800
3801         target->working_area        = 0x0;
3802         target->working_area_size   = 0x0;
3803         target->working_areas       = NULL;
3804         target->backup_working_area = 0;
3805
3806         target->state               = TARGET_UNKNOWN;
3807         target->debug_reason        = DBG_REASON_UNDEFINED;
3808         target->reg_cache           = NULL;
3809         target->breakpoints         = NULL;
3810         target->watchpoints         = NULL;
3811         target->next                = NULL;
3812         target->arch_info           = NULL;
3813
3814         target->display             = 1;
3815
3816         /* initialize trace information */
3817         target->trace_info = malloc(sizeof(trace_t));
3818         target->trace_info->num_trace_points         = 0;
3819         target->trace_info->trace_points_size        = 0;
3820         target->trace_info->trace_points             = NULL;
3821         target->trace_info->trace_history_size       = 0;
3822         target->trace_info->trace_history            = NULL;
3823         target->trace_info->trace_history_pos        = 0;
3824         target->trace_info->trace_history_overflowed = 0;
3825
3826         target->dbgmsg          = NULL;
3827         target->dbg_msg_enabled = 0;
3828
3829         target->endianness = TARGET_ENDIAN_UNKNOWN;
3830
3831         /* Do the rest as "configure" options */
3832         goi->isconfigure = 1;
3833         e = target_configure( goi, target);
3834         if( e != JIM_OK ){
3835                 free( target->type );
3836                 free( target );
3837                 return e;
3838         }
3839
3840         if( target->endianness == TARGET_ENDIAN_UNKNOWN ){
3841                 /* default endian to little if not specified */
3842                 target->endianness = TARGET_LITTLE_ENDIAN;
3843         }
3844
3845         /* incase variant is not set */
3846         if (!target->variant)
3847                 target->variant = strdup("");
3848         
3849         /* create the target specific commands */
3850         if( target->type->register_commands ){
3851                 (*(target->type->register_commands))( cmd_ctx );
3852         }
3853         if( target->type->target_create ){
3854                 (*(target->type->target_create))( target, goi->interp );
3855         }
3856
3857         /* append to end of list */
3858         {
3859                 target_t **tpp;
3860                 tpp = &(all_targets);
3861                 while( *tpp ){
3862                         tpp = &( (*tpp)->next );
3863                 }
3864                 *tpp = target;
3865         }
3866
3867         cp = Jim_GetString( new_cmd, NULL );
3868         target->cmd_name = strdup(cp);
3869
3870         /* now - create the new target name command */
3871         e = Jim_CreateCommand( goi->interp,
3872                                                    /* name */
3873                                                    cp,
3874                                                    tcl_target_func, /* C function */
3875                                                    target, /* private data */
3876                                                    NULL ); /* no del proc */
3877
3878         return e;
3879 }
3880
3881 static int jim_target( Jim_Interp *interp, int argc, Jim_Obj *const *argv )
3882 {
3883         int x,r,e;
3884         jim_wide w;
3885         struct command_context_s *cmd_ctx;
3886         target_t *target;
3887         Jim_GetOptInfo goi;
3888         enum tcmd {
3889                 /* TG = target generic */
3890                 TG_CMD_CREATE,
3891                 TG_CMD_TYPES,
3892                 TG_CMD_NAMES,
3893                 TG_CMD_CURRENT,
3894                 TG_CMD_NUMBER,
3895                 TG_CMD_COUNT,
3896         };
3897         const char *target_cmds[] = {
3898                 "create", "types", "names", "current", "number",
3899                 "count",
3900                 NULL /* terminate */
3901         };
3902
3903         LOG_DEBUG("Target command params:");
3904         LOG_DEBUG(Jim_Debug_ArgvString( interp, argc, argv) );
3905
3906         cmd_ctx = Jim_GetAssocData( interp, "context" );
3907
3908         Jim_GetOpt_Setup( &goi, interp, argc-1, argv+1 );
3909
3910         if( goi.argc == 0 ){
3911                 Jim_WrongNumArgs(interp, 1, argv, "missing: command ...");
3912                 return JIM_ERR;
3913         }
3914
3915         /* Jim_GetOpt_Debug( &goi ); */
3916         r = Jim_GetOpt_Enum( &goi, target_cmds, &x   );
3917         if( r != JIM_OK ){
3918                 return r;
3919         }
3920
3921         switch(x){
3922         default:
3923                 Jim_Panic(goi.interp,"Why am I here?");
3924                 return JIM_ERR;
3925         case TG_CMD_CURRENT:
3926                 if( goi.argc != 0 ){
3927                         Jim_WrongNumArgs( goi.interp, 1, goi.argv, "Too many parameters");
3928                         return JIM_ERR;
3929                 }
3930                 Jim_SetResultString( goi.interp, get_current_target( cmd_ctx )->cmd_name, -1 );
3931                 return JIM_OK;
3932         case TG_CMD_TYPES:
3933                 if( goi.argc != 0 ){
3934                         Jim_WrongNumArgs( goi.interp, 1, goi.argv, "Too many parameters" );
3935                         return JIM_ERR;
3936                 }
3937                 Jim_SetResult( goi.interp, Jim_NewListObj( goi.interp, NULL, 0 ) );
3938                 for( x = 0 ; target_types[x] ; x++ ){
3939                         Jim_ListAppendElement( goi.interp,
3940                                                                    Jim_GetResult(goi.interp),
3941                                                                    Jim_NewStringObj( goi.interp, target_types[x]->name, -1 ) );
3942                 }
3943                 return JIM_OK;
3944         case TG_CMD_NAMES:
3945                 if( goi.argc != 0 ){
3946                         Jim_WrongNumArgs( goi.interp, 1, goi.argv, "Too many parameters" );
3947                         return JIM_ERR;
3948                 }
3949                 Jim_SetResult( goi.interp, Jim_NewListObj( goi.interp, NULL, 0 ) );
3950                 target = all_targets;
3951                 while( target ){
3952                         Jim_ListAppendElement( goi.interp,
3953                                                                    Jim_GetResult(goi.interp),
3954                                                                    Jim_NewStringObj( goi.interp, target->cmd_name, -1 ) );
3955                         target = target->next;
3956                 }
3957                 return JIM_OK;
3958         case TG_CMD_CREATE:
3959                 if( goi.argc < 3 ){
3960                         Jim_WrongNumArgs( goi.interp, goi.argc, goi.argv, "?name  ... config options ...");
3961                         return JIM_ERR;
3962                 }
3963                 return target_create( &goi );
3964                 break;
3965         case TG_CMD_NUMBER:
3966                 if( goi.argc != 1 ){
3967                         Jim_SetResult_sprintf( goi.interp, "expected: target number ?NUMBER?");
3968                         return JIM_ERR;
3969                 }
3970                 e = Jim_GetOpt_Wide( &goi, &w );
3971                 if( e != JIM_OK ){
3972                         return JIM_ERR;
3973                 }
3974                 {
3975                         target_t *t;
3976                         t = get_target_by_num(w);
3977                         if( t == NULL ){
3978                                 Jim_SetResult_sprintf( goi.interp,"Target: number %d does not exist", (int)(w));
3979                                 return JIM_ERR;
3980                         }
3981                         Jim_SetResultString( goi.interp, t->cmd_name, -1 );
3982                         return JIM_OK;
3983                 }
3984         case TG_CMD_COUNT:
3985                 if( goi.argc != 0 ){
3986                         Jim_WrongNumArgs( goi.interp, 0, goi.argv, "<no parameters>");
3987                         return JIM_ERR;
3988                 }
3989                 Jim_SetResult( goi.interp,
3990                                            Jim_NewIntObj( goi.interp, max_target_number()));
3991                 return JIM_OK;
3992         }
3993
3994         return JIM_ERR;
3995 }