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