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