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