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