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