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