target: add API to temporarily mask target polling
[openocd.git] / src / target / target.c
blob10a25efde6193afeedb04b7310374807df8a7b13
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
3 /***************************************************************************
4 * Copyright (C) 2005 by Dominic Rath *
5 * Dominic.Rath@gmx.de *
6 * *
7 * Copyright (C) 2007-2010 Øyvind Harboe *
8 * oyvind.harboe@zylin.com *
9 * *
10 * Copyright (C) 2008, Duane Ellis *
11 * openocd@duaneeellis.com *
12 * *
13 * Copyright (C) 2008 by Spencer Oliver *
14 * spen@spen-soft.co.uk *
15 * *
16 * Copyright (C) 2008 by Rick Altherr *
17 * kc8apf@kc8apf.net> *
18 * *
19 * Copyright (C) 2011 by Broadcom Corporation *
20 * Evan Hunter - ehunter@broadcom.com *
21 * *
22 * Copyright (C) ST-Ericsson SA 2011 *
23 * michel.jaouen@stericsson.com : smp minimum support *
24 * *
25 * Copyright (C) 2011 Andreas Fritiofson *
26 * andreas.fritiofson@gmail.com *
27 ***************************************************************************/
29 #ifdef HAVE_CONFIG_H
30 #include "config.h"
31 #endif
33 #include <helper/align.h>
34 #include <helper/time_support.h>
35 #include <jtag/jtag.h>
36 #include <flash/nor/core.h>
38 #include "target.h"
39 #include "target_type.h"
40 #include "target_request.h"
41 #include "breakpoints.h"
42 #include "register.h"
43 #include "trace.h"
44 #include "image.h"
45 #include "rtos/rtos.h"
46 #include "transport/transport.h"
47 #include "arm_cti.h"
48 #include "smp.h"
49 #include "semihosting_common.h"
51 /* default halt wait timeout (ms) */
52 #define DEFAULT_HALT_TIMEOUT 5000
54 static int target_read_buffer_default(struct target *target, target_addr_t address,
55 uint32_t count, uint8_t *buffer);
56 static int target_write_buffer_default(struct target *target, target_addr_t address,
57 uint32_t count, const uint8_t *buffer);
58 static int target_array2mem(Jim_Interp *interp, struct target *target,
59 int argc, Jim_Obj * const *argv);
60 static int target_mem2array(Jim_Interp *interp, struct target *target,
61 int argc, Jim_Obj * const *argv);
62 static int target_register_user_commands(struct command_context *cmd_ctx);
63 static int target_get_gdb_fileio_info_default(struct target *target,
64 struct gdb_fileio_info *fileio_info);
65 static int target_gdb_fileio_end_default(struct target *target, int retcode,
66 int fileio_errno, bool ctrl_c);
68 /* targets */
69 extern struct target_type arm7tdmi_target;
70 extern struct target_type arm720t_target;
71 extern struct target_type arm9tdmi_target;
72 extern struct target_type arm920t_target;
73 extern struct target_type arm966e_target;
74 extern struct target_type arm946e_target;
75 extern struct target_type arm926ejs_target;
76 extern struct target_type fa526_target;
77 extern struct target_type feroceon_target;
78 extern struct target_type dragonite_target;
79 extern struct target_type xscale_target;
80 extern struct target_type cortexm_target;
81 extern struct target_type cortexa_target;
82 extern struct target_type aarch64_target;
83 extern struct target_type cortexr4_target;
84 extern struct target_type arm11_target;
85 extern struct target_type ls1_sap_target;
86 extern struct target_type mips_m4k_target;
87 extern struct target_type mips_mips64_target;
88 extern struct target_type avr_target;
89 extern struct target_type dsp563xx_target;
90 extern struct target_type dsp5680xx_target;
91 extern struct target_type testee_target;
92 extern struct target_type avr32_ap7k_target;
93 extern struct target_type hla_target;
94 extern struct target_type nds32_v2_target;
95 extern struct target_type nds32_v3_target;
96 extern struct target_type nds32_v3m_target;
97 extern struct target_type esp32_target;
98 extern struct target_type esp32s2_target;
99 extern struct target_type esp32s3_target;
100 extern struct target_type or1k_target;
101 extern struct target_type quark_x10xx_target;
102 extern struct target_type quark_d20xx_target;
103 extern struct target_type stm8_target;
104 extern struct target_type riscv_target;
105 extern struct target_type mem_ap_target;
106 extern struct target_type esirisc_target;
107 extern struct target_type arcv2_target;
109 static struct target_type *target_types[] = {
110 &arm7tdmi_target,
111 &arm9tdmi_target,
112 &arm920t_target,
113 &arm720t_target,
114 &arm966e_target,
115 &arm946e_target,
116 &arm926ejs_target,
117 &fa526_target,
118 &feroceon_target,
119 &dragonite_target,
120 &xscale_target,
121 &cortexm_target,
122 &cortexa_target,
123 &cortexr4_target,
124 &arm11_target,
125 &ls1_sap_target,
126 &mips_m4k_target,
127 &avr_target,
128 &dsp563xx_target,
129 &dsp5680xx_target,
130 &testee_target,
131 &avr32_ap7k_target,
132 &hla_target,
133 &nds32_v2_target,
134 &nds32_v3_target,
135 &nds32_v3m_target,
136 &esp32_target,
137 &esp32s2_target,
138 &esp32s3_target,
139 &or1k_target,
140 &quark_x10xx_target,
141 &quark_d20xx_target,
142 &stm8_target,
143 &riscv_target,
144 &mem_ap_target,
145 &esirisc_target,
146 &arcv2_target,
147 &aarch64_target,
148 &mips_mips64_target,
149 NULL,
152 struct target *all_targets;
153 static struct target_event_callback *target_event_callbacks;
154 static struct target_timer_callback *target_timer_callbacks;
155 static int64_t target_timer_next_event_value;
156 static LIST_HEAD(target_reset_callback_list);
157 static LIST_HEAD(target_trace_callback_list);
158 static const int polling_interval = TARGET_DEFAULT_POLLING_INTERVAL;
159 static LIST_HEAD(empty_smp_targets);
161 static const struct jim_nvp nvp_assert[] = {
162 { .name = "assert", NVP_ASSERT },
163 { .name = "deassert", NVP_DEASSERT },
164 { .name = "T", NVP_ASSERT },
165 { .name = "F", NVP_DEASSERT },
166 { .name = "t", NVP_ASSERT },
167 { .name = "f", NVP_DEASSERT },
168 { .name = NULL, .value = -1 }
171 static const struct jim_nvp nvp_error_target[] = {
172 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
173 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
174 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
175 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
176 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
177 { .value = ERROR_TARGET_UNALIGNED_ACCESS, .name = "err-unaligned-access" },
178 { .value = ERROR_TARGET_DATA_ABORT, .name = "err-data-abort" },
179 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE, .name = "err-resource-not-available" },
180 { .value = ERROR_TARGET_TRANSLATION_FAULT, .name = "err-translation-fault" },
181 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
182 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
183 { .value = -1, .name = NULL }
186 static const char *target_strerror_safe(int err)
188 const struct jim_nvp *n;
190 n = jim_nvp_value2name_simple(nvp_error_target, err);
191 if (!n->name)
192 return "unknown";
193 else
194 return n->name;
197 static const struct jim_nvp nvp_target_event[] = {
199 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
200 { .value = TARGET_EVENT_HALTED, .name = "halted" },
201 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
202 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
203 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
204 { .value = TARGET_EVENT_STEP_START, .name = "step-start" },
205 { .value = TARGET_EVENT_STEP_END, .name = "step-end" },
207 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
208 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
210 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
211 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
212 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
213 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
214 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
215 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
216 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
217 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
219 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
220 { .value = TARGET_EVENT_EXAMINE_FAIL, .name = "examine-fail" },
221 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
223 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
224 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
226 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
227 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
229 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
230 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END, .name = "gdb-flash-write-end" },
232 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
233 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END, .name = "gdb-flash-erase-end" },
235 { .value = TARGET_EVENT_TRACE_CONFIG, .name = "trace-config" },
237 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x100, .name = "semihosting-user-cmd-0x100" },
238 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x101, .name = "semihosting-user-cmd-0x101" },
239 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x102, .name = "semihosting-user-cmd-0x102" },
240 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x103, .name = "semihosting-user-cmd-0x103" },
241 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x104, .name = "semihosting-user-cmd-0x104" },
242 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x105, .name = "semihosting-user-cmd-0x105" },
243 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x106, .name = "semihosting-user-cmd-0x106" },
244 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x107, .name = "semihosting-user-cmd-0x107" },
246 { .name = NULL, .value = -1 }
249 static const struct jim_nvp nvp_target_state[] = {
250 { .name = "unknown", .value = TARGET_UNKNOWN },
251 { .name = "running", .value = TARGET_RUNNING },
252 { .name = "halted", .value = TARGET_HALTED },
253 { .name = "reset", .value = TARGET_RESET },
254 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
255 { .name = NULL, .value = -1 },
258 static const struct jim_nvp nvp_target_debug_reason[] = {
259 { .name = "debug-request", .value = DBG_REASON_DBGRQ },
260 { .name = "breakpoint", .value = DBG_REASON_BREAKPOINT },
261 { .name = "watchpoint", .value = DBG_REASON_WATCHPOINT },
262 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
263 { .name = "single-step", .value = DBG_REASON_SINGLESTEP },
264 { .name = "target-not-halted", .value = DBG_REASON_NOTHALTED },
265 { .name = "program-exit", .value = DBG_REASON_EXIT },
266 { .name = "exception-catch", .value = DBG_REASON_EXC_CATCH },
267 { .name = "undefined", .value = DBG_REASON_UNDEFINED },
268 { .name = NULL, .value = -1 },
271 static const struct jim_nvp nvp_target_endian[] = {
272 { .name = "big", .value = TARGET_BIG_ENDIAN },
273 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
274 { .name = "be", .value = TARGET_BIG_ENDIAN },
275 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
276 { .name = NULL, .value = -1 },
279 static const struct jim_nvp nvp_reset_modes[] = {
280 { .name = "unknown", .value = RESET_UNKNOWN },
281 { .name = "run", .value = RESET_RUN },
282 { .name = "halt", .value = RESET_HALT },
283 { .name = "init", .value = RESET_INIT },
284 { .name = NULL, .value = -1 },
287 const char *debug_reason_name(struct target *t)
289 const char *cp;
291 cp = jim_nvp_value2name_simple(nvp_target_debug_reason,
292 t->debug_reason)->name;
293 if (!cp) {
294 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
295 cp = "(*BUG*unknown*BUG*)";
297 return cp;
300 const char *target_state_name(struct target *t)
302 const char *cp;
303 cp = jim_nvp_value2name_simple(nvp_target_state, t->state)->name;
304 if (!cp) {
305 LOG_ERROR("Invalid target state: %d", (int)(t->state));
306 cp = "(*BUG*unknown*BUG*)";
309 if (!target_was_examined(t) && t->defer_examine)
310 cp = "examine deferred";
312 return cp;
315 const char *target_event_name(enum target_event event)
317 const char *cp;
318 cp = jim_nvp_value2name_simple(nvp_target_event, event)->name;
319 if (!cp) {
320 LOG_ERROR("Invalid target event: %d", (int)(event));
321 cp = "(*BUG*unknown*BUG*)";
323 return cp;
326 const char *target_reset_mode_name(enum target_reset_mode reset_mode)
328 const char *cp;
329 cp = jim_nvp_value2name_simple(nvp_reset_modes, reset_mode)->name;
330 if (!cp) {
331 LOG_ERROR("Invalid target reset mode: %d", (int)(reset_mode));
332 cp = "(*BUG*unknown*BUG*)";
334 return cp;
337 /* determine the number of the new target */
338 static int new_target_number(void)
340 struct target *t;
341 int x;
343 /* number is 0 based */
344 x = -1;
345 t = all_targets;
346 while (t) {
347 if (x < t->target_number)
348 x = t->target_number;
349 t = t->next;
351 return x + 1;
354 static void append_to_list_all_targets(struct target *target)
356 struct target **t = &all_targets;
358 while (*t)
359 t = &((*t)->next);
360 *t = target;
363 /* read a uint64_t from a buffer in target memory endianness */
364 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
366 if (target->endianness == TARGET_LITTLE_ENDIAN)
367 return le_to_h_u64(buffer);
368 else
369 return be_to_h_u64(buffer);
372 /* read a uint32_t from a buffer in target memory endianness */
373 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
375 if (target->endianness == TARGET_LITTLE_ENDIAN)
376 return le_to_h_u32(buffer);
377 else
378 return be_to_h_u32(buffer);
381 /* read a uint24_t from a buffer in target memory endianness */
382 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
384 if (target->endianness == TARGET_LITTLE_ENDIAN)
385 return le_to_h_u24(buffer);
386 else
387 return be_to_h_u24(buffer);
390 /* read a uint16_t from a buffer in target memory endianness */
391 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
393 if (target->endianness == TARGET_LITTLE_ENDIAN)
394 return le_to_h_u16(buffer);
395 else
396 return be_to_h_u16(buffer);
399 /* write a uint64_t to a buffer in target memory endianness */
400 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
402 if (target->endianness == TARGET_LITTLE_ENDIAN)
403 h_u64_to_le(buffer, value);
404 else
405 h_u64_to_be(buffer, value);
408 /* write a uint32_t to a buffer in target memory endianness */
409 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
411 if (target->endianness == TARGET_LITTLE_ENDIAN)
412 h_u32_to_le(buffer, value);
413 else
414 h_u32_to_be(buffer, value);
417 /* write a uint24_t to a buffer in target memory endianness */
418 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
420 if (target->endianness == TARGET_LITTLE_ENDIAN)
421 h_u24_to_le(buffer, value);
422 else
423 h_u24_to_be(buffer, value);
426 /* write a uint16_t to a buffer in target memory endianness */
427 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
429 if (target->endianness == TARGET_LITTLE_ENDIAN)
430 h_u16_to_le(buffer, value);
431 else
432 h_u16_to_be(buffer, value);
435 /* write a uint8_t to a buffer in target memory endianness */
436 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
438 *buffer = value;
441 /* write a uint64_t array to a buffer in target memory endianness */
442 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
444 uint32_t i;
445 for (i = 0; i < count; i++)
446 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
449 /* write a uint32_t array to a buffer in target memory endianness */
450 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
452 uint32_t i;
453 for (i = 0; i < count; i++)
454 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
457 /* write a uint16_t array to a buffer in target memory endianness */
458 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
460 uint32_t i;
461 for (i = 0; i < count; i++)
462 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
465 /* write a uint64_t array to a buffer in target memory endianness */
466 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
468 uint32_t i;
469 for (i = 0; i < count; i++)
470 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
473 /* write a uint32_t array to a buffer in target memory endianness */
474 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
476 uint32_t i;
477 for (i = 0; i < count; i++)
478 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
481 /* write a uint16_t array to a buffer in target memory endianness */
482 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
484 uint32_t i;
485 for (i = 0; i < count; i++)
486 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
489 /* return a pointer to a configured target; id is name or number */
490 struct target *get_target(const char *id)
492 struct target *target;
494 /* try as tcltarget name */
495 for (target = all_targets; target; target = target->next) {
496 if (!target_name(target))
497 continue;
498 if (strcmp(id, target_name(target)) == 0)
499 return target;
502 /* It's OK to remove this fallback sometime after August 2010 or so */
504 /* no match, try as number */
505 unsigned num;
506 if (parse_uint(id, &num) != ERROR_OK)
507 return NULL;
509 for (target = all_targets; target; target = target->next) {
510 if (target->target_number == (int)num) {
511 LOG_WARNING("use '%s' as target identifier, not '%u'",
512 target_name(target), num);
513 return target;
517 return NULL;
520 /* returns a pointer to the n-th configured target */
521 struct target *get_target_by_num(int num)
523 struct target *target = all_targets;
525 while (target) {
526 if (target->target_number == num)
527 return target;
528 target = target->next;
531 return NULL;
534 struct target *get_current_target(struct command_context *cmd_ctx)
536 struct target *target = get_current_target_or_null(cmd_ctx);
538 if (!target) {
539 LOG_ERROR("BUG: current_target out of bounds");
540 exit(-1);
543 return target;
546 struct target *get_current_target_or_null(struct command_context *cmd_ctx)
548 return cmd_ctx->current_target_override
549 ? cmd_ctx->current_target_override
550 : cmd_ctx->current_target;
553 int target_poll(struct target *target)
555 int retval;
557 /* We can't poll until after examine */
558 if (!target_was_examined(target)) {
559 /* Fail silently lest we pollute the log */
560 return ERROR_FAIL;
563 retval = target->type->poll(target);
564 if (retval != ERROR_OK)
565 return retval;
567 if (target->halt_issued) {
568 if (target->state == TARGET_HALTED)
569 target->halt_issued = false;
570 else {
571 int64_t t = timeval_ms() - target->halt_issued_time;
572 if (t > DEFAULT_HALT_TIMEOUT) {
573 target->halt_issued = false;
574 LOG_INFO("Halt timed out, wake up GDB.");
575 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
580 return ERROR_OK;
583 int target_halt(struct target *target)
585 int retval;
586 /* We can't poll until after examine */
587 if (!target_was_examined(target)) {
588 LOG_ERROR("Target not examined yet");
589 return ERROR_FAIL;
592 retval = target->type->halt(target);
593 if (retval != ERROR_OK)
594 return retval;
596 target->halt_issued = true;
597 target->halt_issued_time = timeval_ms();
599 return ERROR_OK;
603 * Make the target (re)start executing using its saved execution
604 * context (possibly with some modifications).
606 * @param target Which target should start executing.
607 * @param current True to use the target's saved program counter instead
608 * of the address parameter
609 * @param address Optionally used as the program counter.
610 * @param handle_breakpoints True iff breakpoints at the resumption PC
611 * should be skipped. (For example, maybe execution was stopped by
612 * such a breakpoint, in which case it would be counterproductive to
613 * let it re-trigger.
614 * @param debug_execution False if all working areas allocated by OpenOCD
615 * should be released and/or restored to their original contents.
616 * (This would for example be true to run some downloaded "helper"
617 * algorithm code, which resides in one such working buffer and uses
618 * another for data storage.)
620 * @todo Resolve the ambiguity about what the "debug_execution" flag
621 * signifies. For example, Target implementations don't agree on how
622 * it relates to invalidation of the register cache, or to whether
623 * breakpoints and watchpoints should be enabled. (It would seem wrong
624 * to enable breakpoints when running downloaded "helper" algorithms
625 * (debug_execution true), since the breakpoints would be set to match
626 * target firmware being debugged, not the helper algorithm.... and
627 * enabling them could cause such helpers to malfunction (for example,
628 * by overwriting data with a breakpoint instruction. On the other
629 * hand the infrastructure for running such helpers might use this
630 * procedure but rely on hardware breakpoint to detect termination.)
632 int target_resume(struct target *target, int current, target_addr_t address,
633 int handle_breakpoints, int debug_execution)
635 int retval;
637 /* We can't poll until after examine */
638 if (!target_was_examined(target)) {
639 LOG_ERROR("Target not examined yet");
640 return ERROR_FAIL;
643 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
645 /* note that resume *must* be asynchronous. The CPU can halt before
646 * we poll. The CPU can even halt at the current PC as a result of
647 * a software breakpoint being inserted by (a bug?) the application.
650 * resume() triggers the event 'resumed'. The execution of TCL commands
651 * in the event handler causes the polling of targets. If the target has
652 * already halted for a breakpoint, polling will run the 'halted' event
653 * handler before the pending 'resumed' handler.
654 * Disable polling during resume() to guarantee the execution of handlers
655 * in the correct order.
657 bool save_poll_mask = jtag_poll_mask();
658 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
659 jtag_poll_unmask(save_poll_mask);
661 if (retval != ERROR_OK)
662 return retval;
664 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
666 return retval;
669 static int target_process_reset(struct command_invocation *cmd, enum target_reset_mode reset_mode)
671 char buf[100];
672 int retval;
673 struct jim_nvp *n;
674 n = jim_nvp_value2name_simple(nvp_reset_modes, reset_mode);
675 if (!n->name) {
676 LOG_ERROR("invalid reset mode");
677 return ERROR_FAIL;
680 struct target *target;
681 for (target = all_targets; target; target = target->next)
682 target_call_reset_callbacks(target, reset_mode);
684 /* disable polling during reset to make reset event scripts
685 * more predictable, i.e. dr/irscan & pathmove in events will
686 * not have JTAG operations injected into the middle of a sequence.
688 bool save_poll_mask = jtag_poll_mask();
690 sprintf(buf, "ocd_process_reset %s", n->name);
691 retval = Jim_Eval(cmd->ctx->interp, buf);
693 jtag_poll_unmask(save_poll_mask);
695 if (retval != JIM_OK) {
696 Jim_MakeErrorMessage(cmd->ctx->interp);
697 command_print(cmd, "%s", Jim_GetString(Jim_GetResult(cmd->ctx->interp), NULL));
698 return ERROR_FAIL;
701 /* We want any events to be processed before the prompt */
702 retval = target_call_timer_callbacks_now();
704 for (target = all_targets; target; target = target->next) {
705 target->type->check_reset(target);
706 target->running_alg = false;
709 return retval;
712 static int identity_virt2phys(struct target *target,
713 target_addr_t virtual, target_addr_t *physical)
715 *physical = virtual;
716 return ERROR_OK;
719 static int no_mmu(struct target *target, int *enabled)
721 *enabled = 0;
722 return ERROR_OK;
726 * Reset the @c examined flag for the given target.
727 * Pure paranoia -- targets are zeroed on allocation.
729 static inline void target_reset_examined(struct target *target)
731 target->examined = false;
734 static int default_examine(struct target *target)
736 target_set_examined(target);
737 return ERROR_OK;
740 /* no check by default */
741 static int default_check_reset(struct target *target)
743 return ERROR_OK;
746 /* Equivalent Tcl code arp_examine_one is in src/target/startup.tcl
747 * Keep in sync */
748 int target_examine_one(struct target *target)
750 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
752 int retval = target->type->examine(target);
753 if (retval != ERROR_OK) {
754 target_reset_examined(target);
755 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_FAIL);
756 return retval;
759 target_set_examined(target);
760 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
762 return ERROR_OK;
765 static int jtag_enable_callback(enum jtag_event event, void *priv)
767 struct target *target = priv;
769 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
770 return ERROR_OK;
772 jtag_unregister_event_callback(jtag_enable_callback, target);
774 return target_examine_one(target);
777 /* Targets that correctly implement init + examine, i.e.
778 * no communication with target during init:
780 * XScale
782 int target_examine(void)
784 int retval = ERROR_OK;
785 struct target *target;
787 for (target = all_targets; target; target = target->next) {
788 /* defer examination, but don't skip it */
789 if (!target->tap->enabled) {
790 jtag_register_event_callback(jtag_enable_callback,
791 target);
792 continue;
795 if (target->defer_examine)
796 continue;
798 int retval2 = target_examine_one(target);
799 if (retval2 != ERROR_OK) {
800 LOG_WARNING("target %s examination failed", target_name(target));
801 retval = retval2;
804 return retval;
807 const char *target_type_name(struct target *target)
809 return target->type->name;
812 static int target_soft_reset_halt(struct target *target)
814 if (!target_was_examined(target)) {
815 LOG_ERROR("Target not examined yet");
816 return ERROR_FAIL;
818 if (!target->type->soft_reset_halt) {
819 LOG_ERROR("Target %s does not support soft_reset_halt",
820 target_name(target));
821 return ERROR_FAIL;
823 return target->type->soft_reset_halt(target);
827 * Downloads a target-specific native code algorithm to the target,
828 * and executes it. * Note that some targets may need to set up, enable,
829 * and tear down a breakpoint (hard or * soft) to detect algorithm
830 * termination, while others may support lower overhead schemes where
831 * soft breakpoints embedded in the algorithm automatically terminate the
832 * algorithm.
834 * @param target used to run the algorithm
835 * @param num_mem_params
836 * @param mem_params
837 * @param num_reg_params
838 * @param reg_param
839 * @param entry_point
840 * @param exit_point
841 * @param timeout_ms
842 * @param arch_info target-specific description of the algorithm.
844 int target_run_algorithm(struct target *target,
845 int num_mem_params, struct mem_param *mem_params,
846 int num_reg_params, struct reg_param *reg_param,
847 target_addr_t entry_point, target_addr_t exit_point,
848 int timeout_ms, void *arch_info)
850 int retval = ERROR_FAIL;
852 if (!target_was_examined(target)) {
853 LOG_ERROR("Target not examined yet");
854 goto done;
856 if (!target->type->run_algorithm) {
857 LOG_ERROR("Target type '%s' does not support %s",
858 target_type_name(target), __func__);
859 goto done;
862 target->running_alg = true;
863 retval = target->type->run_algorithm(target,
864 num_mem_params, mem_params,
865 num_reg_params, reg_param,
866 entry_point, exit_point, timeout_ms, arch_info);
867 target->running_alg = false;
869 done:
870 return retval;
874 * Executes a target-specific native code algorithm and leaves it running.
876 * @param target used to run the algorithm
877 * @param num_mem_params
878 * @param mem_params
879 * @param num_reg_params
880 * @param reg_params
881 * @param entry_point
882 * @param exit_point
883 * @param arch_info target-specific description of the algorithm.
885 int target_start_algorithm(struct target *target,
886 int num_mem_params, struct mem_param *mem_params,
887 int num_reg_params, struct reg_param *reg_params,
888 target_addr_t entry_point, target_addr_t exit_point,
889 void *arch_info)
891 int retval = ERROR_FAIL;
893 if (!target_was_examined(target)) {
894 LOG_ERROR("Target not examined yet");
895 goto done;
897 if (!target->type->start_algorithm) {
898 LOG_ERROR("Target type '%s' does not support %s",
899 target_type_name(target), __func__);
900 goto done;
902 if (target->running_alg) {
903 LOG_ERROR("Target is already running an algorithm");
904 goto done;
907 target->running_alg = true;
908 retval = target->type->start_algorithm(target,
909 num_mem_params, mem_params,
910 num_reg_params, reg_params,
911 entry_point, exit_point, arch_info);
913 done:
914 return retval;
918 * Waits for an algorithm started with target_start_algorithm() to complete.
920 * @param target used to run the algorithm
921 * @param num_mem_params
922 * @param mem_params
923 * @param num_reg_params
924 * @param reg_params
925 * @param exit_point
926 * @param timeout_ms
927 * @param arch_info target-specific description of the algorithm.
929 int target_wait_algorithm(struct target *target,
930 int num_mem_params, struct mem_param *mem_params,
931 int num_reg_params, struct reg_param *reg_params,
932 target_addr_t exit_point, int timeout_ms,
933 void *arch_info)
935 int retval = ERROR_FAIL;
937 if (!target->type->wait_algorithm) {
938 LOG_ERROR("Target type '%s' does not support %s",
939 target_type_name(target), __func__);
940 goto done;
942 if (!target->running_alg) {
943 LOG_ERROR("Target is not running an algorithm");
944 goto done;
947 retval = target->type->wait_algorithm(target,
948 num_mem_params, mem_params,
949 num_reg_params, reg_params,
950 exit_point, timeout_ms, arch_info);
951 if (retval != ERROR_TARGET_TIMEOUT)
952 target->running_alg = false;
954 done:
955 return retval;
959 * Streams data to a circular buffer on target intended for consumption by code
960 * running asynchronously on target.
962 * This is intended for applications where target-specific native code runs
963 * on the target, receives data from the circular buffer, does something with
964 * it (most likely writing it to a flash memory), and advances the circular
965 * buffer pointer.
967 * This assumes that the helper algorithm has already been loaded to the target,
968 * but has not been started yet. Given memory and register parameters are passed
969 * to the algorithm.
971 * The buffer is defined by (buffer_start, buffer_size) arguments and has the
972 * following format:
974 * [buffer_start + 0, buffer_start + 4):
975 * Write Pointer address (aka head). Written and updated by this
976 * routine when new data is written to the circular buffer.
977 * [buffer_start + 4, buffer_start + 8):
978 * Read Pointer address (aka tail). Updated by code running on the
979 * target after it consumes data.
980 * [buffer_start + 8, buffer_start + buffer_size):
981 * Circular buffer contents.
983 * See contrib/loaders/flash/stm32f1x.S for an example.
985 * @param target used to run the algorithm
986 * @param buffer address on the host where data to be sent is located
987 * @param count number of blocks to send
988 * @param block_size size in bytes of each block
989 * @param num_mem_params count of memory-based params to pass to algorithm
990 * @param mem_params memory-based params to pass to algorithm
991 * @param num_reg_params count of register-based params to pass to algorithm
992 * @param reg_params memory-based params to pass to algorithm
993 * @param buffer_start address on the target of the circular buffer structure
994 * @param buffer_size size of the circular buffer structure
995 * @param entry_point address on the target to execute to start the algorithm
996 * @param exit_point address at which to set a breakpoint to catch the
997 * end of the algorithm; can be 0 if target triggers a breakpoint itself
998 * @param arch_info
1001 int target_run_flash_async_algorithm(struct target *target,
1002 const uint8_t *buffer, uint32_t count, int block_size,
1003 int num_mem_params, struct mem_param *mem_params,
1004 int num_reg_params, struct reg_param *reg_params,
1005 uint32_t buffer_start, uint32_t buffer_size,
1006 uint32_t entry_point, uint32_t exit_point, void *arch_info)
1008 int retval;
1009 int timeout = 0;
1011 const uint8_t *buffer_orig = buffer;
1013 /* Set up working area. First word is write pointer, second word is read pointer,
1014 * rest is fifo data area. */
1015 uint32_t wp_addr = buffer_start;
1016 uint32_t rp_addr = buffer_start + 4;
1017 uint32_t fifo_start_addr = buffer_start + 8;
1018 uint32_t fifo_end_addr = buffer_start + buffer_size;
1020 uint32_t wp = fifo_start_addr;
1021 uint32_t rp = fifo_start_addr;
1023 /* validate block_size is 2^n */
1024 assert(IS_PWR_OF_2(block_size));
1026 retval = target_write_u32(target, wp_addr, wp);
1027 if (retval != ERROR_OK)
1028 return retval;
1029 retval = target_write_u32(target, rp_addr, rp);
1030 if (retval != ERROR_OK)
1031 return retval;
1033 /* Start up algorithm on target and let it idle while writing the first chunk */
1034 retval = target_start_algorithm(target, num_mem_params, mem_params,
1035 num_reg_params, reg_params,
1036 entry_point,
1037 exit_point,
1038 arch_info);
1040 if (retval != ERROR_OK) {
1041 LOG_ERROR("error starting target flash write algorithm");
1042 return retval;
1045 while (count > 0) {
1047 retval = target_read_u32(target, rp_addr, &rp);
1048 if (retval != ERROR_OK) {
1049 LOG_ERROR("failed to get read pointer");
1050 break;
1053 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1054 (size_t) (buffer - buffer_orig), count, wp, rp);
1056 if (rp == 0) {
1057 LOG_ERROR("flash write algorithm aborted by target");
1058 retval = ERROR_FLASH_OPERATION_FAILED;
1059 break;
1062 if (!IS_ALIGNED(rp - fifo_start_addr, block_size) || rp < fifo_start_addr || rp >= fifo_end_addr) {
1063 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
1064 break;
1067 /* Count the number of bytes available in the fifo without
1068 * crossing the wrap around. Make sure to not fill it completely,
1069 * because that would make wp == rp and that's the empty condition. */
1070 uint32_t thisrun_bytes;
1071 if (rp > wp)
1072 thisrun_bytes = rp - wp - block_size;
1073 else if (rp > fifo_start_addr)
1074 thisrun_bytes = fifo_end_addr - wp;
1075 else
1076 thisrun_bytes = fifo_end_addr - wp - block_size;
1078 if (thisrun_bytes == 0) {
1079 /* Throttle polling a bit if transfer is (much) faster than flash
1080 * programming. The exact delay shouldn't matter as long as it's
1081 * less than buffer size / flash speed. This is very unlikely to
1082 * run when using high latency connections such as USB. */
1083 alive_sleep(2);
1085 /* to stop an infinite loop on some targets check and increment a timeout
1086 * this issue was observed on a stellaris using the new ICDI interface */
1087 if (timeout++ >= 2500) {
1088 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1089 return ERROR_FLASH_OPERATION_FAILED;
1091 continue;
1094 /* reset our timeout */
1095 timeout = 0;
1097 /* Limit to the amount of data we actually want to write */
1098 if (thisrun_bytes > count * block_size)
1099 thisrun_bytes = count * block_size;
1101 /* Force end of large blocks to be word aligned */
1102 if (thisrun_bytes >= 16)
1103 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1105 /* Write data to fifo */
1106 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
1107 if (retval != ERROR_OK)
1108 break;
1110 /* Update counters and wrap write pointer */
1111 buffer += thisrun_bytes;
1112 count -= thisrun_bytes / block_size;
1113 wp += thisrun_bytes;
1114 if (wp >= fifo_end_addr)
1115 wp = fifo_start_addr;
1117 /* Store updated write pointer to target */
1118 retval = target_write_u32(target, wp_addr, wp);
1119 if (retval != ERROR_OK)
1120 break;
1122 /* Avoid GDB timeouts */
1123 keep_alive();
1126 if (retval != ERROR_OK) {
1127 /* abort flash write algorithm on target */
1128 target_write_u32(target, wp_addr, 0);
1131 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1132 num_reg_params, reg_params,
1133 exit_point,
1134 10000,
1135 arch_info);
1137 if (retval2 != ERROR_OK) {
1138 LOG_ERROR("error waiting for target flash write algorithm");
1139 retval = retval2;
1142 if (retval == ERROR_OK) {
1143 /* check if algorithm set rp = 0 after fifo writer loop finished */
1144 retval = target_read_u32(target, rp_addr, &rp);
1145 if (retval == ERROR_OK && rp == 0) {
1146 LOG_ERROR("flash write algorithm aborted by target");
1147 retval = ERROR_FLASH_OPERATION_FAILED;
1151 return retval;
1154 int target_run_read_async_algorithm(struct target *target,
1155 uint8_t *buffer, uint32_t count, int block_size,
1156 int num_mem_params, struct mem_param *mem_params,
1157 int num_reg_params, struct reg_param *reg_params,
1158 uint32_t buffer_start, uint32_t buffer_size,
1159 uint32_t entry_point, uint32_t exit_point, void *arch_info)
1161 int retval;
1162 int timeout = 0;
1164 const uint8_t *buffer_orig = buffer;
1166 /* Set up working area. First word is write pointer, second word is read pointer,
1167 * rest is fifo data area. */
1168 uint32_t wp_addr = buffer_start;
1169 uint32_t rp_addr = buffer_start + 4;
1170 uint32_t fifo_start_addr = buffer_start + 8;
1171 uint32_t fifo_end_addr = buffer_start + buffer_size;
1173 uint32_t wp = fifo_start_addr;
1174 uint32_t rp = fifo_start_addr;
1176 /* validate block_size is 2^n */
1177 assert(IS_PWR_OF_2(block_size));
1179 retval = target_write_u32(target, wp_addr, wp);
1180 if (retval != ERROR_OK)
1181 return retval;
1182 retval = target_write_u32(target, rp_addr, rp);
1183 if (retval != ERROR_OK)
1184 return retval;
1186 /* Start up algorithm on target */
1187 retval = target_start_algorithm(target, num_mem_params, mem_params,
1188 num_reg_params, reg_params,
1189 entry_point,
1190 exit_point,
1191 arch_info);
1193 if (retval != ERROR_OK) {
1194 LOG_ERROR("error starting target flash read algorithm");
1195 return retval;
1198 while (count > 0) {
1199 retval = target_read_u32(target, wp_addr, &wp);
1200 if (retval != ERROR_OK) {
1201 LOG_ERROR("failed to get write pointer");
1202 break;
1205 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1206 (size_t)(buffer - buffer_orig), count, wp, rp);
1208 if (wp == 0) {
1209 LOG_ERROR("flash read algorithm aborted by target");
1210 retval = ERROR_FLASH_OPERATION_FAILED;
1211 break;
1214 if (!IS_ALIGNED(wp - fifo_start_addr, block_size) || wp < fifo_start_addr || wp >= fifo_end_addr) {
1215 LOG_ERROR("corrupted fifo write pointer 0x%" PRIx32, wp);
1216 break;
1219 /* Count the number of bytes available in the fifo without
1220 * crossing the wrap around. */
1221 uint32_t thisrun_bytes;
1222 if (wp >= rp)
1223 thisrun_bytes = wp - rp;
1224 else
1225 thisrun_bytes = fifo_end_addr - rp;
1227 if (thisrun_bytes == 0) {
1228 /* Throttle polling a bit if transfer is (much) faster than flash
1229 * reading. The exact delay shouldn't matter as long as it's
1230 * less than buffer size / flash speed. This is very unlikely to
1231 * run when using high latency connections such as USB. */
1232 alive_sleep(2);
1234 /* to stop an infinite loop on some targets check and increment a timeout
1235 * this issue was observed on a stellaris using the new ICDI interface */
1236 if (timeout++ >= 2500) {
1237 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1238 return ERROR_FLASH_OPERATION_FAILED;
1240 continue;
1243 /* Reset our timeout */
1244 timeout = 0;
1246 /* Limit to the amount of data we actually want to read */
1247 if (thisrun_bytes > count * block_size)
1248 thisrun_bytes = count * block_size;
1250 /* Force end of large blocks to be word aligned */
1251 if (thisrun_bytes >= 16)
1252 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1254 /* Read data from fifo */
1255 retval = target_read_buffer(target, rp, thisrun_bytes, buffer);
1256 if (retval != ERROR_OK)
1257 break;
1259 /* Update counters and wrap write pointer */
1260 buffer += thisrun_bytes;
1261 count -= thisrun_bytes / block_size;
1262 rp += thisrun_bytes;
1263 if (rp >= fifo_end_addr)
1264 rp = fifo_start_addr;
1266 /* Store updated write pointer to target */
1267 retval = target_write_u32(target, rp_addr, rp);
1268 if (retval != ERROR_OK)
1269 break;
1271 /* Avoid GDB timeouts */
1272 keep_alive();
1276 if (retval != ERROR_OK) {
1277 /* abort flash write algorithm on target */
1278 target_write_u32(target, rp_addr, 0);
1281 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1282 num_reg_params, reg_params,
1283 exit_point,
1284 10000,
1285 arch_info);
1287 if (retval2 != ERROR_OK) {
1288 LOG_ERROR("error waiting for target flash write algorithm");
1289 retval = retval2;
1292 if (retval == ERROR_OK) {
1293 /* check if algorithm set wp = 0 after fifo writer loop finished */
1294 retval = target_read_u32(target, wp_addr, &wp);
1295 if (retval == ERROR_OK && wp == 0) {
1296 LOG_ERROR("flash read algorithm aborted by target");
1297 retval = ERROR_FLASH_OPERATION_FAILED;
1301 return retval;
1304 int target_read_memory(struct target *target,
1305 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1307 if (!target_was_examined(target)) {
1308 LOG_ERROR("Target not examined yet");
1309 return ERROR_FAIL;
1311 if (!target->type->read_memory) {
1312 LOG_ERROR("Target %s doesn't support read_memory", target_name(target));
1313 return ERROR_FAIL;
1315 return target->type->read_memory(target, address, size, count, buffer);
1318 int target_read_phys_memory(struct target *target,
1319 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1321 if (!target_was_examined(target)) {
1322 LOG_ERROR("Target not examined yet");
1323 return ERROR_FAIL;
1325 if (!target->type->read_phys_memory) {
1326 LOG_ERROR("Target %s doesn't support read_phys_memory", target_name(target));
1327 return ERROR_FAIL;
1329 return target->type->read_phys_memory(target, address, size, count, buffer);
1332 int target_write_memory(struct target *target,
1333 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1335 if (!target_was_examined(target)) {
1336 LOG_ERROR("Target not examined yet");
1337 return ERROR_FAIL;
1339 if (!target->type->write_memory) {
1340 LOG_ERROR("Target %s doesn't support write_memory", target_name(target));
1341 return ERROR_FAIL;
1343 return target->type->write_memory(target, address, size, count, buffer);
1346 int target_write_phys_memory(struct target *target,
1347 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1349 if (!target_was_examined(target)) {
1350 LOG_ERROR("Target not examined yet");
1351 return ERROR_FAIL;
1353 if (!target->type->write_phys_memory) {
1354 LOG_ERROR("Target %s doesn't support write_phys_memory", target_name(target));
1355 return ERROR_FAIL;
1357 return target->type->write_phys_memory(target, address, size, count, buffer);
1360 int target_add_breakpoint(struct target *target,
1361 struct breakpoint *breakpoint)
1363 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1364 LOG_WARNING("target %s is not halted (add breakpoint)", target_name(target));
1365 return ERROR_TARGET_NOT_HALTED;
1367 return target->type->add_breakpoint(target, breakpoint);
1370 int target_add_context_breakpoint(struct target *target,
1371 struct breakpoint *breakpoint)
1373 if (target->state != TARGET_HALTED) {
1374 LOG_WARNING("target %s is not halted (add context breakpoint)", target_name(target));
1375 return ERROR_TARGET_NOT_HALTED;
1377 return target->type->add_context_breakpoint(target, breakpoint);
1380 int target_add_hybrid_breakpoint(struct target *target,
1381 struct breakpoint *breakpoint)
1383 if (target->state != TARGET_HALTED) {
1384 LOG_WARNING("target %s is not halted (add hybrid breakpoint)", target_name(target));
1385 return ERROR_TARGET_NOT_HALTED;
1387 return target->type->add_hybrid_breakpoint(target, breakpoint);
1390 int target_remove_breakpoint(struct target *target,
1391 struct breakpoint *breakpoint)
1393 return target->type->remove_breakpoint(target, breakpoint);
1396 int target_add_watchpoint(struct target *target,
1397 struct watchpoint *watchpoint)
1399 if (target->state != TARGET_HALTED) {
1400 LOG_WARNING("target %s is not halted (add watchpoint)", target_name(target));
1401 return ERROR_TARGET_NOT_HALTED;
1403 return target->type->add_watchpoint(target, watchpoint);
1405 int target_remove_watchpoint(struct target *target,
1406 struct watchpoint *watchpoint)
1408 return target->type->remove_watchpoint(target, watchpoint);
1410 int target_hit_watchpoint(struct target *target,
1411 struct watchpoint **hit_watchpoint)
1413 if (target->state != TARGET_HALTED) {
1414 LOG_WARNING("target %s is not halted (hit watchpoint)", target->cmd_name);
1415 return ERROR_TARGET_NOT_HALTED;
1418 if (!target->type->hit_watchpoint) {
1419 /* For backward compatible, if hit_watchpoint is not implemented,
1420 * return ERROR_FAIL such that gdb_server will not take the nonsense
1421 * information. */
1422 return ERROR_FAIL;
1425 return target->type->hit_watchpoint(target, hit_watchpoint);
1428 const char *target_get_gdb_arch(struct target *target)
1430 if (!target->type->get_gdb_arch)
1431 return NULL;
1432 return target->type->get_gdb_arch(target);
1435 int target_get_gdb_reg_list(struct target *target,
1436 struct reg **reg_list[], int *reg_list_size,
1437 enum target_register_class reg_class)
1439 int result = ERROR_FAIL;
1441 if (!target_was_examined(target)) {
1442 LOG_ERROR("Target not examined yet");
1443 goto done;
1446 result = target->type->get_gdb_reg_list(target, reg_list,
1447 reg_list_size, reg_class);
1449 done:
1450 if (result != ERROR_OK) {
1451 *reg_list = NULL;
1452 *reg_list_size = 0;
1454 return result;
1457 int target_get_gdb_reg_list_noread(struct target *target,
1458 struct reg **reg_list[], int *reg_list_size,
1459 enum target_register_class reg_class)
1461 if (target->type->get_gdb_reg_list_noread &&
1462 target->type->get_gdb_reg_list_noread(target, reg_list,
1463 reg_list_size, reg_class) == ERROR_OK)
1464 return ERROR_OK;
1465 return target_get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1468 bool target_supports_gdb_connection(struct target *target)
1471 * exclude all the targets that don't provide get_gdb_reg_list
1472 * or that have explicit gdb_max_connection == 0
1474 return !!target->type->get_gdb_reg_list && !!target->gdb_max_connections;
1477 int target_step(struct target *target,
1478 int current, target_addr_t address, int handle_breakpoints)
1480 int retval;
1482 target_call_event_callbacks(target, TARGET_EVENT_STEP_START);
1484 retval = target->type->step(target, current, address, handle_breakpoints);
1485 if (retval != ERROR_OK)
1486 return retval;
1488 target_call_event_callbacks(target, TARGET_EVENT_STEP_END);
1490 return retval;
1493 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1495 if (target->state != TARGET_HALTED) {
1496 LOG_WARNING("target %s is not halted (gdb fileio)", target->cmd_name);
1497 return ERROR_TARGET_NOT_HALTED;
1499 return target->type->get_gdb_fileio_info(target, fileio_info);
1502 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1504 if (target->state != TARGET_HALTED) {
1505 LOG_WARNING("target %s is not halted (gdb fileio end)", target->cmd_name);
1506 return ERROR_TARGET_NOT_HALTED;
1508 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1511 target_addr_t target_address_max(struct target *target)
1513 unsigned bits = target_address_bits(target);
1514 if (sizeof(target_addr_t) * 8 == bits)
1515 return (target_addr_t) -1;
1516 else
1517 return (((target_addr_t) 1) << bits) - 1;
1520 unsigned target_address_bits(struct target *target)
1522 if (target->type->address_bits)
1523 return target->type->address_bits(target);
1524 return 32;
1527 unsigned int target_data_bits(struct target *target)
1529 if (target->type->data_bits)
1530 return target->type->data_bits(target);
1531 return 32;
1534 static int target_profiling(struct target *target, uint32_t *samples,
1535 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1537 return target->type->profiling(target, samples, max_num_samples,
1538 num_samples, seconds);
1541 static int handle_target(void *priv);
1543 static int target_init_one(struct command_context *cmd_ctx,
1544 struct target *target)
1546 target_reset_examined(target);
1548 struct target_type *type = target->type;
1549 if (!type->examine)
1550 type->examine = default_examine;
1552 if (!type->check_reset)
1553 type->check_reset = default_check_reset;
1555 assert(type->init_target);
1557 int retval = type->init_target(cmd_ctx, target);
1558 if (retval != ERROR_OK) {
1559 LOG_ERROR("target '%s' init failed", target_name(target));
1560 return retval;
1563 /* Sanity-check MMU support ... stub in what we must, to help
1564 * implement it in stages, but warn if we need to do so.
1566 if (type->mmu) {
1567 if (!type->virt2phys) {
1568 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1569 type->virt2phys = identity_virt2phys;
1571 } else {
1572 /* Make sure no-MMU targets all behave the same: make no
1573 * distinction between physical and virtual addresses, and
1574 * ensure that virt2phys() is always an identity mapping.
1576 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1577 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1579 type->mmu = no_mmu;
1580 type->write_phys_memory = type->write_memory;
1581 type->read_phys_memory = type->read_memory;
1582 type->virt2phys = identity_virt2phys;
1585 if (!target->type->read_buffer)
1586 target->type->read_buffer = target_read_buffer_default;
1588 if (!target->type->write_buffer)
1589 target->type->write_buffer = target_write_buffer_default;
1591 if (!target->type->get_gdb_fileio_info)
1592 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1594 if (!target->type->gdb_fileio_end)
1595 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1597 if (!target->type->profiling)
1598 target->type->profiling = target_profiling_default;
1600 return ERROR_OK;
1603 static int target_init(struct command_context *cmd_ctx)
1605 struct target *target;
1606 int retval;
1608 for (target = all_targets; target; target = target->next) {
1609 retval = target_init_one(cmd_ctx, target);
1610 if (retval != ERROR_OK)
1611 return retval;
1614 if (!all_targets)
1615 return ERROR_OK;
1617 retval = target_register_user_commands(cmd_ctx);
1618 if (retval != ERROR_OK)
1619 return retval;
1621 retval = target_register_timer_callback(&handle_target,
1622 polling_interval, TARGET_TIMER_TYPE_PERIODIC, cmd_ctx->interp);
1623 if (retval != ERROR_OK)
1624 return retval;
1626 return ERROR_OK;
1629 COMMAND_HANDLER(handle_target_init_command)
1631 int retval;
1633 if (CMD_ARGC != 0)
1634 return ERROR_COMMAND_SYNTAX_ERROR;
1636 static bool target_initialized;
1637 if (target_initialized) {
1638 LOG_INFO("'target init' has already been called");
1639 return ERROR_OK;
1641 target_initialized = true;
1643 retval = command_run_line(CMD_CTX, "init_targets");
1644 if (retval != ERROR_OK)
1645 return retval;
1647 retval = command_run_line(CMD_CTX, "init_target_events");
1648 if (retval != ERROR_OK)
1649 return retval;
1651 retval = command_run_line(CMD_CTX, "init_board");
1652 if (retval != ERROR_OK)
1653 return retval;
1655 LOG_DEBUG("Initializing targets...");
1656 return target_init(CMD_CTX);
1659 int target_register_event_callback(int (*callback)(struct target *target,
1660 enum target_event event, void *priv), void *priv)
1662 struct target_event_callback **callbacks_p = &target_event_callbacks;
1664 if (!callback)
1665 return ERROR_COMMAND_SYNTAX_ERROR;
1667 if (*callbacks_p) {
1668 while ((*callbacks_p)->next)
1669 callbacks_p = &((*callbacks_p)->next);
1670 callbacks_p = &((*callbacks_p)->next);
1673 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1674 (*callbacks_p)->callback = callback;
1675 (*callbacks_p)->priv = priv;
1676 (*callbacks_p)->next = NULL;
1678 return ERROR_OK;
1681 int target_register_reset_callback(int (*callback)(struct target *target,
1682 enum target_reset_mode reset_mode, void *priv), void *priv)
1684 struct target_reset_callback *entry;
1686 if (!callback)
1687 return ERROR_COMMAND_SYNTAX_ERROR;
1689 entry = malloc(sizeof(struct target_reset_callback));
1690 if (!entry) {
1691 LOG_ERROR("error allocating buffer for reset callback entry");
1692 return ERROR_COMMAND_SYNTAX_ERROR;
1695 entry->callback = callback;
1696 entry->priv = priv;
1697 list_add(&entry->list, &target_reset_callback_list);
1700 return ERROR_OK;
1703 int target_register_trace_callback(int (*callback)(struct target *target,
1704 size_t len, uint8_t *data, void *priv), void *priv)
1706 struct target_trace_callback *entry;
1708 if (!callback)
1709 return ERROR_COMMAND_SYNTAX_ERROR;
1711 entry = malloc(sizeof(struct target_trace_callback));
1712 if (!entry) {
1713 LOG_ERROR("error allocating buffer for trace callback entry");
1714 return ERROR_COMMAND_SYNTAX_ERROR;
1717 entry->callback = callback;
1718 entry->priv = priv;
1719 list_add(&entry->list, &target_trace_callback_list);
1722 return ERROR_OK;
1725 int target_register_timer_callback(int (*callback)(void *priv),
1726 unsigned int time_ms, enum target_timer_type type, void *priv)
1728 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1730 if (!callback)
1731 return ERROR_COMMAND_SYNTAX_ERROR;
1733 if (*callbacks_p) {
1734 while ((*callbacks_p)->next)
1735 callbacks_p = &((*callbacks_p)->next);
1736 callbacks_p = &((*callbacks_p)->next);
1739 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1740 (*callbacks_p)->callback = callback;
1741 (*callbacks_p)->type = type;
1742 (*callbacks_p)->time_ms = time_ms;
1743 (*callbacks_p)->removed = false;
1745 (*callbacks_p)->when = timeval_ms() + time_ms;
1746 target_timer_next_event_value = MIN(target_timer_next_event_value, (*callbacks_p)->when);
1748 (*callbacks_p)->priv = priv;
1749 (*callbacks_p)->next = NULL;
1751 return ERROR_OK;
1754 int target_unregister_event_callback(int (*callback)(struct target *target,
1755 enum target_event event, void *priv), void *priv)
1757 struct target_event_callback **p = &target_event_callbacks;
1758 struct target_event_callback *c = target_event_callbacks;
1760 if (!callback)
1761 return ERROR_COMMAND_SYNTAX_ERROR;
1763 while (c) {
1764 struct target_event_callback *next = c->next;
1765 if ((c->callback == callback) && (c->priv == priv)) {
1766 *p = next;
1767 free(c);
1768 return ERROR_OK;
1769 } else
1770 p = &(c->next);
1771 c = next;
1774 return ERROR_OK;
1777 int target_unregister_reset_callback(int (*callback)(struct target *target,
1778 enum target_reset_mode reset_mode, void *priv), void *priv)
1780 struct target_reset_callback *entry;
1782 if (!callback)
1783 return ERROR_COMMAND_SYNTAX_ERROR;
1785 list_for_each_entry(entry, &target_reset_callback_list, list) {
1786 if (entry->callback == callback && entry->priv == priv) {
1787 list_del(&entry->list);
1788 free(entry);
1789 break;
1793 return ERROR_OK;
1796 int target_unregister_trace_callback(int (*callback)(struct target *target,
1797 size_t len, uint8_t *data, void *priv), void *priv)
1799 struct target_trace_callback *entry;
1801 if (!callback)
1802 return ERROR_COMMAND_SYNTAX_ERROR;
1804 list_for_each_entry(entry, &target_trace_callback_list, list) {
1805 if (entry->callback == callback && entry->priv == priv) {
1806 list_del(&entry->list);
1807 free(entry);
1808 break;
1812 return ERROR_OK;
1815 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1817 if (!callback)
1818 return ERROR_COMMAND_SYNTAX_ERROR;
1820 for (struct target_timer_callback *c = target_timer_callbacks;
1821 c; c = c->next) {
1822 if ((c->callback == callback) && (c->priv == priv)) {
1823 c->removed = true;
1824 return ERROR_OK;
1828 return ERROR_FAIL;
1831 int target_call_event_callbacks(struct target *target, enum target_event event)
1833 struct target_event_callback *callback = target_event_callbacks;
1834 struct target_event_callback *next_callback;
1836 if (event == TARGET_EVENT_HALTED) {
1837 /* execute early halted first */
1838 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1841 LOG_DEBUG("target event %i (%s) for core %s", event,
1842 target_event_name(event),
1843 target_name(target));
1845 target_handle_event(target, event);
1847 while (callback) {
1848 next_callback = callback->next;
1849 callback->callback(target, event, callback->priv);
1850 callback = next_callback;
1853 return ERROR_OK;
1856 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1858 struct target_reset_callback *callback;
1860 LOG_DEBUG("target reset %i (%s)", reset_mode,
1861 jim_nvp_value2name_simple(nvp_reset_modes, reset_mode)->name);
1863 list_for_each_entry(callback, &target_reset_callback_list, list)
1864 callback->callback(target, reset_mode, callback->priv);
1866 return ERROR_OK;
1869 int target_call_trace_callbacks(struct target *target, size_t len, uint8_t *data)
1871 struct target_trace_callback *callback;
1873 list_for_each_entry(callback, &target_trace_callback_list, list)
1874 callback->callback(target, len, data, callback->priv);
1876 return ERROR_OK;
1879 static int target_timer_callback_periodic_restart(
1880 struct target_timer_callback *cb, int64_t *now)
1882 cb->when = *now + cb->time_ms;
1883 return ERROR_OK;
1886 static int target_call_timer_callback(struct target_timer_callback *cb,
1887 int64_t *now)
1889 cb->callback(cb->priv);
1891 if (cb->type == TARGET_TIMER_TYPE_PERIODIC)
1892 return target_timer_callback_periodic_restart(cb, now);
1894 return target_unregister_timer_callback(cb->callback, cb->priv);
1897 static int target_call_timer_callbacks_check_time(int checktime)
1899 static bool callback_processing;
1901 /* Do not allow nesting */
1902 if (callback_processing)
1903 return ERROR_OK;
1905 callback_processing = true;
1907 keep_alive();
1909 int64_t now = timeval_ms();
1911 /* Initialize to a default value that's a ways into the future.
1912 * The loop below will make it closer to now if there are
1913 * callbacks that want to be called sooner. */
1914 target_timer_next_event_value = now + 1000;
1916 /* Store an address of the place containing a pointer to the
1917 * next item; initially, that's a standalone "root of the
1918 * list" variable. */
1919 struct target_timer_callback **callback = &target_timer_callbacks;
1920 while (callback && *callback) {
1921 if ((*callback)->removed) {
1922 struct target_timer_callback *p = *callback;
1923 *callback = (*callback)->next;
1924 free(p);
1925 continue;
1928 bool call_it = (*callback)->callback &&
1929 ((!checktime && (*callback)->type == TARGET_TIMER_TYPE_PERIODIC) ||
1930 now >= (*callback)->when);
1932 if (call_it)
1933 target_call_timer_callback(*callback, &now);
1935 if (!(*callback)->removed && (*callback)->when < target_timer_next_event_value)
1936 target_timer_next_event_value = (*callback)->when;
1938 callback = &(*callback)->next;
1941 callback_processing = false;
1942 return ERROR_OK;
1945 int target_call_timer_callbacks()
1947 return target_call_timer_callbacks_check_time(1);
1950 /* invoke periodic callbacks immediately */
1951 int target_call_timer_callbacks_now()
1953 return target_call_timer_callbacks_check_time(0);
1956 int64_t target_timer_next_event(void)
1958 return target_timer_next_event_value;
1961 /* Prints the working area layout for debug purposes */
1962 static void print_wa_layout(struct target *target)
1964 struct working_area *c = target->working_areas;
1966 while (c) {
1967 LOG_DEBUG("%c%c " TARGET_ADDR_FMT "-" TARGET_ADDR_FMT " (%" PRIu32 " bytes)",
1968 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1969 c->address, c->address + c->size - 1, c->size);
1970 c = c->next;
1974 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1975 static void target_split_working_area(struct working_area *area, uint32_t size)
1977 assert(area->free); /* Shouldn't split an allocated area */
1978 assert(size <= area->size); /* Caller should guarantee this */
1980 /* Split only if not already the right size */
1981 if (size < area->size) {
1982 struct working_area *new_wa = malloc(sizeof(*new_wa));
1984 if (!new_wa)
1985 return;
1987 new_wa->next = area->next;
1988 new_wa->size = area->size - size;
1989 new_wa->address = area->address + size;
1990 new_wa->backup = NULL;
1991 new_wa->user = NULL;
1992 new_wa->free = true;
1994 area->next = new_wa;
1995 area->size = size;
1997 /* If backup memory was allocated to this area, it has the wrong size
1998 * now so free it and it will be reallocated if/when needed */
1999 free(area->backup);
2000 area->backup = NULL;
2004 /* Merge all adjacent free areas into one */
2005 static void target_merge_working_areas(struct target *target)
2007 struct working_area *c = target->working_areas;
2009 while (c && c->next) {
2010 assert(c->next->address == c->address + c->size); /* This is an invariant */
2012 /* Find two adjacent free areas */
2013 if (c->free && c->next->free) {
2014 /* Merge the last into the first */
2015 c->size += c->next->size;
2017 /* Remove the last */
2018 struct working_area *to_be_freed = c->next;
2019 c->next = c->next->next;
2020 free(to_be_freed->backup);
2021 free(to_be_freed);
2023 /* If backup memory was allocated to the remaining area, it's has
2024 * the wrong size now */
2025 free(c->backup);
2026 c->backup = NULL;
2027 } else {
2028 c = c->next;
2033 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
2035 /* Reevaluate working area address based on MMU state*/
2036 if (!target->working_areas) {
2037 int retval;
2038 int enabled;
2040 retval = target->type->mmu(target, &enabled);
2041 if (retval != ERROR_OK)
2042 return retval;
2044 if (!enabled) {
2045 if (target->working_area_phys_spec) {
2046 LOG_DEBUG("MMU disabled, using physical "
2047 "address for working memory " TARGET_ADDR_FMT,
2048 target->working_area_phys);
2049 target->working_area = target->working_area_phys;
2050 } else {
2051 LOG_ERROR("No working memory available. "
2052 "Specify -work-area-phys to target.");
2053 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2055 } else {
2056 if (target->working_area_virt_spec) {
2057 LOG_DEBUG("MMU enabled, using virtual "
2058 "address for working memory " TARGET_ADDR_FMT,
2059 target->working_area_virt);
2060 target->working_area = target->working_area_virt;
2061 } else {
2062 LOG_ERROR("No working memory available. "
2063 "Specify -work-area-virt to target.");
2064 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2068 /* Set up initial working area on first call */
2069 struct working_area *new_wa = malloc(sizeof(*new_wa));
2070 if (new_wa) {
2071 new_wa->next = NULL;
2072 new_wa->size = ALIGN_DOWN(target->working_area_size, 4); /* 4-byte align */
2073 new_wa->address = target->working_area;
2074 new_wa->backup = NULL;
2075 new_wa->user = NULL;
2076 new_wa->free = true;
2079 target->working_areas = new_wa;
2082 /* only allocate multiples of 4 byte */
2083 size = ALIGN_UP(size, 4);
2085 struct working_area *c = target->working_areas;
2087 /* Find the first large enough working area */
2088 while (c) {
2089 if (c->free && c->size >= size)
2090 break;
2091 c = c->next;
2094 if (!c)
2095 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2097 /* Split the working area into the requested size */
2098 target_split_working_area(c, size);
2100 LOG_DEBUG("allocated new working area of %" PRIu32 " bytes at address " TARGET_ADDR_FMT,
2101 size, c->address);
2103 if (target->backup_working_area) {
2104 if (!c->backup) {
2105 c->backup = malloc(c->size);
2106 if (!c->backup)
2107 return ERROR_FAIL;
2110 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
2111 if (retval != ERROR_OK)
2112 return retval;
2115 /* mark as used, and return the new (reused) area */
2116 c->free = false;
2117 *area = c;
2119 /* user pointer */
2120 c->user = area;
2122 print_wa_layout(target);
2124 return ERROR_OK;
2127 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
2129 int retval;
2131 retval = target_alloc_working_area_try(target, size, area);
2132 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
2133 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
2134 return retval;
2138 static int target_restore_working_area(struct target *target, struct working_area *area)
2140 int retval = ERROR_OK;
2142 if (target->backup_working_area && area->backup) {
2143 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
2144 if (retval != ERROR_OK)
2145 LOG_ERROR("failed to restore %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2146 area->size, area->address);
2149 return retval;
2152 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
2153 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
2155 if (!area || area->free)
2156 return ERROR_OK;
2158 int retval = ERROR_OK;
2159 if (restore) {
2160 retval = target_restore_working_area(target, area);
2161 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
2162 if (retval != ERROR_OK)
2163 return retval;
2166 area->free = true;
2168 LOG_DEBUG("freed %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2169 area->size, area->address);
2171 /* mark user pointer invalid */
2172 /* TODO: Is this really safe? It points to some previous caller's memory.
2173 * How could we know that the area pointer is still in that place and not
2174 * some other vital data? What's the purpose of this, anyway? */
2175 *area->user = NULL;
2176 area->user = NULL;
2178 target_merge_working_areas(target);
2180 print_wa_layout(target);
2182 return retval;
2185 int target_free_working_area(struct target *target, struct working_area *area)
2187 return target_free_working_area_restore(target, area, 1);
2190 /* free resources and restore memory, if restoring memory fails,
2191 * free up resources anyway
2193 static void target_free_all_working_areas_restore(struct target *target, int restore)
2195 struct working_area *c = target->working_areas;
2197 LOG_DEBUG("freeing all working areas");
2199 /* Loop through all areas, restoring the allocated ones and marking them as free */
2200 while (c) {
2201 if (!c->free) {
2202 if (restore)
2203 target_restore_working_area(target, c);
2204 c->free = true;
2205 *c->user = NULL; /* Same as above */
2206 c->user = NULL;
2208 c = c->next;
2211 /* Run a merge pass to combine all areas into one */
2212 target_merge_working_areas(target);
2214 print_wa_layout(target);
2217 void target_free_all_working_areas(struct target *target)
2219 target_free_all_working_areas_restore(target, 1);
2221 /* Now we have none or only one working area marked as free */
2222 if (target->working_areas) {
2223 /* Free the last one to allow on-the-fly moving and resizing */
2224 free(target->working_areas->backup);
2225 free(target->working_areas);
2226 target->working_areas = NULL;
2230 /* Find the largest number of bytes that can be allocated */
2231 uint32_t target_get_working_area_avail(struct target *target)
2233 struct working_area *c = target->working_areas;
2234 uint32_t max_size = 0;
2236 if (!c)
2237 return ALIGN_DOWN(target->working_area_size, 4);
2239 while (c) {
2240 if (c->free && max_size < c->size)
2241 max_size = c->size;
2243 c = c->next;
2246 return max_size;
2249 static void target_destroy(struct target *target)
2251 if (target->type->deinit_target)
2252 target->type->deinit_target(target);
2254 if (target->semihosting)
2255 free(target->semihosting->basedir);
2256 free(target->semihosting);
2258 jtag_unregister_event_callback(jtag_enable_callback, target);
2260 struct target_event_action *teap = target->event_action;
2261 while (teap) {
2262 struct target_event_action *next = teap->next;
2263 Jim_DecrRefCount(teap->interp, teap->body);
2264 free(teap);
2265 teap = next;
2268 target_free_all_working_areas(target);
2270 /* release the targets SMP list */
2271 if (target->smp) {
2272 struct target_list *head, *tmp;
2274 list_for_each_entry_safe(head, tmp, target->smp_targets, lh) {
2275 list_del(&head->lh);
2276 head->target->smp = 0;
2277 free(head);
2279 if (target->smp_targets != &empty_smp_targets)
2280 free(target->smp_targets);
2281 target->smp = 0;
2284 rtos_destroy(target);
2286 free(target->gdb_port_override);
2287 free(target->type);
2288 free(target->trace_info);
2289 free(target->fileio_info);
2290 free(target->cmd_name);
2291 free(target);
2294 void target_quit(void)
2296 struct target_event_callback *pe = target_event_callbacks;
2297 while (pe) {
2298 struct target_event_callback *t = pe->next;
2299 free(pe);
2300 pe = t;
2302 target_event_callbacks = NULL;
2304 struct target_timer_callback *pt = target_timer_callbacks;
2305 while (pt) {
2306 struct target_timer_callback *t = pt->next;
2307 free(pt);
2308 pt = t;
2310 target_timer_callbacks = NULL;
2312 for (struct target *target = all_targets; target;) {
2313 struct target *tmp;
2315 tmp = target->next;
2316 target_destroy(target);
2317 target = tmp;
2320 all_targets = NULL;
2323 int target_arch_state(struct target *target)
2325 int retval;
2326 if (!target) {
2327 LOG_WARNING("No target has been configured");
2328 return ERROR_OK;
2331 if (target->state != TARGET_HALTED)
2332 return ERROR_OK;
2334 retval = target->type->arch_state(target);
2335 return retval;
2338 static int target_get_gdb_fileio_info_default(struct target *target,
2339 struct gdb_fileio_info *fileio_info)
2341 /* If target does not support semi-hosting function, target
2342 has no need to provide .get_gdb_fileio_info callback.
2343 It just return ERROR_FAIL and gdb_server will return "Txx"
2344 as target halted every time. */
2345 return ERROR_FAIL;
2348 static int target_gdb_fileio_end_default(struct target *target,
2349 int retcode, int fileio_errno, bool ctrl_c)
2351 return ERROR_OK;
2354 int target_profiling_default(struct target *target, uint32_t *samples,
2355 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
2357 struct timeval timeout, now;
2359 gettimeofday(&timeout, NULL);
2360 timeval_add_time(&timeout, seconds, 0);
2362 LOG_INFO("Starting profiling. Halting and resuming the"
2363 " target as often as we can...");
2365 uint32_t sample_count = 0;
2366 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2367 struct reg *reg = register_get_by_name(target->reg_cache, "pc", true);
2369 int retval = ERROR_OK;
2370 for (;;) {
2371 target_poll(target);
2372 if (target->state == TARGET_HALTED) {
2373 uint32_t t = buf_get_u32(reg->value, 0, 32);
2374 samples[sample_count++] = t;
2375 /* current pc, addr = 0, do not handle breakpoints, not debugging */
2376 retval = target_resume(target, 1, 0, 0, 0);
2377 target_poll(target);
2378 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2379 } else if (target->state == TARGET_RUNNING) {
2380 /* We want to quickly sample the PC. */
2381 retval = target_halt(target);
2382 } else {
2383 LOG_INFO("Target not halted or running");
2384 retval = ERROR_OK;
2385 break;
2388 if (retval != ERROR_OK)
2389 break;
2391 gettimeofday(&now, NULL);
2392 if ((sample_count >= max_num_samples) || timeval_compare(&now, &timeout) >= 0) {
2393 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2394 break;
2398 *num_samples = sample_count;
2399 return retval;
2402 /* Single aligned words are guaranteed to use 16 or 32 bit access
2403 * mode respectively, otherwise data is handled as quickly as
2404 * possible
2406 int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
2408 LOG_DEBUG("writing buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2409 size, address);
2411 if (!target_was_examined(target)) {
2412 LOG_ERROR("Target not examined yet");
2413 return ERROR_FAIL;
2416 if (size == 0)
2417 return ERROR_OK;
2419 if ((address + size - 1) < address) {
2420 /* GDB can request this when e.g. PC is 0xfffffffc */
2421 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2422 address,
2423 size);
2424 return ERROR_FAIL;
2427 return target->type->write_buffer(target, address, size, buffer);
2430 static int target_write_buffer_default(struct target *target,
2431 target_addr_t address, uint32_t count, const uint8_t *buffer)
2433 uint32_t size;
2434 unsigned int data_bytes = target_data_bits(target) / 8;
2436 /* Align up to maximum bytes. The loop condition makes sure the next pass
2437 * will have something to do with the size we leave to it. */
2438 for (size = 1;
2439 size < data_bytes && count >= size * 2 + (address & size);
2440 size *= 2) {
2441 if (address & size) {
2442 int retval = target_write_memory(target, address, size, 1, buffer);
2443 if (retval != ERROR_OK)
2444 return retval;
2445 address += size;
2446 count -= size;
2447 buffer += size;
2451 /* Write the data with as large access size as possible. */
2452 for (; size > 0; size /= 2) {
2453 uint32_t aligned = count - count % size;
2454 if (aligned > 0) {
2455 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2456 if (retval != ERROR_OK)
2457 return retval;
2458 address += aligned;
2459 count -= aligned;
2460 buffer += aligned;
2464 return ERROR_OK;
2467 /* Single aligned words are guaranteed to use 16 or 32 bit access
2468 * mode respectively, otherwise data is handled as quickly as
2469 * possible
2471 int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
2473 LOG_DEBUG("reading buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2474 size, address);
2476 if (!target_was_examined(target)) {
2477 LOG_ERROR("Target not examined yet");
2478 return ERROR_FAIL;
2481 if (size == 0)
2482 return ERROR_OK;
2484 if ((address + size - 1) < address) {
2485 /* GDB can request this when e.g. PC is 0xfffffffc */
2486 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2487 address,
2488 size);
2489 return ERROR_FAIL;
2492 return target->type->read_buffer(target, address, size, buffer);
2495 static int target_read_buffer_default(struct target *target, target_addr_t address, uint32_t count, uint8_t *buffer)
2497 uint32_t size;
2498 unsigned int data_bytes = target_data_bits(target) / 8;
2500 /* Align up to maximum bytes. The loop condition makes sure the next pass
2501 * will have something to do with the size we leave to it. */
2502 for (size = 1;
2503 size < data_bytes && count >= size * 2 + (address & size);
2504 size *= 2) {
2505 if (address & size) {
2506 int retval = target_read_memory(target, address, size, 1, buffer);
2507 if (retval != ERROR_OK)
2508 return retval;
2509 address += size;
2510 count -= size;
2511 buffer += size;
2515 /* Read the data with as large access size as possible. */
2516 for (; size > 0; size /= 2) {
2517 uint32_t aligned = count - count % size;
2518 if (aligned > 0) {
2519 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2520 if (retval != ERROR_OK)
2521 return retval;
2522 address += aligned;
2523 count -= aligned;
2524 buffer += aligned;
2528 return ERROR_OK;
2531 int target_checksum_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t *crc)
2533 uint8_t *buffer;
2534 int retval;
2535 uint32_t i;
2536 uint32_t checksum = 0;
2537 if (!target_was_examined(target)) {
2538 LOG_ERROR("Target not examined yet");
2539 return ERROR_FAIL;
2541 if (!target->type->checksum_memory) {
2542 LOG_ERROR("Target %s doesn't support checksum_memory", target_name(target));
2543 return ERROR_FAIL;
2546 retval = target->type->checksum_memory(target, address, size, &checksum);
2547 if (retval != ERROR_OK) {
2548 buffer = malloc(size);
2549 if (!buffer) {
2550 LOG_ERROR("error allocating buffer for section (%" PRIu32 " bytes)", size);
2551 return ERROR_COMMAND_SYNTAX_ERROR;
2553 retval = target_read_buffer(target, address, size, buffer);
2554 if (retval != ERROR_OK) {
2555 free(buffer);
2556 return retval;
2559 /* convert to target endianness */
2560 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2561 uint32_t target_data;
2562 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2563 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2566 retval = image_calculate_checksum(buffer, size, &checksum);
2567 free(buffer);
2570 *crc = checksum;
2572 return retval;
2575 int target_blank_check_memory(struct target *target,
2576 struct target_memory_check_block *blocks, int num_blocks,
2577 uint8_t erased_value)
2579 if (!target_was_examined(target)) {
2580 LOG_ERROR("Target not examined yet");
2581 return ERROR_FAIL;
2584 if (!target->type->blank_check_memory)
2585 return ERROR_NOT_IMPLEMENTED;
2587 return target->type->blank_check_memory(target, blocks, num_blocks, erased_value);
2590 int target_read_u64(struct target *target, target_addr_t address, uint64_t *value)
2592 uint8_t value_buf[8];
2593 if (!target_was_examined(target)) {
2594 LOG_ERROR("Target not examined yet");
2595 return ERROR_FAIL;
2598 int retval = target_read_memory(target, address, 8, 1, value_buf);
2600 if (retval == ERROR_OK) {
2601 *value = target_buffer_get_u64(target, value_buf);
2602 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2603 address,
2604 *value);
2605 } else {
2606 *value = 0x0;
2607 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2608 address);
2611 return retval;
2614 int target_read_u32(struct target *target, target_addr_t address, uint32_t *value)
2616 uint8_t value_buf[4];
2617 if (!target_was_examined(target)) {
2618 LOG_ERROR("Target not examined yet");
2619 return ERROR_FAIL;
2622 int retval = target_read_memory(target, address, 4, 1, value_buf);
2624 if (retval == ERROR_OK) {
2625 *value = target_buffer_get_u32(target, value_buf);
2626 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2627 address,
2628 *value);
2629 } else {
2630 *value = 0x0;
2631 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2632 address);
2635 return retval;
2638 int target_read_u16(struct target *target, target_addr_t address, uint16_t *value)
2640 uint8_t value_buf[2];
2641 if (!target_was_examined(target)) {
2642 LOG_ERROR("Target not examined yet");
2643 return ERROR_FAIL;
2646 int retval = target_read_memory(target, address, 2, 1, value_buf);
2648 if (retval == ERROR_OK) {
2649 *value = target_buffer_get_u16(target, value_buf);
2650 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%4.4" PRIx16,
2651 address,
2652 *value);
2653 } else {
2654 *value = 0x0;
2655 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2656 address);
2659 return retval;
2662 int target_read_u8(struct target *target, target_addr_t address, uint8_t *value)
2664 if (!target_was_examined(target)) {
2665 LOG_ERROR("Target not examined yet");
2666 return ERROR_FAIL;
2669 int retval = target_read_memory(target, address, 1, 1, value);
2671 if (retval == ERROR_OK) {
2672 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2673 address,
2674 *value);
2675 } else {
2676 *value = 0x0;
2677 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2678 address);
2681 return retval;
2684 int target_write_u64(struct target *target, target_addr_t address, uint64_t value)
2686 int retval;
2687 uint8_t value_buf[8];
2688 if (!target_was_examined(target)) {
2689 LOG_ERROR("Target not examined yet");
2690 return ERROR_FAIL;
2693 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2694 address,
2695 value);
2697 target_buffer_set_u64(target, value_buf, value);
2698 retval = target_write_memory(target, address, 8, 1, value_buf);
2699 if (retval != ERROR_OK)
2700 LOG_DEBUG("failed: %i", retval);
2702 return retval;
2705 int target_write_u32(struct target *target, target_addr_t address, uint32_t value)
2707 int retval;
2708 uint8_t value_buf[4];
2709 if (!target_was_examined(target)) {
2710 LOG_ERROR("Target not examined yet");
2711 return ERROR_FAIL;
2714 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2715 address,
2716 value);
2718 target_buffer_set_u32(target, value_buf, value);
2719 retval = target_write_memory(target, address, 4, 1, value_buf);
2720 if (retval != ERROR_OK)
2721 LOG_DEBUG("failed: %i", retval);
2723 return retval;
2726 int target_write_u16(struct target *target, target_addr_t address, uint16_t value)
2728 int retval;
2729 uint8_t value_buf[2];
2730 if (!target_was_examined(target)) {
2731 LOG_ERROR("Target not examined yet");
2732 return ERROR_FAIL;
2735 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2736 address,
2737 value);
2739 target_buffer_set_u16(target, value_buf, value);
2740 retval = target_write_memory(target, address, 2, 1, value_buf);
2741 if (retval != ERROR_OK)
2742 LOG_DEBUG("failed: %i", retval);
2744 return retval;
2747 int target_write_u8(struct target *target, target_addr_t address, uint8_t value)
2749 int retval;
2750 if (!target_was_examined(target)) {
2751 LOG_ERROR("Target not examined yet");
2752 return ERROR_FAIL;
2755 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2756 address, value);
2758 retval = target_write_memory(target, address, 1, 1, &value);
2759 if (retval != ERROR_OK)
2760 LOG_DEBUG("failed: %i", retval);
2762 return retval;
2765 int target_write_phys_u64(struct target *target, target_addr_t address, uint64_t value)
2767 int retval;
2768 uint8_t value_buf[8];
2769 if (!target_was_examined(target)) {
2770 LOG_ERROR("Target not examined yet");
2771 return ERROR_FAIL;
2774 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2775 address,
2776 value);
2778 target_buffer_set_u64(target, value_buf, value);
2779 retval = target_write_phys_memory(target, address, 8, 1, value_buf);
2780 if (retval != ERROR_OK)
2781 LOG_DEBUG("failed: %i", retval);
2783 return retval;
2786 int target_write_phys_u32(struct target *target, target_addr_t address, uint32_t value)
2788 int retval;
2789 uint8_t value_buf[4];
2790 if (!target_was_examined(target)) {
2791 LOG_ERROR("Target not examined yet");
2792 return ERROR_FAIL;
2795 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2796 address,
2797 value);
2799 target_buffer_set_u32(target, value_buf, value);
2800 retval = target_write_phys_memory(target, address, 4, 1, value_buf);
2801 if (retval != ERROR_OK)
2802 LOG_DEBUG("failed: %i", retval);
2804 return retval;
2807 int target_write_phys_u16(struct target *target, target_addr_t address, uint16_t value)
2809 int retval;
2810 uint8_t value_buf[2];
2811 if (!target_was_examined(target)) {
2812 LOG_ERROR("Target not examined yet");
2813 return ERROR_FAIL;
2816 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2817 address,
2818 value);
2820 target_buffer_set_u16(target, value_buf, value);
2821 retval = target_write_phys_memory(target, address, 2, 1, value_buf);
2822 if (retval != ERROR_OK)
2823 LOG_DEBUG("failed: %i", retval);
2825 return retval;
2828 int target_write_phys_u8(struct target *target, target_addr_t address, uint8_t value)
2830 int retval;
2831 if (!target_was_examined(target)) {
2832 LOG_ERROR("Target not examined yet");
2833 return ERROR_FAIL;
2836 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2837 address, value);
2839 retval = target_write_phys_memory(target, address, 1, 1, &value);
2840 if (retval != ERROR_OK)
2841 LOG_DEBUG("failed: %i", retval);
2843 return retval;
2846 static int find_target(struct command_invocation *cmd, const char *name)
2848 struct target *target = get_target(name);
2849 if (!target) {
2850 command_print(cmd, "Target: %s is unknown, try one of:\n", name);
2851 return ERROR_FAIL;
2853 if (!target->tap->enabled) {
2854 command_print(cmd, "Target: TAP %s is disabled, "
2855 "can't be the current target\n",
2856 target->tap->dotted_name);
2857 return ERROR_FAIL;
2860 cmd->ctx->current_target = target;
2861 if (cmd->ctx->current_target_override)
2862 cmd->ctx->current_target_override = target;
2864 return ERROR_OK;
2868 COMMAND_HANDLER(handle_targets_command)
2870 int retval = ERROR_OK;
2871 if (CMD_ARGC == 1) {
2872 retval = find_target(CMD, CMD_ARGV[0]);
2873 if (retval == ERROR_OK) {
2874 /* we're done! */
2875 return retval;
2879 struct target *target = all_targets;
2880 command_print(CMD, " TargetName Type Endian TapName State ");
2881 command_print(CMD, "-- ------------------ ---------- ------ ------------------ ------------");
2882 while (target) {
2883 const char *state;
2884 char marker = ' ';
2886 if (target->tap->enabled)
2887 state = target_state_name(target);
2888 else
2889 state = "tap-disabled";
2891 if (CMD_CTX->current_target == target)
2892 marker = '*';
2894 /* keep columns lined up to match the headers above */
2895 command_print(CMD,
2896 "%2d%c %-18s %-10s %-6s %-18s %s",
2897 target->target_number,
2898 marker,
2899 target_name(target),
2900 target_type_name(target),
2901 jim_nvp_value2name_simple(nvp_target_endian,
2902 target->endianness)->name,
2903 target->tap->dotted_name,
2904 state);
2905 target = target->next;
2908 return retval;
2911 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2913 static int power_dropout;
2914 static int srst_asserted;
2916 static int run_power_restore;
2917 static int run_power_dropout;
2918 static int run_srst_asserted;
2919 static int run_srst_deasserted;
2921 static int sense_handler(void)
2923 static int prev_srst_asserted;
2924 static int prev_power_dropout;
2926 int retval = jtag_power_dropout(&power_dropout);
2927 if (retval != ERROR_OK)
2928 return retval;
2930 int power_restored;
2931 power_restored = prev_power_dropout && !power_dropout;
2932 if (power_restored)
2933 run_power_restore = 1;
2935 int64_t current = timeval_ms();
2936 static int64_t last_power;
2937 bool wait_more = last_power + 2000 > current;
2938 if (power_dropout && !wait_more) {
2939 run_power_dropout = 1;
2940 last_power = current;
2943 retval = jtag_srst_asserted(&srst_asserted);
2944 if (retval != ERROR_OK)
2945 return retval;
2947 int srst_deasserted;
2948 srst_deasserted = prev_srst_asserted && !srst_asserted;
2950 static int64_t last_srst;
2951 wait_more = last_srst + 2000 > current;
2952 if (srst_deasserted && !wait_more) {
2953 run_srst_deasserted = 1;
2954 last_srst = current;
2957 if (!prev_srst_asserted && srst_asserted)
2958 run_srst_asserted = 1;
2960 prev_srst_asserted = srst_asserted;
2961 prev_power_dropout = power_dropout;
2963 if (srst_deasserted || power_restored) {
2964 /* Other than logging the event we can't do anything here.
2965 * Issuing a reset is a particularly bad idea as we might
2966 * be inside a reset already.
2970 return ERROR_OK;
2973 /* process target state changes */
2974 static int handle_target(void *priv)
2976 Jim_Interp *interp = (Jim_Interp *)priv;
2977 int retval = ERROR_OK;
2979 if (!is_jtag_poll_safe()) {
2980 /* polling is disabled currently */
2981 return ERROR_OK;
2984 /* we do not want to recurse here... */
2985 static int recursive;
2986 if (!recursive) {
2987 recursive = 1;
2988 sense_handler();
2989 /* danger! running these procedures can trigger srst assertions and power dropouts.
2990 * We need to avoid an infinite loop/recursion here and we do that by
2991 * clearing the flags after running these events.
2993 int did_something = 0;
2994 if (run_srst_asserted) {
2995 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2996 Jim_Eval(interp, "srst_asserted");
2997 did_something = 1;
2999 if (run_srst_deasserted) {
3000 Jim_Eval(interp, "srst_deasserted");
3001 did_something = 1;
3003 if (run_power_dropout) {
3004 LOG_INFO("Power dropout detected, running power_dropout proc.");
3005 Jim_Eval(interp, "power_dropout");
3006 did_something = 1;
3008 if (run_power_restore) {
3009 Jim_Eval(interp, "power_restore");
3010 did_something = 1;
3013 if (did_something) {
3014 /* clear detect flags */
3015 sense_handler();
3018 /* clear action flags */
3020 run_srst_asserted = 0;
3021 run_srst_deasserted = 0;
3022 run_power_restore = 0;
3023 run_power_dropout = 0;
3025 recursive = 0;
3028 /* Poll targets for state changes unless that's globally disabled.
3029 * Skip targets that are currently disabled.
3031 for (struct target *target = all_targets;
3032 is_jtag_poll_safe() && target;
3033 target = target->next) {
3035 if (!target_was_examined(target))
3036 continue;
3038 if (!target->tap->enabled)
3039 continue;
3041 if (target->backoff.times > target->backoff.count) {
3042 /* do not poll this time as we failed previously */
3043 target->backoff.count++;
3044 continue;
3046 target->backoff.count = 0;
3048 /* only poll target if we've got power and srst isn't asserted */
3049 if (!power_dropout && !srst_asserted) {
3050 /* polling may fail silently until the target has been examined */
3051 retval = target_poll(target);
3052 if (retval != ERROR_OK) {
3053 /* 100ms polling interval. Increase interval between polling up to 5000ms */
3054 if (target->backoff.times * polling_interval < 5000) {
3055 target->backoff.times *= 2;
3056 target->backoff.times++;
3059 /* Tell GDB to halt the debugger. This allows the user to
3060 * run monitor commands to handle the situation.
3062 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3064 if (target->backoff.times > 0) {
3065 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
3066 target_reset_examined(target);
3067 retval = target_examine_one(target);
3068 /* Target examination could have failed due to unstable connection,
3069 * but we set the examined flag anyway to repoll it later */
3070 if (retval != ERROR_OK) {
3071 target_set_examined(target);
3072 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
3073 target->backoff.times * polling_interval);
3074 return retval;
3078 /* Since we succeeded, we reset backoff count */
3079 target->backoff.times = 0;
3083 return retval;
3086 COMMAND_HANDLER(handle_reg_command)
3088 LOG_DEBUG("-");
3090 struct target *target = get_current_target(CMD_CTX);
3091 struct reg *reg = NULL;
3093 /* list all available registers for the current target */
3094 if (CMD_ARGC == 0) {
3095 struct reg_cache *cache = target->reg_cache;
3097 unsigned int count = 0;
3098 while (cache) {
3099 unsigned i;
3101 command_print(CMD, "===== %s", cache->name);
3103 for (i = 0, reg = cache->reg_list;
3104 i < cache->num_regs;
3105 i++, reg++, count++) {
3106 if (reg->exist == false || reg->hidden)
3107 continue;
3108 /* only print cached values if they are valid */
3109 if (reg->valid) {
3110 char *value = buf_to_hex_str(reg->value,
3111 reg->size);
3112 command_print(CMD,
3113 "(%i) %s (/%" PRIu32 "): 0x%s%s",
3114 count, reg->name,
3115 reg->size, value,
3116 reg->dirty
3117 ? " (dirty)"
3118 : "");
3119 free(value);
3120 } else {
3121 command_print(CMD, "(%i) %s (/%" PRIu32 ")",
3122 count, reg->name,
3123 reg->size);
3126 cache = cache->next;
3129 return ERROR_OK;
3132 /* access a single register by its ordinal number */
3133 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
3134 unsigned num;
3135 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
3137 struct reg_cache *cache = target->reg_cache;
3138 unsigned int count = 0;
3139 while (cache) {
3140 unsigned i;
3141 for (i = 0; i < cache->num_regs; i++) {
3142 if (count++ == num) {
3143 reg = &cache->reg_list[i];
3144 break;
3147 if (reg)
3148 break;
3149 cache = cache->next;
3152 if (!reg) {
3153 command_print(CMD, "%i is out of bounds, the current target "
3154 "has only %i registers (0 - %i)", num, count, count - 1);
3155 return ERROR_OK;
3157 } else {
3158 /* access a single register by its name */
3159 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], true);
3161 if (!reg)
3162 goto not_found;
3165 assert(reg); /* give clang a hint that we *know* reg is != NULL here */
3167 if (!reg->exist)
3168 goto not_found;
3170 /* display a register */
3171 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
3172 && (CMD_ARGV[1][0] <= '9')))) {
3173 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
3174 reg->valid = 0;
3176 if (reg->valid == 0) {
3177 int retval = reg->type->get(reg);
3178 if (retval != ERROR_OK) {
3179 LOG_ERROR("Could not read register '%s'", reg->name);
3180 return retval;
3183 char *value = buf_to_hex_str(reg->value, reg->size);
3184 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3185 free(value);
3186 return ERROR_OK;
3189 /* set register value */
3190 if (CMD_ARGC == 2) {
3191 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
3192 if (!buf)
3193 return ERROR_FAIL;
3194 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
3196 int retval = reg->type->set(reg, buf);
3197 if (retval != ERROR_OK) {
3198 LOG_ERROR("Could not write to register '%s'", reg->name);
3199 } else {
3200 char *value = buf_to_hex_str(reg->value, reg->size);
3201 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3202 free(value);
3205 free(buf);
3207 return retval;
3210 return ERROR_COMMAND_SYNTAX_ERROR;
3212 not_found:
3213 command_print(CMD, "register %s not found in current target", CMD_ARGV[0]);
3214 return ERROR_OK;
3217 COMMAND_HANDLER(handle_poll_command)
3219 int retval = ERROR_OK;
3220 struct target *target = get_current_target(CMD_CTX);
3222 if (CMD_ARGC == 0) {
3223 command_print(CMD, "background polling: %s",
3224 jtag_poll_get_enabled() ? "on" : "off");
3225 command_print(CMD, "TAP: %s (%s)",
3226 target->tap->dotted_name,
3227 target->tap->enabled ? "enabled" : "disabled");
3228 if (!target->tap->enabled)
3229 return ERROR_OK;
3230 retval = target_poll(target);
3231 if (retval != ERROR_OK)
3232 return retval;
3233 retval = target_arch_state(target);
3234 if (retval != ERROR_OK)
3235 return retval;
3236 } else if (CMD_ARGC == 1) {
3237 bool enable;
3238 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
3239 jtag_poll_set_enabled(enable);
3240 } else
3241 return ERROR_COMMAND_SYNTAX_ERROR;
3243 return retval;
3246 COMMAND_HANDLER(handle_wait_halt_command)
3248 if (CMD_ARGC > 1)
3249 return ERROR_COMMAND_SYNTAX_ERROR;
3251 unsigned ms = DEFAULT_HALT_TIMEOUT;
3252 if (1 == CMD_ARGC) {
3253 int retval = parse_uint(CMD_ARGV[0], &ms);
3254 if (retval != ERROR_OK)
3255 return ERROR_COMMAND_SYNTAX_ERROR;
3258 struct target *target = get_current_target(CMD_CTX);
3259 return target_wait_state(target, TARGET_HALTED, ms);
3262 /* wait for target state to change. The trick here is to have a low
3263 * latency for short waits and not to suck up all the CPU time
3264 * on longer waits.
3266 * After 500ms, keep_alive() is invoked
3268 int target_wait_state(struct target *target, enum target_state state, int ms)
3270 int retval;
3271 int64_t then = 0, cur;
3272 bool once = true;
3274 for (;;) {
3275 retval = target_poll(target);
3276 if (retval != ERROR_OK)
3277 return retval;
3278 if (target->state == state)
3279 break;
3280 cur = timeval_ms();
3281 if (once) {
3282 once = false;
3283 then = timeval_ms();
3284 LOG_DEBUG("waiting for target %s...",
3285 jim_nvp_value2name_simple(nvp_target_state, state)->name);
3288 if (cur-then > 500)
3289 keep_alive();
3291 if ((cur-then) > ms) {
3292 LOG_ERROR("timed out while waiting for target %s",
3293 jim_nvp_value2name_simple(nvp_target_state, state)->name);
3294 return ERROR_FAIL;
3298 return ERROR_OK;
3301 COMMAND_HANDLER(handle_halt_command)
3303 LOG_DEBUG("-");
3305 struct target *target = get_current_target(CMD_CTX);
3307 target->verbose_halt_msg = true;
3309 int retval = target_halt(target);
3310 if (retval != ERROR_OK)
3311 return retval;
3313 if (CMD_ARGC == 1) {
3314 unsigned wait_local;
3315 retval = parse_uint(CMD_ARGV[0], &wait_local);
3316 if (retval != ERROR_OK)
3317 return ERROR_COMMAND_SYNTAX_ERROR;
3318 if (!wait_local)
3319 return ERROR_OK;
3322 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
3325 COMMAND_HANDLER(handle_soft_reset_halt_command)
3327 struct target *target = get_current_target(CMD_CTX);
3329 LOG_TARGET_INFO(target, "requesting target halt and executing a soft reset");
3331 target_soft_reset_halt(target);
3333 return ERROR_OK;
3336 COMMAND_HANDLER(handle_reset_command)
3338 if (CMD_ARGC > 1)
3339 return ERROR_COMMAND_SYNTAX_ERROR;
3341 enum target_reset_mode reset_mode = RESET_RUN;
3342 if (CMD_ARGC == 1) {
3343 const struct jim_nvp *n;
3344 n = jim_nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
3345 if ((!n->name) || (n->value == RESET_UNKNOWN))
3346 return ERROR_COMMAND_SYNTAX_ERROR;
3347 reset_mode = n->value;
3350 /* reset *all* targets */
3351 return target_process_reset(CMD, reset_mode);
3355 COMMAND_HANDLER(handle_resume_command)
3357 int current = 1;
3358 if (CMD_ARGC > 1)
3359 return ERROR_COMMAND_SYNTAX_ERROR;
3361 struct target *target = get_current_target(CMD_CTX);
3363 /* with no CMD_ARGV, resume from current pc, addr = 0,
3364 * with one arguments, addr = CMD_ARGV[0],
3365 * handle breakpoints, not debugging */
3366 target_addr_t addr = 0;
3367 if (CMD_ARGC == 1) {
3368 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3369 current = 0;
3372 return target_resume(target, current, addr, 1, 0);
3375 COMMAND_HANDLER(handle_step_command)
3377 if (CMD_ARGC > 1)
3378 return ERROR_COMMAND_SYNTAX_ERROR;
3380 LOG_DEBUG("-");
3382 /* with no CMD_ARGV, step from current pc, addr = 0,
3383 * with one argument addr = CMD_ARGV[0],
3384 * handle breakpoints, debugging */
3385 target_addr_t addr = 0;
3386 int current_pc = 1;
3387 if (CMD_ARGC == 1) {
3388 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3389 current_pc = 0;
3392 struct target *target = get_current_target(CMD_CTX);
3394 return target_step(target, current_pc, addr, 1);
3397 void target_handle_md_output(struct command_invocation *cmd,
3398 struct target *target, target_addr_t address, unsigned size,
3399 unsigned count, const uint8_t *buffer)
3401 const unsigned line_bytecnt = 32;
3402 unsigned line_modulo = line_bytecnt / size;
3404 char output[line_bytecnt * 4 + 1];
3405 unsigned output_len = 0;
3407 const char *value_fmt;
3408 switch (size) {
3409 case 8:
3410 value_fmt = "%16.16"PRIx64" ";
3411 break;
3412 case 4:
3413 value_fmt = "%8.8"PRIx64" ";
3414 break;
3415 case 2:
3416 value_fmt = "%4.4"PRIx64" ";
3417 break;
3418 case 1:
3419 value_fmt = "%2.2"PRIx64" ";
3420 break;
3421 default:
3422 /* "can't happen", caller checked */
3423 LOG_ERROR("invalid memory read size: %u", size);
3424 return;
3427 for (unsigned i = 0; i < count; i++) {
3428 if (i % line_modulo == 0) {
3429 output_len += snprintf(output + output_len,
3430 sizeof(output) - output_len,
3431 TARGET_ADDR_FMT ": ",
3432 (address + (i * size)));
3435 uint64_t value = 0;
3436 const uint8_t *value_ptr = buffer + i * size;
3437 switch (size) {
3438 case 8:
3439 value = target_buffer_get_u64(target, value_ptr);
3440 break;
3441 case 4:
3442 value = target_buffer_get_u32(target, value_ptr);
3443 break;
3444 case 2:
3445 value = target_buffer_get_u16(target, value_ptr);
3446 break;
3447 case 1:
3448 value = *value_ptr;
3450 output_len += snprintf(output + output_len,
3451 sizeof(output) - output_len,
3452 value_fmt, value);
3454 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
3455 command_print(cmd, "%s", output);
3456 output_len = 0;
3461 COMMAND_HANDLER(handle_md_command)
3463 if (CMD_ARGC < 1)
3464 return ERROR_COMMAND_SYNTAX_ERROR;
3466 unsigned size = 0;
3467 switch (CMD_NAME[2]) {
3468 case 'd':
3469 size = 8;
3470 break;
3471 case 'w':
3472 size = 4;
3473 break;
3474 case 'h':
3475 size = 2;
3476 break;
3477 case 'b':
3478 size = 1;
3479 break;
3480 default:
3481 return ERROR_COMMAND_SYNTAX_ERROR;
3484 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3485 int (*fn)(struct target *target,
3486 target_addr_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
3487 if (physical) {
3488 CMD_ARGC--;
3489 CMD_ARGV++;
3490 fn = target_read_phys_memory;
3491 } else
3492 fn = target_read_memory;
3493 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
3494 return ERROR_COMMAND_SYNTAX_ERROR;
3496 target_addr_t address;
3497 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3499 unsigned count = 1;
3500 if (CMD_ARGC == 2)
3501 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3503 uint8_t *buffer = calloc(count, size);
3504 if (!buffer) {
3505 LOG_ERROR("Failed to allocate md read buffer");
3506 return ERROR_FAIL;
3509 struct target *target = get_current_target(CMD_CTX);
3510 int retval = fn(target, address, size, count, buffer);
3511 if (retval == ERROR_OK)
3512 target_handle_md_output(CMD, target, address, size, count, buffer);
3514 free(buffer);
3516 return retval;
3519 typedef int (*target_write_fn)(struct target *target,
3520 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3522 static int target_fill_mem(struct target *target,
3523 target_addr_t address,
3524 target_write_fn fn,
3525 unsigned data_size,
3526 /* value */
3527 uint64_t b,
3528 /* count */
3529 unsigned c)
3531 /* We have to write in reasonably large chunks to be able
3532 * to fill large memory areas with any sane speed */
3533 const unsigned chunk_size = 16384;
3534 uint8_t *target_buf = malloc(chunk_size * data_size);
3535 if (!target_buf) {
3536 LOG_ERROR("Out of memory");
3537 return ERROR_FAIL;
3540 for (unsigned i = 0; i < chunk_size; i++) {
3541 switch (data_size) {
3542 case 8:
3543 target_buffer_set_u64(target, target_buf + i * data_size, b);
3544 break;
3545 case 4:
3546 target_buffer_set_u32(target, target_buf + i * data_size, b);
3547 break;
3548 case 2:
3549 target_buffer_set_u16(target, target_buf + i * data_size, b);
3550 break;
3551 case 1:
3552 target_buffer_set_u8(target, target_buf + i * data_size, b);
3553 break;
3554 default:
3555 exit(-1);
3559 int retval = ERROR_OK;
3561 for (unsigned x = 0; x < c; x += chunk_size) {
3562 unsigned current;
3563 current = c - x;
3564 if (current > chunk_size)
3565 current = chunk_size;
3566 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3567 if (retval != ERROR_OK)
3568 break;
3569 /* avoid GDB timeouts */
3570 keep_alive();
3572 free(target_buf);
3574 return retval;
3578 COMMAND_HANDLER(handle_mw_command)
3580 if (CMD_ARGC < 2)
3581 return ERROR_COMMAND_SYNTAX_ERROR;
3582 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3583 target_write_fn fn;
3584 if (physical) {
3585 CMD_ARGC--;
3586 CMD_ARGV++;
3587 fn = target_write_phys_memory;
3588 } else
3589 fn = target_write_memory;
3590 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3591 return ERROR_COMMAND_SYNTAX_ERROR;
3593 target_addr_t address;
3594 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3596 uint64_t value;
3597 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[1], value);
3599 unsigned count = 1;
3600 if (CMD_ARGC == 3)
3601 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3603 struct target *target = get_current_target(CMD_CTX);
3604 unsigned wordsize;
3605 switch (CMD_NAME[2]) {
3606 case 'd':
3607 wordsize = 8;
3608 break;
3609 case 'w':
3610 wordsize = 4;
3611 break;
3612 case 'h':
3613 wordsize = 2;
3614 break;
3615 case 'b':
3616 wordsize = 1;
3617 break;
3618 default:
3619 return ERROR_COMMAND_SYNTAX_ERROR;
3622 return target_fill_mem(target, address, fn, wordsize, value, count);
3625 static COMMAND_HELPER(parse_load_image_command, struct image *image,
3626 target_addr_t *min_address, target_addr_t *max_address)
3628 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3629 return ERROR_COMMAND_SYNTAX_ERROR;
3631 /* a base address isn't always necessary,
3632 * default to 0x0 (i.e. don't relocate) */
3633 if (CMD_ARGC >= 2) {
3634 target_addr_t addr;
3635 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3636 image->base_address = addr;
3637 image->base_address_set = true;
3638 } else
3639 image->base_address_set = false;
3641 image->start_address_set = false;
3643 if (CMD_ARGC >= 4)
3644 COMMAND_PARSE_ADDRESS(CMD_ARGV[3], *min_address);
3645 if (CMD_ARGC == 5) {
3646 COMMAND_PARSE_ADDRESS(CMD_ARGV[4], *max_address);
3647 /* use size (given) to find max (required) */
3648 *max_address += *min_address;
3651 if (*min_address > *max_address)
3652 return ERROR_COMMAND_SYNTAX_ERROR;
3654 return ERROR_OK;
3657 COMMAND_HANDLER(handle_load_image_command)
3659 uint8_t *buffer;
3660 size_t buf_cnt;
3661 uint32_t image_size;
3662 target_addr_t min_address = 0;
3663 target_addr_t max_address = -1;
3664 struct image image;
3666 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
3667 &image, &min_address, &max_address);
3668 if (retval != ERROR_OK)
3669 return retval;
3671 struct target *target = get_current_target(CMD_CTX);
3673 struct duration bench;
3674 duration_start(&bench);
3676 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3677 return ERROR_FAIL;
3679 image_size = 0x0;
3680 retval = ERROR_OK;
3681 for (unsigned int i = 0; i < image.num_sections; i++) {
3682 buffer = malloc(image.sections[i].size);
3683 if (!buffer) {
3684 command_print(CMD,
3685 "error allocating buffer for section (%d bytes)",
3686 (int)(image.sections[i].size));
3687 retval = ERROR_FAIL;
3688 break;
3691 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3692 if (retval != ERROR_OK) {
3693 free(buffer);
3694 break;
3697 uint32_t offset = 0;
3698 uint32_t length = buf_cnt;
3700 /* DANGER!!! beware of unsigned comparison here!!! */
3702 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3703 (image.sections[i].base_address < max_address)) {
3705 if (image.sections[i].base_address < min_address) {
3706 /* clip addresses below */
3707 offset += min_address-image.sections[i].base_address;
3708 length -= offset;
3711 if (image.sections[i].base_address + buf_cnt > max_address)
3712 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3714 retval = target_write_buffer(target,
3715 image.sections[i].base_address + offset, length, buffer + offset);
3716 if (retval != ERROR_OK) {
3717 free(buffer);
3718 break;
3720 image_size += length;
3721 command_print(CMD, "%u bytes written at address " TARGET_ADDR_FMT "",
3722 (unsigned int)length,
3723 image.sections[i].base_address + offset);
3726 free(buffer);
3729 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3730 command_print(CMD, "downloaded %" PRIu32 " bytes "
3731 "in %fs (%0.3f KiB/s)", image_size,
3732 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3735 image_close(&image);
3737 return retval;
3741 COMMAND_HANDLER(handle_dump_image_command)
3743 struct fileio *fileio;
3744 uint8_t *buffer;
3745 int retval, retvaltemp;
3746 target_addr_t address, size;
3747 struct duration bench;
3748 struct target *target = get_current_target(CMD_CTX);
3750 if (CMD_ARGC != 3)
3751 return ERROR_COMMAND_SYNTAX_ERROR;
3753 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], address);
3754 COMMAND_PARSE_ADDRESS(CMD_ARGV[2], size);
3756 uint32_t buf_size = (size > 4096) ? 4096 : size;
3757 buffer = malloc(buf_size);
3758 if (!buffer)
3759 return ERROR_FAIL;
3761 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3762 if (retval != ERROR_OK) {
3763 free(buffer);
3764 return retval;
3767 duration_start(&bench);
3769 while (size > 0) {
3770 size_t size_written;
3771 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3772 retval = target_read_buffer(target, address, this_run_size, buffer);
3773 if (retval != ERROR_OK)
3774 break;
3776 retval = fileio_write(fileio, this_run_size, buffer, &size_written);
3777 if (retval != ERROR_OK)
3778 break;
3780 size -= this_run_size;
3781 address += this_run_size;
3784 free(buffer);
3786 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3787 size_t filesize;
3788 retval = fileio_size(fileio, &filesize);
3789 if (retval != ERROR_OK)
3790 return retval;
3791 command_print(CMD,
3792 "dumped %zu bytes in %fs (%0.3f KiB/s)", filesize,
3793 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3796 retvaltemp = fileio_close(fileio);
3797 if (retvaltemp != ERROR_OK)
3798 return retvaltemp;
3800 return retval;
3803 enum verify_mode {
3804 IMAGE_TEST = 0,
3805 IMAGE_VERIFY = 1,
3806 IMAGE_CHECKSUM_ONLY = 2
3809 static COMMAND_HELPER(handle_verify_image_command_internal, enum verify_mode verify)
3811 uint8_t *buffer;
3812 size_t buf_cnt;
3813 uint32_t image_size;
3814 int retval;
3815 uint32_t checksum = 0;
3816 uint32_t mem_checksum = 0;
3818 struct image image;
3820 struct target *target = get_current_target(CMD_CTX);
3822 if (CMD_ARGC < 1)
3823 return ERROR_COMMAND_SYNTAX_ERROR;
3825 if (!target) {
3826 LOG_ERROR("no target selected");
3827 return ERROR_FAIL;
3830 struct duration bench;
3831 duration_start(&bench);
3833 if (CMD_ARGC >= 2) {
3834 target_addr_t addr;
3835 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3836 image.base_address = addr;
3837 image.base_address_set = true;
3838 } else {
3839 image.base_address_set = false;
3840 image.base_address = 0x0;
3843 image.start_address_set = false;
3845 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3846 if (retval != ERROR_OK)
3847 return retval;
3849 image_size = 0x0;
3850 int diffs = 0;
3851 retval = ERROR_OK;
3852 for (unsigned int i = 0; i < image.num_sections; i++) {
3853 buffer = malloc(image.sections[i].size);
3854 if (!buffer) {
3855 command_print(CMD,
3856 "error allocating buffer for section (%" PRIu32 " bytes)",
3857 image.sections[i].size);
3858 break;
3860 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3861 if (retval != ERROR_OK) {
3862 free(buffer);
3863 break;
3866 if (verify >= IMAGE_VERIFY) {
3867 /* calculate checksum of image */
3868 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3869 if (retval != ERROR_OK) {
3870 free(buffer);
3871 break;
3874 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3875 if (retval != ERROR_OK) {
3876 free(buffer);
3877 break;
3879 if ((checksum != mem_checksum) && (verify == IMAGE_CHECKSUM_ONLY)) {
3880 LOG_ERROR("checksum mismatch");
3881 free(buffer);
3882 retval = ERROR_FAIL;
3883 goto done;
3885 if (checksum != mem_checksum) {
3886 /* failed crc checksum, fall back to a binary compare */
3887 uint8_t *data;
3889 if (diffs == 0)
3890 LOG_ERROR("checksum mismatch - attempting binary compare");
3892 data = malloc(buf_cnt);
3894 retval = target_read_buffer(target, image.sections[i].base_address, buf_cnt, data);
3895 if (retval == ERROR_OK) {
3896 uint32_t t;
3897 for (t = 0; t < buf_cnt; t++) {
3898 if (data[t] != buffer[t]) {
3899 command_print(CMD,
3900 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3901 diffs,
3902 (unsigned)(t + image.sections[i].base_address),
3903 data[t],
3904 buffer[t]);
3905 if (diffs++ >= 127) {
3906 command_print(CMD, "More than 128 errors, the rest are not printed.");
3907 free(data);
3908 free(buffer);
3909 goto done;
3912 keep_alive();
3915 free(data);
3917 } else {
3918 command_print(CMD, "address " TARGET_ADDR_FMT " length 0x%08zx",
3919 image.sections[i].base_address,
3920 buf_cnt);
3923 free(buffer);
3924 image_size += buf_cnt;
3926 if (diffs > 0)
3927 command_print(CMD, "No more differences found.");
3928 done:
3929 if (diffs > 0)
3930 retval = ERROR_FAIL;
3931 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3932 command_print(CMD, "verified %" PRIu32 " bytes "
3933 "in %fs (%0.3f KiB/s)", image_size,
3934 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3937 image_close(&image);
3939 return retval;
3942 COMMAND_HANDLER(handle_verify_image_checksum_command)
3944 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_CHECKSUM_ONLY);
3947 COMMAND_HANDLER(handle_verify_image_command)
3949 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_VERIFY);
3952 COMMAND_HANDLER(handle_test_image_command)
3954 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_TEST);
3957 static int handle_bp_command_list(struct command_invocation *cmd)
3959 struct target *target = get_current_target(cmd->ctx);
3960 struct breakpoint *breakpoint = target->breakpoints;
3961 while (breakpoint) {
3962 if (breakpoint->type == BKPT_SOFT) {
3963 char *buf = buf_to_hex_str(breakpoint->orig_instr,
3964 breakpoint->length);
3965 command_print(cmd, "IVA breakpoint: " TARGET_ADDR_FMT ", 0x%x, 0x%s",
3966 breakpoint->address,
3967 breakpoint->length,
3968 buf);
3969 free(buf);
3970 } else {
3971 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3972 command_print(cmd, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %u",
3973 breakpoint->asid,
3974 breakpoint->length, breakpoint->number);
3975 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3976 command_print(cmd, "Hybrid breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %u",
3977 breakpoint->address,
3978 breakpoint->length, breakpoint->number);
3979 command_print(cmd, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3980 breakpoint->asid);
3981 } else
3982 command_print(cmd, "Breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %u",
3983 breakpoint->address,
3984 breakpoint->length, breakpoint->number);
3987 breakpoint = breakpoint->next;
3989 return ERROR_OK;
3992 static int handle_bp_command_set(struct command_invocation *cmd,
3993 target_addr_t addr, uint32_t asid, uint32_t length, int hw)
3995 struct target *target = get_current_target(cmd->ctx);
3996 int retval;
3998 if (asid == 0) {
3999 retval = breakpoint_add(target, addr, length, hw);
4000 /* error is always logged in breakpoint_add(), do not print it again */
4001 if (retval == ERROR_OK)
4002 command_print(cmd, "breakpoint set at " TARGET_ADDR_FMT "", addr);
4004 } else if (addr == 0) {
4005 if (!target->type->add_context_breakpoint) {
4006 LOG_ERROR("Context breakpoint not available");
4007 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
4009 retval = context_breakpoint_add(target, asid, length, hw);
4010 /* error is always logged in context_breakpoint_add(), do not print it again */
4011 if (retval == ERROR_OK)
4012 command_print(cmd, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
4014 } else {
4015 if (!target->type->add_hybrid_breakpoint) {
4016 LOG_ERROR("Hybrid breakpoint not available");
4017 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
4019 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
4020 /* error is always logged in hybrid_breakpoint_add(), do not print it again */
4021 if (retval == ERROR_OK)
4022 command_print(cmd, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
4024 return retval;
4027 COMMAND_HANDLER(handle_bp_command)
4029 target_addr_t addr;
4030 uint32_t asid;
4031 uint32_t length;
4032 int hw = BKPT_SOFT;
4034 switch (CMD_ARGC) {
4035 case 0:
4036 return handle_bp_command_list(CMD);
4038 case 2:
4039 asid = 0;
4040 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4041 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4042 return handle_bp_command_set(CMD, addr, asid, length, hw);
4044 case 3:
4045 if (strcmp(CMD_ARGV[2], "hw") == 0) {
4046 hw = BKPT_HARD;
4047 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4048 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4049 asid = 0;
4050 return handle_bp_command_set(CMD, addr, asid, length, hw);
4051 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
4052 hw = BKPT_HARD;
4053 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
4054 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4055 addr = 0;
4056 return handle_bp_command_set(CMD, addr, asid, length, hw);
4058 /* fallthrough */
4059 case 4:
4060 hw = BKPT_HARD;
4061 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4062 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
4063 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
4064 return handle_bp_command_set(CMD, addr, asid, length, hw);
4066 default:
4067 return ERROR_COMMAND_SYNTAX_ERROR;
4071 COMMAND_HANDLER(handle_rbp_command)
4073 if (CMD_ARGC != 1)
4074 return ERROR_COMMAND_SYNTAX_ERROR;
4076 struct target *target = get_current_target(CMD_CTX);
4078 if (!strcmp(CMD_ARGV[0], "all")) {
4079 breakpoint_remove_all(target);
4080 } else {
4081 target_addr_t addr;
4082 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4084 breakpoint_remove(target, addr);
4087 return ERROR_OK;
4090 COMMAND_HANDLER(handle_wp_command)
4092 struct target *target = get_current_target(CMD_CTX);
4094 if (CMD_ARGC == 0) {
4095 struct watchpoint *watchpoint = target->watchpoints;
4097 while (watchpoint) {
4098 command_print(CMD, "address: " TARGET_ADDR_FMT
4099 ", len: 0x%8.8" PRIx32
4100 ", r/w/a: %i, value: 0x%8.8" PRIx32
4101 ", mask: 0x%8.8" PRIx32,
4102 watchpoint->address,
4103 watchpoint->length,
4104 (int)watchpoint->rw,
4105 watchpoint->value,
4106 watchpoint->mask);
4107 watchpoint = watchpoint->next;
4109 return ERROR_OK;
4112 enum watchpoint_rw type = WPT_ACCESS;
4113 target_addr_t addr = 0;
4114 uint32_t length = 0;
4115 uint32_t data_value = 0x0;
4116 uint32_t data_mask = 0xffffffff;
4118 switch (CMD_ARGC) {
4119 case 5:
4120 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
4121 /* fall through */
4122 case 4:
4123 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
4124 /* fall through */
4125 case 3:
4126 switch (CMD_ARGV[2][0]) {
4127 case 'r':
4128 type = WPT_READ;
4129 break;
4130 case 'w':
4131 type = WPT_WRITE;
4132 break;
4133 case 'a':
4134 type = WPT_ACCESS;
4135 break;
4136 default:
4137 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
4138 return ERROR_COMMAND_SYNTAX_ERROR;
4140 /* fall through */
4141 case 2:
4142 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4143 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4144 break;
4146 default:
4147 return ERROR_COMMAND_SYNTAX_ERROR;
4150 int retval = watchpoint_add(target, addr, length, type,
4151 data_value, data_mask);
4152 if (retval != ERROR_OK)
4153 LOG_ERROR("Failure setting watchpoints");
4155 return retval;
4158 COMMAND_HANDLER(handle_rwp_command)
4160 if (CMD_ARGC != 1)
4161 return ERROR_COMMAND_SYNTAX_ERROR;
4163 target_addr_t addr;
4164 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4166 struct target *target = get_current_target(CMD_CTX);
4167 watchpoint_remove(target, addr);
4169 return ERROR_OK;
4173 * Translate a virtual address to a physical address.
4175 * The low-level target implementation must have logged a detailed error
4176 * which is forwarded to telnet/GDB session.
4178 COMMAND_HANDLER(handle_virt2phys_command)
4180 if (CMD_ARGC != 1)
4181 return ERROR_COMMAND_SYNTAX_ERROR;
4183 target_addr_t va;
4184 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], va);
4185 target_addr_t pa;
4187 struct target *target = get_current_target(CMD_CTX);
4188 int retval = target->type->virt2phys(target, va, &pa);
4189 if (retval == ERROR_OK)
4190 command_print(CMD, "Physical address " TARGET_ADDR_FMT "", pa);
4192 return retval;
4195 static void write_data(FILE *f, const void *data, size_t len)
4197 size_t written = fwrite(data, 1, len, f);
4198 if (written != len)
4199 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
4202 static void write_long(FILE *f, int l, struct target *target)
4204 uint8_t val[4];
4206 target_buffer_set_u32(target, val, l);
4207 write_data(f, val, 4);
4210 static void write_string(FILE *f, char *s)
4212 write_data(f, s, strlen(s));
4215 typedef unsigned char UNIT[2]; /* unit of profiling */
4217 /* Dump a gmon.out histogram file. */
4218 static void write_gmon(uint32_t *samples, uint32_t sample_num, const char *filename, bool with_range,
4219 uint32_t start_address, uint32_t end_address, struct target *target, uint32_t duration_ms)
4221 uint32_t i;
4222 FILE *f = fopen(filename, "w");
4223 if (!f)
4224 return;
4225 write_string(f, "gmon");
4226 write_long(f, 0x00000001, target); /* Version */
4227 write_long(f, 0, target); /* padding */
4228 write_long(f, 0, target); /* padding */
4229 write_long(f, 0, target); /* padding */
4231 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
4232 write_data(f, &zero, 1);
4234 /* figure out bucket size */
4235 uint32_t min;
4236 uint32_t max;
4237 if (with_range) {
4238 min = start_address;
4239 max = end_address;
4240 } else {
4241 min = samples[0];
4242 max = samples[0];
4243 for (i = 0; i < sample_num; i++) {
4244 if (min > samples[i])
4245 min = samples[i];
4246 if (max < samples[i])
4247 max = samples[i];
4250 /* max should be (largest sample + 1)
4251 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
4252 max++;
4255 int address_space = max - min;
4256 assert(address_space >= 2);
4258 /* FIXME: What is the reasonable number of buckets?
4259 * The profiling result will be more accurate if there are enough buckets. */
4260 static const uint32_t max_buckets = 128 * 1024; /* maximum buckets. */
4261 uint32_t num_buckets = address_space / sizeof(UNIT);
4262 if (num_buckets > max_buckets)
4263 num_buckets = max_buckets;
4264 int *buckets = malloc(sizeof(int) * num_buckets);
4265 if (!buckets) {
4266 fclose(f);
4267 return;
4269 memset(buckets, 0, sizeof(int) * num_buckets);
4270 for (i = 0; i < sample_num; i++) {
4271 uint32_t address = samples[i];
4273 if ((address < min) || (max <= address))
4274 continue;
4276 long long a = address - min;
4277 long long b = num_buckets;
4278 long long c = address_space;
4279 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
4280 buckets[index_t]++;
4283 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
4284 write_long(f, min, target); /* low_pc */
4285 write_long(f, max, target); /* high_pc */
4286 write_long(f, num_buckets, target); /* # of buckets */
4287 float sample_rate = sample_num / (duration_ms / 1000.0);
4288 write_long(f, sample_rate, target);
4289 write_string(f, "seconds");
4290 for (i = 0; i < (15-strlen("seconds")); i++)
4291 write_data(f, &zero, 1);
4292 write_string(f, "s");
4294 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
4296 char *data = malloc(2 * num_buckets);
4297 if (data) {
4298 for (i = 0; i < num_buckets; i++) {
4299 int val;
4300 val = buckets[i];
4301 if (val > 65535)
4302 val = 65535;
4303 data[i * 2] = val&0xff;
4304 data[i * 2 + 1] = (val >> 8) & 0xff;
4306 free(buckets);
4307 write_data(f, data, num_buckets * 2);
4308 free(data);
4309 } else
4310 free(buckets);
4312 fclose(f);
4315 /* profiling samples the CPU PC as quickly as OpenOCD is able,
4316 * which will be used as a random sampling of PC */
4317 COMMAND_HANDLER(handle_profile_command)
4319 struct target *target = get_current_target(CMD_CTX);
4321 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
4322 return ERROR_COMMAND_SYNTAX_ERROR;
4324 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
4325 uint32_t offset;
4326 uint32_t num_of_samples;
4327 int retval = ERROR_OK;
4328 bool halted_before_profiling = target->state == TARGET_HALTED;
4330 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
4332 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
4333 if (!samples) {
4334 LOG_ERROR("No memory to store samples.");
4335 return ERROR_FAIL;
4338 uint64_t timestart_ms = timeval_ms();
4340 * Some cores let us sample the PC without the
4341 * annoying halt/resume step; for example, ARMv7 PCSR.
4342 * Provide a way to use that more efficient mechanism.
4344 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
4345 &num_of_samples, offset);
4346 if (retval != ERROR_OK) {
4347 free(samples);
4348 return retval;
4350 uint32_t duration_ms = timeval_ms() - timestart_ms;
4352 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
4354 retval = target_poll(target);
4355 if (retval != ERROR_OK) {
4356 free(samples);
4357 return retval;
4360 if (target->state == TARGET_RUNNING && halted_before_profiling) {
4361 /* The target was halted before we started and is running now. Halt it,
4362 * for consistency. */
4363 retval = target_halt(target);
4364 if (retval != ERROR_OK) {
4365 free(samples);
4366 return retval;
4368 } else if (target->state == TARGET_HALTED && !halted_before_profiling) {
4369 /* The target was running before we started and is halted now. Resume
4370 * it, for consistency. */
4371 retval = target_resume(target, 1, 0, 0, 0);
4372 if (retval != ERROR_OK) {
4373 free(samples);
4374 return retval;
4378 retval = target_poll(target);
4379 if (retval != ERROR_OK) {
4380 free(samples);
4381 return retval;
4384 uint32_t start_address = 0;
4385 uint32_t end_address = 0;
4386 bool with_range = false;
4387 if (CMD_ARGC == 4) {
4388 with_range = true;
4389 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
4390 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
4393 write_gmon(samples, num_of_samples, CMD_ARGV[1],
4394 with_range, start_address, end_address, target, duration_ms);
4395 command_print(CMD, "Wrote %s", CMD_ARGV[1]);
4397 free(samples);
4398 return retval;
4401 static int new_u64_array_element(Jim_Interp *interp, const char *varname, int idx, uint64_t val)
4403 char *namebuf;
4404 Jim_Obj *obj_name, *obj_val;
4405 int result;
4407 namebuf = alloc_printf("%s(%d)", varname, idx);
4408 if (!namebuf)
4409 return JIM_ERR;
4411 obj_name = Jim_NewStringObj(interp, namebuf, -1);
4412 jim_wide wide_val = val;
4413 obj_val = Jim_NewWideObj(interp, wide_val);
4414 if (!obj_name || !obj_val) {
4415 free(namebuf);
4416 return JIM_ERR;
4419 Jim_IncrRefCount(obj_name);
4420 Jim_IncrRefCount(obj_val);
4421 result = Jim_SetVariable(interp, obj_name, obj_val);
4422 Jim_DecrRefCount(interp, obj_name);
4423 Jim_DecrRefCount(interp, obj_val);
4424 free(namebuf);
4425 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
4426 return result;
4429 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
4431 int e;
4433 LOG_WARNING("DEPRECATED! use 'read_memory' not 'mem2array'");
4435 /* argv[0] = name of array to receive the data
4436 * argv[1] = desired element width in bits
4437 * argv[2] = memory address
4438 * argv[3] = count of times to read
4439 * argv[4] = optional "phys"
4441 if (argc < 4 || argc > 5) {
4442 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4443 return JIM_ERR;
4446 /* Arg 0: Name of the array variable */
4447 const char *varname = Jim_GetString(argv[0], NULL);
4449 /* Arg 1: Bit width of one element */
4450 long l;
4451 e = Jim_GetLong(interp, argv[1], &l);
4452 if (e != JIM_OK)
4453 return e;
4454 const unsigned int width_bits = l;
4456 if (width_bits != 8 &&
4457 width_bits != 16 &&
4458 width_bits != 32 &&
4459 width_bits != 64) {
4460 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4461 Jim_AppendStrings(interp, Jim_GetResult(interp),
4462 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4463 return JIM_ERR;
4465 const unsigned int width = width_bits / 8;
4467 /* Arg 2: Memory address */
4468 jim_wide wide_addr;
4469 e = Jim_GetWide(interp, argv[2], &wide_addr);
4470 if (e != JIM_OK)
4471 return e;
4472 target_addr_t addr = (target_addr_t)wide_addr;
4474 /* Arg 3: Number of elements to read */
4475 e = Jim_GetLong(interp, argv[3], &l);
4476 if (e != JIM_OK)
4477 return e;
4478 size_t len = l;
4480 /* Arg 4: phys */
4481 bool is_phys = false;
4482 if (argc > 4) {
4483 int str_len = 0;
4484 const char *phys = Jim_GetString(argv[4], &str_len);
4485 if (!strncmp(phys, "phys", str_len))
4486 is_phys = true;
4487 else
4488 return JIM_ERR;
4491 /* Argument checks */
4492 if (len == 0) {
4493 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4494 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
4495 return JIM_ERR;
4497 if ((addr + (len * width)) < addr) {
4498 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4499 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
4500 return JIM_ERR;
4502 if (len > 65536) {
4503 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4504 Jim_AppendStrings(interp, Jim_GetResult(interp),
4505 "mem2array: too large read request, exceeds 64K items", NULL);
4506 return JIM_ERR;
4509 if ((width == 1) ||
4510 ((width == 2) && ((addr & 1) == 0)) ||
4511 ((width == 4) && ((addr & 3) == 0)) ||
4512 ((width == 8) && ((addr & 7) == 0))) {
4513 /* alignment correct */
4514 } else {
4515 char buf[100];
4516 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4517 sprintf(buf, "mem2array address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4518 addr,
4519 width);
4520 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4521 return JIM_ERR;
4524 /* Transfer loop */
4526 /* index counter */
4527 size_t idx = 0;
4529 const size_t buffersize = 4096;
4530 uint8_t *buffer = malloc(buffersize);
4531 if (!buffer)
4532 return JIM_ERR;
4534 /* assume ok */
4535 e = JIM_OK;
4536 while (len) {
4537 /* Slurp... in buffer size chunks */
4538 const unsigned int max_chunk_len = buffersize / width;
4539 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4541 int retval;
4542 if (is_phys)
4543 retval = target_read_phys_memory(target, addr, width, chunk_len, buffer);
4544 else
4545 retval = target_read_memory(target, addr, width, chunk_len, buffer);
4546 if (retval != ERROR_OK) {
4547 /* BOO !*/
4548 LOG_ERROR("mem2array: Read @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4549 addr,
4550 width,
4551 chunk_len);
4552 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4553 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
4554 e = JIM_ERR;
4555 break;
4556 } else {
4557 for (size_t i = 0; i < chunk_len ; i++, idx++) {
4558 uint64_t v = 0;
4559 switch (width) {
4560 case 8:
4561 v = target_buffer_get_u64(target, &buffer[i*width]);
4562 break;
4563 case 4:
4564 v = target_buffer_get_u32(target, &buffer[i*width]);
4565 break;
4566 case 2:
4567 v = target_buffer_get_u16(target, &buffer[i*width]);
4568 break;
4569 case 1:
4570 v = buffer[i] & 0x0ff;
4571 break;
4573 new_u64_array_element(interp, varname, idx, v);
4575 len -= chunk_len;
4576 addr += chunk_len * width;
4580 free(buffer);
4582 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4584 return e;
4587 static int target_jim_read_memory(Jim_Interp *interp, int argc,
4588 Jim_Obj * const *argv)
4591 * argv[1] = memory address
4592 * argv[2] = desired element width in bits
4593 * argv[3] = number of elements to read
4594 * argv[4] = optional "phys"
4597 if (argc < 4 || argc > 5) {
4598 Jim_WrongNumArgs(interp, 1, argv, "address width count ['phys']");
4599 return JIM_ERR;
4602 /* Arg 1: Memory address. */
4603 jim_wide wide_addr;
4604 int e;
4605 e = Jim_GetWide(interp, argv[1], &wide_addr);
4607 if (e != JIM_OK)
4608 return e;
4610 target_addr_t addr = (target_addr_t)wide_addr;
4612 /* Arg 2: Bit width of one element. */
4613 long l;
4614 e = Jim_GetLong(interp, argv[2], &l);
4616 if (e != JIM_OK)
4617 return e;
4619 const unsigned int width_bits = l;
4621 /* Arg 3: Number of elements to read. */
4622 e = Jim_GetLong(interp, argv[3], &l);
4624 if (e != JIM_OK)
4625 return e;
4627 size_t count = l;
4629 /* Arg 4: Optional 'phys'. */
4630 bool is_phys = false;
4632 if (argc > 4) {
4633 const char *phys = Jim_GetString(argv[4], NULL);
4635 if (strcmp(phys, "phys")) {
4636 Jim_SetResultFormatted(interp, "invalid argument '%s', must be 'phys'", phys);
4637 return JIM_ERR;
4640 is_phys = true;
4643 switch (width_bits) {
4644 case 8:
4645 case 16:
4646 case 32:
4647 case 64:
4648 break;
4649 default:
4650 Jim_SetResultString(interp, "invalid width, must be 8, 16, 32 or 64", -1);
4651 return JIM_ERR;
4654 const unsigned int width = width_bits / 8;
4656 if ((addr + (count * width)) < addr) {
4657 Jim_SetResultString(interp, "read_memory: addr + count wraps to zero", -1);
4658 return JIM_ERR;
4661 if (count > 65536) {
4662 Jim_SetResultString(interp, "read_memory: too large read request, exeeds 64K elements", -1);
4663 return JIM_ERR;
4666 struct command_context *cmd_ctx = current_command_context(interp);
4667 assert(cmd_ctx != NULL);
4668 struct target *target = get_current_target(cmd_ctx);
4670 const size_t buffersize = 4096;
4671 uint8_t *buffer = malloc(buffersize);
4673 if (!buffer) {
4674 LOG_ERROR("Failed to allocate memory");
4675 return JIM_ERR;
4678 Jim_Obj *result_list = Jim_NewListObj(interp, NULL, 0);
4679 Jim_IncrRefCount(result_list);
4681 while (count > 0) {
4682 const unsigned int max_chunk_len = buffersize / width;
4683 const size_t chunk_len = MIN(count, max_chunk_len);
4685 int retval;
4687 if (is_phys)
4688 retval = target_read_phys_memory(target, addr, width, chunk_len, buffer);
4689 else
4690 retval = target_read_memory(target, addr, width, chunk_len, buffer);
4692 if (retval != ERROR_OK) {
4693 LOG_ERROR("read_memory: read at " TARGET_ADDR_FMT " with width=%u and count=%zu failed",
4694 addr, width_bits, chunk_len);
4695 Jim_SetResultString(interp, "read_memory: failed to read memory", -1);
4696 e = JIM_ERR;
4697 break;
4700 for (size_t i = 0; i < chunk_len ; i++) {
4701 uint64_t v = 0;
4703 switch (width) {
4704 case 8:
4705 v = target_buffer_get_u64(target, &buffer[i * width]);
4706 break;
4707 case 4:
4708 v = target_buffer_get_u32(target, &buffer[i * width]);
4709 break;
4710 case 2:
4711 v = target_buffer_get_u16(target, &buffer[i * width]);
4712 break;
4713 case 1:
4714 v = buffer[i];
4715 break;
4718 char value_buf[11];
4719 snprintf(value_buf, sizeof(value_buf), "0x%" PRIx64, v);
4721 Jim_ListAppendElement(interp, result_list,
4722 Jim_NewStringObj(interp, value_buf, -1));
4725 count -= chunk_len;
4726 addr += chunk_len * width;
4729 free(buffer);
4731 if (e != JIM_OK) {
4732 Jim_DecrRefCount(interp, result_list);
4733 return e;
4736 Jim_SetResult(interp, result_list);
4737 Jim_DecrRefCount(interp, result_list);
4739 return JIM_OK;
4742 static int get_u64_array_element(Jim_Interp *interp, const char *varname, size_t idx, uint64_t *val)
4744 char *namebuf = alloc_printf("%s(%zu)", varname, idx);
4745 if (!namebuf)
4746 return JIM_ERR;
4748 Jim_Obj *obj_name = Jim_NewStringObj(interp, namebuf, -1);
4749 if (!obj_name) {
4750 free(namebuf);
4751 return JIM_ERR;
4754 Jim_IncrRefCount(obj_name);
4755 Jim_Obj *obj_val = Jim_GetVariable(interp, obj_name, JIM_ERRMSG);
4756 Jim_DecrRefCount(interp, obj_name);
4757 free(namebuf);
4758 if (!obj_val)
4759 return JIM_ERR;
4761 jim_wide wide_val;
4762 int result = Jim_GetWide(interp, obj_val, &wide_val);
4763 *val = wide_val;
4764 return result;
4767 static int target_array2mem(Jim_Interp *interp, struct target *target,
4768 int argc, Jim_Obj *const *argv)
4770 int e;
4772 LOG_WARNING("DEPRECATED! use 'write_memory' not 'array2mem'");
4774 /* argv[0] = name of array from which to read the data
4775 * argv[1] = desired element width in bits
4776 * argv[2] = memory address
4777 * argv[3] = number of elements to write
4778 * argv[4] = optional "phys"
4780 if (argc < 4 || argc > 5) {
4781 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4782 return JIM_ERR;
4785 /* Arg 0: Name of the array variable */
4786 const char *varname = Jim_GetString(argv[0], NULL);
4788 /* Arg 1: Bit width of one element */
4789 long l;
4790 e = Jim_GetLong(interp, argv[1], &l);
4791 if (e != JIM_OK)
4792 return e;
4793 const unsigned int width_bits = l;
4795 if (width_bits != 8 &&
4796 width_bits != 16 &&
4797 width_bits != 32 &&
4798 width_bits != 64) {
4799 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4800 Jim_AppendStrings(interp, Jim_GetResult(interp),
4801 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4802 return JIM_ERR;
4804 const unsigned int width = width_bits / 8;
4806 /* Arg 2: Memory address */
4807 jim_wide wide_addr;
4808 e = Jim_GetWide(interp, argv[2], &wide_addr);
4809 if (e != JIM_OK)
4810 return e;
4811 target_addr_t addr = (target_addr_t)wide_addr;
4813 /* Arg 3: Number of elements to write */
4814 e = Jim_GetLong(interp, argv[3], &l);
4815 if (e != JIM_OK)
4816 return e;
4817 size_t len = l;
4819 /* Arg 4: Phys */
4820 bool is_phys = false;
4821 if (argc > 4) {
4822 int str_len = 0;
4823 const char *phys = Jim_GetString(argv[4], &str_len);
4824 if (!strncmp(phys, "phys", str_len))
4825 is_phys = true;
4826 else
4827 return JIM_ERR;
4830 /* Argument checks */
4831 if (len == 0) {
4832 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4833 Jim_AppendStrings(interp, Jim_GetResult(interp),
4834 "array2mem: zero width read?", NULL);
4835 return JIM_ERR;
4838 if ((addr + (len * width)) < addr) {
4839 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4840 Jim_AppendStrings(interp, Jim_GetResult(interp),
4841 "array2mem: addr + len - wraps to zero?", NULL);
4842 return JIM_ERR;
4845 if (len > 65536) {
4846 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4847 Jim_AppendStrings(interp, Jim_GetResult(interp),
4848 "array2mem: too large memory write request, exceeds 64K items", NULL);
4849 return JIM_ERR;
4852 if ((width == 1) ||
4853 ((width == 2) && ((addr & 1) == 0)) ||
4854 ((width == 4) && ((addr & 3) == 0)) ||
4855 ((width == 8) && ((addr & 7) == 0))) {
4856 /* alignment correct */
4857 } else {
4858 char buf[100];
4859 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4860 sprintf(buf, "array2mem address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4861 addr,
4862 width);
4863 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4864 return JIM_ERR;
4867 /* Transfer loop */
4869 /* assume ok */
4870 e = JIM_OK;
4872 const size_t buffersize = 4096;
4873 uint8_t *buffer = malloc(buffersize);
4874 if (!buffer)
4875 return JIM_ERR;
4877 /* index counter */
4878 size_t idx = 0;
4880 while (len) {
4881 /* Slurp... in buffer size chunks */
4882 const unsigned int max_chunk_len = buffersize / width;
4884 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4886 /* Fill the buffer */
4887 for (size_t i = 0; i < chunk_len; i++, idx++) {
4888 uint64_t v = 0;
4889 if (get_u64_array_element(interp, varname, idx, &v) != JIM_OK) {
4890 free(buffer);
4891 return JIM_ERR;
4893 switch (width) {
4894 case 8:
4895 target_buffer_set_u64(target, &buffer[i * width], v);
4896 break;
4897 case 4:
4898 target_buffer_set_u32(target, &buffer[i * width], v);
4899 break;
4900 case 2:
4901 target_buffer_set_u16(target, &buffer[i * width], v);
4902 break;
4903 case 1:
4904 buffer[i] = v & 0x0ff;
4905 break;
4908 len -= chunk_len;
4910 /* Write the buffer to memory */
4911 int retval;
4912 if (is_phys)
4913 retval = target_write_phys_memory(target, addr, width, chunk_len, buffer);
4914 else
4915 retval = target_write_memory(target, addr, width, chunk_len, buffer);
4916 if (retval != ERROR_OK) {
4917 /* BOO !*/
4918 LOG_ERROR("array2mem: Write @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4919 addr,
4920 width,
4921 chunk_len);
4922 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4923 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4924 e = JIM_ERR;
4925 break;
4927 addr += chunk_len * width;
4930 free(buffer);
4932 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4934 return e;
4937 static int target_jim_write_memory(Jim_Interp *interp, int argc,
4938 Jim_Obj * const *argv)
4941 * argv[1] = memory address
4942 * argv[2] = desired element width in bits
4943 * argv[3] = list of data to write
4944 * argv[4] = optional "phys"
4947 if (argc < 4 || argc > 5) {
4948 Jim_WrongNumArgs(interp, 1, argv, "address width data ['phys']");
4949 return JIM_ERR;
4952 /* Arg 1: Memory address. */
4953 int e;
4954 jim_wide wide_addr;
4955 e = Jim_GetWide(interp, argv[1], &wide_addr);
4957 if (e != JIM_OK)
4958 return e;
4960 target_addr_t addr = (target_addr_t)wide_addr;
4962 /* Arg 2: Bit width of one element. */
4963 long l;
4964 e = Jim_GetLong(interp, argv[2], &l);
4966 if (e != JIM_OK)
4967 return e;
4969 const unsigned int width_bits = l;
4970 size_t count = Jim_ListLength(interp, argv[3]);
4972 /* Arg 4: Optional 'phys'. */
4973 bool is_phys = false;
4975 if (argc > 4) {
4976 const char *phys = Jim_GetString(argv[4], NULL);
4978 if (strcmp(phys, "phys")) {
4979 Jim_SetResultFormatted(interp, "invalid argument '%s', must be 'phys'", phys);
4980 return JIM_ERR;
4983 is_phys = true;
4986 switch (width_bits) {
4987 case 8:
4988 case 16:
4989 case 32:
4990 case 64:
4991 break;
4992 default:
4993 Jim_SetResultString(interp, "invalid width, must be 8, 16, 32 or 64", -1);
4994 return JIM_ERR;
4997 const unsigned int width = width_bits / 8;
4999 if ((addr + (count * width)) < addr) {
5000 Jim_SetResultString(interp, "write_memory: addr + len wraps to zero", -1);
5001 return JIM_ERR;
5004 if (count > 65536) {
5005 Jim_SetResultString(interp, "write_memory: too large memory write request, exceeds 64K elements", -1);
5006 return JIM_ERR;
5009 struct command_context *cmd_ctx = current_command_context(interp);
5010 assert(cmd_ctx != NULL);
5011 struct target *target = get_current_target(cmd_ctx);
5013 const size_t buffersize = 4096;
5014 uint8_t *buffer = malloc(buffersize);
5016 if (!buffer) {
5017 LOG_ERROR("Failed to allocate memory");
5018 return JIM_ERR;
5021 size_t j = 0;
5023 while (count > 0) {
5024 const unsigned int max_chunk_len = buffersize / width;
5025 const size_t chunk_len = MIN(count, max_chunk_len);
5027 for (size_t i = 0; i < chunk_len; i++, j++) {
5028 Jim_Obj *tmp = Jim_ListGetIndex(interp, argv[3], j);
5029 jim_wide element_wide;
5030 Jim_GetWide(interp, tmp, &element_wide);
5032 const uint64_t v = element_wide;
5034 switch (width) {
5035 case 8:
5036 target_buffer_set_u64(target, &buffer[i * width], v);
5037 break;
5038 case 4:
5039 target_buffer_set_u32(target, &buffer[i * width], v);
5040 break;
5041 case 2:
5042 target_buffer_set_u16(target, &buffer[i * width], v);
5043 break;
5044 case 1:
5045 buffer[i] = v & 0x0ff;
5046 break;
5050 count -= chunk_len;
5052 int retval;
5054 if (is_phys)
5055 retval = target_write_phys_memory(target, addr, width, chunk_len, buffer);
5056 else
5057 retval = target_write_memory(target, addr, width, chunk_len, buffer);
5059 if (retval != ERROR_OK) {
5060 LOG_ERROR("write_memory: write at " TARGET_ADDR_FMT " with width=%u and count=%zu failed",
5061 addr, width_bits, chunk_len);
5062 Jim_SetResultString(interp, "write_memory: failed to write memory", -1);
5063 e = JIM_ERR;
5064 break;
5067 addr += chunk_len * width;
5070 free(buffer);
5072 return e;
5075 /* FIX? should we propagate errors here rather than printing them
5076 * and continuing?
5078 void target_handle_event(struct target *target, enum target_event e)
5080 struct target_event_action *teap;
5081 int retval;
5083 for (teap = target->event_action; teap; teap = teap->next) {
5084 if (teap->event == e) {
5085 LOG_DEBUG("target(%d): %s (%s) event: %d (%s) action: %s",
5086 target->target_number,
5087 target_name(target),
5088 target_type_name(target),
5090 target_event_name(e),
5091 Jim_GetString(teap->body, NULL));
5093 /* Override current target by the target an event
5094 * is issued from (lot of scripts need it).
5095 * Return back to previous override as soon
5096 * as the handler processing is done */
5097 struct command_context *cmd_ctx = current_command_context(teap->interp);
5098 struct target *saved_target_override = cmd_ctx->current_target_override;
5099 cmd_ctx->current_target_override = target;
5101 retval = Jim_EvalObj(teap->interp, teap->body);
5103 cmd_ctx->current_target_override = saved_target_override;
5105 if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
5106 return;
5108 if (retval == JIM_RETURN)
5109 retval = teap->interp->returnCode;
5111 if (retval != JIM_OK) {
5112 Jim_MakeErrorMessage(teap->interp);
5113 LOG_USER("Error executing event %s on target %s:\n%s",
5114 target_event_name(e),
5115 target_name(target),
5116 Jim_GetString(Jim_GetResult(teap->interp), NULL));
5117 /* clean both error code and stacktrace before return */
5118 Jim_Eval(teap->interp, "error \"\" \"\"");
5124 static int target_jim_get_reg(Jim_Interp *interp, int argc,
5125 Jim_Obj * const *argv)
5127 bool force = false;
5129 if (argc == 3) {
5130 const char *option = Jim_GetString(argv[1], NULL);
5132 if (!strcmp(option, "-force")) {
5133 argc--;
5134 argv++;
5135 force = true;
5136 } else {
5137 Jim_SetResultFormatted(interp, "invalid option '%s'", option);
5138 return JIM_ERR;
5142 if (argc != 2) {
5143 Jim_WrongNumArgs(interp, 1, argv, "[-force] list");
5144 return JIM_ERR;
5147 const int length = Jim_ListLength(interp, argv[1]);
5149 Jim_Obj *result_dict = Jim_NewDictObj(interp, NULL, 0);
5151 if (!result_dict)
5152 return JIM_ERR;
5154 struct command_context *cmd_ctx = current_command_context(interp);
5155 assert(cmd_ctx != NULL);
5156 const struct target *target = get_current_target(cmd_ctx);
5158 for (int i = 0; i < length; i++) {
5159 Jim_Obj *elem = Jim_ListGetIndex(interp, argv[1], i);
5161 if (!elem)
5162 return JIM_ERR;
5164 const char *reg_name = Jim_String(elem);
5166 struct reg *reg = register_get_by_name(target->reg_cache, reg_name,
5167 false);
5169 if (!reg || !reg->exist) {
5170 Jim_SetResultFormatted(interp, "unknown register '%s'", reg_name);
5171 return JIM_ERR;
5174 if (force) {
5175 int retval = reg->type->get(reg);
5177 if (retval != ERROR_OK) {
5178 Jim_SetResultFormatted(interp, "failed to read register '%s'",
5179 reg_name);
5180 return JIM_ERR;
5184 char *reg_value = buf_to_hex_str(reg->value, reg->size);
5186 if (!reg_value) {
5187 LOG_ERROR("Failed to allocate memory");
5188 return JIM_ERR;
5191 char *tmp = alloc_printf("0x%s", reg_value);
5193 free(reg_value);
5195 if (!tmp) {
5196 LOG_ERROR("Failed to allocate memory");
5197 return JIM_ERR;
5200 Jim_DictAddElement(interp, result_dict, elem,
5201 Jim_NewStringObj(interp, tmp, -1));
5203 free(tmp);
5206 Jim_SetResult(interp, result_dict);
5208 return JIM_OK;
5211 static int target_jim_set_reg(Jim_Interp *interp, int argc,
5212 Jim_Obj * const *argv)
5214 if (argc != 2) {
5215 Jim_WrongNumArgs(interp, 1, argv, "dict");
5216 return JIM_ERR;
5219 int tmp;
5220 #if JIM_VERSION >= 80
5221 Jim_Obj **dict = Jim_DictPairs(interp, argv[1], &tmp);
5223 if (!dict)
5224 return JIM_ERR;
5225 #else
5226 Jim_Obj **dict;
5227 int ret = Jim_DictPairs(interp, argv[1], &dict, &tmp);
5229 if (ret != JIM_OK)
5230 return ret;
5231 #endif
5233 const unsigned int length = tmp;
5234 struct command_context *cmd_ctx = current_command_context(interp);
5235 assert(cmd_ctx);
5236 const struct target *target = get_current_target(cmd_ctx);
5238 for (unsigned int i = 0; i < length; i += 2) {
5239 const char *reg_name = Jim_String(dict[i]);
5240 const char *reg_value = Jim_String(dict[i + 1]);
5241 struct reg *reg = register_get_by_name(target->reg_cache, reg_name,
5242 false);
5244 if (!reg || !reg->exist) {
5245 Jim_SetResultFormatted(interp, "unknown register '%s'", reg_name);
5246 return JIM_ERR;
5249 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
5251 if (!buf) {
5252 LOG_ERROR("Failed to allocate memory");
5253 return JIM_ERR;
5256 str_to_buf(reg_value, strlen(reg_value), buf, reg->size, 0);
5257 int retval = reg->type->set(reg, buf);
5258 free(buf);
5260 if (retval != ERROR_OK) {
5261 Jim_SetResultFormatted(interp, "failed to set '%s' to register '%s'",
5262 reg_value, reg_name);
5263 return JIM_ERR;
5267 return JIM_OK;
5271 * Returns true only if the target has a handler for the specified event.
5273 bool target_has_event_action(struct target *target, enum target_event event)
5275 struct target_event_action *teap;
5277 for (teap = target->event_action; teap; teap = teap->next) {
5278 if (teap->event == event)
5279 return true;
5281 return false;
5284 enum target_cfg_param {
5285 TCFG_TYPE,
5286 TCFG_EVENT,
5287 TCFG_WORK_AREA_VIRT,
5288 TCFG_WORK_AREA_PHYS,
5289 TCFG_WORK_AREA_SIZE,
5290 TCFG_WORK_AREA_BACKUP,
5291 TCFG_ENDIAN,
5292 TCFG_COREID,
5293 TCFG_CHAIN_POSITION,
5294 TCFG_DBGBASE,
5295 TCFG_RTOS,
5296 TCFG_DEFER_EXAMINE,
5297 TCFG_GDB_PORT,
5298 TCFG_GDB_MAX_CONNECTIONS,
5301 static struct jim_nvp nvp_config_opts[] = {
5302 { .name = "-type", .value = TCFG_TYPE },
5303 { .name = "-event", .value = TCFG_EVENT },
5304 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
5305 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
5306 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
5307 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
5308 { .name = "-endian", .value = TCFG_ENDIAN },
5309 { .name = "-coreid", .value = TCFG_COREID },
5310 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
5311 { .name = "-dbgbase", .value = TCFG_DBGBASE },
5312 { .name = "-rtos", .value = TCFG_RTOS },
5313 { .name = "-defer-examine", .value = TCFG_DEFER_EXAMINE },
5314 { .name = "-gdb-port", .value = TCFG_GDB_PORT },
5315 { .name = "-gdb-max-connections", .value = TCFG_GDB_MAX_CONNECTIONS },
5316 { .name = NULL, .value = -1 }
5319 static int target_configure(struct jim_getopt_info *goi, struct target *target)
5321 struct jim_nvp *n;
5322 Jim_Obj *o;
5323 jim_wide w;
5324 int e;
5326 /* parse config or cget options ... */
5327 while (goi->argc > 0) {
5328 Jim_SetEmptyResult(goi->interp);
5329 /* jim_getopt_debug(goi); */
5331 if (target->type->target_jim_configure) {
5332 /* target defines a configure function */
5333 /* target gets first dibs on parameters */
5334 e = (*(target->type->target_jim_configure))(target, goi);
5335 if (e == JIM_OK) {
5336 /* more? */
5337 continue;
5339 if (e == JIM_ERR) {
5340 /* An error */
5341 return e;
5343 /* otherwise we 'continue' below */
5345 e = jim_getopt_nvp(goi, nvp_config_opts, &n);
5346 if (e != JIM_OK) {
5347 jim_getopt_nvp_unknown(goi, nvp_config_opts, 0);
5348 return e;
5350 switch (n->value) {
5351 case TCFG_TYPE:
5352 /* not settable */
5353 if (goi->isconfigure) {
5354 Jim_SetResultFormatted(goi->interp,
5355 "not settable: %s", n->name);
5356 return JIM_ERR;
5357 } else {
5358 no_params:
5359 if (goi->argc != 0) {
5360 Jim_WrongNumArgs(goi->interp,
5361 goi->argc, goi->argv,
5362 "NO PARAMS");
5363 return JIM_ERR;
5366 Jim_SetResultString(goi->interp,
5367 target_type_name(target), -1);
5368 /* loop for more */
5369 break;
5370 case TCFG_EVENT:
5371 if (goi->argc == 0) {
5372 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
5373 return JIM_ERR;
5376 e = jim_getopt_nvp(goi, nvp_target_event, &n);
5377 if (e != JIM_OK) {
5378 jim_getopt_nvp_unknown(goi, nvp_target_event, 1);
5379 return e;
5382 if (goi->isconfigure) {
5383 if (goi->argc != 1) {
5384 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
5385 return JIM_ERR;
5387 } else {
5388 if (goi->argc != 0) {
5389 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
5390 return JIM_ERR;
5395 struct target_event_action *teap;
5397 teap = target->event_action;
5398 /* replace existing? */
5399 while (teap) {
5400 if (teap->event == (enum target_event)n->value)
5401 break;
5402 teap = teap->next;
5405 if (goi->isconfigure) {
5406 /* START_DEPRECATED_TPIU */
5407 if (n->value == TARGET_EVENT_TRACE_CONFIG)
5408 LOG_INFO("DEPRECATED target event %s; use TPIU events {pre,post}-{enable,disable}", n->name);
5409 /* END_DEPRECATED_TPIU */
5411 bool replace = true;
5412 if (!teap) {
5413 /* create new */
5414 teap = calloc(1, sizeof(*teap));
5415 replace = false;
5417 teap->event = n->value;
5418 teap->interp = goi->interp;
5419 jim_getopt_obj(goi, &o);
5420 if (teap->body)
5421 Jim_DecrRefCount(teap->interp, teap->body);
5422 teap->body = Jim_DuplicateObj(goi->interp, o);
5424 * FIXME:
5425 * Tcl/TK - "tk events" have a nice feature.
5426 * See the "BIND" command.
5427 * We should support that here.
5428 * You can specify %X and %Y in the event code.
5429 * The idea is: %T - target name.
5430 * The idea is: %N - target number
5431 * The idea is: %E - event name.
5433 Jim_IncrRefCount(teap->body);
5435 if (!replace) {
5436 /* add to head of event list */
5437 teap->next = target->event_action;
5438 target->event_action = teap;
5440 Jim_SetEmptyResult(goi->interp);
5441 } else {
5442 /* get */
5443 if (!teap)
5444 Jim_SetEmptyResult(goi->interp);
5445 else
5446 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
5449 /* loop for more */
5450 break;
5452 case TCFG_WORK_AREA_VIRT:
5453 if (goi->isconfigure) {
5454 target_free_all_working_areas(target);
5455 e = jim_getopt_wide(goi, &w);
5456 if (e != JIM_OK)
5457 return e;
5458 target->working_area_virt = w;
5459 target->working_area_virt_spec = true;
5460 } else {
5461 if (goi->argc != 0)
5462 goto no_params;
5464 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
5465 /* loop for more */
5466 break;
5468 case TCFG_WORK_AREA_PHYS:
5469 if (goi->isconfigure) {
5470 target_free_all_working_areas(target);
5471 e = jim_getopt_wide(goi, &w);
5472 if (e != JIM_OK)
5473 return e;
5474 target->working_area_phys = w;
5475 target->working_area_phys_spec = true;
5476 } else {
5477 if (goi->argc != 0)
5478 goto no_params;
5480 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
5481 /* loop for more */
5482 break;
5484 case TCFG_WORK_AREA_SIZE:
5485 if (goi->isconfigure) {
5486 target_free_all_working_areas(target);
5487 e = jim_getopt_wide(goi, &w);
5488 if (e != JIM_OK)
5489 return e;
5490 target->working_area_size = w;
5491 } else {
5492 if (goi->argc != 0)
5493 goto no_params;
5495 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
5496 /* loop for more */
5497 break;
5499 case TCFG_WORK_AREA_BACKUP:
5500 if (goi->isconfigure) {
5501 target_free_all_working_areas(target);
5502 e = jim_getopt_wide(goi, &w);
5503 if (e != JIM_OK)
5504 return e;
5505 /* make this exactly 1 or 0 */
5506 target->backup_working_area = (!!w);
5507 } else {
5508 if (goi->argc != 0)
5509 goto no_params;
5511 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
5512 /* loop for more e*/
5513 break;
5516 case TCFG_ENDIAN:
5517 if (goi->isconfigure) {
5518 e = jim_getopt_nvp(goi, nvp_target_endian, &n);
5519 if (e != JIM_OK) {
5520 jim_getopt_nvp_unknown(goi, nvp_target_endian, 1);
5521 return e;
5523 target->endianness = n->value;
5524 } else {
5525 if (goi->argc != 0)
5526 goto no_params;
5528 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5529 if (!n->name) {
5530 target->endianness = TARGET_LITTLE_ENDIAN;
5531 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5533 Jim_SetResultString(goi->interp, n->name, -1);
5534 /* loop for more */
5535 break;
5537 case TCFG_COREID:
5538 if (goi->isconfigure) {
5539 e = jim_getopt_wide(goi, &w);
5540 if (e != JIM_OK)
5541 return e;
5542 target->coreid = (int32_t)w;
5543 } else {
5544 if (goi->argc != 0)
5545 goto no_params;
5547 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->coreid));
5548 /* loop for more */
5549 break;
5551 case TCFG_CHAIN_POSITION:
5552 if (goi->isconfigure) {
5553 Jim_Obj *o_t;
5554 struct jtag_tap *tap;
5556 if (target->has_dap) {
5557 Jim_SetResultString(goi->interp,
5558 "target requires -dap parameter instead of -chain-position!", -1);
5559 return JIM_ERR;
5562 target_free_all_working_areas(target);
5563 e = jim_getopt_obj(goi, &o_t);
5564 if (e != JIM_OK)
5565 return e;
5566 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
5567 if (!tap)
5568 return JIM_ERR;
5569 target->tap = tap;
5570 target->tap_configured = true;
5571 } else {
5572 if (goi->argc != 0)
5573 goto no_params;
5575 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
5576 /* loop for more e*/
5577 break;
5578 case TCFG_DBGBASE:
5579 if (goi->isconfigure) {
5580 e = jim_getopt_wide(goi, &w);
5581 if (e != JIM_OK)
5582 return e;
5583 target->dbgbase = (uint32_t)w;
5584 target->dbgbase_set = true;
5585 } else {
5586 if (goi->argc != 0)
5587 goto no_params;
5589 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
5590 /* loop for more */
5591 break;
5592 case TCFG_RTOS:
5593 /* RTOS */
5595 int result = rtos_create(goi, target);
5596 if (result != JIM_OK)
5597 return result;
5599 /* loop for more */
5600 break;
5602 case TCFG_DEFER_EXAMINE:
5603 /* DEFER_EXAMINE */
5604 target->defer_examine = true;
5605 /* loop for more */
5606 break;
5608 case TCFG_GDB_PORT:
5609 if (goi->isconfigure) {
5610 struct command_context *cmd_ctx = current_command_context(goi->interp);
5611 if (cmd_ctx->mode != COMMAND_CONFIG) {
5612 Jim_SetResultString(goi->interp, "-gdb-port must be configured before 'init'", -1);
5613 return JIM_ERR;
5616 const char *s;
5617 e = jim_getopt_string(goi, &s, NULL);
5618 if (e != JIM_OK)
5619 return e;
5620 free(target->gdb_port_override);
5621 target->gdb_port_override = strdup(s);
5622 } else {
5623 if (goi->argc != 0)
5624 goto no_params;
5626 Jim_SetResultString(goi->interp, target->gdb_port_override ? target->gdb_port_override : "undefined", -1);
5627 /* loop for more */
5628 break;
5630 case TCFG_GDB_MAX_CONNECTIONS:
5631 if (goi->isconfigure) {
5632 struct command_context *cmd_ctx = current_command_context(goi->interp);
5633 if (cmd_ctx->mode != COMMAND_CONFIG) {
5634 Jim_SetResultString(goi->interp, "-gdb-max-connections must be configured before 'init'", -1);
5635 return JIM_ERR;
5638 e = jim_getopt_wide(goi, &w);
5639 if (e != JIM_OK)
5640 return e;
5641 target->gdb_max_connections = (w < 0) ? CONNECTION_LIMIT_UNLIMITED : (int)w;
5642 } else {
5643 if (goi->argc != 0)
5644 goto no_params;
5646 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->gdb_max_connections));
5647 break;
5649 } /* while (goi->argc) */
5652 /* done - we return */
5653 return JIM_OK;
5656 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5658 struct command *c = jim_to_command(interp);
5659 struct jim_getopt_info goi;
5661 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5662 goi.isconfigure = !strcmp(c->name, "configure");
5663 if (goi.argc < 1) {
5664 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5665 "missing: -option ...");
5666 return JIM_ERR;
5668 struct command_context *cmd_ctx = current_command_context(interp);
5669 assert(cmd_ctx);
5670 struct target *target = get_current_target(cmd_ctx);
5671 return target_configure(&goi, target);
5674 static int jim_target_mem2array(Jim_Interp *interp,
5675 int argc, Jim_Obj *const *argv)
5677 struct command_context *cmd_ctx = current_command_context(interp);
5678 assert(cmd_ctx);
5679 struct target *target = get_current_target(cmd_ctx);
5680 return target_mem2array(interp, target, argc - 1, argv + 1);
5683 static int jim_target_array2mem(Jim_Interp *interp,
5684 int argc, Jim_Obj *const *argv)
5686 struct command_context *cmd_ctx = current_command_context(interp);
5687 assert(cmd_ctx);
5688 struct target *target = get_current_target(cmd_ctx);
5689 return target_array2mem(interp, target, argc - 1, argv + 1);
5692 static int jim_target_tap_disabled(Jim_Interp *interp)
5694 Jim_SetResultFormatted(interp, "[TAP is disabled]");
5695 return JIM_ERR;
5698 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5700 bool allow_defer = false;
5702 struct jim_getopt_info goi;
5703 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5704 if (goi.argc > 1) {
5705 const char *cmd_name = Jim_GetString(argv[0], NULL);
5706 Jim_SetResultFormatted(goi.interp,
5707 "usage: %s ['allow-defer']", cmd_name);
5708 return JIM_ERR;
5710 if (goi.argc > 0 &&
5711 strcmp(Jim_GetString(argv[1], NULL), "allow-defer") == 0) {
5712 /* consume it */
5713 Jim_Obj *obj;
5714 int e = jim_getopt_obj(&goi, &obj);
5715 if (e != JIM_OK)
5716 return e;
5717 allow_defer = true;
5720 struct command_context *cmd_ctx = current_command_context(interp);
5721 assert(cmd_ctx);
5722 struct target *target = get_current_target(cmd_ctx);
5723 if (!target->tap->enabled)
5724 return jim_target_tap_disabled(interp);
5726 if (allow_defer && target->defer_examine) {
5727 LOG_INFO("Deferring arp_examine of %s", target_name(target));
5728 LOG_INFO("Use arp_examine command to examine it manually!");
5729 return JIM_OK;
5732 int e = target->type->examine(target);
5733 if (e != ERROR_OK) {
5734 target_reset_examined(target);
5735 return JIM_ERR;
5738 target_set_examined(target);
5740 return JIM_OK;
5743 static int jim_target_was_examined(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5745 struct command_context *cmd_ctx = current_command_context(interp);
5746 assert(cmd_ctx);
5747 struct target *target = get_current_target(cmd_ctx);
5749 Jim_SetResultBool(interp, target_was_examined(target));
5750 return JIM_OK;
5753 static int jim_target_examine_deferred(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5755 struct command_context *cmd_ctx = current_command_context(interp);
5756 assert(cmd_ctx);
5757 struct target *target = get_current_target(cmd_ctx);
5759 Jim_SetResultBool(interp, target->defer_examine);
5760 return JIM_OK;
5763 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5765 if (argc != 1) {
5766 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5767 return JIM_ERR;
5769 struct command_context *cmd_ctx = current_command_context(interp);
5770 assert(cmd_ctx);
5771 struct target *target = get_current_target(cmd_ctx);
5773 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
5774 return JIM_ERR;
5776 return JIM_OK;
5779 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5781 if (argc != 1) {
5782 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5783 return JIM_ERR;
5785 struct command_context *cmd_ctx = current_command_context(interp);
5786 assert(cmd_ctx);
5787 struct target *target = get_current_target(cmd_ctx);
5788 if (!target->tap->enabled)
5789 return jim_target_tap_disabled(interp);
5791 int e;
5792 if (!(target_was_examined(target)))
5793 e = ERROR_TARGET_NOT_EXAMINED;
5794 else
5795 e = target->type->poll(target);
5796 if (e != ERROR_OK)
5797 return JIM_ERR;
5798 return JIM_OK;
5801 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5803 struct jim_getopt_info goi;
5804 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5806 if (goi.argc != 2) {
5807 Jim_WrongNumArgs(interp, 0, argv,
5808 "([tT]|[fF]|assert|deassert) BOOL");
5809 return JIM_ERR;
5812 struct jim_nvp *n;
5813 int e = jim_getopt_nvp(&goi, nvp_assert, &n);
5814 if (e != JIM_OK) {
5815 jim_getopt_nvp_unknown(&goi, nvp_assert, 1);
5816 return e;
5818 /* the halt or not param */
5819 jim_wide a;
5820 e = jim_getopt_wide(&goi, &a);
5821 if (e != JIM_OK)
5822 return e;
5824 struct command_context *cmd_ctx = current_command_context(interp);
5825 assert(cmd_ctx);
5826 struct target *target = get_current_target(cmd_ctx);
5827 if (!target->tap->enabled)
5828 return jim_target_tap_disabled(interp);
5830 if (!target->type->assert_reset || !target->type->deassert_reset) {
5831 Jim_SetResultFormatted(interp,
5832 "No target-specific reset for %s",
5833 target_name(target));
5834 return JIM_ERR;
5837 if (target->defer_examine)
5838 target_reset_examined(target);
5840 /* determine if we should halt or not. */
5841 target->reset_halt = (a != 0);
5842 /* When this happens - all workareas are invalid. */
5843 target_free_all_working_areas_restore(target, 0);
5845 /* do the assert */
5846 if (n->value == NVP_ASSERT)
5847 e = target->type->assert_reset(target);
5848 else
5849 e = target->type->deassert_reset(target);
5850 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5853 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5855 if (argc != 1) {
5856 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5857 return JIM_ERR;
5859 struct command_context *cmd_ctx = current_command_context(interp);
5860 assert(cmd_ctx);
5861 struct target *target = get_current_target(cmd_ctx);
5862 if (!target->tap->enabled)
5863 return jim_target_tap_disabled(interp);
5864 int e = target->type->halt(target);
5865 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5868 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5870 struct jim_getopt_info goi;
5871 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5873 /* params: <name> statename timeoutmsecs */
5874 if (goi.argc != 2) {
5875 const char *cmd_name = Jim_GetString(argv[0], NULL);
5876 Jim_SetResultFormatted(goi.interp,
5877 "%s <state_name> <timeout_in_msec>", cmd_name);
5878 return JIM_ERR;
5881 struct jim_nvp *n;
5882 int e = jim_getopt_nvp(&goi, nvp_target_state, &n);
5883 if (e != JIM_OK) {
5884 jim_getopt_nvp_unknown(&goi, nvp_target_state, 1);
5885 return e;
5887 jim_wide a;
5888 e = jim_getopt_wide(&goi, &a);
5889 if (e != JIM_OK)
5890 return e;
5891 struct command_context *cmd_ctx = current_command_context(interp);
5892 assert(cmd_ctx);
5893 struct target *target = get_current_target(cmd_ctx);
5894 if (!target->tap->enabled)
5895 return jim_target_tap_disabled(interp);
5897 e = target_wait_state(target, n->value, a);
5898 if (e != ERROR_OK) {
5899 Jim_Obj *obj = Jim_NewIntObj(interp, e);
5900 Jim_SetResultFormatted(goi.interp,
5901 "target: %s wait %s fails (%#s) %s",
5902 target_name(target), n->name,
5903 obj, target_strerror_safe(e));
5904 return JIM_ERR;
5906 return JIM_OK;
5908 /* List for human, Events defined for this target.
5909 * scripts/programs should use 'name cget -event NAME'
5911 COMMAND_HANDLER(handle_target_event_list)
5913 struct target *target = get_current_target(CMD_CTX);
5914 struct target_event_action *teap = target->event_action;
5916 command_print(CMD, "Event actions for target (%d) %s\n",
5917 target->target_number,
5918 target_name(target));
5919 command_print(CMD, "%-25s | Body", "Event");
5920 command_print(CMD, "------------------------- | "
5921 "----------------------------------------");
5922 while (teap) {
5923 command_print(CMD, "%-25s | %s",
5924 target_event_name(teap->event),
5925 Jim_GetString(teap->body, NULL));
5926 teap = teap->next;
5928 command_print(CMD, "***END***");
5929 return ERROR_OK;
5931 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5933 if (argc != 1) {
5934 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5935 return JIM_ERR;
5937 struct command_context *cmd_ctx = current_command_context(interp);
5938 assert(cmd_ctx);
5939 struct target *target = get_current_target(cmd_ctx);
5940 Jim_SetResultString(interp, target_state_name(target), -1);
5941 return JIM_OK;
5943 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5945 struct jim_getopt_info goi;
5946 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5947 if (goi.argc != 1) {
5948 const char *cmd_name = Jim_GetString(argv[0], NULL);
5949 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5950 return JIM_ERR;
5952 struct jim_nvp *n;
5953 int e = jim_getopt_nvp(&goi, nvp_target_event, &n);
5954 if (e != JIM_OK) {
5955 jim_getopt_nvp_unknown(&goi, nvp_target_event, 1);
5956 return e;
5958 struct command_context *cmd_ctx = current_command_context(interp);
5959 assert(cmd_ctx);
5960 struct target *target = get_current_target(cmd_ctx);
5961 target_handle_event(target, n->value);
5962 return JIM_OK;
5965 static const struct command_registration target_instance_command_handlers[] = {
5967 .name = "configure",
5968 .mode = COMMAND_ANY,
5969 .jim_handler = jim_target_configure,
5970 .help = "configure a new target for use",
5971 .usage = "[target_attribute ...]",
5974 .name = "cget",
5975 .mode = COMMAND_ANY,
5976 .jim_handler = jim_target_configure,
5977 .help = "returns the specified target attribute",
5978 .usage = "target_attribute",
5981 .name = "mwd",
5982 .handler = handle_mw_command,
5983 .mode = COMMAND_EXEC,
5984 .help = "Write 64-bit word(s) to target memory",
5985 .usage = "address data [count]",
5988 .name = "mww",
5989 .handler = handle_mw_command,
5990 .mode = COMMAND_EXEC,
5991 .help = "Write 32-bit word(s) to target memory",
5992 .usage = "address data [count]",
5995 .name = "mwh",
5996 .handler = handle_mw_command,
5997 .mode = COMMAND_EXEC,
5998 .help = "Write 16-bit half-word(s) to target memory",
5999 .usage = "address data [count]",
6002 .name = "mwb",
6003 .handler = handle_mw_command,
6004 .mode = COMMAND_EXEC,
6005 .help = "Write byte(s) to target memory",
6006 .usage = "address data [count]",
6009 .name = "mdd",
6010 .handler = handle_md_command,
6011 .mode = COMMAND_EXEC,
6012 .help = "Display target memory as 64-bit words",
6013 .usage = "address [count]",
6016 .name = "mdw",
6017 .handler = handle_md_command,
6018 .mode = COMMAND_EXEC,
6019 .help = "Display target memory as 32-bit words",
6020 .usage = "address [count]",
6023 .name = "mdh",
6024 .handler = handle_md_command,
6025 .mode = COMMAND_EXEC,
6026 .help = "Display target memory as 16-bit half-words",
6027 .usage = "address [count]",
6030 .name = "mdb",
6031 .handler = handle_md_command,
6032 .mode = COMMAND_EXEC,
6033 .help = "Display target memory as 8-bit bytes",
6034 .usage = "address [count]",
6037 .name = "array2mem",
6038 .mode = COMMAND_EXEC,
6039 .jim_handler = jim_target_array2mem,
6040 .help = "Writes Tcl array of 8/16/32 bit numbers "
6041 "to target memory",
6042 .usage = "arrayname bitwidth address count",
6045 .name = "mem2array",
6046 .mode = COMMAND_EXEC,
6047 .jim_handler = jim_target_mem2array,
6048 .help = "Loads Tcl array of 8/16/32 bit numbers "
6049 "from target memory",
6050 .usage = "arrayname bitwidth address count",
6053 .name = "get_reg",
6054 .mode = COMMAND_EXEC,
6055 .jim_handler = target_jim_get_reg,
6056 .help = "Get register values from the target",
6057 .usage = "list",
6060 .name = "set_reg",
6061 .mode = COMMAND_EXEC,
6062 .jim_handler = target_jim_set_reg,
6063 .help = "Set target register values",
6064 .usage = "dict",
6067 .name = "read_memory",
6068 .mode = COMMAND_EXEC,
6069 .jim_handler = target_jim_read_memory,
6070 .help = "Read Tcl list of 8/16/32/64 bit numbers from target memory",
6071 .usage = "address width count ['phys']",
6074 .name = "write_memory",
6075 .mode = COMMAND_EXEC,
6076 .jim_handler = target_jim_write_memory,
6077 .help = "Write Tcl list of 8/16/32/64 bit numbers to target memory",
6078 .usage = "address width data ['phys']",
6081 .name = "eventlist",
6082 .handler = handle_target_event_list,
6083 .mode = COMMAND_EXEC,
6084 .help = "displays a table of events defined for this target",
6085 .usage = "",
6088 .name = "curstate",
6089 .mode = COMMAND_EXEC,
6090 .jim_handler = jim_target_current_state,
6091 .help = "displays the current state of this target",
6094 .name = "arp_examine",
6095 .mode = COMMAND_EXEC,
6096 .jim_handler = jim_target_examine,
6097 .help = "used internally for reset processing",
6098 .usage = "['allow-defer']",
6101 .name = "was_examined",
6102 .mode = COMMAND_EXEC,
6103 .jim_handler = jim_target_was_examined,
6104 .help = "used internally for reset processing",
6107 .name = "examine_deferred",
6108 .mode = COMMAND_EXEC,
6109 .jim_handler = jim_target_examine_deferred,
6110 .help = "used internally for reset processing",
6113 .name = "arp_halt_gdb",
6114 .mode = COMMAND_EXEC,
6115 .jim_handler = jim_target_halt_gdb,
6116 .help = "used internally for reset processing to halt GDB",
6119 .name = "arp_poll",
6120 .mode = COMMAND_EXEC,
6121 .jim_handler = jim_target_poll,
6122 .help = "used internally for reset processing",
6125 .name = "arp_reset",
6126 .mode = COMMAND_EXEC,
6127 .jim_handler = jim_target_reset,
6128 .help = "used internally for reset processing",
6131 .name = "arp_halt",
6132 .mode = COMMAND_EXEC,
6133 .jim_handler = jim_target_halt,
6134 .help = "used internally for reset processing",
6137 .name = "arp_waitstate",
6138 .mode = COMMAND_EXEC,
6139 .jim_handler = jim_target_wait_state,
6140 .help = "used internally for reset processing",
6143 .name = "invoke-event",
6144 .mode = COMMAND_EXEC,
6145 .jim_handler = jim_target_invoke_event,
6146 .help = "invoke handler for specified event",
6147 .usage = "event_name",
6149 COMMAND_REGISTRATION_DONE
6152 static int target_create(struct jim_getopt_info *goi)
6154 Jim_Obj *new_cmd;
6155 Jim_Cmd *cmd;
6156 const char *cp;
6157 int e;
6158 int x;
6159 struct target *target;
6160 struct command_context *cmd_ctx;
6162 cmd_ctx = current_command_context(goi->interp);
6163 assert(cmd_ctx);
6165 if (goi->argc < 3) {
6166 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
6167 return JIM_ERR;
6170 /* COMMAND */
6171 jim_getopt_obj(goi, &new_cmd);
6172 /* does this command exist? */
6173 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_NONE);
6174 if (cmd) {
6175 cp = Jim_GetString(new_cmd, NULL);
6176 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
6177 return JIM_ERR;
6180 /* TYPE */
6181 e = jim_getopt_string(goi, &cp, NULL);
6182 if (e != JIM_OK)
6183 return e;
6184 struct transport *tr = get_current_transport();
6185 if (tr->override_target) {
6186 e = tr->override_target(&cp);
6187 if (e != ERROR_OK) {
6188 LOG_ERROR("The selected transport doesn't support this target");
6189 return JIM_ERR;
6191 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
6193 /* now does target type exist */
6194 for (x = 0 ; target_types[x] ; x++) {
6195 if (strcmp(cp, target_types[x]->name) == 0) {
6196 /* found */
6197 break;
6200 if (!target_types[x]) {
6201 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
6202 for (x = 0 ; target_types[x] ; x++) {
6203 if (target_types[x + 1]) {
6204 Jim_AppendStrings(goi->interp,
6205 Jim_GetResult(goi->interp),
6206 target_types[x]->name,
6207 ", ", NULL);
6208 } else {
6209 Jim_AppendStrings(goi->interp,
6210 Jim_GetResult(goi->interp),
6211 " or ",
6212 target_types[x]->name, NULL);
6215 return JIM_ERR;
6218 /* Create it */
6219 target = calloc(1, sizeof(struct target));
6220 if (!target) {
6221 LOG_ERROR("Out of memory");
6222 return JIM_ERR;
6225 /* set empty smp cluster */
6226 target->smp_targets = &empty_smp_targets;
6228 /* set target number */
6229 target->target_number = new_target_number();
6231 /* allocate memory for each unique target type */
6232 target->type = malloc(sizeof(struct target_type));
6233 if (!target->type) {
6234 LOG_ERROR("Out of memory");
6235 free(target);
6236 return JIM_ERR;
6239 memcpy(target->type, target_types[x], sizeof(struct target_type));
6241 /* default to first core, override with -coreid */
6242 target->coreid = 0;
6244 target->working_area = 0x0;
6245 target->working_area_size = 0x0;
6246 target->working_areas = NULL;
6247 target->backup_working_area = 0;
6249 target->state = TARGET_UNKNOWN;
6250 target->debug_reason = DBG_REASON_UNDEFINED;
6251 target->reg_cache = NULL;
6252 target->breakpoints = NULL;
6253 target->watchpoints = NULL;
6254 target->next = NULL;
6255 target->arch_info = NULL;
6257 target->verbose_halt_msg = true;
6259 target->halt_issued = false;
6261 /* initialize trace information */
6262 target->trace_info = calloc(1, sizeof(struct trace));
6263 if (!target->trace_info) {
6264 LOG_ERROR("Out of memory");
6265 free(target->type);
6266 free(target);
6267 return JIM_ERR;
6270 target->dbgmsg = NULL;
6271 target->dbg_msg_enabled = 0;
6273 target->endianness = TARGET_ENDIAN_UNKNOWN;
6275 target->rtos = NULL;
6276 target->rtos_auto_detect = false;
6278 target->gdb_port_override = NULL;
6279 target->gdb_max_connections = 1;
6281 /* Do the rest as "configure" options */
6282 goi->isconfigure = 1;
6283 e = target_configure(goi, target);
6285 if (e == JIM_OK) {
6286 if (target->has_dap) {
6287 if (!target->dap_configured) {
6288 Jim_SetResultString(goi->interp, "-dap ?name? required when creating target", -1);
6289 e = JIM_ERR;
6291 } else {
6292 if (!target->tap_configured) {
6293 Jim_SetResultString(goi->interp, "-chain-position ?name? required when creating target", -1);
6294 e = JIM_ERR;
6297 /* tap must be set after target was configured */
6298 if (!target->tap)
6299 e = JIM_ERR;
6302 if (e != JIM_OK) {
6303 rtos_destroy(target);
6304 free(target->gdb_port_override);
6305 free(target->trace_info);
6306 free(target->type);
6307 free(target);
6308 return e;
6311 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
6312 /* default endian to little if not specified */
6313 target->endianness = TARGET_LITTLE_ENDIAN;
6316 cp = Jim_GetString(new_cmd, NULL);
6317 target->cmd_name = strdup(cp);
6318 if (!target->cmd_name) {
6319 LOG_ERROR("Out of memory");
6320 rtos_destroy(target);
6321 free(target->gdb_port_override);
6322 free(target->trace_info);
6323 free(target->type);
6324 free(target);
6325 return JIM_ERR;
6328 if (target->type->target_create) {
6329 e = (*(target->type->target_create))(target, goi->interp);
6330 if (e != ERROR_OK) {
6331 LOG_DEBUG("target_create failed");
6332 free(target->cmd_name);
6333 rtos_destroy(target);
6334 free(target->gdb_port_override);
6335 free(target->trace_info);
6336 free(target->type);
6337 free(target);
6338 return JIM_ERR;
6342 /* create the target specific commands */
6343 if (target->type->commands) {
6344 e = register_commands(cmd_ctx, NULL, target->type->commands);
6345 if (e != ERROR_OK)
6346 LOG_ERROR("unable to register '%s' commands", cp);
6349 /* now - create the new target name command */
6350 const struct command_registration target_subcommands[] = {
6352 .chain = target_instance_command_handlers,
6355 .chain = target->type->commands,
6357 COMMAND_REGISTRATION_DONE
6359 const struct command_registration target_commands[] = {
6361 .name = cp,
6362 .mode = COMMAND_ANY,
6363 .help = "target command group",
6364 .usage = "",
6365 .chain = target_subcommands,
6367 COMMAND_REGISTRATION_DONE
6369 e = register_commands_override_target(cmd_ctx, NULL, target_commands, target);
6370 if (e != ERROR_OK) {
6371 if (target->type->deinit_target)
6372 target->type->deinit_target(target);
6373 free(target->cmd_name);
6374 rtos_destroy(target);
6375 free(target->gdb_port_override);
6376 free(target->trace_info);
6377 free(target->type);
6378 free(target);
6379 return JIM_ERR;
6382 /* append to end of list */
6383 append_to_list_all_targets(target);
6385 cmd_ctx->current_target = target;
6386 return JIM_OK;
6389 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6391 if (argc != 1) {
6392 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
6393 return JIM_ERR;
6395 struct command_context *cmd_ctx = current_command_context(interp);
6396 assert(cmd_ctx);
6398 struct target *target = get_current_target_or_null(cmd_ctx);
6399 if (target)
6400 Jim_SetResultString(interp, target_name(target), -1);
6401 return JIM_OK;
6404 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6406 if (argc != 1) {
6407 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
6408 return JIM_ERR;
6410 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
6411 for (unsigned x = 0; target_types[x]; x++) {
6412 Jim_ListAppendElement(interp, Jim_GetResult(interp),
6413 Jim_NewStringObj(interp, target_types[x]->name, -1));
6415 return JIM_OK;
6418 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6420 if (argc != 1) {
6421 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
6422 return JIM_ERR;
6424 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
6425 struct target *target = all_targets;
6426 while (target) {
6427 Jim_ListAppendElement(interp, Jim_GetResult(interp),
6428 Jim_NewStringObj(interp, target_name(target), -1));
6429 target = target->next;
6431 return JIM_OK;
6434 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6436 int i;
6437 const char *targetname;
6438 int retval, len;
6439 static int smp_group = 1;
6440 struct target *target = NULL;
6441 struct target_list *head, *new;
6443 retval = 0;
6444 LOG_DEBUG("%d", argc);
6445 /* argv[1] = target to associate in smp
6446 * argv[2] = target to associate in smp
6447 * argv[3] ...
6450 struct list_head *lh = malloc(sizeof(*lh));
6451 if (!lh) {
6452 LOG_ERROR("Out of memory");
6453 return JIM_ERR;
6455 INIT_LIST_HEAD(lh);
6457 for (i = 1; i < argc; i++) {
6459 targetname = Jim_GetString(argv[i], &len);
6460 target = get_target(targetname);
6461 LOG_DEBUG("%s ", targetname);
6462 if (target) {
6463 new = malloc(sizeof(struct target_list));
6464 new->target = target;
6465 list_add_tail(&new->lh, lh);
6468 /* now parse the list of cpu and put the target in smp mode*/
6469 foreach_smp_target(head, lh) {
6470 target = head->target;
6471 target->smp = smp_group;
6472 target->smp_targets = lh;
6474 smp_group++;
6476 if (target && target->rtos)
6477 retval = rtos_smp_init(target);
6479 return retval;
6483 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6485 struct jim_getopt_info goi;
6486 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
6487 if (goi.argc < 3) {
6488 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
6489 "<name> <target_type> [<target_options> ...]");
6490 return JIM_ERR;
6492 return target_create(&goi);
6495 static const struct command_registration target_subcommand_handlers[] = {
6497 .name = "init",
6498 .mode = COMMAND_CONFIG,
6499 .handler = handle_target_init_command,
6500 .help = "initialize targets",
6501 .usage = "",
6504 .name = "create",
6505 .mode = COMMAND_CONFIG,
6506 .jim_handler = jim_target_create,
6507 .usage = "name type '-chain-position' name [options ...]",
6508 .help = "Creates and selects a new target",
6511 .name = "current",
6512 .mode = COMMAND_ANY,
6513 .jim_handler = jim_target_current,
6514 .help = "Returns the currently selected target",
6517 .name = "types",
6518 .mode = COMMAND_ANY,
6519 .jim_handler = jim_target_types,
6520 .help = "Returns the available target types as "
6521 "a list of strings",
6524 .name = "names",
6525 .mode = COMMAND_ANY,
6526 .jim_handler = jim_target_names,
6527 .help = "Returns the names of all targets as a list of strings",
6530 .name = "smp",
6531 .mode = COMMAND_ANY,
6532 .jim_handler = jim_target_smp,
6533 .usage = "targetname1 targetname2 ...",
6534 .help = "gather several target in a smp list"
6537 COMMAND_REGISTRATION_DONE
6540 struct fast_load {
6541 target_addr_t address;
6542 uint8_t *data;
6543 int length;
6547 static int fastload_num;
6548 static struct fast_load *fastload;
6550 static void free_fastload(void)
6552 if (fastload) {
6553 for (int i = 0; i < fastload_num; i++)
6554 free(fastload[i].data);
6555 free(fastload);
6556 fastload = NULL;
6560 COMMAND_HANDLER(handle_fast_load_image_command)
6562 uint8_t *buffer;
6563 size_t buf_cnt;
6564 uint32_t image_size;
6565 target_addr_t min_address = 0;
6566 target_addr_t max_address = -1;
6568 struct image image;
6570 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
6571 &image, &min_address, &max_address);
6572 if (retval != ERROR_OK)
6573 return retval;
6575 struct duration bench;
6576 duration_start(&bench);
6578 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
6579 if (retval != ERROR_OK)
6580 return retval;
6582 image_size = 0x0;
6583 retval = ERROR_OK;
6584 fastload_num = image.num_sections;
6585 fastload = malloc(sizeof(struct fast_load)*image.num_sections);
6586 if (!fastload) {
6587 command_print(CMD, "out of memory");
6588 image_close(&image);
6589 return ERROR_FAIL;
6591 memset(fastload, 0, sizeof(struct fast_load)*image.num_sections);
6592 for (unsigned int i = 0; i < image.num_sections; i++) {
6593 buffer = malloc(image.sections[i].size);
6594 if (!buffer) {
6595 command_print(CMD, "error allocating buffer for section (%d bytes)",
6596 (int)(image.sections[i].size));
6597 retval = ERROR_FAIL;
6598 break;
6601 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
6602 if (retval != ERROR_OK) {
6603 free(buffer);
6604 break;
6607 uint32_t offset = 0;
6608 uint32_t length = buf_cnt;
6610 /* DANGER!!! beware of unsigned comparison here!!! */
6612 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
6613 (image.sections[i].base_address < max_address)) {
6614 if (image.sections[i].base_address < min_address) {
6615 /* clip addresses below */
6616 offset += min_address-image.sections[i].base_address;
6617 length -= offset;
6620 if (image.sections[i].base_address + buf_cnt > max_address)
6621 length -= (image.sections[i].base_address + buf_cnt)-max_address;
6623 fastload[i].address = image.sections[i].base_address + offset;
6624 fastload[i].data = malloc(length);
6625 if (!fastload[i].data) {
6626 free(buffer);
6627 command_print(CMD, "error allocating buffer for section (%" PRIu32 " bytes)",
6628 length);
6629 retval = ERROR_FAIL;
6630 break;
6632 memcpy(fastload[i].data, buffer + offset, length);
6633 fastload[i].length = length;
6635 image_size += length;
6636 command_print(CMD, "%u bytes written at address 0x%8.8x",
6637 (unsigned int)length,
6638 ((unsigned int)(image.sections[i].base_address + offset)));
6641 free(buffer);
6644 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
6645 command_print(CMD, "Loaded %" PRIu32 " bytes "
6646 "in %fs (%0.3f KiB/s)", image_size,
6647 duration_elapsed(&bench), duration_kbps(&bench, image_size));
6649 command_print(CMD,
6650 "WARNING: image has not been loaded to target!"
6651 "You can issue a 'fast_load' to finish loading.");
6654 image_close(&image);
6656 if (retval != ERROR_OK)
6657 free_fastload();
6659 return retval;
6662 COMMAND_HANDLER(handle_fast_load_command)
6664 if (CMD_ARGC > 0)
6665 return ERROR_COMMAND_SYNTAX_ERROR;
6666 if (!fastload) {
6667 LOG_ERROR("No image in memory");
6668 return ERROR_FAIL;
6670 int i;
6671 int64_t ms = timeval_ms();
6672 int size = 0;
6673 int retval = ERROR_OK;
6674 for (i = 0; i < fastload_num; i++) {
6675 struct target *target = get_current_target(CMD_CTX);
6676 command_print(CMD, "Write to 0x%08x, length 0x%08x",
6677 (unsigned int)(fastload[i].address),
6678 (unsigned int)(fastload[i].length));
6679 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
6680 if (retval != ERROR_OK)
6681 break;
6682 size += fastload[i].length;
6684 if (retval == ERROR_OK) {
6685 int64_t after = timeval_ms();
6686 command_print(CMD, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
6688 return retval;
6691 static const struct command_registration target_command_handlers[] = {
6693 .name = "targets",
6694 .handler = handle_targets_command,
6695 .mode = COMMAND_ANY,
6696 .help = "change current default target (one parameter) "
6697 "or prints table of all targets (no parameters)",
6698 .usage = "[target]",
6701 .name = "target",
6702 .mode = COMMAND_CONFIG,
6703 .help = "configure target",
6704 .chain = target_subcommand_handlers,
6705 .usage = "",
6707 COMMAND_REGISTRATION_DONE
6710 int target_register_commands(struct command_context *cmd_ctx)
6712 return register_commands(cmd_ctx, NULL, target_command_handlers);
6715 static bool target_reset_nag = true;
6717 bool get_target_reset_nag(void)
6719 return target_reset_nag;
6722 COMMAND_HANDLER(handle_target_reset_nag)
6724 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
6725 &target_reset_nag, "Nag after each reset about options to improve "
6726 "performance");
6729 COMMAND_HANDLER(handle_ps_command)
6731 struct target *target = get_current_target(CMD_CTX);
6732 char *display;
6733 if (target->state != TARGET_HALTED) {
6734 LOG_INFO("target not halted !!");
6735 return ERROR_OK;
6738 if ((target->rtos) && (target->rtos->type)
6739 && (target->rtos->type->ps_command)) {
6740 display = target->rtos->type->ps_command(target);
6741 command_print(CMD, "%s", display);
6742 free(display);
6743 return ERROR_OK;
6744 } else {
6745 LOG_INFO("failed");
6746 return ERROR_TARGET_FAILURE;
6750 static void binprint(struct command_invocation *cmd, const char *text, const uint8_t *buf, int size)
6752 if (text)
6753 command_print_sameline(cmd, "%s", text);
6754 for (int i = 0; i < size; i++)
6755 command_print_sameline(cmd, " %02x", buf[i]);
6756 command_print(cmd, " ");
6759 COMMAND_HANDLER(handle_test_mem_access_command)
6761 struct target *target = get_current_target(CMD_CTX);
6762 uint32_t test_size;
6763 int retval = ERROR_OK;
6765 if (target->state != TARGET_HALTED) {
6766 LOG_INFO("target not halted !!");
6767 return ERROR_FAIL;
6770 if (CMD_ARGC != 1)
6771 return ERROR_COMMAND_SYNTAX_ERROR;
6773 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
6775 /* Test reads */
6776 size_t num_bytes = test_size + 4;
6778 struct working_area *wa = NULL;
6779 retval = target_alloc_working_area(target, num_bytes, &wa);
6780 if (retval != ERROR_OK) {
6781 LOG_ERROR("Not enough working area");
6782 return ERROR_FAIL;
6785 uint8_t *test_pattern = malloc(num_bytes);
6787 for (size_t i = 0; i < num_bytes; i++)
6788 test_pattern[i] = rand();
6790 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6791 if (retval != ERROR_OK) {
6792 LOG_ERROR("Test pattern write failed");
6793 goto out;
6796 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6797 for (int size = 1; size <= 4; size *= 2) {
6798 for (int offset = 0; offset < 4; offset++) {
6799 uint32_t count = test_size / size;
6800 size_t host_bufsiz = (count + 2) * size + host_offset;
6801 uint8_t *read_ref = malloc(host_bufsiz);
6802 uint8_t *read_buf = malloc(host_bufsiz);
6804 for (size_t i = 0; i < host_bufsiz; i++) {
6805 read_ref[i] = rand();
6806 read_buf[i] = read_ref[i];
6808 command_print_sameline(CMD,
6809 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
6810 size, offset, host_offset ? "un" : "");
6812 struct duration bench;
6813 duration_start(&bench);
6815 retval = target_read_memory(target, wa->address + offset, size, count,
6816 read_buf + size + host_offset);
6818 duration_measure(&bench);
6820 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6821 command_print(CMD, "Unsupported alignment");
6822 goto next;
6823 } else if (retval != ERROR_OK) {
6824 command_print(CMD, "Memory read failed");
6825 goto next;
6828 /* replay on host */
6829 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
6831 /* check result */
6832 int result = memcmp(read_ref, read_buf, host_bufsiz);
6833 if (result == 0) {
6834 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6835 duration_elapsed(&bench),
6836 duration_kbps(&bench, count * size));
6837 } else {
6838 command_print(CMD, "Compare failed");
6839 binprint(CMD, "ref:", read_ref, host_bufsiz);
6840 binprint(CMD, "buf:", read_buf, host_bufsiz);
6842 next:
6843 free(read_ref);
6844 free(read_buf);
6849 out:
6850 free(test_pattern);
6852 target_free_working_area(target, wa);
6854 /* Test writes */
6855 num_bytes = test_size + 4 + 4 + 4;
6857 retval = target_alloc_working_area(target, num_bytes, &wa);
6858 if (retval != ERROR_OK) {
6859 LOG_ERROR("Not enough working area");
6860 return ERROR_FAIL;
6863 test_pattern = malloc(num_bytes);
6865 for (size_t i = 0; i < num_bytes; i++)
6866 test_pattern[i] = rand();
6868 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6869 for (int size = 1; size <= 4; size *= 2) {
6870 for (int offset = 0; offset < 4; offset++) {
6871 uint32_t count = test_size / size;
6872 size_t host_bufsiz = count * size + host_offset;
6873 uint8_t *read_ref = malloc(num_bytes);
6874 uint8_t *read_buf = malloc(num_bytes);
6875 uint8_t *write_buf = malloc(host_bufsiz);
6877 for (size_t i = 0; i < host_bufsiz; i++)
6878 write_buf[i] = rand();
6879 command_print_sameline(CMD,
6880 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
6881 size, offset, host_offset ? "un" : "");
6883 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6884 if (retval != ERROR_OK) {
6885 command_print(CMD, "Test pattern write failed");
6886 goto nextw;
6889 /* replay on host */
6890 memcpy(read_ref, test_pattern, num_bytes);
6891 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
6893 struct duration bench;
6894 duration_start(&bench);
6896 retval = target_write_memory(target, wa->address + size + offset, size, count,
6897 write_buf + host_offset);
6899 duration_measure(&bench);
6901 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6902 command_print(CMD, "Unsupported alignment");
6903 goto nextw;
6904 } else if (retval != ERROR_OK) {
6905 command_print(CMD, "Memory write failed");
6906 goto nextw;
6909 /* read back */
6910 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
6911 if (retval != ERROR_OK) {
6912 command_print(CMD, "Test pattern write failed");
6913 goto nextw;
6916 /* check result */
6917 int result = memcmp(read_ref, read_buf, num_bytes);
6918 if (result == 0) {
6919 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6920 duration_elapsed(&bench),
6921 duration_kbps(&bench, count * size));
6922 } else {
6923 command_print(CMD, "Compare failed");
6924 binprint(CMD, "ref:", read_ref, num_bytes);
6925 binprint(CMD, "buf:", read_buf, num_bytes);
6927 nextw:
6928 free(read_ref);
6929 free(read_buf);
6934 free(test_pattern);
6936 target_free_working_area(target, wa);
6937 return retval;
6940 static const struct command_registration target_exec_command_handlers[] = {
6942 .name = "fast_load_image",
6943 .handler = handle_fast_load_image_command,
6944 .mode = COMMAND_ANY,
6945 .help = "Load image into server memory for later use by "
6946 "fast_load; primarily for profiling",
6947 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6948 "[min_address [max_length]]",
6951 .name = "fast_load",
6952 .handler = handle_fast_load_command,
6953 .mode = COMMAND_EXEC,
6954 .help = "loads active fast load image to current target "
6955 "- mainly for profiling purposes",
6956 .usage = "",
6959 .name = "profile",
6960 .handler = handle_profile_command,
6961 .mode = COMMAND_EXEC,
6962 .usage = "seconds filename [start end]",
6963 .help = "profiling samples the CPU PC",
6965 /** @todo don't register virt2phys() unless target supports it */
6967 .name = "virt2phys",
6968 .handler = handle_virt2phys_command,
6969 .mode = COMMAND_ANY,
6970 .help = "translate a virtual address into a physical address",
6971 .usage = "virtual_address",
6974 .name = "reg",
6975 .handler = handle_reg_command,
6976 .mode = COMMAND_EXEC,
6977 .help = "display (reread from target with \"force\") or set a register; "
6978 "with no arguments, displays all registers and their values",
6979 .usage = "[(register_number|register_name) [(value|'force')]]",
6982 .name = "poll",
6983 .handler = handle_poll_command,
6984 .mode = COMMAND_EXEC,
6985 .help = "poll target state; or reconfigure background polling",
6986 .usage = "['on'|'off']",
6989 .name = "wait_halt",
6990 .handler = handle_wait_halt_command,
6991 .mode = COMMAND_EXEC,
6992 .help = "wait up to the specified number of milliseconds "
6993 "(default 5000) for a previously requested halt",
6994 .usage = "[milliseconds]",
6997 .name = "halt",
6998 .handler = handle_halt_command,
6999 .mode = COMMAND_EXEC,
7000 .help = "request target to halt, then wait up to the specified "
7001 "number of milliseconds (default 5000) for it to complete",
7002 .usage = "[milliseconds]",
7005 .name = "resume",
7006 .handler = handle_resume_command,
7007 .mode = COMMAND_EXEC,
7008 .help = "resume target execution from current PC or address",
7009 .usage = "[address]",
7012 .name = "reset",
7013 .handler = handle_reset_command,
7014 .mode = COMMAND_EXEC,
7015 .usage = "[run|halt|init]",
7016 .help = "Reset all targets into the specified mode. "
7017 "Default reset mode is run, if not given.",
7020 .name = "soft_reset_halt",
7021 .handler = handle_soft_reset_halt_command,
7022 .mode = COMMAND_EXEC,
7023 .usage = "",
7024 .help = "halt the target and do a soft reset",
7027 .name = "step",
7028 .handler = handle_step_command,
7029 .mode = COMMAND_EXEC,
7030 .help = "step one instruction from current PC or address",
7031 .usage = "[address]",
7034 .name = "mdd",
7035 .handler = handle_md_command,
7036 .mode = COMMAND_EXEC,
7037 .help = "display memory double-words",
7038 .usage = "['phys'] address [count]",
7041 .name = "mdw",
7042 .handler = handle_md_command,
7043 .mode = COMMAND_EXEC,
7044 .help = "display memory words",
7045 .usage = "['phys'] address [count]",
7048 .name = "mdh",
7049 .handler = handle_md_command,
7050 .mode = COMMAND_EXEC,
7051 .help = "display memory half-words",
7052 .usage = "['phys'] address [count]",
7055 .name = "mdb",
7056 .handler = handle_md_command,
7057 .mode = COMMAND_EXEC,
7058 .help = "display memory bytes",
7059 .usage = "['phys'] address [count]",
7062 .name = "mwd",
7063 .handler = handle_mw_command,
7064 .mode = COMMAND_EXEC,
7065 .help = "write memory double-word",
7066 .usage = "['phys'] address value [count]",
7069 .name = "mww",
7070 .handler = handle_mw_command,
7071 .mode = COMMAND_EXEC,
7072 .help = "write memory word",
7073 .usage = "['phys'] address value [count]",
7076 .name = "mwh",
7077 .handler = handle_mw_command,
7078 .mode = COMMAND_EXEC,
7079 .help = "write memory half-word",
7080 .usage = "['phys'] address value [count]",
7083 .name = "mwb",
7084 .handler = handle_mw_command,
7085 .mode = COMMAND_EXEC,
7086 .help = "write memory byte",
7087 .usage = "['phys'] address value [count]",
7090 .name = "bp",
7091 .handler = handle_bp_command,
7092 .mode = COMMAND_EXEC,
7093 .help = "list or set hardware or software breakpoint",
7094 .usage = "[<address> [<asid>] <length> ['hw'|'hw_ctx']]",
7097 .name = "rbp",
7098 .handler = handle_rbp_command,
7099 .mode = COMMAND_EXEC,
7100 .help = "remove breakpoint",
7101 .usage = "'all' | address",
7104 .name = "wp",
7105 .handler = handle_wp_command,
7106 .mode = COMMAND_EXEC,
7107 .help = "list (no params) or create watchpoints",
7108 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
7111 .name = "rwp",
7112 .handler = handle_rwp_command,
7113 .mode = COMMAND_EXEC,
7114 .help = "remove watchpoint",
7115 .usage = "address",
7118 .name = "load_image",
7119 .handler = handle_load_image_command,
7120 .mode = COMMAND_EXEC,
7121 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
7122 "[min_address] [max_length]",
7125 .name = "dump_image",
7126 .handler = handle_dump_image_command,
7127 .mode = COMMAND_EXEC,
7128 .usage = "filename address size",
7131 .name = "verify_image_checksum",
7132 .handler = handle_verify_image_checksum_command,
7133 .mode = COMMAND_EXEC,
7134 .usage = "filename [offset [type]]",
7137 .name = "verify_image",
7138 .handler = handle_verify_image_command,
7139 .mode = COMMAND_EXEC,
7140 .usage = "filename [offset [type]]",
7143 .name = "test_image",
7144 .handler = handle_test_image_command,
7145 .mode = COMMAND_EXEC,
7146 .usage = "filename [offset [type]]",
7149 .name = "get_reg",
7150 .mode = COMMAND_EXEC,
7151 .jim_handler = target_jim_get_reg,
7152 .help = "Get register values from the target",
7153 .usage = "list",
7156 .name = "set_reg",
7157 .mode = COMMAND_EXEC,
7158 .jim_handler = target_jim_set_reg,
7159 .help = "Set target register values",
7160 .usage = "dict",
7163 .name = "read_memory",
7164 .mode = COMMAND_EXEC,
7165 .jim_handler = target_jim_read_memory,
7166 .help = "Read Tcl list of 8/16/32/64 bit numbers from target memory",
7167 .usage = "address width count ['phys']",
7170 .name = "write_memory",
7171 .mode = COMMAND_EXEC,
7172 .jim_handler = target_jim_write_memory,
7173 .help = "Write Tcl list of 8/16/32/64 bit numbers to target memory",
7174 .usage = "address width data ['phys']",
7177 .name = "reset_nag",
7178 .handler = handle_target_reset_nag,
7179 .mode = COMMAND_ANY,
7180 .help = "Nag after each reset about options that could have been "
7181 "enabled to improve performance.",
7182 .usage = "['enable'|'disable']",
7185 .name = "ps",
7186 .handler = handle_ps_command,
7187 .mode = COMMAND_EXEC,
7188 .help = "list all tasks",
7189 .usage = "",
7192 .name = "test_mem_access",
7193 .handler = handle_test_mem_access_command,
7194 .mode = COMMAND_EXEC,
7195 .help = "Test the target's memory access functions",
7196 .usage = "size",
7199 COMMAND_REGISTRATION_DONE
7201 static int target_register_user_commands(struct command_context *cmd_ctx)
7203 int retval = ERROR_OK;
7204 retval = target_request_register_commands(cmd_ctx);
7205 if (retval != ERROR_OK)
7206 return retval;
7208 retval = trace_register_commands(cmd_ctx);
7209 if (retval != ERROR_OK)
7210 return retval;
7213 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);