rtos: Destroy RTOS and fix memory leak
[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         rtos_destroy(target);
2053
2054         free(target->gdb_port_override);
2055         free(target->type);
2056         free(target->trace_info);
2057         free(target->fileio_info);
2058         free(target->cmd_name);
2059         free(target);
2060 }
2061
2062 void target_quit(void)
2063 {
2064         struct target_event_callback *pe = target_event_callbacks;
2065         while (pe) {
2066                 struct target_event_callback *t = pe->next;
2067                 free(pe);
2068                 pe = t;
2069         }
2070         target_event_callbacks = NULL;
2071
2072         struct target_timer_callback *pt = target_timer_callbacks;
2073         while (pt) {
2074                 struct target_timer_callback *t = pt->next;
2075                 free(pt);
2076                 pt = t;
2077         }
2078         target_timer_callbacks = NULL;
2079
2080         for (struct target *target = all_targets; target;) {
2081                 struct target *tmp;
2082
2083                 tmp = target->next;
2084                 target_destroy(target);
2085                 target = tmp;
2086         }
2087
2088         all_targets = NULL;
2089 }
2090
2091 int target_arch_state(struct target *target)
2092 {
2093         int retval;
2094         if (target == NULL) {
2095                 LOG_WARNING("No target has been configured");
2096                 return ERROR_OK;
2097         }
2098
2099         if (target->state != TARGET_HALTED)
2100                 return ERROR_OK;
2101
2102         retval = target->type->arch_state(target);
2103         return retval;
2104 }
2105
2106 static int target_get_gdb_fileio_info_default(struct target *target,
2107                 struct gdb_fileio_info *fileio_info)
2108 {
2109         /* If target does not support semi-hosting function, target
2110            has no need to provide .get_gdb_fileio_info callback.
2111            It just return ERROR_FAIL and gdb_server will return "Txx"
2112            as target halted every time.  */
2113         return ERROR_FAIL;
2114 }
2115
2116 static int target_gdb_fileio_end_default(struct target *target,
2117                 int retcode, int fileio_errno, bool ctrl_c)
2118 {
2119         return ERROR_OK;
2120 }
2121
2122 static int target_profiling_default(struct target *target, uint32_t *samples,
2123                 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
2124 {
2125         struct timeval timeout, now;
2126
2127         gettimeofday(&timeout, NULL);
2128         timeval_add_time(&timeout, seconds, 0);
2129
2130         LOG_INFO("Starting profiling. Halting and resuming the"
2131                         " target as often as we can...");
2132
2133         uint32_t sample_count = 0;
2134         /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2135         struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
2136
2137         int retval = ERROR_OK;
2138         for (;;) {
2139                 target_poll(target);
2140                 if (target->state == TARGET_HALTED) {
2141                         uint32_t t = buf_get_u32(reg->value, 0, 32);
2142                         samples[sample_count++] = t;
2143                         /* current pc, addr = 0, do not handle breakpoints, not debugging */
2144                         retval = target_resume(target, 1, 0, 0, 0);
2145                         target_poll(target);
2146                         alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2147                 } else if (target->state == TARGET_RUNNING) {
2148                         /* We want to quickly sample the PC. */
2149                         retval = target_halt(target);
2150                 } else {
2151                         LOG_INFO("Target not halted or running");
2152                         retval = ERROR_OK;
2153                         break;
2154                 }
2155
2156                 if (retval != ERROR_OK)
2157                         break;
2158
2159                 gettimeofday(&now, NULL);
2160                 if ((sample_count >= max_num_samples) || timeval_compare(&now, &timeout) >= 0) {
2161                         LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2162                         break;
2163                 }
2164         }
2165
2166         *num_samples = sample_count;
2167         return retval;
2168 }
2169
2170 /* Single aligned words are guaranteed to use 16 or 32 bit access
2171  * mode respectively, otherwise data is handled as quickly as
2172  * possible
2173  */
2174 int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
2175 {
2176         LOG_DEBUG("writing buffer of %" PRIi32 " byte at " TARGET_ADDR_FMT,
2177                           size, address);
2178
2179         if (!target_was_examined(target)) {
2180                 LOG_ERROR("Target not examined yet");
2181                 return ERROR_FAIL;
2182         }
2183
2184         if (size == 0)
2185                 return ERROR_OK;
2186
2187         if ((address + size - 1) < address) {
2188                 /* GDB can request this when e.g. PC is 0xfffffffc */
2189                 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2190                                   address,
2191                                   size);
2192                 return ERROR_FAIL;
2193         }
2194
2195         return target->type->write_buffer(target, address, size, buffer);
2196 }
2197
2198 static int target_write_buffer_default(struct target *target,
2199         target_addr_t address, uint32_t count, const uint8_t *buffer)
2200 {
2201         uint32_t size;
2202
2203         /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2204          * will have something to do with the size we leave to it. */
2205         for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2206                 if (address & size) {
2207                         int retval = target_write_memory(target, address, size, 1, buffer);
2208                         if (retval != ERROR_OK)
2209                                 return retval;
2210                         address += size;
2211                         count -= size;
2212                         buffer += size;
2213                 }
2214         }
2215
2216         /* Write the data with as large access size as possible. */
2217         for (; size > 0; size /= 2) {
2218                 uint32_t aligned = count - count % size;
2219                 if (aligned > 0) {
2220                         int retval = target_write_memory(target, address, size, aligned / size, buffer);
2221                         if (retval != ERROR_OK)
2222                                 return retval;
2223                         address += aligned;
2224                         count -= aligned;
2225                         buffer += aligned;
2226                 }
2227         }
2228
2229         return ERROR_OK;
2230 }
2231
2232 /* Single aligned words are guaranteed to use 16 or 32 bit access
2233  * mode respectively, otherwise data is handled as quickly as
2234  * possible
2235  */
2236 int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
2237 {
2238         LOG_DEBUG("reading buffer of %" PRIi32 " byte at " TARGET_ADDR_FMT,
2239                           size, address);
2240
2241         if (!target_was_examined(target)) {
2242                 LOG_ERROR("Target not examined yet");
2243                 return ERROR_FAIL;
2244         }
2245
2246         if (size == 0)
2247                 return ERROR_OK;
2248
2249         if ((address + size - 1) < address) {
2250                 /* GDB can request this when e.g. PC is 0xfffffffc */
2251                 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2252                                   address,
2253                                   size);
2254                 return ERROR_FAIL;
2255         }
2256
2257         return target->type->read_buffer(target, address, size, buffer);
2258 }
2259
2260 static int target_read_buffer_default(struct target *target, target_addr_t address, uint32_t count, uint8_t *buffer)
2261 {
2262         uint32_t size;
2263
2264         /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2265          * will have something to do with the size we leave to it. */
2266         for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2267                 if (address & size) {
2268                         int retval = target_read_memory(target, address, size, 1, buffer);
2269                         if (retval != ERROR_OK)
2270                                 return retval;
2271                         address += size;
2272                         count -= size;
2273                         buffer += size;
2274                 }
2275         }
2276
2277         /* Read the data with as large access size as possible. */
2278         for (; size > 0; size /= 2) {
2279                 uint32_t aligned = count - count % size;
2280                 if (aligned > 0) {
2281                         int retval = target_read_memory(target, address, size, aligned / size, buffer);
2282                         if (retval != ERROR_OK)
2283                                 return retval;
2284                         address += aligned;
2285                         count -= aligned;
2286                         buffer += aligned;
2287                 }
2288         }
2289
2290         return ERROR_OK;
2291 }
2292
2293 int target_checksum_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t *crc)
2294 {
2295         uint8_t *buffer;
2296         int retval;
2297         uint32_t i;
2298         uint32_t checksum = 0;
2299         if (!target_was_examined(target)) {
2300                 LOG_ERROR("Target not examined yet");
2301                 return ERROR_FAIL;
2302         }
2303
2304         retval = target->type->checksum_memory(target, address, size, &checksum);
2305         if (retval != ERROR_OK) {
2306                 buffer = malloc(size);
2307                 if (buffer == NULL) {
2308                         LOG_ERROR("error allocating buffer for section (%" PRId32 " bytes)", size);
2309                         return ERROR_COMMAND_SYNTAX_ERROR;
2310                 }
2311                 retval = target_read_buffer(target, address, size, buffer);
2312                 if (retval != ERROR_OK) {
2313                         free(buffer);
2314                         return retval;
2315                 }
2316
2317                 /* convert to target endianness */
2318                 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2319                         uint32_t target_data;
2320                         target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2321                         target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2322                 }
2323
2324                 retval = image_calculate_checksum(buffer, size, &checksum);
2325                 free(buffer);
2326         }
2327
2328         *crc = checksum;
2329
2330         return retval;
2331 }
2332
2333 int target_blank_check_memory(struct target *target,
2334         struct target_memory_check_block *blocks, int num_blocks,
2335         uint8_t erased_value)
2336 {
2337         if (!target_was_examined(target)) {
2338                 LOG_ERROR("Target not examined yet");
2339                 return ERROR_FAIL;
2340         }
2341
2342         if (target->type->blank_check_memory == NULL)
2343                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2344
2345         return target->type->blank_check_memory(target, blocks, num_blocks, erased_value);
2346 }
2347
2348 int target_read_u64(struct target *target, target_addr_t address, uint64_t *value)
2349 {
2350         uint8_t value_buf[8];
2351         if (!target_was_examined(target)) {
2352                 LOG_ERROR("Target not examined yet");
2353                 return ERROR_FAIL;
2354         }
2355
2356         int retval = target_read_memory(target, address, 8, 1, value_buf);
2357
2358         if (retval == ERROR_OK) {
2359                 *value = target_buffer_get_u64(target, value_buf);
2360                 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2361                                   address,
2362                                   *value);
2363         } else {
2364                 *value = 0x0;
2365                 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2366                                   address);
2367         }
2368
2369         return retval;
2370 }
2371
2372 int target_read_u32(struct target *target, target_addr_t address, uint32_t *value)
2373 {
2374         uint8_t value_buf[4];
2375         if (!target_was_examined(target)) {
2376                 LOG_ERROR("Target not examined yet");
2377                 return ERROR_FAIL;
2378         }
2379
2380         int retval = target_read_memory(target, address, 4, 1, value_buf);
2381
2382         if (retval == ERROR_OK) {
2383                 *value = target_buffer_get_u32(target, value_buf);
2384                 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2385                                   address,
2386                                   *value);
2387         } else {
2388                 *value = 0x0;
2389                 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2390                                   address);
2391         }
2392
2393         return retval;
2394 }
2395
2396 int target_read_u16(struct target *target, target_addr_t address, uint16_t *value)
2397 {
2398         uint8_t value_buf[2];
2399         if (!target_was_examined(target)) {
2400                 LOG_ERROR("Target not examined yet");
2401                 return ERROR_FAIL;
2402         }
2403
2404         int retval = target_read_memory(target, address, 2, 1, value_buf);
2405
2406         if (retval == ERROR_OK) {
2407                 *value = target_buffer_get_u16(target, value_buf);
2408                 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%4.4" PRIx16,
2409                                   address,
2410                                   *value);
2411         } else {
2412                 *value = 0x0;
2413                 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2414                                   address);
2415         }
2416
2417         return retval;
2418 }
2419
2420 int target_read_u8(struct target *target, target_addr_t address, uint8_t *value)
2421 {
2422         if (!target_was_examined(target)) {
2423                 LOG_ERROR("Target not examined yet");
2424                 return ERROR_FAIL;
2425         }
2426
2427         int retval = target_read_memory(target, address, 1, 1, value);
2428
2429         if (retval == ERROR_OK) {
2430                 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2431                                   address,
2432                                   *value);
2433         } else {
2434                 *value = 0x0;
2435                 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2436                                   address);
2437         }
2438
2439         return retval;
2440 }
2441
2442 int target_write_u64(struct target *target, target_addr_t address, uint64_t value)
2443 {
2444         int retval;
2445         uint8_t value_buf[8];
2446         if (!target_was_examined(target)) {
2447                 LOG_ERROR("Target not examined yet");
2448                 return ERROR_FAIL;
2449         }
2450
2451         LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2452                           address,
2453                           value);
2454
2455         target_buffer_set_u64(target, value_buf, value);
2456         retval = target_write_memory(target, address, 8, 1, value_buf);
2457         if (retval != ERROR_OK)
2458                 LOG_DEBUG("failed: %i", retval);
2459
2460         return retval;
2461 }
2462
2463 int target_write_u32(struct target *target, target_addr_t address, uint32_t value)
2464 {
2465         int retval;
2466         uint8_t value_buf[4];
2467         if (!target_was_examined(target)) {
2468                 LOG_ERROR("Target not examined yet");
2469                 return ERROR_FAIL;
2470         }
2471
2472         LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2473                           address,
2474                           value);
2475
2476         target_buffer_set_u32(target, value_buf, value);
2477         retval = target_write_memory(target, address, 4, 1, value_buf);
2478         if (retval != ERROR_OK)
2479                 LOG_DEBUG("failed: %i", retval);
2480
2481         return retval;
2482 }
2483
2484 int target_write_u16(struct target *target, target_addr_t address, uint16_t value)
2485 {
2486         int retval;
2487         uint8_t value_buf[2];
2488         if (!target_was_examined(target)) {
2489                 LOG_ERROR("Target not examined yet");
2490                 return ERROR_FAIL;
2491         }
2492
2493         LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2494                           address,
2495                           value);
2496
2497         target_buffer_set_u16(target, value_buf, value);
2498         retval = target_write_memory(target, address, 2, 1, value_buf);
2499         if (retval != ERROR_OK)
2500                 LOG_DEBUG("failed: %i", retval);
2501
2502         return retval;
2503 }
2504
2505 int target_write_u8(struct target *target, target_addr_t address, uint8_t value)
2506 {
2507         int retval;
2508         if (!target_was_examined(target)) {
2509                 LOG_ERROR("Target not examined yet");
2510                 return ERROR_FAIL;
2511         }
2512
2513         LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2514                           address, value);
2515
2516         retval = target_write_memory(target, address, 1, 1, &value);
2517         if (retval != ERROR_OK)
2518                 LOG_DEBUG("failed: %i", retval);
2519
2520         return retval;
2521 }
2522
2523 int target_write_phys_u64(struct target *target, target_addr_t address, uint64_t value)
2524 {
2525         int retval;
2526         uint8_t value_buf[8];
2527         if (!target_was_examined(target)) {
2528                 LOG_ERROR("Target not examined yet");
2529                 return ERROR_FAIL;
2530         }
2531
2532         LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2533                           address,
2534                           value);
2535
2536         target_buffer_set_u64(target, value_buf, value);
2537         retval = target_write_phys_memory(target, address, 8, 1, value_buf);
2538         if (retval != ERROR_OK)
2539                 LOG_DEBUG("failed: %i", retval);
2540
2541         return retval;
2542 }
2543
2544 int target_write_phys_u32(struct target *target, target_addr_t address, uint32_t value)
2545 {
2546         int retval;
2547         uint8_t value_buf[4];
2548         if (!target_was_examined(target)) {
2549                 LOG_ERROR("Target not examined yet");
2550                 return ERROR_FAIL;
2551         }
2552
2553         LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2554                           address,
2555                           value);
2556
2557         target_buffer_set_u32(target, value_buf, value);
2558         retval = target_write_phys_memory(target, address, 4, 1, value_buf);
2559         if (retval != ERROR_OK)
2560                 LOG_DEBUG("failed: %i", retval);
2561
2562         return retval;
2563 }
2564
2565 int target_write_phys_u16(struct target *target, target_addr_t address, uint16_t value)
2566 {
2567         int retval;
2568         uint8_t value_buf[2];
2569         if (!target_was_examined(target)) {
2570                 LOG_ERROR("Target not examined yet");
2571                 return ERROR_FAIL;
2572         }
2573
2574         LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2575                           address,
2576                           value);
2577
2578         target_buffer_set_u16(target, value_buf, value);
2579         retval = target_write_phys_memory(target, address, 2, 1, value_buf);
2580         if (retval != ERROR_OK)
2581                 LOG_DEBUG("failed: %i", retval);
2582
2583         return retval;
2584 }
2585
2586 int target_write_phys_u8(struct target *target, target_addr_t address, uint8_t value)
2587 {
2588         int retval;
2589         if (!target_was_examined(target)) {
2590                 LOG_ERROR("Target not examined yet");
2591                 return ERROR_FAIL;
2592         }
2593
2594         LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2595                           address, value);
2596
2597         retval = target_write_phys_memory(target, address, 1, 1, &value);
2598         if (retval != ERROR_OK)
2599                 LOG_DEBUG("failed: %i", retval);
2600
2601         return retval;
2602 }
2603
2604 static int find_target(struct command_invocation *cmd, const char *name)
2605 {
2606         struct target *target = get_target(name);
2607         if (target == NULL) {
2608                 command_print(cmd, "Target: %s is unknown, try one of:\n", name);
2609                 return ERROR_FAIL;
2610         }
2611         if (!target->tap->enabled) {
2612                 command_print(cmd, "Target: TAP %s is disabled, "
2613                          "can't be the current target\n",
2614                          target->tap->dotted_name);
2615                 return ERROR_FAIL;
2616         }
2617
2618         cmd->ctx->current_target = target;
2619         if (cmd->ctx->current_target_override)
2620                 cmd->ctx->current_target_override = target;
2621
2622         return ERROR_OK;
2623 }
2624
2625
2626 COMMAND_HANDLER(handle_targets_command)
2627 {
2628         int retval = ERROR_OK;
2629         if (CMD_ARGC == 1) {
2630                 retval = find_target(CMD, CMD_ARGV[0]);
2631                 if (retval == ERROR_OK) {
2632                         /* we're done! */
2633                         return retval;
2634                 }
2635         }
2636
2637         struct target *target = all_targets;
2638         command_print(CMD, "    TargetName         Type       Endian TapName            State       ");
2639         command_print(CMD, "--  ------------------ ---------- ------ ------------------ ------------");
2640         while (target) {
2641                 const char *state;
2642                 char marker = ' ';
2643
2644                 if (target->tap->enabled)
2645                         state = target_state_name(target);
2646                 else
2647                         state = "tap-disabled";
2648
2649                 if (CMD_CTX->current_target == target)
2650                         marker = '*';
2651
2652                 /* keep columns lined up to match the headers above */
2653                 command_print(CMD,
2654                                 "%2d%c %-18s %-10s %-6s %-18s %s",
2655                                 target->target_number,
2656                                 marker,
2657                                 target_name(target),
2658                                 target_type_name(target),
2659                                 Jim_Nvp_value2name_simple(nvp_target_endian,
2660                                         target->endianness)->name,
2661                                 target->tap->dotted_name,
2662                                 state);
2663                 target = target->next;
2664         }
2665
2666         return retval;
2667 }
2668
2669 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2670
2671 static int powerDropout;
2672 static int srstAsserted;
2673
2674 static int runPowerRestore;
2675 static int runPowerDropout;
2676 static int runSrstAsserted;
2677 static int runSrstDeasserted;
2678
2679 static int sense_handler(void)
2680 {
2681         static int prevSrstAsserted;
2682         static int prevPowerdropout;
2683
2684         int retval = jtag_power_dropout(&powerDropout);
2685         if (retval != ERROR_OK)
2686                 return retval;
2687
2688         int powerRestored;
2689         powerRestored = prevPowerdropout && !powerDropout;
2690         if (powerRestored)
2691                 runPowerRestore = 1;
2692
2693         int64_t current = timeval_ms();
2694         static int64_t lastPower;
2695         bool waitMore = lastPower + 2000 > current;
2696         if (powerDropout && !waitMore) {
2697                 runPowerDropout = 1;
2698                 lastPower = current;
2699         }
2700
2701         retval = jtag_srst_asserted(&srstAsserted);
2702         if (retval != ERROR_OK)
2703                 return retval;
2704
2705         int srstDeasserted;
2706         srstDeasserted = prevSrstAsserted && !srstAsserted;
2707
2708         static int64_t lastSrst;
2709         waitMore = lastSrst + 2000 > current;
2710         if (srstDeasserted && !waitMore) {
2711                 runSrstDeasserted = 1;
2712                 lastSrst = current;
2713         }
2714
2715         if (!prevSrstAsserted && srstAsserted)
2716                 runSrstAsserted = 1;
2717
2718         prevSrstAsserted = srstAsserted;
2719         prevPowerdropout = powerDropout;
2720
2721         if (srstDeasserted || powerRestored) {
2722                 /* Other than logging the event we can't do anything here.
2723                  * Issuing a reset is a particularly bad idea as we might
2724                  * be inside a reset already.
2725                  */
2726         }
2727
2728         return ERROR_OK;
2729 }
2730
2731 /* process target state changes */
2732 static int handle_target(void *priv)
2733 {
2734         Jim_Interp *interp = (Jim_Interp *)priv;
2735         int retval = ERROR_OK;
2736
2737         if (!is_jtag_poll_safe()) {
2738                 /* polling is disabled currently */
2739                 return ERROR_OK;
2740         }
2741
2742         /* we do not want to recurse here... */
2743         static int recursive;
2744         if (!recursive) {
2745                 recursive = 1;
2746                 sense_handler();
2747                 /* danger! running these procedures can trigger srst assertions and power dropouts.
2748                  * We need to avoid an infinite loop/recursion here and we do that by
2749                  * clearing the flags after running these events.
2750                  */
2751                 int did_something = 0;
2752                 if (runSrstAsserted) {
2753                         LOG_INFO("srst asserted detected, running srst_asserted proc.");
2754                         Jim_Eval(interp, "srst_asserted");
2755                         did_something = 1;
2756                 }
2757                 if (runSrstDeasserted) {
2758                         Jim_Eval(interp, "srst_deasserted");
2759                         did_something = 1;
2760                 }
2761                 if (runPowerDropout) {
2762                         LOG_INFO("Power dropout detected, running power_dropout proc.");
2763                         Jim_Eval(interp, "power_dropout");
2764                         did_something = 1;
2765                 }
2766                 if (runPowerRestore) {
2767                         Jim_Eval(interp, "power_restore");
2768                         did_something = 1;
2769                 }
2770
2771                 if (did_something) {
2772                         /* clear detect flags */
2773                         sense_handler();
2774                 }
2775
2776                 /* clear action flags */
2777
2778                 runSrstAsserted = 0;
2779                 runSrstDeasserted = 0;
2780                 runPowerRestore = 0;
2781                 runPowerDropout = 0;
2782
2783                 recursive = 0;
2784         }
2785
2786         /* Poll targets for state changes unless that's globally disabled.
2787          * Skip targets that are currently disabled.
2788          */
2789         for (struct target *target = all_targets;
2790                         is_jtag_poll_safe() && target;
2791                         target = target->next) {
2792
2793                 if (!target_was_examined(target))
2794                         continue;
2795
2796                 if (!target->tap->enabled)
2797                         continue;
2798
2799                 if (target->backoff.times > target->backoff.count) {
2800                         /* do not poll this time as we failed previously */
2801                         target->backoff.count++;
2802                         continue;
2803                 }
2804                 target->backoff.count = 0;
2805
2806                 /* only poll target if we've got power and srst isn't asserted */
2807                 if (!powerDropout && !srstAsserted) {
2808                         /* polling may fail silently until the target has been examined */
2809                         retval = target_poll(target);
2810                         if (retval != ERROR_OK) {
2811                                 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2812                                 if (target->backoff.times * polling_interval < 5000) {
2813                                         target->backoff.times *= 2;
2814                                         target->backoff.times++;
2815                                 }
2816
2817                                 /* Tell GDB to halt the debugger. This allows the user to
2818                                  * run monitor commands to handle the situation.
2819                                  */
2820                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2821                         }
2822                         if (target->backoff.times > 0) {
2823                                 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
2824                                 target_reset_examined(target);
2825                                 retval = target_examine_one(target);
2826                                 /* Target examination could have failed due to unstable connection,
2827                                  * but we set the examined flag anyway to repoll it later */
2828                                 if (retval != ERROR_OK) {
2829                                         target->examined = true;
2830                                         LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
2831                                                  target->backoff.times * polling_interval);
2832                                         return retval;
2833                                 }
2834                         }
2835
2836                         /* Since we succeeded, we reset backoff count */
2837                         target->backoff.times = 0;
2838                 }
2839         }
2840
2841         return retval;
2842 }
2843
2844 COMMAND_HANDLER(handle_reg_command)
2845 {
2846         struct target *target;
2847         struct reg *reg = NULL;
2848         unsigned count = 0;
2849         char *value;
2850
2851         LOG_DEBUG("-");
2852
2853         target = get_current_target(CMD_CTX);
2854
2855         /* list all available registers for the current target */
2856         if (CMD_ARGC == 0) {
2857                 struct reg_cache *cache = target->reg_cache;
2858
2859                 count = 0;
2860                 while (cache) {
2861                         unsigned i;
2862
2863                         command_print(CMD, "===== %s", cache->name);
2864
2865                         for (i = 0, reg = cache->reg_list;
2866                                         i < cache->num_regs;
2867                                         i++, reg++, count++) {
2868                                 if (reg->exist == false)
2869                                         continue;
2870                                 /* only print cached values if they are valid */
2871                                 if (reg->valid) {
2872                                         value = buf_to_str(reg->value,
2873                                                         reg->size, 16);
2874                                         command_print(CMD,
2875                                                         "(%i) %s (/%" PRIu32 "): 0x%s%s",
2876                                                         count, reg->name,
2877                                                         reg->size, value,
2878                                                         reg->dirty
2879                                                                 ? " (dirty)"
2880                                                                 : "");
2881                                         free(value);
2882                                 } else {
2883                                         command_print(CMD, "(%i) %s (/%" PRIu32 ")",
2884                                                           count, reg->name,
2885                                                           reg->size) ;
2886                                 }
2887                         }
2888                         cache = cache->next;
2889                 }
2890
2891                 return ERROR_OK;
2892         }
2893
2894         /* access a single register by its ordinal number */
2895         if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2896                 unsigned num;
2897                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2898
2899                 struct reg_cache *cache = target->reg_cache;
2900                 count = 0;
2901                 while (cache) {
2902                         unsigned i;
2903                         for (i = 0; i < cache->num_regs; i++) {
2904                                 if (count++ == num) {
2905                                         reg = &cache->reg_list[i];
2906                                         break;
2907                                 }
2908                         }
2909                         if (reg)
2910                                 break;
2911                         cache = cache->next;
2912                 }
2913
2914                 if (!reg) {
2915                         command_print(CMD, "%i is out of bounds, the current target "
2916                                         "has only %i registers (0 - %i)", num, count, count - 1);
2917                         return ERROR_OK;
2918                 }
2919         } else {
2920                 /* access a single register by its name */
2921                 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2922
2923                 if (!reg)
2924                         goto not_found;
2925         }
2926
2927         assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2928
2929         if (!reg->exist)
2930                 goto not_found;
2931
2932         /* display a register */
2933         if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2934                         && (CMD_ARGV[1][0] <= '9')))) {
2935                 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2936                         reg->valid = 0;
2937
2938                 if (reg->valid == 0)
2939                         reg->type->get(reg);
2940                 value = buf_to_str(reg->value, reg->size, 16);
2941                 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2942                 free(value);
2943                 return ERROR_OK;
2944         }
2945
2946         /* set register value */
2947         if (CMD_ARGC == 2) {
2948                 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2949                 if (buf == NULL)
2950                         return ERROR_FAIL;
2951                 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2952
2953                 reg->type->set(reg, buf);
2954
2955                 value = buf_to_str(reg->value, reg->size, 16);
2956                 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2957                 free(value);
2958
2959                 free(buf);
2960
2961                 return ERROR_OK;
2962         }
2963
2964         return ERROR_COMMAND_SYNTAX_ERROR;
2965
2966 not_found:
2967         command_print(CMD, "register %s not found in current target", CMD_ARGV[0]);
2968         return ERROR_OK;
2969 }
2970
2971 COMMAND_HANDLER(handle_poll_command)
2972 {
2973         int retval = ERROR_OK;
2974         struct target *target = get_current_target(CMD_CTX);
2975
2976         if (CMD_ARGC == 0) {
2977                 command_print(CMD, "background polling: %s",
2978                                 jtag_poll_get_enabled() ? "on" : "off");
2979                 command_print(CMD, "TAP: %s (%s)",
2980                                 target->tap->dotted_name,
2981                                 target->tap->enabled ? "enabled" : "disabled");
2982                 if (!target->tap->enabled)
2983                         return ERROR_OK;
2984                 retval = target_poll(target);
2985                 if (retval != ERROR_OK)
2986                         return retval;
2987                 retval = target_arch_state(target);
2988                 if (retval != ERROR_OK)
2989                         return retval;
2990         } else if (CMD_ARGC == 1) {
2991                 bool enable;
2992                 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2993                 jtag_poll_set_enabled(enable);
2994         } else
2995                 return ERROR_COMMAND_SYNTAX_ERROR;
2996
2997         return retval;
2998 }
2999
3000 COMMAND_HANDLER(handle_wait_halt_command)
3001 {
3002         if (CMD_ARGC > 1)
3003                 return ERROR_COMMAND_SYNTAX_ERROR;
3004
3005         unsigned ms = DEFAULT_HALT_TIMEOUT;
3006         if (1 == CMD_ARGC) {
3007                 int retval = parse_uint(CMD_ARGV[0], &ms);
3008                 if (ERROR_OK != retval)
3009                         return ERROR_COMMAND_SYNTAX_ERROR;
3010         }
3011
3012         struct target *target = get_current_target(CMD_CTX);
3013         return target_wait_state(target, TARGET_HALTED, ms);
3014 }
3015
3016 /* wait for target state to change. The trick here is to have a low
3017  * latency for short waits and not to suck up all the CPU time
3018  * on longer waits.
3019  *
3020  * After 500ms, keep_alive() is invoked
3021  */
3022 int target_wait_state(struct target *target, enum target_state state, int ms)
3023 {
3024         int retval;
3025         int64_t then = 0, cur;
3026         bool once = true;
3027
3028         for (;;) {
3029                 retval = target_poll(target);
3030                 if (retval != ERROR_OK)
3031                         return retval;
3032                 if (target->state == state)
3033                         break;
3034                 cur = timeval_ms();
3035                 if (once) {
3036                         once = false;
3037                         then = timeval_ms();
3038                         LOG_DEBUG("waiting for target %s...",
3039                                 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
3040                 }
3041
3042                 if (cur-then > 500)
3043                         keep_alive();
3044
3045                 if ((cur-then) > ms) {
3046                         LOG_ERROR("timed out while waiting for target %s",
3047                                 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
3048                         return ERROR_FAIL;
3049                 }
3050         }
3051
3052         return ERROR_OK;
3053 }
3054
3055 COMMAND_HANDLER(handle_halt_command)
3056 {
3057         LOG_DEBUG("-");
3058
3059         struct target *target = get_current_target(CMD_CTX);
3060
3061         target->verbose_halt_msg = true;
3062
3063         int retval = target_halt(target);
3064         if (ERROR_OK != retval)
3065                 return retval;
3066
3067         if (CMD_ARGC == 1) {
3068                 unsigned wait_local;
3069                 retval = parse_uint(CMD_ARGV[0], &wait_local);
3070                 if (ERROR_OK != retval)
3071                         return ERROR_COMMAND_SYNTAX_ERROR;
3072                 if (!wait_local)
3073                         return ERROR_OK;
3074         }
3075
3076         return CALL_COMMAND_HANDLER(handle_wait_halt_command);
3077 }
3078
3079 COMMAND_HANDLER(handle_soft_reset_halt_command)
3080 {
3081         struct target *target = get_current_target(CMD_CTX);
3082
3083         LOG_USER("requesting target halt and executing a soft reset");
3084
3085         target_soft_reset_halt(target);
3086
3087         return ERROR_OK;
3088 }
3089
3090 COMMAND_HANDLER(handle_reset_command)
3091 {
3092         if (CMD_ARGC > 1)
3093                 return ERROR_COMMAND_SYNTAX_ERROR;
3094
3095         enum target_reset_mode reset_mode = RESET_RUN;
3096         if (CMD_ARGC == 1) {
3097                 const Jim_Nvp *n;
3098                 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
3099                 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
3100                         return ERROR_COMMAND_SYNTAX_ERROR;
3101                 reset_mode = n->value;
3102         }
3103
3104         /* reset *all* targets */
3105         return target_process_reset(CMD, reset_mode);
3106 }
3107
3108
3109 COMMAND_HANDLER(handle_resume_command)
3110 {
3111         int current = 1;
3112         if (CMD_ARGC > 1)
3113                 return ERROR_COMMAND_SYNTAX_ERROR;
3114
3115         struct target *target = get_current_target(CMD_CTX);
3116
3117         /* with no CMD_ARGV, resume from current pc, addr = 0,
3118          * with one arguments, addr = CMD_ARGV[0],
3119          * handle breakpoints, not debugging */
3120         target_addr_t addr = 0;
3121         if (CMD_ARGC == 1) {
3122                 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3123                 current = 0;
3124         }
3125
3126         return target_resume(target, current, addr, 1, 0);
3127 }
3128
3129 COMMAND_HANDLER(handle_step_command)
3130 {
3131         if (CMD_ARGC > 1)
3132                 return ERROR_COMMAND_SYNTAX_ERROR;
3133
3134         LOG_DEBUG("-");
3135
3136         /* with no CMD_ARGV, step from current pc, addr = 0,
3137          * with one argument addr = CMD_ARGV[0],
3138          * handle breakpoints, debugging */
3139         target_addr_t addr = 0;
3140         int current_pc = 1;
3141         if (CMD_ARGC == 1) {
3142                 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3143                 current_pc = 0;
3144         }
3145
3146         struct target *target = get_current_target(CMD_CTX);
3147
3148         return target->type->step(target, current_pc, addr, 1);
3149 }
3150
3151 void target_handle_md_output(struct command_invocation *cmd,
3152                 struct target *target, target_addr_t address, unsigned size,
3153                 unsigned count, const uint8_t *buffer)
3154 {
3155         const unsigned line_bytecnt = 32;
3156         unsigned line_modulo = line_bytecnt / size;
3157
3158         char output[line_bytecnt * 4 + 1];
3159         unsigned output_len = 0;
3160
3161         const char *value_fmt;
3162         switch (size) {
3163         case 8:
3164                 value_fmt = "%16.16"PRIx64" ";
3165                 break;
3166         case 4:
3167                 value_fmt = "%8.8"PRIx64" ";
3168                 break;
3169         case 2:
3170                 value_fmt = "%4.4"PRIx64" ";
3171                 break;
3172         case 1:
3173                 value_fmt = "%2.2"PRIx64" ";
3174                 break;
3175         default:
3176                 /* "can't happen", caller checked */
3177                 LOG_ERROR("invalid memory read size: %u", size);
3178                 return;
3179         }
3180
3181         for (unsigned i = 0; i < count; i++) {
3182                 if (i % line_modulo == 0) {
3183                         output_len += snprintf(output + output_len,
3184                                         sizeof(output) - output_len,
3185                                         TARGET_ADDR_FMT ": ",
3186                                         (address + (i * size)));
3187                 }
3188
3189                 uint64_t value = 0;
3190                 const uint8_t *value_ptr = buffer + i * size;
3191                 switch (size) {
3192                 case 8:
3193                         value = target_buffer_get_u64(target, value_ptr);
3194                         break;
3195                 case 4:
3196                         value = target_buffer_get_u32(target, value_ptr);
3197                         break;
3198                 case 2:
3199                         value = target_buffer_get_u16(target, value_ptr);
3200                         break;
3201                 case 1:
3202                         value = *value_ptr;
3203                 }
3204                 output_len += snprintf(output + output_len,
3205                                 sizeof(output) - output_len,
3206                                 value_fmt, value);
3207
3208                 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
3209                         command_print(cmd, "%s", output);
3210                         output_len = 0;
3211                 }
3212         }
3213 }
3214
3215 COMMAND_HANDLER(handle_md_command)
3216 {
3217         if (CMD_ARGC < 1)
3218                 return ERROR_COMMAND_SYNTAX_ERROR;
3219
3220         unsigned size = 0;
3221         switch (CMD_NAME[2]) {
3222         case 'd':
3223                 size = 8;
3224                 break;
3225         case 'w':
3226                 size = 4;
3227                 break;
3228         case 'h':
3229                 size = 2;
3230                 break;
3231         case 'b':
3232                 size = 1;
3233                 break;
3234         default:
3235                 return ERROR_COMMAND_SYNTAX_ERROR;
3236         }
3237
3238         bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3239         int (*fn)(struct target *target,
3240                         target_addr_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
3241         if (physical) {
3242                 CMD_ARGC--;
3243                 CMD_ARGV++;
3244                 fn = target_read_phys_memory;
3245         } else
3246                 fn = target_read_memory;
3247         if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
3248                 return ERROR_COMMAND_SYNTAX_ERROR;
3249
3250         target_addr_t address;
3251         COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3252
3253         unsigned count = 1;
3254         if (CMD_ARGC == 2)
3255                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3256
3257         uint8_t *buffer = calloc(count, size);
3258         if (buffer == NULL) {
3259                 LOG_ERROR("Failed to allocate md read buffer");
3260                 return ERROR_FAIL;
3261         }
3262
3263         struct target *target = get_current_target(CMD_CTX);
3264         int retval = fn(target, address, size, count, buffer);
3265         if (ERROR_OK == retval)
3266                 target_handle_md_output(CMD, target, address, size, count, buffer);
3267
3268         free(buffer);
3269
3270         return retval;
3271 }
3272
3273 typedef int (*target_write_fn)(struct target *target,
3274                 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3275
3276 static int target_fill_mem(struct target *target,
3277                 target_addr_t address,
3278                 target_write_fn fn,
3279                 unsigned data_size,
3280                 /* value */
3281                 uint64_t b,
3282                 /* count */
3283                 unsigned c)
3284 {
3285         /* We have to write in reasonably large chunks to be able
3286          * to fill large memory areas with any sane speed */
3287         const unsigned chunk_size = 16384;
3288         uint8_t *target_buf = malloc(chunk_size * data_size);
3289         if (target_buf == NULL) {
3290                 LOG_ERROR("Out of memory");
3291                 return ERROR_FAIL;
3292         }
3293
3294         for (unsigned i = 0; i < chunk_size; i++) {
3295                 switch (data_size) {
3296                 case 8:
3297                         target_buffer_set_u64(target, target_buf + i * data_size, b);
3298                         break;
3299                 case 4:
3300                         target_buffer_set_u32(target, target_buf + i * data_size, b);
3301                         break;
3302                 case 2:
3303                         target_buffer_set_u16(target, target_buf + i * data_size, b);
3304                         break;
3305                 case 1:
3306                         target_buffer_set_u8(target, target_buf + i * data_size, b);
3307                         break;
3308                 default:
3309                         exit(-1);
3310                 }
3311         }
3312
3313         int retval = ERROR_OK;
3314
3315         for (unsigned x = 0; x < c; x += chunk_size) {
3316                 unsigned current;
3317                 current = c - x;
3318                 if (current > chunk_size)
3319                         current = chunk_size;
3320                 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3321                 if (retval != ERROR_OK)
3322                         break;
3323                 /* avoid GDB timeouts */
3324                 keep_alive();
3325         }
3326         free(target_buf);
3327
3328         return retval;
3329 }
3330
3331
3332 COMMAND_HANDLER(handle_mw_command)
3333 {
3334         if (CMD_ARGC < 2)
3335                 return ERROR_COMMAND_SYNTAX_ERROR;
3336         bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3337         target_write_fn fn;
3338         if (physical) {
3339                 CMD_ARGC--;
3340                 CMD_ARGV++;
3341                 fn = target_write_phys_memory;
3342         } else
3343                 fn = target_write_memory;
3344         if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3345                 return ERROR_COMMAND_SYNTAX_ERROR;
3346
3347         target_addr_t address;
3348         COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3349
3350         uint64_t value;
3351         COMMAND_PARSE_NUMBER(u64, CMD_ARGV[1], value);
3352
3353         unsigned count = 1;
3354         if (CMD_ARGC == 3)
3355                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3356
3357         struct target *target = get_current_target(CMD_CTX);
3358         unsigned wordsize;
3359         switch (CMD_NAME[2]) {
3360                 case 'd':
3361                         wordsize = 8;
3362                         break;
3363                 case 'w':
3364                         wordsize = 4;
3365                         break;
3366                 case 'h':
3367                         wordsize = 2;
3368                         break;
3369                 case 'b':
3370                         wordsize = 1;
3371                         break;
3372                 default:
3373                         return ERROR_COMMAND_SYNTAX_ERROR;
3374         }
3375
3376         return target_fill_mem(target, address, fn, wordsize, value, count);
3377 }
3378
3379 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
3380                 target_addr_t *min_address, target_addr_t *max_address)
3381 {
3382         if (CMD_ARGC < 1 || CMD_ARGC > 5)
3383                 return ERROR_COMMAND_SYNTAX_ERROR;
3384
3385         /* a base address isn't always necessary,
3386          * default to 0x0 (i.e. don't relocate) */
3387         if (CMD_ARGC >= 2) {
3388                 target_addr_t addr;
3389                 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3390                 image->base_address = addr;
3391                 image->base_address_set = 1;
3392         } else
3393                 image->base_address_set = 0;
3394
3395         image->start_address_set = 0;
3396
3397         if (CMD_ARGC >= 4)
3398                 COMMAND_PARSE_ADDRESS(CMD_ARGV[3], *min_address);
3399         if (CMD_ARGC == 5) {
3400                 COMMAND_PARSE_ADDRESS(CMD_ARGV[4], *max_address);
3401                 /* use size (given) to find max (required) */
3402                 *max_address += *min_address;
3403         }
3404
3405         if (*min_address > *max_address)
3406                 return ERROR_COMMAND_SYNTAX_ERROR;
3407
3408         return ERROR_OK;
3409 }
3410
3411 COMMAND_HANDLER(handle_load_image_command)
3412 {
3413         uint8_t *buffer;
3414         size_t buf_cnt;
3415         uint32_t image_size;
3416         target_addr_t min_address = 0;
3417         target_addr_t max_address = -1;
3418         int i;
3419         struct image image;
3420
3421         int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
3422                         &image, &min_address, &max_address);
3423         if (ERROR_OK != retval)
3424                 return retval;
3425
3426         struct target *target = get_current_target(CMD_CTX);
3427
3428         struct duration bench;
3429         duration_start(&bench);
3430
3431         if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3432                 return ERROR_FAIL;
3433
3434         image_size = 0x0;
3435         retval = ERROR_OK;
3436         for (i = 0; i < image.num_sections; i++) {
3437                 buffer = malloc(image.sections[i].size);
3438                 if (buffer == NULL) {
3439                         command_print(CMD,
3440                                                   "error allocating buffer for section (%d bytes)",
3441                                                   (int)(image.sections[i].size));
3442                         retval = ERROR_FAIL;
3443                         break;
3444                 }
3445
3446                 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3447                 if (retval != ERROR_OK) {
3448                         free(buffer);
3449                         break;
3450                 }
3451
3452                 uint32_t offset = 0;
3453                 uint32_t length = buf_cnt;
3454
3455                 /* DANGER!!! beware of unsigned comparision here!!! */
3456
3457                 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3458                                 (image.sections[i].base_address < max_address)) {
3459
3460                         if (image.sections[i].base_address < min_address) {
3461                                 /* clip addresses below */
3462                                 offset += min_address-image.sections[i].base_address;
3463                                 length -= offset;
3464                         }
3465
3466                         if (image.sections[i].base_address + buf_cnt > max_address)
3467                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3468
3469                         retval = target_write_buffer(target,
3470                                         image.sections[i].base_address + offset, length, buffer + offset);
3471                         if (retval != ERROR_OK) {
3472                                 free(buffer);
3473                                 break;
3474                         }
3475                         image_size += length;
3476                         command_print(CMD, "%u bytes written at address " TARGET_ADDR_FMT "",
3477                                         (unsigned int)length,
3478                                         image.sections[i].base_address + offset);
3479                 }
3480
3481                 free(buffer);
3482         }
3483
3484         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3485                 command_print(CMD, "downloaded %" PRIu32 " bytes "
3486                                 "in %fs (%0.3f KiB/s)", image_size,
3487                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3488         }
3489
3490         image_close(&image);
3491
3492         return retval;
3493
3494 }
3495
3496 COMMAND_HANDLER(handle_dump_image_command)
3497 {
3498         struct fileio *fileio;
3499         uint8_t *buffer;
3500         int retval, retvaltemp;
3501         target_addr_t address, size;
3502         struct duration bench;
3503         struct target *target = get_current_target(CMD_CTX);
3504
3505         if (CMD_ARGC != 3)
3506                 return ERROR_COMMAND_SYNTAX_ERROR;
3507
3508         COMMAND_PARSE_ADDRESS(CMD_ARGV[1], address);
3509         COMMAND_PARSE_ADDRESS(CMD_ARGV[2], size);
3510
3511         uint32_t buf_size = (size > 4096) ? 4096 : size;
3512         buffer = malloc(buf_size);
3513         if (!buffer)
3514                 return ERROR_FAIL;
3515
3516         retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3517         if (retval != ERROR_OK) {
3518                 free(buffer);
3519                 return retval;
3520         }
3521
3522         duration_start(&bench);
3523
3524         while (size > 0) {
3525                 size_t size_written;
3526                 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3527                 retval = target_read_buffer(target, address, this_run_size, buffer);
3528                 if (retval != ERROR_OK)
3529                         break;
3530
3531                 retval = fileio_write(fileio, this_run_size, buffer, &size_written);
3532                 if (retval != ERROR_OK)
3533                         break;
3534
3535                 size -= this_run_size;
3536                 address += this_run_size;
3537         }
3538
3539         free(buffer);
3540
3541         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3542                 size_t filesize;
3543                 retval = fileio_size(fileio, &filesize);
3544                 if (retval != ERROR_OK)
3545                         return retval;
3546                 command_print(CMD,
3547                                 "dumped %zu bytes in %fs (%0.3f KiB/s)", filesize,
3548                                 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3549         }
3550
3551         retvaltemp = fileio_close(fileio);
3552         if (retvaltemp != ERROR_OK)
3553                 return retvaltemp;
3554
3555         return retval;
3556 }
3557
3558 enum verify_mode {
3559         IMAGE_TEST = 0,
3560         IMAGE_VERIFY = 1,
3561         IMAGE_CHECKSUM_ONLY = 2
3562 };
3563
3564 static COMMAND_HELPER(handle_verify_image_command_internal, enum verify_mode verify)
3565 {
3566         uint8_t *buffer;
3567         size_t buf_cnt;
3568         uint32_t image_size;
3569         int i;
3570         int retval;
3571         uint32_t checksum = 0;
3572         uint32_t mem_checksum = 0;
3573
3574         struct image image;
3575
3576         struct target *target = get_current_target(CMD_CTX);
3577
3578         if (CMD_ARGC < 1)
3579                 return ERROR_COMMAND_SYNTAX_ERROR;
3580
3581         if (!target) {
3582                 LOG_ERROR("no target selected");
3583                 return ERROR_FAIL;
3584         }
3585
3586         struct duration bench;
3587         duration_start(&bench);
3588
3589         if (CMD_ARGC >= 2) {
3590                 target_addr_t addr;
3591                 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3592                 image.base_address = addr;
3593                 image.base_address_set = 1;
3594         } else {
3595                 image.base_address_set = 0;
3596                 image.base_address = 0x0;
3597         }
3598
3599         image.start_address_set = 0;
3600
3601         retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3602         if (retval != ERROR_OK)
3603                 return retval;
3604
3605         image_size = 0x0;
3606         int diffs = 0;
3607         retval = ERROR_OK;
3608         for (i = 0; i < image.num_sections; i++) {
3609                 buffer = malloc(image.sections[i].size);
3610                 if (buffer == NULL) {
3611                         command_print(CMD,
3612                                         "error allocating buffer for section (%d bytes)",
3613                                         (int)(image.sections[i].size));
3614                         break;
3615                 }
3616                 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3617                 if (retval != ERROR_OK) {
3618                         free(buffer);
3619                         break;
3620                 }
3621
3622                 if (verify >= IMAGE_VERIFY) {
3623                         /* calculate checksum of image */
3624                         retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3625                         if (retval != ERROR_OK) {
3626                                 free(buffer);
3627                                 break;
3628                         }
3629
3630                         retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3631                         if (retval != ERROR_OK) {
3632                                 free(buffer);
3633                                 break;
3634                         }
3635                         if ((checksum != mem_checksum) && (verify == IMAGE_CHECKSUM_ONLY)) {
3636                                 LOG_ERROR("checksum mismatch");
3637                                 free(buffer);
3638                                 retval = ERROR_FAIL;
3639                                 goto done;
3640                         }
3641                         if (checksum != mem_checksum) {
3642                                 /* failed crc checksum, fall back to a binary compare */
3643                                 uint8_t *data;
3644
3645                                 if (diffs == 0)
3646                                         LOG_ERROR("checksum mismatch - attempting binary compare");
3647
3648                                 data = malloc(buf_cnt);
3649
3650                                 retval = target_read_buffer(target, image.sections[i].base_address, buf_cnt, data);
3651                                 if (retval == ERROR_OK) {
3652                                         uint32_t t;
3653                                         for (t = 0; t < buf_cnt; t++) {
3654                                                 if (data[t] != buffer[t]) {
3655                                                         command_print(CMD,
3656                                                                                   "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3657                                                                                   diffs,
3658                                                                                   (unsigned)(t + image.sections[i].base_address),
3659                                                                                   data[t],
3660                                                                                   buffer[t]);
3661                                                         if (diffs++ >= 127) {
3662                                                                 command_print(CMD, "More than 128 errors, the rest are not printed.");
3663                                                                 free(data);
3664                                                                 free(buffer);
3665                                                                 goto done;
3666                                                         }
3667                                                 }
3668                                                 keep_alive();
3669                                         }
3670                                 }
3671                                 free(data);
3672                         }
3673                 } else {
3674                         command_print(CMD, "address " TARGET_ADDR_FMT " length 0x%08zx",
3675                                                   image.sections[i].base_address,
3676                                                   buf_cnt);
3677                 }
3678
3679                 free(buffer);
3680                 image_size += buf_cnt;
3681         }
3682         if (diffs > 0)
3683                 command_print(CMD, "No more differences found.");
3684 done:
3685         if (diffs > 0)
3686                 retval = ERROR_FAIL;
3687         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3688                 command_print(CMD, "verified %" PRIu32 " bytes "
3689                                 "in %fs (%0.3f KiB/s)", image_size,
3690                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3691         }
3692
3693         image_close(&image);
3694
3695         return retval;
3696 }
3697
3698 COMMAND_HANDLER(handle_verify_image_checksum_command)
3699 {
3700         return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_CHECKSUM_ONLY);
3701 }
3702
3703 COMMAND_HANDLER(handle_verify_image_command)
3704 {
3705         return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_VERIFY);
3706 }
3707
3708 COMMAND_HANDLER(handle_test_image_command)
3709 {
3710         return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_TEST);
3711 }
3712
3713 static int handle_bp_command_list(struct command_invocation *cmd)
3714 {
3715         struct target *target = get_current_target(cmd->ctx);
3716         struct breakpoint *breakpoint = target->breakpoints;
3717         while (breakpoint) {
3718                 if (breakpoint->type == BKPT_SOFT) {
3719                         char *buf = buf_to_str(breakpoint->orig_instr,
3720                                         breakpoint->length, 16);
3721                         command_print(cmd, "IVA breakpoint: " TARGET_ADDR_FMT ", 0x%x, %i, 0x%s",
3722                                         breakpoint->address,
3723                                         breakpoint->length,
3724                                         breakpoint->set, buf);
3725                         free(buf);
3726                 } else {
3727                         if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3728                                 command_print(cmd, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3729                                                         breakpoint->asid,
3730                                                         breakpoint->length, breakpoint->set);
3731                         else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3732                                 command_print(cmd, "Hybrid breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3733                                                         breakpoint->address,
3734                                                         breakpoint->length, breakpoint->set);
3735                                 command_print(cmd, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3736                                                         breakpoint->asid);
3737                         } else
3738                                 command_print(cmd, "Breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3739                                                         breakpoint->address,
3740                                                         breakpoint->length, breakpoint->set);
3741                 }
3742
3743                 breakpoint = breakpoint->next;
3744         }
3745         return ERROR_OK;
3746 }
3747
3748 static int handle_bp_command_set(struct command_invocation *cmd,
3749                 target_addr_t addr, uint32_t asid, uint32_t length, int hw)
3750 {
3751         struct target *target = get_current_target(cmd->ctx);
3752         int retval;
3753
3754         if (asid == 0) {
3755                 retval = breakpoint_add(target, addr, length, hw);
3756                 /* error is always logged in breakpoint_add(), do not print it again */
3757                 if (ERROR_OK == retval)
3758                         command_print(cmd, "breakpoint set at " TARGET_ADDR_FMT "", addr);
3759
3760         } else if (addr == 0) {
3761                 if (target->type->add_context_breakpoint == NULL) {
3762                         LOG_ERROR("Context breakpoint not available");
3763                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
3764                 }
3765                 retval = context_breakpoint_add(target, asid, length, hw);
3766                 /* error is always logged in context_breakpoint_add(), do not print it again */
3767                 if (ERROR_OK == retval)
3768                         command_print(cmd, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3769
3770         } else {
3771                 if (target->type->add_hybrid_breakpoint == NULL) {
3772                         LOG_ERROR("Hybrid breakpoint not available");
3773                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
3774                 }
3775                 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3776                 /* error is always logged in hybrid_breakpoint_add(), do not print it again */
3777                 if (ERROR_OK == retval)
3778                         command_print(cmd, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3779         }
3780         return retval;
3781 }
3782
3783 COMMAND_HANDLER(handle_bp_command)
3784 {
3785         target_addr_t addr;
3786         uint32_t asid;
3787         uint32_t length;
3788         int hw = BKPT_SOFT;
3789
3790         switch (CMD_ARGC) {
3791                 case 0:
3792                         return handle_bp_command_list(CMD);
3793
3794                 case 2:
3795                         asid = 0;
3796                         COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3797                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3798                         return handle_bp_command_set(CMD, addr, asid, length, hw);
3799
3800                 case 3:
3801                         if (strcmp(CMD_ARGV[2], "hw") == 0) {
3802                                 hw = BKPT_HARD;
3803                                 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3804                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3805                                 asid = 0;
3806                                 return handle_bp_command_set(CMD, addr, asid, length, hw);
3807                         } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3808                                 hw = BKPT_HARD;
3809                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3810                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3811                                 addr = 0;
3812                                 return handle_bp_command_set(CMD, addr, asid, length, hw);
3813                         }
3814                         /* fallthrough */
3815                 case 4:
3816                         hw = BKPT_HARD;
3817                         COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3818                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3819                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3820                         return handle_bp_command_set(CMD, addr, asid, length, hw);
3821
3822                 default:
3823                         return ERROR_COMMAND_SYNTAX_ERROR;
3824         }
3825 }
3826
3827 COMMAND_HANDLER(handle_rbp_command)
3828 {
3829         if (CMD_ARGC != 1)
3830                 return ERROR_COMMAND_SYNTAX_ERROR;
3831
3832         target_addr_t addr;
3833         COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3834
3835         struct target *target = get_current_target(CMD_CTX);
3836         breakpoint_remove(target, addr);
3837
3838         return ERROR_OK;
3839 }
3840
3841 COMMAND_HANDLER(handle_wp_command)
3842 {
3843         struct target *target = get_current_target(CMD_CTX);
3844
3845         if (CMD_ARGC == 0) {
3846                 struct watchpoint *watchpoint = target->watchpoints;
3847
3848                 while (watchpoint) {
3849                         command_print(CMD, "address: " TARGET_ADDR_FMT
3850                                         ", len: 0x%8.8" PRIx32
3851                                         ", r/w/a: %i, value: 0x%8.8" PRIx32
3852                                         ", mask: 0x%8.8" PRIx32,
3853                                         watchpoint->address,
3854                                         watchpoint->length,
3855                                         (int)watchpoint->rw,
3856                                         watchpoint->value,
3857                                         watchpoint->mask);
3858                         watchpoint = watchpoint->next;
3859                 }
3860                 return ERROR_OK;
3861         }
3862
3863         enum watchpoint_rw type = WPT_ACCESS;
3864         uint32_t addr = 0;
3865         uint32_t length = 0;
3866         uint32_t data_value = 0x0;
3867         uint32_t data_mask = 0xffffffff;
3868
3869         switch (CMD_ARGC) {
3870         case 5:
3871                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3872                 /* fall through */
3873         case 4:
3874                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3875                 /* fall through */
3876         case 3:
3877                 switch (CMD_ARGV[2][0]) {
3878                 case 'r':
3879                         type = WPT_READ;
3880                         break;
3881                 case 'w':
3882                         type = WPT_WRITE;
3883                         break;
3884                 case 'a':
3885                         type = WPT_ACCESS;
3886                         break;
3887                 default:
3888                         LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3889                         return ERROR_COMMAND_SYNTAX_ERROR;
3890                 }
3891                 /* fall through */
3892         case 2:
3893                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3894                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3895                 break;
3896
3897         default:
3898                 return ERROR_COMMAND_SYNTAX_ERROR;
3899         }
3900
3901         int retval = watchpoint_add(target, addr, length, type,
3902                         data_value, data_mask);
3903         if (ERROR_OK != retval)
3904                 LOG_ERROR("Failure setting watchpoints");
3905
3906         return retval;
3907 }
3908
3909 COMMAND_HANDLER(handle_rwp_command)
3910 {
3911         if (CMD_ARGC != 1)
3912                 return ERROR_COMMAND_SYNTAX_ERROR;
3913
3914         uint32_t addr;
3915         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3916
3917         struct target *target = get_current_target(CMD_CTX);
3918         watchpoint_remove(target, addr);
3919
3920         return ERROR_OK;
3921 }
3922
3923 /**
3924  * Translate a virtual address to a physical address.
3925  *
3926  * The low-level target implementation must have logged a detailed error
3927  * which is forwarded to telnet/GDB session.
3928  */
3929 COMMAND_HANDLER(handle_virt2phys_command)
3930 {
3931         if (CMD_ARGC != 1)
3932                 return ERROR_COMMAND_SYNTAX_ERROR;
3933
3934         target_addr_t va;
3935         COMMAND_PARSE_ADDRESS(CMD_ARGV[0], va);
3936         target_addr_t pa;
3937
3938         struct target *target = get_current_target(CMD_CTX);
3939         int retval = target->type->virt2phys(target, va, &pa);
3940         if (retval == ERROR_OK)
3941                 command_print(CMD, "Physical address " TARGET_ADDR_FMT "", pa);
3942
3943         return retval;
3944 }
3945
3946 static void writeData(FILE *f, const void *data, size_t len)
3947 {
3948         size_t written = fwrite(data, 1, len, f);
3949         if (written != len)
3950                 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3951 }
3952
3953 static void writeLong(FILE *f, int l, struct target *target)
3954 {
3955         uint8_t val[4];
3956
3957         target_buffer_set_u32(target, val, l);
3958         writeData(f, val, 4);
3959 }
3960
3961 static void writeString(FILE *f, char *s)
3962 {
3963         writeData(f, s, strlen(s));
3964 }
3965
3966 typedef unsigned char UNIT[2];  /* unit of profiling */
3967
3968 /* Dump a gmon.out histogram file. */
3969 static void write_gmon(uint32_t *samples, uint32_t sampleNum, const char *filename, bool with_range,
3970                         uint32_t start_address, uint32_t end_address, struct target *target, uint32_t duration_ms)
3971 {
3972         uint32_t i;
3973         FILE *f = fopen(filename, "w");
3974         if (f == NULL)
3975                 return;
3976         writeString(f, "gmon");
3977         writeLong(f, 0x00000001, target); /* Version */
3978         writeLong(f, 0, target); /* padding */
3979         writeLong(f, 0, target); /* padding */
3980         writeLong(f, 0, target); /* padding */
3981
3982         uint8_t zero = 0;  /* GMON_TAG_TIME_HIST */
3983         writeData(f, &zero, 1);
3984
3985         /* figure out bucket size */
3986         uint32_t min;
3987         uint32_t max;
3988         if (with_range) {
3989                 min = start_address;
3990                 max = end_address;
3991         } else {
3992                 min = samples[0];
3993                 max = samples[0];
3994                 for (i = 0; i < sampleNum; i++) {
3995                         if (min > samples[i])
3996                                 min = samples[i];
3997                         if (max < samples[i])
3998                                 max = samples[i];
3999                 }
4000
4001                 /* max should be (largest sample + 1)
4002                  * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
4003                 max++;
4004         }
4005
4006         int addressSpace = max - min;
4007         assert(addressSpace >= 2);
4008
4009         /* FIXME: What is the reasonable number of buckets?
4010          * The profiling result will be more accurate if there are enough buckets. */
4011         static const uint32_t maxBuckets = 128 * 1024; /* maximum buckets. */
4012         uint32_t numBuckets = addressSpace / sizeof(UNIT);
4013         if (numBuckets > maxBuckets)
4014                 numBuckets = maxBuckets;
4015         int *buckets = malloc(sizeof(int) * numBuckets);
4016         if (buckets == NULL) {
4017                 fclose(f);
4018                 return;
4019         }
4020         memset(buckets, 0, sizeof(int) * numBuckets);
4021         for (i = 0; i < sampleNum; i++) {
4022                 uint32_t address = samples[i];
4023
4024                 if ((address < min) || (max <= address))
4025                         continue;
4026
4027                 long long a = address - min;
4028                 long long b = numBuckets;
4029                 long long c = addressSpace;
4030                 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
4031                 buckets[index_t]++;
4032         }
4033
4034         /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
4035         writeLong(f, min, target);                      /* low_pc */
4036         writeLong(f, max, target);                      /* high_pc */
4037         writeLong(f, numBuckets, target);       /* # of buckets */
4038         float sample_rate = sampleNum / (duration_ms / 1000.0);
4039         writeLong(f, sample_rate, target);
4040         writeString(f, "seconds");
4041         for (i = 0; i < (15-strlen("seconds")); i++)
4042                 writeData(f, &zero, 1);
4043         writeString(f, "s");
4044
4045         /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
4046
4047         char *data = malloc(2 * numBuckets);
4048         if (data != NULL) {
4049                 for (i = 0; i < numBuckets; i++) {
4050                         int val;
4051                         val = buckets[i];
4052                         if (val > 65535)
4053                                 val = 65535;
4054                         data[i * 2] = val&0xff;
4055                         data[i * 2 + 1] = (val >> 8) & 0xff;
4056                 }
4057                 free(buckets);
4058                 writeData(f, data, numBuckets * 2);
4059                 free(data);
4060         } else
4061                 free(buckets);
4062
4063         fclose(f);
4064 }
4065
4066 /* profiling samples the CPU PC as quickly as OpenOCD is able,
4067  * which will be used as a random sampling of PC */
4068 COMMAND_HANDLER(handle_profile_command)
4069 {
4070         struct target *target = get_current_target(CMD_CTX);
4071
4072         if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
4073                 return ERROR_COMMAND_SYNTAX_ERROR;
4074
4075         const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
4076         uint32_t offset;
4077         uint32_t num_of_samples;
4078         int retval = ERROR_OK;
4079
4080         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
4081
4082         uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
4083         if (samples == NULL) {
4084                 LOG_ERROR("No memory to store samples.");
4085                 return ERROR_FAIL;
4086         }
4087
4088         uint64_t timestart_ms = timeval_ms();
4089         /**
4090          * Some cores let us sample the PC without the
4091          * annoying halt/resume step; for example, ARMv7 PCSR.
4092          * Provide a way to use that more efficient mechanism.
4093          */
4094         retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
4095                                 &num_of_samples, offset);
4096         if (retval != ERROR_OK) {
4097                 free(samples);
4098                 return retval;
4099         }
4100         uint32_t duration_ms = timeval_ms() - timestart_ms;
4101
4102         assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
4103
4104         retval = target_poll(target);
4105         if (retval != ERROR_OK) {
4106                 free(samples);
4107                 return retval;
4108         }
4109         if (target->state == TARGET_RUNNING) {
4110                 retval = target_halt(target);
4111                 if (retval != ERROR_OK) {
4112                         free(samples);
4113                         return retval;
4114                 }
4115         }
4116
4117         retval = target_poll(target);
4118         if (retval != ERROR_OK) {
4119                 free(samples);
4120                 return retval;
4121         }
4122
4123         uint32_t start_address = 0;
4124         uint32_t end_address = 0;
4125         bool with_range = false;
4126         if (CMD_ARGC == 4) {
4127                 with_range = true;
4128                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
4129                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
4130         }
4131
4132         write_gmon(samples, num_of_samples, CMD_ARGV[1],
4133                    with_range, start_address, end_address, target, duration_ms);
4134         command_print(CMD, "Wrote %s", CMD_ARGV[1]);
4135
4136         free(samples);
4137         return retval;
4138 }
4139
4140 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
4141 {
4142         char *namebuf;
4143         Jim_Obj *nameObjPtr, *valObjPtr;
4144         int result;
4145
4146         namebuf = alloc_printf("%s(%d)", varname, idx);
4147         if (!namebuf)
4148                 return JIM_ERR;
4149
4150         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
4151         valObjPtr = Jim_NewIntObj(interp, val);
4152         if (!nameObjPtr || !valObjPtr) {
4153                 free(namebuf);
4154                 return JIM_ERR;
4155         }
4156
4157         Jim_IncrRefCount(nameObjPtr);
4158         Jim_IncrRefCount(valObjPtr);
4159         result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
4160         Jim_DecrRefCount(interp, nameObjPtr);
4161         Jim_DecrRefCount(interp, valObjPtr);
4162         free(namebuf);
4163         /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
4164         return result;
4165 }
4166
4167 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4168 {
4169         struct command_context *context;
4170         struct target *target;
4171
4172         context = current_command_context(interp);
4173         assert(context != NULL);
4174
4175         target = get_current_target(context);
4176         if (target == NULL) {
4177                 LOG_ERROR("mem2array: no current target");
4178                 return JIM_ERR;
4179         }
4180
4181         return target_mem2array(interp, target, argc - 1, argv + 1);
4182 }
4183
4184 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
4185 {
4186         long l;
4187         uint32_t width;
4188         int len;
4189         uint32_t addr;
4190         uint32_t count;
4191         uint32_t v;
4192         const char *varname;
4193         const char *phys;
4194         bool is_phys;
4195         int  n, e, retval;
4196         uint32_t i;
4197
4198         /* argv[1] = name of array to receive the data
4199          * argv[2] = desired width
4200          * argv[3] = memory address
4201          * argv[4] = count of times to read
4202          */
4203
4204         if (argc < 4 || argc > 5) {
4205                 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4206                 return JIM_ERR;
4207         }
4208         varname = Jim_GetString(argv[0], &len);
4209         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
4210
4211         e = Jim_GetLong(interp, argv[1], &l);
4212         width = l;
4213         if (e != JIM_OK)
4214                 return e;
4215
4216         e = Jim_GetLong(interp, argv[2], &l);
4217         addr = l;
4218         if (e != JIM_OK)
4219                 return e;
4220         e = Jim_GetLong(interp, argv[3], &l);
4221         len = l;
4222         if (e != JIM_OK)
4223                 return e;
4224         is_phys = false;
4225         if (argc > 4) {
4226                 phys = Jim_GetString(argv[4], &n);
4227                 if (!strncmp(phys, "phys", n))
4228                         is_phys = true;
4229                 else
4230                         return JIM_ERR;
4231         }
4232         switch (width) {
4233                 case 8:
4234                         width = 1;
4235                         break;
4236                 case 16:
4237                         width = 2;
4238                         break;
4239                 case 32:
4240                         width = 4;
4241                         break;
4242                 default:
4243                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4244                         Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
4245                         return JIM_ERR;
4246         }
4247         if (len == 0) {
4248                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4249                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
4250                 return JIM_ERR;
4251         }
4252         if ((addr + (len * width)) < addr) {
4253                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4254                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
4255                 return JIM_ERR;
4256         }
4257         /* absurd transfer size? */
4258         if (len > 65536) {
4259                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4260                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
4261                 return JIM_ERR;
4262         }
4263
4264         if ((width == 1) ||
4265                 ((width == 2) && ((addr & 1) == 0)) ||
4266                 ((width == 4) && ((addr & 3) == 0))) {
4267                 /* all is well */
4268         } else {
4269                 char buf[100];
4270                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4271                 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
4272                                 addr,
4273                                 width);
4274                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4275                 return JIM_ERR;
4276         }
4277
4278         /* Transfer loop */
4279
4280         /* index counter */
4281         n = 0;
4282
4283         size_t buffersize = 4096;
4284         uint8_t *buffer = malloc(buffersize);
4285         if (buffer == NULL)
4286                 return JIM_ERR;
4287
4288         /* assume ok */
4289         e = JIM_OK;
4290         while (len) {
4291                 /* Slurp... in buffer size chunks */
4292
4293                 count = len; /* in objects.. */
4294                 if (count > (buffersize / width))
4295                         count = (buffersize / width);
4296
4297                 if (is_phys)
4298                         retval = target_read_phys_memory(target, addr, width, count, buffer);
4299                 else
4300                         retval = target_read_memory(target, addr, width, count, buffer);
4301                 if (retval != ERROR_OK) {
4302                         /* BOO !*/
4303                         LOG_ERROR("mem2array: Read @ 0x%08" PRIx32 ", w=%" PRId32 ", cnt=%" PRId32 ", failed",
4304                                           addr,
4305                                           width,
4306                                           count);
4307                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4308                         Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
4309                         e = JIM_ERR;
4310                         break;
4311                 } else {
4312                         v = 0; /* shut up gcc */
4313                         for (i = 0; i < count ; i++, n++) {
4314                                 switch (width) {
4315                                         case 4:
4316                                                 v = target_buffer_get_u32(target, &buffer[i*width]);
4317                                                 break;
4318                                         case 2:
4319                                                 v = target_buffer_get_u16(target, &buffer[i*width]);
4320                                                 break;
4321                                         case 1:
4322                                                 v = buffer[i] & 0x0ff;
4323                                                 break;
4324                                 }
4325                                 new_int_array_element(interp, varname, n, v);
4326                         }
4327                         len -= count;
4328                         addr += count * width;
4329                 }
4330         }
4331
4332         free(buffer);
4333
4334         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4335
4336         return e;
4337 }
4338
4339 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
4340 {
4341         char *namebuf;
4342         Jim_Obj *nameObjPtr, *valObjPtr;
4343         int result;
4344         long l;
4345
4346         namebuf = alloc_printf("%s(%d)", varname, idx);
4347         if (!namebuf)
4348                 return JIM_ERR;
4349
4350         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
4351         if (!nameObjPtr) {
4352                 free(namebuf);
4353                 return JIM_ERR;
4354         }
4355
4356         Jim_IncrRefCount(nameObjPtr);
4357         valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
4358         Jim_DecrRefCount(interp, nameObjPtr);
4359         free(namebuf);
4360         if (valObjPtr == NULL)
4361                 return JIM_ERR;
4362
4363         result = Jim_GetLong(interp, valObjPtr, &l);
4364         /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
4365         *val = l;
4366         return result;
4367 }
4368
4369 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4370 {
4371         struct command_context *context;
4372         struct target *target;
4373
4374         context = current_command_context(interp);
4375         assert(context != NULL);
4376
4377         target = get_current_target(context);
4378         if (target == NULL) {
4379                 LOG_ERROR("array2mem: no current target");
4380                 return JIM_ERR;
4381         }
4382
4383         return target_array2mem(interp, target, argc-1, argv + 1);
4384 }
4385
4386 static int target_array2mem(Jim_Interp *interp, struct target *target,
4387                 int argc, Jim_Obj *const *argv)
4388 {
4389         long l;
4390         uint32_t width;
4391         int len;
4392         uint32_t addr;
4393         uint32_t count;
4394         uint32_t v;
4395         const char *varname;
4396         const char *phys;
4397         bool is_phys;
4398         int  n, e, retval;
4399         uint32_t i;
4400
4401         /* argv[1] = name of array to get the data
4402          * argv[2] = desired width
4403          * argv[3] = memory address
4404          * argv[4] = count to write
4405          */
4406         if (argc < 4 || argc > 5) {
4407                 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4408                 return JIM_ERR;
4409         }
4410         varname = Jim_GetString(argv[0], &len);
4411         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
4412
4413         e = Jim_GetLong(interp, argv[1], &l);
4414         width = l;
4415         if (e != JIM_OK)
4416                 return e;
4417
4418         e = Jim_GetLong(interp, argv[2], &l);
4419         addr = l;
4420         if (e != JIM_OK)
4421                 return e;
4422         e = Jim_GetLong(interp, argv[3], &l);
4423         len = l;
4424         if (e != JIM_OK)
4425                 return e;
4426         is_phys = false;
4427         if (argc > 4) {
4428                 phys = Jim_GetString(argv[4], &n);
4429                 if (!strncmp(phys, "phys", n))
4430                         is_phys = true;
4431                 else
4432                         return JIM_ERR;
4433         }
4434         switch (width) {
4435                 case 8:
4436                         width = 1;
4437                         break;
4438                 case 16:
4439                         width = 2;
4440                         break;
4441                 case 32:
4442                         width = 4;
4443                         break;
4444                 default:
4445                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4446                         Jim_AppendStrings(interp, Jim_GetResult(interp),
4447                                         "Invalid width param, must be 8/16/32", NULL);
4448                         return JIM_ERR;
4449         }
4450         if (len == 0) {
4451                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4452                 Jim_AppendStrings(interp, Jim_GetResult(interp),
4453                                 "array2mem: zero width read?", NULL);
4454                 return JIM_ERR;
4455         }
4456         if ((addr + (len * width)) < addr) {
4457                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4458                 Jim_AppendStrings(interp, Jim_GetResult(interp),
4459                                 "array2mem: addr + len - wraps to zero?", NULL);
4460                 return JIM_ERR;
4461         }
4462         /* absurd transfer size? */
4463         if (len > 65536) {
4464                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4465                 Jim_AppendStrings(interp, Jim_GetResult(interp),
4466                                 "array2mem: absurd > 64K item request", NULL);
4467                 return JIM_ERR;
4468         }
4469
4470         if ((width == 1) ||
4471                 ((width == 2) && ((addr & 1) == 0)) ||
4472                 ((width == 4) && ((addr & 3) == 0))) {
4473                 /* all is well */
4474         } else {
4475                 char buf[100];
4476                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4477                 sprintf(buf, "array2mem address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
4478                                 addr,
4479                                 width);
4480                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4481                 return JIM_ERR;
4482         }
4483
4484         /* Transfer loop */
4485
4486         /* index counter */
4487         n = 0;
4488         /* assume ok */
4489         e = JIM_OK;
4490
4491         size_t buffersize = 4096;
4492         uint8_t *buffer = malloc(buffersize);
4493         if (buffer == NULL)
4494                 return JIM_ERR;
4495
4496         while (len) {
4497                 /* Slurp... in buffer size chunks */
4498
4499                 count = len; /* in objects.. */
4500                 if (count > (buffersize / width))
4501                         count = (buffersize / width);
4502
4503                 v = 0; /* shut up gcc */
4504                 for (i = 0; i < count; i++, n++) {
4505                         get_int_array_element(interp, varname, n, &v);
4506                         switch (width) {
4507                         case 4:
4508                                 target_buffer_set_u32(target, &buffer[i * width], v);
4509                                 break;
4510                         case 2:
4511                                 target_buffer_set_u16(target, &buffer[i * width], v);
4512                                 break;
4513                         case 1:
4514                                 buffer[i] = v & 0x0ff;
4515                                 break;
4516                         }
4517                 }
4518                 len -= count;
4519
4520                 if (is_phys)
4521                         retval = target_write_phys_memory(target, addr, width, count, buffer);
4522                 else
4523                         retval = target_write_memory(target, addr, width, count, buffer);
4524                 if (retval != ERROR_OK) {
4525                         /* BOO !*/
4526                         LOG_ERROR("array2mem: Write @ 0x%08" PRIx32 ", w=%" PRId32 ", cnt=%" PRId32 ", failed",
4527                                           addr,
4528                                           width,
4529                                           count);
4530                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4531                         Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4532                         e = JIM_ERR;
4533                         break;
4534                 }
4535                 addr += count * width;
4536         }
4537
4538         free(buffer);
4539
4540         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4541
4542         return e;
4543 }
4544
4545 /* FIX? should we propagate errors here rather than printing them
4546  * and continuing?
4547  */
4548 void target_handle_event(struct target *target, enum target_event e)
4549 {
4550         struct target_event_action *teap;
4551         int retval;
4552
4553         for (teap = target->event_action; teap != NULL; teap = teap->next) {
4554                 if (teap->event == e) {
4555                         LOG_DEBUG("target(%d): %s (%s) event: %d (%s) action: %s",
4556                                            target->target_number,
4557                                            target_name(target),
4558                                            target_type_name(target),
4559                                            e,
4560                                            Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
4561                                            Jim_GetString(teap->body, NULL));
4562
4563                         /* Override current target by the target an event
4564                          * is issued from (lot of scripts need it).
4565                          * Return back to previous override as soon
4566                          * as the handler processing is done */
4567                         struct command_context *cmd_ctx = current_command_context(teap->interp);
4568                         struct target *saved_target_override = cmd_ctx->current_target_override;
4569                         cmd_ctx->current_target_override = target;
4570                         retval = Jim_EvalObj(teap->interp, teap->body);
4571
4572                         if (retval == JIM_RETURN)
4573                                 retval = teap->interp->returnCode;
4574
4575                         if (retval != JIM_OK) {
4576                                 Jim_MakeErrorMessage(teap->interp);
4577                                 LOG_USER("Error executing event %s on target %s:\n%s",
4578                                                   Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
4579                                                   target_name(target),
4580                                                   Jim_GetString(Jim_GetResult(teap->interp), NULL));
4581                                 /* clean both error code and stacktrace before return */
4582                                 Jim_Eval(teap->interp, "error \"\" \"\"");
4583                         }
4584
4585                         cmd_ctx->current_target_override = saved_target_override;
4586                 }
4587         }
4588 }
4589
4590 /**
4591  * Returns true only if the target has a handler for the specified event.
4592  */
4593 bool target_has_event_action(struct target *target, enum target_event event)
4594 {
4595         struct target_event_action *teap;
4596
4597         for (teap = target->event_action; teap != NULL; teap = teap->next) {
4598                 if (teap->event == event)
4599                         return true;
4600         }
4601         return false;
4602 }
4603
4604 enum target_cfg_param {
4605         TCFG_TYPE,
4606         TCFG_EVENT,
4607         TCFG_WORK_AREA_VIRT,
4608         TCFG_WORK_AREA_PHYS,
4609         TCFG_WORK_AREA_SIZE,
4610         TCFG_WORK_AREA_BACKUP,
4611         TCFG_ENDIAN,
4612         TCFG_COREID,
4613         TCFG_CHAIN_POSITION,
4614         TCFG_DBGBASE,
4615         TCFG_RTOS,
4616         TCFG_DEFER_EXAMINE,
4617         TCFG_GDB_PORT,
4618 };
4619
4620 static Jim_Nvp nvp_config_opts[] = {
4621         { .name = "-type",             .value = TCFG_TYPE },
4622         { .name = "-event",            .value = TCFG_EVENT },
4623         { .name = "-work-area-virt",   .value = TCFG_WORK_AREA_VIRT },
4624         { .name = "-work-area-phys",   .value = TCFG_WORK_AREA_PHYS },
4625         { .name = "-work-area-size",   .value = TCFG_WORK_AREA_SIZE },
4626         { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4627         { .name = "-endian" ,          .value = TCFG_ENDIAN },
4628         { .name = "-coreid",           .value = TCFG_COREID },
4629         { .name = "-chain-position",   .value = TCFG_CHAIN_POSITION },
4630         { .name = "-dbgbase",          .value = TCFG_DBGBASE },
4631         { .name = "-rtos",             .value = TCFG_RTOS },
4632         { .name = "-defer-examine",    .value = TCFG_DEFER_EXAMINE },
4633         { .name = "-gdb-port",         .value = TCFG_GDB_PORT },
4634         { .name = NULL, .value = -1 }
4635 };
4636
4637 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
4638 {
4639         Jim_Nvp *n;
4640         Jim_Obj *o;
4641         jim_wide w;
4642         int e;
4643
4644         /* parse config or cget options ... */
4645         while (goi->argc > 0) {
4646                 Jim_SetEmptyResult(goi->interp);
4647                 /* Jim_GetOpt_Debug(goi); */
4648
4649                 if (target->type->target_jim_configure) {
4650                         /* target defines a configure function */
4651                         /* target gets first dibs on parameters */
4652                         e = (*(target->type->target_jim_configure))(target, goi);
4653                         if (e == JIM_OK) {
4654                                 /* more? */
4655                                 continue;
4656                         }
4657                         if (e == JIM_ERR) {
4658                                 /* An error */
4659                                 return e;
4660                         }
4661                         /* otherwise we 'continue' below */
4662                 }
4663                 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
4664                 if (e != JIM_OK) {
4665                         Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
4666                         return e;
4667                 }
4668                 switch (n->value) {
4669                 case TCFG_TYPE:
4670                         /* not setable */
4671                         if (goi->isconfigure) {
4672                                 Jim_SetResultFormatted(goi->interp,
4673                                                 "not settable: %s", n->name);
4674                                 return JIM_ERR;
4675                         } else {
4676 no_params:
4677                                 if (goi->argc != 0) {
4678                                         Jim_WrongNumArgs(goi->interp,
4679                                                         goi->argc, goi->argv,
4680                                                         "NO PARAMS");
4681                                         return JIM_ERR;
4682                                 }
4683                         }
4684                         Jim_SetResultString(goi->interp,
4685                                         target_type_name(target), -1);
4686                         /* loop for more */
4687                         break;
4688                 case TCFG_EVENT:
4689                         if (goi->argc == 0) {
4690                                 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4691                                 return JIM_ERR;
4692                         }
4693
4694                         e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4695                         if (e != JIM_OK) {
4696                                 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4697                                 return e;
4698                         }
4699
4700                         if (goi->isconfigure) {
4701                                 if (goi->argc != 1) {
4702                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4703                                         return JIM_ERR;
4704                                 }
4705                         } else {
4706                                 if (goi->argc != 0) {
4707                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4708                                         return JIM_ERR;
4709                                 }
4710                         }
4711
4712                         {
4713                                 struct target_event_action *teap;
4714
4715                                 teap = target->event_action;
4716                                 /* replace existing? */
4717                                 while (teap) {
4718                                         if (teap->event == (enum target_event)n->value)
4719                                                 break;
4720                                         teap = teap->next;
4721                                 }
4722
4723                                 if (goi->isconfigure) {
4724                                         bool replace = true;
4725                                         if (teap == NULL) {
4726                                                 /* create new */
4727                                                 teap = calloc(1, sizeof(*teap));
4728                                                 replace = false;
4729                                         }
4730                                         teap->event = n->value;
4731                                         teap->interp = goi->interp;
4732                                         Jim_GetOpt_Obj(goi, &o);
4733                                         if (teap->body)
4734                                                 Jim_DecrRefCount(teap->interp, teap->body);
4735                                         teap->body  = Jim_DuplicateObj(goi->interp, o);
4736                                         /*
4737                                          * FIXME:
4738                                          *     Tcl/TK - "tk events" have a nice feature.
4739                                          *     See the "BIND" command.
4740                                          *    We should support that here.
4741                                          *     You can specify %X and %Y in the event code.
4742                                          *     The idea is: %T - target name.
4743                                          *     The idea is: %N - target number
4744                                          *     The idea is: %E - event name.
4745                                          */
4746                                         Jim_IncrRefCount(teap->body);
4747
4748                                         if (!replace) {
4749                                                 /* add to head of event list */
4750                                                 teap->next = target->event_action;
4751                                                 target->event_action = teap;
4752                                         }
4753                                         Jim_SetEmptyResult(goi->interp);
4754                                 } else {
4755                                         /* get */
4756                                         if (teap == NULL)
4757                                                 Jim_SetEmptyResult(goi->interp);
4758                                         else
4759                                                 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4760                                 }
4761                         }
4762                         /* loop for more */
4763                         break;
4764
4765                 case TCFG_WORK_AREA_VIRT:
4766                         if (goi->isconfigure) {
4767                                 target_free_all_working_areas(target);
4768                                 e = Jim_GetOpt_Wide(goi, &w);
4769                                 if (e != JIM_OK)
4770                                         return e;
4771                                 target->working_area_virt = w;
4772                                 target->working_area_virt_spec = true;
4773                         } else {
4774                                 if (goi->argc != 0)
4775                                         goto no_params;
4776                         }
4777                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4778                         /* loop for more */
4779                         break;
4780
4781                 case TCFG_WORK_AREA_PHYS:
4782                         if (goi->isconfigure) {
4783                                 target_free_all_working_areas(target);
4784                                 e = Jim_GetOpt_Wide(goi, &w);
4785                                 if (e != JIM_OK)
4786                                         return e;
4787                                 target->working_area_phys = w;
4788                                 target->working_area_phys_spec = true;
4789                         } else {
4790                                 if (goi->argc != 0)
4791                                         goto no_params;
4792                         }
4793                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4794                         /* loop for more */
4795                         break;
4796
4797                 case TCFG_WORK_AREA_SIZE:
4798                         if (goi->isconfigure) {
4799                                 target_free_all_working_areas(target);
4800                                 e = Jim_GetOpt_Wide(goi, &w);
4801                                 if (e != JIM_OK)
4802                                         return e;
4803                                 target->working_area_size = w;
4804                         } else {
4805                                 if (goi->argc != 0)
4806                                         goto no_params;
4807                         }
4808                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4809                         /* loop for more */
4810                         break;
4811
4812                 case TCFG_WORK_AREA_BACKUP:
4813                         if (goi->isconfigure) {
4814                                 target_free_all_working_areas(target);
4815                                 e = Jim_GetOpt_Wide(goi, &w);
4816                                 if (e != JIM_OK)
4817                                         return e;
4818                                 /* make this exactly 1 or 0 */
4819                                 target->backup_working_area = (!!w);
4820                         } else {
4821                                 if (goi->argc != 0)
4822                                         goto no_params;
4823                         }
4824                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4825                         /* loop for more e*/
4826                         break;
4827
4828
4829                 case TCFG_ENDIAN:
4830                         if (goi->isconfigure) {
4831                                 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4832                                 if (e != JIM_OK) {
4833                                         Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4834                                         return e;
4835                                 }
4836                                 target->endianness = n->value;
4837                         } else {
4838                                 if (goi->argc != 0)
4839                                         goto no_params;
4840                         }
4841                         n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4842                         if (n->name == NULL) {
4843                                 target->endianness = TARGET_LITTLE_ENDIAN;
4844                                 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4845                         }
4846                         Jim_SetResultString(goi->interp, n->name, -1);
4847                         /* loop for more */
4848                         break;
4849
4850                 case TCFG_COREID:
4851                         if (goi->isconfigure) {
4852                                 e = Jim_GetOpt_Wide(goi, &w);
4853                                 if (e != JIM_OK)
4854                                         return e;
4855                                 target->coreid = (int32_t)w;
4856                         } else {
4857                                 if (goi->argc != 0)
4858                                         goto no_params;
4859                         }
4860                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->coreid));
4861                         /* loop for more */
4862                         break;
4863
4864                 case TCFG_CHAIN_POSITION:
4865                         if (goi->isconfigure) {
4866                                 Jim_Obj *o_t;
4867                                 struct jtag_tap *tap;
4868
4869                                 if (target->has_dap) {
4870                                         Jim_SetResultString(goi->interp,
4871                                                 "target requires -dap parameter instead of -chain-position!", -1);
4872                                         return JIM_ERR;
4873                                 }
4874
4875                                 target_free_all_working_areas(target);
4876                                 e = Jim_GetOpt_Obj(goi, &o_t);
4877                                 if (e != JIM_OK)
4878                                         return e;
4879                                 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4880                                 if (tap == NULL)
4881                                         return JIM_ERR;
4882                                 target->tap = tap;
4883                                 target->tap_configured = true;
4884                         } else {
4885                                 if (goi->argc != 0)
4886                                         goto no_params;
4887                         }
4888                         Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4889                         /* loop for more e*/
4890                         break;
4891                 case TCFG_DBGBASE:
4892                         if (goi->isconfigure) {
4893                                 e = Jim_GetOpt_Wide(goi, &w);
4894                                 if (e != JIM_OK)
4895                                         return e;
4896                                 target->dbgbase = (uint32_t)w;
4897                                 target->dbgbase_set = true;
4898                         } else {
4899                                 if (goi->argc != 0)
4900                                         goto no_params;
4901                         }
4902                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4903                         /* loop for more */
4904                         break;
4905                 case TCFG_RTOS:
4906                         /* RTOS */
4907                         {
4908                                 int result = rtos_create(goi, target);
4909                                 if (result != JIM_OK)
4910                                         return result;
4911                         }
4912                         /* loop for more */
4913                         break;
4914
4915                 case TCFG_DEFER_EXAMINE:
4916                         /* DEFER_EXAMINE */
4917                         target->defer_examine = true;
4918                         /* loop for more */
4919                         break;
4920
4921                 case TCFG_GDB_PORT:
4922                         if (goi->isconfigure) {
4923                                 struct command_context *cmd_ctx = current_command_context(goi->interp);
4924                                 if (cmd_ctx->mode != COMMAND_CONFIG) {
4925                                         Jim_SetResultString(goi->interp, "-gdb-port must be configured before 'init'", -1);
4926                                         return JIM_ERR;
4927                                 }
4928
4929                                 const char *s;
4930                                 e = Jim_GetOpt_String(goi, &s, NULL);
4931                                 if (e != JIM_OK)
4932                                         return e;
4933                                 target->gdb_port_override = strdup(s);
4934                         } else {
4935                                 if (goi->argc != 0)
4936                                         goto no_params;
4937                         }
4938                         Jim_SetResultString(goi->interp, target->gdb_port_override ? : "undefined", -1);
4939                         /* loop for more */
4940                         break;
4941                 }
4942         } /* while (goi->argc) */
4943
4944
4945                 /* done - we return */
4946         return JIM_OK;
4947 }
4948
4949 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4950 {
4951         Jim_GetOptInfo goi;
4952
4953         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4954         goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4955         if (goi.argc < 1) {
4956                 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4957                                  "missing: -option ...");
4958                 return JIM_ERR;
4959         }
4960         struct target *target = Jim_CmdPrivData(goi.interp);
4961         return target_configure(&goi, target);
4962 }
4963
4964 static int jim_target_mem2array(Jim_Interp *interp,
4965                 int argc, Jim_Obj *const *argv)
4966 {
4967         struct target *target = Jim_CmdPrivData(interp);
4968         return target_mem2array(interp, target, argc - 1, argv + 1);
4969 }
4970
4971 static int jim_target_array2mem(Jim_Interp *interp,
4972                 int argc, Jim_Obj *const *argv)
4973 {
4974         struct target *target = Jim_CmdPrivData(interp);
4975         return target_array2mem(interp, target, argc - 1, argv + 1);
4976 }
4977
4978 static int jim_target_tap_disabled(Jim_Interp *interp)
4979 {
4980         Jim_SetResultFormatted(interp, "[TAP is disabled]");
4981         return JIM_ERR;
4982 }
4983
4984 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4985 {
4986         bool allow_defer = false;
4987
4988         Jim_GetOptInfo goi;
4989         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4990         if (goi.argc > 1) {
4991                 const char *cmd_name = Jim_GetString(argv[0], NULL);
4992                 Jim_SetResultFormatted(goi.interp,
4993                                 "usage: %s ['allow-defer']", cmd_name);
4994                 return JIM_ERR;
4995         }
4996         if (goi.argc > 0 &&
4997             strcmp(Jim_GetString(argv[1], NULL), "allow-defer") == 0) {
4998                 /* consume it */
4999                 struct Jim_Obj *obj;
5000                 int e = Jim_GetOpt_Obj(&goi, &obj);
5001                 if (e != JIM_OK)
5002                         return e;
5003                 allow_defer = true;
5004         }
5005
5006         struct target *target = Jim_CmdPrivData(interp);
5007         if (!target->tap->enabled)
5008                 return jim_target_tap_disabled(interp);
5009
5010         if (allow_defer && target->defer_examine) {
5011                 LOG_INFO("Deferring arp_examine of %s", target_name(target));
5012                 LOG_INFO("Use arp_examine command to examine it manually!");
5013                 return JIM_OK;
5014         }
5015
5016         int e = target->type->examine(target);
5017         if (e != ERROR_OK)
5018                 return JIM_ERR;
5019         return JIM_OK;
5020 }
5021
5022 static int jim_target_was_examined(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5023 {
5024         struct target *target = Jim_CmdPrivData(interp);
5025
5026         Jim_SetResultBool(interp, target_was_examined(target));
5027         return JIM_OK;
5028 }
5029
5030 static int jim_target_examine_deferred(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5031 {
5032         struct target *target = Jim_CmdPrivData(interp);
5033
5034         Jim_SetResultBool(interp, target->defer_examine);
5035         return JIM_OK;
5036 }
5037
5038 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5039 {
5040         if (argc != 1) {
5041                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5042                 return JIM_ERR;
5043         }
5044         struct target *target = Jim_CmdPrivData(interp);
5045
5046         if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
5047                 return JIM_ERR;
5048
5049         return JIM_OK;
5050 }
5051
5052 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5053 {
5054         if (argc != 1) {
5055                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5056                 return JIM_ERR;
5057         }
5058         struct target *target = Jim_CmdPrivData(interp);
5059         if (!target->tap->enabled)
5060                 return jim_target_tap_disabled(interp);
5061
5062         int e;
5063         if (!(target_was_examined(target)))
5064                 e = ERROR_TARGET_NOT_EXAMINED;
5065         else
5066                 e = target->type->poll(target);
5067         if (e != ERROR_OK)
5068                 return JIM_ERR;
5069         return JIM_OK;
5070 }
5071
5072 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5073 {
5074         Jim_GetOptInfo goi;
5075         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5076
5077         if (goi.argc != 2) {
5078                 Jim_WrongNumArgs(interp, 0, argv,
5079                                 "([tT]|[fF]|assert|deassert) BOOL");
5080                 return JIM_ERR;
5081         }
5082
5083         Jim_Nvp *n;
5084         int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
5085         if (e != JIM_OK) {
5086                 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
5087                 return e;
5088         }
5089         /* the halt or not param */
5090         jim_wide a;
5091         e = Jim_GetOpt_Wide(&goi, &a);
5092         if (e != JIM_OK)
5093                 return e;
5094
5095         struct target *target = Jim_CmdPrivData(goi.interp);
5096         if (!target->tap->enabled)
5097                 return jim_target_tap_disabled(interp);
5098
5099         if (!target->type->assert_reset || !target->type->deassert_reset) {
5100                 Jim_SetResultFormatted(interp,
5101                                 "No target-specific reset for %s",
5102                                 target_name(target));
5103                 return JIM_ERR;
5104         }
5105
5106         if (target->defer_examine)
5107                 target_reset_examined(target);
5108
5109         /* determine if we should halt or not. */
5110         target->reset_halt = !!a;
5111         /* When this happens - all workareas are invalid. */
5112         target_free_all_working_areas_restore(target, 0);
5113
5114         /* do the assert */
5115         if (n->value == NVP_ASSERT)
5116                 e = target->type->assert_reset(target);
5117         else
5118                 e = target->type->deassert_reset(target);
5119         return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5120 }
5121
5122 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5123 {
5124         if (argc != 1) {
5125                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5126                 return JIM_ERR;
5127         }
5128         struct target *target = Jim_CmdPrivData(interp);
5129         if (!target->tap->enabled)
5130                 return jim_target_tap_disabled(interp);
5131         int e = target->type->halt(target);
5132         return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5133 }
5134
5135 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5136 {
5137         Jim_GetOptInfo goi;
5138         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5139
5140         /* params:  <name>  statename timeoutmsecs */
5141         if (goi.argc != 2) {
5142                 const char *cmd_name = Jim_GetString(argv[0], NULL);
5143                 Jim_SetResultFormatted(goi.interp,
5144                                 "%s <state_name> <timeout_in_msec>", cmd_name);
5145                 return JIM_ERR;
5146         }
5147
5148         Jim_Nvp *n;
5149         int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
5150         if (e != JIM_OK) {
5151                 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
5152                 return e;
5153         }
5154         jim_wide a;
5155         e = Jim_GetOpt_Wide(&goi, &a);
5156         if (e != JIM_OK)
5157                 return e;
5158         struct target *target = Jim_CmdPrivData(interp);
5159         if (!target->tap->enabled)
5160                 return jim_target_tap_disabled(interp);
5161
5162         e = target_wait_state(target, n->value, a);
5163         if (e != ERROR_OK) {
5164                 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
5165                 Jim_SetResultFormatted(goi.interp,
5166                                 "target: %s wait %s fails (%#s) %s",
5167                                 target_name(target), n->name,
5168                                 eObj, target_strerror_safe(e));
5169                 return JIM_ERR;
5170         }
5171         return JIM_OK;
5172 }
5173 /* List for human, Events defined for this target.
5174  * scripts/programs should use 'name cget -event NAME'
5175  */
5176 COMMAND_HANDLER(handle_target_event_list)
5177 {
5178         struct target *target = get_current_target(CMD_CTX);
5179         struct target_event_action *teap = target->event_action;
5180
5181         command_print(CMD, "Event actions for target (%d) %s\n",
5182                                    target->target_number,
5183                                    target_name(target));
5184         command_print(CMD, "%-25s | Body", "Event");
5185         command_print(CMD, "------------------------- | "
5186                         "----------------------------------------");
5187         while (teap) {
5188                 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
5189                 command_print(CMD, "%-25s | %s",
5190                                 opt->name, Jim_GetString(teap->body, NULL));
5191                 teap = teap->next;
5192         }
5193         command_print(CMD, "***END***");
5194         return ERROR_OK;
5195 }
5196 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5197 {
5198         if (argc != 1) {
5199                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5200                 return JIM_ERR;
5201         }
5202         struct target *target = Jim_CmdPrivData(interp);
5203         Jim_SetResultString(interp, target_state_name(target), -1);
5204         return JIM_OK;
5205 }
5206 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5207 {
5208         Jim_GetOptInfo goi;
5209         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5210         if (goi.argc != 1) {
5211                 const char *cmd_name = Jim_GetString(argv[0], NULL);
5212                 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5213                 return JIM_ERR;
5214         }
5215         Jim_Nvp *n;
5216         int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
5217         if (e != JIM_OK) {
5218                 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
5219                 return e;
5220         }
5221         struct target *target = Jim_CmdPrivData(interp);
5222         target_handle_event(target, n->value);
5223         return JIM_OK;
5224 }
5225
5226 static const struct command_registration target_instance_command_handlers[] = {
5227         {
5228                 .name = "configure",
5229                 .mode = COMMAND_ANY,
5230                 .jim_handler = jim_target_configure,
5231                 .help  = "configure a new target for use",
5232                 .usage = "[target_attribute ...]",
5233         },
5234         {
5235                 .name = "cget",
5236                 .mode = COMMAND_ANY,
5237                 .jim_handler = jim_target_configure,
5238                 .help  = "returns the specified target attribute",
5239                 .usage = "target_attribute",
5240         },
5241         {
5242                 .name = "mwd",
5243                 .handler = handle_mw_command,
5244                 .mode = COMMAND_EXEC,
5245                 .help = "Write 64-bit word(s) to target memory",
5246                 .usage = "address data [count]",
5247         },
5248         {
5249                 .name = "mww",
5250                 .handler = handle_mw_command,
5251                 .mode = COMMAND_EXEC,
5252                 .help = "Write 32-bit word(s) to target memory",
5253                 .usage = "address data [count]",
5254         },
5255         {
5256                 .name = "mwh",
5257                 .handler = handle_mw_command,
5258                 .mode = COMMAND_EXEC,
5259                 .help = "Write 16-bit half-word(s) to target memory",
5260                 .usage = "address data [count]",
5261         },
5262         {
5263                 .name = "mwb",
5264                 .handler = handle_mw_command,
5265                 .mode = COMMAND_EXEC,
5266                 .help = "Write byte(s) to target memory",
5267                 .usage = "address data [count]",
5268         },
5269         {
5270                 .name = "mdd",
5271                 .handler = handle_md_command,
5272                 .mode = COMMAND_EXEC,
5273                 .help = "Display target memory as 64-bit words",
5274                 .usage = "address [count]",
5275         },
5276         {
5277                 .name = "mdw",
5278                 .handler = handle_md_command,
5279                 .mode = COMMAND_EXEC,
5280                 .help = "Display target memory as 32-bit words",
5281                 .usage = "address [count]",
5282         },
5283         {
5284                 .name = "mdh",
5285                 .handler = handle_md_command,
5286                 .mode = COMMAND_EXEC,
5287                 .help = "Display target memory as 16-bit half-words",
5288                 .usage = "address [count]",
5289         },
5290         {
5291                 .name = "mdb",
5292                 .handler = handle_md_command,
5293                 .mode = COMMAND_EXEC,
5294                 .help = "Display target memory as 8-bit bytes",
5295                 .usage = "address [count]",
5296         },
5297         {
5298                 .name = "array2mem",
5299                 .mode = COMMAND_EXEC,
5300                 .jim_handler = jim_target_array2mem,
5301                 .help = "Writes Tcl array of 8/16/32 bit numbers "
5302                         "to target memory",
5303                 .usage = "arrayname bitwidth address count",
5304         },
5305         {
5306                 .name = "mem2array",
5307                 .mode = COMMAND_EXEC,
5308                 .jim_handler = jim_target_mem2array,
5309                 .help = "Loads Tcl array of 8/16/32 bit numbers "
5310                         "from target memory",
5311                 .usage = "arrayname bitwidth address count",
5312         },
5313         {
5314                 .name = "eventlist",
5315                 .handler = handle_target_event_list,
5316                 .mode = COMMAND_EXEC,
5317                 .help = "displays a table of events defined for this target",
5318                 .usage = "",
5319         },
5320         {
5321                 .name = "curstate",
5322                 .mode = COMMAND_EXEC,
5323                 .jim_handler = jim_target_current_state,
5324                 .help = "displays the current state of this target",
5325         },
5326         {
5327                 .name = "arp_examine",
5328                 .mode = COMMAND_EXEC,
5329                 .jim_handler = jim_target_examine,
5330                 .help = "used internally for reset processing",
5331                 .usage = "['allow-defer']",
5332         },
5333         {
5334                 .name = "was_examined",
5335                 .mode = COMMAND_EXEC,
5336                 .jim_handler = jim_target_was_examined,
5337                 .help = "used internally for reset processing",
5338         },
5339         {
5340                 .name = "examine_deferred",
5341                 .mode = COMMAND_EXEC,
5342                 .jim_handler = jim_target_examine_deferred,
5343                 .help = "used internally for reset processing",
5344         },
5345         {
5346                 .name = "arp_halt_gdb",
5347                 .mode = COMMAND_EXEC,
5348                 .jim_handler = jim_target_halt_gdb,
5349                 .help = "used internally for reset processing to halt GDB",
5350         },
5351         {
5352                 .name = "arp_poll",
5353                 .mode = COMMAND_EXEC,
5354                 .jim_handler = jim_target_poll,
5355                 .help = "used internally for reset processing",
5356         },
5357         {
5358                 .name = "arp_reset",
5359                 .mode = COMMAND_EXEC,
5360                 .jim_handler = jim_target_reset,
5361                 .help = "used internally for reset processing",
5362         },
5363         {
5364                 .name = "arp_halt",
5365                 .mode = COMMAND_EXEC,
5366                 .jim_handler = jim_target_halt,
5367                 .help = "used internally for reset processing",
5368         },
5369         {
5370                 .name = "arp_waitstate",
5371                 .mode = COMMAND_EXEC,
5372                 .jim_handler = jim_target_wait_state,
5373                 .help = "used internally for reset processing",
5374         },
5375         {
5376                 .name = "invoke-event",
5377                 .mode = COMMAND_EXEC,
5378                 .jim_handler = jim_target_invoke_event,
5379                 .help = "invoke handler for specified event",
5380                 .usage = "event_name",
5381         },
5382         COMMAND_REGISTRATION_DONE
5383 };
5384
5385 static int target_create(Jim_GetOptInfo *goi)
5386 {
5387         Jim_Obj *new_cmd;
5388         Jim_Cmd *cmd;
5389         const char *cp;
5390         int e;
5391         int x;
5392         struct target *target;
5393         struct command_context *cmd_ctx;
5394
5395         cmd_ctx = current_command_context(goi->interp);
5396         assert(cmd_ctx != NULL);
5397
5398         if (goi->argc < 3) {
5399                 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5400                 return JIM_ERR;
5401         }
5402
5403         /* COMMAND */
5404         Jim_GetOpt_Obj(goi, &new_cmd);
5405         /* does this command exist? */
5406         cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
5407         if (cmd) {
5408                 cp = Jim_GetString(new_cmd, NULL);
5409                 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5410                 return JIM_ERR;
5411         }
5412
5413         /* TYPE */
5414         e = Jim_GetOpt_String(goi, &cp, NULL);
5415         if (e != JIM_OK)
5416                 return e;
5417         struct transport *tr = get_current_transport();
5418         if (tr->override_target) {
5419                 e = tr->override_target(&cp);
5420                 if (e != ERROR_OK) {
5421                         LOG_ERROR("The selected transport doesn't support this target");
5422                         return JIM_ERR;
5423                 }
5424                 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5425         }
5426         /* now does target type exist */
5427         for (x = 0 ; target_types[x] ; x++) {
5428                 if (0 == strcmp(cp, target_types[x]->name)) {
5429                         /* found */
5430                         break;
5431                 }
5432
5433                 /* check for deprecated name */
5434                 if (target_types[x]->deprecated_name) {
5435                         if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
5436                                 /* found */
5437                                 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
5438                                 break;
5439                         }
5440                 }
5441         }
5442         if (target_types[x] == NULL) {
5443                 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5444                 for (x = 0 ; target_types[x] ; x++) {
5445                         if (target_types[x + 1]) {
5446                                 Jim_AppendStrings(goi->interp,
5447                                                                    Jim_GetResult(goi->interp),
5448                                                                    target_types[x]->name,
5449                                                                    ", ", NULL);
5450                         } else {
5451                                 Jim_AppendStrings(goi->interp,
5452                                                                    Jim_GetResult(goi->interp),
5453                                                                    " or ",
5454                                                                    target_types[x]->name, NULL);
5455                         }
5456                 }
5457                 return JIM_ERR;
5458         }
5459
5460         /* Create it */
5461         target = calloc(1, sizeof(struct target));
5462         /* set target number */
5463         target->target_number = new_target_number();
5464         cmd_ctx->current_target = target;
5465
5466         /* allocate memory for each unique target type */
5467         target->type = calloc(1, sizeof(struct target_type));
5468
5469         memcpy(target->type, target_types[x], sizeof(struct target_type));
5470
5471         /* will be set by "-endian" */
5472         target->endianness = TARGET_ENDIAN_UNKNOWN;
5473
5474         /* default to first core, override with -coreid */
5475         target->coreid = 0;
5476
5477         target->working_area        = 0x0;
5478         target->working_area_size   = 0x0;
5479         target->working_areas       = NULL;
5480         target->backup_working_area = 0;
5481
5482         target->state               = TARGET_UNKNOWN;
5483         target->debug_reason        = DBG_REASON_UNDEFINED;
5484         target->reg_cache           = NULL;
5485         target->breakpoints         = NULL;
5486         target->watchpoints         = NULL;
5487         target->next                = NULL;
5488         target->arch_info           = NULL;
5489
5490         target->verbose_halt_msg        = true;
5491
5492         target->halt_issued                     = false;
5493
5494         /* initialize trace information */
5495         target->trace_info = calloc(1, sizeof(struct trace));
5496
5497         target->dbgmsg          = NULL;
5498         target->dbg_msg_enabled = 0;
5499
5500         target->endianness = TARGET_ENDIAN_UNKNOWN;
5501
5502         target->rtos = NULL;
5503         target->rtos_auto_detect = false;
5504
5505         target->gdb_port_override = NULL;
5506
5507         /* Do the rest as "configure" options */
5508         goi->isconfigure = 1;
5509         e = target_configure(goi, target);
5510
5511         if (e == JIM_OK) {
5512                 if (target->has_dap) {
5513                         if (!target->dap_configured) {
5514                                 Jim_SetResultString(goi->interp, "-dap ?name? required when creating target", -1);
5515                                 e = JIM_ERR;
5516                         }
5517                 } else {
5518                         if (!target->tap_configured) {
5519                                 Jim_SetResultString(goi->interp, "-chain-position ?name? required when creating target", -1);
5520                                 e = JIM_ERR;
5521                         }
5522                 }
5523                 /* tap must be set after target was configured */
5524                 if (target->tap == NULL)
5525                         e = JIM_ERR;
5526         }
5527
5528         if (e != JIM_OK) {
5529                 free(target->gdb_port_override);
5530                 free(target->type);
5531                 free(target);
5532                 return e;
5533         }
5534
5535         if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5536                 /* default endian to little if not specified */
5537                 target->endianness = TARGET_LITTLE_ENDIAN;
5538         }
5539
5540         cp = Jim_GetString(new_cmd, NULL);
5541         target->cmd_name = strdup(cp);
5542
5543         if (target->type->target_create) {
5544                 e = (*(target->type->target_create))(target, goi->interp);
5545                 if (e != ERROR_OK) {
5546                         LOG_DEBUG("target_create failed");
5547                         free(target->gdb_port_override);
5548                         free(target->type);
5549                         free(target->cmd_name);
5550                         free(target);
5551                         return JIM_ERR;
5552                 }
5553         }
5554
5555         /* create the target specific commands */
5556         if (target->type->commands) {
5557                 e = register_commands(cmd_ctx, NULL, target->type->commands);
5558                 if (ERROR_OK != e)
5559                         LOG_ERROR("unable to register '%s' commands", cp);
5560         }
5561
5562         /* append to end of list */
5563         {
5564                 struct target **tpp;
5565                 tpp = &(all_targets);
5566                 while (*tpp)
5567                         tpp = &((*tpp)->next);
5568                 *tpp = target;
5569         }
5570
5571         /* now - create the new target name command */
5572         const struct command_registration target_subcommands[] = {
5573                 {
5574                         .chain = target_instance_command_handlers,
5575                 },
5576                 {
5577                         .chain = target->type->commands,
5578                 },
5579                 COMMAND_REGISTRATION_DONE
5580         };
5581         const struct command_registration target_commands[] = {
5582                 {
5583                         .name = cp,
5584                         .mode = COMMAND_ANY,
5585                         .help = "target command group",
5586                         .usage = "",
5587                         .chain = target_subcommands,
5588                 },
5589                 COMMAND_REGISTRATION_DONE
5590         };
5591         e = register_commands(cmd_ctx, NULL, target_commands);
5592         if (ERROR_OK != e)
5593                 return JIM_ERR;
5594
5595         struct command *c = command_find_in_context(cmd_ctx, cp);
5596         assert(c);
5597         command_set_handler_data(c, target);
5598
5599         return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5600 }
5601
5602 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5603 {
5604         if (argc != 1) {
5605                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5606                 return JIM_ERR;
5607         }
5608         struct command_context *cmd_ctx = current_command_context(interp);
5609         assert(cmd_ctx != NULL);
5610
5611         Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5612         return JIM_OK;
5613 }
5614
5615 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5616 {
5617         if (argc != 1) {
5618                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5619                 return JIM_ERR;
5620         }
5621         Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5622         for (unsigned x = 0; NULL != target_types[x]; x++) {
5623                 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5624                         Jim_NewStringObj(interp, target_types[x]->name, -1));
5625         }
5626         return JIM_OK;
5627 }
5628
5629 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5630 {
5631         if (argc != 1) {
5632                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5633                 return JIM_ERR;
5634         }
5635         Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5636         struct target *target = all_targets;
5637         while (target) {
5638                 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5639                         Jim_NewStringObj(interp, target_name(target), -1));
5640                 target = target->next;
5641         }
5642         return JIM_OK;
5643 }
5644
5645 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5646 {
5647         int i;
5648         const char *targetname;
5649         int retval, len;
5650         struct target *target = (struct target *) NULL;
5651         struct target_list *head, *curr, *new;
5652         curr = (struct target_list *) NULL;
5653         head = (struct target_list *) NULL;
5654
5655         retval = 0;
5656         LOG_DEBUG("%d", argc);
5657         /* argv[1] = target to associate in smp
5658          * argv[2] = target to assoicate in smp
5659          * argv[3] ...
5660          */
5661
5662         for (i = 1; i < argc; i++) {
5663
5664                 targetname = Jim_GetString(argv[i], &len);
5665                 target = get_target(targetname);
5666                 LOG_DEBUG("%s ", targetname);
5667                 if (target) {
5668                         new = malloc(sizeof(struct target_list));
5669                         new->target = target;
5670                         new->next = (struct target_list *)NULL;
5671                         if (head == (struct target_list *)NULL) {
5672                                 head = new;
5673                                 curr = head;
5674                         } else {
5675                                 curr->next = new;
5676                                 curr = new;
5677                         }
5678                 }
5679         }
5680         /*  now parse the list of cpu and put the target in smp mode*/
5681         curr = head;
5682
5683         while (curr != (struct target_list *)NULL) {
5684                 target = curr->target;
5685                 target->smp = 1;
5686                 target->head = head;
5687                 curr = curr->next;
5688         }
5689
5690         if (target && target->rtos)
5691                 retval = rtos_smp_init(head->target);
5692
5693         return retval;
5694 }
5695
5696
5697 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5698 {
5699         Jim_GetOptInfo goi;
5700         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5701         if (goi.argc < 3) {
5702                 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5703                         "<name> <target_type> [<target_options> ...]");
5704                 return JIM_ERR;
5705         }
5706         return target_create(&goi);
5707 }
5708
5709 static const struct command_registration target_subcommand_handlers[] = {
5710         {
5711                 .name = "init",
5712                 .mode = COMMAND_CONFIG,
5713                 .handler = handle_target_init_command,
5714                 .help = "initialize targets",
5715                 .usage = "",
5716         },
5717         {
5718                 .name = "create",
5719                 .mode = COMMAND_CONFIG,
5720                 .jim_handler = jim_target_create,
5721                 .usage = "name type '-chain-position' name [options ...]",
5722                 .help = "Creates and selects a new target",
5723         },
5724         {
5725                 .name = "current",
5726                 .mode = COMMAND_ANY,
5727                 .jim_handler = jim_target_current,
5728                 .help = "Returns the currently selected target",
5729         },
5730         {
5731                 .name = "types",
5732                 .mode = COMMAND_ANY,
5733                 .jim_handler = jim_target_types,
5734                 .help = "Returns the available target types as "
5735                                 "a list of strings",
5736         },
5737         {
5738                 .name = "names",
5739                 .mode = COMMAND_ANY,
5740                 .jim_handler = jim_target_names,
5741                 .help = "Returns the names of all targets as a list of strings",
5742         },
5743         {
5744                 .name = "smp",
5745                 .mode = COMMAND_ANY,
5746                 .jim_handler = jim_target_smp,
5747                 .usage = "targetname1 targetname2 ...",
5748                 .help = "gather several target in a smp list"
5749         },
5750
5751         COMMAND_REGISTRATION_DONE
5752 };
5753
5754 struct FastLoad {
5755         target_addr_t address;
5756         uint8_t *data;
5757         int length;
5758
5759 };
5760
5761 static int fastload_num;
5762 static struct FastLoad *fastload;
5763
5764 static void free_fastload(void)
5765 {
5766         if (fastload != NULL) {
5767                 int i;
5768                 for (i = 0; i < fastload_num; i++) {
5769                         if (fastload[i].data)
5770                                 free(fastload[i].data);
5771                 }
5772                 free(fastload);
5773                 fastload = NULL;
5774         }
5775 }
5776
5777 COMMAND_HANDLER(handle_fast_load_image_command)
5778 {
5779         uint8_t *buffer;
5780         size_t buf_cnt;
5781         uint32_t image_size;
5782         target_addr_t min_address = 0;
5783         target_addr_t max_address = -1;
5784         int i;
5785
5786         struct image image;
5787
5788         int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5789                         &image, &min_address, &max_address);
5790         if (ERROR_OK != retval)
5791                 return retval;
5792
5793         struct duration bench;
5794         duration_start(&bench);
5795
5796         retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5797         if (retval != ERROR_OK)
5798                 return retval;
5799
5800         image_size = 0x0;
5801         retval = ERROR_OK;
5802         fastload_num = image.num_sections;
5803         fastload = malloc(sizeof(struct FastLoad)*image.num_sections);
5804         if (fastload == NULL) {
5805                 command_print(CMD, "out of memory");
5806                 image_close(&image);
5807                 return ERROR_FAIL;
5808         }
5809         memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5810         for (i = 0; i < image.num_sections; i++) {
5811                 buffer = malloc(image.sections[i].size);
5812                 if (buffer == NULL) {
5813                         command_print(CMD, "error allocating buffer for section (%d bytes)",
5814                                                   (int)(image.sections[i].size));
5815                         retval = ERROR_FAIL;
5816                         break;
5817                 }
5818
5819                 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5820                 if (retval != ERROR_OK) {
5821                         free(buffer);
5822                         break;
5823                 }
5824
5825                 uint32_t offset = 0;
5826                 uint32_t length = buf_cnt;
5827
5828                 /* DANGER!!! beware of unsigned comparision here!!! */
5829
5830                 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5831                                 (image.sections[i].base_address < max_address)) {
5832                         if (image.sections[i].base_address < min_address) {
5833                                 /* clip addresses below */
5834                                 offset += min_address-image.sections[i].base_address;
5835                                 length -= offset;
5836                         }
5837
5838                         if (image.sections[i].base_address + buf_cnt > max_address)
5839                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5840
5841                         fastload[i].address = image.sections[i].base_address + offset;
5842                         fastload[i].data = malloc(length);
5843                         if (fastload[i].data == NULL) {
5844                                 free(buffer);
5845                                 command_print(CMD, "error allocating buffer for section (%" PRIu32 " bytes)",
5846                                                           length);
5847                                 retval = ERROR_FAIL;
5848                                 break;
5849                         }
5850                         memcpy(fastload[i].data, buffer + offset, length);
5851                         fastload[i].length = length;
5852
5853                         image_size += length;
5854                         command_print(CMD, "%u bytes written at address 0x%8.8x",
5855                                                   (unsigned int)length,
5856                                                   ((unsigned int)(image.sections[i].base_address + offset)));
5857                 }
5858
5859                 free(buffer);
5860         }
5861
5862         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5863                 command_print(CMD, "Loaded %" PRIu32 " bytes "
5864                                 "in %fs (%0.3f KiB/s)", image_size,
5865                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5866
5867                 command_print(CMD,
5868                                 "WARNING: image has not been loaded to target!"
5869                                 "You can issue a 'fast_load' to finish loading.");
5870         }
5871
5872         image_close(&image);
5873
5874         if (retval != ERROR_OK)
5875                 free_fastload();
5876
5877         return retval;
5878 }
5879
5880 COMMAND_HANDLER(handle_fast_load_command)
5881 {
5882         if (CMD_ARGC > 0)
5883                 return ERROR_COMMAND_SYNTAX_ERROR;
5884         if (fastload == NULL) {
5885                 LOG_ERROR("No image in memory");
5886                 return ERROR_FAIL;
5887         }
5888         int i;
5889         int64_t ms = timeval_ms();
5890         int size = 0;
5891         int retval = ERROR_OK;
5892         for (i = 0; i < fastload_num; i++) {
5893                 struct target *target = get_current_target(CMD_CTX);
5894                 command_print(CMD, "Write to 0x%08x, length 0x%08x",
5895                                           (unsigned int)(fastload[i].address),
5896                                           (unsigned int)(fastload[i].length));
5897                 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5898                 if (retval != ERROR_OK)
5899                         break;
5900                 size += fastload[i].length;
5901         }
5902         if (retval == ERROR_OK) {
5903                 int64_t after = timeval_ms();
5904                 command_print(CMD, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5905         }
5906         return retval;
5907 }
5908
5909 static const struct command_registration target_command_handlers[] = {
5910         {
5911                 .name = "targets",
5912                 .handler = handle_targets_command,
5913                 .mode = COMMAND_ANY,
5914                 .help = "change current default target (one parameter) "
5915                         "or prints table of all targets (no parameters)",
5916                 .usage = "[target]",
5917         },
5918         {
5919                 .name = "target",
5920                 .mode = COMMAND_CONFIG,
5921                 .help = "configure target",
5922                 .chain = target_subcommand_handlers,
5923                 .usage = "",
5924         },
5925         COMMAND_REGISTRATION_DONE
5926 };
5927
5928 int target_register_commands(struct command_context *cmd_ctx)
5929 {
5930         return register_commands(cmd_ctx, NULL, target_command_handlers);
5931 }
5932
5933 static bool target_reset_nag = true;
5934
5935 bool get_target_reset_nag(void)
5936 {
5937         return target_reset_nag;
5938 }
5939
5940 COMMAND_HANDLER(handle_target_reset_nag)
5941 {
5942         return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5943                         &target_reset_nag, "Nag after each reset about options to improve "
5944                         "performance");
5945 }
5946
5947 COMMAND_HANDLER(handle_ps_command)
5948 {
5949         struct target *target = get_current_target(CMD_CTX);
5950         char *display;
5951         if (target->state != TARGET_HALTED) {
5952                 LOG_INFO("target not halted !!");
5953                 return ERROR_OK;
5954         }
5955
5956         if ((target->rtos) && (target->rtos->type)
5957                         && (target->rtos->type->ps_command)) {
5958                 display = target->rtos->type->ps_command(target);
5959                 command_print(CMD, "%s", display);
5960                 free(display);
5961                 return ERROR_OK;
5962         } else {
5963                 LOG_INFO("failed");
5964                 return ERROR_TARGET_FAILURE;
5965         }
5966 }
5967
5968 static void binprint(struct command_invocation *cmd, const char *text, const uint8_t *buf, int size)
5969 {
5970         if (text != NULL)
5971                 command_print_sameline(cmd, "%s", text);
5972         for (int i = 0; i < size; i++)
5973                 command_print_sameline(cmd, " %02x", buf[i]);
5974         command_print(cmd, " ");
5975 }
5976
5977 COMMAND_HANDLER(handle_test_mem_access_command)
5978 {
5979         struct target *target = get_current_target(CMD_CTX);
5980         uint32_t test_size;
5981         int retval = ERROR_OK;
5982
5983         if (target->state != TARGET_HALTED) {
5984                 LOG_INFO("target not halted !!");
5985                 return ERROR_FAIL;
5986         }
5987
5988         if (CMD_ARGC != 1)
5989                 return ERROR_COMMAND_SYNTAX_ERROR;
5990
5991         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
5992
5993         /* Test reads */
5994         size_t num_bytes = test_size + 4;
5995
5996         struct working_area *wa = NULL;
5997         retval = target_alloc_working_area(target, num_bytes, &wa);
5998         if (retval != ERROR_OK) {
5999                 LOG_ERROR("Not enough working area");
6000                 return ERROR_FAIL;
6001         }
6002
6003         uint8_t *test_pattern = malloc(num_bytes);
6004
6005         for (size_t i = 0; i < num_bytes; i++)
6006                 test_pattern[i] = rand();
6007
6008         retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6009         if (retval != ERROR_OK) {
6010                 LOG_ERROR("Test pattern write failed");
6011                 goto out;
6012         }
6013
6014         for (int host_offset = 0; host_offset <= 1; host_offset++) {
6015                 for (int size = 1; size <= 4; size *= 2) {
6016                         for (int offset = 0; offset < 4; offset++) {
6017                                 uint32_t count = test_size / size;
6018                                 size_t host_bufsiz = (count + 2) * size + host_offset;
6019                                 uint8_t *read_ref = malloc(host_bufsiz);
6020                                 uint8_t *read_buf = malloc(host_bufsiz);
6021
6022                                 for (size_t i = 0; i < host_bufsiz; i++) {
6023                                         read_ref[i] = rand();
6024                                         read_buf[i] = read_ref[i];
6025                                 }
6026                                 command_print_sameline(CMD,
6027                                                 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
6028                                                 size, offset, host_offset ? "un" : "");
6029
6030                                 struct duration bench;
6031                                 duration_start(&bench);
6032
6033                                 retval = target_read_memory(target, wa->address + offset, size, count,
6034                                                 read_buf + size + host_offset);
6035
6036                                 duration_measure(&bench);
6037
6038                                 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6039                                         command_print(CMD, "Unsupported alignment");
6040                                         goto next;
6041                                 } else if (retval != ERROR_OK) {
6042                                         command_print(CMD, "Memory read failed");
6043                                         goto next;
6044                                 }
6045
6046                                 /* replay on host */
6047                                 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
6048
6049                                 /* check result */
6050                                 int result = memcmp(read_ref, read_buf, host_bufsiz);
6051                                 if (result == 0) {
6052                                         command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6053                                                         duration_elapsed(&bench),
6054                                                         duration_kbps(&bench, count * size));
6055                                 } else {
6056                                         command_print(CMD, "Compare failed");
6057                                         binprint(CMD, "ref:", read_ref, host_bufsiz);
6058                                         binprint(CMD, "buf:", read_buf, host_bufsiz);
6059                                 }
6060 next:
6061                                 free(read_ref);
6062                                 free(read_buf);
6063                         }
6064                 }
6065         }
6066
6067 out:
6068         free(test_pattern);
6069
6070         if (wa != NULL)
6071                 target_free_working_area(target, wa);
6072
6073         /* Test writes */
6074         num_bytes = test_size + 4 + 4 + 4;
6075
6076         retval = target_alloc_working_area(target, num_bytes, &wa);
6077         if (retval != ERROR_OK) {
6078                 LOG_ERROR("Not enough working area");
6079                 return ERROR_FAIL;
6080         }
6081
6082         test_pattern = malloc(num_bytes);
6083
6084         for (size_t i = 0; i < num_bytes; i++)
6085                 test_pattern[i] = rand();
6086
6087         for (int host_offset = 0; host_offset <= 1; host_offset++) {
6088                 for (int size = 1; size <= 4; size *= 2) {
6089                         for (int offset = 0; offset < 4; offset++) {
6090                                 uint32_t count = test_size / size;
6091                                 size_t host_bufsiz = count * size + host_offset;
6092                                 uint8_t *read_ref = malloc(num_bytes);
6093                                 uint8_t *read_buf = malloc(num_bytes);
6094                                 uint8_t *write_buf = malloc(host_bufsiz);
6095
6096                                 for (size_t i = 0; i < host_bufsiz; i++)
6097                                         write_buf[i] = rand();
6098                                 command_print_sameline(CMD,
6099                                                 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
6100                                                 size, offset, host_offset ? "un" : "");
6101
6102                                 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6103                                 if (retval != ERROR_OK) {
6104                                         command_print(CMD, "Test pattern write failed");
6105                                         goto nextw;
6106                                 }
6107
6108                                 /* replay on host */
6109                                 memcpy(read_ref, test_pattern, num_bytes);
6110                                 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
6111
6112                                 struct duration bench;
6113                                 duration_start(&bench);
6114
6115                                 retval = target_write_memory(target, wa->address + size + offset, size, count,
6116                                                 write_buf + host_offset);
6117
6118                                 duration_measure(&bench);
6119
6120                                 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6121                                         command_print(CMD, "Unsupported alignment");
6122                                         goto nextw;
6123                                 } else if (retval != ERROR_OK) {
6124                                         command_print(CMD, "Memory write failed");
6125                                         goto nextw;
6126                                 }
6127
6128                                 /* read back */
6129                                 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
6130                                 if (retval != ERROR_OK) {
6131                                         command_print(CMD, "Test pattern write failed");
6132                                         goto nextw;
6133                                 }
6134
6135                                 /* check result */
6136                                 int result = memcmp(read_ref, read_buf, num_bytes);
6137                                 if (result == 0) {
6138                                         command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6139                                                         duration_elapsed(&bench),
6140                                                         duration_kbps(&bench, count * size));
6141                                 } else {
6142                                         command_print(CMD, "Compare failed");
6143                                         binprint(CMD, "ref:", read_ref, num_bytes);
6144                                         binprint(CMD, "buf:", read_buf, num_bytes);
6145                                 }
6146 nextw:
6147                                 free(read_ref);
6148                                 free(read_buf);
6149                         }
6150                 }
6151         }
6152
6153         free(test_pattern);
6154
6155         if (wa != NULL)
6156                 target_free_working_area(target, wa);
6157         return retval;
6158 }
6159
6160 static const struct command_registration target_exec_command_handlers[] = {
6161         {
6162                 .name = "fast_load_image",
6163                 .handler = handle_fast_load_image_command,
6164                 .mode = COMMAND_ANY,
6165                 .help = "Load image into server memory for later use by "
6166                         "fast_load; primarily for profiling",
6167                 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6168                         "[min_address [max_length]]",
6169         },
6170         {
6171                 .name = "fast_load",
6172                 .handler = handle_fast_load_command,
6173                 .mode = COMMAND_EXEC,
6174                 .help = "loads active fast load image to current target "
6175                         "- mainly for profiling purposes",
6176                 .usage = "",
6177         },
6178         {
6179                 .name = "profile",
6180                 .handler = handle_profile_command,
6181                 .mode = COMMAND_EXEC,
6182                 .usage = "seconds filename [start end]",
6183                 .help = "profiling samples the CPU PC",
6184         },
6185         /** @todo don't register virt2phys() unless target supports it */
6186         {
6187                 .name = "virt2phys",
6188                 .handler = handle_virt2phys_command,
6189                 .mode = COMMAND_ANY,
6190                 .help = "translate a virtual address into a physical address",
6191                 .usage = "virtual_address",
6192         },
6193         {
6194                 .name = "reg",
6195                 .handler = handle_reg_command,
6196                 .mode = COMMAND_EXEC,
6197                 .help = "display (reread from target with \"force\") or set a register; "
6198                         "with no arguments, displays all registers and their values",
6199                 .usage = "[(register_number|register_name) [(value|'force')]]",
6200         },
6201         {
6202                 .name = "poll",
6203                 .handler = handle_poll_command,
6204                 .mode = COMMAND_EXEC,
6205                 .help = "poll target state; or reconfigure background polling",
6206                 .usage = "['on'|'off']",
6207         },
6208         {
6209                 .name = "wait_halt",
6210                 .handler = handle_wait_halt_command,
6211                 .mode = COMMAND_EXEC,
6212                 .help = "wait up to the specified number of milliseconds "
6213                         "(default 5000) for a previously requested halt",
6214                 .usage = "[milliseconds]",
6215         },
6216         {
6217                 .name = "halt",
6218                 .handler = handle_halt_command,
6219                 .mode = COMMAND_EXEC,
6220                 .help = "request target to halt, then wait up to the specified"
6221                         "number of milliseconds (default 5000) for it to complete",
6222                 .usage = "[milliseconds]",
6223         },
6224         {
6225                 .name = "resume",
6226                 .handler = handle_resume_command,
6227                 .mode = COMMAND_EXEC,
6228                 .help = "resume target execution from current PC or address",
6229                 .usage = "[address]",
6230         },
6231         {
6232                 .name = "reset",
6233                 .handler = handle_reset_command,
6234                 .mode = COMMAND_EXEC,
6235                 .usage = "[run|halt|init]",
6236                 .help = "Reset all targets into the specified mode."
6237                         "Default reset mode is run, if not given.",
6238         },
6239         {
6240                 .name = "soft_reset_halt",
6241                 .handler = handle_soft_reset_halt_command,
6242                 .mode = COMMAND_EXEC,
6243                 .usage = "",
6244                 .help = "halt the target and do a soft reset",
6245         },
6246         {
6247                 .name = "step",
6248                 .handler = handle_step_command,
6249                 .mode = COMMAND_EXEC,
6250                 .help = "step one instruction from current PC or address",
6251                 .usage = "[address]",
6252         },
6253         {
6254                 .name = "mdd",
6255                 .handler = handle_md_command,
6256                 .mode = COMMAND_EXEC,
6257                 .help = "display memory double-words",
6258                 .usage = "['phys'] address [count]",
6259         },
6260         {
6261                 .name = "mdw",
6262                 .handler = handle_md_command,
6263                 .mode = COMMAND_EXEC,
6264                 .help = "display memory words",
6265                 .usage = "['phys'] address [count]",
6266         },
6267         {
6268                 .name = "mdh",
6269                 .handler = handle_md_command,
6270                 .mode = COMMAND_EXEC,
6271                 .help = "display memory half-words",
6272                 .usage = "['phys'] address [count]",
6273         },
6274         {
6275                 .name = "mdb",
6276                 .handler = handle_md_command,
6277                 .mode = COMMAND_EXEC,
6278                 .help = "display memory bytes",
6279                 .usage = "['phys'] address [count]",
6280         },
6281         {
6282                 .name = "mwd",
6283                 .handler = handle_mw_command,
6284                 .mode = COMMAND_EXEC,
6285                 .help = "write memory double-word",
6286                 .usage = "['phys'] address value [count]",
6287         },
6288         {
6289                 .name = "mww",
6290                 .handler = handle_mw_command,
6291                 .mode = COMMAND_EXEC,
6292                 .help = "write memory word",
6293                 .usage = "['phys'] address value [count]",
6294         },
6295         {
6296                 .name = "mwh",
6297                 .handler = handle_mw_command,
6298                 .mode = COMMAND_EXEC,
6299                 .help = "write memory half-word",
6300                 .usage = "['phys'] address value [count]",
6301         },
6302         {
6303                 .name = "mwb",
6304                 .handler = handle_mw_command,
6305                 .mode = COMMAND_EXEC,
6306                 .help = "write memory byte",
6307                 .usage = "['phys'] address value [count]",
6308         },
6309         {
6310                 .name = "bp",
6311                 .handler = handle_bp_command,
6312                 .mode = COMMAND_EXEC,
6313                 .help = "list or set hardware or software breakpoint",
6314                 .usage = "[<address> [<asid>] <length> ['hw'|'hw_ctx']]",
6315         },
6316         {
6317                 .name = "rbp",
6318                 .handler = handle_rbp_command,
6319                 .mode = COMMAND_EXEC,
6320                 .help = "remove breakpoint",
6321                 .usage = "address",
6322         },
6323         {
6324                 .name = "wp",
6325                 .handler = handle_wp_command,
6326                 .mode = COMMAND_EXEC,
6327                 .help = "list (no params) or create watchpoints",
6328                 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
6329         },
6330         {
6331                 .name = "rwp",
6332                 .handler = handle_rwp_command,
6333                 .mode = COMMAND_EXEC,
6334                 .help = "remove watchpoint",
6335                 .usage = "address",
6336         },
6337         {
6338                 .name = "load_image",
6339                 .handler = handle_load_image_command,
6340                 .mode = COMMAND_EXEC,
6341                 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6342                         "[min_address] [max_length]",
6343         },
6344         {
6345                 .name = "dump_image",
6346                 .handler = handle_dump_image_command,
6347                 .mode = COMMAND_EXEC,
6348                 .usage = "filename address size",
6349         },
6350         {
6351                 .name = "verify_image_checksum",
6352                 .handler = handle_verify_image_checksum_command,
6353                 .mode = COMMAND_EXEC,
6354                 .usage = "filename [offset [type]]",
6355         },
6356         {
6357                 .name = "verify_image",
6358                 .handler = handle_verify_image_command,
6359                 .mode = COMMAND_EXEC,
6360                 .usage = "filename [offset [type]]",
6361         },
6362         {
6363                 .name = "test_image",
6364                 .handler = handle_test_image_command,
6365                 .mode = COMMAND_EXEC,
6366                 .usage = "filename [offset [type]]",
6367         },
6368         {
6369                 .name = "mem2array",
6370                 .mode = COMMAND_EXEC,
6371                 .jim_handler = jim_mem2array,
6372                 .help = "read 8/16/32 bit memory and return as a TCL array "
6373                         "for script processing",
6374                 .usage = "arrayname bitwidth address count",
6375         },
6376         {
6377                 .name = "array2mem",
6378                 .mode = COMMAND_EXEC,
6379                 .jim_handler = jim_array2mem,
6380                 .help = "convert a TCL array to memory locations "
6381                         "and write the 8/16/32 bit values",
6382                 .usage = "arrayname bitwidth address count",
6383         },
6384         {
6385                 .name = "reset_nag",
6386                 .handler = handle_target_reset_nag,
6387                 .mode = COMMAND_ANY,
6388                 .help = "Nag after each reset about options that could have been "
6389                                 "enabled to improve performance. ",
6390                 .usage = "['enable'|'disable']",
6391         },
6392         {
6393                 .name = "ps",
6394                 .handler = handle_ps_command,
6395                 .mode = COMMAND_EXEC,
6396                 .help = "list all tasks ",
6397                 .usage = " ",
6398         },
6399         {
6400                 .name = "test_mem_access",
6401                 .handler = handle_test_mem_access_command,
6402                 .mode = COMMAND_EXEC,
6403                 .help = "Test the target's memory access functions",
6404                 .usage = "size",
6405         },
6406
6407         COMMAND_REGISTRATION_DONE
6408 };
6409 static int target_register_user_commands(struct command_context *cmd_ctx)
6410 {
6411         int retval = ERROR_OK;
6412         retval = target_request_register_commands(cmd_ctx);
6413         if (retval != ERROR_OK)
6414                 return retval;
6415
6416         retval = trace_register_commands(cmd_ctx);
6417         if (retval != ERROR_OK)
6418                 return retval;
6419
6420
6421         return register_commands(cmd_ctx, NULL, target_exec_command_handlers);
6422 }