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