1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
5 * Copyright (C) 2007-2010 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
8 * Copyright (C) 2008, Duane Ellis *
9 * openocd@duaneeellis.com *
11 * Copyright (C) 2008 by Spencer Oliver *
12 * spen@spen-soft.co.uk *
14 * Copyright (C) 2008 by Rick Altherr *
15 * kc8apf@kc8apf.net> *
17 * Copyright (C) 2011 by Broadcom Corporation *
18 * Evan Hunter - ehunter@broadcom.com *
20 * Copyright (C) ST-Ericsson SA 2011 *
21 * michel.jaouen@stericsson.com : smp minimum support *
23 * Copyright (C) 2011 Andreas Fritiofson *
24 * andreas.fritiofson@gmail.com *
26 * This program is free software; you can redistribute it and/or modify *
27 * it under the terms of the GNU General Public License as published by *
28 * the Free Software Foundation; either version 2 of the License, or *
29 * (at your option) any later version. *
31 * This program is distributed in the hope that it will be useful, *
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
34 * GNU General Public License for more details. *
36 * You should have received a copy of the GNU General Public License *
37 * along with this program. If not, see <http://www.gnu.org/licenses/>. *
38 ***************************************************************************/
44 #include <helper/align.h>
45 #include <helper/time_support.h>
46 #include <jtag/jtag.h>
47 #include <flash/nor/core.h>
50 #include "target_type.h"
51 #include "target_request.h"
52 #include "breakpoints.h"
56 #include "rtos/rtos.h"
57 #include "transport/transport.h"
60 /* default halt wait timeout (ms) */
61 #define DEFAULT_HALT_TIMEOUT 5000
63 static int target_read_buffer_default(struct target *target, target_addr_t address,
64 uint32_t count, uint8_t *buffer);
65 static int target_write_buffer_default(struct target *target, target_addr_t address,
66 uint32_t count, const uint8_t *buffer);
67 static int target_array2mem(Jim_Interp *interp, struct target *target,
68 int argc, Jim_Obj * const *argv);
69 static int target_mem2array(Jim_Interp *interp, struct target *target,
70 int argc, Jim_Obj * const *argv);
71 static int target_register_user_commands(struct command_context *cmd_ctx);
72 static int target_get_gdb_fileio_info_default(struct target *target,
73 struct gdb_fileio_info *fileio_info);
74 static int target_gdb_fileio_end_default(struct target *target, int retcode,
75 int fileio_errno, bool ctrl_c);
78 extern struct target_type arm7tdmi_target;
79 extern struct target_type arm720t_target;
80 extern struct target_type arm9tdmi_target;
81 extern struct target_type arm920t_target;
82 extern struct target_type arm966e_target;
83 extern struct target_type arm946e_target;
84 extern struct target_type arm926ejs_target;
85 extern struct target_type fa526_target;
86 extern struct target_type feroceon_target;
87 extern struct target_type dragonite_target;
88 extern struct target_type xscale_target;
89 extern struct target_type cortexm_target;
90 extern struct target_type cortexa_target;
91 extern struct target_type aarch64_target;
92 extern struct target_type cortexr4_target;
93 extern struct target_type arm11_target;
94 extern struct target_type ls1_sap_target;
95 extern struct target_type mips_m4k_target;
96 extern struct target_type mips_mips64_target;
97 extern struct target_type avr_target;
98 extern struct target_type dsp563xx_target;
99 extern struct target_type dsp5680xx_target;
100 extern struct target_type testee_target;
101 extern struct target_type avr32_ap7k_target;
102 extern struct target_type hla_target;
103 extern struct target_type nds32_v2_target;
104 extern struct target_type nds32_v3_target;
105 extern struct target_type nds32_v3m_target;
106 extern struct target_type or1k_target;
107 extern struct target_type quark_x10xx_target;
108 extern struct target_type quark_d20xx_target;
109 extern struct target_type stm8_target;
110 extern struct target_type riscv_target;
111 extern struct target_type mem_ap_target;
112 extern struct target_type esirisc_target;
113 extern struct target_type arcv2_target;
115 static struct target_type *target_types[] = {
155 struct target *all_targets;
156 static struct target_event_callback *target_event_callbacks;
157 static struct target_timer_callback *target_timer_callbacks;
158 static int64_t target_timer_next_event_value;
159 static LIST_HEAD(target_reset_callback_list);
160 static LIST_HEAD(target_trace_callback_list);
161 static const int polling_interval = TARGET_DEFAULT_POLLING_INTERVAL;
163 static const struct jim_nvp nvp_assert[] = {
164 { .name = "assert", NVP_ASSERT },
165 { .name = "deassert", NVP_DEASSERT },
166 { .name = "T", NVP_ASSERT },
167 { .name = "F", NVP_DEASSERT },
168 { .name = "t", NVP_ASSERT },
169 { .name = "f", NVP_DEASSERT },
170 { .name = NULL, .value = -1 }
173 static const struct jim_nvp nvp_error_target[] = {
174 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
175 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
176 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
177 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
178 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
179 { .value = ERROR_TARGET_UNALIGNED_ACCESS, .name = "err-unaligned-access" },
180 { .value = ERROR_TARGET_DATA_ABORT, .name = "err-data-abort" },
181 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE, .name = "err-resource-not-available" },
182 { .value = ERROR_TARGET_TRANSLATION_FAULT, .name = "err-translation-fault" },
183 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
184 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
185 { .value = -1, .name = NULL }
188 static const char *target_strerror_safe(int err)
190 const struct jim_nvp *n;
192 n = jim_nvp_value2name_simple(nvp_error_target, err);
199 static const struct jim_nvp nvp_target_event[] = {
201 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
202 { .value = TARGET_EVENT_HALTED, .name = "halted" },
203 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
204 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
205 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
206 { .value = TARGET_EVENT_STEP_START, .name = "step-start" },
207 { .value = TARGET_EVENT_STEP_END, .name = "step-end" },
209 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
210 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
212 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
213 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
214 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
215 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
216 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
217 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
218 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
219 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
221 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
222 { .value = TARGET_EVENT_EXAMINE_FAIL, .name = "examine-fail" },
223 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
225 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
226 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
228 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
229 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
231 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
232 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END, .name = "gdb-flash-write-end" },
234 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
235 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END, .name = "gdb-flash-erase-end" },
237 { .value = TARGET_EVENT_TRACE_CONFIG, .name = "trace-config" },
239 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x100, .name = "semihosting-user-cmd-0x100" },
240 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x101, .name = "semihosting-user-cmd-0x101" },
241 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x102, .name = "semihosting-user-cmd-0x102" },
242 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x103, .name = "semihosting-user-cmd-0x103" },
243 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x104, .name = "semihosting-user-cmd-0x104" },
244 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x105, .name = "semihosting-user-cmd-0x105" },
245 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x106, .name = "semihosting-user-cmd-0x106" },
246 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x107, .name = "semihosting-user-cmd-0x107" },
248 { .name = NULL, .value = -1 }
251 static const struct jim_nvp nvp_target_state[] = {
252 { .name = "unknown", .value = TARGET_UNKNOWN },
253 { .name = "running", .value = TARGET_RUNNING },
254 { .name = "halted", .value = TARGET_HALTED },
255 { .name = "reset", .value = TARGET_RESET },
256 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
257 { .name = NULL, .value = -1 },
260 static const struct jim_nvp nvp_target_debug_reason[] = {
261 { .name = "debug-request", .value = DBG_REASON_DBGRQ },
262 { .name = "breakpoint", .value = DBG_REASON_BREAKPOINT },
263 { .name = "watchpoint", .value = DBG_REASON_WATCHPOINT },
264 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
265 { .name = "single-step", .value = DBG_REASON_SINGLESTEP },
266 { .name = "target-not-halted", .value = DBG_REASON_NOTHALTED },
267 { .name = "program-exit", .value = DBG_REASON_EXIT },
268 { .name = "exception-catch", .value = DBG_REASON_EXC_CATCH },
269 { .name = "undefined", .value = DBG_REASON_UNDEFINED },
270 { .name = NULL, .value = -1 },
273 static const struct jim_nvp nvp_target_endian[] = {
274 { .name = "big", .value = TARGET_BIG_ENDIAN },
275 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
276 { .name = "be", .value = TARGET_BIG_ENDIAN },
277 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
278 { .name = NULL, .value = -1 },
281 static const struct jim_nvp nvp_reset_modes[] = {
282 { .name = "unknown", .value = RESET_UNKNOWN },
283 { .name = "run", .value = RESET_RUN },
284 { .name = "halt", .value = RESET_HALT },
285 { .name = "init", .value = RESET_INIT },
286 { .name = NULL, .value = -1 },
289 const char *debug_reason_name(struct target *t)
293 cp = jim_nvp_value2name_simple(nvp_target_debug_reason,
294 t->debug_reason)->name;
296 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
297 cp = "(*BUG*unknown*BUG*)";
302 const char *target_state_name(struct target *t)
305 cp = jim_nvp_value2name_simple(nvp_target_state, t->state)->name;
307 LOG_ERROR("Invalid target state: %d", (int)(t->state));
308 cp = "(*BUG*unknown*BUG*)";
311 if (!target_was_examined(t) && t->defer_examine)
312 cp = "examine deferred";
317 const char *target_event_name(enum target_event event)
320 cp = jim_nvp_value2name_simple(nvp_target_event, event)->name;
322 LOG_ERROR("Invalid target event: %d", (int)(event));
323 cp = "(*BUG*unknown*BUG*)";
328 const char *target_reset_mode_name(enum target_reset_mode reset_mode)
331 cp = jim_nvp_value2name_simple(nvp_reset_modes, reset_mode)->name;
333 LOG_ERROR("Invalid target reset mode: %d", (int)(reset_mode));
334 cp = "(*BUG*unknown*BUG*)";
339 /* determine the number of the new target */
340 static int new_target_number(void)
345 /* number is 0 based */
349 if (x < t->target_number)
350 x = t->target_number;
356 static void append_to_list_all_targets(struct target *target)
358 struct target **t = &all_targets;
365 /* read a uint64_t from a buffer in target memory endianness */
366 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
368 if (target->endianness == TARGET_LITTLE_ENDIAN)
369 return le_to_h_u64(buffer);
371 return be_to_h_u64(buffer);
374 /* read a uint32_t from a buffer in target memory endianness */
375 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
377 if (target->endianness == TARGET_LITTLE_ENDIAN)
378 return le_to_h_u32(buffer);
380 return be_to_h_u32(buffer);
383 /* read a uint24_t from a buffer in target memory endianness */
384 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
386 if (target->endianness == TARGET_LITTLE_ENDIAN)
387 return le_to_h_u24(buffer);
389 return be_to_h_u24(buffer);
392 /* read a uint16_t from a buffer in target memory endianness */
393 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
395 if (target->endianness == TARGET_LITTLE_ENDIAN)
396 return le_to_h_u16(buffer);
398 return be_to_h_u16(buffer);
401 /* write a uint64_t to a buffer in target memory endianness */
402 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
404 if (target->endianness == TARGET_LITTLE_ENDIAN)
405 h_u64_to_le(buffer, value);
407 h_u64_to_be(buffer, value);
410 /* write a uint32_t to a buffer in target memory endianness */
411 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
413 if (target->endianness == TARGET_LITTLE_ENDIAN)
414 h_u32_to_le(buffer, value);
416 h_u32_to_be(buffer, value);
419 /* write a uint24_t to a buffer in target memory endianness */
420 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
422 if (target->endianness == TARGET_LITTLE_ENDIAN)
423 h_u24_to_le(buffer, value);
425 h_u24_to_be(buffer, value);
428 /* write a uint16_t to a buffer in target memory endianness */
429 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
431 if (target->endianness == TARGET_LITTLE_ENDIAN)
432 h_u16_to_le(buffer, value);
434 h_u16_to_be(buffer, value);
437 /* write a uint8_t to a buffer in target memory endianness */
438 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
443 /* write a uint64_t array to a buffer in target memory endianness */
444 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
447 for (i = 0; i < count; i++)
448 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
451 /* write a uint32_t array to a buffer in target memory endianness */
452 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
455 for (i = 0; i < count; i++)
456 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
459 /* write a uint16_t array to a buffer in target memory endianness */
460 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
463 for (i = 0; i < count; i++)
464 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
467 /* write a uint64_t array to a buffer in target memory endianness */
468 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
471 for (i = 0; i < count; i++)
472 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
475 /* write a uint32_t array to a buffer in target memory endianness */
476 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
479 for (i = 0; i < count; i++)
480 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
483 /* write a uint16_t array to a buffer in target memory endianness */
484 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
487 for (i = 0; i < count; i++)
488 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
491 /* return a pointer to a configured target; id is name or number */
492 struct target *get_target(const char *id)
494 struct target *target;
496 /* try as tcltarget name */
497 for (target = all_targets; target; target = target->next) {
498 if (!target_name(target))
500 if (strcmp(id, target_name(target)) == 0)
504 /* It's OK to remove this fallback sometime after August 2010 or so */
506 /* no match, try as number */
508 if (parse_uint(id, &num) != ERROR_OK)
511 for (target = all_targets; target; target = target->next) {
512 if (target->target_number == (int)num) {
513 LOG_WARNING("use '%s' as target identifier, not '%u'",
514 target_name(target), num);
522 /* returns a pointer to the n-th configured target */
523 struct target *get_target_by_num(int num)
525 struct target *target = all_targets;
528 if (target->target_number == num)
530 target = target->next;
536 struct target *get_current_target(struct command_context *cmd_ctx)
538 struct target *target = get_current_target_or_null(cmd_ctx);
541 LOG_ERROR("BUG: current_target out of bounds");
548 struct target *get_current_target_or_null(struct command_context *cmd_ctx)
550 return cmd_ctx->current_target_override
551 ? cmd_ctx->current_target_override
552 : cmd_ctx->current_target;
555 int target_poll(struct target *target)
559 /* We can't poll until after examine */
560 if (!target_was_examined(target)) {
561 /* Fail silently lest we pollute the log */
565 retval = target->type->poll(target);
566 if (retval != ERROR_OK)
569 if (target->halt_issued) {
570 if (target->state == TARGET_HALTED)
571 target->halt_issued = false;
573 int64_t t = timeval_ms() - target->halt_issued_time;
574 if (t > DEFAULT_HALT_TIMEOUT) {
575 target->halt_issued = false;
576 LOG_INFO("Halt timed out, wake up GDB.");
577 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
585 int target_halt(struct target *target)
588 /* We can't poll until after examine */
589 if (!target_was_examined(target)) {
590 LOG_ERROR("Target not examined yet");
594 retval = target->type->halt(target);
595 if (retval != ERROR_OK)
598 target->halt_issued = true;
599 target->halt_issued_time = timeval_ms();
605 * Make the target (re)start executing using its saved execution
606 * context (possibly with some modifications).
608 * @param target Which target should start executing.
609 * @param current True to use the target's saved program counter instead
610 * of the address parameter
611 * @param address Optionally used as the program counter.
612 * @param handle_breakpoints True iff breakpoints at the resumption PC
613 * should be skipped. (For example, maybe execution was stopped by
614 * such a breakpoint, in which case it would be counterproductive to
616 * @param debug_execution False if all working areas allocated by OpenOCD
617 * should be released and/or restored to their original contents.
618 * (This would for example be true to run some downloaded "helper"
619 * algorithm code, which resides in one such working buffer and uses
620 * another for data storage.)
622 * @todo Resolve the ambiguity about what the "debug_execution" flag
623 * signifies. For example, Target implementations don't agree on how
624 * it relates to invalidation of the register cache, or to whether
625 * breakpoints and watchpoints should be enabled. (It would seem wrong
626 * to enable breakpoints when running downloaded "helper" algorithms
627 * (debug_execution true), since the breakpoints would be set to match
628 * target firmware being debugged, not the helper algorithm.... and
629 * enabling them could cause such helpers to malfunction (for example,
630 * by overwriting data with a breakpoint instruction. On the other
631 * hand the infrastructure for running such helpers might use this
632 * procedure but rely on hardware breakpoint to detect termination.)
634 int target_resume(struct target *target, int current, target_addr_t address,
635 int handle_breakpoints, int debug_execution)
639 /* We can't poll until after examine */
640 if (!target_was_examined(target)) {
641 LOG_ERROR("Target not examined yet");
645 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
647 /* note that resume *must* be asynchronous. The CPU can halt before
648 * we poll. The CPU can even halt at the current PC as a result of
649 * a software breakpoint being inserted by (a bug?) the application.
652 * resume() triggers the event 'resumed'. The execution of TCL commands
653 * in the event handler causes the polling of targets. If the target has
654 * already halted for a breakpoint, polling will run the 'halted' event
655 * handler before the pending 'resumed' handler.
656 * Disable polling during resume() to guarantee the execution of handlers
657 * in the correct order.
659 bool save_poll = jtag_poll_get_enabled();
660 jtag_poll_set_enabled(false);
661 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
662 jtag_poll_set_enabled(save_poll);
663 if (retval != ERROR_OK)
666 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
671 static int target_process_reset(struct command_invocation *cmd, enum target_reset_mode reset_mode)
676 n = jim_nvp_value2name_simple(nvp_reset_modes, reset_mode);
678 LOG_ERROR("invalid reset mode");
682 struct target *target;
683 for (target = all_targets; target; target = target->next)
684 target_call_reset_callbacks(target, reset_mode);
686 /* disable polling during reset to make reset event scripts
687 * more predictable, i.e. dr/irscan & pathmove in events will
688 * not have JTAG operations injected into the middle of a sequence.
690 bool save_poll = jtag_poll_get_enabled();
692 jtag_poll_set_enabled(false);
694 sprintf(buf, "ocd_process_reset %s", n->name);
695 retval = Jim_Eval(cmd->ctx->interp, buf);
697 jtag_poll_set_enabled(save_poll);
699 if (retval != JIM_OK) {
700 Jim_MakeErrorMessage(cmd->ctx->interp);
701 command_print(cmd, "%s", Jim_GetString(Jim_GetResult(cmd->ctx->interp), NULL));
705 /* We want any events to be processed before the prompt */
706 retval = target_call_timer_callbacks_now();
708 for (target = all_targets; target; target = target->next) {
709 target->type->check_reset(target);
710 target->running_alg = false;
716 static int identity_virt2phys(struct target *target,
717 target_addr_t virtual, target_addr_t *physical)
723 static int no_mmu(struct target *target, int *enabled)
730 * Reset the @c examined flag for the given target.
731 * Pure paranoia -- targets are zeroed on allocation.
733 static inline void target_reset_examined(struct target *target)
735 target->examined = false;
738 static int default_examine(struct target *target)
740 target_set_examined(target);
744 /* no check by default */
745 static int default_check_reset(struct target *target)
750 /* Equivalent Tcl code arp_examine_one is in src/target/startup.tcl
752 int target_examine_one(struct target *target)
754 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
756 int retval = target->type->examine(target);
757 if (retval != ERROR_OK) {
758 target_reset_examined(target);
759 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_FAIL);
763 target_set_examined(target);
764 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
769 static int jtag_enable_callback(enum jtag_event event, void *priv)
771 struct target *target = priv;
773 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
776 jtag_unregister_event_callback(jtag_enable_callback, target);
778 return target_examine_one(target);
781 /* Targets that correctly implement init + examine, i.e.
782 * no communication with target during init:
786 int target_examine(void)
788 int retval = ERROR_OK;
789 struct target *target;
791 for (target = all_targets; target; target = target->next) {
792 /* defer examination, but don't skip it */
793 if (!target->tap->enabled) {
794 jtag_register_event_callback(jtag_enable_callback,
799 if (target->defer_examine)
802 int retval2 = target_examine_one(target);
803 if (retval2 != ERROR_OK) {
804 LOG_WARNING("target %s examination failed", target_name(target));
811 const char *target_type_name(struct target *target)
813 return target->type->name;
816 static int target_soft_reset_halt(struct target *target)
818 if (!target_was_examined(target)) {
819 LOG_ERROR("Target not examined yet");
822 if (!target->type->soft_reset_halt) {
823 LOG_ERROR("Target %s does not support soft_reset_halt",
824 target_name(target));
827 return target->type->soft_reset_halt(target);
831 * Downloads a target-specific native code algorithm to the target,
832 * and executes it. * Note that some targets may need to set up, enable,
833 * and tear down a breakpoint (hard or * soft) to detect algorithm
834 * termination, while others may support lower overhead schemes where
835 * soft breakpoints embedded in the algorithm automatically terminate the
838 * @param target used to run the algorithm
839 * @param num_mem_params
841 * @param num_reg_params
846 * @param arch_info target-specific description of the algorithm.
848 int target_run_algorithm(struct target *target,
849 int num_mem_params, struct mem_param *mem_params,
850 int num_reg_params, struct reg_param *reg_param,
851 target_addr_t entry_point, target_addr_t exit_point,
852 int timeout_ms, void *arch_info)
854 int retval = ERROR_FAIL;
856 if (!target_was_examined(target)) {
857 LOG_ERROR("Target not examined yet");
860 if (!target->type->run_algorithm) {
861 LOG_ERROR("Target type '%s' does not support %s",
862 target_type_name(target), __func__);
866 target->running_alg = true;
867 retval = target->type->run_algorithm(target,
868 num_mem_params, mem_params,
869 num_reg_params, reg_param,
870 entry_point, exit_point, timeout_ms, arch_info);
871 target->running_alg = false;
878 * Executes a target-specific native code algorithm and leaves it running.
880 * @param target used to run the algorithm
881 * @param num_mem_params
883 * @param num_reg_params
887 * @param arch_info target-specific description of the algorithm.
889 int target_start_algorithm(struct target *target,
890 int num_mem_params, struct mem_param *mem_params,
891 int num_reg_params, struct reg_param *reg_params,
892 target_addr_t entry_point, target_addr_t exit_point,
895 int retval = ERROR_FAIL;
897 if (!target_was_examined(target)) {
898 LOG_ERROR("Target not examined yet");
901 if (!target->type->start_algorithm) {
902 LOG_ERROR("Target type '%s' does not support %s",
903 target_type_name(target), __func__);
906 if (target->running_alg) {
907 LOG_ERROR("Target is already running an algorithm");
911 target->running_alg = true;
912 retval = target->type->start_algorithm(target,
913 num_mem_params, mem_params,
914 num_reg_params, reg_params,
915 entry_point, exit_point, arch_info);
922 * Waits for an algorithm started with target_start_algorithm() to complete.
924 * @param target used to run the algorithm
925 * @param num_mem_params
927 * @param num_reg_params
931 * @param arch_info target-specific description of the algorithm.
933 int target_wait_algorithm(struct target *target,
934 int num_mem_params, struct mem_param *mem_params,
935 int num_reg_params, struct reg_param *reg_params,
936 target_addr_t exit_point, int timeout_ms,
939 int retval = ERROR_FAIL;
941 if (!target->type->wait_algorithm) {
942 LOG_ERROR("Target type '%s' does not support %s",
943 target_type_name(target), __func__);
946 if (!target->running_alg) {
947 LOG_ERROR("Target is not running an algorithm");
951 retval = target->type->wait_algorithm(target,
952 num_mem_params, mem_params,
953 num_reg_params, reg_params,
954 exit_point, timeout_ms, arch_info);
955 if (retval != ERROR_TARGET_TIMEOUT)
956 target->running_alg = false;
963 * Streams data to a circular buffer on target intended for consumption by code
964 * running asynchronously on target.
966 * This is intended for applications where target-specific native code runs
967 * on the target, receives data from the circular buffer, does something with
968 * it (most likely writing it to a flash memory), and advances the circular
971 * This assumes that the helper algorithm has already been loaded to the target,
972 * but has not been started yet. Given memory and register parameters are passed
975 * The buffer is defined by (buffer_start, buffer_size) arguments and has the
978 * [buffer_start + 0, buffer_start + 4):
979 * Write Pointer address (aka head). Written and updated by this
980 * routine when new data is written to the circular buffer.
981 * [buffer_start + 4, buffer_start + 8):
982 * Read Pointer address (aka tail). Updated by code running on the
983 * target after it consumes data.
984 * [buffer_start + 8, buffer_start + buffer_size):
985 * Circular buffer contents.
987 * See contrib/loaders/flash/stm32f1x.S for an example.
989 * @param target used to run the algorithm
990 * @param buffer address on the host where data to be sent is located
991 * @param count number of blocks to send
992 * @param block_size size in bytes of each block
993 * @param num_mem_params count of memory-based params to pass to algorithm
994 * @param mem_params memory-based params to pass to algorithm
995 * @param num_reg_params count of register-based params to pass to algorithm
996 * @param reg_params memory-based params to pass to algorithm
997 * @param buffer_start address on the target of the circular buffer structure
998 * @param buffer_size size of the circular buffer structure
999 * @param entry_point address on the target to execute to start the algorithm
1000 * @param exit_point address at which to set a breakpoint to catch the
1001 * end of the algorithm; can be 0 if target triggers a breakpoint itself
1005 int target_run_flash_async_algorithm(struct target *target,
1006 const uint8_t *buffer, uint32_t count, int block_size,
1007 int num_mem_params, struct mem_param *mem_params,
1008 int num_reg_params, struct reg_param *reg_params,
1009 uint32_t buffer_start, uint32_t buffer_size,
1010 uint32_t entry_point, uint32_t exit_point, void *arch_info)
1015 const uint8_t *buffer_orig = buffer;
1017 /* Set up working area. First word is write pointer, second word is read pointer,
1018 * rest is fifo data area. */
1019 uint32_t wp_addr = buffer_start;
1020 uint32_t rp_addr = buffer_start + 4;
1021 uint32_t fifo_start_addr = buffer_start + 8;
1022 uint32_t fifo_end_addr = buffer_start + buffer_size;
1024 uint32_t wp = fifo_start_addr;
1025 uint32_t rp = fifo_start_addr;
1027 /* validate block_size is 2^n */
1028 assert(IS_PWR_OF_2(block_size));
1030 retval = target_write_u32(target, wp_addr, wp);
1031 if (retval != ERROR_OK)
1033 retval = target_write_u32(target, rp_addr, rp);
1034 if (retval != ERROR_OK)
1037 /* Start up algorithm on target and let it idle while writing the first chunk */
1038 retval = target_start_algorithm(target, num_mem_params, mem_params,
1039 num_reg_params, reg_params,
1044 if (retval != ERROR_OK) {
1045 LOG_ERROR("error starting target flash write algorithm");
1051 retval = target_read_u32(target, rp_addr, &rp);
1052 if (retval != ERROR_OK) {
1053 LOG_ERROR("failed to get read pointer");
1057 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1058 (size_t) (buffer - buffer_orig), count, wp, rp);
1061 LOG_ERROR("flash write algorithm aborted by target");
1062 retval = ERROR_FLASH_OPERATION_FAILED;
1066 if (!IS_ALIGNED(rp - fifo_start_addr, block_size) || rp < fifo_start_addr || rp >= fifo_end_addr) {
1067 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
1071 /* Count the number of bytes available in the fifo without
1072 * crossing the wrap around. Make sure to not fill it completely,
1073 * because that would make wp == rp and that's the empty condition. */
1074 uint32_t thisrun_bytes;
1076 thisrun_bytes = rp - wp - block_size;
1077 else if (rp > fifo_start_addr)
1078 thisrun_bytes = fifo_end_addr - wp;
1080 thisrun_bytes = fifo_end_addr - wp - block_size;
1082 if (thisrun_bytes == 0) {
1083 /* Throttle polling a bit if transfer is (much) faster than flash
1084 * programming. The exact delay shouldn't matter as long as it's
1085 * less than buffer size / flash speed. This is very unlikely to
1086 * run when using high latency connections such as USB. */
1089 /* to stop an infinite loop on some targets check and increment a timeout
1090 * this issue was observed on a stellaris using the new ICDI interface */
1091 if (timeout++ >= 2500) {
1092 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1093 return ERROR_FLASH_OPERATION_FAILED;
1098 /* reset our timeout */
1101 /* Limit to the amount of data we actually want to write */
1102 if (thisrun_bytes > count * block_size)
1103 thisrun_bytes = count * block_size;
1105 /* Force end of large blocks to be word aligned */
1106 if (thisrun_bytes >= 16)
1107 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1109 /* Write data to fifo */
1110 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
1111 if (retval != ERROR_OK)
1114 /* Update counters and wrap write pointer */
1115 buffer += thisrun_bytes;
1116 count -= thisrun_bytes / block_size;
1117 wp += thisrun_bytes;
1118 if (wp >= fifo_end_addr)
1119 wp = fifo_start_addr;
1121 /* Store updated write pointer to target */
1122 retval = target_write_u32(target, wp_addr, wp);
1123 if (retval != ERROR_OK)
1126 /* Avoid GDB timeouts */
1130 if (retval != ERROR_OK) {
1131 /* abort flash write algorithm on target */
1132 target_write_u32(target, wp_addr, 0);
1135 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1136 num_reg_params, reg_params,
1141 if (retval2 != ERROR_OK) {
1142 LOG_ERROR("error waiting for target flash write algorithm");
1146 if (retval == ERROR_OK) {
1147 /* check if algorithm set rp = 0 after fifo writer loop finished */
1148 retval = target_read_u32(target, rp_addr, &rp);
1149 if (retval == ERROR_OK && rp == 0) {
1150 LOG_ERROR("flash write algorithm aborted by target");
1151 retval = ERROR_FLASH_OPERATION_FAILED;
1158 int target_run_read_async_algorithm(struct target *target,
1159 uint8_t *buffer, uint32_t count, int block_size,
1160 int num_mem_params, struct mem_param *mem_params,
1161 int num_reg_params, struct reg_param *reg_params,
1162 uint32_t buffer_start, uint32_t buffer_size,
1163 uint32_t entry_point, uint32_t exit_point, void *arch_info)
1168 const uint8_t *buffer_orig = buffer;
1170 /* Set up working area. First word is write pointer, second word is read pointer,
1171 * rest is fifo data area. */
1172 uint32_t wp_addr = buffer_start;
1173 uint32_t rp_addr = buffer_start + 4;
1174 uint32_t fifo_start_addr = buffer_start + 8;
1175 uint32_t fifo_end_addr = buffer_start + buffer_size;
1177 uint32_t wp = fifo_start_addr;
1178 uint32_t rp = fifo_start_addr;
1180 /* validate block_size is 2^n */
1181 assert(IS_PWR_OF_2(block_size));
1183 retval = target_write_u32(target, wp_addr, wp);
1184 if (retval != ERROR_OK)
1186 retval = target_write_u32(target, rp_addr, rp);
1187 if (retval != ERROR_OK)
1190 /* Start up algorithm on target */
1191 retval = target_start_algorithm(target, num_mem_params, mem_params,
1192 num_reg_params, reg_params,
1197 if (retval != ERROR_OK) {
1198 LOG_ERROR("error starting target flash read algorithm");
1203 retval = target_read_u32(target, wp_addr, &wp);
1204 if (retval != ERROR_OK) {
1205 LOG_ERROR("failed to get write pointer");
1209 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1210 (size_t)(buffer - buffer_orig), count, wp, rp);
1213 LOG_ERROR("flash read algorithm aborted by target");
1214 retval = ERROR_FLASH_OPERATION_FAILED;
1218 if (!IS_ALIGNED(wp - fifo_start_addr, block_size) || wp < fifo_start_addr || wp >= fifo_end_addr) {
1219 LOG_ERROR("corrupted fifo write pointer 0x%" PRIx32, wp);
1223 /* Count the number of bytes available in the fifo without
1224 * crossing the wrap around. */
1225 uint32_t thisrun_bytes;
1227 thisrun_bytes = wp - rp;
1229 thisrun_bytes = fifo_end_addr - rp;
1231 if (thisrun_bytes == 0) {
1232 /* Throttle polling a bit if transfer is (much) faster than flash
1233 * reading. The exact delay shouldn't matter as long as it's
1234 * less than buffer size / flash speed. This is very unlikely to
1235 * run when using high latency connections such as USB. */
1238 /* to stop an infinite loop on some targets check and increment a timeout
1239 * this issue was observed on a stellaris using the new ICDI interface */
1240 if (timeout++ >= 2500) {
1241 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1242 return ERROR_FLASH_OPERATION_FAILED;
1247 /* Reset our timeout */
1250 /* Limit to the amount of data we actually want to read */
1251 if (thisrun_bytes > count * block_size)
1252 thisrun_bytes = count * block_size;
1254 /* Force end of large blocks to be word aligned */
1255 if (thisrun_bytes >= 16)
1256 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1258 /* Read data from fifo */
1259 retval = target_read_buffer(target, rp, thisrun_bytes, buffer);
1260 if (retval != ERROR_OK)
1263 /* Update counters and wrap write pointer */
1264 buffer += thisrun_bytes;
1265 count -= thisrun_bytes / block_size;
1266 rp += thisrun_bytes;
1267 if (rp >= fifo_end_addr)
1268 rp = fifo_start_addr;
1270 /* Store updated write pointer to target */
1271 retval = target_write_u32(target, rp_addr, rp);
1272 if (retval != ERROR_OK)
1275 /* Avoid GDB timeouts */
1280 if (retval != ERROR_OK) {
1281 /* abort flash write algorithm on target */
1282 target_write_u32(target, rp_addr, 0);
1285 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1286 num_reg_params, reg_params,
1291 if (retval2 != ERROR_OK) {
1292 LOG_ERROR("error waiting for target flash write algorithm");
1296 if (retval == ERROR_OK) {
1297 /* check if algorithm set wp = 0 after fifo writer loop finished */
1298 retval = target_read_u32(target, wp_addr, &wp);
1299 if (retval == ERROR_OK && wp == 0) {
1300 LOG_ERROR("flash read algorithm aborted by target");
1301 retval = ERROR_FLASH_OPERATION_FAILED;
1308 int target_read_memory(struct target *target,
1309 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1311 if (!target_was_examined(target)) {
1312 LOG_ERROR("Target not examined yet");
1315 if (!target->type->read_memory) {
1316 LOG_ERROR("Target %s doesn't support read_memory", target_name(target));
1319 return target->type->read_memory(target, address, size, count, buffer);
1322 int target_read_phys_memory(struct target *target,
1323 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1325 if (!target_was_examined(target)) {
1326 LOG_ERROR("Target not examined yet");
1329 if (!target->type->read_phys_memory) {
1330 LOG_ERROR("Target %s doesn't support read_phys_memory", target_name(target));
1333 return target->type->read_phys_memory(target, address, size, count, buffer);
1336 int target_write_memory(struct target *target,
1337 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1339 if (!target_was_examined(target)) {
1340 LOG_ERROR("Target not examined yet");
1343 if (!target->type->write_memory) {
1344 LOG_ERROR("Target %s doesn't support write_memory", target_name(target));
1347 return target->type->write_memory(target, address, size, count, buffer);
1350 int target_write_phys_memory(struct target *target,
1351 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1353 if (!target_was_examined(target)) {
1354 LOG_ERROR("Target not examined yet");
1357 if (!target->type->write_phys_memory) {
1358 LOG_ERROR("Target %s doesn't support write_phys_memory", target_name(target));
1361 return target->type->write_phys_memory(target, address, size, count, buffer);
1364 int target_add_breakpoint(struct target *target,
1365 struct breakpoint *breakpoint)
1367 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1368 LOG_WARNING("target %s is not halted (add breakpoint)", target_name(target));
1369 return ERROR_TARGET_NOT_HALTED;
1371 return target->type->add_breakpoint(target, breakpoint);
1374 int target_add_context_breakpoint(struct target *target,
1375 struct breakpoint *breakpoint)
1377 if (target->state != TARGET_HALTED) {
1378 LOG_WARNING("target %s is not halted (add context breakpoint)", target_name(target));
1379 return ERROR_TARGET_NOT_HALTED;
1381 return target->type->add_context_breakpoint(target, breakpoint);
1384 int target_add_hybrid_breakpoint(struct target *target,
1385 struct breakpoint *breakpoint)
1387 if (target->state != TARGET_HALTED) {
1388 LOG_WARNING("target %s is not halted (add hybrid breakpoint)", target_name(target));
1389 return ERROR_TARGET_NOT_HALTED;
1391 return target->type->add_hybrid_breakpoint(target, breakpoint);
1394 int target_remove_breakpoint(struct target *target,
1395 struct breakpoint *breakpoint)
1397 return target->type->remove_breakpoint(target, breakpoint);
1400 int target_add_watchpoint(struct target *target,
1401 struct watchpoint *watchpoint)
1403 if (target->state != TARGET_HALTED) {
1404 LOG_WARNING("target %s is not halted (add watchpoint)", target_name(target));
1405 return ERROR_TARGET_NOT_HALTED;
1407 return target->type->add_watchpoint(target, watchpoint);
1409 int target_remove_watchpoint(struct target *target,
1410 struct watchpoint *watchpoint)
1412 return target->type->remove_watchpoint(target, watchpoint);
1414 int target_hit_watchpoint(struct target *target,
1415 struct watchpoint **hit_watchpoint)
1417 if (target->state != TARGET_HALTED) {
1418 LOG_WARNING("target %s is not halted (hit watchpoint)", target->cmd_name);
1419 return ERROR_TARGET_NOT_HALTED;
1422 if (!target->type->hit_watchpoint) {
1423 /* For backward compatible, if hit_watchpoint is not implemented,
1424 * return ERROR_FAIL such that gdb_server will not take the nonsense
1429 return target->type->hit_watchpoint(target, hit_watchpoint);
1432 const char *target_get_gdb_arch(struct target *target)
1434 if (!target->type->get_gdb_arch)
1436 return target->type->get_gdb_arch(target);
1439 int target_get_gdb_reg_list(struct target *target,
1440 struct reg **reg_list[], int *reg_list_size,
1441 enum target_register_class reg_class)
1443 int result = ERROR_FAIL;
1445 if (!target_was_examined(target)) {
1446 LOG_ERROR("Target not examined yet");
1450 result = target->type->get_gdb_reg_list(target, reg_list,
1451 reg_list_size, reg_class);
1454 if (result != ERROR_OK) {
1461 int target_get_gdb_reg_list_noread(struct target *target,
1462 struct reg **reg_list[], int *reg_list_size,
1463 enum target_register_class reg_class)
1465 if (target->type->get_gdb_reg_list_noread &&
1466 target->type->get_gdb_reg_list_noread(target, reg_list,
1467 reg_list_size, reg_class) == ERROR_OK)
1469 return target_get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1472 bool target_supports_gdb_connection(struct target *target)
1475 * exclude all the targets that don't provide get_gdb_reg_list
1476 * or that have explicit gdb_max_connection == 0
1478 return !!target->type->get_gdb_reg_list && !!target->gdb_max_connections;
1481 int target_step(struct target *target,
1482 int current, target_addr_t address, int handle_breakpoints)
1486 target_call_event_callbacks(target, TARGET_EVENT_STEP_START);
1488 retval = target->type->step(target, current, address, handle_breakpoints);
1489 if (retval != ERROR_OK)
1492 target_call_event_callbacks(target, TARGET_EVENT_STEP_END);
1497 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1499 if (target->state != TARGET_HALTED) {
1500 LOG_WARNING("target %s is not halted (gdb fileio)", target->cmd_name);
1501 return ERROR_TARGET_NOT_HALTED;
1503 return target->type->get_gdb_fileio_info(target, fileio_info);
1506 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1508 if (target->state != TARGET_HALTED) {
1509 LOG_WARNING("target %s is not halted (gdb fileio end)", target->cmd_name);
1510 return ERROR_TARGET_NOT_HALTED;
1512 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1515 target_addr_t target_address_max(struct target *target)
1517 unsigned bits = target_address_bits(target);
1518 if (sizeof(target_addr_t) * 8 == bits)
1519 return (target_addr_t) -1;
1521 return (((target_addr_t) 1) << bits) - 1;
1524 unsigned target_address_bits(struct target *target)
1526 if (target->type->address_bits)
1527 return target->type->address_bits(target);
1531 unsigned int target_data_bits(struct target *target)
1533 if (target->type->data_bits)
1534 return target->type->data_bits(target);
1538 static int target_profiling(struct target *target, uint32_t *samples,
1539 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1541 return target->type->profiling(target, samples, max_num_samples,
1542 num_samples, seconds);
1545 static int handle_target(void *priv);
1547 static int target_init_one(struct command_context *cmd_ctx,
1548 struct target *target)
1550 target_reset_examined(target);
1552 struct target_type *type = target->type;
1554 type->examine = default_examine;
1556 if (!type->check_reset)
1557 type->check_reset = default_check_reset;
1559 assert(type->init_target);
1561 int retval = type->init_target(cmd_ctx, target);
1562 if (retval != ERROR_OK) {
1563 LOG_ERROR("target '%s' init failed", target_name(target));
1567 /* Sanity-check MMU support ... stub in what we must, to help
1568 * implement it in stages, but warn if we need to do so.
1571 if (!type->virt2phys) {
1572 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1573 type->virt2phys = identity_virt2phys;
1576 /* Make sure no-MMU targets all behave the same: make no
1577 * distinction between physical and virtual addresses, and
1578 * ensure that virt2phys() is always an identity mapping.
1580 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1581 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1584 type->write_phys_memory = type->write_memory;
1585 type->read_phys_memory = type->read_memory;
1586 type->virt2phys = identity_virt2phys;
1589 if (!target->type->read_buffer)
1590 target->type->read_buffer = target_read_buffer_default;
1592 if (!target->type->write_buffer)
1593 target->type->write_buffer = target_write_buffer_default;
1595 if (!target->type->get_gdb_fileio_info)
1596 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1598 if (!target->type->gdb_fileio_end)
1599 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1601 if (!target->type->profiling)
1602 target->type->profiling = target_profiling_default;
1607 static int target_init(struct command_context *cmd_ctx)
1609 struct target *target;
1612 for (target = all_targets; target; target = target->next) {
1613 retval = target_init_one(cmd_ctx, target);
1614 if (retval != ERROR_OK)
1621 retval = target_register_user_commands(cmd_ctx);
1622 if (retval != ERROR_OK)
1625 retval = target_register_timer_callback(&handle_target,
1626 polling_interval, TARGET_TIMER_TYPE_PERIODIC, cmd_ctx->interp);
1627 if (retval != ERROR_OK)
1633 COMMAND_HANDLER(handle_target_init_command)
1638 return ERROR_COMMAND_SYNTAX_ERROR;
1640 static bool target_initialized;
1641 if (target_initialized) {
1642 LOG_INFO("'target init' has already been called");
1645 target_initialized = true;
1647 retval = command_run_line(CMD_CTX, "init_targets");
1648 if (retval != ERROR_OK)
1651 retval = command_run_line(CMD_CTX, "init_target_events");
1652 if (retval != ERROR_OK)
1655 retval = command_run_line(CMD_CTX, "init_board");
1656 if (retval != ERROR_OK)
1659 LOG_DEBUG("Initializing targets...");
1660 return target_init(CMD_CTX);
1663 int target_register_event_callback(int (*callback)(struct target *target,
1664 enum target_event event, void *priv), void *priv)
1666 struct target_event_callback **callbacks_p = &target_event_callbacks;
1669 return ERROR_COMMAND_SYNTAX_ERROR;
1672 while ((*callbacks_p)->next)
1673 callbacks_p = &((*callbacks_p)->next);
1674 callbacks_p = &((*callbacks_p)->next);
1677 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1678 (*callbacks_p)->callback = callback;
1679 (*callbacks_p)->priv = priv;
1680 (*callbacks_p)->next = NULL;
1685 int target_register_reset_callback(int (*callback)(struct target *target,
1686 enum target_reset_mode reset_mode, void *priv), void *priv)
1688 struct target_reset_callback *entry;
1691 return ERROR_COMMAND_SYNTAX_ERROR;
1693 entry = malloc(sizeof(struct target_reset_callback));
1695 LOG_ERROR("error allocating buffer for reset callback entry");
1696 return ERROR_COMMAND_SYNTAX_ERROR;
1699 entry->callback = callback;
1701 list_add(&entry->list, &target_reset_callback_list);
1707 int target_register_trace_callback(int (*callback)(struct target *target,
1708 size_t len, uint8_t *data, void *priv), void *priv)
1710 struct target_trace_callback *entry;
1713 return ERROR_COMMAND_SYNTAX_ERROR;
1715 entry = malloc(sizeof(struct target_trace_callback));
1717 LOG_ERROR("error allocating buffer for trace callback entry");
1718 return ERROR_COMMAND_SYNTAX_ERROR;
1721 entry->callback = callback;
1723 list_add(&entry->list, &target_trace_callback_list);
1729 int target_register_timer_callback(int (*callback)(void *priv),
1730 unsigned int time_ms, enum target_timer_type type, void *priv)
1732 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1735 return ERROR_COMMAND_SYNTAX_ERROR;
1738 while ((*callbacks_p)->next)
1739 callbacks_p = &((*callbacks_p)->next);
1740 callbacks_p = &((*callbacks_p)->next);
1743 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1744 (*callbacks_p)->callback = callback;
1745 (*callbacks_p)->type = type;
1746 (*callbacks_p)->time_ms = time_ms;
1747 (*callbacks_p)->removed = false;
1749 (*callbacks_p)->when = timeval_ms() + time_ms;
1750 target_timer_next_event_value = MIN(target_timer_next_event_value, (*callbacks_p)->when);
1752 (*callbacks_p)->priv = priv;
1753 (*callbacks_p)->next = NULL;
1758 int target_unregister_event_callback(int (*callback)(struct target *target,
1759 enum target_event event, void *priv), void *priv)
1761 struct target_event_callback **p = &target_event_callbacks;
1762 struct target_event_callback *c = target_event_callbacks;
1765 return ERROR_COMMAND_SYNTAX_ERROR;
1768 struct target_event_callback *next = c->next;
1769 if ((c->callback == callback) && (c->priv == priv)) {
1781 int target_unregister_reset_callback(int (*callback)(struct target *target,
1782 enum target_reset_mode reset_mode, void *priv), void *priv)
1784 struct target_reset_callback *entry;
1787 return ERROR_COMMAND_SYNTAX_ERROR;
1789 list_for_each_entry(entry, &target_reset_callback_list, list) {
1790 if (entry->callback == callback && entry->priv == priv) {
1791 list_del(&entry->list);
1800 int target_unregister_trace_callback(int (*callback)(struct target *target,
1801 size_t len, uint8_t *data, void *priv), void *priv)
1803 struct target_trace_callback *entry;
1806 return ERROR_COMMAND_SYNTAX_ERROR;
1808 list_for_each_entry(entry, &target_trace_callback_list, list) {
1809 if (entry->callback == callback && entry->priv == priv) {
1810 list_del(&entry->list);
1819 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1822 return ERROR_COMMAND_SYNTAX_ERROR;
1824 for (struct target_timer_callback *c = target_timer_callbacks;
1826 if ((c->callback == callback) && (c->priv == priv)) {
1835 int target_call_event_callbacks(struct target *target, enum target_event event)
1837 struct target_event_callback *callback = target_event_callbacks;
1838 struct target_event_callback *next_callback;
1840 if (event == TARGET_EVENT_HALTED) {
1841 /* execute early halted first */
1842 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1845 LOG_DEBUG("target event %i (%s) for core %s", event,
1846 target_event_name(event),
1847 target_name(target));
1849 target_handle_event(target, event);
1852 next_callback = callback->next;
1853 callback->callback(target, event, callback->priv);
1854 callback = next_callback;
1860 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1862 struct target_reset_callback *callback;
1864 LOG_DEBUG("target reset %i (%s)", reset_mode,
1865 jim_nvp_value2name_simple(nvp_reset_modes, reset_mode)->name);
1867 list_for_each_entry(callback, &target_reset_callback_list, list)
1868 callback->callback(target, reset_mode, callback->priv);
1873 int target_call_trace_callbacks(struct target *target, size_t len, uint8_t *data)
1875 struct target_trace_callback *callback;
1877 list_for_each_entry(callback, &target_trace_callback_list, list)
1878 callback->callback(target, len, data, callback->priv);
1883 static int target_timer_callback_periodic_restart(
1884 struct target_timer_callback *cb, int64_t *now)
1886 cb->when = *now + cb->time_ms;
1890 static int target_call_timer_callback(struct target_timer_callback *cb,
1893 cb->callback(cb->priv);
1895 if (cb->type == TARGET_TIMER_TYPE_PERIODIC)
1896 return target_timer_callback_periodic_restart(cb, now);
1898 return target_unregister_timer_callback(cb->callback, cb->priv);
1901 static int target_call_timer_callbacks_check_time(int checktime)
1903 static bool callback_processing;
1905 /* Do not allow nesting */
1906 if (callback_processing)
1909 callback_processing = true;
1913 int64_t now = timeval_ms();
1915 /* Initialize to a default value that's a ways into the future.
1916 * The loop below will make it closer to now if there are
1917 * callbacks that want to be called sooner. */
1918 target_timer_next_event_value = now + 1000;
1920 /* Store an address of the place containing a pointer to the
1921 * next item; initially, that's a standalone "root of the
1922 * list" variable. */
1923 struct target_timer_callback **callback = &target_timer_callbacks;
1924 while (callback && *callback) {
1925 if ((*callback)->removed) {
1926 struct target_timer_callback *p = *callback;
1927 *callback = (*callback)->next;
1932 bool call_it = (*callback)->callback &&
1933 ((!checktime && (*callback)->type == TARGET_TIMER_TYPE_PERIODIC) ||
1934 now >= (*callback)->when);
1937 target_call_timer_callback(*callback, &now);
1939 if (!(*callback)->removed && (*callback)->when < target_timer_next_event_value)
1940 target_timer_next_event_value = (*callback)->when;
1942 callback = &(*callback)->next;
1945 callback_processing = false;
1949 int target_call_timer_callbacks()
1951 return target_call_timer_callbacks_check_time(1);
1954 /* invoke periodic callbacks immediately */
1955 int target_call_timer_callbacks_now()
1957 return target_call_timer_callbacks_check_time(0);
1960 int64_t target_timer_next_event(void)
1962 return target_timer_next_event_value;
1965 /* Prints the working area layout for debug purposes */
1966 static void print_wa_layout(struct target *target)
1968 struct working_area *c = target->working_areas;
1971 LOG_DEBUG("%c%c " TARGET_ADDR_FMT "-" TARGET_ADDR_FMT " (%" PRIu32 " bytes)",
1972 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1973 c->address, c->address + c->size - 1, c->size);
1978 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1979 static void target_split_working_area(struct working_area *area, uint32_t size)
1981 assert(area->free); /* Shouldn't split an allocated area */
1982 assert(size <= area->size); /* Caller should guarantee this */
1984 /* Split only if not already the right size */
1985 if (size < area->size) {
1986 struct working_area *new_wa = malloc(sizeof(*new_wa));
1991 new_wa->next = area->next;
1992 new_wa->size = area->size - size;
1993 new_wa->address = area->address + size;
1994 new_wa->backup = NULL;
1995 new_wa->user = NULL;
1996 new_wa->free = true;
1998 area->next = new_wa;
2001 /* If backup memory was allocated to this area, it has the wrong size
2002 * now so free it and it will be reallocated if/when needed */
2004 area->backup = NULL;
2008 /* Merge all adjacent free areas into one */
2009 static void target_merge_working_areas(struct target *target)
2011 struct working_area *c = target->working_areas;
2013 while (c && c->next) {
2014 assert(c->next->address == c->address + c->size); /* This is an invariant */
2016 /* Find two adjacent free areas */
2017 if (c->free && c->next->free) {
2018 /* Merge the last into the first */
2019 c->size += c->next->size;
2021 /* Remove the last */
2022 struct working_area *to_be_freed = c->next;
2023 c->next = c->next->next;
2024 free(to_be_freed->backup);
2027 /* If backup memory was allocated to the remaining area, it's has
2028 * the wrong size now */
2037 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
2039 /* Reevaluate working area address based on MMU state*/
2040 if (!target->working_areas) {
2044 retval = target->type->mmu(target, &enabled);
2045 if (retval != ERROR_OK)
2049 if (target->working_area_phys_spec) {
2050 LOG_DEBUG("MMU disabled, using physical "
2051 "address for working memory " TARGET_ADDR_FMT,
2052 target->working_area_phys);
2053 target->working_area = target->working_area_phys;
2055 LOG_ERROR("No working memory available. "
2056 "Specify -work-area-phys to target.");
2057 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2060 if (target->working_area_virt_spec) {
2061 LOG_DEBUG("MMU enabled, using virtual "
2062 "address for working memory " TARGET_ADDR_FMT,
2063 target->working_area_virt);
2064 target->working_area = target->working_area_virt;
2066 LOG_ERROR("No working memory available. "
2067 "Specify -work-area-virt to target.");
2068 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2072 /* Set up initial working area on first call */
2073 struct working_area *new_wa = malloc(sizeof(*new_wa));
2075 new_wa->next = NULL;
2076 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
2077 new_wa->address = target->working_area;
2078 new_wa->backup = NULL;
2079 new_wa->user = NULL;
2080 new_wa->free = true;
2083 target->working_areas = new_wa;
2086 /* only allocate multiples of 4 byte */
2088 size = (size + 3) & (~3UL);
2090 struct working_area *c = target->working_areas;
2092 /* Find the first large enough working area */
2094 if (c->free && c->size >= size)
2100 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2102 /* Split the working area into the requested size */
2103 target_split_working_area(c, size);
2105 LOG_DEBUG("allocated new working area of %" PRIu32 " bytes at address " TARGET_ADDR_FMT,
2108 if (target->backup_working_area) {
2110 c->backup = malloc(c->size);
2115 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
2116 if (retval != ERROR_OK)
2120 /* mark as used, and return the new (reused) area */
2127 print_wa_layout(target);
2132 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
2136 retval = target_alloc_working_area_try(target, size, area);
2137 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
2138 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
2143 static int target_restore_working_area(struct target *target, struct working_area *area)
2145 int retval = ERROR_OK;
2147 if (target->backup_working_area && area->backup) {
2148 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
2149 if (retval != ERROR_OK)
2150 LOG_ERROR("failed to restore %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2151 area->size, area->address);
2157 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
2158 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
2160 if (!area || area->free)
2163 int retval = ERROR_OK;
2165 retval = target_restore_working_area(target, area);
2166 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
2167 if (retval != ERROR_OK)
2173 LOG_DEBUG("freed %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2174 area->size, area->address);
2176 /* mark user pointer invalid */
2177 /* TODO: Is this really safe? It points to some previous caller's memory.
2178 * How could we know that the area pointer is still in that place and not
2179 * some other vital data? What's the purpose of this, anyway? */
2183 target_merge_working_areas(target);
2185 print_wa_layout(target);
2190 int target_free_working_area(struct target *target, struct working_area *area)
2192 return target_free_working_area_restore(target, area, 1);
2195 /* free resources and restore memory, if restoring memory fails,
2196 * free up resources anyway
2198 static void target_free_all_working_areas_restore(struct target *target, int restore)
2200 struct working_area *c = target->working_areas;
2202 LOG_DEBUG("freeing all working areas");
2204 /* Loop through all areas, restoring the allocated ones and marking them as free */
2208 target_restore_working_area(target, c);
2210 *c->user = NULL; /* Same as above */
2216 /* Run a merge pass to combine all areas into one */
2217 target_merge_working_areas(target);
2219 print_wa_layout(target);
2222 void target_free_all_working_areas(struct target *target)
2224 target_free_all_working_areas_restore(target, 1);
2226 /* Now we have none or only one working area marked as free */
2227 if (target->working_areas) {
2228 /* Free the last one to allow on-the-fly moving and resizing */
2229 free(target->working_areas->backup);
2230 free(target->working_areas);
2231 target->working_areas = NULL;
2235 /* Find the largest number of bytes that can be allocated */
2236 uint32_t target_get_working_area_avail(struct target *target)
2238 struct working_area *c = target->working_areas;
2239 uint32_t max_size = 0;
2242 return target->working_area_size;
2245 if (c->free && max_size < c->size)
2254 static void target_destroy(struct target *target)
2256 if (target->type->deinit_target)
2257 target->type->deinit_target(target);
2259 free(target->semihosting);
2261 jtag_unregister_event_callback(jtag_enable_callback, target);
2263 struct target_event_action *teap = target->event_action;
2265 struct target_event_action *next = teap->next;
2266 Jim_DecrRefCount(teap->interp, teap->body);
2271 target_free_all_working_areas(target);
2273 /* release the targets SMP list */
2275 struct target_list *head = target->head;
2277 struct target_list *pos = head->next;
2278 head->target->smp = 0;
2285 rtos_destroy(target);
2287 free(target->gdb_port_override);
2289 free(target->trace_info);
2290 free(target->fileio_info);
2291 free(target->cmd_name);
2295 void target_quit(void)
2297 struct target_event_callback *pe = target_event_callbacks;
2299 struct target_event_callback *t = pe->next;
2303 target_event_callbacks = NULL;
2305 struct target_timer_callback *pt = target_timer_callbacks;
2307 struct target_timer_callback *t = pt->next;
2311 target_timer_callbacks = NULL;
2313 for (struct target *target = all_targets; target;) {
2317 target_destroy(target);
2324 int target_arch_state(struct target *target)
2328 LOG_WARNING("No target has been configured");
2332 if (target->state != TARGET_HALTED)
2335 retval = target->type->arch_state(target);
2339 static int target_get_gdb_fileio_info_default(struct target *target,
2340 struct gdb_fileio_info *fileio_info)
2342 /* If target does not support semi-hosting function, target
2343 has no need to provide .get_gdb_fileio_info callback.
2344 It just return ERROR_FAIL and gdb_server will return "Txx"
2345 as target halted every time. */
2349 static int target_gdb_fileio_end_default(struct target *target,
2350 int retcode, int fileio_errno, bool ctrl_c)
2355 int target_profiling_default(struct target *target, uint32_t *samples,
2356 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
2358 struct timeval timeout, now;
2360 gettimeofday(&timeout, NULL);
2361 timeval_add_time(&timeout, seconds, 0);
2363 LOG_INFO("Starting profiling. Halting and resuming the"
2364 " target as often as we can...");
2366 uint32_t sample_count = 0;
2367 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2368 struct reg *reg = register_get_by_name(target->reg_cache, "pc", true);
2370 int retval = ERROR_OK;
2372 target_poll(target);
2373 if (target->state == TARGET_HALTED) {
2374 uint32_t t = buf_get_u32(reg->value, 0, 32);
2375 samples[sample_count++] = t;
2376 /* current pc, addr = 0, do not handle breakpoints, not debugging */
2377 retval = target_resume(target, 1, 0, 0, 0);
2378 target_poll(target);
2379 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2380 } else if (target->state == TARGET_RUNNING) {
2381 /* We want to quickly sample the PC. */
2382 retval = target_halt(target);
2384 LOG_INFO("Target not halted or running");
2389 if (retval != ERROR_OK)
2392 gettimeofday(&now, NULL);
2393 if ((sample_count >= max_num_samples) || timeval_compare(&now, &timeout) >= 0) {
2394 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2399 *num_samples = sample_count;
2403 /* Single aligned words are guaranteed to use 16 or 32 bit access
2404 * mode respectively, otherwise data is handled as quickly as
2407 int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
2409 LOG_DEBUG("writing buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2412 if (!target_was_examined(target)) {
2413 LOG_ERROR("Target not examined yet");
2420 if ((address + size - 1) < address) {
2421 /* GDB can request this when e.g. PC is 0xfffffffc */
2422 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2428 return target->type->write_buffer(target, address, size, buffer);
2431 static int target_write_buffer_default(struct target *target,
2432 target_addr_t address, uint32_t count, const uint8_t *buffer)
2435 unsigned int data_bytes = target_data_bits(target) / 8;
2437 /* Align up to maximum bytes. The loop condition makes sure the next pass
2438 * will have something to do with the size we leave to it. */
2440 size < data_bytes && count >= size * 2 + (address & size);
2442 if (address & size) {
2443 int retval = target_write_memory(target, address, size, 1, buffer);
2444 if (retval != ERROR_OK)
2452 /* Write the data with as large access size as possible. */
2453 for (; size > 0; size /= 2) {
2454 uint32_t aligned = count - count % size;
2456 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2457 if (retval != ERROR_OK)
2468 /* Single aligned words are guaranteed to use 16 or 32 bit access
2469 * mode respectively, otherwise data is handled as quickly as
2472 int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
2474 LOG_DEBUG("reading buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2477 if (!target_was_examined(target)) {
2478 LOG_ERROR("Target not examined yet");
2485 if ((address + size - 1) < address) {
2486 /* GDB can request this when e.g. PC is 0xfffffffc */
2487 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2493 return target->type->read_buffer(target, address, size, buffer);
2496 static int target_read_buffer_default(struct target *target, target_addr_t address, uint32_t count, uint8_t *buffer)
2499 unsigned int data_bytes = target_data_bits(target) / 8;
2501 /* Align up to maximum bytes. The loop condition makes sure the next pass
2502 * will have something to do with the size we leave to it. */
2504 size < data_bytes && count >= size * 2 + (address & size);
2506 if (address & size) {
2507 int retval = target_read_memory(target, address, size, 1, buffer);
2508 if (retval != ERROR_OK)
2516 /* Read the data with as large access size as possible. */
2517 for (; size > 0; size /= 2) {
2518 uint32_t aligned = count - count % size;
2520 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2521 if (retval != ERROR_OK)
2532 int target_checksum_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t *crc)
2537 uint32_t checksum = 0;
2538 if (!target_was_examined(target)) {
2539 LOG_ERROR("Target not examined yet");
2542 if (!target->type->checksum_memory) {
2543 LOG_ERROR("Target %s doesn't support checksum_memory", target_name(target));
2547 retval = target->type->checksum_memory(target, address, size, &checksum);
2548 if (retval != ERROR_OK) {
2549 buffer = malloc(size);
2551 LOG_ERROR("error allocating buffer for section (%" PRIu32 " bytes)", size);
2552 return ERROR_COMMAND_SYNTAX_ERROR;
2554 retval = target_read_buffer(target, address, size, buffer);
2555 if (retval != ERROR_OK) {
2560 /* convert to target endianness */
2561 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2562 uint32_t target_data;
2563 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2564 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2567 retval = image_calculate_checksum(buffer, size, &checksum);
2576 int target_blank_check_memory(struct target *target,
2577 struct target_memory_check_block *blocks, int num_blocks,
2578 uint8_t erased_value)
2580 if (!target_was_examined(target)) {
2581 LOG_ERROR("Target not examined yet");
2585 if (!target->type->blank_check_memory)
2586 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2588 return target->type->blank_check_memory(target, blocks, num_blocks, erased_value);
2591 int target_read_u64(struct target *target, target_addr_t address, uint64_t *value)
2593 uint8_t value_buf[8];
2594 if (!target_was_examined(target)) {
2595 LOG_ERROR("Target not examined yet");
2599 int retval = target_read_memory(target, address, 8, 1, value_buf);
2601 if (retval == ERROR_OK) {
2602 *value = target_buffer_get_u64(target, value_buf);
2603 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2608 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2615 int target_read_u32(struct target *target, target_addr_t address, uint32_t *value)
2617 uint8_t value_buf[4];
2618 if (!target_was_examined(target)) {
2619 LOG_ERROR("Target not examined yet");
2623 int retval = target_read_memory(target, address, 4, 1, value_buf);
2625 if (retval == ERROR_OK) {
2626 *value = target_buffer_get_u32(target, value_buf);
2627 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2632 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2639 int target_read_u16(struct target *target, target_addr_t address, uint16_t *value)
2641 uint8_t value_buf[2];
2642 if (!target_was_examined(target)) {
2643 LOG_ERROR("Target not examined yet");
2647 int retval = target_read_memory(target, address, 2, 1, value_buf);
2649 if (retval == ERROR_OK) {
2650 *value = target_buffer_get_u16(target, value_buf);
2651 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%4.4" PRIx16,
2656 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2663 int target_read_u8(struct target *target, target_addr_t address, uint8_t *value)
2665 if (!target_was_examined(target)) {
2666 LOG_ERROR("Target not examined yet");
2670 int retval = target_read_memory(target, address, 1, 1, value);
2672 if (retval == ERROR_OK) {
2673 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2678 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2685 int target_write_u64(struct target *target, target_addr_t address, uint64_t value)
2688 uint8_t value_buf[8];
2689 if (!target_was_examined(target)) {
2690 LOG_ERROR("Target not examined yet");
2694 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2698 target_buffer_set_u64(target, value_buf, value);
2699 retval = target_write_memory(target, address, 8, 1, value_buf);
2700 if (retval != ERROR_OK)
2701 LOG_DEBUG("failed: %i", retval);
2706 int target_write_u32(struct target *target, target_addr_t address, uint32_t value)
2709 uint8_t value_buf[4];
2710 if (!target_was_examined(target)) {
2711 LOG_ERROR("Target not examined yet");
2715 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2719 target_buffer_set_u32(target, value_buf, value);
2720 retval = target_write_memory(target, address, 4, 1, value_buf);
2721 if (retval != ERROR_OK)
2722 LOG_DEBUG("failed: %i", retval);
2727 int target_write_u16(struct target *target, target_addr_t address, uint16_t value)
2730 uint8_t value_buf[2];
2731 if (!target_was_examined(target)) {
2732 LOG_ERROR("Target not examined yet");
2736 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2740 target_buffer_set_u16(target, value_buf, value);
2741 retval = target_write_memory(target, address, 2, 1, value_buf);
2742 if (retval != ERROR_OK)
2743 LOG_DEBUG("failed: %i", retval);
2748 int target_write_u8(struct target *target, target_addr_t address, uint8_t value)
2751 if (!target_was_examined(target)) {
2752 LOG_ERROR("Target not examined yet");
2756 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2759 retval = target_write_memory(target, address, 1, 1, &value);
2760 if (retval != ERROR_OK)
2761 LOG_DEBUG("failed: %i", retval);
2766 int target_write_phys_u64(struct target *target, target_addr_t address, uint64_t value)
2769 uint8_t value_buf[8];
2770 if (!target_was_examined(target)) {
2771 LOG_ERROR("Target not examined yet");
2775 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2779 target_buffer_set_u64(target, value_buf, value);
2780 retval = target_write_phys_memory(target, address, 8, 1, value_buf);
2781 if (retval != ERROR_OK)
2782 LOG_DEBUG("failed: %i", retval);
2787 int target_write_phys_u32(struct target *target, target_addr_t address, uint32_t value)
2790 uint8_t value_buf[4];
2791 if (!target_was_examined(target)) {
2792 LOG_ERROR("Target not examined yet");
2796 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2800 target_buffer_set_u32(target, value_buf, value);
2801 retval = target_write_phys_memory(target, address, 4, 1, value_buf);
2802 if (retval != ERROR_OK)
2803 LOG_DEBUG("failed: %i", retval);
2808 int target_write_phys_u16(struct target *target, target_addr_t address, uint16_t value)
2811 uint8_t value_buf[2];
2812 if (!target_was_examined(target)) {
2813 LOG_ERROR("Target not examined yet");
2817 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2821 target_buffer_set_u16(target, value_buf, value);
2822 retval = target_write_phys_memory(target, address, 2, 1, value_buf);
2823 if (retval != ERROR_OK)
2824 LOG_DEBUG("failed: %i", retval);
2829 int target_write_phys_u8(struct target *target, target_addr_t address, uint8_t value)
2832 if (!target_was_examined(target)) {
2833 LOG_ERROR("Target not examined yet");
2837 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2840 retval = target_write_phys_memory(target, address, 1, 1, &value);
2841 if (retval != ERROR_OK)
2842 LOG_DEBUG("failed: %i", retval);
2847 static int find_target(struct command_invocation *cmd, const char *name)
2849 struct target *target = get_target(name);
2851 command_print(cmd, "Target: %s is unknown, try one of:\n", name);
2854 if (!target->tap->enabled) {
2855 command_print(cmd, "Target: TAP %s is disabled, "
2856 "can't be the current target\n",
2857 target->tap->dotted_name);
2861 cmd->ctx->current_target = target;
2862 if (cmd->ctx->current_target_override)
2863 cmd->ctx->current_target_override = target;
2869 COMMAND_HANDLER(handle_targets_command)
2871 int retval = ERROR_OK;
2872 if (CMD_ARGC == 1) {
2873 retval = find_target(CMD, CMD_ARGV[0]);
2874 if (retval == ERROR_OK) {
2880 struct target *target = all_targets;
2881 command_print(CMD, " TargetName Type Endian TapName State ");
2882 command_print(CMD, "-- ------------------ ---------- ------ ------------------ ------------");
2887 if (target->tap->enabled)
2888 state = target_state_name(target);
2890 state = "tap-disabled";
2892 if (CMD_CTX->current_target == target)
2895 /* keep columns lined up to match the headers above */
2897 "%2d%c %-18s %-10s %-6s %-18s %s",
2898 target->target_number,
2900 target_name(target),
2901 target_type_name(target),
2902 jim_nvp_value2name_simple(nvp_target_endian,
2903 target->endianness)->name,
2904 target->tap->dotted_name,
2906 target = target->next;
2912 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2914 static int power_dropout;
2915 static int srst_asserted;
2917 static int run_power_restore;
2918 static int run_power_dropout;
2919 static int run_srst_asserted;
2920 static int run_srst_deasserted;
2922 static int sense_handler(void)
2924 static int prev_srst_asserted;
2925 static int prev_power_dropout;
2927 int retval = jtag_power_dropout(&power_dropout);
2928 if (retval != ERROR_OK)
2932 power_restored = prev_power_dropout && !power_dropout;
2934 run_power_restore = 1;
2936 int64_t current = timeval_ms();
2937 static int64_t last_power;
2938 bool wait_more = last_power + 2000 > current;
2939 if (power_dropout && !wait_more) {
2940 run_power_dropout = 1;
2941 last_power = current;
2944 retval = jtag_srst_asserted(&srst_asserted);
2945 if (retval != ERROR_OK)
2948 int srst_deasserted;
2949 srst_deasserted = prev_srst_asserted && !srst_asserted;
2951 static int64_t last_srst;
2952 wait_more = last_srst + 2000 > current;
2953 if (srst_deasserted && !wait_more) {
2954 run_srst_deasserted = 1;
2955 last_srst = current;
2958 if (!prev_srst_asserted && srst_asserted)
2959 run_srst_asserted = 1;
2961 prev_srst_asserted = srst_asserted;
2962 prev_power_dropout = power_dropout;
2964 if (srst_deasserted || power_restored) {
2965 /* Other than logging the event we can't do anything here.
2966 * Issuing a reset is a particularly bad idea as we might
2967 * be inside a reset already.
2974 /* process target state changes */
2975 static int handle_target(void *priv)
2977 Jim_Interp *interp = (Jim_Interp *)priv;
2978 int retval = ERROR_OK;
2980 if (!is_jtag_poll_safe()) {
2981 /* polling is disabled currently */
2985 /* we do not want to recurse here... */
2986 static int recursive;
2990 /* danger! running these procedures can trigger srst assertions and power dropouts.
2991 * We need to avoid an infinite loop/recursion here and we do that by
2992 * clearing the flags after running these events.
2994 int did_something = 0;
2995 if (run_srst_asserted) {
2996 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2997 Jim_Eval(interp, "srst_asserted");
3000 if (run_srst_deasserted) {
3001 Jim_Eval(interp, "srst_deasserted");
3004 if (run_power_dropout) {
3005 LOG_INFO("Power dropout detected, running power_dropout proc.");
3006 Jim_Eval(interp, "power_dropout");
3009 if (run_power_restore) {
3010 Jim_Eval(interp, "power_restore");
3014 if (did_something) {
3015 /* clear detect flags */
3019 /* clear action flags */
3021 run_srst_asserted = 0;
3022 run_srst_deasserted = 0;
3023 run_power_restore = 0;
3024 run_power_dropout = 0;
3029 /* Poll targets for state changes unless that's globally disabled.
3030 * Skip targets that are currently disabled.
3032 for (struct target *target = all_targets;
3033 is_jtag_poll_safe() && target;
3034 target = target->next) {
3036 if (!target_was_examined(target))
3039 if (!target->tap->enabled)
3042 if (target->backoff.times > target->backoff.count) {
3043 /* do not poll this time as we failed previously */
3044 target->backoff.count++;
3047 target->backoff.count = 0;
3049 /* only poll target if we've got power and srst isn't asserted */
3050 if (!power_dropout && !srst_asserted) {
3051 /* polling may fail silently until the target has been examined */
3052 retval = target_poll(target);
3053 if (retval != ERROR_OK) {
3054 /* 100ms polling interval. Increase interval between polling up to 5000ms */
3055 if (target->backoff.times * polling_interval < 5000) {
3056 target->backoff.times *= 2;
3057 target->backoff.times++;
3060 /* Tell GDB to halt the debugger. This allows the user to
3061 * run monitor commands to handle the situation.
3063 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3065 if (target->backoff.times > 0) {
3066 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
3067 target_reset_examined(target);
3068 retval = target_examine_one(target);
3069 /* Target examination could have failed due to unstable connection,
3070 * but we set the examined flag anyway to repoll it later */
3071 if (retval != ERROR_OK) {
3072 target_set_examined(target);
3073 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
3074 target->backoff.times * polling_interval);
3079 /* Since we succeeded, we reset backoff count */
3080 target->backoff.times = 0;
3087 COMMAND_HANDLER(handle_reg_command)
3091 struct target *target = get_current_target(CMD_CTX);
3092 struct reg *reg = NULL;
3094 /* list all available registers for the current target */
3095 if (CMD_ARGC == 0) {
3096 struct reg_cache *cache = target->reg_cache;
3098 unsigned int count = 0;
3102 command_print(CMD, "===== %s", cache->name);
3104 for (i = 0, reg = cache->reg_list;
3105 i < cache->num_regs;
3106 i++, reg++, count++) {
3107 if (reg->exist == false || reg->hidden)
3109 /* only print cached values if they are valid */
3111 char *value = buf_to_hex_str(reg->value,
3114 "(%i) %s (/%" PRIu32 "): 0x%s%s",
3122 command_print(CMD, "(%i) %s (/%" PRIu32 ")",
3127 cache = cache->next;
3133 /* access a single register by its ordinal number */
3134 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
3136 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
3138 struct reg_cache *cache = target->reg_cache;
3139 unsigned int count = 0;
3142 for (i = 0; i < cache->num_regs; i++) {
3143 if (count++ == num) {
3144 reg = &cache->reg_list[i];
3150 cache = cache->next;
3154 command_print(CMD, "%i is out of bounds, the current target "
3155 "has only %i registers (0 - %i)", num, count, count - 1);
3159 /* access a single register by its name */
3160 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], true);
3166 assert(reg); /* give clang a hint that we *know* reg is != NULL here */
3171 /* display a register */
3172 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
3173 && (CMD_ARGV[1][0] <= '9')))) {
3174 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
3177 if (reg->valid == 0) {
3178 int retval = reg->type->get(reg);
3179 if (retval != ERROR_OK) {
3180 LOG_ERROR("Could not read register '%s'", reg->name);
3184 char *value = buf_to_hex_str(reg->value, reg->size);
3185 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3190 /* set register value */
3191 if (CMD_ARGC == 2) {
3192 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
3195 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
3197 int retval = reg->type->set(reg, buf);
3198 if (retval != ERROR_OK) {
3199 LOG_ERROR("Could not write to register '%s'", reg->name);
3201 char *value = buf_to_hex_str(reg->value, reg->size);
3202 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3211 return ERROR_COMMAND_SYNTAX_ERROR;
3214 command_print(CMD, "register %s not found in current target", CMD_ARGV[0]);
3218 COMMAND_HANDLER(handle_poll_command)
3220 int retval = ERROR_OK;
3221 struct target *target = get_current_target(CMD_CTX);
3223 if (CMD_ARGC == 0) {
3224 command_print(CMD, "background polling: %s",
3225 jtag_poll_get_enabled() ? "on" : "off");
3226 command_print(CMD, "TAP: %s (%s)",
3227 target->tap->dotted_name,
3228 target->tap->enabled ? "enabled" : "disabled");
3229 if (!target->tap->enabled)
3231 retval = target_poll(target);
3232 if (retval != ERROR_OK)
3234 retval = target_arch_state(target);
3235 if (retval != ERROR_OK)
3237 } else if (CMD_ARGC == 1) {
3239 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
3240 jtag_poll_set_enabled(enable);
3242 return ERROR_COMMAND_SYNTAX_ERROR;
3247 COMMAND_HANDLER(handle_wait_halt_command)
3250 return ERROR_COMMAND_SYNTAX_ERROR;
3252 unsigned ms = DEFAULT_HALT_TIMEOUT;
3253 if (1 == CMD_ARGC) {
3254 int retval = parse_uint(CMD_ARGV[0], &ms);
3255 if (retval != ERROR_OK)
3256 return ERROR_COMMAND_SYNTAX_ERROR;
3259 struct target *target = get_current_target(CMD_CTX);
3260 return target_wait_state(target, TARGET_HALTED, ms);
3263 /* wait for target state to change. The trick here is to have a low
3264 * latency for short waits and not to suck up all the CPU time
3267 * After 500ms, keep_alive() is invoked
3269 int target_wait_state(struct target *target, enum target_state state, int ms)
3272 int64_t then = 0, cur;
3276 retval = target_poll(target);
3277 if (retval != ERROR_OK)
3279 if (target->state == state)
3284 then = timeval_ms();
3285 LOG_DEBUG("waiting for target %s...",
3286 jim_nvp_value2name_simple(nvp_target_state, state)->name);
3292 if ((cur-then) > ms) {
3293 LOG_ERROR("timed out while waiting for target %s",
3294 jim_nvp_value2name_simple(nvp_target_state, state)->name);
3302 COMMAND_HANDLER(handle_halt_command)
3306 struct target *target = get_current_target(CMD_CTX);
3308 target->verbose_halt_msg = true;
3310 int retval = target_halt(target);
3311 if (retval != ERROR_OK)
3314 if (CMD_ARGC == 1) {
3315 unsigned wait_local;
3316 retval = parse_uint(CMD_ARGV[0], &wait_local);
3317 if (retval != ERROR_OK)
3318 return ERROR_COMMAND_SYNTAX_ERROR;
3323 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
3326 COMMAND_HANDLER(handle_soft_reset_halt_command)
3328 struct target *target = get_current_target(CMD_CTX);
3330 LOG_USER("requesting target halt and executing a soft reset");
3332 target_soft_reset_halt(target);
3337 COMMAND_HANDLER(handle_reset_command)
3340 return ERROR_COMMAND_SYNTAX_ERROR;
3342 enum target_reset_mode reset_mode = RESET_RUN;
3343 if (CMD_ARGC == 1) {
3344 const struct jim_nvp *n;
3345 n = jim_nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
3346 if ((!n->name) || (n->value == RESET_UNKNOWN))
3347 return ERROR_COMMAND_SYNTAX_ERROR;
3348 reset_mode = n->value;
3351 /* reset *all* targets */
3352 return target_process_reset(CMD, reset_mode);
3356 COMMAND_HANDLER(handle_resume_command)
3360 return ERROR_COMMAND_SYNTAX_ERROR;
3362 struct target *target = get_current_target(CMD_CTX);
3364 /* with no CMD_ARGV, resume from current pc, addr = 0,
3365 * with one arguments, addr = CMD_ARGV[0],
3366 * handle breakpoints, not debugging */
3367 target_addr_t addr = 0;
3368 if (CMD_ARGC == 1) {
3369 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3373 return target_resume(target, current, addr, 1, 0);
3376 COMMAND_HANDLER(handle_step_command)
3379 return ERROR_COMMAND_SYNTAX_ERROR;
3383 /* with no CMD_ARGV, step from current pc, addr = 0,
3384 * with one argument addr = CMD_ARGV[0],
3385 * handle breakpoints, debugging */
3386 target_addr_t addr = 0;
3388 if (CMD_ARGC == 1) {
3389 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3393 struct target *target = get_current_target(CMD_CTX);
3395 return target_step(target, current_pc, addr, 1);
3398 void target_handle_md_output(struct command_invocation *cmd,
3399 struct target *target, target_addr_t address, unsigned size,
3400 unsigned count, const uint8_t *buffer)
3402 const unsigned line_bytecnt = 32;
3403 unsigned line_modulo = line_bytecnt / size;
3405 char output[line_bytecnt * 4 + 1];
3406 unsigned output_len = 0;
3408 const char *value_fmt;
3411 value_fmt = "%16.16"PRIx64" ";
3414 value_fmt = "%8.8"PRIx64" ";
3417 value_fmt = "%4.4"PRIx64" ";
3420 value_fmt = "%2.2"PRIx64" ";
3423 /* "can't happen", caller checked */
3424 LOG_ERROR("invalid memory read size: %u", size);
3428 for (unsigned i = 0; i < count; i++) {
3429 if (i % line_modulo == 0) {
3430 output_len += snprintf(output + output_len,
3431 sizeof(output) - output_len,
3432 TARGET_ADDR_FMT ": ",
3433 (address + (i * size)));
3437 const uint8_t *value_ptr = buffer + i * size;
3440 value = target_buffer_get_u64(target, value_ptr);
3443 value = target_buffer_get_u32(target, value_ptr);
3446 value = target_buffer_get_u16(target, value_ptr);
3451 output_len += snprintf(output + output_len,
3452 sizeof(output) - output_len,
3455 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
3456 command_print(cmd, "%s", output);
3462 COMMAND_HANDLER(handle_md_command)
3465 return ERROR_COMMAND_SYNTAX_ERROR;
3468 switch (CMD_NAME[2]) {
3482 return ERROR_COMMAND_SYNTAX_ERROR;
3485 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3486 int (*fn)(struct target *target,
3487 target_addr_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
3491 fn = target_read_phys_memory;
3493 fn = target_read_memory;
3494 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
3495 return ERROR_COMMAND_SYNTAX_ERROR;
3497 target_addr_t address;
3498 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3502 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3504 uint8_t *buffer = calloc(count, size);
3506 LOG_ERROR("Failed to allocate md read buffer");
3510 struct target *target = get_current_target(CMD_CTX);
3511 int retval = fn(target, address, size, count, buffer);
3512 if (retval == ERROR_OK)
3513 target_handle_md_output(CMD, target, address, size, count, buffer);
3520 typedef int (*target_write_fn)(struct target *target,
3521 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3523 static int target_fill_mem(struct target *target,
3524 target_addr_t address,
3532 /* We have to write in reasonably large chunks to be able
3533 * to fill large memory areas with any sane speed */
3534 const unsigned chunk_size = 16384;
3535 uint8_t *target_buf = malloc(chunk_size * data_size);
3537 LOG_ERROR("Out of memory");
3541 for (unsigned i = 0; i < chunk_size; i++) {
3542 switch (data_size) {
3544 target_buffer_set_u64(target, target_buf + i * data_size, b);
3547 target_buffer_set_u32(target, target_buf + i * data_size, b);
3550 target_buffer_set_u16(target, target_buf + i * data_size, b);
3553 target_buffer_set_u8(target, target_buf + i * data_size, b);
3560 int retval = ERROR_OK;
3562 for (unsigned x = 0; x < c; x += chunk_size) {
3565 if (current > chunk_size)
3566 current = chunk_size;
3567 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3568 if (retval != ERROR_OK)
3570 /* avoid GDB timeouts */
3579 COMMAND_HANDLER(handle_mw_command)
3582 return ERROR_COMMAND_SYNTAX_ERROR;
3583 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3588 fn = target_write_phys_memory;
3590 fn = target_write_memory;
3591 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3592 return ERROR_COMMAND_SYNTAX_ERROR;
3594 target_addr_t address;
3595 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3598 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[1], value);
3602 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3604 struct target *target = get_current_target(CMD_CTX);
3606 switch (CMD_NAME[2]) {
3620 return ERROR_COMMAND_SYNTAX_ERROR;
3623 return target_fill_mem(target, address, fn, wordsize, value, count);
3626 static COMMAND_HELPER(parse_load_image_command, struct image *image,
3627 target_addr_t *min_address, target_addr_t *max_address)
3629 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3630 return ERROR_COMMAND_SYNTAX_ERROR;
3632 /* a base address isn't always necessary,
3633 * default to 0x0 (i.e. don't relocate) */
3634 if (CMD_ARGC >= 2) {
3636 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3637 image->base_address = addr;
3638 image->base_address_set = true;
3640 image->base_address_set = false;
3642 image->start_address_set = false;
3645 COMMAND_PARSE_ADDRESS(CMD_ARGV[3], *min_address);
3646 if (CMD_ARGC == 5) {
3647 COMMAND_PARSE_ADDRESS(CMD_ARGV[4], *max_address);
3648 /* use size (given) to find max (required) */
3649 *max_address += *min_address;
3652 if (*min_address > *max_address)
3653 return ERROR_COMMAND_SYNTAX_ERROR;
3658 COMMAND_HANDLER(handle_load_image_command)
3662 uint32_t image_size;
3663 target_addr_t min_address = 0;
3664 target_addr_t max_address = -1;
3667 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
3668 &image, &min_address, &max_address);
3669 if (retval != ERROR_OK)
3672 struct target *target = get_current_target(CMD_CTX);
3674 struct duration bench;
3675 duration_start(&bench);
3677 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3682 for (unsigned int i = 0; i < image.num_sections; i++) {
3683 buffer = malloc(image.sections[i].size);
3686 "error allocating buffer for section (%d bytes)",
3687 (int)(image.sections[i].size));
3688 retval = ERROR_FAIL;
3692 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3693 if (retval != ERROR_OK) {
3698 uint32_t offset = 0;
3699 uint32_t length = buf_cnt;
3701 /* DANGER!!! beware of unsigned comparison here!!! */
3703 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3704 (image.sections[i].base_address < max_address)) {
3706 if (image.sections[i].base_address < min_address) {
3707 /* clip addresses below */
3708 offset += min_address-image.sections[i].base_address;
3712 if (image.sections[i].base_address + buf_cnt > max_address)
3713 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3715 retval = target_write_buffer(target,
3716 image.sections[i].base_address + offset, length, buffer + offset);
3717 if (retval != ERROR_OK) {
3721 image_size += length;
3722 command_print(CMD, "%u bytes written at address " TARGET_ADDR_FMT "",
3723 (unsigned int)length,
3724 image.sections[i].base_address + offset);
3730 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3731 command_print(CMD, "downloaded %" PRIu32 " bytes "
3732 "in %fs (%0.3f KiB/s)", image_size,
3733 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3736 image_close(&image);
3742 COMMAND_HANDLER(handle_dump_image_command)
3744 struct fileio *fileio;
3746 int retval, retvaltemp;
3747 target_addr_t address, size;
3748 struct duration bench;
3749 struct target *target = get_current_target(CMD_CTX);
3752 return ERROR_COMMAND_SYNTAX_ERROR;
3754 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], address);
3755 COMMAND_PARSE_ADDRESS(CMD_ARGV[2], size);
3757 uint32_t buf_size = (size > 4096) ? 4096 : size;
3758 buffer = malloc(buf_size);
3762 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3763 if (retval != ERROR_OK) {
3768 duration_start(&bench);
3771 size_t size_written;
3772 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3773 retval = target_read_buffer(target, address, this_run_size, buffer);
3774 if (retval != ERROR_OK)
3777 retval = fileio_write(fileio, this_run_size, buffer, &size_written);
3778 if (retval != ERROR_OK)
3781 size -= this_run_size;
3782 address += this_run_size;
3787 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3789 retval = fileio_size(fileio, &filesize);
3790 if (retval != ERROR_OK)
3793 "dumped %zu bytes in %fs (%0.3f KiB/s)", filesize,
3794 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3797 retvaltemp = fileio_close(fileio);
3798 if (retvaltemp != ERROR_OK)
3807 IMAGE_CHECKSUM_ONLY = 2
3810 static COMMAND_HELPER(handle_verify_image_command_internal, enum verify_mode verify)
3814 uint32_t image_size;
3816 uint32_t checksum = 0;
3817 uint32_t mem_checksum = 0;
3821 struct target *target = get_current_target(CMD_CTX);
3824 return ERROR_COMMAND_SYNTAX_ERROR;
3827 LOG_ERROR("no target selected");
3831 struct duration bench;
3832 duration_start(&bench);
3834 if (CMD_ARGC >= 2) {
3836 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3837 image.base_address = addr;
3838 image.base_address_set = true;
3840 image.base_address_set = false;
3841 image.base_address = 0x0;
3844 image.start_address_set = false;
3846 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3847 if (retval != ERROR_OK)
3853 for (unsigned int i = 0; i < image.num_sections; i++) {
3854 buffer = malloc(image.sections[i].size);
3857 "error allocating buffer for section (%" PRIu32 " bytes)",
3858 image.sections[i].size);
3861 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3862 if (retval != ERROR_OK) {
3867 if (verify >= IMAGE_VERIFY) {
3868 /* calculate checksum of image */
3869 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3870 if (retval != ERROR_OK) {
3875 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3876 if (retval != ERROR_OK) {
3880 if ((checksum != mem_checksum) && (verify == IMAGE_CHECKSUM_ONLY)) {
3881 LOG_ERROR("checksum mismatch");
3883 retval = ERROR_FAIL;
3886 if (checksum != mem_checksum) {
3887 /* failed crc checksum, fall back to a binary compare */
3891 LOG_ERROR("checksum mismatch - attempting binary compare");
3893 data = malloc(buf_cnt);
3895 retval = target_read_buffer(target, image.sections[i].base_address, buf_cnt, data);
3896 if (retval == ERROR_OK) {
3898 for (t = 0; t < buf_cnt; t++) {
3899 if (data[t] != buffer[t]) {
3901 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3903 (unsigned)(t + image.sections[i].base_address),
3906 if (diffs++ >= 127) {
3907 command_print(CMD, "More than 128 errors, the rest are not printed.");
3919 command_print(CMD, "address " TARGET_ADDR_FMT " length 0x%08zx",
3920 image.sections[i].base_address,
3925 image_size += buf_cnt;
3928 command_print(CMD, "No more differences found.");
3931 retval = ERROR_FAIL;
3932 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3933 command_print(CMD, "verified %" PRIu32 " bytes "
3934 "in %fs (%0.3f KiB/s)", image_size,
3935 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3938 image_close(&image);
3943 COMMAND_HANDLER(handle_verify_image_checksum_command)
3945 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_CHECKSUM_ONLY);
3948 COMMAND_HANDLER(handle_verify_image_command)
3950 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_VERIFY);
3953 COMMAND_HANDLER(handle_test_image_command)
3955 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_TEST);
3958 static int handle_bp_command_list(struct command_invocation *cmd)
3960 struct target *target = get_current_target(cmd->ctx);
3961 struct breakpoint *breakpoint = target->breakpoints;
3962 while (breakpoint) {
3963 if (breakpoint->type == BKPT_SOFT) {
3964 char *buf = buf_to_hex_str(breakpoint->orig_instr,
3965 breakpoint->length);
3966 command_print(cmd, "IVA breakpoint: " TARGET_ADDR_FMT ", 0x%x, %i, 0x%s",
3967 breakpoint->address,
3969 breakpoint->set, buf);
3972 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3973 command_print(cmd, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3975 breakpoint->length, breakpoint->set);
3976 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3977 command_print(cmd, "Hybrid breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3978 breakpoint->address,
3979 breakpoint->length, breakpoint->set);
3980 command_print(cmd, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3983 command_print(cmd, "Breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3984 breakpoint->address,
3985 breakpoint->length, breakpoint->set);
3988 breakpoint = breakpoint->next;
3993 static int handle_bp_command_set(struct command_invocation *cmd,
3994 target_addr_t addr, uint32_t asid, uint32_t length, int hw)
3996 struct target *target = get_current_target(cmd->ctx);
4000 retval = breakpoint_add(target, addr, length, hw);
4001 /* error is always logged in breakpoint_add(), do not print it again */
4002 if (retval == ERROR_OK)
4003 command_print(cmd, "breakpoint set at " TARGET_ADDR_FMT "", addr);
4005 } else if (addr == 0) {
4006 if (!target->type->add_context_breakpoint) {
4007 LOG_ERROR("Context breakpoint not available");
4008 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
4010 retval = context_breakpoint_add(target, asid, length, hw);
4011 /* error is always logged in context_breakpoint_add(), do not print it again */
4012 if (retval == ERROR_OK)
4013 command_print(cmd, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
4016 if (!target->type->add_hybrid_breakpoint) {
4017 LOG_ERROR("Hybrid breakpoint not available");
4018 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
4020 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
4021 /* error is always logged in hybrid_breakpoint_add(), do not print it again */
4022 if (retval == ERROR_OK)
4023 command_print(cmd, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
4028 COMMAND_HANDLER(handle_bp_command)
4037 return handle_bp_command_list(CMD);
4041 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4042 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4043 return handle_bp_command_set(CMD, addr, asid, length, hw);
4046 if (strcmp(CMD_ARGV[2], "hw") == 0) {
4048 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4049 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4051 return handle_bp_command_set(CMD, addr, asid, length, hw);
4052 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
4054 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
4055 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4057 return handle_bp_command_set(CMD, addr, asid, length, hw);
4062 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4063 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
4064 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
4065 return handle_bp_command_set(CMD, addr, asid, length, hw);
4068 return ERROR_COMMAND_SYNTAX_ERROR;
4072 COMMAND_HANDLER(handle_rbp_command)
4075 return ERROR_COMMAND_SYNTAX_ERROR;
4077 struct target *target = get_current_target(CMD_CTX);
4079 if (!strcmp(CMD_ARGV[0], "all")) {
4080 breakpoint_remove_all(target);
4083 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4085 breakpoint_remove(target, addr);
4091 COMMAND_HANDLER(handle_wp_command)
4093 struct target *target = get_current_target(CMD_CTX);
4095 if (CMD_ARGC == 0) {
4096 struct watchpoint *watchpoint = target->watchpoints;
4098 while (watchpoint) {
4099 command_print(CMD, "address: " TARGET_ADDR_FMT
4100 ", len: 0x%8.8" PRIx32
4101 ", r/w/a: %i, value: 0x%8.8" PRIx32
4102 ", mask: 0x%8.8" PRIx32,
4103 watchpoint->address,
4105 (int)watchpoint->rw,
4108 watchpoint = watchpoint->next;
4113 enum watchpoint_rw type = WPT_ACCESS;
4114 target_addr_t addr = 0;
4115 uint32_t length = 0;
4116 uint32_t data_value = 0x0;
4117 uint32_t data_mask = 0xffffffff;
4121 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
4124 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
4127 switch (CMD_ARGV[2][0]) {
4138 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
4139 return ERROR_COMMAND_SYNTAX_ERROR;
4143 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4144 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4148 return ERROR_COMMAND_SYNTAX_ERROR;
4151 int retval = watchpoint_add(target, addr, length, type,
4152 data_value, data_mask);
4153 if (retval != ERROR_OK)
4154 LOG_ERROR("Failure setting watchpoints");
4159 COMMAND_HANDLER(handle_rwp_command)
4162 return ERROR_COMMAND_SYNTAX_ERROR;
4165 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4167 struct target *target = get_current_target(CMD_CTX);
4168 watchpoint_remove(target, addr);
4174 * Translate a virtual address to a physical address.
4176 * The low-level target implementation must have logged a detailed error
4177 * which is forwarded to telnet/GDB session.
4179 COMMAND_HANDLER(handle_virt2phys_command)
4182 return ERROR_COMMAND_SYNTAX_ERROR;
4185 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], va);
4188 struct target *target = get_current_target(CMD_CTX);
4189 int retval = target->type->virt2phys(target, va, &pa);
4190 if (retval == ERROR_OK)
4191 command_print(CMD, "Physical address " TARGET_ADDR_FMT "", pa);
4196 static void write_data(FILE *f, const void *data, size_t len)
4198 size_t written = fwrite(data, 1, len, f);
4200 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
4203 static void write_long(FILE *f, int l, struct target *target)
4207 target_buffer_set_u32(target, val, l);
4208 write_data(f, val, 4);
4211 static void write_string(FILE *f, char *s)
4213 write_data(f, s, strlen(s));
4216 typedef unsigned char UNIT[2]; /* unit of profiling */
4218 /* Dump a gmon.out histogram file. */
4219 static void write_gmon(uint32_t *samples, uint32_t sample_num, const char *filename, bool with_range,
4220 uint32_t start_address, uint32_t end_address, struct target *target, uint32_t duration_ms)
4223 FILE *f = fopen(filename, "w");
4226 write_string(f, "gmon");
4227 write_long(f, 0x00000001, target); /* Version */
4228 write_long(f, 0, target); /* padding */
4229 write_long(f, 0, target); /* padding */
4230 write_long(f, 0, target); /* padding */
4232 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
4233 write_data(f, &zero, 1);
4235 /* figure out bucket size */
4239 min = start_address;
4244 for (i = 0; i < sample_num; i++) {
4245 if (min > samples[i])
4247 if (max < samples[i])
4251 /* max should be (largest sample + 1)
4252 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
4256 int address_space = max - min;
4257 assert(address_space >= 2);
4259 /* FIXME: What is the reasonable number of buckets?
4260 * The profiling result will be more accurate if there are enough buckets. */
4261 static const uint32_t max_buckets = 128 * 1024; /* maximum buckets. */
4262 uint32_t num_buckets = address_space / sizeof(UNIT);
4263 if (num_buckets > max_buckets)
4264 num_buckets = max_buckets;
4265 int *buckets = malloc(sizeof(int) * num_buckets);
4270 memset(buckets, 0, sizeof(int) * num_buckets);
4271 for (i = 0; i < sample_num; i++) {
4272 uint32_t address = samples[i];
4274 if ((address < min) || (max <= address))
4277 long long a = address - min;
4278 long long b = num_buckets;
4279 long long c = address_space;
4280 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
4284 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
4285 write_long(f, min, target); /* low_pc */
4286 write_long(f, max, target); /* high_pc */
4287 write_long(f, num_buckets, target); /* # of buckets */
4288 float sample_rate = sample_num / (duration_ms / 1000.0);
4289 write_long(f, sample_rate, target);
4290 write_string(f, "seconds");
4291 for (i = 0; i < (15-strlen("seconds")); i++)
4292 write_data(f, &zero, 1);
4293 write_string(f, "s");
4295 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
4297 char *data = malloc(2 * num_buckets);
4299 for (i = 0; i < num_buckets; i++) {
4304 data[i * 2] = val&0xff;
4305 data[i * 2 + 1] = (val >> 8) & 0xff;
4308 write_data(f, data, num_buckets * 2);
4316 /* profiling samples the CPU PC as quickly as OpenOCD is able,
4317 * which will be used as a random sampling of PC */
4318 COMMAND_HANDLER(handle_profile_command)
4320 struct target *target = get_current_target(CMD_CTX);
4322 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
4323 return ERROR_COMMAND_SYNTAX_ERROR;
4325 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
4327 uint32_t num_of_samples;
4328 int retval = ERROR_OK;
4329 bool halted_before_profiling = target->state == TARGET_HALTED;
4331 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
4333 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
4335 LOG_ERROR("No memory to store samples.");
4339 uint64_t timestart_ms = timeval_ms();
4341 * Some cores let us sample the PC without the
4342 * annoying halt/resume step; for example, ARMv7 PCSR.
4343 * Provide a way to use that more efficient mechanism.
4345 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
4346 &num_of_samples, offset);
4347 if (retval != ERROR_OK) {
4351 uint32_t duration_ms = timeval_ms() - timestart_ms;
4353 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
4355 retval = target_poll(target);
4356 if (retval != ERROR_OK) {
4361 if (target->state == TARGET_RUNNING && halted_before_profiling) {
4362 /* The target was halted before we started and is running now. Halt it,
4363 * for consistency. */
4364 retval = target_halt(target);
4365 if (retval != ERROR_OK) {
4369 } else if (target->state == TARGET_HALTED && !halted_before_profiling) {
4370 /* The target was running before we started and is halted now. Resume
4371 * it, for consistency. */
4372 retval = target_resume(target, 1, 0, 0, 0);
4373 if (retval != ERROR_OK) {
4379 retval = target_poll(target);
4380 if (retval != ERROR_OK) {
4385 uint32_t start_address = 0;
4386 uint32_t end_address = 0;
4387 bool with_range = false;
4388 if (CMD_ARGC == 4) {
4390 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
4391 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
4394 write_gmon(samples, num_of_samples, CMD_ARGV[1],
4395 with_range, start_address, end_address, target, duration_ms);
4396 command_print(CMD, "Wrote %s", CMD_ARGV[1]);
4402 static int new_u64_array_element(Jim_Interp *interp, const char *varname, int idx, uint64_t val)
4405 Jim_Obj *obj_name, *obj_val;
4408 namebuf = alloc_printf("%s(%d)", varname, idx);
4412 obj_name = Jim_NewStringObj(interp, namebuf, -1);
4413 jim_wide wide_val = val;
4414 obj_val = Jim_NewWideObj(interp, wide_val);
4415 if (!obj_name || !obj_val) {
4420 Jim_IncrRefCount(obj_name);
4421 Jim_IncrRefCount(obj_val);
4422 result = Jim_SetVariable(interp, obj_name, obj_val);
4423 Jim_DecrRefCount(interp, obj_name);
4424 Jim_DecrRefCount(interp, obj_val);
4426 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
4430 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4432 struct command_context *context;
4433 struct target *target;
4435 context = current_command_context(interp);
4438 target = get_current_target(context);
4440 LOG_ERROR("mem2array: no current target");
4444 return target_mem2array(interp, target, argc - 1, argv + 1);
4447 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
4451 /* argv[0] = name of array to receive the data
4452 * argv[1] = desired element width in bits
4453 * argv[2] = memory address
4454 * argv[3] = count of times to read
4455 * argv[4] = optional "phys"
4457 if (argc < 4 || argc > 5) {
4458 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4462 /* Arg 0: Name of the array variable */
4463 const char *varname = Jim_GetString(argv[0], NULL);
4465 /* Arg 1: Bit width of one element */
4467 e = Jim_GetLong(interp, argv[1], &l);
4470 const unsigned int width_bits = l;
4472 if (width_bits != 8 &&
4476 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4477 Jim_AppendStrings(interp, Jim_GetResult(interp),
4478 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4481 const unsigned int width = width_bits / 8;
4483 /* Arg 2: Memory address */
4485 e = Jim_GetWide(interp, argv[2], &wide_addr);
4488 target_addr_t addr = (target_addr_t)wide_addr;
4490 /* Arg 3: Number of elements to read */
4491 e = Jim_GetLong(interp, argv[3], &l);
4497 bool is_phys = false;
4500 const char *phys = Jim_GetString(argv[4], &str_len);
4501 if (!strncmp(phys, "phys", str_len))
4507 /* Argument checks */
4509 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4510 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
4513 if ((addr + (len * width)) < addr) {
4514 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4515 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
4519 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4520 Jim_AppendStrings(interp, Jim_GetResult(interp),
4521 "mem2array: too large read request, exceeds 64K items", NULL);
4526 ((width == 2) && ((addr & 1) == 0)) ||
4527 ((width == 4) && ((addr & 3) == 0)) ||
4528 ((width == 8) && ((addr & 7) == 0))) {
4529 /* alignment correct */
4532 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4533 sprintf(buf, "mem2array address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4536 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4545 const size_t buffersize = 4096;
4546 uint8_t *buffer = malloc(buffersize);
4553 /* Slurp... in buffer size chunks */
4554 const unsigned int max_chunk_len = buffersize / width;
4555 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4559 retval = target_read_phys_memory(target, addr, width, chunk_len, buffer);
4561 retval = target_read_memory(target, addr, width, chunk_len, buffer);
4562 if (retval != ERROR_OK) {
4564 LOG_ERROR("mem2array: Read @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4568 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4569 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
4573 for (size_t i = 0; i < chunk_len ; i++, idx++) {
4577 v = target_buffer_get_u64(target, &buffer[i*width]);
4580 v = target_buffer_get_u32(target, &buffer[i*width]);
4583 v = target_buffer_get_u16(target, &buffer[i*width]);
4586 v = buffer[i] & 0x0ff;
4589 new_u64_array_element(interp, varname, idx, v);
4592 addr += chunk_len * width;
4598 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4603 static int get_u64_array_element(Jim_Interp *interp, const char *varname, size_t idx, uint64_t *val)
4605 char *namebuf = alloc_printf("%s(%zu)", varname, idx);
4609 Jim_Obj *obj_name = Jim_NewStringObj(interp, namebuf, -1);
4615 Jim_IncrRefCount(obj_name);
4616 Jim_Obj *obj_val = Jim_GetVariable(interp, obj_name, JIM_ERRMSG);
4617 Jim_DecrRefCount(interp, obj_name);
4623 int result = Jim_GetWide(interp, obj_val, &wide_val);
4628 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4630 struct command_context *context;
4631 struct target *target;
4633 context = current_command_context(interp);
4636 target = get_current_target(context);
4638 LOG_ERROR("array2mem: no current target");
4642 return target_array2mem(interp, target, argc-1, argv + 1);
4645 static int target_array2mem(Jim_Interp *interp, struct target *target,
4646 int argc, Jim_Obj *const *argv)
4650 /* argv[0] = name of array from which to read the data
4651 * argv[1] = desired element width in bits
4652 * argv[2] = memory address
4653 * argv[3] = number of elements to write
4654 * argv[4] = optional "phys"
4656 if (argc < 4 || argc > 5) {
4657 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4661 /* Arg 0: Name of the array variable */
4662 const char *varname = Jim_GetString(argv[0], NULL);
4664 /* Arg 1: Bit width of one element */
4666 e = Jim_GetLong(interp, argv[1], &l);
4669 const unsigned int width_bits = l;
4671 if (width_bits != 8 &&
4675 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4676 Jim_AppendStrings(interp, Jim_GetResult(interp),
4677 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4680 const unsigned int width = width_bits / 8;
4682 /* Arg 2: Memory address */
4684 e = Jim_GetWide(interp, argv[2], &wide_addr);
4687 target_addr_t addr = (target_addr_t)wide_addr;
4689 /* Arg 3: Number of elements to write */
4690 e = Jim_GetLong(interp, argv[3], &l);
4696 bool is_phys = false;
4699 const char *phys = Jim_GetString(argv[4], &str_len);
4700 if (!strncmp(phys, "phys", str_len))
4706 /* Argument checks */
4708 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4709 Jim_AppendStrings(interp, Jim_GetResult(interp),
4710 "array2mem: zero width read?", NULL);
4714 if ((addr + (len * width)) < addr) {
4715 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4716 Jim_AppendStrings(interp, Jim_GetResult(interp),
4717 "array2mem: addr + len - wraps to zero?", NULL);
4722 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4723 Jim_AppendStrings(interp, Jim_GetResult(interp),
4724 "array2mem: too large memory write request, exceeds 64K items", NULL);
4729 ((width == 2) && ((addr & 1) == 0)) ||
4730 ((width == 4) && ((addr & 3) == 0)) ||
4731 ((width == 8) && ((addr & 7) == 0))) {
4732 /* alignment correct */
4735 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4736 sprintf(buf, "array2mem address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4739 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4748 const size_t buffersize = 4096;
4749 uint8_t *buffer = malloc(buffersize);
4757 /* Slurp... in buffer size chunks */
4758 const unsigned int max_chunk_len = buffersize / width;
4760 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4762 /* Fill the buffer */
4763 for (size_t i = 0; i < chunk_len; i++, idx++) {
4765 if (get_u64_array_element(interp, varname, idx, &v) != JIM_OK) {
4771 target_buffer_set_u64(target, &buffer[i * width], v);
4774 target_buffer_set_u32(target, &buffer[i * width], v);
4777 target_buffer_set_u16(target, &buffer[i * width], v);
4780 buffer[i] = v & 0x0ff;
4786 /* Write the buffer to memory */
4789 retval = target_write_phys_memory(target, addr, width, chunk_len, buffer);
4791 retval = target_write_memory(target, addr, width, chunk_len, buffer);
4792 if (retval != ERROR_OK) {
4794 LOG_ERROR("array2mem: Write @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4798 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4799 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4803 addr += chunk_len * width;
4808 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4813 /* FIX? should we propagate errors here rather than printing them
4816 void target_handle_event(struct target *target, enum target_event e)
4818 struct target_event_action *teap;
4821 for (teap = target->event_action; teap; teap = teap->next) {
4822 if (teap->event == e) {
4823 LOG_DEBUG("target(%d): %s (%s) event: %d (%s) action: %s",
4824 target->target_number,
4825 target_name(target),
4826 target_type_name(target),
4828 target_event_name(e),
4829 Jim_GetString(teap->body, NULL));
4831 /* Override current target by the target an event
4832 * is issued from (lot of scripts need it).
4833 * Return back to previous override as soon
4834 * as the handler processing is done */
4835 struct command_context *cmd_ctx = current_command_context(teap->interp);
4836 struct target *saved_target_override = cmd_ctx->current_target_override;
4837 cmd_ctx->current_target_override = target;
4839 retval = Jim_EvalObj(teap->interp, teap->body);
4841 cmd_ctx->current_target_override = saved_target_override;
4843 if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
4846 if (retval == JIM_RETURN)
4847 retval = teap->interp->returnCode;
4849 if (retval != JIM_OK) {
4850 Jim_MakeErrorMessage(teap->interp);
4851 LOG_USER("Error executing event %s on target %s:\n%s",
4852 target_event_name(e),
4853 target_name(target),
4854 Jim_GetString(Jim_GetResult(teap->interp), NULL));
4855 /* clean both error code and stacktrace before return */
4856 Jim_Eval(teap->interp, "error \"\" \"\"");
4863 * Returns true only if the target has a handler for the specified event.
4865 bool target_has_event_action(struct target *target, enum target_event event)
4867 struct target_event_action *teap;
4869 for (teap = target->event_action; teap; teap = teap->next) {
4870 if (teap->event == event)
4876 enum target_cfg_param {
4879 TCFG_WORK_AREA_VIRT,
4880 TCFG_WORK_AREA_PHYS,
4881 TCFG_WORK_AREA_SIZE,
4882 TCFG_WORK_AREA_BACKUP,
4885 TCFG_CHAIN_POSITION,
4890 TCFG_GDB_MAX_CONNECTIONS,
4893 static struct jim_nvp nvp_config_opts[] = {
4894 { .name = "-type", .value = TCFG_TYPE },
4895 { .name = "-event", .value = TCFG_EVENT },
4896 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4897 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4898 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4899 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4900 { .name = "-endian", .value = TCFG_ENDIAN },
4901 { .name = "-coreid", .value = TCFG_COREID },
4902 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4903 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4904 { .name = "-rtos", .value = TCFG_RTOS },
4905 { .name = "-defer-examine", .value = TCFG_DEFER_EXAMINE },
4906 { .name = "-gdb-port", .value = TCFG_GDB_PORT },
4907 { .name = "-gdb-max-connections", .value = TCFG_GDB_MAX_CONNECTIONS },
4908 { .name = NULL, .value = -1 }
4911 static int target_configure(struct jim_getopt_info *goi, struct target *target)
4918 /* parse config or cget options ... */
4919 while (goi->argc > 0) {
4920 Jim_SetEmptyResult(goi->interp);
4921 /* jim_getopt_debug(goi); */
4923 if (target->type->target_jim_configure) {
4924 /* target defines a configure function */
4925 /* target gets first dibs on parameters */
4926 e = (*(target->type->target_jim_configure))(target, goi);
4935 /* otherwise we 'continue' below */
4937 e = jim_getopt_nvp(goi, nvp_config_opts, &n);
4939 jim_getopt_nvp_unknown(goi, nvp_config_opts, 0);
4945 if (goi->isconfigure) {
4946 Jim_SetResultFormatted(goi->interp,
4947 "not settable: %s", n->name);
4951 if (goi->argc != 0) {
4952 Jim_WrongNumArgs(goi->interp,
4953 goi->argc, goi->argv,
4958 Jim_SetResultString(goi->interp,
4959 target_type_name(target), -1);
4963 if (goi->argc == 0) {
4964 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4968 e = jim_getopt_nvp(goi, nvp_target_event, &n);
4970 jim_getopt_nvp_unknown(goi, nvp_target_event, 1);
4974 if (goi->isconfigure) {
4975 if (goi->argc != 1) {
4976 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4980 if (goi->argc != 0) {
4981 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4987 struct target_event_action *teap;
4989 teap = target->event_action;
4990 /* replace existing? */
4992 if (teap->event == (enum target_event)n->value)
4997 if (goi->isconfigure) {
4998 /* START_DEPRECATED_TPIU */
4999 if (n->value == TARGET_EVENT_TRACE_CONFIG)
5000 LOG_INFO("DEPRECATED target event %s; use TPIU events {pre,post}-{enable,disable}", n->name);
5001 /* END_DEPRECATED_TPIU */
5003 bool replace = true;
5006 teap = calloc(1, sizeof(*teap));
5009 teap->event = n->value;
5010 teap->interp = goi->interp;
5011 jim_getopt_obj(goi, &o);
5013 Jim_DecrRefCount(teap->interp, teap->body);
5014 teap->body = Jim_DuplicateObj(goi->interp, o);
5017 * Tcl/TK - "tk events" have a nice feature.
5018 * See the "BIND" command.
5019 * We should support that here.
5020 * You can specify %X and %Y in the event code.
5021 * The idea is: %T - target name.
5022 * The idea is: %N - target number
5023 * The idea is: %E - event name.
5025 Jim_IncrRefCount(teap->body);
5028 /* add to head of event list */
5029 teap->next = target->event_action;
5030 target->event_action = teap;
5032 Jim_SetEmptyResult(goi->interp);
5036 Jim_SetEmptyResult(goi->interp);
5038 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
5044 case TCFG_WORK_AREA_VIRT:
5045 if (goi->isconfigure) {
5046 target_free_all_working_areas(target);
5047 e = jim_getopt_wide(goi, &w);
5050 target->working_area_virt = w;
5051 target->working_area_virt_spec = true;
5056 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
5060 case TCFG_WORK_AREA_PHYS:
5061 if (goi->isconfigure) {
5062 target_free_all_working_areas(target);
5063 e = jim_getopt_wide(goi, &w);
5066 target->working_area_phys = w;
5067 target->working_area_phys_spec = true;
5072 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
5076 case TCFG_WORK_AREA_SIZE:
5077 if (goi->isconfigure) {
5078 target_free_all_working_areas(target);
5079 e = jim_getopt_wide(goi, &w);
5082 target->working_area_size = w;
5087 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
5091 case TCFG_WORK_AREA_BACKUP:
5092 if (goi->isconfigure) {
5093 target_free_all_working_areas(target);
5094 e = jim_getopt_wide(goi, &w);
5097 /* make this exactly 1 or 0 */
5098 target->backup_working_area = (!!w);
5103 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
5104 /* loop for more e*/
5109 if (goi->isconfigure) {
5110 e = jim_getopt_nvp(goi, nvp_target_endian, &n);
5112 jim_getopt_nvp_unknown(goi, nvp_target_endian, 1);
5115 target->endianness = n->value;
5120 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5122 target->endianness = TARGET_LITTLE_ENDIAN;
5123 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5125 Jim_SetResultString(goi->interp, n->name, -1);
5130 if (goi->isconfigure) {
5131 e = jim_getopt_wide(goi, &w);
5134 target->coreid = (int32_t)w;
5139 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->coreid));
5143 case TCFG_CHAIN_POSITION:
5144 if (goi->isconfigure) {
5146 struct jtag_tap *tap;
5148 if (target->has_dap) {
5149 Jim_SetResultString(goi->interp,
5150 "target requires -dap parameter instead of -chain-position!", -1);
5154 target_free_all_working_areas(target);
5155 e = jim_getopt_obj(goi, &o_t);
5158 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
5162 target->tap_configured = true;
5167 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
5168 /* loop for more e*/
5171 if (goi->isconfigure) {
5172 e = jim_getopt_wide(goi, &w);
5175 target->dbgbase = (uint32_t)w;
5176 target->dbgbase_set = true;
5181 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
5187 int result = rtos_create(goi, target);
5188 if (result != JIM_OK)
5194 case TCFG_DEFER_EXAMINE:
5196 target->defer_examine = true;
5201 if (goi->isconfigure) {
5202 struct command_context *cmd_ctx = current_command_context(goi->interp);
5203 if (cmd_ctx->mode != COMMAND_CONFIG) {
5204 Jim_SetResultString(goi->interp, "-gdb-port must be configured before 'init'", -1);
5209 e = jim_getopt_string(goi, &s, NULL);
5212 free(target->gdb_port_override);
5213 target->gdb_port_override = strdup(s);
5218 Jim_SetResultString(goi->interp, target->gdb_port_override ? target->gdb_port_override : "undefined", -1);
5222 case TCFG_GDB_MAX_CONNECTIONS:
5223 if (goi->isconfigure) {
5224 struct command_context *cmd_ctx = current_command_context(goi->interp);
5225 if (cmd_ctx->mode != COMMAND_CONFIG) {
5226 Jim_SetResultString(goi->interp, "-gdb-max-connections must be configured before 'init'", -1);
5230 e = jim_getopt_wide(goi, &w);
5233 target->gdb_max_connections = (w < 0) ? CONNECTION_LIMIT_UNLIMITED : (int)w;
5238 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->gdb_max_connections));
5241 } /* while (goi->argc) */
5244 /* done - we return */
5248 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5250 struct command *c = jim_to_command(interp);
5251 struct jim_getopt_info goi;
5253 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5254 goi.isconfigure = !strcmp(c->name, "configure");
5256 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5257 "missing: -option ...");
5260 struct command_context *cmd_ctx = current_command_context(interp);
5262 struct target *target = get_current_target(cmd_ctx);
5263 return target_configure(&goi, target);
5266 static int jim_target_mem2array(Jim_Interp *interp,
5267 int argc, Jim_Obj *const *argv)
5269 struct command_context *cmd_ctx = current_command_context(interp);
5271 struct target *target = get_current_target(cmd_ctx);
5272 return target_mem2array(interp, target, argc - 1, argv + 1);
5275 static int jim_target_array2mem(Jim_Interp *interp,
5276 int argc, Jim_Obj *const *argv)
5278 struct command_context *cmd_ctx = current_command_context(interp);
5280 struct target *target = get_current_target(cmd_ctx);
5281 return target_array2mem(interp, target, argc - 1, argv + 1);
5284 static int jim_target_tap_disabled(Jim_Interp *interp)
5286 Jim_SetResultFormatted(interp, "[TAP is disabled]");
5290 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5292 bool allow_defer = false;
5294 struct jim_getopt_info goi;
5295 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5297 const char *cmd_name = Jim_GetString(argv[0], NULL);
5298 Jim_SetResultFormatted(goi.interp,
5299 "usage: %s ['allow-defer']", cmd_name);
5303 strcmp(Jim_GetString(argv[1], NULL), "allow-defer") == 0) {
5306 int e = jim_getopt_obj(&goi, &obj);
5312 struct command_context *cmd_ctx = current_command_context(interp);
5314 struct target *target = get_current_target(cmd_ctx);
5315 if (!target->tap->enabled)
5316 return jim_target_tap_disabled(interp);
5318 if (allow_defer && target->defer_examine) {
5319 LOG_INFO("Deferring arp_examine of %s", target_name(target));
5320 LOG_INFO("Use arp_examine command to examine it manually!");
5324 int e = target->type->examine(target);
5325 if (e != ERROR_OK) {
5326 target_reset_examined(target);
5330 target_set_examined(target);
5335 static int jim_target_was_examined(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5337 struct command_context *cmd_ctx = current_command_context(interp);
5339 struct target *target = get_current_target(cmd_ctx);
5341 Jim_SetResultBool(interp, target_was_examined(target));
5345 static int jim_target_examine_deferred(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5347 struct command_context *cmd_ctx = current_command_context(interp);
5349 struct target *target = get_current_target(cmd_ctx);
5351 Jim_SetResultBool(interp, target->defer_examine);
5355 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5358 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5361 struct command_context *cmd_ctx = current_command_context(interp);
5363 struct target *target = get_current_target(cmd_ctx);
5365 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
5371 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5374 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5377 struct command_context *cmd_ctx = current_command_context(interp);
5379 struct target *target = get_current_target(cmd_ctx);
5380 if (!target->tap->enabled)
5381 return jim_target_tap_disabled(interp);
5384 if (!(target_was_examined(target)))
5385 e = ERROR_TARGET_NOT_EXAMINED;
5387 e = target->type->poll(target);
5393 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5395 struct jim_getopt_info goi;
5396 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5398 if (goi.argc != 2) {
5399 Jim_WrongNumArgs(interp, 0, argv,
5400 "([tT]|[fF]|assert|deassert) BOOL");
5405 int e = jim_getopt_nvp(&goi, nvp_assert, &n);
5407 jim_getopt_nvp_unknown(&goi, nvp_assert, 1);
5410 /* the halt or not param */
5412 e = jim_getopt_wide(&goi, &a);
5416 struct command_context *cmd_ctx = current_command_context(interp);
5418 struct target *target = get_current_target(cmd_ctx);
5419 if (!target->tap->enabled)
5420 return jim_target_tap_disabled(interp);
5422 if (!target->type->assert_reset || !target->type->deassert_reset) {
5423 Jim_SetResultFormatted(interp,
5424 "No target-specific reset for %s",
5425 target_name(target));
5429 if (target->defer_examine)
5430 target_reset_examined(target);
5432 /* determine if we should halt or not. */
5433 target->reset_halt = (a != 0);
5434 /* When this happens - all workareas are invalid. */
5435 target_free_all_working_areas_restore(target, 0);
5438 if (n->value == NVP_ASSERT)
5439 e = target->type->assert_reset(target);
5441 e = target->type->deassert_reset(target);
5442 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5445 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5448 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5451 struct command_context *cmd_ctx = current_command_context(interp);
5453 struct target *target = get_current_target(cmd_ctx);
5454 if (!target->tap->enabled)
5455 return jim_target_tap_disabled(interp);
5456 int e = target->type->halt(target);
5457 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5460 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5462 struct jim_getopt_info goi;
5463 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5465 /* params: <name> statename timeoutmsecs */
5466 if (goi.argc != 2) {
5467 const char *cmd_name = Jim_GetString(argv[0], NULL);
5468 Jim_SetResultFormatted(goi.interp,
5469 "%s <state_name> <timeout_in_msec>", cmd_name);
5474 int e = jim_getopt_nvp(&goi, nvp_target_state, &n);
5476 jim_getopt_nvp_unknown(&goi, nvp_target_state, 1);
5480 e = jim_getopt_wide(&goi, &a);
5483 struct command_context *cmd_ctx = current_command_context(interp);
5485 struct target *target = get_current_target(cmd_ctx);
5486 if (!target->tap->enabled)
5487 return jim_target_tap_disabled(interp);
5489 e = target_wait_state(target, n->value, a);
5490 if (e != ERROR_OK) {
5491 Jim_Obj *obj = Jim_NewIntObj(interp, e);
5492 Jim_SetResultFormatted(goi.interp,
5493 "target: %s wait %s fails (%#s) %s",
5494 target_name(target), n->name,
5495 obj, target_strerror_safe(e));
5500 /* List for human, Events defined for this target.
5501 * scripts/programs should use 'name cget -event NAME'
5503 COMMAND_HANDLER(handle_target_event_list)
5505 struct target *target = get_current_target(CMD_CTX);
5506 struct target_event_action *teap = target->event_action;
5508 command_print(CMD, "Event actions for target (%d) %s\n",
5509 target->target_number,
5510 target_name(target));
5511 command_print(CMD, "%-25s | Body", "Event");
5512 command_print(CMD, "------------------------- | "
5513 "----------------------------------------");
5515 command_print(CMD, "%-25s | %s",
5516 target_event_name(teap->event),
5517 Jim_GetString(teap->body, NULL));
5520 command_print(CMD, "***END***");
5523 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5526 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5529 struct command_context *cmd_ctx = current_command_context(interp);
5531 struct target *target = get_current_target(cmd_ctx);
5532 Jim_SetResultString(interp, target_state_name(target), -1);
5535 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5537 struct jim_getopt_info goi;
5538 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5539 if (goi.argc != 1) {
5540 const char *cmd_name = Jim_GetString(argv[0], NULL);
5541 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5545 int e = jim_getopt_nvp(&goi, nvp_target_event, &n);
5547 jim_getopt_nvp_unknown(&goi, nvp_target_event, 1);
5550 struct command_context *cmd_ctx = current_command_context(interp);
5552 struct target *target = get_current_target(cmd_ctx);
5553 target_handle_event(target, n->value);
5557 static const struct command_registration target_instance_command_handlers[] = {
5559 .name = "configure",
5560 .mode = COMMAND_ANY,
5561 .jim_handler = jim_target_configure,
5562 .help = "configure a new target for use",
5563 .usage = "[target_attribute ...]",
5567 .mode = COMMAND_ANY,
5568 .jim_handler = jim_target_configure,
5569 .help = "returns the specified target attribute",
5570 .usage = "target_attribute",
5574 .handler = handle_mw_command,
5575 .mode = COMMAND_EXEC,
5576 .help = "Write 64-bit word(s) to target memory",
5577 .usage = "address data [count]",
5581 .handler = handle_mw_command,
5582 .mode = COMMAND_EXEC,
5583 .help = "Write 32-bit word(s) to target memory",
5584 .usage = "address data [count]",
5588 .handler = handle_mw_command,
5589 .mode = COMMAND_EXEC,
5590 .help = "Write 16-bit half-word(s) to target memory",
5591 .usage = "address data [count]",
5595 .handler = handle_mw_command,
5596 .mode = COMMAND_EXEC,
5597 .help = "Write byte(s) to target memory",
5598 .usage = "address data [count]",
5602 .handler = handle_md_command,
5603 .mode = COMMAND_EXEC,
5604 .help = "Display target memory as 64-bit words",
5605 .usage = "address [count]",
5609 .handler = handle_md_command,
5610 .mode = COMMAND_EXEC,
5611 .help = "Display target memory as 32-bit words",
5612 .usage = "address [count]",
5616 .handler = handle_md_command,
5617 .mode = COMMAND_EXEC,
5618 .help = "Display target memory as 16-bit half-words",
5619 .usage = "address [count]",
5623 .handler = handle_md_command,
5624 .mode = COMMAND_EXEC,
5625 .help = "Display target memory as 8-bit bytes",
5626 .usage = "address [count]",
5629 .name = "array2mem",
5630 .mode = COMMAND_EXEC,
5631 .jim_handler = jim_target_array2mem,
5632 .help = "Writes Tcl array of 8/16/32 bit numbers "
5634 .usage = "arrayname bitwidth address count",
5637 .name = "mem2array",
5638 .mode = COMMAND_EXEC,
5639 .jim_handler = jim_target_mem2array,
5640 .help = "Loads Tcl array of 8/16/32 bit numbers "
5641 "from target memory",
5642 .usage = "arrayname bitwidth address count",
5645 .name = "eventlist",
5646 .handler = handle_target_event_list,
5647 .mode = COMMAND_EXEC,
5648 .help = "displays a table of events defined for this target",
5653 .mode = COMMAND_EXEC,
5654 .jim_handler = jim_target_current_state,
5655 .help = "displays the current state of this target",
5658 .name = "arp_examine",
5659 .mode = COMMAND_EXEC,
5660 .jim_handler = jim_target_examine,
5661 .help = "used internally for reset processing",
5662 .usage = "['allow-defer']",
5665 .name = "was_examined",
5666 .mode = COMMAND_EXEC,
5667 .jim_handler = jim_target_was_examined,
5668 .help = "used internally for reset processing",
5671 .name = "examine_deferred",
5672 .mode = COMMAND_EXEC,
5673 .jim_handler = jim_target_examine_deferred,
5674 .help = "used internally for reset processing",
5677 .name = "arp_halt_gdb",
5678 .mode = COMMAND_EXEC,
5679 .jim_handler = jim_target_halt_gdb,
5680 .help = "used internally for reset processing to halt GDB",
5684 .mode = COMMAND_EXEC,
5685 .jim_handler = jim_target_poll,
5686 .help = "used internally for reset processing",
5689 .name = "arp_reset",
5690 .mode = COMMAND_EXEC,
5691 .jim_handler = jim_target_reset,
5692 .help = "used internally for reset processing",
5696 .mode = COMMAND_EXEC,
5697 .jim_handler = jim_target_halt,
5698 .help = "used internally for reset processing",
5701 .name = "arp_waitstate",
5702 .mode = COMMAND_EXEC,
5703 .jim_handler = jim_target_wait_state,
5704 .help = "used internally for reset processing",
5707 .name = "invoke-event",
5708 .mode = COMMAND_EXEC,
5709 .jim_handler = jim_target_invoke_event,
5710 .help = "invoke handler for specified event",
5711 .usage = "event_name",
5713 COMMAND_REGISTRATION_DONE
5716 static int target_create(struct jim_getopt_info *goi)
5723 struct target *target;
5724 struct command_context *cmd_ctx;
5726 cmd_ctx = current_command_context(goi->interp);
5729 if (goi->argc < 3) {
5730 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5735 jim_getopt_obj(goi, &new_cmd);
5736 /* does this command exist? */
5737 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_NONE);
5739 cp = Jim_GetString(new_cmd, NULL);
5740 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5745 e = jim_getopt_string(goi, &cp, NULL);
5748 struct transport *tr = get_current_transport();
5749 if (tr->override_target) {
5750 e = tr->override_target(&cp);
5751 if (e != ERROR_OK) {
5752 LOG_ERROR("The selected transport doesn't support this target");
5755 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5757 /* now does target type exist */
5758 for (x = 0 ; target_types[x] ; x++) {
5759 if (strcmp(cp, target_types[x]->name) == 0) {
5764 if (!target_types[x]) {
5765 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5766 for (x = 0 ; target_types[x] ; x++) {
5767 if (target_types[x + 1]) {
5768 Jim_AppendStrings(goi->interp,
5769 Jim_GetResult(goi->interp),
5770 target_types[x]->name,
5773 Jim_AppendStrings(goi->interp,
5774 Jim_GetResult(goi->interp),
5776 target_types[x]->name, NULL);
5783 target = calloc(1, sizeof(struct target));
5785 LOG_ERROR("Out of memory");
5789 /* set target number */
5790 target->target_number = new_target_number();
5792 /* allocate memory for each unique target type */
5793 target->type = malloc(sizeof(struct target_type));
5794 if (!target->type) {
5795 LOG_ERROR("Out of memory");
5800 memcpy(target->type, target_types[x], sizeof(struct target_type));
5802 /* default to first core, override with -coreid */
5805 target->working_area = 0x0;
5806 target->working_area_size = 0x0;
5807 target->working_areas = NULL;
5808 target->backup_working_area = 0;
5810 target->state = TARGET_UNKNOWN;
5811 target->debug_reason = DBG_REASON_UNDEFINED;
5812 target->reg_cache = NULL;
5813 target->breakpoints = NULL;
5814 target->watchpoints = NULL;
5815 target->next = NULL;
5816 target->arch_info = NULL;
5818 target->verbose_halt_msg = true;
5820 target->halt_issued = false;
5822 /* initialize trace information */
5823 target->trace_info = calloc(1, sizeof(struct trace));
5824 if (!target->trace_info) {
5825 LOG_ERROR("Out of memory");
5831 target->dbgmsg = NULL;
5832 target->dbg_msg_enabled = 0;
5834 target->endianness = TARGET_ENDIAN_UNKNOWN;
5836 target->rtos = NULL;
5837 target->rtos_auto_detect = false;
5839 target->gdb_port_override = NULL;
5840 target->gdb_max_connections = 1;
5842 /* Do the rest as "configure" options */
5843 goi->isconfigure = 1;
5844 e = target_configure(goi, target);
5847 if (target->has_dap) {
5848 if (!target->dap_configured) {
5849 Jim_SetResultString(goi->interp, "-dap ?name? required when creating target", -1);
5853 if (!target->tap_configured) {
5854 Jim_SetResultString(goi->interp, "-chain-position ?name? required when creating target", -1);
5858 /* tap must be set after target was configured */
5864 rtos_destroy(target);
5865 free(target->gdb_port_override);
5866 free(target->trace_info);
5872 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5873 /* default endian to little if not specified */
5874 target->endianness = TARGET_LITTLE_ENDIAN;
5877 cp = Jim_GetString(new_cmd, NULL);
5878 target->cmd_name = strdup(cp);
5879 if (!target->cmd_name) {
5880 LOG_ERROR("Out of memory");
5881 rtos_destroy(target);
5882 free(target->gdb_port_override);
5883 free(target->trace_info);
5889 if (target->type->target_create) {
5890 e = (*(target->type->target_create))(target, goi->interp);
5891 if (e != ERROR_OK) {
5892 LOG_DEBUG("target_create failed");
5893 free(target->cmd_name);
5894 rtos_destroy(target);
5895 free(target->gdb_port_override);
5896 free(target->trace_info);
5903 /* create the target specific commands */
5904 if (target->type->commands) {
5905 e = register_commands(cmd_ctx, NULL, target->type->commands);
5907 LOG_ERROR("unable to register '%s' commands", cp);
5910 /* now - create the new target name command */
5911 const struct command_registration target_subcommands[] = {
5913 .chain = target_instance_command_handlers,
5916 .chain = target->type->commands,
5918 COMMAND_REGISTRATION_DONE
5920 const struct command_registration target_commands[] = {
5923 .mode = COMMAND_ANY,
5924 .help = "target command group",
5926 .chain = target_subcommands,
5928 COMMAND_REGISTRATION_DONE
5930 e = register_commands_override_target(cmd_ctx, NULL, target_commands, target);
5931 if (e != ERROR_OK) {
5932 if (target->type->deinit_target)
5933 target->type->deinit_target(target);
5934 free(target->cmd_name);
5935 rtos_destroy(target);
5936 free(target->gdb_port_override);
5937 free(target->trace_info);
5943 /* append to end of list */
5944 append_to_list_all_targets(target);
5946 cmd_ctx->current_target = target;
5950 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5953 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5956 struct command_context *cmd_ctx = current_command_context(interp);
5959 struct target *target = get_current_target_or_null(cmd_ctx);
5961 Jim_SetResultString(interp, target_name(target), -1);
5965 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5968 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5971 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5972 for (unsigned x = 0; target_types[x]; x++) {
5973 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5974 Jim_NewStringObj(interp, target_types[x]->name, -1));
5979 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5982 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5985 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5986 struct target *target = all_targets;
5988 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5989 Jim_NewStringObj(interp, target_name(target), -1));
5990 target = target->next;
5995 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5998 const char *targetname;
6000 struct target *target = NULL;
6001 struct target_list *head, *curr, *new;
6006 LOG_DEBUG("%d", argc);
6007 /* argv[1] = target to associate in smp
6008 * argv[2] = target to associate in smp
6012 for (i = 1; i < argc; i++) {
6014 targetname = Jim_GetString(argv[i], &len);
6015 target = get_target(targetname);
6016 LOG_DEBUG("%s ", targetname);
6018 new = malloc(sizeof(struct target_list));
6019 new->target = target;
6030 /* now parse the list of cpu and put the target in smp mode*/
6034 target = curr->target;
6036 target->head = head;
6040 if (target && target->rtos)
6041 retval = rtos_smp_init(head->target);
6047 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6049 struct jim_getopt_info goi;
6050 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
6052 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
6053 "<name> <target_type> [<target_options> ...]");
6056 return target_create(&goi);
6059 static const struct command_registration target_subcommand_handlers[] = {
6062 .mode = COMMAND_CONFIG,
6063 .handler = handle_target_init_command,
6064 .help = "initialize targets",
6069 .mode = COMMAND_CONFIG,
6070 .jim_handler = jim_target_create,
6071 .usage = "name type '-chain-position' name [options ...]",
6072 .help = "Creates and selects a new target",
6076 .mode = COMMAND_ANY,
6077 .jim_handler = jim_target_current,
6078 .help = "Returns the currently selected target",
6082 .mode = COMMAND_ANY,
6083 .jim_handler = jim_target_types,
6084 .help = "Returns the available target types as "
6085 "a list of strings",
6089 .mode = COMMAND_ANY,
6090 .jim_handler = jim_target_names,
6091 .help = "Returns the names of all targets as a list of strings",
6095 .mode = COMMAND_ANY,
6096 .jim_handler = jim_target_smp,
6097 .usage = "targetname1 targetname2 ...",
6098 .help = "gather several target in a smp list"
6101 COMMAND_REGISTRATION_DONE
6105 target_addr_t address;
6111 static int fastload_num;
6112 static struct fast_load *fastload;
6114 static void free_fastload(void)
6117 for (int i = 0; i < fastload_num; i++)
6118 free(fastload[i].data);
6124 COMMAND_HANDLER(handle_fast_load_image_command)
6128 uint32_t image_size;
6129 target_addr_t min_address = 0;
6130 target_addr_t max_address = -1;
6134 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
6135 &image, &min_address, &max_address);
6136 if (retval != ERROR_OK)
6139 struct duration bench;
6140 duration_start(&bench);
6142 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
6143 if (retval != ERROR_OK)
6148 fastload_num = image.num_sections;
6149 fastload = malloc(sizeof(struct fast_load)*image.num_sections);
6151 command_print(CMD, "out of memory");
6152 image_close(&image);
6155 memset(fastload, 0, sizeof(struct fast_load)*image.num_sections);
6156 for (unsigned int i = 0; i < image.num_sections; i++) {
6157 buffer = malloc(image.sections[i].size);
6159 command_print(CMD, "error allocating buffer for section (%d bytes)",
6160 (int)(image.sections[i].size));
6161 retval = ERROR_FAIL;
6165 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
6166 if (retval != ERROR_OK) {
6171 uint32_t offset = 0;
6172 uint32_t length = buf_cnt;
6174 /* DANGER!!! beware of unsigned comparison here!!! */
6176 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
6177 (image.sections[i].base_address < max_address)) {
6178 if (image.sections[i].base_address < min_address) {
6179 /* clip addresses below */
6180 offset += min_address-image.sections[i].base_address;
6184 if (image.sections[i].base_address + buf_cnt > max_address)
6185 length -= (image.sections[i].base_address + buf_cnt)-max_address;
6187 fastload[i].address = image.sections[i].base_address + offset;
6188 fastload[i].data = malloc(length);
6189 if (!fastload[i].data) {
6191 command_print(CMD, "error allocating buffer for section (%" PRIu32 " bytes)",
6193 retval = ERROR_FAIL;
6196 memcpy(fastload[i].data, buffer + offset, length);
6197 fastload[i].length = length;
6199 image_size += length;
6200 command_print(CMD, "%u bytes written at address 0x%8.8x",
6201 (unsigned int)length,
6202 ((unsigned int)(image.sections[i].base_address + offset)));
6208 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
6209 command_print(CMD, "Loaded %" PRIu32 " bytes "
6210 "in %fs (%0.3f KiB/s)", image_size,
6211 duration_elapsed(&bench), duration_kbps(&bench, image_size));
6214 "WARNING: image has not been loaded to target!"
6215 "You can issue a 'fast_load' to finish loading.");
6218 image_close(&image);
6220 if (retval != ERROR_OK)
6226 COMMAND_HANDLER(handle_fast_load_command)
6229 return ERROR_COMMAND_SYNTAX_ERROR;
6231 LOG_ERROR("No image in memory");
6235 int64_t ms = timeval_ms();
6237 int retval = ERROR_OK;
6238 for (i = 0; i < fastload_num; i++) {
6239 struct target *target = get_current_target(CMD_CTX);
6240 command_print(CMD, "Write to 0x%08x, length 0x%08x",
6241 (unsigned int)(fastload[i].address),
6242 (unsigned int)(fastload[i].length));
6243 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
6244 if (retval != ERROR_OK)
6246 size += fastload[i].length;
6248 if (retval == ERROR_OK) {
6249 int64_t after = timeval_ms();
6250 command_print(CMD, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
6255 static const struct command_registration target_command_handlers[] = {
6258 .handler = handle_targets_command,
6259 .mode = COMMAND_ANY,
6260 .help = "change current default target (one parameter) "
6261 "or prints table of all targets (no parameters)",
6262 .usage = "[target]",
6266 .mode = COMMAND_CONFIG,
6267 .help = "configure target",
6268 .chain = target_subcommand_handlers,
6271 COMMAND_REGISTRATION_DONE
6274 int target_register_commands(struct command_context *cmd_ctx)
6276 return register_commands(cmd_ctx, NULL, target_command_handlers);
6279 static bool target_reset_nag = true;
6281 bool get_target_reset_nag(void)
6283 return target_reset_nag;
6286 COMMAND_HANDLER(handle_target_reset_nag)
6288 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
6289 &target_reset_nag, "Nag after each reset about options to improve "
6293 COMMAND_HANDLER(handle_ps_command)
6295 struct target *target = get_current_target(CMD_CTX);
6297 if (target->state != TARGET_HALTED) {
6298 LOG_INFO("target not halted !!");
6302 if ((target->rtos) && (target->rtos->type)
6303 && (target->rtos->type->ps_command)) {
6304 display = target->rtos->type->ps_command(target);
6305 command_print(CMD, "%s", display);
6310 return ERROR_TARGET_FAILURE;
6314 static void binprint(struct command_invocation *cmd, const char *text, const uint8_t *buf, int size)
6317 command_print_sameline(cmd, "%s", text);
6318 for (int i = 0; i < size; i++)
6319 command_print_sameline(cmd, " %02x", buf[i]);
6320 command_print(cmd, " ");
6323 COMMAND_HANDLER(handle_test_mem_access_command)
6325 struct target *target = get_current_target(CMD_CTX);
6327 int retval = ERROR_OK;
6329 if (target->state != TARGET_HALTED) {
6330 LOG_INFO("target not halted !!");
6335 return ERROR_COMMAND_SYNTAX_ERROR;
6337 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
6340 size_t num_bytes = test_size + 4;
6342 struct working_area *wa = NULL;
6343 retval = target_alloc_working_area(target, num_bytes, &wa);
6344 if (retval != ERROR_OK) {
6345 LOG_ERROR("Not enough working area");
6349 uint8_t *test_pattern = malloc(num_bytes);
6351 for (size_t i = 0; i < num_bytes; i++)
6352 test_pattern[i] = rand();
6354 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6355 if (retval != ERROR_OK) {
6356 LOG_ERROR("Test pattern write failed");
6360 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6361 for (int size = 1; size <= 4; size *= 2) {
6362 for (int offset = 0; offset < 4; offset++) {
6363 uint32_t count = test_size / size;
6364 size_t host_bufsiz = (count + 2) * size + host_offset;
6365 uint8_t *read_ref = malloc(host_bufsiz);
6366 uint8_t *read_buf = malloc(host_bufsiz);
6368 for (size_t i = 0; i < host_bufsiz; i++) {
6369 read_ref[i] = rand();
6370 read_buf[i] = read_ref[i];
6372 command_print_sameline(CMD,
6373 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
6374 size, offset, host_offset ? "un" : "");
6376 struct duration bench;
6377 duration_start(&bench);
6379 retval = target_read_memory(target, wa->address + offset, size, count,
6380 read_buf + size + host_offset);
6382 duration_measure(&bench);
6384 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6385 command_print(CMD, "Unsupported alignment");
6387 } else if (retval != ERROR_OK) {
6388 command_print(CMD, "Memory read failed");
6392 /* replay on host */
6393 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
6396 int result = memcmp(read_ref, read_buf, host_bufsiz);
6398 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6399 duration_elapsed(&bench),
6400 duration_kbps(&bench, count * size));
6402 command_print(CMD, "Compare failed");
6403 binprint(CMD, "ref:", read_ref, host_bufsiz);
6404 binprint(CMD, "buf:", read_buf, host_bufsiz);
6416 target_free_working_area(target, wa);
6419 num_bytes = test_size + 4 + 4 + 4;
6421 retval = target_alloc_working_area(target, num_bytes, &wa);
6422 if (retval != ERROR_OK) {
6423 LOG_ERROR("Not enough working area");
6427 test_pattern = malloc(num_bytes);
6429 for (size_t i = 0; i < num_bytes; i++)
6430 test_pattern[i] = rand();
6432 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6433 for (int size = 1; size <= 4; size *= 2) {
6434 for (int offset = 0; offset < 4; offset++) {
6435 uint32_t count = test_size / size;
6436 size_t host_bufsiz = count * size + host_offset;
6437 uint8_t *read_ref = malloc(num_bytes);
6438 uint8_t *read_buf = malloc(num_bytes);
6439 uint8_t *write_buf = malloc(host_bufsiz);
6441 for (size_t i = 0; i < host_bufsiz; i++)
6442 write_buf[i] = rand();
6443 command_print_sameline(CMD,
6444 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
6445 size, offset, host_offset ? "un" : "");
6447 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6448 if (retval != ERROR_OK) {
6449 command_print(CMD, "Test pattern write failed");
6453 /* replay on host */
6454 memcpy(read_ref, test_pattern, num_bytes);
6455 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
6457 struct duration bench;
6458 duration_start(&bench);
6460 retval = target_write_memory(target, wa->address + size + offset, size, count,
6461 write_buf + host_offset);
6463 duration_measure(&bench);
6465 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6466 command_print(CMD, "Unsupported alignment");
6468 } else if (retval != ERROR_OK) {
6469 command_print(CMD, "Memory write failed");
6474 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
6475 if (retval != ERROR_OK) {
6476 command_print(CMD, "Test pattern write failed");
6481 int result = memcmp(read_ref, read_buf, num_bytes);
6483 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6484 duration_elapsed(&bench),
6485 duration_kbps(&bench, count * size));
6487 command_print(CMD, "Compare failed");
6488 binprint(CMD, "ref:", read_ref, num_bytes);
6489 binprint(CMD, "buf:", read_buf, num_bytes);
6500 target_free_working_area(target, wa);
6504 static const struct command_registration target_exec_command_handlers[] = {
6506 .name = "fast_load_image",
6507 .handler = handle_fast_load_image_command,
6508 .mode = COMMAND_ANY,
6509 .help = "Load image into server memory for later use by "
6510 "fast_load; primarily for profiling",
6511 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6512 "[min_address [max_length]]",
6515 .name = "fast_load",
6516 .handler = handle_fast_load_command,
6517 .mode = COMMAND_EXEC,
6518 .help = "loads active fast load image to current target "
6519 "- mainly for profiling purposes",
6524 .handler = handle_profile_command,
6525 .mode = COMMAND_EXEC,
6526 .usage = "seconds filename [start end]",
6527 .help = "profiling samples the CPU PC",
6529 /** @todo don't register virt2phys() unless target supports it */
6531 .name = "virt2phys",
6532 .handler = handle_virt2phys_command,
6533 .mode = COMMAND_ANY,
6534 .help = "translate a virtual address into a physical address",
6535 .usage = "virtual_address",
6539 .handler = handle_reg_command,
6540 .mode = COMMAND_EXEC,
6541 .help = "display (reread from target with \"force\") or set a register; "
6542 "with no arguments, displays all registers and their values",
6543 .usage = "[(register_number|register_name) [(value|'force')]]",
6547 .handler = handle_poll_command,
6548 .mode = COMMAND_EXEC,
6549 .help = "poll target state; or reconfigure background polling",
6550 .usage = "['on'|'off']",
6553 .name = "wait_halt",
6554 .handler = handle_wait_halt_command,
6555 .mode = COMMAND_EXEC,
6556 .help = "wait up to the specified number of milliseconds "
6557 "(default 5000) for a previously requested halt",
6558 .usage = "[milliseconds]",
6562 .handler = handle_halt_command,
6563 .mode = COMMAND_EXEC,
6564 .help = "request target to halt, then wait up to the specified "
6565 "number of milliseconds (default 5000) for it to complete",
6566 .usage = "[milliseconds]",
6570 .handler = handle_resume_command,
6571 .mode = COMMAND_EXEC,
6572 .help = "resume target execution from current PC or address",
6573 .usage = "[address]",
6577 .handler = handle_reset_command,
6578 .mode = COMMAND_EXEC,
6579 .usage = "[run|halt|init]",
6580 .help = "Reset all targets into the specified mode. "
6581 "Default reset mode is run, if not given.",
6584 .name = "soft_reset_halt",
6585 .handler = handle_soft_reset_halt_command,
6586 .mode = COMMAND_EXEC,
6588 .help = "halt the target and do a soft reset",
6592 .handler = handle_step_command,
6593 .mode = COMMAND_EXEC,
6594 .help = "step one instruction from current PC or address",
6595 .usage = "[address]",
6599 .handler = handle_md_command,
6600 .mode = COMMAND_EXEC,
6601 .help = "display memory double-words",
6602 .usage = "['phys'] address [count]",
6606 .handler = handle_md_command,
6607 .mode = COMMAND_EXEC,
6608 .help = "display memory words",
6609 .usage = "['phys'] address [count]",
6613 .handler = handle_md_command,
6614 .mode = COMMAND_EXEC,
6615 .help = "display memory half-words",
6616 .usage = "['phys'] address [count]",
6620 .handler = handle_md_command,
6621 .mode = COMMAND_EXEC,
6622 .help = "display memory bytes",
6623 .usage = "['phys'] address [count]",
6627 .handler = handle_mw_command,
6628 .mode = COMMAND_EXEC,
6629 .help = "write memory double-word",
6630 .usage = "['phys'] address value [count]",
6634 .handler = handle_mw_command,
6635 .mode = COMMAND_EXEC,
6636 .help = "write memory word",
6637 .usage = "['phys'] address value [count]",
6641 .handler = handle_mw_command,
6642 .mode = COMMAND_EXEC,
6643 .help = "write memory half-word",
6644 .usage = "['phys'] address value [count]",
6648 .handler = handle_mw_command,
6649 .mode = COMMAND_EXEC,
6650 .help = "write memory byte",
6651 .usage = "['phys'] address value [count]",
6655 .handler = handle_bp_command,
6656 .mode = COMMAND_EXEC,
6657 .help = "list or set hardware or software breakpoint",
6658 .usage = "[<address> [<asid>] <length> ['hw'|'hw_ctx']]",
6662 .handler = handle_rbp_command,
6663 .mode = COMMAND_EXEC,
6664 .help = "remove breakpoint",
6665 .usage = "'all' | address",
6669 .handler = handle_wp_command,
6670 .mode = COMMAND_EXEC,
6671 .help = "list (no params) or create watchpoints",
6672 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
6676 .handler = handle_rwp_command,
6677 .mode = COMMAND_EXEC,
6678 .help = "remove watchpoint",
6682 .name = "load_image",
6683 .handler = handle_load_image_command,
6684 .mode = COMMAND_EXEC,
6685 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6686 "[min_address] [max_length]",
6689 .name = "dump_image",
6690 .handler = handle_dump_image_command,
6691 .mode = COMMAND_EXEC,
6692 .usage = "filename address size",
6695 .name = "verify_image_checksum",
6696 .handler = handle_verify_image_checksum_command,
6697 .mode = COMMAND_EXEC,
6698 .usage = "filename [offset [type]]",
6701 .name = "verify_image",
6702 .handler = handle_verify_image_command,
6703 .mode = COMMAND_EXEC,
6704 .usage = "filename [offset [type]]",
6707 .name = "test_image",
6708 .handler = handle_test_image_command,
6709 .mode = COMMAND_EXEC,
6710 .usage = "filename [offset [type]]",
6713 .name = "mem2array",
6714 .mode = COMMAND_EXEC,
6715 .jim_handler = jim_mem2array,
6716 .help = "read 8/16/32 bit memory and return as a TCL array "
6717 "for script processing",
6718 .usage = "arrayname bitwidth address count",
6721 .name = "array2mem",
6722 .mode = COMMAND_EXEC,
6723 .jim_handler = jim_array2mem,
6724 .help = "convert a TCL array to memory locations "
6725 "and write the 8/16/32 bit values",
6726 .usage = "arrayname bitwidth address count",
6729 .name = "reset_nag",
6730 .handler = handle_target_reset_nag,
6731 .mode = COMMAND_ANY,
6732 .help = "Nag after each reset about options that could have been "
6733 "enabled to improve performance.",
6734 .usage = "['enable'|'disable']",
6738 .handler = handle_ps_command,
6739 .mode = COMMAND_EXEC,
6740 .help = "list all tasks",
6744 .name = "test_mem_access",
6745 .handler = handle_test_mem_access_command,
6746 .mode = COMMAND_EXEC,
6747 .help = "Test the target's memory access functions",
6751 COMMAND_REGISTRATION_DONE
6753 static int target_register_user_commands(struct command_context *cmd_ctx)
6755 int retval = ERROR_OK;
6756 retval = target_request_register_commands(cmd_ctx);
6757 if (retval != ERROR_OK)
6760 retval = trace_register_commands(cmd_ctx);
6761 if (retval != ERROR_OK)
6765 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);