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