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