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