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