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