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