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