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