target: fix poll off
[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         if (!is_jtag_poll_safe())
1788         {
1789                 /* polling is disabled currently */
1790                 return ERROR_OK;
1791         }
1792
1793         /* we do not want to recurse here... */
1794         static int recursive = 0;
1795         if (! recursive)
1796         {
1797                 recursive = 1;
1798                 sense_handler();
1799                 /* danger! running these procedures can trigger srst assertions and power dropouts.
1800                  * We need to avoid an infinite loop/recursion here and we do that by
1801                  * clearing the flags after running these events.
1802                  */
1803                 int did_something = 0;
1804                 if (runSrstAsserted)
1805                 {
1806                         LOG_INFO("srst asserted detected, running srst_asserted proc.");
1807                         Jim_Eval(interp, "srst_asserted");
1808                         did_something = 1;
1809                 }
1810                 if (runSrstDeasserted)
1811                 {
1812                         Jim_Eval(interp, "srst_deasserted");
1813                         did_something = 1;
1814                 }
1815                 if (runPowerDropout)
1816                 {
1817                         LOG_INFO("Power dropout detected, running power_dropout proc.");
1818                         Jim_Eval(interp, "power_dropout");
1819                         did_something = 1;
1820                 }
1821                 if (runPowerRestore)
1822                 {
1823                         Jim_Eval(interp, "power_restore");
1824                         did_something = 1;
1825                 }
1826
1827                 if (did_something)
1828                 {
1829                         /* clear detect flags */
1830                         sense_handler();
1831                 }
1832
1833                 /* clear action flags */
1834
1835                 runSrstAsserted = 0;
1836                 runSrstDeasserted = 0;
1837                 runPowerRestore = 0;
1838                 runPowerDropout = 0;
1839
1840                 recursive = 0;
1841         }
1842
1843         /* Poll targets for state changes unless that's globally disabled.
1844          * Skip targets that are currently disabled.
1845          */
1846         for (struct target *target = all_targets;
1847                         is_jtag_poll_safe() && target;
1848                         target = target->next)
1849         {
1850                 if (!target->tap->enabled)
1851                         continue;
1852
1853                 /* only poll target if we've got power and srst isn't asserted */
1854                 if (!powerDropout && !srstAsserted)
1855                 {
1856                         /* polling may fail silently until the target has been examined */
1857                         if ((retval = target_poll(target)) != ERROR_OK)
1858                         {
1859                                 /* FIX!!!!! If we add a LOG_INFO() here to output a line in GDB
1860                                  * *why* we are aborting GDB, then we'll spam telnet when the
1861                                  * poll is failing persistently.
1862                                  *
1863                                  * If we could implement an event that detected the
1864                                  * target going from non-pollable to pollable, we could issue
1865                                  * an error only upon the transition.
1866                                  */
1867                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1868                                 return retval;
1869                         }
1870                 }
1871         }
1872
1873         return retval;
1874 }
1875
1876 COMMAND_HANDLER(handle_reg_command)
1877 {
1878         struct target *target;
1879         struct reg *reg = NULL;
1880         unsigned count = 0;
1881         char *value;
1882
1883         LOG_DEBUG("-");
1884
1885         target = get_current_target(CMD_CTX);
1886
1887         /* list all available registers for the current target */
1888         if (CMD_ARGC == 0)
1889         {
1890                 struct reg_cache *cache = target->reg_cache;
1891
1892                 count = 0;
1893                 while (cache)
1894                 {
1895                         unsigned i;
1896
1897                         command_print(CMD_CTX, "===== %s", cache->name);
1898
1899                         for (i = 0, reg = cache->reg_list;
1900                                         i < cache->num_regs;
1901                                         i++, reg++, count++)
1902                         {
1903                                 /* only print cached values if they are valid */
1904                                 if (reg->valid) {
1905                                         value = buf_to_str(reg->value,
1906                                                         reg->size, 16);
1907                                         command_print(CMD_CTX,
1908                                                         "(%i) %s (/%" PRIu32 "): 0x%s%s",
1909                                                         count, reg->name,
1910                                                         reg->size, value,
1911                                                         reg->dirty
1912                                                                 ? " (dirty)"
1913                                                                 : "");
1914                                         free(value);
1915                                 } else {
1916                                         command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
1917                                                           count, reg->name,
1918                                                           reg->size) ;
1919                                 }
1920                         }
1921                         cache = cache->next;
1922                 }
1923
1924                 return ERROR_OK;
1925         }
1926
1927         /* access a single register by its ordinal number */
1928         if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9'))
1929         {
1930                 unsigned num;
1931                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
1932
1933                 struct reg_cache *cache = target->reg_cache;
1934                 count = 0;
1935                 while (cache)
1936                 {
1937                         unsigned i;
1938                         for (i = 0; i < cache->num_regs; i++)
1939                         {
1940                                 if (count++ == num)
1941                                 {
1942                                         reg = &cache->reg_list[i];
1943                                         break;
1944                                 }
1945                         }
1946                         if (reg)
1947                                 break;
1948                         cache = cache->next;
1949                 }
1950
1951                 if (!reg)
1952                 {
1953                         command_print(CMD_CTX, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1954                         return ERROR_OK;
1955                 }
1956         } else /* access a single register by its name */
1957         {
1958                 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
1959
1960                 if (!reg)
1961                 {
1962                         command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
1963                         return ERROR_OK;
1964                 }
1965         }
1966
1967         /* display a register */
1968         if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0') && (CMD_ARGV[1][0] <= '9'))))
1969         {
1970                 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
1971                         reg->valid = 0;
1972
1973                 if (reg->valid == 0)
1974                 {
1975                         reg->type->get(reg);
1976                 }
1977                 value = buf_to_str(reg->value, reg->size, 16);
1978                 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1979                 free(value);
1980                 return ERROR_OK;
1981         }
1982
1983         /* set register value */
1984         if (CMD_ARGC == 2)
1985         {
1986                 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
1987                 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
1988
1989                 reg->type->set(reg, buf);
1990
1991                 value = buf_to_str(reg->value, reg->size, 16);
1992                 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1993                 free(value);
1994
1995                 free(buf);
1996
1997                 return ERROR_OK;
1998         }
1999
2000         command_print(CMD_CTX, "usage: reg <#|name> [value]");
2001
2002         return ERROR_OK;
2003 }
2004
2005 COMMAND_HANDLER(handle_poll_command)
2006 {
2007         int retval = ERROR_OK;
2008         struct target *target = get_current_target(CMD_CTX);
2009
2010         if (CMD_ARGC == 0)
2011         {
2012                 command_print(CMD_CTX, "background polling: %s",
2013                                 jtag_poll_get_enabled() ? "on" : "off");
2014                 command_print(CMD_CTX, "TAP: %s (%s)",
2015                                 target->tap->dotted_name,
2016                                 target->tap->enabled ? "enabled" : "disabled");
2017                 if (!target->tap->enabled)
2018                         return ERROR_OK;
2019                 if ((retval = target_poll(target)) != ERROR_OK)
2020                         return retval;
2021                 if ((retval = target_arch_state(target)) != ERROR_OK)
2022                         return retval;
2023         }
2024         else if (CMD_ARGC == 1)
2025         {
2026                 bool enable;
2027                 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2028                 jtag_poll_set_enabled(enable);
2029         }
2030         else
2031         {
2032                 return ERROR_COMMAND_SYNTAX_ERROR;
2033         }
2034
2035         return retval;
2036 }
2037
2038 COMMAND_HANDLER(handle_wait_halt_command)
2039 {
2040         if (CMD_ARGC > 1)
2041                 return ERROR_COMMAND_SYNTAX_ERROR;
2042
2043         unsigned ms = 5000;
2044         if (1 == CMD_ARGC)
2045         {
2046                 int retval = parse_uint(CMD_ARGV[0], &ms);
2047                 if (ERROR_OK != retval)
2048                 {
2049                         command_print(CMD_CTX, "usage: %s [seconds]", CMD_NAME);
2050                         return ERROR_COMMAND_SYNTAX_ERROR;
2051                 }
2052                 // convert seconds (given) to milliseconds (needed)
2053                 ms *= 1000;
2054         }
2055
2056         struct target *target = get_current_target(CMD_CTX);
2057         return target_wait_state(target, TARGET_HALTED, ms);
2058 }
2059
2060 /* wait for target state to change. The trick here is to have a low
2061  * latency for short waits and not to suck up all the CPU time
2062  * on longer waits.
2063  *
2064  * After 500ms, keep_alive() is invoked
2065  */
2066 int target_wait_state(struct target *target, enum target_state state, int ms)
2067 {
2068         int retval;
2069         long long then = 0, cur;
2070         int once = 1;
2071
2072         for (;;)
2073         {
2074                 if ((retval = target_poll(target)) != ERROR_OK)
2075                         return retval;
2076                 if (target->state == state)
2077                 {
2078                         break;
2079                 }
2080                 cur = timeval_ms();
2081                 if (once)
2082                 {
2083                         once = 0;
2084                         then = timeval_ms();
2085                         LOG_DEBUG("waiting for target %s...",
2086                                 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2087                 }
2088
2089                 if (cur-then > 500)
2090                 {
2091                         keep_alive();
2092                 }
2093
2094                 if ((cur-then) > ms)
2095                 {
2096                         LOG_ERROR("timed out while waiting for target %s",
2097                                 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2098                         return ERROR_FAIL;
2099                 }
2100         }
2101
2102         return ERROR_OK;
2103 }
2104
2105 COMMAND_HANDLER(handle_halt_command)
2106 {
2107         LOG_DEBUG("-");
2108
2109         struct target *target = get_current_target(CMD_CTX);
2110         int retval = target_halt(target);
2111         if (ERROR_OK != retval)
2112                 return retval;
2113
2114         if (CMD_ARGC == 1)
2115         {
2116                 unsigned wait;
2117                 retval = parse_uint(CMD_ARGV[0], &wait);
2118                 if (ERROR_OK != retval)
2119                         return ERROR_COMMAND_SYNTAX_ERROR;
2120                 if (!wait)
2121                         return ERROR_OK;
2122         }
2123
2124         return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2125 }
2126
2127 COMMAND_HANDLER(handle_soft_reset_halt_command)
2128 {
2129         struct target *target = get_current_target(CMD_CTX);
2130
2131         LOG_USER("requesting target halt and executing a soft reset");
2132
2133         target->type->soft_reset_halt(target);
2134
2135         return ERROR_OK;
2136 }
2137
2138 COMMAND_HANDLER(handle_reset_command)
2139 {
2140         if (CMD_ARGC > 1)
2141                 return ERROR_COMMAND_SYNTAX_ERROR;
2142
2143         enum target_reset_mode reset_mode = RESET_RUN;
2144         if (CMD_ARGC == 1)
2145         {
2146                 const Jim_Nvp *n;
2147                 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2148                 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2149                         return ERROR_COMMAND_SYNTAX_ERROR;
2150                 }
2151                 reset_mode = n->value;
2152         }
2153
2154         /* reset *all* targets */
2155         return target_process_reset(CMD_CTX, reset_mode);
2156 }
2157
2158
2159 COMMAND_HANDLER(handle_resume_command)
2160 {
2161         int current = 1;
2162         if (CMD_ARGC > 1)
2163                 return ERROR_COMMAND_SYNTAX_ERROR;
2164
2165         struct target *target = get_current_target(CMD_CTX);
2166         target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2167
2168         /* with no CMD_ARGV, resume from current pc, addr = 0,
2169          * with one arguments, addr = CMD_ARGV[0],
2170          * handle breakpoints, not debugging */
2171         uint32_t addr = 0;
2172         if (CMD_ARGC == 1)
2173         {
2174                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2175                 current = 0;
2176         }
2177
2178         return target_resume(target, current, addr, 1, 0);
2179 }
2180
2181 COMMAND_HANDLER(handle_step_command)
2182 {
2183         if (CMD_ARGC > 1)
2184                 return ERROR_COMMAND_SYNTAX_ERROR;
2185
2186         LOG_DEBUG("-");
2187
2188         /* with no CMD_ARGV, step from current pc, addr = 0,
2189          * with one argument addr = CMD_ARGV[0],
2190          * handle breakpoints, debugging */
2191         uint32_t addr = 0;
2192         int current_pc = 1;
2193         if (CMD_ARGC == 1)
2194         {
2195                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2196                 current_pc = 0;
2197         }
2198
2199         struct target *target = get_current_target(CMD_CTX);
2200
2201         return target->type->step(target, current_pc, addr, 1);
2202 }
2203
2204 static void handle_md_output(struct command_context *cmd_ctx,
2205                 struct target *target, uint32_t address, unsigned size,
2206                 unsigned count, const uint8_t *buffer)
2207 {
2208         const unsigned line_bytecnt = 32;
2209         unsigned line_modulo = line_bytecnt / size;
2210
2211         char output[line_bytecnt * 4 + 1];
2212         unsigned output_len = 0;
2213
2214         const char *value_fmt;
2215         switch (size) {
2216         case 4: value_fmt = "%8.8x "; break;
2217         case 2: value_fmt = "%4.4x "; break;
2218         case 1: value_fmt = "%2.2x "; break;
2219         default:
2220                 /* "can't happen", caller checked */
2221                 LOG_ERROR("invalid memory read size: %u", size);
2222                 return;
2223         }
2224
2225         for (unsigned i = 0; i < count; i++)
2226         {
2227                 if (i % line_modulo == 0)
2228                 {
2229                         output_len += snprintf(output + output_len,
2230                                         sizeof(output) - output_len,
2231                                         "0x%8.8x: ",
2232                                         (unsigned)(address + (i*size)));
2233                 }
2234
2235                 uint32_t value = 0;
2236                 const uint8_t *value_ptr = buffer + i * size;
2237                 switch (size) {
2238                 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2239                 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2240                 case 1: value = *value_ptr;
2241                 }
2242                 output_len += snprintf(output + output_len,
2243                                 sizeof(output) - output_len,
2244                                 value_fmt, value);
2245
2246                 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2247                 {
2248                         command_print(cmd_ctx, "%s", output);
2249                         output_len = 0;
2250                 }
2251         }
2252 }
2253
2254 COMMAND_HANDLER(handle_md_command)
2255 {
2256         if (CMD_ARGC < 1)
2257                 return ERROR_COMMAND_SYNTAX_ERROR;
2258
2259         unsigned size = 0;
2260         switch (CMD_NAME[2]) {
2261         case 'w': size = 4; break;
2262         case 'h': size = 2; break;
2263         case 'b': size = 1; break;
2264         default: return ERROR_COMMAND_SYNTAX_ERROR;
2265         }
2266
2267         bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2268         int (*fn)(struct target *target,
2269                         uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2270         if (physical)
2271         {
2272                 CMD_ARGC--;
2273                 CMD_ARGV++;
2274                 fn=target_read_phys_memory;
2275         } else
2276         {
2277                 fn=target_read_memory;
2278         }
2279         if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2280         {
2281                 return ERROR_COMMAND_SYNTAX_ERROR;
2282         }
2283
2284         uint32_t address;
2285         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2286
2287         unsigned count = 1;
2288         if (CMD_ARGC == 2)
2289                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2290
2291         uint8_t *buffer = calloc(count, size);
2292
2293         struct target *target = get_current_target(CMD_CTX);
2294         int retval = fn(target, address, size, count, buffer);
2295         if (ERROR_OK == retval)
2296                 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2297
2298         free(buffer);
2299
2300         return retval;
2301 }
2302
2303 typedef int (*target_write_fn)(struct target *target,
2304                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2305
2306 static int target_write_memory_fast(struct target *target,
2307                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
2308 {
2309         return target_write_buffer(target, address, size * count, buffer);
2310 }
2311
2312 static int target_fill_mem(struct target *target,
2313                 uint32_t address,
2314                 target_write_fn fn,
2315                 unsigned data_size,
2316                 /* value */
2317                 uint32_t b,
2318                 /* count */
2319                 unsigned c)
2320 {
2321         /* We have to write in reasonably large chunks to be able
2322          * to fill large memory areas with any sane speed */
2323         const unsigned chunk_size = 16384;
2324         uint8_t *target_buf = malloc(chunk_size * data_size);
2325         if (target_buf == NULL)
2326         {
2327                 LOG_ERROR("Out of memory");
2328                 return ERROR_FAIL;
2329         }
2330
2331         for (unsigned i = 0; i < chunk_size; i ++)
2332         {
2333                 switch (data_size)
2334                 {
2335                 case 4:
2336                         target_buffer_set_u32(target, target_buf + i*data_size, b);
2337                         break;
2338                 case 2:
2339                         target_buffer_set_u16(target, target_buf + i*data_size, b);
2340                         break;
2341                 case 1:
2342                         target_buffer_set_u8(target, target_buf + i*data_size, b);
2343                         break;
2344                 default:
2345                         exit(-1);
2346                 }
2347         }
2348
2349         int retval = ERROR_OK;
2350
2351         for (unsigned x = 0; x < c; x += chunk_size)
2352         {
2353                 unsigned current;
2354                 current = c - x;
2355                 if (current > chunk_size)
2356                 {
2357                         current = chunk_size;
2358                 }
2359                 int retval = fn(target, address + x * data_size, data_size, current, target_buf);
2360                 if (retval != ERROR_OK)
2361                 {
2362                         break;
2363                 }
2364                 /* avoid GDB timeouts */
2365                 keep_alive();
2366         }
2367         free(target_buf);
2368
2369         return retval;
2370 }
2371
2372
2373 COMMAND_HANDLER(handle_mw_command)
2374 {
2375         if (CMD_ARGC < 2)
2376         {
2377                 return ERROR_COMMAND_SYNTAX_ERROR;
2378         }
2379         bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2380         target_write_fn fn;
2381         if (physical)
2382         {
2383                 CMD_ARGC--;
2384                 CMD_ARGV++;
2385                 fn=target_write_phys_memory;
2386         } else
2387         {
2388                 fn = target_write_memory_fast;
2389         }
2390         if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2391                 return ERROR_COMMAND_SYNTAX_ERROR;
2392
2393         uint32_t address;
2394         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2395
2396         uint32_t value;
2397         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2398
2399         unsigned count = 1;
2400         if (CMD_ARGC == 3)
2401                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2402
2403         struct target *target = get_current_target(CMD_CTX);
2404         unsigned wordsize;
2405         switch (CMD_NAME[2])
2406         {
2407                 case 'w':
2408                         wordsize = 4;
2409                         break;
2410                 case 'h':
2411                         wordsize = 2;
2412                         break;
2413                 case 'b':
2414                         wordsize = 1;
2415                         break;
2416                 default:
2417                         return ERROR_COMMAND_SYNTAX_ERROR;
2418         }
2419
2420         return target_fill_mem(target, address, fn, wordsize, value, count);
2421 }
2422
2423 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2424                 uint32_t *min_address, uint32_t *max_address)
2425 {
2426         if (CMD_ARGC < 1 || CMD_ARGC > 5)
2427                 return ERROR_COMMAND_SYNTAX_ERROR;
2428
2429         /* a base address isn't always necessary,
2430          * default to 0x0 (i.e. don't relocate) */
2431         if (CMD_ARGC >= 2)
2432         {
2433                 uint32_t addr;
2434                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2435                 image->base_address = addr;
2436                 image->base_address_set = 1;
2437         }
2438         else
2439                 image->base_address_set = 0;
2440
2441         image->start_address_set = 0;
2442
2443         if (CMD_ARGC >= 4)
2444         {
2445                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2446         }
2447         if (CMD_ARGC == 5)
2448         {
2449                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2450                 // use size (given) to find max (required)
2451                 *max_address += *min_address;
2452         }
2453
2454         if (*min_address > *max_address)
2455                 return ERROR_COMMAND_SYNTAX_ERROR;
2456
2457         return ERROR_OK;
2458 }
2459
2460 COMMAND_HANDLER(handle_load_image_command)
2461 {
2462         uint8_t *buffer;
2463         size_t buf_cnt;
2464         uint32_t image_size;
2465         uint32_t min_address = 0;
2466         uint32_t max_address = 0xffffffff;
2467         int i;
2468         struct image image;
2469
2470         int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2471                         &image, &min_address, &max_address);
2472         if (ERROR_OK != retval)
2473                 return retval;
2474
2475         struct target *target = get_current_target(CMD_CTX);
2476
2477         struct duration bench;
2478         duration_start(&bench);
2479
2480         if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2481         {
2482                 return ERROR_OK;
2483         }
2484
2485         image_size = 0x0;
2486         retval = ERROR_OK;
2487         for (i = 0; i < image.num_sections; i++)
2488         {
2489                 buffer = malloc(image.sections[i].size);
2490                 if (buffer == NULL)
2491                 {
2492                         command_print(CMD_CTX,
2493                                                   "error allocating buffer for section (%d bytes)",
2494                                                   (int)(image.sections[i].size));
2495                         break;
2496                 }
2497
2498                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2499                 {
2500                         free(buffer);
2501                         break;
2502                 }
2503
2504                 uint32_t offset = 0;
2505                 uint32_t length = buf_cnt;
2506
2507                 /* DANGER!!! beware of unsigned comparision here!!! */
2508
2509                 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2510                                 (image.sections[i].base_address < max_address))
2511                 {
2512                         if (image.sections[i].base_address < min_address)
2513                         {
2514                                 /* clip addresses below */
2515                                 offset += min_address-image.sections[i].base_address;
2516                                 length -= offset;
2517                         }
2518
2519                         if (image.sections[i].base_address + buf_cnt > max_address)
2520                         {
2521                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2522                         }
2523
2524                         if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2525                         {
2526                                 free(buffer);
2527                                 break;
2528                         }
2529                         image_size += length;
2530                         command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2531                                                   (unsigned int)length,
2532                                                   image.sections[i].base_address + offset);
2533                 }
2534
2535                 free(buffer);
2536         }
2537
2538         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2539         {
2540                 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2541                                 "in %fs (%0.3f kb/s)", image_size,
2542                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2543         }
2544
2545         image_close(&image);
2546
2547         return retval;
2548
2549 }
2550
2551 COMMAND_HANDLER(handle_dump_image_command)
2552 {
2553         struct fileio fileio;
2554
2555         uint8_t buffer[560];
2556         int retvaltemp;
2557
2558
2559         struct target *target = get_current_target(CMD_CTX);
2560
2561         if (CMD_ARGC != 3)
2562         {
2563                 command_print(CMD_CTX, "usage: dump_image <filename> <address> <size>");
2564                 return ERROR_OK;
2565         }
2566
2567         uint32_t address;
2568         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2569         uint32_t size;
2570         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2571
2572         if (fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2573         {
2574                 return ERROR_OK;
2575         }
2576
2577         struct duration bench;
2578         duration_start(&bench);
2579
2580         int retval = ERROR_OK;
2581         while (size > 0)
2582         {
2583                 size_t size_written;
2584                 uint32_t this_run_size = (size > 560) ? 560 : size;
2585                 retval = target_read_buffer(target, address, this_run_size, buffer);
2586                 if (retval != ERROR_OK)
2587                 {
2588                         break;
2589                 }
2590
2591                 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2592                 if (retval != ERROR_OK)
2593                 {
2594                         break;
2595                 }
2596
2597                 size -= this_run_size;
2598                 address += this_run_size;
2599         }
2600
2601         if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2602                 return retvaltemp;
2603
2604         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2605         {
2606                 command_print(CMD_CTX,
2607                                 "dumped %ld bytes in %fs (%0.3f kb/s)", (long)fileio.size,
2608                                 duration_elapsed(&bench), duration_kbps(&bench, fileio.size));
2609         }
2610
2611         return retval;
2612 }
2613
2614 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2615 {
2616         uint8_t *buffer;
2617         size_t buf_cnt;
2618         uint32_t image_size;
2619         int i;
2620         int retval;
2621         uint32_t checksum = 0;
2622         uint32_t mem_checksum = 0;
2623
2624         struct image image;
2625
2626         struct target *target = get_current_target(CMD_CTX);
2627
2628         if (CMD_ARGC < 1)
2629         {
2630                 return ERROR_COMMAND_SYNTAX_ERROR;
2631         }
2632
2633         if (!target)
2634         {
2635                 LOG_ERROR("no target selected");
2636                 return ERROR_FAIL;
2637         }
2638
2639         struct duration bench;
2640         duration_start(&bench);
2641
2642         if (CMD_ARGC >= 2)
2643         {
2644                 uint32_t addr;
2645                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2646                 image.base_address = addr;
2647                 image.base_address_set = 1;
2648         }
2649         else
2650         {
2651                 image.base_address_set = 0;
2652                 image.base_address = 0x0;
2653         }
2654
2655         image.start_address_set = 0;
2656
2657         if ((retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL)) != ERROR_OK)
2658         {
2659                 return retval;
2660         }
2661
2662         image_size = 0x0;
2663         retval = ERROR_OK;
2664         for (i = 0; i < image.num_sections; i++)
2665         {
2666                 buffer = malloc(image.sections[i].size);
2667                 if (buffer == NULL)
2668                 {
2669                         command_print(CMD_CTX,
2670                                                   "error allocating buffer for section (%d bytes)",
2671                                                   (int)(image.sections[i].size));
2672                         break;
2673                 }
2674                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2675                 {
2676                         free(buffer);
2677                         break;
2678                 }
2679
2680                 if (verify)
2681                 {
2682                         /* calculate checksum of image */
2683                         image_calculate_checksum(buffer, buf_cnt, &checksum);
2684
2685                         retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2686                         if (retval != ERROR_OK)
2687                         {
2688                                 free(buffer);
2689                                 break;
2690                         }
2691
2692                         if (checksum != mem_checksum)
2693                         {
2694                                 /* failed crc checksum, fall back to a binary compare */
2695                                 uint8_t *data;
2696
2697                                 command_print(CMD_CTX, "checksum mismatch - attempting binary compare");
2698
2699                                 data = (uint8_t*)malloc(buf_cnt);
2700
2701                                 /* Can we use 32bit word accesses? */
2702                                 int size = 1;
2703                                 int count = buf_cnt;
2704                                 if ((count % 4) == 0)
2705                                 {
2706                                         size *= 4;
2707                                         count /= 4;
2708                                 }
2709                                 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2710                                 if (retval == ERROR_OK)
2711                                 {
2712                                         uint32_t t;
2713                                         for (t = 0; t < buf_cnt; t++)
2714                                         {
2715                                                 if (data[t] != buffer[t])
2716                                                 {
2717                                                         command_print(CMD_CTX,
2718                                                                                   "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n",
2719                                                                                   (unsigned)(t + image.sections[i].base_address),
2720                                                                                   data[t],
2721                                                                                   buffer[t]);
2722                                                         free(data);
2723                                                         free(buffer);
2724                                                         retval = ERROR_FAIL;
2725                                                         goto done;
2726                                                 }
2727                                                 if ((t%16384) == 0)
2728                                                 {
2729                                                         keep_alive();
2730                                                 }
2731                                         }
2732                                 }
2733
2734                                 free(data);
2735                         }
2736                 } else
2737                 {
2738                         command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
2739                                                   image.sections[i].base_address,
2740                                                   buf_cnt);
2741                 }
2742
2743                 free(buffer);
2744                 image_size += buf_cnt;
2745         }
2746 done:
2747         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2748         {
2749                 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
2750                                 "in %fs (%0.3f kb/s)", image_size,
2751                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2752         }
2753
2754         image_close(&image);
2755
2756         return retval;
2757 }
2758
2759 COMMAND_HANDLER(handle_verify_image_command)
2760 {
2761         return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2762 }
2763
2764 COMMAND_HANDLER(handle_test_image_command)
2765 {
2766         return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2767 }
2768
2769 static int handle_bp_command_list(struct command_context *cmd_ctx)
2770 {
2771         struct target *target = get_current_target(cmd_ctx);
2772         struct breakpoint *breakpoint = target->breakpoints;
2773         while (breakpoint)
2774         {
2775                 if (breakpoint->type == BKPT_SOFT)
2776                 {
2777                         char* buf = buf_to_str(breakpoint->orig_instr,
2778                                         breakpoint->length, 16);
2779                         command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2780                                         breakpoint->address,
2781                                         breakpoint->length,
2782                                         breakpoint->set, buf);
2783                         free(buf);
2784                 }
2785                 else
2786                 {
2787                         command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2788                                                   breakpoint->address,
2789                                                   breakpoint->length, breakpoint->set);
2790                 }
2791
2792                 breakpoint = breakpoint->next;
2793         }
2794         return ERROR_OK;
2795 }
2796
2797 static int handle_bp_command_set(struct command_context *cmd_ctx,
2798                 uint32_t addr, uint32_t length, int hw)
2799 {
2800         struct target *target = get_current_target(cmd_ctx);
2801         int retval = breakpoint_add(target, addr, length, hw);
2802         if (ERROR_OK == retval)
2803                 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2804         else
2805                 LOG_ERROR("Failure setting breakpoint");
2806         return retval;
2807 }
2808
2809 COMMAND_HANDLER(handle_bp_command)
2810 {
2811         if (CMD_ARGC == 0)
2812                 return handle_bp_command_list(CMD_CTX);
2813
2814         if (CMD_ARGC < 2 || CMD_ARGC > 3)
2815         {
2816                 command_print(CMD_CTX, "usage: bp <address> <length> ['hw']");
2817                 return ERROR_COMMAND_SYNTAX_ERROR;
2818         }
2819
2820         uint32_t addr;
2821         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2822         uint32_t length;
2823         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2824
2825         int hw = BKPT_SOFT;
2826         if (CMD_ARGC == 3)
2827         {
2828                 if (strcmp(CMD_ARGV[2], "hw") == 0)
2829                         hw = BKPT_HARD;
2830                 else
2831                         return ERROR_COMMAND_SYNTAX_ERROR;
2832         }
2833
2834         return handle_bp_command_set(CMD_CTX, addr, length, hw);
2835 }
2836
2837 COMMAND_HANDLER(handle_rbp_command)
2838 {
2839         if (CMD_ARGC != 1)
2840                 return ERROR_COMMAND_SYNTAX_ERROR;
2841
2842         uint32_t addr;
2843         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2844
2845         struct target *target = get_current_target(CMD_CTX);
2846         breakpoint_remove(target, addr);
2847
2848         return ERROR_OK;
2849 }
2850
2851 COMMAND_HANDLER(handle_wp_command)
2852 {
2853         struct target *target = get_current_target(CMD_CTX);
2854
2855         if (CMD_ARGC == 0)
2856         {
2857                 struct watchpoint *watchpoint = target->watchpoints;
2858
2859                 while (watchpoint)
2860                 {
2861                         command_print(CMD_CTX, "address: 0x%8.8" PRIx32
2862                                         ", len: 0x%8.8" PRIx32
2863                                         ", r/w/a: %i, value: 0x%8.8" PRIx32
2864                                         ", mask: 0x%8.8" PRIx32,
2865                                         watchpoint->address,
2866                                         watchpoint->length,
2867                                         (int)watchpoint->rw,
2868                                         watchpoint->value,
2869                                         watchpoint->mask);
2870                         watchpoint = watchpoint->next;
2871                 }
2872                 return ERROR_OK;
2873         }
2874
2875         enum watchpoint_rw type = WPT_ACCESS;
2876         uint32_t addr = 0;
2877         uint32_t length = 0;
2878         uint32_t data_value = 0x0;
2879         uint32_t data_mask = 0xffffffff;
2880
2881         switch (CMD_ARGC)
2882         {
2883         case 5:
2884                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
2885                 // fall through
2886         case 4:
2887                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
2888                 // fall through
2889         case 3:
2890                 switch (CMD_ARGV[2][0])
2891                 {
2892                 case 'r':
2893                         type = WPT_READ;
2894                         break;
2895                 case 'w':
2896                         type = WPT_WRITE;
2897                         break;
2898                 case 'a':
2899                         type = WPT_ACCESS;
2900                         break;
2901                 default:
2902                         LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
2903                         return ERROR_COMMAND_SYNTAX_ERROR;
2904                 }
2905                 // fall through
2906         case 2:
2907                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2908                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2909                 break;
2910
2911         default:
2912                 command_print(CMD_CTX, "usage: wp [address length "
2913                                 "[(r|w|a) [value [mask]]]]");
2914                 return ERROR_COMMAND_SYNTAX_ERROR;
2915         }
2916
2917         int retval = watchpoint_add(target, addr, length, type,
2918                         data_value, data_mask);
2919         if (ERROR_OK != retval)
2920                 LOG_ERROR("Failure setting watchpoints");
2921
2922         return retval;
2923 }
2924
2925 COMMAND_HANDLER(handle_rwp_command)
2926 {
2927         if (CMD_ARGC != 1)
2928                 return ERROR_COMMAND_SYNTAX_ERROR;
2929
2930         uint32_t addr;
2931         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2932
2933         struct target *target = get_current_target(CMD_CTX);
2934         watchpoint_remove(target, addr);
2935
2936         return ERROR_OK;
2937 }
2938
2939
2940 /**
2941  * Translate a virtual address to a physical address.
2942  *
2943  * The low-level target implementation must have logged a detailed error
2944  * which is forwarded to telnet/GDB session.
2945  */
2946 COMMAND_HANDLER(handle_virt2phys_command)
2947 {
2948         if (CMD_ARGC != 1)
2949                 return ERROR_COMMAND_SYNTAX_ERROR;
2950
2951         uint32_t va;
2952         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
2953         uint32_t pa;
2954
2955         struct target *target = get_current_target(CMD_CTX);
2956         int retval = target->type->virt2phys(target, va, &pa);
2957         if (retval == ERROR_OK)
2958                 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
2959
2960         return retval;
2961 }
2962
2963 static void writeData(FILE *f, const void *data, size_t len)
2964 {
2965         size_t written = fwrite(data, 1, len, f);
2966         if (written != len)
2967                 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
2968 }
2969
2970 static void writeLong(FILE *f, int l)
2971 {
2972         int i;
2973         for (i = 0; i < 4; i++)
2974         {
2975                 char c = (l >> (i*8))&0xff;
2976                 writeData(f, &c, 1);
2977         }
2978
2979 }
2980
2981 static void writeString(FILE *f, char *s)
2982 {
2983         writeData(f, s, strlen(s));
2984 }
2985
2986 /* Dump a gmon.out histogram file. */
2987 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
2988 {
2989         uint32_t i;
2990         FILE *f = fopen(filename, "w");
2991         if (f == NULL)
2992                 return;
2993         writeString(f, "gmon");
2994         writeLong(f, 0x00000001); /* Version */
2995         writeLong(f, 0); /* padding */
2996         writeLong(f, 0); /* padding */
2997         writeLong(f, 0); /* padding */
2998
2999         uint8_t zero = 0;  /* GMON_TAG_TIME_HIST */
3000         writeData(f, &zero, 1);
3001
3002         /* figure out bucket size */
3003         uint32_t min = samples[0];
3004         uint32_t max = samples[0];
3005         for (i = 0; i < sampleNum; i++)
3006         {
3007                 if (min > samples[i])
3008                 {
3009                         min = samples[i];
3010                 }
3011                 if (max < samples[i])
3012                 {
3013                         max = samples[i];
3014                 }
3015         }
3016
3017         int addressSpace = (max-min + 1);
3018
3019         static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
3020         uint32_t length = addressSpace;
3021         if (length > maxBuckets)
3022         {
3023                 length = maxBuckets;
3024         }
3025         int *buckets = malloc(sizeof(int)*length);
3026         if (buckets == NULL)
3027         {
3028                 fclose(f);
3029                 return;
3030         }
3031         memset(buckets, 0, sizeof(int)*length);
3032         for (i = 0; i < sampleNum;i++)
3033         {
3034                 uint32_t address = samples[i];
3035                 long long a = address-min;
3036                 long long b = length-1;
3037                 long long c = addressSpace-1;
3038                 int index = (a*b)/c; /* danger!!!! int32 overflows */
3039                 buckets[index]++;
3040         }
3041
3042         /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3043         writeLong(f, min);                      /* low_pc */
3044         writeLong(f, max);                      /* high_pc */
3045         writeLong(f, length);           /* # of samples */
3046         writeLong(f, 64000000);         /* 64MHz */
3047         writeString(f, "seconds");
3048         for (i = 0; i < (15-strlen("seconds")); i++)
3049                 writeData(f, &zero, 1);
3050         writeString(f, "s");
3051
3052         /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3053
3054         char *data = malloc(2*length);
3055         if (data != NULL)
3056         {
3057                 for (i = 0; i < length;i++)
3058                 {
3059                         int val;
3060                         val = buckets[i];
3061                         if (val > 65535)
3062                         {
3063                                 val = 65535;
3064                         }
3065                         data[i*2]=val&0xff;
3066                         data[i*2 + 1]=(val >> 8)&0xff;
3067                 }
3068                 free(buckets);
3069                 writeData(f, data, length * 2);
3070                 free(data);
3071         } else
3072         {
3073                 free(buckets);
3074         }
3075
3076         fclose(f);
3077 }
3078
3079 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3080  * which will be used as a random sampling of PC */
3081 COMMAND_HANDLER(handle_profile_command)
3082 {
3083         struct target *target = get_current_target(CMD_CTX);
3084         struct timeval timeout, now;
3085
3086         gettimeofday(&timeout, NULL);
3087         if (CMD_ARGC != 2)
3088         {
3089                 return ERROR_COMMAND_SYNTAX_ERROR;
3090         }
3091         unsigned offset;
3092         COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3093
3094         timeval_add_time(&timeout, offset, 0);
3095
3096         /**
3097          * @todo: Some cores let us sample the PC without the
3098          * annoying halt/resume step; for example, ARMv7 PCSR.
3099          * Provide a way to use that more efficient mechanism.
3100          */
3101
3102         command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3103
3104         static const int maxSample = 10000;
3105         uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3106         if (samples == NULL)
3107                 return ERROR_OK;
3108
3109         int numSamples = 0;
3110         /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3111         struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3112
3113         for (;;)
3114         {
3115                 int retval;
3116                 target_poll(target);
3117                 if (target->state == TARGET_HALTED)
3118                 {
3119                         uint32_t t=*((uint32_t *)reg->value);
3120                         samples[numSamples++]=t;
3121                         retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3122                         target_poll(target);
3123                         alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3124                 } else if (target->state == TARGET_RUNNING)
3125                 {
3126                         /* We want to quickly sample the PC. */
3127                         if ((retval = target_halt(target)) != ERROR_OK)
3128                         {
3129                                 free(samples);
3130                                 return retval;
3131                         }
3132                 } else
3133                 {
3134                         command_print(CMD_CTX, "Target not halted or running");
3135                         retval = ERROR_OK;
3136                         break;
3137                 }
3138                 if (retval != ERROR_OK)
3139                 {
3140                         break;
3141                 }
3142
3143                 gettimeofday(&now, NULL);
3144                 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3145                 {
3146                         command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3147                         if ((retval = target_poll(target)) != ERROR_OK)
3148                         {
3149                                 free(samples);
3150                                 return retval;
3151                         }
3152                         if (target->state == TARGET_HALTED)
3153                         {
3154                                 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3155                         }
3156                         if ((retval = target_poll(target)) != ERROR_OK)
3157                         {
3158                                 free(samples);
3159                                 return retval;
3160                         }
3161                         writeGmon(samples, numSamples, CMD_ARGV[1]);
3162                         command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3163                         break;
3164                 }
3165         }
3166         free(samples);
3167
3168         return ERROR_OK;
3169 }
3170
3171 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3172 {
3173         char *namebuf;
3174         Jim_Obj *nameObjPtr, *valObjPtr;
3175         int result;
3176
3177         namebuf = alloc_printf("%s(%d)", varname, idx);
3178         if (!namebuf)
3179                 return JIM_ERR;
3180
3181         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3182         valObjPtr = Jim_NewIntObj(interp, val);
3183         if (!nameObjPtr || !valObjPtr)
3184         {
3185                 free(namebuf);
3186                 return JIM_ERR;
3187         }
3188
3189         Jim_IncrRefCount(nameObjPtr);
3190         Jim_IncrRefCount(valObjPtr);
3191         result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3192         Jim_DecrRefCount(interp, nameObjPtr);
3193         Jim_DecrRefCount(interp, valObjPtr);
3194         free(namebuf);
3195         /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3196         return result;
3197 }
3198
3199 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3200 {
3201         struct command_context *context;
3202         struct target *target;
3203
3204         context = Jim_GetAssocData(interp, "context");
3205         if (context == NULL)
3206         {
3207                 LOG_ERROR("mem2array: no command context");
3208                 return JIM_ERR;
3209         }
3210         target = get_current_target(context);
3211         if (target == NULL)
3212         {
3213                 LOG_ERROR("mem2array: no current target");
3214                 return JIM_ERR;
3215         }
3216
3217         return  target_mem2array(interp, target, argc-1, argv + 1);
3218 }
3219
3220 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3221 {
3222         long l;
3223         uint32_t width;
3224         int len;
3225         uint32_t addr;
3226         uint32_t count;
3227         uint32_t v;
3228         const char *varname;
3229         int  n, e, retval;
3230         uint32_t i;
3231
3232         /* argv[1] = name of array to receive the data
3233          * argv[2] = desired width
3234          * argv[3] = memory address
3235          * argv[4] = count of times to read
3236          */
3237         if (argc != 4) {
3238                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3239                 return JIM_ERR;
3240         }
3241         varname = Jim_GetString(argv[0], &len);
3242         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3243
3244         e = Jim_GetLong(interp, argv[1], &l);
3245         width = l;
3246         if (e != JIM_OK) {
3247                 return e;
3248         }
3249
3250         e = Jim_GetLong(interp, argv[2], &l);
3251         addr = l;
3252         if (e != JIM_OK) {
3253                 return e;
3254         }
3255         e = Jim_GetLong(interp, argv[3], &l);
3256         len = l;
3257         if (e != JIM_OK) {
3258                 return e;
3259         }
3260         switch (width) {
3261                 case 8:
3262                         width = 1;
3263                         break;
3264                 case 16:
3265                         width = 2;
3266                         break;
3267                 case 32:
3268                         width = 4;
3269                         break;
3270                 default:
3271                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3272                         Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3273                         return JIM_ERR;
3274         }
3275         if (len == 0) {
3276                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3277                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3278                 return JIM_ERR;
3279         }
3280         if ((addr + (len * width)) < addr) {
3281                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3282                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3283                 return JIM_ERR;
3284         }
3285         /* absurd transfer size? */
3286         if (len > 65536) {
3287                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3288                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3289                 return JIM_ERR;
3290         }
3291
3292         if ((width == 1) ||
3293                 ((width == 2) && ((addr & 1) == 0)) ||
3294                 ((width == 4) && ((addr & 3) == 0))) {
3295                 /* all is well */
3296         } else {
3297                 char buf[100];
3298                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3299                 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3300                                 addr,
3301                                 width);
3302                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3303                 return JIM_ERR;
3304         }
3305
3306         /* Transfer loop */
3307
3308         /* index counter */
3309         n = 0;
3310
3311         size_t buffersize = 4096;
3312         uint8_t *buffer = malloc(buffersize);
3313         if (buffer == NULL)
3314                 return JIM_ERR;
3315
3316         /* assume ok */
3317         e = JIM_OK;
3318         while (len) {
3319                 /* Slurp... in buffer size chunks */
3320
3321                 count = len; /* in objects.. */
3322                 if (count > (buffersize/width)) {
3323                         count = (buffersize/width);
3324                 }
3325
3326                 retval = target_read_memory(target, addr, width, count, buffer);
3327                 if (retval != ERROR_OK) {
3328                         /* BOO !*/
3329                         LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3330                                           (unsigned int)addr,
3331                                           (int)width,
3332                                           (int)count);
3333                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3334                         Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3335                         e = JIM_ERR;
3336                         len = 0;
3337                 } else {
3338                         v = 0; /* shut up gcc */
3339                         for (i = 0 ;i < count ;i++, n++) {
3340                                 switch (width) {
3341                                         case 4:
3342                                                 v = target_buffer_get_u32(target, &buffer[i*width]);
3343                                                 break;
3344                                         case 2:
3345                                                 v = target_buffer_get_u16(target, &buffer[i*width]);
3346                                                 break;
3347                                         case 1:
3348                                                 v = buffer[i] & 0x0ff;
3349                                                 break;
3350                                 }
3351                                 new_int_array_element(interp, varname, n, v);
3352                         }
3353                         len -= count;
3354                 }
3355         }
3356
3357         free(buffer);
3358
3359         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3360
3361         return JIM_OK;
3362 }
3363
3364 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3365 {
3366         char *namebuf;
3367         Jim_Obj *nameObjPtr, *valObjPtr;
3368         int result;
3369         long l;
3370
3371         namebuf = alloc_printf("%s(%d)", varname, idx);
3372         if (!namebuf)
3373                 return JIM_ERR;
3374
3375         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3376         if (!nameObjPtr)
3377         {
3378                 free(namebuf);
3379                 return JIM_ERR;
3380         }
3381
3382         Jim_IncrRefCount(nameObjPtr);
3383         valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3384         Jim_DecrRefCount(interp, nameObjPtr);
3385         free(namebuf);
3386         if (valObjPtr == NULL)
3387                 return JIM_ERR;
3388
3389         result = Jim_GetLong(interp, valObjPtr, &l);
3390         /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3391         *val = l;
3392         return result;
3393 }
3394
3395 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3396 {
3397         struct command_context *context;
3398         struct target *target;
3399
3400         context = Jim_GetAssocData(interp, "context");
3401         if (context == NULL) {
3402                 LOG_ERROR("array2mem: no command context");
3403                 return JIM_ERR;
3404         }
3405         target = get_current_target(context);
3406         if (target == NULL) {
3407                 LOG_ERROR("array2mem: no current target");
3408                 return JIM_ERR;
3409         }
3410
3411         return target_array2mem(interp,target, argc-1, argv + 1);
3412 }
3413
3414 static int target_array2mem(Jim_Interp *interp, struct target *target,
3415                 int argc, Jim_Obj *const *argv)
3416 {
3417         long l;
3418         uint32_t width;
3419         int len;
3420         uint32_t addr;
3421         uint32_t count;
3422         uint32_t v;
3423         const char *varname;
3424         int  n, e, retval;
3425         uint32_t i;
3426
3427         /* argv[1] = name of array to get the data
3428          * argv[2] = desired width
3429          * argv[3] = memory address
3430          * argv[4] = count to write
3431          */
3432         if (argc != 4) {
3433                 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3434                 return JIM_ERR;
3435         }
3436         varname = Jim_GetString(argv[0], &len);
3437         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3438
3439         e = Jim_GetLong(interp, argv[1], &l);
3440         width = l;
3441         if (e != JIM_OK) {
3442                 return e;
3443         }
3444
3445         e = Jim_GetLong(interp, argv[2], &l);
3446         addr = l;
3447         if (e != JIM_OK) {
3448                 return e;
3449         }
3450         e = Jim_GetLong(interp, argv[3], &l);
3451         len = l;
3452         if (e != JIM_OK) {
3453                 return e;
3454         }
3455         switch (width) {
3456                 case 8:
3457                         width = 1;
3458                         break;
3459                 case 16:
3460                         width = 2;
3461                         break;
3462                 case 32:
3463                         width = 4;
3464                         break;
3465                 default:
3466                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3467                         Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3468                         return JIM_ERR;
3469         }
3470         if (len == 0) {
3471                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3472                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3473                 return JIM_ERR;
3474         }
3475         if ((addr + (len * width)) < addr) {
3476                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3477                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3478                 return JIM_ERR;
3479         }
3480         /* absurd transfer size? */
3481         if (len > 65536) {
3482                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3483                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3484                 return JIM_ERR;
3485         }
3486
3487         if ((width == 1) ||
3488                 ((width == 2) && ((addr & 1) == 0)) ||
3489                 ((width == 4) && ((addr & 3) == 0))) {
3490                 /* all is well */
3491         } else {
3492                 char buf[100];
3493                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3494                 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3495                                 (unsigned int)addr,
3496                                 (int)width);
3497                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3498                 return JIM_ERR;
3499         }
3500
3501         /* Transfer loop */
3502
3503         /* index counter */
3504         n = 0;
3505         /* assume ok */
3506         e = JIM_OK;
3507
3508         size_t buffersize = 4096;
3509         uint8_t *buffer = malloc(buffersize);
3510         if (buffer == NULL)
3511                 return JIM_ERR;
3512
3513         while (len) {
3514                 /* Slurp... in buffer size chunks */
3515
3516                 count = len; /* in objects.. */
3517                 if (count > (buffersize/width)) {
3518                         count = (buffersize/width);
3519                 }
3520
3521                 v = 0; /* shut up gcc */
3522                 for (i = 0 ;i < count ;i++, n++) {
3523                         get_int_array_element(interp, varname, n, &v);
3524                         switch (width) {
3525                         case 4:
3526                                 target_buffer_set_u32(target, &buffer[i*width], v);
3527                                 break;
3528                         case 2:
3529                                 target_buffer_set_u16(target, &buffer[i*width], v);
3530                                 break;
3531                         case 1:
3532                                 buffer[i] = v & 0x0ff;
3533                                 break;
3534                         }
3535                 }
3536                 len -= count;
3537
3538                 retval = target_write_memory(target, addr, width, count, buffer);
3539                 if (retval != ERROR_OK) {
3540                         /* BOO !*/
3541                         LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3542                                           (unsigned int)addr,
3543                                           (int)width,
3544                                           (int)count);
3545                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3546                         Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3547                         e = JIM_ERR;
3548                         len = 0;
3549                 }
3550         }
3551
3552         free(buffer);
3553
3554         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3555
3556         return JIM_OK;
3557 }
3558
3559 void target_all_handle_event(enum target_event e)
3560 {
3561         struct target *target;
3562
3563         LOG_DEBUG("**all*targets: event: %d, %s",
3564                            (int)e,
3565                            Jim_Nvp_value2name_simple(nvp_target_event, e)->name);
3566
3567         target = all_targets;
3568         while (target) {
3569                 target_handle_event(target, e);
3570                 target = target->next;
3571         }
3572 }
3573
3574
3575 /* FIX? should we propagate errors here rather than printing them
3576  * and continuing?
3577  */
3578 void target_handle_event(struct target *target, enum target_event e)
3579 {
3580         struct target_event_action *teap;
3581
3582         for (teap = target->event_action; teap != NULL; teap = teap->next) {
3583                 if (teap->event == e) {
3584                         LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3585                                            target->target_number,
3586                                            target_name(target),
3587                                            target_type_name(target),
3588                                            e,
3589                                            Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3590                                            Jim_GetString(teap->body, NULL));
3591                         if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK)
3592                         {
3593                                 Jim_PrintErrorMessage(teap->interp);
3594                         }
3595                 }
3596         }
3597 }
3598
3599 /**
3600  * Returns true only if the target has a handler for the specified event.
3601  */
3602 bool target_has_event_action(struct target *target, enum target_event event)
3603 {
3604         struct target_event_action *teap;
3605
3606         for (teap = target->event_action; teap != NULL; teap = teap->next) {
3607                 if (teap->event == event)
3608                         return true;
3609         }
3610         return false;
3611 }
3612
3613 enum target_cfg_param {
3614         TCFG_TYPE,
3615         TCFG_EVENT,
3616         TCFG_WORK_AREA_VIRT,
3617         TCFG_WORK_AREA_PHYS,
3618         TCFG_WORK_AREA_SIZE,
3619         TCFG_WORK_AREA_BACKUP,
3620         TCFG_ENDIAN,
3621         TCFG_VARIANT,
3622         TCFG_CHAIN_POSITION,
3623 };
3624
3625 static Jim_Nvp nvp_config_opts[] = {
3626         { .name = "-type",             .value = TCFG_TYPE },
3627         { .name = "-event",            .value = TCFG_EVENT },
3628         { .name = "-work-area-virt",   .value = TCFG_WORK_AREA_VIRT },
3629         { .name = "-work-area-phys",   .value = TCFG_WORK_AREA_PHYS },
3630         { .name = "-work-area-size",   .value = TCFG_WORK_AREA_SIZE },
3631         { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3632         { .name = "-endian" ,          .value = TCFG_ENDIAN },
3633         { .name = "-variant",          .value = TCFG_VARIANT },
3634         { .name = "-chain-position",   .value = TCFG_CHAIN_POSITION },
3635
3636         { .name = NULL, .value = -1 }
3637 };
3638
3639 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3640 {
3641         Jim_Nvp *n;
3642         Jim_Obj *o;
3643         jim_wide w;
3644         char *cp;
3645         int e;
3646
3647         /* parse config or cget options ... */
3648         while (goi->argc > 0) {
3649                 Jim_SetEmptyResult(goi->interp);
3650                 /* Jim_GetOpt_Debug(goi); */
3651
3652                 if (target->type->target_jim_configure) {
3653                         /* target defines a configure function */
3654                         /* target gets first dibs on parameters */
3655                         e = (*(target->type->target_jim_configure))(target, goi);
3656                         if (e == JIM_OK) {
3657                                 /* more? */
3658                                 continue;
3659                         }
3660                         if (e == JIM_ERR) {
3661                                 /* An error */
3662                                 return e;
3663                         }
3664                         /* otherwise we 'continue' below */
3665                 }
3666                 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3667                 if (e != JIM_OK) {
3668                         Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3669                         return e;
3670                 }
3671                 switch (n->value) {
3672                 case TCFG_TYPE:
3673                         /* not setable */
3674                         if (goi->isconfigure) {
3675                                 Jim_SetResult_sprintf(goi->interp,
3676                                                 "not settable: %s", n->name);
3677                                 return JIM_ERR;
3678                         } else {
3679                         no_params:
3680                                 if (goi->argc != 0) {
3681                                         Jim_WrongNumArgs(goi->interp,
3682                                                         goi->argc, goi->argv,
3683                                                         "NO PARAMS");
3684                                         return JIM_ERR;
3685                                 }
3686                         }
3687                         Jim_SetResultString(goi->interp,
3688                                         target_type_name(target), -1);
3689                         /* loop for more */
3690                         break;
3691                 case TCFG_EVENT:
3692                         if (goi->argc == 0) {
3693                                 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3694                                 return JIM_ERR;
3695                         }
3696
3697                         e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3698                         if (e != JIM_OK) {
3699                                 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3700                                 return e;
3701                         }
3702
3703                         if (goi->isconfigure) {
3704                                 if (goi->argc != 1) {
3705                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3706                                         return JIM_ERR;
3707                                 }
3708                         } else {
3709                                 if (goi->argc != 0) {
3710                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3711                                         return JIM_ERR;
3712                                 }
3713                         }
3714
3715                         {
3716                                 struct target_event_action *teap;
3717
3718                                 teap = target->event_action;
3719                                 /* replace existing? */
3720                                 while (teap) {
3721                                         if (teap->event == (enum target_event)n->value) {
3722                                                 break;
3723                                         }
3724                                         teap = teap->next;
3725                                 }
3726
3727                                 if (goi->isconfigure) {
3728                                         bool replace = true;
3729                                         if (teap == NULL) {
3730                                                 /* create new */
3731                                                 teap = calloc(1, sizeof(*teap));
3732                                                 replace = false;
3733                                         }
3734                                         teap->event = n->value;
3735                                         teap->interp = goi->interp;
3736                                         Jim_GetOpt_Obj(goi, &o);
3737                                         if (teap->body) {
3738                                                 Jim_DecrRefCount(teap->interp, teap->body);
3739                                         }
3740                                         teap->body  = Jim_DuplicateObj(goi->interp, o);
3741                                         /*
3742                                          * FIXME:
3743                                          *     Tcl/TK - "tk events" have a nice feature.
3744                                          *     See the "BIND" command.
3745                                          *    We should support that here.
3746                                          *     You can specify %X and %Y in the event code.
3747                                          *     The idea is: %T - target name.
3748                                          *     The idea is: %N - target number
3749                                          *     The idea is: %E - event name.
3750                                          */
3751                                         Jim_IncrRefCount(teap->body);
3752
3753                                         if (!replace)
3754                                         {
3755                                                 /* add to head of event list */
3756                                                 teap->next = target->event_action;
3757                                                 target->event_action = teap;
3758                                         }
3759                                         Jim_SetEmptyResult(goi->interp);
3760                                 } else {
3761                                         /* get */
3762                                         if (teap == NULL) {
3763                                                 Jim_SetEmptyResult(goi->interp);
3764                                         } else {
3765                                                 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3766                                         }
3767                                 }
3768                         }
3769                         /* loop for more */
3770                         break;
3771
3772                 case TCFG_WORK_AREA_VIRT:
3773                         if (goi->isconfigure) {
3774                                 target_free_all_working_areas(target);
3775                                 e = Jim_GetOpt_Wide(goi, &w);
3776                                 if (e != JIM_OK) {
3777                                         return e;
3778                                 }
3779                                 target->working_area_virt = w;
3780                                 target->working_area_virt_spec = true;
3781                         } else {
3782                                 if (goi->argc != 0) {
3783                                         goto no_params;
3784                                 }
3785                         }
3786                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3787                         /* loop for more */
3788                         break;
3789
3790                 case TCFG_WORK_AREA_PHYS:
3791                         if (goi->isconfigure) {
3792                                 target_free_all_working_areas(target);
3793                                 e = Jim_GetOpt_Wide(goi, &w);
3794                                 if (e != JIM_OK) {
3795                                         return e;
3796                                 }
3797                                 target->working_area_phys = w;
3798                                 target->working_area_phys_spec = true;
3799                         } else {
3800                                 if (goi->argc != 0) {
3801                                         goto no_params;
3802                                 }
3803                         }
3804                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3805                         /* loop for more */
3806                         break;
3807
3808                 case TCFG_WORK_AREA_SIZE:
3809                         if (goi->isconfigure) {
3810                                 target_free_all_working_areas(target);
3811                                 e = Jim_GetOpt_Wide(goi, &w);
3812                                 if (e != JIM_OK) {
3813                                         return e;
3814                                 }
3815                                 target->working_area_size = w;
3816                         } else {
3817                                 if (goi->argc != 0) {
3818                                         goto no_params;
3819                                 }
3820                         }
3821                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3822                         /* loop for more */
3823                         break;
3824
3825                 case TCFG_WORK_AREA_BACKUP:
3826                         if (goi->isconfigure) {
3827                                 target_free_all_working_areas(target);
3828                                 e = Jim_GetOpt_Wide(goi, &w);
3829                                 if (e != JIM_OK) {
3830                                         return e;
3831                                 }
3832                                 /* make this exactly 1 or 0 */
3833                                 target->backup_working_area = (!!w);
3834                         } else {
3835                                 if (goi->argc != 0) {
3836                                         goto no_params;
3837                                 }
3838                         }
3839                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3840                         /* loop for more e*/
3841                         break;
3842
3843                 case TCFG_ENDIAN:
3844                         if (goi->isconfigure) {
3845                                 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3846                                 if (e != JIM_OK) {
3847                                         Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3848                                         return e;
3849                                 }
3850                                 target->endianness = n->value;
3851                         } else {
3852                                 if (goi->argc != 0) {
3853                                         goto no_params;
3854                                 }
3855                         }
3856                         n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3857                         if (n->name == NULL) {
3858                                 target->endianness = TARGET_LITTLE_ENDIAN;
3859                                 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3860                         }
3861                         Jim_SetResultString(goi->interp, n->name, -1);
3862                         /* loop for more */
3863                         break;
3864
3865                 case TCFG_VARIANT:
3866                         if (goi->isconfigure) {
3867                                 if (goi->argc < 1) {
3868                                         Jim_SetResult_sprintf(goi->interp,
3869                                                                                    "%s ?STRING?",
3870                                                                                    n->name);
3871                                         return JIM_ERR;
3872                                 }
3873                                 if (target->variant) {
3874                                         free((void *)(target->variant));
3875                                 }
3876                                 e = Jim_GetOpt_String(goi, &cp, NULL);
3877                                 target->variant = strdup(cp);
3878                         } else {
3879                                 if (goi->argc != 0) {
3880                                         goto no_params;
3881                                 }
3882                         }
3883                         Jim_SetResultString(goi->interp, target->variant,-1);
3884                         /* loop for more */
3885                         break;
3886                 case TCFG_CHAIN_POSITION:
3887                         if (goi->isconfigure) {
3888                                 Jim_Obj *o;
3889                                 struct jtag_tap *tap;
3890                                 target_free_all_working_areas(target);
3891                                 e = Jim_GetOpt_Obj(goi, &o);
3892                                 if (e != JIM_OK) {
3893                                         return e;
3894                                 }
3895                                 tap = jtag_tap_by_jim_obj(goi->interp, o);
3896                                 if (tap == NULL) {
3897                                         return JIM_ERR;
3898                                 }
3899                                 /* make this exactly 1 or 0 */
3900                                 target->tap = tap;
3901                         } else {
3902                                 if (goi->argc != 0) {
3903                                         goto no_params;
3904                                 }
3905                         }
3906                         Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
3907                         /* loop for more e*/
3908                         break;
3909                 }
3910         } /* while (goi->argc) */
3911
3912
3913                 /* done - we return */
3914         return JIM_OK;
3915 }
3916
3917 static int
3918 jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3919 {
3920         Jim_GetOptInfo goi;
3921
3922         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3923         goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
3924         int need_args = 1 + goi.isconfigure;
3925         if (goi.argc < need_args)
3926         {
3927                 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
3928                         goi.isconfigure
3929                                 ? "missing: -option VALUE ..."
3930                                 : "missing: -option ...");
3931                 return JIM_ERR;
3932         }
3933         struct target *target = Jim_CmdPrivData(goi.interp);
3934         return target_configure(&goi, target);
3935 }
3936
3937 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3938 {
3939         const char *cmd_name = Jim_GetString(argv[0], NULL);
3940
3941         Jim_GetOptInfo goi;
3942         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3943
3944         /* danger! goi.argc will be modified below! */
3945         argc = goi.argc;
3946
3947         if (argc != 2 && argc != 3)
3948         {
3949                 Jim_SetResult_sprintf(goi.interp,
3950                                 "usage: %s <address> <data> [<count>]", cmd_name);
3951                 return JIM_ERR;
3952         }
3953
3954
3955         jim_wide a;
3956         int e = Jim_GetOpt_Wide(&goi, &a);
3957         if (e != JIM_OK)
3958                 return e;
3959
3960         jim_wide b;
3961         e = Jim_GetOpt_Wide(&goi, &b);
3962         if (e != JIM_OK)
3963                 return e;
3964
3965         jim_wide c = 1;
3966         if (argc == 3)
3967         {
3968                 e = Jim_GetOpt_Wide(&goi, &c);
3969                 if (e != JIM_OK)
3970                         return e;
3971         }
3972
3973         struct target *target = Jim_CmdPrivData(goi.interp);
3974         unsigned data_size;
3975         if (strcasecmp(cmd_name, "mww") == 0) {
3976                 data_size = 4;
3977         }
3978         else if (strcasecmp(cmd_name, "mwh") == 0) {
3979                 data_size = 2;
3980         }
3981         else if (strcasecmp(cmd_name, "mwb") == 0) {
3982                 data_size = 1;
3983         } else {
3984                 LOG_ERROR("command '%s' unknown: ", cmd_name);
3985                 return JIM_ERR;
3986         }
3987
3988         return (target_fill_mem(target, a, target_write_memory_fast, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
3989 }
3990
3991 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3992 {
3993         const char *cmd_name = Jim_GetString(argv[0], NULL);
3994
3995         Jim_GetOptInfo goi;
3996         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3997
3998         /* danger! goi.argc will be modified below! */
3999         argc = goi.argc;
4000
4001         if ((argc != 1) && (argc != 2))
4002         {
4003                 Jim_SetResult_sprintf(goi.interp,
4004                                 "usage: %s <address> [<count>]", cmd_name);
4005                 return JIM_ERR;
4006         }
4007
4008         jim_wide a;
4009         int e = Jim_GetOpt_Wide(&goi, &a);
4010         if (e != JIM_OK) {
4011                 return JIM_ERR;
4012         }
4013         jim_wide c;
4014         if (argc == 2) {
4015                 e = Jim_GetOpt_Wide(&goi, &c);
4016                 if (e != JIM_OK) {
4017                         return JIM_ERR;
4018                 }
4019         } else {
4020                 c = 1;
4021         }
4022         jim_wide b = 1; /* shut up gcc */
4023         if (strcasecmp(cmd_name, "mdw") == 0)
4024                 b = 4;
4025         else if (strcasecmp(cmd_name, "mdh") == 0)
4026                 b = 2;
4027         else if (strcasecmp(cmd_name, "mdb") == 0)
4028                 b = 1;
4029         else {
4030                 LOG_ERROR("command '%s' unknown: ", cmd_name);
4031                 return JIM_ERR;
4032         }
4033
4034         /* convert count to "bytes" */
4035         c = c * b;
4036
4037         struct target *target = Jim_CmdPrivData(goi.interp);
4038         uint8_t  target_buf[32];
4039         jim_wide x, y, z;
4040         while (c > 0) {
4041                 y = c;
4042                 if (y > 16) {
4043                         y = 16;
4044                 }
4045                 e = target_read_memory(target, a, b, y / b, target_buf);
4046                 if (e != ERROR_OK) {
4047                         Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
4048                         return JIM_ERR;
4049                 }
4050
4051                 Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
4052                 switch (b) {
4053                 case 4:
4054                         for (x = 0; x < 16 && x < y; x += 4)
4055                         {
4056                                 z = target_buffer_get_u32(target, &(target_buf[ x ]));
4057                                 Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
4058                         }
4059                         for (; (x < 16) ; x += 4) {
4060                                 Jim_fprintf(interp, interp->cookie_stdout, "         ");
4061                         }
4062                         break;
4063                 case 2:
4064                         for (x = 0; x < 16 && x < y; x += 2)
4065                         {
4066                                 z = target_buffer_get_u16(target, &(target_buf[ x ]));
4067                                 Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
4068                         }
4069                         for (; (x < 16) ; x += 2) {
4070                                 Jim_fprintf(interp, interp->cookie_stdout, "     ");
4071                         }
4072                         break;
4073                 case 1:
4074                 default:
4075                         for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4076                                 z = target_buffer_get_u8(target, &(target_buf[ x ]));
4077                                 Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
4078                         }
4079                         for (; (x < 16) ; x += 1) {
4080                                 Jim_fprintf(interp, interp->cookie_stdout, "   ");
4081                         }
4082                         break;
4083                 }
4084                 /* ascii-ify the bytes */
4085                 for (x = 0 ; x < y ; x++) {
4086                         if ((target_buf[x] >= 0x20) &&
4087                                 (target_buf[x] <= 0x7e)) {
4088                                 /* good */
4089                         } else {
4090                                 /* smack it */
4091                                 target_buf[x] = '.';
4092                         }
4093                 }
4094                 /* space pad  */
4095                 while (x < 16) {
4096                         target_buf[x] = ' ';
4097                         x++;
4098                 }
4099                 /* terminate */
4100                 target_buf[16] = 0;
4101                 /* print - with a newline */
4102                 Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
4103                 /* NEXT... */
4104                 c -= 16;
4105                 a += 16;
4106         }
4107         return JIM_OK;
4108 }
4109
4110 static int jim_target_mem2array(Jim_Interp *interp,
4111                 int argc, Jim_Obj *const *argv)
4112 {
4113         struct target *target = Jim_CmdPrivData(interp);
4114         return target_mem2array(interp, target, argc - 1, argv + 1);
4115 }
4116
4117 static int jim_target_array2mem(Jim_Interp *interp,
4118                 int argc, Jim_Obj *const *argv)
4119 {
4120         struct target *target = Jim_CmdPrivData(interp);
4121         return target_array2mem(interp, target, argc - 1, argv + 1);
4122 }
4123
4124 static int jim_target_tap_disabled(Jim_Interp *interp)
4125 {
4126         Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4127         return JIM_ERR;
4128 }
4129
4130 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4131 {
4132         if (argc != 1)
4133         {
4134                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4135                 return JIM_ERR;
4136         }
4137         struct target *target = Jim_CmdPrivData(interp);
4138         if (!target->tap->enabled)
4139                 return jim_target_tap_disabled(interp);
4140
4141         int e = target->type->examine(target);
4142         if (e != ERROR_OK)
4143         {
4144                 Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
4145                 return JIM_ERR;
4146         }
4147         return JIM_OK;
4148 }
4149
4150 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4151 {
4152         if (argc != 1)
4153         {
4154                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4155                 return JIM_ERR;
4156         }
4157         struct target *target = Jim_CmdPrivData(interp);
4158
4159         if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4160                 return JIM_ERR;
4161
4162         return JIM_OK;
4163 }
4164
4165 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4166 {
4167         if (argc != 1)
4168         {
4169                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4170                 return JIM_ERR;
4171         }
4172         struct target *target = Jim_CmdPrivData(interp);
4173         if (!target->tap->enabled)
4174                 return jim_target_tap_disabled(interp);
4175
4176         int e;
4177         if (!(target_was_examined(target))) {
4178                 e = ERROR_TARGET_NOT_EXAMINED;
4179         } else {
4180                 e = target->type->poll(target);
4181         }
4182         if (e != ERROR_OK)
4183         {
4184                 Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4185                 return JIM_ERR;
4186         }
4187         return JIM_OK;
4188 }
4189
4190 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4191 {
4192         Jim_GetOptInfo goi;
4193         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4194
4195         if (goi.argc != 2)
4196         {
4197                 Jim_WrongNumArgs(interp, 0, argv,
4198                                 "([tT]|[fF]|assert|deassert) BOOL");
4199                 return JIM_ERR;
4200         }
4201
4202         Jim_Nvp *n;
4203         int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4204         if (e != JIM_OK)
4205         {
4206                 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4207                 return e;
4208         }
4209         /* the halt or not param */
4210         jim_wide a;
4211         e = Jim_GetOpt_Wide(&goi, &a);
4212         if (e != JIM_OK)
4213                 return e;
4214
4215         struct target *target = Jim_CmdPrivData(goi.interp);
4216         if (!target->tap->enabled)
4217                 return jim_target_tap_disabled(interp);
4218         if (!(target_was_examined(target)))
4219         {
4220                 LOG_ERROR("Target not examined yet");
4221                 return ERROR_TARGET_NOT_EXAMINED;
4222         }
4223         if (!target->type->assert_reset || !target->type->deassert_reset)
4224         {
4225                 Jim_SetResult_sprintf(interp,
4226                                 "No target-specific reset for %s",
4227                                 target_name(target));
4228                 return JIM_ERR;
4229         }
4230         /* determine if we should halt or not. */
4231         target->reset_halt = !!a;
4232         /* When this happens - all workareas are invalid. */
4233         target_free_all_working_areas_restore(target, 0);
4234
4235         /* do the assert */
4236         if (n->value == NVP_ASSERT) {
4237                 e = target->type->assert_reset(target);
4238         } else {
4239                 e = target->type->deassert_reset(target);
4240         }
4241         return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4242 }
4243
4244 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4245 {
4246         if (argc != 1) {
4247                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4248                 return JIM_ERR;
4249         }
4250         struct target *target = Jim_CmdPrivData(interp);
4251         if (!target->tap->enabled)
4252                 return jim_target_tap_disabled(interp);
4253         int e = target->type->halt(target);
4254         return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4255 }
4256
4257 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4258 {
4259         Jim_GetOptInfo goi;
4260         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4261
4262         /* params:  <name>  statename timeoutmsecs */
4263         if (goi.argc != 2)
4264         {
4265                 const char *cmd_name = Jim_GetString(argv[0], NULL);
4266                 Jim_SetResult_sprintf(goi.interp,
4267                                 "%s <state_name> <timeout_in_msec>", cmd_name);
4268                 return JIM_ERR;
4269         }
4270
4271         Jim_Nvp *n;
4272         int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4273         if (e != JIM_OK) {
4274                 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4275                 return e;
4276         }
4277         jim_wide a;
4278         e = Jim_GetOpt_Wide(&goi, &a);
4279         if (e != JIM_OK) {
4280                 return e;
4281         }
4282         struct target *target = Jim_CmdPrivData(interp);
4283         if (!target->tap->enabled)
4284                 return jim_target_tap_disabled(interp);
4285
4286         e = target_wait_state(target, n->value, a);
4287         if (e != ERROR_OK)
4288         {
4289                 Jim_SetResult_sprintf(goi.interp,
4290                                 "target: %s wait %s fails (%d) %s",
4291                                 target_name(target), n->name,
4292                                 e, target_strerror_safe(e));
4293                 return JIM_ERR;
4294         }
4295         return JIM_OK;
4296 }
4297 /* List for human, Events defined for this target.
4298  * scripts/programs should use 'name cget -event NAME'
4299  */
4300 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4301 {
4302         struct command_context *cmd_ctx = Jim_GetAssocData(interp, "context");
4303         struct target *target = Jim_CmdPrivData(interp);
4304         struct target_event_action *teap = target->event_action;
4305         command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4306                                    target->target_number,
4307                                    target_name(target));
4308         command_print(cmd_ctx, "%-25s | Body", "Event");
4309         command_print(cmd_ctx, "------------------------- | "
4310                         "----------------------------------------");
4311         while (teap)
4312         {
4313                 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4314                 command_print(cmd_ctx, "%-25s | %s",
4315                                 opt->name, Jim_GetString(teap->body, NULL));
4316                 teap = teap->next;
4317         }
4318         command_print(cmd_ctx, "***END***");
4319         return JIM_OK;
4320 }
4321 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4322 {
4323         if (argc != 1)
4324         {
4325                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4326                 return JIM_ERR;
4327         }
4328         struct target *target = Jim_CmdPrivData(interp);
4329         Jim_SetResultString(interp, target_state_name(target), -1);
4330         return JIM_OK;
4331 }
4332 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4333 {
4334         Jim_GetOptInfo goi;
4335         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4336         if (goi.argc != 1)
4337         {
4338                 const char *cmd_name = Jim_GetString(argv[0], NULL);
4339                 Jim_SetResult_sprintf(goi.interp, "%s <eventname>", cmd_name);
4340                 return JIM_ERR;
4341         }
4342         Jim_Nvp *n;
4343         int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4344         if (e != JIM_OK)
4345         {
4346                 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4347                 return e;
4348         }
4349         struct target *target = Jim_CmdPrivData(interp);
4350         target_handle_event(target, n->value);
4351         return JIM_OK;
4352 }
4353
4354 static const struct command_registration target_instance_command_handlers[] = {
4355         {
4356                 .name = "configure",
4357                 .mode = COMMAND_CONFIG,
4358                 .jim_handler = jim_target_configure,
4359                 .help  = "configure a new target for use",
4360                 .usage = "[target_attribute ...]",
4361         },
4362         {
4363                 .name = "cget",
4364                 .mode = COMMAND_ANY,
4365                 .jim_handler = jim_target_configure,
4366                 .help  = "returns the specified target attribute",
4367                 .usage = "target_attribute",
4368         },
4369         {
4370                 .name = "mww",
4371                 .mode = COMMAND_EXEC,
4372                 .jim_handler = jim_target_mw,
4373                 .help = "Write 32-bit word(s) to target memory",
4374                 .usage = "address data [count]",
4375         },
4376         {
4377                 .name = "mwh",
4378                 .mode = COMMAND_EXEC,
4379                 .jim_handler = jim_target_mw,
4380                 .help = "Write 16-bit half-word(s) to target memory",
4381                 .usage = "address data [count]",
4382         },
4383         {
4384                 .name = "mwb",
4385                 .mode = COMMAND_EXEC,
4386                 .jim_handler = jim_target_mw,
4387                 .help = "Write byte(s) to target memory",
4388                 .usage = "address data [count]",
4389         },
4390         {
4391                 .name = "mdw",
4392                 .mode = COMMAND_EXEC,
4393                 .jim_handler = jim_target_md,
4394                 .help = "Display target memory as 32-bit words",
4395                 .usage = "address [count]",
4396         },
4397         {
4398                 .name = "mdh",
4399                 .mode = COMMAND_EXEC,
4400                 .jim_handler = jim_target_md,
4401                 .help = "Display target memory as 16-bit half-words",
4402                 .usage = "address [count]",
4403         },
4404         {
4405                 .name = "mdb",
4406                 .mode = COMMAND_EXEC,
4407                 .jim_handler = jim_target_md,
4408                 .help = "Display target memory as 8-bit bytes",
4409                 .usage = "address [count]",
4410         },
4411         {
4412                 .name = "array2mem",
4413                 .mode = COMMAND_EXEC,
4414                 .jim_handler = jim_target_array2mem,
4415                 .help = "Writes Tcl array of 8/16/32 bit numbers "
4416                         "to target memory",
4417                 .usage = "arrayname bitwidth address count",
4418         },
4419         {
4420                 .name = "mem2array",
4421                 .mode = COMMAND_EXEC,
4422                 .jim_handler = jim_target_mem2array,
4423                 .help = "Loads Tcl array of 8/16/32 bit numbers "
4424                         "from target memory",
4425                 .usage = "arrayname bitwidth address count",
4426         },
4427         {
4428                 .name = "eventlist",
4429                 .mode = COMMAND_EXEC,
4430                 .jim_handler = jim_target_event_list,
4431                 .help = "displays a table of events defined for this target",
4432         },
4433         {
4434                 .name = "curstate",
4435                 .mode = COMMAND_EXEC,
4436                 .jim_handler = jim_target_current_state,
4437                 .help = "displays the current state of this target",
4438         },
4439         {
4440                 .name = "arp_examine",
4441                 .mode = COMMAND_EXEC,
4442                 .jim_handler = jim_target_examine,
4443                 .help = "used internally for reset processing",
4444         },
4445         {
4446                 .name = "arp_halt_gdb",
4447                 .mode = COMMAND_EXEC,
4448                 .jim_handler = jim_target_halt_gdb,
4449                 .help = "used internally for reset processing to halt GDB",
4450         },
4451         {
4452                 .name = "arp_poll",
4453                 .mode = COMMAND_EXEC,
4454                 .jim_handler = jim_target_poll,
4455                 .help = "used internally for reset processing",
4456         },
4457         {
4458                 .name = "arp_reset",
4459                 .mode = COMMAND_EXEC,
4460                 .jim_handler = jim_target_reset,
4461                 .help = "used internally for reset processing",
4462         },
4463         {
4464                 .name = "arp_halt",
4465                 .mode = COMMAND_EXEC,
4466                 .jim_handler = jim_target_halt,
4467                 .help = "used internally for reset processing",
4468         },
4469         {
4470                 .name = "arp_waitstate",
4471                 .mode = COMMAND_EXEC,
4472                 .jim_handler = jim_target_wait_state,
4473                 .help = "used internally for reset processing",
4474         },
4475         {
4476                 .name = "invoke-event",
4477                 .mode = COMMAND_EXEC,
4478                 .jim_handler = jim_target_invoke_event,
4479                 .help = "invoke handler for specified event",
4480                 .usage = "event_name",
4481         },
4482         COMMAND_REGISTRATION_DONE
4483 };
4484
4485 static int target_create(Jim_GetOptInfo *goi)
4486 {
4487         Jim_Obj *new_cmd;
4488         Jim_Cmd *cmd;
4489         const char *cp;
4490         char *cp2;
4491         int e;
4492         int x;
4493         struct target *target;
4494         struct command_context *cmd_ctx;
4495
4496         cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4497         if (goi->argc < 3) {
4498                 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4499                 return JIM_ERR;
4500         }
4501
4502         /* COMMAND */
4503         Jim_GetOpt_Obj(goi, &new_cmd);
4504         /* does this command exist? */
4505         cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4506         if (cmd) {
4507                 cp = Jim_GetString(new_cmd, NULL);
4508                 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4509                 return JIM_ERR;
4510         }
4511
4512         /* TYPE */
4513         e = Jim_GetOpt_String(goi, &cp2, NULL);
4514         cp = cp2;
4515         /* now does target type exist */
4516         for (x = 0 ; target_types[x] ; x++) {
4517                 if (0 == strcmp(cp, target_types[x]->name)) {
4518                         /* found */
4519                         break;
4520                 }
4521         }
4522         if (target_types[x] == NULL) {
4523                 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4524                 for (x = 0 ; target_types[x] ; x++) {
4525                         if (target_types[x + 1]) {
4526                                 Jim_AppendStrings(goi->interp,
4527                                                                    Jim_GetResult(goi->interp),
4528                                                                    target_types[x]->name,
4529                                                                    ", ", NULL);
4530                         } else {
4531                                 Jim_AppendStrings(goi->interp,
4532                                                                    Jim_GetResult(goi->interp),
4533                                                                    " or ",
4534                                                                    target_types[x]->name,NULL);
4535                         }
4536                 }
4537                 return JIM_ERR;
4538         }
4539
4540         /* Create it */
4541         target = calloc(1,sizeof(struct target));
4542         /* set target number */
4543         target->target_number = new_target_number();
4544
4545         /* allocate memory for each unique target type */
4546         target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4547
4548         memcpy(target->type, target_types[x], sizeof(struct target_type));
4549
4550         /* will be set by "-endian" */
4551         target->endianness = TARGET_ENDIAN_UNKNOWN;
4552
4553         target->working_area        = 0x0;
4554         target->working_area_size   = 0x0;
4555         target->working_areas       = NULL;
4556         target->backup_working_area = 0;
4557
4558         target->state               = TARGET_UNKNOWN;
4559         target->debug_reason        = DBG_REASON_UNDEFINED;
4560         target->reg_cache           = NULL;
4561         target->breakpoints         = NULL;
4562         target->watchpoints         = NULL;
4563         target->next                = NULL;
4564         target->arch_info           = NULL;
4565
4566         target->display             = 1;
4567
4568         target->halt_issued                     = false;
4569
4570         /* initialize trace information */
4571         target->trace_info = malloc(sizeof(struct trace));
4572         target->trace_info->num_trace_points         = 0;
4573         target->trace_info->trace_points_size        = 0;
4574         target->trace_info->trace_points             = NULL;
4575         target->trace_info->trace_history_size       = 0;
4576         target->trace_info->trace_history            = NULL;
4577         target->trace_info->trace_history_pos        = 0;
4578         target->trace_info->trace_history_overflowed = 0;
4579
4580         target->dbgmsg          = NULL;
4581         target->dbg_msg_enabled = 0;
4582
4583         target->endianness = TARGET_ENDIAN_UNKNOWN;
4584
4585         /* Do the rest as "configure" options */
4586         goi->isconfigure = 1;
4587         e = target_configure(goi, target);
4588
4589         if (target->tap == NULL)
4590         {
4591                 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4592                 e = JIM_ERR;
4593         }
4594
4595         if (e != JIM_OK) {
4596                 free(target->type);
4597                 free(target);
4598                 return e;
4599         }
4600
4601         if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4602                 /* default endian to little if not specified */
4603                 target->endianness = TARGET_LITTLE_ENDIAN;
4604         }
4605
4606         /* incase variant is not set */
4607         if (!target->variant)
4608                 target->variant = strdup("");
4609
4610         cp = Jim_GetString(new_cmd, NULL);
4611         target->cmd_name = strdup(cp);
4612
4613         /* create the target specific commands */
4614         if (target->type->commands) {
4615                 e = register_commands(cmd_ctx, NULL, target->type->commands);
4616                 if (ERROR_OK != e)
4617                         LOG_ERROR("unable to register '%s' commands", cp);
4618         }
4619         if (target->type->target_create) {
4620                 (*(target->type->target_create))(target, goi->interp);
4621         }
4622
4623         /* append to end of list */
4624         {
4625                 struct target **tpp;
4626                 tpp = &(all_targets);
4627                 while (*tpp) {
4628                         tpp = &((*tpp)->next);
4629                 }
4630                 *tpp = target;
4631         }
4632
4633         /* now - create the new target name command */
4634         const const struct command_registration target_subcommands[] = {
4635                 {
4636                         .chain = target_instance_command_handlers,
4637                 },
4638                 {
4639                         .chain = target->type->commands,
4640                 },
4641                 COMMAND_REGISTRATION_DONE
4642         };
4643         const const struct command_registration target_commands[] = {
4644                 {
4645                         .name = cp,
4646                         .mode = COMMAND_ANY,
4647                         .help = "target command group",
4648                         .chain = target_subcommands,
4649                 },
4650                 COMMAND_REGISTRATION_DONE
4651         };
4652         e = register_commands(cmd_ctx, NULL, target_commands);
4653         if (ERROR_OK != e)
4654                 return JIM_ERR;
4655
4656         struct command *c = command_find_in_context(cmd_ctx, cp);
4657         assert(c);
4658         command_set_handler_data(c, target);
4659
4660         return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
4661 }
4662
4663 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4664 {
4665         if (argc != 1)
4666         {
4667                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4668                 return JIM_ERR;
4669         }
4670         struct command_context *cmd_ctx = Jim_GetAssocData(interp, "context");
4671         Jim_SetResultString(interp, get_current_target(cmd_ctx)->cmd_name, -1);
4672         return JIM_OK;
4673 }
4674
4675 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4676 {
4677         if (argc != 1)
4678         {
4679                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4680                 return JIM_ERR;
4681         }
4682         Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4683         for (unsigned x = 0; NULL != target_types[x]; x++)
4684         {
4685                 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4686                         Jim_NewStringObj(interp, target_types[x]->name, -1));
4687         }
4688         return JIM_OK;
4689 }
4690
4691 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4692 {
4693         if (argc != 1)
4694         {
4695                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4696                 return JIM_ERR;
4697         }
4698         Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4699         struct target *target = all_targets;
4700         while (target)
4701         {
4702                 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4703                         Jim_NewStringObj(interp, target_name(target), -1));
4704                 target = target->next;
4705         }
4706         return JIM_OK;
4707 }
4708
4709 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4710 {
4711         Jim_GetOptInfo goi;
4712         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4713         if (goi.argc < 3)
4714         {
4715                 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4716                         "<name> <target_type> [<target_options> ...]");
4717                 return JIM_ERR;
4718         }
4719         return target_create(&goi);
4720 }
4721
4722 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4723 {
4724         Jim_GetOptInfo goi;
4725         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4726
4727         /* It's OK to remove this mechanism sometime after August 2010 or so */
4728         LOG_WARNING("don't use numbers as target identifiers; use names");
4729         if (goi.argc != 1)
4730         {
4731                 Jim_SetResult_sprintf(goi.interp, "usage: target number <number>");
4732                 return JIM_ERR;
4733         }
4734         jim_wide w;
4735         int e = Jim_GetOpt_Wide(&goi, &w);
4736         if (e != JIM_OK)
4737                 return JIM_ERR;
4738
4739         struct target *target;
4740         for (target = all_targets; NULL != target; target = target->next)
4741         {
4742                 if (target->target_number != w)
4743                         continue;
4744
4745                 Jim_SetResultString(goi.interp, target_name(target), -1);
4746                 return JIM_OK;
4747         }
4748         Jim_SetResult_sprintf(goi.interp,
4749                         "Target: number %d does not exist", (int)(w));
4750         return JIM_ERR;
4751 }
4752
4753 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4754 {
4755         if (argc != 1)
4756         {
4757                 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
4758                 return JIM_ERR;
4759         }
4760         unsigned count = 0;
4761         struct target *target = all_targets;
4762         while (NULL != target)
4763         {
4764                 target = target->next;
4765                 count++;
4766         }
4767         Jim_SetResult(interp, Jim_NewIntObj(interp, count));
4768         return JIM_OK;
4769 }
4770
4771 static const struct command_registration target_subcommand_handlers[] = {
4772         {
4773                 .name = "init",
4774                 .mode = COMMAND_CONFIG,
4775                 .handler = handle_target_init_command,
4776                 .help = "initialize targets",
4777         },
4778         {
4779                 .name = "create",
4780                 /* REVISIT this should be COMMAND_CONFIG ... */
4781                 .mode = COMMAND_ANY,
4782                 .jim_handler = jim_target_create,
4783                 .usage = "name type '-chain-position' name [options ...]",
4784                 .help = "Creates and selects a new target",
4785         },
4786         {
4787                 .name = "current",
4788                 .mode = COMMAND_ANY,
4789                 .jim_handler = jim_target_current,
4790                 .help = "Returns the currently selected target",
4791         },
4792         {
4793                 .name = "types",
4794                 .mode = COMMAND_ANY,
4795                 .jim_handler = jim_target_types,
4796                 .help = "Returns the available target types as "
4797                                 "a list of strings",
4798         },
4799         {
4800                 .name = "names",
4801                 .mode = COMMAND_ANY,
4802                 .jim_handler = jim_target_names,
4803                 .help = "Returns the names of all targets as a list of strings",
4804         },
4805         {
4806                 .name = "number",
4807                 .mode = COMMAND_ANY,
4808                 .jim_handler = jim_target_number,
4809                 .usage = "number",
4810                 .help = "Returns the name of the numbered target "
4811                         "(DEPRECATED)",
4812         },
4813         {
4814                 .name = "count",
4815                 .mode = COMMAND_ANY,
4816                 .jim_handler = jim_target_count,
4817                 .help = "Returns the number of targets as an integer "
4818                         "(DEPRECATED)",
4819         },
4820         COMMAND_REGISTRATION_DONE
4821 };
4822
4823 struct FastLoad
4824 {
4825         uint32_t address;
4826         uint8_t *data;
4827         int length;
4828
4829 };
4830
4831 static int fastload_num;
4832 static struct FastLoad *fastload;
4833
4834 static void free_fastload(void)
4835 {
4836         if (fastload != NULL)
4837         {
4838                 int i;
4839                 for (i = 0; i < fastload_num; i++)
4840                 {
4841                         if (fastload[i].data)
4842                                 free(fastload[i].data);
4843                 }
4844                 free(fastload);
4845                 fastload = NULL;
4846         }
4847 }
4848
4849
4850
4851
4852 COMMAND_HANDLER(handle_fast_load_image_command)
4853 {
4854         uint8_t *buffer;
4855         size_t buf_cnt;
4856         uint32_t image_size;
4857         uint32_t min_address = 0;
4858         uint32_t max_address = 0xffffffff;
4859         int i;
4860
4861         struct image image;
4862
4863         int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
4864                         &image, &min_address, &max_address);
4865         if (ERROR_OK != retval)
4866                 return retval;
4867
4868         struct duration bench;
4869         duration_start(&bench);
4870
4871         if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
4872         {
4873                 return ERROR_OK;
4874         }
4875
4876         image_size = 0x0;
4877         retval = ERROR_OK;
4878         fastload_num = image.num_sections;
4879         fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4880         if (fastload == NULL)
4881         {
4882                 image_close(&image);
4883                 return ERROR_FAIL;
4884         }
4885         memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4886         for (i = 0; i < image.num_sections; i++)
4887         {
4888                 buffer = malloc(image.sections[i].size);
4889                 if (buffer == NULL)
4890                 {
4891                         command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
4892                                                   (int)(image.sections[i].size));
4893                         break;
4894                 }
4895
4896                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4897                 {
4898                         free(buffer);
4899                         break;
4900                 }
4901
4902                 uint32_t offset = 0;
4903                 uint32_t length = buf_cnt;
4904
4905
4906                 /* DANGER!!! beware of unsigned comparision here!!! */
4907
4908                 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4909                                 (image.sections[i].base_address < max_address))
4910                 {
4911                         if (image.sections[i].base_address < min_address)
4912                         {
4913                                 /* clip addresses below */
4914                                 offset += min_address-image.sections[i].base_address;
4915                                 length -= offset;
4916                         }
4917
4918                         if (image.sections[i].base_address + buf_cnt > max_address)
4919                         {
4920                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
4921                         }
4922
4923                         fastload[i].address = image.sections[i].base_address + offset;
4924                         fastload[i].data = malloc(length);
4925                         if (fastload[i].data == NULL)
4926                         {
4927                                 free(buffer);
4928                                 break;
4929                         }
4930                         memcpy(fastload[i].data, buffer + offset, length);
4931                         fastload[i].length = length;
4932
4933                         image_size += length;
4934                         command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
4935                                                   (unsigned int)length,
4936                                                   ((unsigned int)(image.sections[i].base_address + offset)));
4937                 }
4938
4939                 free(buffer);
4940         }
4941
4942         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
4943         {
4944                 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
4945                                 "in %fs (%0.3f kb/s)", image_size, 
4946                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
4947
4948                 command_print(CMD_CTX,
4949                                 "WARNING: image has not been loaded to target!"
4950                                 "You can issue a 'fast_load' to finish loading.");
4951         }
4952
4953         image_close(&image);
4954
4955         if (retval != ERROR_OK)
4956         {
4957                 free_fastload();
4958         }
4959
4960         return retval;
4961 }
4962
4963 COMMAND_HANDLER(handle_fast_load_command)
4964 {
4965         if (CMD_ARGC > 0)
4966                 return ERROR_COMMAND_SYNTAX_ERROR;
4967         if (fastload == NULL)
4968         {
4969                 LOG_ERROR("No image in memory");
4970                 return ERROR_FAIL;
4971         }
4972         int i;
4973         int ms = timeval_ms();
4974         int size = 0;
4975         int retval = ERROR_OK;
4976         for (i = 0; i < fastload_num;i++)
4977         {
4978                 struct target *target = get_current_target(CMD_CTX);
4979                 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
4980                                           (unsigned int)(fastload[i].address),
4981                                           (unsigned int)(fastload[i].length));
4982                 if (retval == ERROR_OK)
4983                 {
4984                         retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
4985                 }
4986                 size += fastload[i].length;
4987         }
4988         int after = timeval_ms();
4989         command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
4990         return retval;
4991 }
4992
4993 static const struct command_registration target_command_handlers[] = {
4994         {
4995                 .name = "targets",
4996                 .handler = handle_targets_command,
4997                 .mode = COMMAND_ANY,
4998                 .help = "change current default target (one parameter) "
4999                         "or prints table of all targets (no parameters)",
5000                 .usage = "[target]",
5001         },
5002         {
5003                 .name = "target",
5004                 .mode = COMMAND_CONFIG,
5005                 .help = "configure target",
5006
5007                 .chain = target_subcommand_handlers,
5008         },
5009         COMMAND_REGISTRATION_DONE
5010 };
5011
5012 int target_register_commands(struct command_context *cmd_ctx)
5013 {
5014         return register_commands(cmd_ctx, NULL, target_command_handlers);
5015 }
5016
5017 static bool target_reset_nag = true;
5018
5019 bool get_target_reset_nag(void)
5020 {
5021         return target_reset_nag;
5022 }
5023
5024 COMMAND_HANDLER(handle_target_reset_nag)
5025 {
5026         return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5027                         &target_reset_nag, "Nag after each reset about options to improve "
5028                         "performance");
5029 }
5030
5031 static const struct command_registration target_exec_command_handlers[] = {
5032         {
5033                 .name = "fast_load_image",
5034                 .handler = handle_fast_load_image_command,
5035                 .mode = COMMAND_ANY,
5036                 .help = "Load image into server memory for later use by "
5037                         "fast_load; primarily for profiling",
5038                 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5039                         "[min_address [max_length]]",
5040         },
5041         {
5042                 .name = "fast_load",
5043                 .handler = handle_fast_load_command,
5044                 .mode = COMMAND_EXEC,
5045                 .help = "loads active fast load image to current target "
5046                         "- mainly for profiling purposes",
5047         },
5048         {
5049                 .name = "profile",
5050                 .handler = handle_profile_command,
5051                 .mode = COMMAND_EXEC,
5052                 .help = "profiling samples the CPU PC",
5053         },
5054         /** @todo don't register virt2phys() unless target supports it */
5055         {
5056                 .name = "virt2phys",
5057                 .handler = handle_virt2phys_command,
5058                 .mode = COMMAND_ANY,
5059                 .help = "translate a virtual address into a physical address",
5060                 .usage = "virtual_address",
5061         },
5062         {
5063                 .name = "reg",
5064                 .handler = handle_reg_command,
5065                 .mode = COMMAND_EXEC,
5066                 .help = "display or set a register; with no arguments, "
5067                         "displays all registers and their values",
5068                 .usage = "[(register_name|register_number) [value]]",
5069         },
5070         {
5071                 .name = "poll",
5072                 .handler = handle_poll_command,
5073                 .mode = COMMAND_EXEC,
5074                 .help = "poll target state; or reconfigure background polling",
5075                 .usage = "['on'|'off']",
5076         },
5077         {
5078                 .name = "wait_halt",
5079                 .handler = handle_wait_halt_command,
5080                 .mode = COMMAND_EXEC,
5081                 .help = "wait up to the specified number of milliseconds "
5082                         "(default 5) for a previously requested halt",
5083                 .usage = "[milliseconds]",
5084         },
5085         {
5086                 .name = "halt",
5087                 .handler = handle_halt_command,
5088                 .mode = COMMAND_EXEC,
5089                 .help = "request target to halt, then wait up to the specified"
5090                         "number of milliseconds (default 5) for it to complete",
5091                 .usage = "[milliseconds]",
5092         },
5093         {
5094                 .name = "resume",
5095                 .handler = handle_resume_command,
5096                 .mode = COMMAND_EXEC,
5097                 .help = "resume target execution from current PC or address",
5098                 .usage = "[address]",
5099         },
5100         {
5101                 .name = "reset",
5102                 .handler = handle_reset_command,
5103                 .mode = COMMAND_EXEC,
5104                 .usage = "[run|halt|init]",
5105                 .help = "Reset all targets into the specified mode."
5106                         "Default reset mode is run, if not given.",
5107         },
5108         {
5109                 .name = "soft_reset_halt",
5110                 .handler = handle_soft_reset_halt_command,
5111                 .mode = COMMAND_EXEC,
5112                 .help = "halt the target and do a soft reset",
5113         },
5114         {
5115                 .name = "step",
5116                 .handler = handle_step_command,
5117                 .mode = COMMAND_EXEC,
5118                 .help = "step one instruction from current PC or address",
5119                 .usage = "[address]",
5120         },
5121         {
5122                 .name = "mdw",
5123                 .handler = handle_md_command,
5124                 .mode = COMMAND_EXEC,
5125                 .help = "display memory words",
5126                 .usage = "['phys'] address [count]",
5127         },
5128         {
5129                 .name = "mdh",
5130                 .handler = handle_md_command,
5131                 .mode = COMMAND_EXEC,
5132                 .help = "display memory half-words",
5133                 .usage = "['phys'] address [count]",
5134         },
5135         {
5136                 .name = "mdb",
5137                 .handler = handle_md_command,
5138                 .mode = COMMAND_EXEC,
5139                 .help = "display memory bytes",
5140                 .usage = "['phys'] address [count]",
5141         },
5142         {
5143                 .name = "mww",
5144                 .handler = handle_mw_command,
5145                 .mode = COMMAND_EXEC,
5146                 .help = "write memory word",
5147                 .usage = "['phys'] address value [count]",
5148         },
5149         {
5150                 .name = "mwh",
5151                 .handler = handle_mw_command,
5152                 .mode = COMMAND_EXEC,
5153                 .help = "write memory half-word",
5154                 .usage = "['phys'] address value [count]",
5155         },
5156         {
5157                 .name = "mwb",
5158                 .handler = handle_mw_command,
5159                 .mode = COMMAND_EXEC,
5160                 .help = "write memory byte",
5161                 .usage = "['phys'] address value [count]",
5162         },
5163         {
5164                 .name = "bp",
5165                 .handler = handle_bp_command,
5166                 .mode = COMMAND_EXEC,
5167                 .help = "list or set hardware or software breakpoint",
5168                 .usage = "[address length ['hw']]",
5169         },
5170         {
5171                 .name = "rbp",
5172                 .handler = handle_rbp_command,
5173                 .mode = COMMAND_EXEC,
5174                 .help = "remove breakpoint",
5175                 .usage = "address",
5176         },
5177         {
5178                 .name = "wp",
5179                 .handler = handle_wp_command,
5180                 .mode = COMMAND_EXEC,
5181                 .help = "list (no params) or create watchpoints",
5182                 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5183         },
5184         {
5185                 .name = "rwp",
5186                 .handler = handle_rwp_command,
5187                 .mode = COMMAND_EXEC,
5188                 .help = "remove watchpoint",
5189                 .usage = "address",
5190         },
5191         {
5192                 .name = "load_image",
5193                 .handler = handle_load_image_command,
5194                 .mode = COMMAND_EXEC,
5195                 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5196                         "[min_address] [max_length]",
5197         },
5198         {
5199                 .name = "dump_image",
5200                 .handler = handle_dump_image_command,
5201                 .mode = COMMAND_EXEC,
5202                 .usage = "filename address size",
5203         },
5204         {
5205                 .name = "verify_image",
5206                 .handler = handle_verify_image_command,
5207                 .mode = COMMAND_EXEC,
5208                 .usage = "filename [offset [type]]",
5209         },
5210         {
5211                 .name = "test_image",
5212                 .handler = handle_test_image_command,
5213                 .mode = COMMAND_EXEC,
5214                 .usage = "filename [offset [type]]",
5215         },
5216         {
5217                 .name = "ocd_mem2array",
5218                 .mode = COMMAND_EXEC,
5219                 .jim_handler = jim_mem2array,
5220                 .help = "read 8/16/32 bit memory and return as a TCL array "
5221                         "for script processing",
5222                 .usage = "arrayname bitwidth address count",
5223         },
5224         {
5225                 .name = "ocd_array2mem",
5226                 .mode = COMMAND_EXEC,
5227                 .jim_handler = jim_array2mem,
5228                 .help = "convert a TCL array to memory locations "
5229                         "and write the 8/16/32 bit values",
5230                 .usage = "arrayname bitwidth address count",
5231         },
5232         {
5233                 .name = "reset_nag",
5234                 .handler = handle_target_reset_nag,
5235                 .mode = COMMAND_ANY,
5236                 .help = "Nag after each reset about options that could have been "
5237                                 "enabled to improve performance. ",
5238                 .usage = "['enable'|'disable']",
5239         },
5240         COMMAND_REGISTRATION_DONE
5241 };
5242 int target_register_user_commands(struct command_context *cmd_ctx)
5243 {
5244         int retval = ERROR_OK;
5245         if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
5246                 return retval;
5247
5248         if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
5249                 return retval;
5250
5251
5252         return register_commands(cmd_ctx, NULL, target_exec_command_handlers);
5253 }