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