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