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