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