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