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