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