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