target: fix halt and wait_halt timeout units
[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         }
2421
2422         struct target *target = get_current_target(CMD_CTX);
2423         return target_wait_state(target, TARGET_HALTED, ms);
2424 }
2425
2426 /* wait for target state to change. The trick here is to have a low
2427  * latency for short waits and not to suck up all the CPU time
2428  * on longer waits.
2429  *
2430  * After 500ms, keep_alive() is invoked
2431  */
2432 int target_wait_state(struct target *target, enum target_state state, int ms)
2433 {
2434         int retval;
2435         long long then = 0, cur;
2436         int once = 1;
2437
2438         for (;;) {
2439                 retval = target_poll(target);
2440                 if (retval != ERROR_OK)
2441                         return retval;
2442                 if (target->state == state)
2443                         break;
2444                 cur = timeval_ms();
2445                 if (once) {
2446                         once = 0;
2447                         then = timeval_ms();
2448                         LOG_DEBUG("waiting for target %s...",
2449                                 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2450                 }
2451
2452                 if (cur-then > 500)
2453                         keep_alive();
2454
2455                 if ((cur-then) > ms) {
2456                         LOG_ERROR("timed out while waiting for target %s",
2457                                 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2458                         return ERROR_FAIL;
2459                 }
2460         }
2461
2462         return ERROR_OK;
2463 }
2464
2465 COMMAND_HANDLER(handle_halt_command)
2466 {
2467         LOG_DEBUG("-");
2468
2469         struct target *target = get_current_target(CMD_CTX);
2470         int retval = target_halt(target);
2471         if (ERROR_OK != retval)
2472                 return retval;
2473
2474         if (CMD_ARGC == 1) {
2475                 unsigned wait_local;
2476                 retval = parse_uint(CMD_ARGV[0], &wait_local);
2477                 if (ERROR_OK != retval)
2478                         return ERROR_COMMAND_SYNTAX_ERROR;
2479                 if (!wait_local)
2480                         return ERROR_OK;
2481         }
2482
2483         return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2484 }
2485
2486 COMMAND_HANDLER(handle_soft_reset_halt_command)
2487 {
2488         struct target *target = get_current_target(CMD_CTX);
2489
2490         LOG_USER("requesting target halt and executing a soft reset");
2491
2492         target_soft_reset_halt(target);
2493
2494         return ERROR_OK;
2495 }
2496
2497 COMMAND_HANDLER(handle_reset_command)
2498 {
2499         if (CMD_ARGC > 1)
2500                 return ERROR_COMMAND_SYNTAX_ERROR;
2501
2502         enum target_reset_mode reset_mode = RESET_RUN;
2503         if (CMD_ARGC == 1) {
2504                 const Jim_Nvp *n;
2505                 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2506                 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2507                         return ERROR_COMMAND_SYNTAX_ERROR;
2508                 reset_mode = n->value;
2509         }
2510
2511         /* reset *all* targets */
2512         return target_process_reset(CMD_CTX, reset_mode);
2513 }
2514
2515
2516 COMMAND_HANDLER(handle_resume_command)
2517 {
2518         int current = 1;
2519         if (CMD_ARGC > 1)
2520                 return ERROR_COMMAND_SYNTAX_ERROR;
2521
2522         struct target *target = get_current_target(CMD_CTX);
2523
2524         /* with no CMD_ARGV, resume from current pc, addr = 0,
2525          * with one arguments, addr = CMD_ARGV[0],
2526          * handle breakpoints, not debugging */
2527         uint32_t addr = 0;
2528         if (CMD_ARGC == 1) {
2529                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2530                 current = 0;
2531         }
2532
2533         return target_resume(target, current, addr, 1, 0);
2534 }
2535
2536 COMMAND_HANDLER(handle_step_command)
2537 {
2538         if (CMD_ARGC > 1)
2539                 return ERROR_COMMAND_SYNTAX_ERROR;
2540
2541         LOG_DEBUG("-");
2542
2543         /* with no CMD_ARGV, step from current pc, addr = 0,
2544          * with one argument addr = CMD_ARGV[0],
2545          * handle breakpoints, debugging */
2546         uint32_t addr = 0;
2547         int current_pc = 1;
2548         if (CMD_ARGC == 1) {
2549                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2550                 current_pc = 0;
2551         }
2552
2553         struct target *target = get_current_target(CMD_CTX);
2554
2555         return target->type->step(target, current_pc, addr, 1);
2556 }
2557
2558 static void handle_md_output(struct command_context *cmd_ctx,
2559                 struct target *target, uint32_t address, unsigned size,
2560                 unsigned count, const uint8_t *buffer)
2561 {
2562         const unsigned line_bytecnt = 32;
2563         unsigned line_modulo = line_bytecnt / size;
2564
2565         char output[line_bytecnt * 4 + 1];
2566         unsigned output_len = 0;
2567
2568         const char *value_fmt;
2569         switch (size) {
2570         case 4:
2571                 value_fmt = "%8.8x ";
2572                 break;
2573         case 2:
2574                 value_fmt = "%4.4x ";
2575                 break;
2576         case 1:
2577                 value_fmt = "%2.2x ";
2578                 break;
2579         default:
2580                 /* "can't happen", caller checked */
2581                 LOG_ERROR("invalid memory read size: %u", size);
2582                 return;
2583         }
2584
2585         for (unsigned i = 0; i < count; i++) {
2586                 if (i % line_modulo == 0) {
2587                         output_len += snprintf(output + output_len,
2588                                         sizeof(output) - output_len,
2589                                         "0x%8.8x: ",
2590                                         (unsigned)(address + (i*size)));
2591                 }
2592
2593                 uint32_t value = 0;
2594                 const uint8_t *value_ptr = buffer + i * size;
2595                 switch (size) {
2596                 case 4:
2597                         value = target_buffer_get_u32(target, value_ptr);
2598                         break;
2599                 case 2:
2600                         value = target_buffer_get_u16(target, value_ptr);
2601                         break;
2602                 case 1:
2603                         value = *value_ptr;
2604                 }
2605                 output_len += snprintf(output + output_len,
2606                                 sizeof(output) - output_len,
2607                                 value_fmt, value);
2608
2609                 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2610                         command_print(cmd_ctx, "%s", output);
2611                         output_len = 0;
2612                 }
2613         }
2614 }
2615
2616 COMMAND_HANDLER(handle_md_command)
2617 {
2618         if (CMD_ARGC < 1)
2619                 return ERROR_COMMAND_SYNTAX_ERROR;
2620
2621         unsigned size = 0;
2622         switch (CMD_NAME[2]) {
2623         case 'w':
2624                 size = 4;
2625                 break;
2626         case 'h':
2627                 size = 2;
2628                 break;
2629         case 'b':
2630                 size = 1;
2631                 break;
2632         default:
2633                 return ERROR_COMMAND_SYNTAX_ERROR;
2634         }
2635
2636         bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2637         int (*fn)(struct target *target,
2638                         uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2639         if (physical) {
2640                 CMD_ARGC--;
2641                 CMD_ARGV++;
2642                 fn = target_read_phys_memory;
2643         } else
2644                 fn = target_read_memory;
2645         if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2646                 return ERROR_COMMAND_SYNTAX_ERROR;
2647
2648         uint32_t address;
2649         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2650
2651         unsigned count = 1;
2652         if (CMD_ARGC == 2)
2653                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2654
2655         uint8_t *buffer = calloc(count, size);
2656
2657         struct target *target = get_current_target(CMD_CTX);
2658         int retval = fn(target, address, size, count, buffer);
2659         if (ERROR_OK == retval)
2660                 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2661
2662         free(buffer);
2663
2664         return retval;
2665 }
2666
2667 typedef int (*target_write_fn)(struct target *target,
2668                 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2669
2670 static int target_write_memory_fast(struct target *target,
2671                 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
2672 {
2673         return target_write_buffer(target, address, size * count, buffer);
2674 }
2675
2676 static int target_fill_mem(struct target *target,
2677                 uint32_t address,
2678                 target_write_fn fn,
2679                 unsigned data_size,
2680                 /* value */
2681                 uint32_t b,
2682                 /* count */
2683                 unsigned c)
2684 {
2685         /* We have to write in reasonably large chunks to be able
2686          * to fill large memory areas with any sane speed */
2687         const unsigned chunk_size = 16384;
2688         uint8_t *target_buf = malloc(chunk_size * data_size);
2689         if (target_buf == NULL) {
2690                 LOG_ERROR("Out of memory");
2691                 return ERROR_FAIL;
2692         }
2693
2694         for (unsigned i = 0; i < chunk_size; i++) {
2695                 switch (data_size) {
2696                 case 4:
2697                         target_buffer_set_u32(target, target_buf + i * data_size, b);
2698                         break;
2699                 case 2:
2700                         target_buffer_set_u16(target, target_buf + i * data_size, b);
2701                         break;
2702                 case 1:
2703                         target_buffer_set_u8(target, target_buf + i * data_size, b);
2704                         break;
2705                 default:
2706                         exit(-1);
2707                 }
2708         }
2709
2710         int retval = ERROR_OK;
2711
2712         for (unsigned x = 0; x < c; x += chunk_size) {
2713                 unsigned current;
2714                 current = c - x;
2715                 if (current > chunk_size)
2716                         current = chunk_size;
2717                 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2718                 if (retval != ERROR_OK)
2719                         break;
2720                 /* avoid GDB timeouts */
2721                 keep_alive();
2722         }
2723         free(target_buf);
2724
2725         return retval;
2726 }
2727
2728
2729 COMMAND_HANDLER(handle_mw_command)
2730 {
2731         if (CMD_ARGC < 2)
2732                 return ERROR_COMMAND_SYNTAX_ERROR;
2733         bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2734         target_write_fn fn;
2735         if (physical) {
2736                 CMD_ARGC--;
2737                 CMD_ARGV++;
2738                 fn = target_write_phys_memory;
2739         } else
2740                 fn = target_write_memory_fast;
2741         if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2742                 return ERROR_COMMAND_SYNTAX_ERROR;
2743
2744         uint32_t address;
2745         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2746
2747         uint32_t value;
2748         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2749
2750         unsigned count = 1;
2751         if (CMD_ARGC == 3)
2752                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2753
2754         struct target *target = get_current_target(CMD_CTX);
2755         unsigned wordsize;
2756         switch (CMD_NAME[2]) {
2757                 case 'w':
2758                         wordsize = 4;
2759                         break;
2760                 case 'h':
2761                         wordsize = 2;
2762                         break;
2763                 case 'b':
2764                         wordsize = 1;
2765                         break;
2766                 default:
2767                         return ERROR_COMMAND_SYNTAX_ERROR;
2768         }
2769
2770         return target_fill_mem(target, address, fn, wordsize, value, count);
2771 }
2772
2773 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2774                 uint32_t *min_address, uint32_t *max_address)
2775 {
2776         if (CMD_ARGC < 1 || CMD_ARGC > 5)
2777                 return ERROR_COMMAND_SYNTAX_ERROR;
2778
2779         /* a base address isn't always necessary,
2780          * default to 0x0 (i.e. don't relocate) */
2781         if (CMD_ARGC >= 2) {
2782                 uint32_t addr;
2783                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2784                 image->base_address = addr;
2785                 image->base_address_set = 1;
2786         } else
2787                 image->base_address_set = 0;
2788
2789         image->start_address_set = 0;
2790
2791         if (CMD_ARGC >= 4)
2792                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2793         if (CMD_ARGC == 5) {
2794                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2795                 /* use size (given) to find max (required) */
2796                 *max_address += *min_address;
2797         }
2798
2799         if (*min_address > *max_address)
2800                 return ERROR_COMMAND_SYNTAX_ERROR;
2801
2802         return ERROR_OK;
2803 }
2804
2805 COMMAND_HANDLER(handle_load_image_command)
2806 {
2807         uint8_t *buffer;
2808         size_t buf_cnt;
2809         uint32_t image_size;
2810         uint32_t min_address = 0;
2811         uint32_t max_address = 0xffffffff;
2812         int i;
2813         struct image image;
2814
2815         int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2816                         &image, &min_address, &max_address);
2817         if (ERROR_OK != retval)
2818                 return retval;
2819
2820         struct target *target = get_current_target(CMD_CTX);
2821
2822         struct duration bench;
2823         duration_start(&bench);
2824
2825         if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2826                 return ERROR_OK;
2827
2828         image_size = 0x0;
2829         retval = ERROR_OK;
2830         for (i = 0; i < image.num_sections; i++) {
2831                 buffer = malloc(image.sections[i].size);
2832                 if (buffer == NULL) {
2833                         command_print(CMD_CTX,
2834                                                   "error allocating buffer for section (%d bytes)",
2835                                                   (int)(image.sections[i].size));
2836                         break;
2837                 }
2838
2839                 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
2840                 if (retval != ERROR_OK) {
2841                         free(buffer);
2842                         break;
2843                 }
2844
2845                 uint32_t offset = 0;
2846                 uint32_t length = buf_cnt;
2847
2848                 /* DANGER!!! beware of unsigned comparision here!!! */
2849
2850                 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
2851                                 (image.sections[i].base_address < max_address)) {
2852
2853                         if (image.sections[i].base_address < min_address) {
2854                                 /* clip addresses below */
2855                                 offset += min_address-image.sections[i].base_address;
2856                                 length -= offset;
2857                         }
2858
2859                         if (image.sections[i].base_address + buf_cnt > max_address)
2860                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2861
2862                         retval = target_write_buffer(target,
2863                                         image.sections[i].base_address + offset, length, buffer + offset);
2864                         if (retval != ERROR_OK) {
2865                                 free(buffer);
2866                                 break;
2867                         }
2868                         image_size += length;
2869                         command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2870                                         (unsigned int)length,
2871                                         image.sections[i].base_address + offset);
2872                 }
2873
2874                 free(buffer);
2875         }
2876
2877         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
2878                 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2879                                 "in %fs (%0.3f KiB/s)", image_size,
2880                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2881         }
2882
2883         image_close(&image);
2884
2885         return retval;
2886
2887 }
2888
2889 COMMAND_HANDLER(handle_dump_image_command)
2890 {
2891         struct fileio fileio;
2892         uint8_t *buffer;
2893         int retval, retvaltemp;
2894         uint32_t address, size;
2895         struct duration bench;
2896         struct target *target = get_current_target(CMD_CTX);
2897
2898         if (CMD_ARGC != 3)
2899                 return ERROR_COMMAND_SYNTAX_ERROR;
2900
2901         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2902         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2903
2904         uint32_t buf_size = (size > 4096) ? 4096 : size;
2905         buffer = malloc(buf_size);
2906         if (!buffer)
2907                 return ERROR_FAIL;
2908
2909         retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2910         if (retval != ERROR_OK) {
2911                 free(buffer);
2912                 return retval;
2913         }
2914
2915         duration_start(&bench);
2916
2917         while (size > 0) {
2918                 size_t size_written;
2919                 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
2920                 retval = target_read_buffer(target, address, this_run_size, buffer);
2921                 if (retval != ERROR_OK)
2922                         break;
2923
2924                 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2925                 if (retval != ERROR_OK)
2926                         break;
2927
2928                 size -= this_run_size;
2929                 address += this_run_size;
2930         }
2931
2932         free(buffer);
2933
2934         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
2935                 int filesize;
2936                 retval = fileio_size(&fileio, &filesize);
2937                 if (retval != ERROR_OK)
2938                         return retval;
2939                 command_print(CMD_CTX,
2940                                 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
2941                                 duration_elapsed(&bench), duration_kbps(&bench, filesize));
2942         }
2943
2944         retvaltemp = fileio_close(&fileio);
2945         if (retvaltemp != ERROR_OK)
2946                 return retvaltemp;
2947
2948         return retval;
2949 }
2950
2951 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2952 {
2953         uint8_t *buffer;
2954         size_t buf_cnt;
2955         uint32_t image_size;
2956         int i;
2957         int retval;
2958         uint32_t checksum = 0;
2959         uint32_t mem_checksum = 0;
2960
2961         struct image image;
2962
2963         struct target *target = get_current_target(CMD_CTX);
2964
2965         if (CMD_ARGC < 1)
2966                 return ERROR_COMMAND_SYNTAX_ERROR;
2967
2968         if (!target) {
2969                 LOG_ERROR("no target selected");
2970                 return ERROR_FAIL;
2971         }
2972
2973         struct duration bench;
2974         duration_start(&bench);
2975
2976         if (CMD_ARGC >= 2) {
2977                 uint32_t addr;
2978                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2979                 image.base_address = addr;
2980                 image.base_address_set = 1;
2981         } else {
2982                 image.base_address_set = 0;
2983                 image.base_address = 0x0;
2984         }
2985
2986         image.start_address_set = 0;
2987
2988         retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
2989         if (retval != ERROR_OK)
2990                 return retval;
2991
2992         image_size = 0x0;
2993         int diffs = 0;
2994         retval = ERROR_OK;
2995         for (i = 0; i < image.num_sections; i++) {
2996                 buffer = malloc(image.sections[i].size);
2997                 if (buffer == NULL) {
2998                         command_print(CMD_CTX,
2999                                         "error allocating buffer for section (%d bytes)",
3000                                         (int)(image.sections[i].size));
3001                         break;
3002                 }
3003                 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3004                 if (retval != ERROR_OK) {
3005                         free(buffer);
3006                         break;
3007                 }
3008
3009                 if (verify) {
3010                         /* calculate checksum of image */
3011                         retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3012                         if (retval != ERROR_OK) {
3013                                 free(buffer);
3014                                 break;
3015                         }
3016
3017                         retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3018                         if (retval != ERROR_OK) {
3019                                 free(buffer);
3020                                 break;
3021                         }
3022
3023                         if (checksum != mem_checksum) {
3024                                 /* failed crc checksum, fall back to a binary compare */
3025                                 uint8_t *data;
3026
3027                                 if (diffs == 0)
3028                                         LOG_ERROR("checksum mismatch - attempting binary compare");
3029
3030                                 data = (uint8_t *)malloc(buf_cnt);
3031
3032                                 /* Can we use 32bit word accesses? */
3033                                 int size = 1;
3034                                 int count = buf_cnt;
3035                                 if ((count % 4) == 0) {
3036                                         size *= 4;
3037                                         count /= 4;
3038                                 }
3039                                 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3040                                 if (retval == ERROR_OK) {
3041                                         uint32_t t;
3042                                         for (t = 0; t < buf_cnt; t++) {
3043                                                 if (data[t] != buffer[t]) {
3044                                                         command_print(CMD_CTX,
3045                                                                                   "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3046                                                                                   diffs,
3047                                                                                   (unsigned)(t + image.sections[i].base_address),
3048                                                                                   data[t],
3049                                                                                   buffer[t]);
3050                                                         if (diffs++ >= 127) {
3051                                                                 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3052                                                                 free(data);
3053                                                                 free(buffer);
3054                                                                 goto done;
3055                                                         }
3056                                                 }
3057                                                 keep_alive();
3058                                         }
3059                                 }
3060                                 free(data);
3061                         }
3062                 } else {
3063                         command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3064                                                   image.sections[i].base_address,
3065                                                   buf_cnt);
3066                 }
3067
3068                 free(buffer);
3069                 image_size += buf_cnt;
3070         }
3071         if (diffs > 0)
3072                 command_print(CMD_CTX, "No more differences found.");
3073 done:
3074         if (diffs > 0)
3075                 retval = ERROR_FAIL;
3076         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3077                 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3078                                 "in %fs (%0.3f KiB/s)", image_size,
3079                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3080         }
3081
3082         image_close(&image);
3083
3084         return retval;
3085 }
3086
3087 COMMAND_HANDLER(handle_verify_image_command)
3088 {
3089         return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3090 }
3091
3092 COMMAND_HANDLER(handle_test_image_command)
3093 {
3094         return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3095 }
3096
3097 static int handle_bp_command_list(struct command_context *cmd_ctx)
3098 {
3099         struct target *target = get_current_target(cmd_ctx);
3100         struct breakpoint *breakpoint = target->breakpoints;
3101         while (breakpoint) {
3102                 if (breakpoint->type == BKPT_SOFT) {
3103                         char *buf = buf_to_str(breakpoint->orig_instr,
3104                                         breakpoint->length, 16);
3105                         command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3106                                         breakpoint->address,
3107                                         breakpoint->length,
3108                                         breakpoint->set, buf);
3109                         free(buf);
3110                 } else {
3111                         if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3112                                 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3113                                                         breakpoint->asid,
3114                                                         breakpoint->length, breakpoint->set);
3115                         else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3116                                 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3117                                                         breakpoint->address,
3118                                                         breakpoint->length, breakpoint->set);
3119                                 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3120                                                         breakpoint->asid);
3121                         } else
3122                                 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3123                                                         breakpoint->address,
3124                                                         breakpoint->length, breakpoint->set);
3125                 }
3126
3127                 breakpoint = breakpoint->next;
3128         }
3129         return ERROR_OK;
3130 }
3131
3132 static int handle_bp_command_set(struct command_context *cmd_ctx,
3133                 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3134 {
3135         struct target *target = get_current_target(cmd_ctx);
3136
3137         if (asid == 0) {
3138                 int retval = breakpoint_add(target, addr, length, hw);
3139                 if (ERROR_OK == retval)
3140                         command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3141                 else {
3142                         LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3143                         return retval;
3144                 }
3145         } else if (addr == 0) {
3146                 int retval = context_breakpoint_add(target, asid, length, hw);
3147                 if (ERROR_OK == retval)
3148                         command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3149                 else {
3150                         LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3151                         return retval;
3152                 }
3153         } else {
3154                 int retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3155                 if (ERROR_OK == retval)
3156                         command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3157                 else {
3158                         LOG_ERROR("Failure setting breakpoint, the same address is already used");
3159                         return retval;
3160                 }
3161         }
3162         return ERROR_OK;
3163 }
3164
3165 COMMAND_HANDLER(handle_bp_command)
3166 {
3167         uint32_t addr;
3168         uint32_t asid;
3169         uint32_t length;
3170         int hw = BKPT_SOFT;
3171
3172         switch (CMD_ARGC) {
3173                 case 0:
3174                         return handle_bp_command_list(CMD_CTX);
3175
3176                 case 2:
3177                         asid = 0;
3178                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3179                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3180                         return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3181
3182                 case 3:
3183                         if (strcmp(CMD_ARGV[2], "hw") == 0) {
3184                                 hw = BKPT_HARD;
3185                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3186
3187                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3188
3189                                 asid = 0;
3190                                 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3191                         } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3192                                 hw = BKPT_HARD;
3193                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3194                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3195                                 addr = 0;
3196                                 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3197                         }
3198
3199                 case 4:
3200                         hw = BKPT_HARD;
3201                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3202                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3203                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3204                         return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3205
3206                 default:
3207                         return ERROR_COMMAND_SYNTAX_ERROR;
3208         }
3209 }
3210
3211 COMMAND_HANDLER(handle_rbp_command)
3212 {
3213         if (CMD_ARGC != 1)
3214                 return ERROR_COMMAND_SYNTAX_ERROR;
3215
3216         uint32_t addr;
3217         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3218
3219         struct target *target = get_current_target(CMD_CTX);
3220         breakpoint_remove(target, addr);
3221
3222         return ERROR_OK;
3223 }
3224
3225 COMMAND_HANDLER(handle_wp_command)
3226 {
3227         struct target *target = get_current_target(CMD_CTX);
3228
3229         if (CMD_ARGC == 0) {
3230                 struct watchpoint *watchpoint = target->watchpoints;
3231
3232                 while (watchpoint) {
3233                         command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3234                                         ", len: 0x%8.8" PRIx32
3235                                         ", r/w/a: %i, value: 0x%8.8" PRIx32
3236                                         ", mask: 0x%8.8" PRIx32,
3237                                         watchpoint->address,
3238                                         watchpoint->length,
3239                                         (int)watchpoint->rw,
3240                                         watchpoint->value,
3241                                         watchpoint->mask);
3242                         watchpoint = watchpoint->next;
3243                 }
3244                 return ERROR_OK;
3245         }
3246
3247         enum watchpoint_rw type = WPT_ACCESS;
3248         uint32_t addr = 0;
3249         uint32_t length = 0;
3250         uint32_t data_value = 0x0;
3251         uint32_t data_mask = 0xffffffff;
3252
3253         switch (CMD_ARGC) {
3254         case 5:
3255                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3256                 /* fall through */
3257         case 4:
3258                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3259                 /* fall through */
3260         case 3:
3261                 switch (CMD_ARGV[2][0]) {
3262                 case 'r':
3263                         type = WPT_READ;
3264                         break;
3265                 case 'w':
3266                         type = WPT_WRITE;
3267                         break;
3268                 case 'a':
3269                         type = WPT_ACCESS;
3270                         break;
3271                 default:
3272                         LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3273                         return ERROR_COMMAND_SYNTAX_ERROR;
3274                 }
3275                 /* fall through */
3276         case 2:
3277                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3278                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3279                 break;
3280
3281         default:
3282                 return ERROR_COMMAND_SYNTAX_ERROR;
3283         }
3284
3285         int retval = watchpoint_add(target, addr, length, type,
3286                         data_value, data_mask);
3287         if (ERROR_OK != retval)
3288                 LOG_ERROR("Failure setting watchpoints");
3289
3290         return retval;
3291 }
3292
3293 COMMAND_HANDLER(handle_rwp_command)
3294 {
3295         if (CMD_ARGC != 1)
3296                 return ERROR_COMMAND_SYNTAX_ERROR;
3297
3298         uint32_t addr;
3299         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3300
3301         struct target *target = get_current_target(CMD_CTX);
3302         watchpoint_remove(target, addr);
3303
3304         return ERROR_OK;
3305 }
3306
3307 /**
3308  * Translate a virtual address to a physical address.
3309  *
3310  * The low-level target implementation must have logged a detailed error
3311  * which is forwarded to telnet/GDB session.
3312  */
3313 COMMAND_HANDLER(handle_virt2phys_command)
3314 {
3315         if (CMD_ARGC != 1)
3316                 return ERROR_COMMAND_SYNTAX_ERROR;
3317
3318         uint32_t va;
3319         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3320         uint32_t pa;
3321
3322         struct target *target = get_current_target(CMD_CTX);
3323         int retval = target->type->virt2phys(target, va, &pa);
3324         if (retval == ERROR_OK)
3325                 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3326
3327         return retval;
3328 }
3329
3330 static void writeData(FILE *f, const void *data, size_t len)
3331 {
3332         size_t written = fwrite(data, 1, len, f);
3333         if (written != len)
3334                 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3335 }
3336
3337 static void writeLong(FILE *f, int l)
3338 {
3339         int i;
3340         for (i = 0; i < 4; i++) {
3341                 char c = (l >> (i*8))&0xff;
3342                 writeData(f, &c, 1);
3343         }
3344
3345 }
3346
3347 static void writeString(FILE *f, char *s)
3348 {
3349         writeData(f, s, strlen(s));
3350 }
3351
3352 /* Dump a gmon.out histogram file. */
3353 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3354 {
3355         uint32_t i;
3356         FILE *f = fopen(filename, "w");
3357         if (f == NULL)
3358                 return;
3359         writeString(f, "gmon");
3360         writeLong(f, 0x00000001); /* Version */
3361         writeLong(f, 0); /* padding */
3362         writeLong(f, 0); /* padding */
3363         writeLong(f, 0); /* padding */
3364
3365         uint8_t zero = 0;  /* GMON_TAG_TIME_HIST */
3366         writeData(f, &zero, 1);
3367
3368         /* figure out bucket size */
3369         uint32_t min = samples[0];
3370         uint32_t max = samples[0];
3371         for (i = 0; i < sampleNum; i++) {
3372                 if (min > samples[i])
3373                         min = samples[i];
3374                 if (max < samples[i])
3375                         max = samples[i];
3376         }
3377
3378         int addressSpace = (max - min + 1);
3379         assert(addressSpace >= 2);
3380
3381         static const uint32_t maxBuckets = 16 * 1024; /* maximum buckets. */
3382         uint32_t length = addressSpace;
3383         if (length > maxBuckets)
3384                 length = maxBuckets;
3385         int *buckets = malloc(sizeof(int)*length);
3386         if (buckets == NULL) {
3387                 fclose(f);
3388                 return;
3389         }
3390         memset(buckets, 0, sizeof(int) * length);
3391         for (i = 0; i < sampleNum; i++) {
3392                 uint32_t address = samples[i];
3393                 long long a = address - min;
3394                 long long b = length - 1;
3395                 long long c = addressSpace - 1;
3396                 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3397                 buckets[index_t]++;
3398         }
3399
3400         /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3401         writeLong(f, min);                      /* low_pc */
3402         writeLong(f, max);                      /* high_pc */
3403         writeLong(f, length);           /* # of samples */
3404         writeLong(f, 100);                      /* KLUDGE! We lie, ca. 100Hz best case. */
3405         writeString(f, "seconds");
3406         for (i = 0; i < (15-strlen("seconds")); i++)
3407                 writeData(f, &zero, 1);
3408         writeString(f, "s");
3409
3410         /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3411
3412         char *data = malloc(2 * length);
3413         if (data != NULL) {
3414                 for (i = 0; i < length; i++) {
3415                         int val;
3416                         val = buckets[i];
3417                         if (val > 65535)
3418                                 val = 65535;
3419                         data[i * 2] = val&0xff;
3420                         data[i * 2 + 1] = (val >> 8) & 0xff;
3421                 }
3422                 free(buckets);
3423                 writeData(f, data, length * 2);
3424                 free(data);
3425         } else
3426                 free(buckets);
3427
3428         fclose(f);
3429 }
3430
3431 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3432  * which will be used as a random sampling of PC */
3433 COMMAND_HANDLER(handle_profile_command)
3434 {
3435         struct target *target = get_current_target(CMD_CTX);
3436         struct timeval timeout, now;
3437
3438         gettimeofday(&timeout, NULL);
3439         if (CMD_ARGC != 2)
3440                 return ERROR_COMMAND_SYNTAX_ERROR;
3441         unsigned offset;
3442         COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3443
3444         timeval_add_time(&timeout, offset, 0);
3445
3446         /**
3447          * @todo: Some cores let us sample the PC without the
3448          * annoying halt/resume step; for example, ARMv7 PCSR.
3449          * Provide a way to use that more efficient mechanism.
3450          */
3451
3452         command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3453
3454         static const int maxSample = 10000;
3455         uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3456         if (samples == NULL)
3457                 return ERROR_OK;
3458
3459         int numSamples = 0;
3460         /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3461         struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3462
3463         int retval = ERROR_OK;
3464         for (;;) {
3465                 target_poll(target);
3466                 if (target->state == TARGET_HALTED) {
3467                         uint32_t t = *((uint32_t *)reg->value);
3468                         samples[numSamples++] = t;
3469                         /* current pc, addr = 0, do not handle breakpoints, not debugging */
3470                         retval = target_resume(target, 1, 0, 0, 0);
3471                         target_poll(target);
3472                         alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3473                 } else if (target->state == TARGET_RUNNING) {
3474                         /* We want to quickly sample the PC. */
3475                         retval = target_halt(target);
3476                         if (retval != ERROR_OK) {
3477                                 free(samples);
3478                                 return retval;
3479                         }
3480                 } else {
3481                         command_print(CMD_CTX, "Target not halted or running");
3482                         retval = ERROR_OK;
3483                         break;
3484                 }
3485                 if (retval != ERROR_OK)
3486                         break;
3487
3488                 gettimeofday(&now, NULL);
3489                 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec)
3490                                 && (now.tv_usec >= timeout.tv_usec))) {
3491                         command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3492                         retval = target_poll(target);
3493                         if (retval != ERROR_OK) {
3494                                 free(samples);
3495                                 return retval;
3496                         }
3497                         if (target->state == TARGET_HALTED) {
3498                                 /* current pc, addr = 0, do not handle
3499                                  * breakpoints, not debugging */
3500                                 target_resume(target, 1, 0, 0, 0);
3501                         }
3502                         retval = target_poll(target);
3503                         if (retval != ERROR_OK) {
3504                                 free(samples);
3505                                 return retval;
3506                         }
3507                         writeGmon(samples, numSamples, CMD_ARGV[1]);
3508                         command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3509                         break;
3510                 }
3511         }
3512         free(samples);
3513
3514         return retval;
3515 }
3516
3517 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3518 {
3519         char *namebuf;
3520         Jim_Obj *nameObjPtr, *valObjPtr;
3521         int result;
3522
3523         namebuf = alloc_printf("%s(%d)", varname, idx);
3524         if (!namebuf)
3525                 return JIM_ERR;
3526
3527         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3528         valObjPtr = Jim_NewIntObj(interp, val);
3529         if (!nameObjPtr || !valObjPtr) {
3530                 free(namebuf);
3531                 return JIM_ERR;
3532         }
3533
3534         Jim_IncrRefCount(nameObjPtr);
3535         Jim_IncrRefCount(valObjPtr);
3536         result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3537         Jim_DecrRefCount(interp, nameObjPtr);
3538         Jim_DecrRefCount(interp, valObjPtr);
3539         free(namebuf);
3540         /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3541         return result;
3542 }
3543
3544 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3545 {
3546         struct command_context *context;
3547         struct target *target;
3548
3549         context = current_command_context(interp);
3550         assert(context != NULL);
3551
3552         target = get_current_target(context);
3553         if (target == NULL) {
3554                 LOG_ERROR("mem2array: no current target");
3555                 return JIM_ERR;
3556         }
3557
3558         return target_mem2array(interp, target, argc - 1, argv + 1);
3559 }
3560
3561 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3562 {
3563         long l;
3564         uint32_t width;
3565         int len;
3566         uint32_t addr;
3567         uint32_t count;
3568         uint32_t v;
3569         const char *varname;
3570         int  n, e, retval;
3571         uint32_t i;
3572
3573         /* argv[1] = name of array to receive the data
3574          * argv[2] = desired width
3575          * argv[3] = memory address
3576          * argv[4] = count of times to read
3577          */
3578         if (argc != 4) {
3579                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3580                 return JIM_ERR;
3581         }
3582         varname = Jim_GetString(argv[0], &len);
3583         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3584
3585         e = Jim_GetLong(interp, argv[1], &l);
3586         width = l;
3587         if (e != JIM_OK)
3588                 return e;
3589
3590         e = Jim_GetLong(interp, argv[2], &l);
3591         addr = l;
3592         if (e != JIM_OK)
3593                 return e;
3594         e = Jim_GetLong(interp, argv[3], &l);
3595         len = l;
3596         if (e != JIM_OK)
3597                 return e;
3598         switch (width) {
3599                 case 8:
3600                         width = 1;
3601                         break;
3602                 case 16:
3603                         width = 2;
3604                         break;
3605                 case 32:
3606                         width = 4;
3607                         break;
3608                 default:
3609                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3610                         Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3611                         return JIM_ERR;
3612         }
3613         if (len == 0) {
3614                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3615                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3616                 return JIM_ERR;
3617         }
3618         if ((addr + (len * width)) < addr) {
3619                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3620                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3621                 return JIM_ERR;
3622         }
3623         /* absurd transfer size? */
3624         if (len > 65536) {
3625                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3626                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3627                 return JIM_ERR;
3628         }
3629
3630         if ((width == 1) ||
3631                 ((width == 2) && ((addr & 1) == 0)) ||
3632                 ((width == 4) && ((addr & 3) == 0))) {
3633                 /* all is well */
3634         } else {
3635                 char buf[100];
3636                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3637                 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3638                                 addr,
3639                                 width);
3640                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3641                 return JIM_ERR;
3642         }
3643
3644         /* Transfer loop */
3645
3646         /* index counter */
3647         n = 0;
3648
3649         size_t buffersize = 4096;
3650         uint8_t *buffer = malloc(buffersize);
3651         if (buffer == NULL)
3652                 return JIM_ERR;
3653
3654         /* assume ok */
3655         e = JIM_OK;
3656         while (len) {
3657                 /* Slurp... in buffer size chunks */
3658
3659                 count = len; /* in objects.. */
3660                 if (count > (buffersize / width))
3661                         count = (buffersize / width);
3662
3663                 retval = target_read_memory(target, addr, width, count, buffer);
3664                 if (retval != ERROR_OK) {
3665                         /* BOO !*/
3666                         LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3667                                           (unsigned int)addr,
3668                                           (int)width,
3669                                           (int)count);
3670                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3671                         Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3672                         e = JIM_ERR;
3673                         break;
3674                 } else {
3675                         v = 0; /* shut up gcc */
3676                         for (i = 0; i < count ; i++, n++) {
3677                                 switch (width) {
3678                                         case 4:
3679                                                 v = target_buffer_get_u32(target, &buffer[i*width]);
3680                                                 break;
3681                                         case 2:
3682                                                 v = target_buffer_get_u16(target, &buffer[i*width]);
3683                                                 break;
3684                                         case 1:
3685                                                 v = buffer[i] & 0x0ff;
3686                                                 break;
3687                                 }
3688                                 new_int_array_element(interp, varname, n, v);
3689                         }
3690                         len -= count;
3691                 }
3692         }
3693
3694         free(buffer);
3695
3696         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3697
3698         return e;
3699 }
3700
3701 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
3702 {
3703         char *namebuf;
3704         Jim_Obj *nameObjPtr, *valObjPtr;
3705         int result;
3706         long l;
3707
3708         namebuf = alloc_printf("%s(%d)", varname, idx);
3709         if (!namebuf)
3710                 return JIM_ERR;
3711
3712         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3713         if (!nameObjPtr) {
3714                 free(namebuf);
3715                 return JIM_ERR;
3716         }
3717
3718         Jim_IncrRefCount(nameObjPtr);
3719         valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3720         Jim_DecrRefCount(interp, nameObjPtr);
3721         free(namebuf);
3722         if (valObjPtr == NULL)
3723                 return JIM_ERR;
3724
3725         result = Jim_GetLong(interp, valObjPtr, &l);
3726         /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3727         *val = l;
3728         return result;
3729 }
3730
3731 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3732 {
3733         struct command_context *context;
3734         struct target *target;
3735
3736         context = current_command_context(interp);
3737         assert(context != NULL);
3738
3739         target = get_current_target(context);
3740         if (target == NULL) {
3741                 LOG_ERROR("array2mem: no current target");
3742                 return JIM_ERR;
3743         }
3744
3745         return target_array2mem(interp, target, argc-1, argv + 1);
3746 }
3747
3748 static int target_array2mem(Jim_Interp *interp, struct target *target,
3749                 int argc, Jim_Obj *const *argv)
3750 {
3751         long l;
3752         uint32_t width;
3753         int len;
3754         uint32_t addr;
3755         uint32_t count;
3756         uint32_t v;
3757         const char *varname;
3758         int  n, e, retval;
3759         uint32_t i;
3760
3761         /* argv[1] = name of array to get the data
3762          * argv[2] = desired width
3763          * argv[3] = memory address
3764          * argv[4] = count to write
3765          */
3766         if (argc != 4) {
3767                 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3768                 return JIM_ERR;
3769         }
3770         varname = Jim_GetString(argv[0], &len);
3771         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3772
3773         e = Jim_GetLong(interp, argv[1], &l);
3774         width = l;
3775         if (e != JIM_OK)
3776                 return e;
3777
3778         e = Jim_GetLong(interp, argv[2], &l);
3779         addr = l;
3780         if (e != JIM_OK)
3781                 return e;
3782         e = Jim_GetLong(interp, argv[3], &l);
3783         len = l;
3784         if (e != JIM_OK)
3785                 return e;
3786         switch (width) {
3787                 case 8:
3788                         width = 1;
3789                         break;
3790                 case 16:
3791                         width = 2;
3792                         break;
3793                 case 32:
3794                         width = 4;
3795                         break;
3796                 default:
3797                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3798                         Jim_AppendStrings(interp, Jim_GetResult(interp),
3799                                         "Invalid width param, must be 8/16/32", NULL);
3800                         return JIM_ERR;
3801         }
3802         if (len == 0) {
3803                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3804                 Jim_AppendStrings(interp, Jim_GetResult(interp),
3805                                 "array2mem: zero width read?", NULL);
3806                 return JIM_ERR;
3807         }
3808         if ((addr + (len * width)) < addr) {
3809                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3810                 Jim_AppendStrings(interp, Jim_GetResult(interp),
3811                                 "array2mem: addr + len - wraps to zero?", NULL);
3812                 return JIM_ERR;
3813         }
3814         /* absurd transfer size? */
3815         if (len > 65536) {
3816                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3817                 Jim_AppendStrings(interp, Jim_GetResult(interp),
3818                                 "array2mem: absurd > 64K item request", NULL);
3819                 return JIM_ERR;
3820         }
3821
3822         if ((width == 1) ||
3823                 ((width == 2) && ((addr & 1) == 0)) ||
3824                 ((width == 4) && ((addr & 3) == 0))) {
3825                 /* all is well */
3826         } else {
3827                 char buf[100];
3828                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3829                 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3830                                 (unsigned int)addr,
3831                                 (int)width);
3832                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3833                 return JIM_ERR;
3834         }
3835
3836         /* Transfer loop */
3837
3838         /* index counter */
3839         n = 0;
3840         /* assume ok */
3841         e = JIM_OK;
3842
3843         size_t buffersize = 4096;
3844         uint8_t *buffer = malloc(buffersize);
3845         if (buffer == NULL)
3846                 return JIM_ERR;
3847
3848         while (len) {
3849                 /* Slurp... in buffer size chunks */
3850
3851                 count = len; /* in objects.. */
3852                 if (count > (buffersize / width))
3853                         count = (buffersize / width);
3854
3855                 v = 0; /* shut up gcc */
3856                 for (i = 0; i < count; i++, n++) {
3857                         get_int_array_element(interp, varname, n, &v);
3858                         switch (width) {
3859                         case 4:
3860                                 target_buffer_set_u32(target, &buffer[i * width], v);
3861                                 break;
3862                         case 2:
3863                                 target_buffer_set_u16(target, &buffer[i * width], v);
3864                                 break;
3865                         case 1:
3866                                 buffer[i] = v & 0x0ff;
3867                                 break;
3868                         }
3869                 }
3870                 len -= count;
3871
3872                 retval = target_write_memory(target, addr, width, count, buffer);
3873                 if (retval != ERROR_OK) {
3874                         /* BOO !*/
3875                         LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3876                                           (unsigned int)addr,
3877                                           (int)width,
3878                                           (int)count);
3879                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3880                         Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3881                         e = JIM_ERR;
3882                         break;
3883                 }
3884         }
3885
3886         free(buffer);
3887
3888         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3889
3890         return e;
3891 }
3892
3893 /* FIX? should we propagate errors here rather than printing them
3894  * and continuing?
3895  */
3896 void target_handle_event(struct target *target, enum target_event e)
3897 {
3898         struct target_event_action *teap;
3899
3900         for (teap = target->event_action; teap != NULL; teap = teap->next) {
3901                 if (teap->event == e) {
3902                         LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3903                                            target->target_number,
3904                                            target_name(target),
3905                                            target_type_name(target),
3906                                            e,
3907                                            Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3908                                            Jim_GetString(teap->body, NULL));
3909                         if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
3910                                 Jim_MakeErrorMessage(teap->interp);
3911                                 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
3912                         }
3913                 }
3914         }
3915 }
3916
3917 /**
3918  * Returns true only if the target has a handler for the specified event.
3919  */
3920 bool target_has_event_action(struct target *target, enum target_event event)
3921 {
3922         struct target_event_action *teap;
3923
3924         for (teap = target->event_action; teap != NULL; teap = teap->next) {
3925                 if (teap->event == event)
3926                         return true;
3927         }
3928         return false;
3929 }
3930
3931 enum target_cfg_param {
3932         TCFG_TYPE,
3933         TCFG_EVENT,
3934         TCFG_WORK_AREA_VIRT,
3935         TCFG_WORK_AREA_PHYS,
3936         TCFG_WORK_AREA_SIZE,
3937         TCFG_WORK_AREA_BACKUP,
3938         TCFG_ENDIAN,
3939         TCFG_VARIANT,
3940         TCFG_COREID,
3941         TCFG_CHAIN_POSITION,
3942         TCFG_DBGBASE,
3943         TCFG_RTOS,
3944 };
3945
3946 static Jim_Nvp nvp_config_opts[] = {
3947         { .name = "-type",             .value = TCFG_TYPE },
3948         { .name = "-event",            .value = TCFG_EVENT },
3949         { .name = "-work-area-virt",   .value = TCFG_WORK_AREA_VIRT },
3950         { .name = "-work-area-phys",   .value = TCFG_WORK_AREA_PHYS },
3951         { .name = "-work-area-size",   .value = TCFG_WORK_AREA_SIZE },
3952         { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3953         { .name = "-endian" ,          .value = TCFG_ENDIAN },
3954         { .name = "-variant",          .value = TCFG_VARIANT },
3955         { .name = "-coreid",           .value = TCFG_COREID },
3956         { .name = "-chain-position",   .value = TCFG_CHAIN_POSITION },
3957         { .name = "-dbgbase",          .value = TCFG_DBGBASE },
3958         { .name = "-rtos",             .value = TCFG_RTOS },
3959         { .name = NULL, .value = -1 }
3960 };
3961
3962 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3963 {
3964         Jim_Nvp *n;
3965         Jim_Obj *o;
3966         jim_wide w;
3967         char *cp;
3968         int e;
3969
3970         /* parse config or cget options ... */
3971         while (goi->argc > 0) {
3972                 Jim_SetEmptyResult(goi->interp);
3973                 /* Jim_GetOpt_Debug(goi); */
3974
3975                 if (target->type->target_jim_configure) {
3976                         /* target defines a configure function */
3977                         /* target gets first dibs on parameters */
3978                         e = (*(target->type->target_jim_configure))(target, goi);
3979                         if (e == JIM_OK) {
3980                                 /* more? */
3981                                 continue;
3982                         }
3983                         if (e == JIM_ERR) {
3984                                 /* An error */
3985                                 return e;
3986                         }
3987                         /* otherwise we 'continue' below */
3988                 }
3989                 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3990                 if (e != JIM_OK) {
3991                         Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3992                         return e;
3993                 }
3994                 switch (n->value) {
3995                 case TCFG_TYPE:
3996                         /* not setable */
3997                         if (goi->isconfigure) {
3998                                 Jim_SetResultFormatted(goi->interp,
3999                                                 "not settable: %s", n->name);
4000                                 return JIM_ERR;
4001                         } else {
4002 no_params:
4003                                 if (goi->argc != 0) {
4004                                         Jim_WrongNumArgs(goi->interp,
4005                                                         goi->argc, goi->argv,
4006                                                         "NO PARAMS");
4007                                         return JIM_ERR;
4008                                 }
4009                         }
4010                         Jim_SetResultString(goi->interp,
4011                                         target_type_name(target), -1);
4012                         /* loop for more */
4013                         break;
4014                 case TCFG_EVENT:
4015                         if (goi->argc == 0) {
4016                                 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4017                                 return JIM_ERR;
4018                         }
4019
4020                         e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4021                         if (e != JIM_OK) {
4022                                 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4023                                 return e;
4024                         }
4025
4026                         if (goi->isconfigure) {
4027                                 if (goi->argc != 1) {
4028                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4029                                         return JIM_ERR;
4030                                 }
4031                         } else {
4032                                 if (goi->argc != 0) {
4033                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4034                                         return JIM_ERR;
4035                                 }
4036                         }
4037
4038                         {
4039                                 struct target_event_action *teap;
4040
4041                                 teap = target->event_action;
4042                                 /* replace existing? */
4043                                 while (teap) {
4044                                         if (teap->event == (enum target_event)n->value)
4045                                                 break;
4046                                         teap = teap->next;
4047                                 }
4048
4049                                 if (goi->isconfigure) {
4050                                         bool replace = true;
4051                                         if (teap == NULL) {
4052                                                 /* create new */
4053                                                 teap = calloc(1, sizeof(*teap));
4054                                                 replace = false;
4055                                         }
4056                                         teap->event = n->value;
4057                                         teap->interp = goi->interp;
4058                                         Jim_GetOpt_Obj(goi, &o);
4059                                         if (teap->body)
4060                                                 Jim_DecrRefCount(teap->interp, teap->body);
4061                                         teap->body  = Jim_DuplicateObj(goi->interp, o);
4062                                         /*
4063                                          * FIXME:
4064                                          *     Tcl/TK - "tk events" have a nice feature.
4065                                          *     See the "BIND" command.
4066                                          *    We should support that here.
4067                                          *     You can specify %X and %Y in the event code.
4068                                          *     The idea is: %T - target name.
4069                                          *     The idea is: %N - target number
4070                                          *     The idea is: %E - event name.
4071                                          */
4072                                         Jim_IncrRefCount(teap->body);
4073
4074                                         if (!replace) {
4075                                                 /* add to head of event list */
4076                                                 teap->next = target->event_action;
4077                                                 target->event_action = teap;
4078                                         }
4079                                         Jim_SetEmptyResult(goi->interp);
4080                                 } else {
4081                                         /* get */
4082                                         if (teap == NULL)
4083                                                 Jim_SetEmptyResult(goi->interp);
4084                                         else
4085                                                 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4086                                 }
4087                         }
4088                         /* loop for more */
4089                         break;
4090
4091                 case TCFG_WORK_AREA_VIRT:
4092                         if (goi->isconfigure) {
4093                                 target_free_all_working_areas(target);
4094                                 e = Jim_GetOpt_Wide(goi, &w);
4095                                 if (e != JIM_OK)
4096                                         return e;
4097                                 target->working_area_virt = w;
4098                                 target->working_area_virt_spec = true;
4099                         } else {
4100                                 if (goi->argc != 0)
4101                                         goto no_params;
4102                         }
4103                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4104                         /* loop for more */
4105                         break;
4106
4107                 case TCFG_WORK_AREA_PHYS:
4108                         if (goi->isconfigure) {
4109                                 target_free_all_working_areas(target);
4110                                 e = Jim_GetOpt_Wide(goi, &w);
4111                                 if (e != JIM_OK)
4112                                         return e;
4113                                 target->working_area_phys = w;
4114                                 target->working_area_phys_spec = true;
4115                         } else {
4116                                 if (goi->argc != 0)
4117                                         goto no_params;
4118                         }
4119                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4120                         /* loop for more */
4121                         break;
4122
4123                 case TCFG_WORK_AREA_SIZE:
4124                         if (goi->isconfigure) {
4125                                 target_free_all_working_areas(target);
4126                                 e = Jim_GetOpt_Wide(goi, &w);
4127                                 if (e != JIM_OK)
4128                                         return e;
4129                                 target->working_area_size = w;
4130                         } else {
4131                                 if (goi->argc != 0)
4132                                         goto no_params;
4133                         }
4134                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4135                         /* loop for more */
4136                         break;
4137
4138                 case TCFG_WORK_AREA_BACKUP:
4139                         if (goi->isconfigure) {
4140                                 target_free_all_working_areas(target);
4141                                 e = Jim_GetOpt_Wide(goi, &w);
4142                                 if (e != JIM_OK)
4143                                         return e;
4144                                 /* make this exactly 1 or 0 */
4145                                 target->backup_working_area = (!!w);
4146                         } else {
4147                                 if (goi->argc != 0)
4148                                         goto no_params;
4149                         }
4150                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4151                         /* loop for more e*/
4152                         break;
4153
4154
4155                 case TCFG_ENDIAN:
4156                         if (goi->isconfigure) {
4157                                 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4158                                 if (e != JIM_OK) {
4159                                         Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4160                                         return e;
4161                                 }
4162                                 target->endianness = n->value;
4163                         } else {
4164                                 if (goi->argc != 0)
4165                                         goto no_params;
4166                         }
4167                         n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4168                         if (n->name == NULL) {
4169                                 target->endianness = TARGET_LITTLE_ENDIAN;
4170                                 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4171                         }
4172                         Jim_SetResultString(goi->interp, n->name, -1);
4173                         /* loop for more */
4174                         break;
4175
4176                 case TCFG_VARIANT:
4177                         if (goi->isconfigure) {
4178                                 if (goi->argc < 1) {
4179                                         Jim_SetResultFormatted(goi->interp,
4180                                                                                    "%s ?STRING?",
4181                                                                                    n->name);
4182                                         return JIM_ERR;
4183                                 }
4184                                 if (target->variant)
4185                                         free((void *)(target->variant));
4186                                 e = Jim_GetOpt_String(goi, &cp, NULL);
4187                                 if (e != JIM_OK)
4188                                         return e;
4189                                 target->variant = strdup(cp);
4190                         } else {
4191                                 if (goi->argc != 0)
4192                                         goto no_params;
4193                         }
4194                         Jim_SetResultString(goi->interp, target->variant, -1);
4195                         /* loop for more */
4196                         break;
4197
4198                 case TCFG_COREID:
4199                         if (goi->isconfigure) {
4200                                 e = Jim_GetOpt_Wide(goi, &w);
4201                                 if (e != JIM_OK)
4202                                         return e;
4203                                 target->coreid = (int32_t)w;
4204                         } else {
4205                                 if (goi->argc != 0)
4206                                         goto no_params;
4207                         }
4208                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4209                         /* loop for more */
4210                         break;
4211
4212                 case TCFG_CHAIN_POSITION:
4213                         if (goi->isconfigure) {
4214                                 Jim_Obj *o_t;
4215                                 struct jtag_tap *tap;
4216                                 target_free_all_working_areas(target);
4217                                 e = Jim_GetOpt_Obj(goi, &o_t);
4218                                 if (e != JIM_OK)
4219                                         return e;
4220                                 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4221                                 if (tap == NULL)
4222                                         return JIM_ERR;
4223                                 /* make this exactly 1 or 0 */
4224                                 target->tap = tap;
4225                         } else {
4226                                 if (goi->argc != 0)
4227                                         goto no_params;
4228                         }
4229                         Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4230                         /* loop for more e*/
4231                         break;
4232                 case TCFG_DBGBASE:
4233                         if (goi->isconfigure) {
4234                                 e = Jim_GetOpt_Wide(goi, &w);
4235                                 if (e != JIM_OK)
4236                                         return e;
4237                                 target->dbgbase = (uint32_t)w;
4238                                 target->dbgbase_set = true;
4239                         } else {
4240                                 if (goi->argc != 0)
4241                                         goto no_params;
4242                         }
4243                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4244                         /* loop for more */
4245                         break;
4246
4247                 case TCFG_RTOS:
4248                         /* RTOS */
4249                         {
4250                                 int result = rtos_create(goi, target);
4251                                 if (result != JIM_OK)
4252                                         return result;
4253                         }
4254                         /* loop for more */
4255                         break;
4256                 }
4257         } /* while (goi->argc) */
4258
4259
4260                 /* done - we return */
4261         return JIM_OK;
4262 }
4263
4264 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4265 {
4266         Jim_GetOptInfo goi;
4267
4268         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4269         goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4270         int need_args = 1 + goi.isconfigure;
4271         if (goi.argc < need_args) {
4272                 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4273                         goi.isconfigure
4274                                 ? "missing: -option VALUE ..."
4275                                 : "missing: -option ...");
4276                 return JIM_ERR;
4277         }
4278         struct target *target = Jim_CmdPrivData(goi.interp);
4279         return target_configure(&goi, target);
4280 }
4281
4282 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4283 {
4284         const char *cmd_name = Jim_GetString(argv[0], NULL);
4285
4286         Jim_GetOptInfo goi;
4287         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4288
4289         if (goi.argc < 2 || goi.argc > 4) {
4290                 Jim_SetResultFormatted(goi.interp,
4291                                 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4292                 return JIM_ERR;
4293         }
4294
4295         target_write_fn fn;
4296         fn = target_write_memory_fast;
4297
4298         int e;
4299         if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4300                 /* consume it */
4301                 struct Jim_Obj *obj;
4302                 e = Jim_GetOpt_Obj(&goi, &obj);
4303                 if (e != JIM_OK)
4304                         return e;
4305
4306                 fn = target_write_phys_memory;
4307         }
4308
4309         jim_wide a;
4310         e = Jim_GetOpt_Wide(&goi, &a);
4311         if (e != JIM_OK)
4312                 return e;
4313
4314         jim_wide b;
4315         e = Jim_GetOpt_Wide(&goi, &b);
4316         if (e != JIM_OK)
4317                 return e;
4318
4319         jim_wide c = 1;
4320         if (goi.argc == 1) {
4321                 e = Jim_GetOpt_Wide(&goi, &c);
4322                 if (e != JIM_OK)
4323                         return e;
4324         }
4325
4326         /* all args must be consumed */
4327         if (goi.argc != 0)
4328                 return JIM_ERR;
4329
4330         struct target *target = Jim_CmdPrivData(goi.interp);
4331         unsigned data_size;
4332         if (strcasecmp(cmd_name, "mww") == 0)
4333                 data_size = 4;
4334         else if (strcasecmp(cmd_name, "mwh") == 0)
4335                 data_size = 2;
4336         else if (strcasecmp(cmd_name, "mwb") == 0)
4337                 data_size = 1;
4338         else {
4339                 LOG_ERROR("command '%s' unknown: ", cmd_name);
4340                 return JIM_ERR;
4341         }
4342
4343         return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4344 }
4345
4346 /**
4347 *  @brief Reads an array of words/halfwords/bytes from target memory starting at specified address.
4348 *
4349 *  Usage: mdw [phys] <address> [<count>] - for 32 bit reads
4350 *         mdh [phys] <address> [<count>] - for 16 bit reads
4351 *         mdb [phys] <address> [<count>] - for  8 bit reads
4352 *
4353 *  Count defaults to 1.
4354 *
4355 *  Calls target_read_memory or target_read_phys_memory depending on
4356 *  the presence of the "phys" argument
4357 *  Reads the target memory in blocks of max. 32 bytes, and returns an array of ints formatted
4358 *  to int representation in base16.
4359 *  Also outputs read data in a human readable form using command_print
4360 *
4361 *  @param phys if present target_read_phys_memory will be used instead of target_read_memory
4362 *  @param address address where to start the read. May be specified in decimal or hex using the standard "0x" prefix
4363 *  @param count optional count parameter to read an array of values. If not specified, defaults to 1.
4364 *  @returns:  JIM_ERR on error or JIM_OK on success and sets the result string to an array of ascii formatted numbers
4365 *  on success, with [<count>] number of elements.
4366 *
4367 *  In case of little endian target:
4368 *      Example1: "mdw 0x00000000"  returns "10123456"
4369 *      Exmaple2: "mdh 0x00000000 1" returns "3456"
4370 *      Example3: "mdb 0x00000000" returns "56"
4371 *      Example4: "mdh 0x00000000 2" returns "3456 1012"
4372 *      Example5: "mdb 0x00000000 3" returns "56 34 12"
4373 **/
4374 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4375 {
4376         const char *cmd_name = Jim_GetString(argv[0], NULL);
4377
4378         Jim_GetOptInfo goi;
4379         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4380
4381         if ((goi.argc < 1) || (goi.argc > 3)) {
4382                 Jim_SetResultFormatted(goi.interp,
4383                                 "usage: %s [phys] <address> [<count>]", cmd_name);
4384                 return JIM_ERR;
4385         }
4386
4387         int (*fn)(struct target *target,
4388                         uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4389         fn = target_read_memory;
4390
4391         int e;
4392         if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4393                 /* consume it */
4394                 struct Jim_Obj *obj;
4395                 e = Jim_GetOpt_Obj(&goi, &obj);
4396                 if (e != JIM_OK)
4397                         return e;
4398
4399                 fn = target_read_phys_memory;
4400         }
4401
4402         /* Read address parameter */
4403         jim_wide addr;
4404         e = Jim_GetOpt_Wide(&goi, &addr);
4405         if (e != JIM_OK)
4406                 return JIM_ERR;
4407
4408         /* If next parameter exists, read it out as the count parameter, if not, set it to 1 (default) */
4409         jim_wide count;
4410         if (goi.argc == 1) {
4411                 e = Jim_GetOpt_Wide(&goi, &count);
4412                 if (e != JIM_OK)
4413                         return JIM_ERR;
4414         } else
4415                 count = 1;
4416
4417         /* all args must be consumed */
4418         if (goi.argc != 0)
4419                 return JIM_ERR;
4420
4421         jim_wide dwidth = 1; /* shut up gcc */
4422         if (strcasecmp(cmd_name, "mdw") == 0)
4423                 dwidth = 4;
4424         else if (strcasecmp(cmd_name, "mdh") == 0)
4425                 dwidth = 2;
4426         else if (strcasecmp(cmd_name, "mdb") == 0)
4427                 dwidth = 1;
4428         else {
4429                 LOG_ERROR("command '%s' unknown: ", cmd_name);
4430                 return JIM_ERR;
4431         }
4432
4433         /* convert count to "bytes" */
4434         int bytes = count * dwidth;
4435
4436         struct target *target = Jim_CmdPrivData(goi.interp);
4437         uint8_t  target_buf[32];
4438         jim_wide x, y, z;
4439         while (bytes > 0) {
4440                 y = (bytes < 16) ? bytes : 16; /* y = min(bytes, 16); */
4441
4442                 /* Try to read out next block */
4443                 e = fn(target, addr, dwidth, y / dwidth, target_buf);
4444
4445                 if (e != ERROR_OK) {
4446                         Jim_SetResultFormatted(interp, "error reading target @ 0x%08lx", (long)addr);
4447                         return JIM_ERR;
4448                 }
4449
4450                 command_print_sameline(NULL, "0x%08x ", (int)(addr));
4451                 switch (dwidth) {
4452                 case 4:
4453                         for (x = 0; x < 16 && x < y; x += 4) {
4454                                 z = target_buffer_get_u32(target, &(target_buf[x]));
4455                                 command_print_sameline(NULL, "%08x ", (int)(z));
4456                         }
4457                         for (; (x < 16) ; x += 4)
4458                                 command_print_sameline(NULL, "         ");
4459                         break;
4460                 case 2:
4461                         for (x = 0; x < 16 && x < y; x += 2) {
4462                                 z = target_buffer_get_u16(target, &(target_buf[x]));
4463                                 command_print_sameline(NULL, "%04x ", (int)(z));
4464                         }
4465                         for (; (x < 16) ; x += 2)
4466                                 command_print_sameline(NULL, "     ");
4467                         break;
4468                 case 1:
4469                 default:
4470                         for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4471                                 z = target_buffer_get_u8(target, &(target_buf[x]));
4472                                 command_print_sameline(NULL, "%02x ", (int)(z));
4473                         }
4474                         for (; (x < 16) ; x += 1)
4475                                 command_print_sameline(NULL, "   ");
4476                         break;
4477                 }
4478                 /* ascii-ify the bytes */
4479                 for (x = 0 ; x < y ; x++) {
4480                         if ((target_buf[x] >= 0x20) &&
4481                                 (target_buf[x] <= 0x7e)) {
4482                                 /* good */
4483                         } else {
4484                                 /* smack it */
4485                                 target_buf[x] = '.';
4486                         }
4487                 }
4488                 /* space pad  */
4489                 while (x < 16) {
4490                         target_buf[x] = ' ';
4491                         x++;
4492                 }
4493                 /* terminate */
4494                 target_buf[16] = 0;
4495                 /* print - with a newline */
4496                 command_print_sameline(NULL, "%s\n", target_buf);
4497                 /* NEXT... */
4498                 bytes -= 16;
4499                 addr += 16;
4500         }
4501         return JIM_OK;
4502 }
4503
4504 static int jim_target_mem2array(Jim_Interp *interp,
4505                 int argc, Jim_Obj *const *argv)
4506 {
4507         struct target *target = Jim_CmdPrivData(interp);
4508         return target_mem2array(interp, target, argc - 1, argv + 1);
4509 }
4510
4511 static int jim_target_array2mem(Jim_Interp *interp,
4512                 int argc, Jim_Obj *const *argv)
4513 {
4514         struct target *target = Jim_CmdPrivData(interp);
4515         return target_array2mem(interp, target, argc - 1, argv + 1);
4516 }
4517
4518 static int jim_target_tap_disabled(Jim_Interp *interp)
4519 {
4520         Jim_SetResultFormatted(interp, "[TAP is disabled]");
4521         return JIM_ERR;
4522 }
4523
4524 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4525 {
4526         if (argc != 1) {
4527                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4528                 return JIM_ERR;
4529         }
4530         struct target *target = Jim_CmdPrivData(interp);
4531         if (!target->tap->enabled)
4532                 return jim_target_tap_disabled(interp);
4533
4534         int e = target->type->examine(target);
4535         if (e != ERROR_OK)
4536                 return JIM_ERR;
4537         return JIM_OK;
4538 }
4539
4540 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4541 {
4542         if (argc != 1) {
4543                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4544                 return JIM_ERR;
4545         }
4546         struct target *target = Jim_CmdPrivData(interp);
4547
4548         if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4549                 return JIM_ERR;
4550
4551         return JIM_OK;
4552 }
4553
4554 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4555 {
4556         if (argc != 1) {
4557                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4558                 return JIM_ERR;
4559         }
4560         struct target *target = Jim_CmdPrivData(interp);
4561         if (!target->tap->enabled)
4562                 return jim_target_tap_disabled(interp);
4563
4564         int e;
4565         if (!(target_was_examined(target)))
4566                 e = ERROR_TARGET_NOT_EXAMINED;
4567         else
4568                 e = target->type->poll(target);
4569         if (e != ERROR_OK)
4570                 return JIM_ERR;
4571         return JIM_OK;
4572 }
4573
4574 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4575 {
4576         Jim_GetOptInfo goi;
4577         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4578
4579         if (goi.argc != 2) {
4580                 Jim_WrongNumArgs(interp, 0, argv,
4581                                 "([tT]|[fF]|assert|deassert) BOOL");
4582                 return JIM_ERR;
4583         }
4584
4585         Jim_Nvp *n;
4586         int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4587         if (e != JIM_OK) {
4588                 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4589                 return e;
4590         }
4591         /* the halt or not param */
4592         jim_wide a;
4593         e = Jim_GetOpt_Wide(&goi, &a);
4594         if (e != JIM_OK)
4595                 return e;
4596
4597         struct target *target = Jim_CmdPrivData(goi.interp);
4598         if (!target->tap->enabled)
4599                 return jim_target_tap_disabled(interp);
4600         if (!(target_was_examined(target))) {
4601                 LOG_ERROR("Target not examined yet");
4602                 return ERROR_TARGET_NOT_EXAMINED;
4603         }
4604         if (!target->type->assert_reset || !target->type->deassert_reset) {
4605                 Jim_SetResultFormatted(interp,
4606                                 "No target-specific reset for %s",
4607                                 target_name(target));
4608                 return JIM_ERR;
4609         }
4610         /* determine if we should halt or not. */
4611         target->reset_halt = !!a;
4612         /* When this happens - all workareas are invalid. */
4613         target_free_all_working_areas_restore(target, 0);
4614
4615         /* do the assert */
4616         if (n->value == NVP_ASSERT)
4617                 e = target->type->assert_reset(target);
4618         else
4619                 e = target->type->deassert_reset(target);
4620         return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4621 }
4622
4623 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4624 {
4625         if (argc != 1) {
4626                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4627                 return JIM_ERR;
4628         }
4629         struct target *target = Jim_CmdPrivData(interp);
4630         if (!target->tap->enabled)
4631                 return jim_target_tap_disabled(interp);
4632         int e = target->type->halt(target);
4633         return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4634 }
4635
4636 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4637 {
4638         Jim_GetOptInfo goi;
4639         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4640
4641         /* params:  <name>  statename timeoutmsecs */
4642         if (goi.argc != 2) {
4643                 const char *cmd_name = Jim_GetString(argv[0], NULL);
4644                 Jim_SetResultFormatted(goi.interp,
4645                                 "%s <state_name> <timeout_in_msec>", cmd_name);
4646                 return JIM_ERR;
4647         }
4648
4649         Jim_Nvp *n;
4650         int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4651         if (e != JIM_OK) {
4652                 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
4653                 return e;
4654         }
4655         jim_wide a;
4656         e = Jim_GetOpt_Wide(&goi, &a);
4657         if (e != JIM_OK)
4658                 return e;
4659         struct target *target = Jim_CmdPrivData(interp);
4660         if (!target->tap->enabled)
4661                 return jim_target_tap_disabled(interp);
4662
4663         e = target_wait_state(target, n->value, a);
4664         if (e != ERROR_OK) {
4665                 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4666                 Jim_SetResultFormatted(goi.interp,
4667                                 "target: %s wait %s fails (%#s) %s",
4668                                 target_name(target), n->name,
4669                                 eObj, target_strerror_safe(e));
4670                 Jim_FreeNewObj(interp, eObj);
4671                 return JIM_ERR;
4672         }
4673         return JIM_OK;
4674 }
4675 /* List for human, Events defined for this target.
4676  * scripts/programs should use 'name cget -event NAME'
4677  */
4678 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4679 {
4680         struct command_context *cmd_ctx = current_command_context(interp);
4681         assert(cmd_ctx != NULL);
4682
4683         struct target *target = Jim_CmdPrivData(interp);
4684         struct target_event_action *teap = target->event_action;
4685         command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4686                                    target->target_number,
4687                                    target_name(target));
4688         command_print(cmd_ctx, "%-25s | Body", "Event");
4689         command_print(cmd_ctx, "------------------------- | "
4690                         "----------------------------------------");
4691         while (teap) {
4692                 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4693                 command_print(cmd_ctx, "%-25s | %s",
4694                                 opt->name, Jim_GetString(teap->body, NULL));
4695                 teap = teap->next;
4696         }
4697         command_print(cmd_ctx, "***END***");
4698         return JIM_OK;
4699 }
4700 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4701 {
4702         if (argc != 1) {
4703                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4704                 return JIM_ERR;
4705         }
4706         struct target *target = Jim_CmdPrivData(interp);
4707         Jim_SetResultString(interp, target_state_name(target), -1);
4708         return JIM_OK;
4709 }
4710 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4711 {
4712         Jim_GetOptInfo goi;
4713         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4714         if (goi.argc != 1) {
4715                 const char *cmd_name = Jim_GetString(argv[0], NULL);
4716                 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4717                 return JIM_ERR;
4718         }
4719         Jim_Nvp *n;
4720         int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4721         if (e != JIM_OK) {
4722                 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4723                 return e;
4724         }
4725         struct target *target = Jim_CmdPrivData(interp);
4726         target_handle_event(target, n->value);
4727         return JIM_OK;
4728 }
4729
4730 static const struct command_registration target_instance_command_handlers[] = {
4731         {
4732                 .name = "configure",
4733                 .mode = COMMAND_CONFIG,
4734                 .jim_handler = jim_target_configure,
4735                 .help  = "configure a new target for use",
4736                 .usage = "[target_attribute ...]",
4737         },
4738         {
4739                 .name = "cget",
4740                 .mode = COMMAND_ANY,
4741                 .jim_handler = jim_target_configure,
4742                 .help  = "returns the specified target attribute",
4743                 .usage = "target_attribute",
4744         },
4745         {
4746                 .name = "mww",
4747                 .mode = COMMAND_EXEC,
4748                 .jim_handler = jim_target_mw,
4749                 .help = "Write 32-bit word(s) to target memory",
4750                 .usage = "address data [count]",
4751         },
4752         {
4753                 .name = "mwh",
4754                 .mode = COMMAND_EXEC,
4755                 .jim_handler = jim_target_mw,
4756                 .help = "Write 16-bit half-word(s) to target memory",
4757                 .usage = "address data [count]",
4758         },
4759         {
4760                 .name = "mwb",
4761                 .mode = COMMAND_EXEC,
4762                 .jim_handler = jim_target_mw,
4763                 .help = "Write byte(s) to target memory",
4764                 .usage = "address data [count]",
4765         },
4766         {
4767                 .name = "mdw",
4768                 .mode = COMMAND_EXEC,
4769                 .jim_handler = jim_target_md,
4770                 .help = "Display target memory as 32-bit words",
4771                 .usage = "address [count]",
4772         },
4773         {
4774                 .name = "mdh",
4775                 .mode = COMMAND_EXEC,
4776                 .jim_handler = jim_target_md,
4777                 .help = "Display target memory as 16-bit half-words",
4778                 .usage = "address [count]",
4779         },
4780         {
4781                 .name = "mdb",
4782                 .mode = COMMAND_EXEC,
4783                 .jim_handler = jim_target_md,
4784                 .help = "Display target memory as 8-bit bytes",
4785                 .usage = "address [count]",
4786         },
4787         {
4788                 .name = "array2mem",
4789                 .mode = COMMAND_EXEC,
4790                 .jim_handler = jim_target_array2mem,
4791                 .help = "Writes Tcl array of 8/16/32 bit numbers "
4792                         "to target memory",
4793                 .usage = "arrayname bitwidth address count",
4794         },
4795         {
4796                 .name = "mem2array",
4797                 .mode = COMMAND_EXEC,
4798                 .jim_handler = jim_target_mem2array,
4799                 .help = "Loads Tcl array of 8/16/32 bit numbers "
4800                         "from target memory",
4801                 .usage = "arrayname bitwidth address count",
4802         },
4803         {
4804                 .name = "eventlist",
4805                 .mode = COMMAND_EXEC,
4806                 .jim_handler = jim_target_event_list,
4807                 .help = "displays a table of events defined for this target",
4808         },
4809         {
4810                 .name = "curstate",
4811                 .mode = COMMAND_EXEC,
4812                 .jim_handler = jim_target_current_state,
4813                 .help = "displays the current state of this target",
4814         },
4815         {
4816                 .name = "arp_examine",
4817                 .mode = COMMAND_EXEC,
4818                 .jim_handler = jim_target_examine,
4819                 .help = "used internally for reset processing",
4820         },
4821         {
4822                 .name = "arp_halt_gdb",
4823                 .mode = COMMAND_EXEC,
4824                 .jim_handler = jim_target_halt_gdb,
4825                 .help = "used internally for reset processing to halt GDB",
4826         },
4827         {
4828                 .name = "arp_poll",
4829                 .mode = COMMAND_EXEC,
4830                 .jim_handler = jim_target_poll,
4831                 .help = "used internally for reset processing",
4832         },
4833         {
4834                 .name = "arp_reset",
4835                 .mode = COMMAND_EXEC,
4836                 .jim_handler = jim_target_reset,
4837                 .help = "used internally for reset processing",
4838         },
4839         {
4840                 .name = "arp_halt",
4841                 .mode = COMMAND_EXEC,
4842                 .jim_handler = jim_target_halt,
4843                 .help = "used internally for reset processing",
4844         },
4845         {
4846                 .name = "arp_waitstate",
4847                 .mode = COMMAND_EXEC,
4848                 .jim_handler = jim_target_wait_state,
4849                 .help = "used internally for reset processing",
4850         },
4851         {
4852                 .name = "invoke-event",
4853                 .mode = COMMAND_EXEC,
4854                 .jim_handler = jim_target_invoke_event,
4855                 .help = "invoke handler for specified event",
4856                 .usage = "event_name",
4857         },
4858         COMMAND_REGISTRATION_DONE
4859 };
4860
4861 static int target_create(Jim_GetOptInfo *goi)
4862 {
4863         Jim_Obj *new_cmd;
4864         Jim_Cmd *cmd;
4865         const char *cp;
4866         char *cp2;
4867         int e;
4868         int x;
4869         struct target *target;
4870         struct command_context *cmd_ctx;
4871
4872         cmd_ctx = current_command_context(goi->interp);
4873         assert(cmd_ctx != NULL);
4874
4875         if (goi->argc < 3) {
4876                 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4877                 return JIM_ERR;
4878         }
4879
4880         /* COMMAND */
4881         Jim_GetOpt_Obj(goi, &new_cmd);
4882         /* does this command exist? */
4883         cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4884         if (cmd) {
4885                 cp = Jim_GetString(new_cmd, NULL);
4886                 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
4887                 return JIM_ERR;
4888         }
4889
4890         /* TYPE */
4891         e = Jim_GetOpt_String(goi, &cp2, NULL);
4892         if (e != JIM_OK)
4893                 return e;
4894         cp = cp2;
4895         /* now does target type exist */
4896         for (x = 0 ; target_types[x] ; x++) {
4897                 if (0 == strcmp(cp, target_types[x]->name)) {
4898                         /* found */
4899                         break;
4900                 }
4901
4902                 /* check for deprecated name */
4903                 if (target_types[x]->deprecated_name) {
4904                         if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
4905                                 /* found */
4906                                 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
4907                                 break;
4908                         }
4909                 }
4910         }
4911         if (target_types[x] == NULL) {
4912                 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
4913                 for (x = 0 ; target_types[x] ; x++) {
4914                         if (target_types[x + 1]) {
4915                                 Jim_AppendStrings(goi->interp,
4916                                                                    Jim_GetResult(goi->interp),
4917                                                                    target_types[x]->name,
4918                                                                    ", ", NULL);
4919                         } else {
4920                                 Jim_AppendStrings(goi->interp,
4921                                                                    Jim_GetResult(goi->interp),
4922                                                                    " or ",
4923                                                                    target_types[x]->name, NULL);
4924                         }
4925                 }
4926                 return JIM_ERR;
4927         }
4928
4929         /* Create it */
4930         target = calloc(1, sizeof(struct target));
4931         /* set target number */
4932         target->target_number = new_target_number();
4933
4934         /* allocate memory for each unique target type */
4935         target->type = (struct target_type *)calloc(1, sizeof(struct target_type));
4936
4937         memcpy(target->type, target_types[x], sizeof(struct target_type));
4938
4939         /* will be set by "-endian" */
4940         target->endianness = TARGET_ENDIAN_UNKNOWN;
4941
4942         /* default to first core, override with -coreid */
4943         target->coreid = 0;
4944
4945         target->working_area        = 0x0;
4946         target->working_area_size   = 0x0;
4947         target->working_areas       = NULL;
4948         target->backup_working_area = 0;
4949
4950         target->state               = TARGET_UNKNOWN;
4951         target->debug_reason        = DBG_REASON_UNDEFINED;
4952         target->reg_cache           = NULL;
4953         target->breakpoints         = NULL;
4954         target->watchpoints         = NULL;
4955         target->next                = NULL;
4956         target->arch_info           = NULL;
4957
4958         target->display             = 1;
4959
4960         target->halt_issued                     = false;
4961
4962         /* initialize trace information */
4963         target->trace_info = malloc(sizeof(struct trace));
4964         target->trace_info->num_trace_points         = 0;
4965         target->trace_info->trace_points_size        = 0;
4966         target->trace_info->trace_points             = NULL;
4967         target->trace_info->trace_history_size       = 0;
4968         target->trace_info->trace_history            = NULL;
4969         target->trace_info->trace_history_pos        = 0;
4970         target->trace_info->trace_history_overflowed = 0;
4971
4972         target->dbgmsg          = NULL;
4973         target->dbg_msg_enabled = 0;
4974
4975         target->endianness = TARGET_ENDIAN_UNKNOWN;
4976
4977         target->rtos = NULL;
4978         target->rtos_auto_detect = false;
4979
4980         /* Do the rest as "configure" options */
4981         goi->isconfigure = 1;
4982         e = target_configure(goi, target);
4983
4984         if (target->tap == NULL) {
4985                 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4986                 e = JIM_ERR;
4987         }
4988
4989         if (e != JIM_OK) {
4990                 free(target->type);
4991                 free(target);
4992                 return e;
4993         }
4994
4995         if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4996                 /* default endian to little if not specified */
4997                 target->endianness = TARGET_LITTLE_ENDIAN;
4998         }
4999
5000         /* incase variant is not set */
5001         if (!target->variant)
5002                 target->variant = strdup("");
5003
5004         cp = Jim_GetString(new_cmd, NULL);
5005         target->cmd_name = strdup(cp);
5006
5007         /* create the target specific commands */
5008         if (target->type->commands) {
5009                 e = register_commands(cmd_ctx, NULL, target->type->commands);
5010                 if (ERROR_OK != e)
5011                         LOG_ERROR("unable to register '%s' commands", cp);
5012         }
5013         if (target->type->target_create)
5014                 (*(target->type->target_create))(target, goi->interp);
5015
5016         /* append to end of list */
5017         {
5018                 struct target **tpp;
5019                 tpp = &(all_targets);
5020                 while (*tpp)
5021                         tpp = &((*tpp)->next);
5022                 *tpp = target;
5023         }
5024
5025         /* now - create the new target name command */
5026         const struct command_registration target_subcommands[] = {
5027                 {
5028                         .chain = target_instance_command_handlers,
5029                 },
5030                 {
5031                         .chain = target->type->commands,
5032                 },
5033                 COMMAND_REGISTRATION_DONE
5034         };
5035         const struct command_registration target_commands[] = {
5036                 {
5037                         .name = cp,
5038                         .mode = COMMAND_ANY,
5039                         .help = "target command group",
5040                         .usage = "",
5041                         .chain = target_subcommands,
5042                 },
5043                 COMMAND_REGISTRATION_DONE
5044         };
5045         e = register_commands(cmd_ctx, NULL, target_commands);
5046         if (ERROR_OK != e)
5047                 return JIM_ERR;
5048
5049         struct command *c = command_find_in_context(cmd_ctx, cp);
5050         assert(c);
5051         command_set_handler_data(c, target);
5052
5053         return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5054 }
5055
5056 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5057 {
5058         if (argc != 1) {
5059                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5060                 return JIM_ERR;
5061         }
5062         struct command_context *cmd_ctx = current_command_context(interp);
5063         assert(cmd_ctx != NULL);
5064
5065         Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5066         return JIM_OK;
5067 }
5068
5069 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5070 {
5071         if (argc != 1) {
5072                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5073                 return JIM_ERR;
5074         }
5075         Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5076         for (unsigned x = 0; NULL != target_types[x]; x++) {
5077                 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5078                         Jim_NewStringObj(interp, target_types[x]->name, -1));
5079         }
5080         return JIM_OK;
5081 }
5082
5083 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5084 {
5085         if (argc != 1) {
5086                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5087                 return JIM_ERR;
5088         }
5089         Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5090         struct target *target = all_targets;
5091         while (target) {
5092                 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5093                         Jim_NewStringObj(interp, target_name(target), -1));
5094                 target = target->next;
5095         }
5096         return JIM_OK;
5097 }
5098
5099 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5100 {
5101         int i;
5102         const char *targetname;
5103         int retval, len;
5104         struct target *target = (struct target *) NULL;
5105         struct target_list *head, *curr, *new;
5106         curr = (struct target_list *) NULL;
5107         head = (struct target_list *) NULL;
5108
5109         retval = 0;
5110         LOG_DEBUG("%d", argc);
5111         /* argv[1] = target to associate in smp
5112          * argv[2] = target to assoicate in smp
5113          * argv[3] ...
5114          */
5115
5116         for (i = 1; i < argc; i++) {
5117
5118                 targetname = Jim_GetString(argv[i], &len);
5119                 target = get_target(targetname);
5120                 LOG_DEBUG("%s ", targetname);
5121                 if (target) {
5122                         new = malloc(sizeof(struct target_list));
5123                         new->target = target;
5124                         new->next = (struct target_list *)NULL;
5125                         if (head == (struct target_list *)NULL) {
5126                                 head = new;
5127                                 curr = head;
5128                         } else {
5129                                 curr->next = new;
5130                                 curr = new;
5131                         }
5132                 }
5133         }
5134         /*  now parse the list of cpu and put the target in smp mode*/
5135         curr = head;
5136
5137         while (curr != (struct target_list *)NULL) {
5138                 target = curr->target;
5139                 target->smp = 1;
5140                 target->head = head;
5141                 curr = curr->next;
5142         }
5143
5144         if (target && target->rtos)
5145                 retval = rtos_smp_init(head->target);
5146
5147         return retval;
5148 }
5149
5150
5151 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5152 {
5153         Jim_GetOptInfo goi;
5154         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5155         if (goi.argc < 3) {
5156                 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5157                         "<name> <target_type> [<target_options> ...]");
5158                 return JIM_ERR;
5159         }
5160         return target_create(&goi);
5161 }
5162
5163 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5164 {
5165         Jim_GetOptInfo goi;
5166         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5167
5168         /* It's OK to remove this mechanism sometime after August 2010 or so */
5169         LOG_WARNING("don't use numbers as target identifiers; use names");
5170         if (goi.argc != 1) {
5171                 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
5172                 return JIM_ERR;
5173         }
5174         jim_wide w;
5175         int e = Jim_GetOpt_Wide(&goi, &w);
5176         if (e != JIM_OK)
5177                 return JIM_ERR;
5178
5179         struct target *target;
5180         for (target = all_targets; NULL != target; target = target->next) {
5181                 if (target->target_number != w)
5182                         continue;
5183
5184                 Jim_SetResultString(goi.interp, target_name(target), -1);
5185                 return JIM_OK;
5186         }
5187         {
5188                 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
5189                 Jim_SetResultFormatted(goi.interp,
5190                         "Target: number %#s does not exist", wObj);
5191                 Jim_FreeNewObj(interp, wObj);
5192         }
5193         return JIM_ERR;
5194 }
5195
5196 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5197 {
5198         if (argc != 1) {
5199                 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
5200                 return JIM_ERR;
5201         }
5202         unsigned count = 0;
5203         struct target *target = all_targets;
5204         while (NULL != target) {
5205                 target = target->next;
5206                 count++;
5207         }
5208         Jim_SetResult(interp, Jim_NewIntObj(interp, count));
5209         return JIM_OK;
5210 }
5211
5212 static const struct command_registration target_subcommand_handlers[] = {
5213         {
5214                 .name = "init",
5215                 .mode = COMMAND_CONFIG,
5216                 .handler = handle_target_init_command,
5217                 .help = "initialize targets",
5218         },
5219         {
5220                 .name = "create",
5221                 /* REVISIT this should be COMMAND_CONFIG ... */
5222                 .mode = COMMAND_ANY,
5223                 .jim_handler = jim_target_create,
5224                 .usage = "name type '-chain-position' name [options ...]",
5225                 .help = "Creates and selects a new target",
5226         },
5227         {
5228                 .name = "current",
5229                 .mode = COMMAND_ANY,
5230                 .jim_handler = jim_target_current,
5231                 .help = "Returns the currently selected target",
5232         },
5233         {
5234                 .name = "types",
5235                 .mode = COMMAND_ANY,
5236                 .jim_handler = jim_target_types,
5237                 .help = "Returns the available target types as "
5238                                 "a list of strings",
5239         },
5240         {
5241                 .name = "names",
5242                 .mode = COMMAND_ANY,
5243                 .jim_handler = jim_target_names,
5244                 .help = "Returns the names of all targets as a list of strings",
5245         },
5246         {
5247                 .name = "number",
5248                 .mode = COMMAND_ANY,
5249                 .jim_handler = jim_target_number,
5250                 .usage = "number",
5251                 .help = "Returns the name of the numbered target "
5252                         "(DEPRECATED)",
5253         },
5254         {
5255                 .name = "count",
5256                 .mode = COMMAND_ANY,
5257                 .jim_handler = jim_target_count,
5258                 .help = "Returns the number of targets as an integer "
5259                         "(DEPRECATED)",
5260         },
5261         {
5262                 .name = "smp",
5263                 .mode = COMMAND_ANY,
5264                 .jim_handler = jim_target_smp,
5265                 .usage = "targetname1 targetname2 ...",
5266                 .help = "gather several target in a smp list"
5267         },
5268
5269         COMMAND_REGISTRATION_DONE
5270 };
5271
5272 struct FastLoad {
5273         uint32_t address;
5274         uint8_t *data;
5275         int length;
5276
5277 };
5278
5279 static int fastload_num;
5280 static struct FastLoad *fastload;
5281
5282 static void free_fastload(void)
5283 {
5284         if (fastload != NULL) {
5285                 int i;
5286                 for (i = 0; i < fastload_num; i++) {
5287                         if (fastload[i].data)
5288                                 free(fastload[i].data);
5289                 }
5290                 free(fastload);
5291                 fastload = NULL;
5292         }
5293 }
5294
5295 COMMAND_HANDLER(handle_fast_load_image_command)
5296 {
5297         uint8_t *buffer;
5298         size_t buf_cnt;
5299         uint32_t image_size;
5300         uint32_t min_address = 0;
5301         uint32_t max_address = 0xffffffff;
5302         int i;
5303
5304         struct image image;
5305
5306         int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5307                         &image, &min_address, &max_address);
5308         if (ERROR_OK != retval)
5309                 return retval;
5310
5311         struct duration bench;
5312         duration_start(&bench);
5313
5314         retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5315         if (retval != ERROR_OK)
5316                 return retval;
5317
5318         image_size = 0x0;
5319         retval = ERROR_OK;
5320         fastload_num = image.num_sections;
5321         fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
5322         if (fastload == NULL) {
5323                 command_print(CMD_CTX, "out of memory");
5324                 image_close(&image);
5325                 return ERROR_FAIL;
5326         }
5327         memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5328         for (i = 0; i < image.num_sections; i++) {
5329                 buffer = malloc(image.sections[i].size);
5330                 if (buffer == NULL) {
5331                         command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5332                                                   (int)(image.sections[i].size));
5333                         retval = ERROR_FAIL;
5334                         break;
5335                 }
5336
5337                 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5338                 if (retval != ERROR_OK) {
5339                         free(buffer);
5340                         break;
5341                 }
5342
5343                 uint32_t offset = 0;
5344                 uint32_t length = buf_cnt;
5345
5346                 /* DANGER!!! beware of unsigned comparision here!!! */
5347
5348                 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5349                                 (image.sections[i].base_address < max_address)) {
5350                         if (image.sections[i].base_address < min_address) {
5351                                 /* clip addresses below */
5352                                 offset += min_address-image.sections[i].base_address;
5353                                 length -= offset;
5354                         }
5355
5356                         if (image.sections[i].base_address + buf_cnt > max_address)
5357                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5358
5359                         fastload[i].address = image.sections[i].base_address + offset;
5360                         fastload[i].data = malloc(length);
5361                         if (fastload[i].data == NULL) {
5362                                 free(buffer);
5363                                 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5364                                                           length);
5365                                 retval = ERROR_FAIL;
5366                                 break;
5367                         }
5368                         memcpy(fastload[i].data, buffer + offset, length);
5369                         fastload[i].length = length;
5370
5371                         image_size += length;
5372                         command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5373                                                   (unsigned int)length,
5374                                                   ((unsigned int)(image.sections[i].base_address + offset)));
5375                 }
5376
5377                 free(buffer);
5378         }
5379
5380         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5381                 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5382                                 "in %fs (%0.3f KiB/s)", image_size,
5383                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5384
5385                 command_print(CMD_CTX,
5386                                 "WARNING: image has not been loaded to target!"
5387                                 "You can issue a 'fast_load' to finish loading.");
5388         }
5389
5390         image_close(&image);
5391
5392         if (retval != ERROR_OK)
5393                 free_fastload();
5394
5395         return retval;
5396 }
5397
5398 COMMAND_HANDLER(handle_fast_load_command)
5399 {
5400         if (CMD_ARGC > 0)
5401                 return ERROR_COMMAND_SYNTAX_ERROR;
5402         if (fastload == NULL) {
5403                 LOG_ERROR("No image in memory");
5404                 return ERROR_FAIL;
5405         }
5406         int i;
5407         int ms = timeval_ms();
5408         int size = 0;
5409         int retval = ERROR_OK;
5410         for (i = 0; i < fastload_num; i++) {
5411                 struct target *target = get_current_target(CMD_CTX);
5412                 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5413                                           (unsigned int)(fastload[i].address),
5414                                           (unsigned int)(fastload[i].length));
5415                 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5416                 if (retval != ERROR_OK)
5417                         break;
5418                 size += fastload[i].length;
5419         }
5420         if (retval == ERROR_OK) {
5421                 int after = timeval_ms();
5422                 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5423         }
5424         return retval;
5425 }
5426
5427 static const struct command_registration target_command_handlers[] = {
5428         {
5429                 .name = "targets",
5430                 .handler = handle_targets_command,
5431                 .mode = COMMAND_ANY,
5432                 .help = "change current default target (one parameter) "
5433                         "or prints table of all targets (no parameters)",
5434                 .usage = "[target]",
5435         },
5436         {
5437                 .name = "target",
5438                 .mode = COMMAND_CONFIG,
5439                 .help = "configure target",
5440
5441                 .chain = target_subcommand_handlers,
5442         },
5443         COMMAND_REGISTRATION_DONE
5444 };
5445
5446 int target_register_commands(struct command_context *cmd_ctx)
5447 {
5448         return register_commands(cmd_ctx, NULL, target_command_handlers);
5449 }
5450
5451 static bool target_reset_nag = true;
5452
5453 bool get_target_reset_nag(void)
5454 {
5455         return target_reset_nag;
5456 }
5457
5458 COMMAND_HANDLER(handle_target_reset_nag)
5459 {
5460         return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5461                         &target_reset_nag, "Nag after each reset about options to improve "
5462                         "performance");
5463 }
5464
5465 COMMAND_HANDLER(handle_ps_command)
5466 {
5467         struct target *target = get_current_target(CMD_CTX);
5468         char *display;
5469         if (target->state != TARGET_HALTED) {
5470                 LOG_INFO("target not halted !!");
5471                 return ERROR_OK;
5472         }
5473
5474         if ((target->rtos) && (target->rtos->type)
5475                         && (target->rtos->type->ps_command)) {
5476                 display = target->rtos->type->ps_command(target);
5477                 command_print(CMD_CTX, "%s", display);
5478                 free(display);
5479                 return ERROR_OK;
5480         } else {
5481                 LOG_INFO("failed");
5482                 return ERROR_TARGET_FAILURE;
5483         }
5484 }
5485
5486 static const struct command_registration target_exec_command_handlers[] = {
5487         {
5488                 .name = "fast_load_image",
5489                 .handler = handle_fast_load_image_command,
5490                 .mode = COMMAND_ANY,
5491                 .help = "Load image into server memory for later use by "
5492                         "fast_load; primarily for profiling",
5493                 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5494                         "[min_address [max_length]]",
5495         },
5496         {
5497                 .name = "fast_load",
5498                 .handler = handle_fast_load_command,
5499                 .mode = COMMAND_EXEC,
5500                 .help = "loads active fast load image to current target "
5501                         "- mainly for profiling purposes",
5502                 .usage = "",
5503         },
5504         {
5505                 .name = "profile",
5506                 .handler = handle_profile_command,
5507                 .mode = COMMAND_EXEC,
5508                 .usage = "seconds filename",
5509                 .help = "profiling samples the CPU PC",
5510         },
5511         /** @todo don't register virt2phys() unless target supports it */
5512         {
5513                 .name = "virt2phys",
5514                 .handler = handle_virt2phys_command,
5515                 .mode = COMMAND_ANY,
5516                 .help = "translate a virtual address into a physical address",
5517                 .usage = "virtual_address",
5518         },
5519         {
5520                 .name = "reg",
5521                 .handler = handle_reg_command,
5522                 .mode = COMMAND_EXEC,
5523                 .help = "display or set a register; with no arguments, "
5524                         "displays all registers and their values",
5525                 .usage = "[(register_name|register_number) [value]]",
5526         },
5527         {
5528                 .name = "poll",
5529                 .handler = handle_poll_command,
5530                 .mode = COMMAND_EXEC,
5531                 .help = "poll target state; or reconfigure background polling",
5532                 .usage = "['on'|'off']",
5533         },
5534         {
5535                 .name = "wait_halt",
5536                 .handler = handle_wait_halt_command,
5537                 .mode = COMMAND_EXEC,
5538                 .help = "wait up to the specified number of milliseconds "
5539                         "(default 5000) for a previously requested halt",
5540                 .usage = "[milliseconds]",
5541         },
5542         {
5543                 .name = "halt",
5544                 .handler = handle_halt_command,
5545                 .mode = COMMAND_EXEC,
5546                 .help = "request target to halt, then wait up to the specified"
5547                         "number of milliseconds (default 5000) for it to complete",
5548                 .usage = "[milliseconds]",
5549         },
5550         {
5551                 .name = "resume",
5552                 .handler = handle_resume_command,
5553                 .mode = COMMAND_EXEC,
5554                 .help = "resume target execution from current PC or address",
5555                 .usage = "[address]",
5556         },
5557         {
5558                 .name = "reset",
5559                 .handler = handle_reset_command,
5560                 .mode = COMMAND_EXEC,
5561                 .usage = "[run|halt|init]",
5562                 .help = "Reset all targets into the specified mode."
5563                         "Default reset mode is run, if not given.",
5564         },
5565         {
5566                 .name = "soft_reset_halt",
5567                 .handler = handle_soft_reset_halt_command,
5568                 .mode = COMMAND_EXEC,
5569                 .usage = "",
5570                 .help = "halt the target and do a soft reset",
5571         },
5572         {
5573                 .name = "step",
5574                 .handler = handle_step_command,
5575                 .mode = COMMAND_EXEC,
5576                 .help = "step one instruction from current PC or address",
5577                 .usage = "[address]",
5578         },
5579         {
5580                 .name = "mdw",
5581                 .handler = handle_md_command,
5582                 .mode = COMMAND_EXEC,
5583                 .help = "display memory words",
5584                 .usage = "['phys'] address [count]",
5585         },
5586         {
5587                 .name = "mdh",
5588                 .handler = handle_md_command,
5589                 .mode = COMMAND_EXEC,
5590                 .help = "display memory half-words",
5591                 .usage = "['phys'] address [count]",
5592         },
5593         {
5594                 .name = "mdb",
5595                 .handler = handle_md_command,
5596                 .mode = COMMAND_EXEC,
5597                 .help = "display memory bytes",
5598                 .usage = "['phys'] address [count]",
5599         },
5600         {
5601                 .name = "mww",
5602                 .handler = handle_mw_command,
5603                 .mode = COMMAND_EXEC,
5604                 .help = "write memory word",
5605                 .usage = "['phys'] address value [count]",
5606         },
5607         {
5608                 .name = "mwh",
5609                 .handler = handle_mw_command,
5610                 .mode = COMMAND_EXEC,
5611                 .help = "write memory half-word",
5612                 .usage = "['phys'] address value [count]",
5613         },
5614         {
5615                 .name = "mwb",
5616                 .handler = handle_mw_command,
5617                 .mode = COMMAND_EXEC,
5618                 .help = "write memory byte",
5619                 .usage = "['phys'] address value [count]",
5620         },
5621         {
5622                 .name = "bp",
5623                 .handler = handle_bp_command,
5624                 .mode = COMMAND_EXEC,
5625                 .help = "list or set hardware or software breakpoint",
5626                 .usage = "<address> [<asid>]<length> ['hw'|'hw_ctx']",
5627         },
5628         {
5629                 .name = "rbp",
5630                 .handler = handle_rbp_command,
5631                 .mode = COMMAND_EXEC,
5632                 .help = "remove breakpoint",
5633                 .usage = "address",
5634         },
5635         {
5636                 .name = "wp",
5637                 .handler = handle_wp_command,
5638                 .mode = COMMAND_EXEC,
5639                 .help = "list (no params) or create watchpoints",
5640                 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5641         },
5642         {
5643                 .name = "rwp",
5644                 .handler = handle_rwp_command,
5645                 .mode = COMMAND_EXEC,
5646                 .help = "remove watchpoint",
5647                 .usage = "address",
5648         },
5649         {
5650                 .name = "load_image",
5651                 .handler = handle_load_image_command,
5652                 .mode = COMMAND_EXEC,
5653                 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5654                         "[min_address] [max_length]",
5655         },
5656         {
5657                 .name = "dump_image",
5658                 .handler = handle_dump_image_command,
5659                 .mode = COMMAND_EXEC,
5660                 .usage = "filename address size",
5661         },
5662         {
5663                 .name = "verify_image",
5664                 .handler = handle_verify_image_command,
5665                 .mode = COMMAND_EXEC,
5666                 .usage = "filename [offset [type]]",
5667         },
5668         {
5669                 .name = "test_image",
5670                 .handler = handle_test_image_command,
5671                 .mode = COMMAND_EXEC,
5672                 .usage = "filename [offset [type]]",
5673         },
5674         {
5675                 .name = "mem2array",
5676                 .mode = COMMAND_EXEC,
5677                 .jim_handler = jim_mem2array,
5678                 .help = "read 8/16/32 bit memory and return as a TCL array "
5679                         "for script processing",
5680                 .usage = "arrayname bitwidth address count",
5681         },
5682         {
5683                 .name = "array2mem",
5684                 .mode = COMMAND_EXEC,
5685                 .jim_handler = jim_array2mem,
5686                 .help = "convert a TCL array to memory locations "
5687                         "and write the 8/16/32 bit values",
5688                 .usage = "arrayname bitwidth address count",
5689         },
5690         {
5691                 .name = "reset_nag",
5692                 .handler = handle_target_reset_nag,
5693                 .mode = COMMAND_ANY,
5694                 .help = "Nag after each reset about options that could have been "
5695                                 "enabled to improve performance. ",
5696                 .usage = "['enable'|'disable']",
5697         },
5698         {
5699                 .name = "ps",
5700                 .handler = handle_ps_command,
5701                 .mode = COMMAND_EXEC,
5702                 .help = "list all tasks ",
5703                 .usage = " ",
5704         },
5705
5706         COMMAND_REGISTRATION_DONE
5707 };
5708 static int target_register_user_commands(struct command_context *cmd_ctx)
5709 {
5710         int retval = ERROR_OK;
5711         retval = target_request_register_commands(cmd_ctx);
5712         if (retval != ERROR_OK)
5713                 return retval;
5714
5715         retval = trace_register_commands(cmd_ctx);
5716         if (retval != ERROR_OK)
5717                 return retval;
5718
5719
5720         return register_commands(cmd_ctx, NULL, target_exec_command_handlers);
5721 }