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 { .name = NULL, .value = -1 }
242 static const struct jim_nvp nvp_target_state[] = {
243 { .name = "unknown", .value = TARGET_UNKNOWN },
244 { .name = "running", .value = TARGET_RUNNING },
245 { .name = "halted", .value = TARGET_HALTED },
246 { .name = "reset", .value = TARGET_RESET },
247 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
248 { .name = NULL, .value = -1 },
251 static const struct jim_nvp nvp_target_debug_reason[] = {
252 { .name = "debug-request", .value = DBG_REASON_DBGRQ },
253 { .name = "breakpoint", .value = DBG_REASON_BREAKPOINT },
254 { .name = "watchpoint", .value = DBG_REASON_WATCHPOINT },
255 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
256 { .name = "single-step", .value = DBG_REASON_SINGLESTEP },
257 { .name = "target-not-halted", .value = DBG_REASON_NOTHALTED },
258 { .name = "program-exit", .value = DBG_REASON_EXIT },
259 { .name = "exception-catch", .value = DBG_REASON_EXC_CATCH },
260 { .name = "undefined", .value = DBG_REASON_UNDEFINED },
261 { .name = NULL, .value = -1 },
264 static const struct jim_nvp nvp_target_endian[] = {
265 { .name = "big", .value = TARGET_BIG_ENDIAN },
266 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
267 { .name = "be", .value = TARGET_BIG_ENDIAN },
268 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
269 { .name = NULL, .value = -1 },
272 static const struct jim_nvp nvp_reset_modes[] = {
273 { .name = "unknown", .value = RESET_UNKNOWN },
274 { .name = "run", .value = RESET_RUN },
275 { .name = "halt", .value = RESET_HALT },
276 { .name = "init", .value = RESET_INIT },
277 { .name = NULL, .value = -1 },
280 const char *debug_reason_name(struct target *t)
284 cp = jim_nvp_value2name_simple(nvp_target_debug_reason,
285 t->debug_reason)->name;
287 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
288 cp = "(*BUG*unknown*BUG*)";
293 const char *target_state_name(struct target *t)
296 cp = jim_nvp_value2name_simple(nvp_target_state, t->state)->name;
298 LOG_ERROR("Invalid target state: %d", (int)(t->state));
299 cp = "(*BUG*unknown*BUG*)";
302 if (!target_was_examined(t) && t->defer_examine)
303 cp = "examine deferred";
308 const char *target_event_name(enum target_event event)
311 cp = jim_nvp_value2name_simple(nvp_target_event, event)->name;
313 LOG_ERROR("Invalid target event: %d", (int)(event));
314 cp = "(*BUG*unknown*BUG*)";
319 const char *target_reset_mode_name(enum target_reset_mode reset_mode)
322 cp = jim_nvp_value2name_simple(nvp_reset_modes, reset_mode)->name;
324 LOG_ERROR("Invalid target reset mode: %d", (int)(reset_mode));
325 cp = "(*BUG*unknown*BUG*)";
330 /* determine the number of the new target */
331 static int new_target_number(void)
336 /* number is 0 based */
340 if (x < t->target_number)
341 x = t->target_number;
347 static void append_to_list_all_targets(struct target *target)
349 struct target **t = &all_targets;
356 /* read a uint64_t from a buffer in target memory endianness */
357 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
359 if (target->endianness == TARGET_LITTLE_ENDIAN)
360 return le_to_h_u64(buffer);
362 return be_to_h_u64(buffer);
365 /* read a uint32_t from a buffer in target memory endianness */
366 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
368 if (target->endianness == TARGET_LITTLE_ENDIAN)
369 return le_to_h_u32(buffer);
371 return be_to_h_u32(buffer);
374 /* read a uint24_t from a buffer in target memory endianness */
375 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
377 if (target->endianness == TARGET_LITTLE_ENDIAN)
378 return le_to_h_u24(buffer);
380 return be_to_h_u24(buffer);
383 /* read a uint16_t from a buffer in target memory endianness */
384 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
386 if (target->endianness == TARGET_LITTLE_ENDIAN)
387 return le_to_h_u16(buffer);
389 return be_to_h_u16(buffer);
392 /* write a uint64_t to a buffer in target memory endianness */
393 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
395 if (target->endianness == TARGET_LITTLE_ENDIAN)
396 h_u64_to_le(buffer, value);
398 h_u64_to_be(buffer, value);
401 /* write a uint32_t to a buffer in target memory endianness */
402 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
404 if (target->endianness == TARGET_LITTLE_ENDIAN)
405 h_u32_to_le(buffer, value);
407 h_u32_to_be(buffer, value);
410 /* write a uint24_t to a buffer in target memory endianness */
411 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
413 if (target->endianness == TARGET_LITTLE_ENDIAN)
414 h_u24_to_le(buffer, value);
416 h_u24_to_be(buffer, value);
419 /* write a uint16_t to a buffer in target memory endianness */
420 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
422 if (target->endianness == TARGET_LITTLE_ENDIAN)
423 h_u16_to_le(buffer, value);
425 h_u16_to_be(buffer, value);
428 /* write a uint8_t to a buffer in target memory endianness */
429 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
434 /* write a uint64_t array to a buffer in target memory endianness */
435 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
438 for (i = 0; i < count; i++)
439 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
442 /* write a uint32_t array to a buffer in target memory endianness */
443 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
446 for (i = 0; i < count; i++)
447 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
450 /* write a uint16_t array to a buffer in target memory endianness */
451 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
454 for (i = 0; i < count; i++)
455 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
458 /* write a uint64_t array to a buffer in target memory endianness */
459 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
462 for (i = 0; i < count; i++)
463 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
466 /* write a uint32_t array to a buffer in target memory endianness */
467 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
470 for (i = 0; i < count; i++)
471 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
474 /* write a uint16_t array to a buffer in target memory endianness */
475 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
478 for (i = 0; i < count; i++)
479 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
482 /* return a pointer to a configured target; id is name or number */
483 struct target *get_target(const char *id)
485 struct target *target;
487 /* try as tcltarget name */
488 for (target = all_targets; target; target = target->next) {
489 if (!target_name(target))
491 if (strcmp(id, target_name(target)) == 0)
495 /* It's OK to remove this fallback sometime after August 2010 or so */
497 /* no match, try as number */
499 if (parse_uint(id, &num) != ERROR_OK)
502 for (target = all_targets; target; target = target->next) {
503 if (target->target_number == (int)num) {
504 LOG_WARNING("use '%s' as target identifier, not '%u'",
505 target_name(target), num);
513 /* returns a pointer to the n-th configured target */
514 struct target *get_target_by_num(int num)
516 struct target *target = all_targets;
519 if (target->target_number == num)
521 target = target->next;
527 struct target *get_current_target(struct command_context *cmd_ctx)
529 struct target *target = get_current_target_or_null(cmd_ctx);
532 LOG_ERROR("BUG: current_target out of bounds");
539 struct target *get_current_target_or_null(struct command_context *cmd_ctx)
541 return cmd_ctx->current_target_override
542 ? cmd_ctx->current_target_override
543 : cmd_ctx->current_target;
546 int target_poll(struct target *target)
550 /* We can't poll until after examine */
551 if (!target_was_examined(target)) {
552 /* Fail silently lest we pollute the log */
556 retval = target->type->poll(target);
557 if (retval != ERROR_OK)
560 if (target->halt_issued) {
561 if (target->state == TARGET_HALTED)
562 target->halt_issued = false;
564 int64_t t = timeval_ms() - target->halt_issued_time;
565 if (t > DEFAULT_HALT_TIMEOUT) {
566 target->halt_issued = false;
567 LOG_INFO("Halt timed out, wake up GDB.");
568 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
576 int target_halt(struct target *target)
579 /* We can't poll until after examine */
580 if (!target_was_examined(target)) {
581 LOG_ERROR("Target not examined yet");
585 retval = target->type->halt(target);
586 if (retval != ERROR_OK)
589 target->halt_issued = true;
590 target->halt_issued_time = timeval_ms();
596 * Make the target (re)start executing using its saved execution
597 * context (possibly with some modifications).
599 * @param target Which target should start executing.
600 * @param current True to use the target's saved program counter instead
601 * of the address parameter
602 * @param address Optionally used as the program counter.
603 * @param handle_breakpoints True iff breakpoints at the resumption PC
604 * should be skipped. (For example, maybe execution was stopped by
605 * such a breakpoint, in which case it would be counterproductive to
607 * @param debug_execution False if all working areas allocated by OpenOCD
608 * should be released and/or restored to their original contents.
609 * (This would for example be true to run some downloaded "helper"
610 * algorithm code, which resides in one such working buffer and uses
611 * another for data storage.)
613 * @todo Resolve the ambiguity about what the "debug_execution" flag
614 * signifies. For example, Target implementations don't agree on how
615 * it relates to invalidation of the register cache, or to whether
616 * breakpoints and watchpoints should be enabled. (It would seem wrong
617 * to enable breakpoints when running downloaded "helper" algorithms
618 * (debug_execution true), since the breakpoints would be set to match
619 * target firmware being debugged, not the helper algorithm.... and
620 * enabling them could cause such helpers to malfunction (for example,
621 * by overwriting data with a breakpoint instruction. On the other
622 * hand the infrastructure for running such helpers might use this
623 * procedure but rely on hardware breakpoint to detect termination.)
625 int target_resume(struct target *target, int current, target_addr_t address,
626 int handle_breakpoints, int debug_execution)
630 /* We can't poll until after examine */
631 if (!target_was_examined(target)) {
632 LOG_ERROR("Target not examined yet");
636 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
638 /* note that resume *must* be asynchronous. The CPU can halt before
639 * we poll. The CPU can even halt at the current PC as a result of
640 * a software breakpoint being inserted by (a bug?) the application.
643 * resume() triggers the event 'resumed'. The execution of TCL commands
644 * in the event handler causes the polling of targets. If the target has
645 * already halted for a breakpoint, polling will run the 'halted' event
646 * handler before the pending 'resumed' handler.
647 * Disable polling during resume() to guarantee the execution of handlers
648 * in the correct order.
650 bool save_poll = jtag_poll_get_enabled();
651 jtag_poll_set_enabled(false);
652 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
653 jtag_poll_set_enabled(save_poll);
654 if (retval != ERROR_OK)
657 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
662 static int target_process_reset(struct command_invocation *cmd, enum target_reset_mode reset_mode)
667 n = jim_nvp_value2name_simple(nvp_reset_modes, reset_mode);
669 LOG_ERROR("invalid reset mode");
673 struct target *target;
674 for (target = all_targets; target; target = target->next)
675 target_call_reset_callbacks(target, reset_mode);
677 /* disable polling during reset to make reset event scripts
678 * more predictable, i.e. dr/irscan & pathmove in events will
679 * not have JTAG operations injected into the middle of a sequence.
681 bool save_poll = jtag_poll_get_enabled();
683 jtag_poll_set_enabled(false);
685 sprintf(buf, "ocd_process_reset %s", n->name);
686 retval = Jim_Eval(cmd->ctx->interp, buf);
688 jtag_poll_set_enabled(save_poll);
690 if (retval != JIM_OK) {
691 Jim_MakeErrorMessage(cmd->ctx->interp);
692 command_print(cmd, "%s", Jim_GetString(Jim_GetResult(cmd->ctx->interp), NULL));
696 /* We want any events to be processed before the prompt */
697 retval = target_call_timer_callbacks_now();
699 for (target = all_targets; target; target = target->next) {
700 target->type->check_reset(target);
701 target->running_alg = false;
707 static int identity_virt2phys(struct target *target,
708 target_addr_t virtual, target_addr_t *physical)
714 static int no_mmu(struct target *target, int *enabled)
721 * Reset the @c examined flag for the given target.
722 * Pure paranoia -- targets are zeroed on allocation.
724 static inline void target_reset_examined(struct target *target)
726 target->examined = false;
729 static int default_examine(struct target *target)
731 target_set_examined(target);
735 /* no check by default */
736 static int default_check_reset(struct target *target)
741 /* Equivalent Tcl code arp_examine_one is in src/target/startup.tcl
743 int target_examine_one(struct target *target)
745 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
747 int retval = target->type->examine(target);
748 if (retval != ERROR_OK) {
749 target_reset_examined(target);
750 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_FAIL);
754 target_set_examined(target);
755 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
760 static int jtag_enable_callback(enum jtag_event event, void *priv)
762 struct target *target = priv;
764 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
767 jtag_unregister_event_callback(jtag_enable_callback, target);
769 return target_examine_one(target);
772 /* Targets that correctly implement init + examine, i.e.
773 * no communication with target during init:
777 int target_examine(void)
779 int retval = ERROR_OK;
780 struct target *target;
782 for (target = all_targets; target; target = target->next) {
783 /* defer examination, but don't skip it */
784 if (!target->tap->enabled) {
785 jtag_register_event_callback(jtag_enable_callback,
790 if (target->defer_examine)
793 int retval2 = target_examine_one(target);
794 if (retval2 != ERROR_OK) {
795 LOG_WARNING("target %s examination failed", target_name(target));
802 const char *target_type_name(struct target *target)
804 return target->type->name;
807 static int target_soft_reset_halt(struct target *target)
809 if (!target_was_examined(target)) {
810 LOG_ERROR("Target not examined yet");
813 if (!target->type->soft_reset_halt) {
814 LOG_ERROR("Target %s does not support soft_reset_halt",
815 target_name(target));
818 return target->type->soft_reset_halt(target);
822 * Downloads a target-specific native code algorithm to the target,
823 * and executes it. * Note that some targets may need to set up, enable,
824 * and tear down a breakpoint (hard or * soft) to detect algorithm
825 * termination, while others may support lower overhead schemes where
826 * soft breakpoints embedded in the algorithm automatically terminate the
829 * @param target used to run the algorithm
830 * @param num_mem_params
832 * @param num_reg_params
837 * @param arch_info target-specific description of the algorithm.
839 int target_run_algorithm(struct target *target,
840 int num_mem_params, struct mem_param *mem_params,
841 int num_reg_params, struct reg_param *reg_param,
842 target_addr_t entry_point, target_addr_t exit_point,
843 int timeout_ms, void *arch_info)
845 int retval = ERROR_FAIL;
847 if (!target_was_examined(target)) {
848 LOG_ERROR("Target not examined yet");
851 if (!target->type->run_algorithm) {
852 LOG_ERROR("Target type '%s' does not support %s",
853 target_type_name(target), __func__);
857 target->running_alg = true;
858 retval = target->type->run_algorithm(target,
859 num_mem_params, mem_params,
860 num_reg_params, reg_param,
861 entry_point, exit_point, timeout_ms, arch_info);
862 target->running_alg = false;
869 * Executes a target-specific native code algorithm and leaves it running.
871 * @param target used to run the algorithm
872 * @param num_mem_params
874 * @param num_reg_params
878 * @param arch_info target-specific description of the algorithm.
880 int target_start_algorithm(struct target *target,
881 int num_mem_params, struct mem_param *mem_params,
882 int num_reg_params, struct reg_param *reg_params,
883 target_addr_t entry_point, target_addr_t exit_point,
886 int retval = ERROR_FAIL;
888 if (!target_was_examined(target)) {
889 LOG_ERROR("Target not examined yet");
892 if (!target->type->start_algorithm) {
893 LOG_ERROR("Target type '%s' does not support %s",
894 target_type_name(target), __func__);
897 if (target->running_alg) {
898 LOG_ERROR("Target is already running an algorithm");
902 target->running_alg = true;
903 retval = target->type->start_algorithm(target,
904 num_mem_params, mem_params,
905 num_reg_params, reg_params,
906 entry_point, exit_point, arch_info);
913 * Waits for an algorithm started with target_start_algorithm() to complete.
915 * @param target used to run the algorithm
916 * @param num_mem_params
918 * @param num_reg_params
922 * @param arch_info target-specific description of the algorithm.
924 int target_wait_algorithm(struct target *target,
925 int num_mem_params, struct mem_param *mem_params,
926 int num_reg_params, struct reg_param *reg_params,
927 target_addr_t exit_point, int timeout_ms,
930 int retval = ERROR_FAIL;
932 if (!target->type->wait_algorithm) {
933 LOG_ERROR("Target type '%s' does not support %s",
934 target_type_name(target), __func__);
937 if (!target->running_alg) {
938 LOG_ERROR("Target is not running an algorithm");
942 retval = target->type->wait_algorithm(target,
943 num_mem_params, mem_params,
944 num_reg_params, reg_params,
945 exit_point, timeout_ms, arch_info);
946 if (retval != ERROR_TARGET_TIMEOUT)
947 target->running_alg = false;
954 * Streams data to a circular buffer on target intended for consumption by code
955 * running asynchronously on target.
957 * This is intended for applications where target-specific native code runs
958 * on the target, receives data from the circular buffer, does something with
959 * it (most likely writing it to a flash memory), and advances the circular
962 * This assumes that the helper algorithm has already been loaded to the target,
963 * but has not been started yet. Given memory and register parameters are passed
966 * The buffer is defined by (buffer_start, buffer_size) arguments and has the
969 * [buffer_start + 0, buffer_start + 4):
970 * Write Pointer address (aka head). Written and updated by this
971 * routine when new data is written to the circular buffer.
972 * [buffer_start + 4, buffer_start + 8):
973 * Read Pointer address (aka tail). Updated by code running on the
974 * target after it consumes data.
975 * [buffer_start + 8, buffer_start + buffer_size):
976 * Circular buffer contents.
978 * See contrib/loaders/flash/stm32f1x.S for an example.
980 * @param target used to run the algorithm
981 * @param buffer address on the host where data to be sent is located
982 * @param count number of blocks to send
983 * @param block_size size in bytes of each block
984 * @param num_mem_params count of memory-based params to pass to algorithm
985 * @param mem_params memory-based params to pass to algorithm
986 * @param num_reg_params count of register-based params to pass to algorithm
987 * @param reg_params memory-based params to pass to algorithm
988 * @param buffer_start address on the target of the circular buffer structure
989 * @param buffer_size size of the circular buffer structure
990 * @param entry_point address on the target to execute to start the algorithm
991 * @param exit_point address at which to set a breakpoint to catch the
992 * end of the algorithm; can be 0 if target triggers a breakpoint itself
996 int target_run_flash_async_algorithm(struct target *target,
997 const uint8_t *buffer, uint32_t count, int block_size,
998 int num_mem_params, struct mem_param *mem_params,
999 int num_reg_params, struct reg_param *reg_params,
1000 uint32_t buffer_start, uint32_t buffer_size,
1001 uint32_t entry_point, uint32_t exit_point, void *arch_info)
1006 const uint8_t *buffer_orig = buffer;
1008 /* Set up working area. First word is write pointer, second word is read pointer,
1009 * rest is fifo data area. */
1010 uint32_t wp_addr = buffer_start;
1011 uint32_t rp_addr = buffer_start + 4;
1012 uint32_t fifo_start_addr = buffer_start + 8;
1013 uint32_t fifo_end_addr = buffer_start + buffer_size;
1015 uint32_t wp = fifo_start_addr;
1016 uint32_t rp = fifo_start_addr;
1018 /* validate block_size is 2^n */
1019 assert(IS_PWR_OF_2(block_size));
1021 retval = target_write_u32(target, wp_addr, wp);
1022 if (retval != ERROR_OK)
1024 retval = target_write_u32(target, rp_addr, rp);
1025 if (retval != ERROR_OK)
1028 /* Start up algorithm on target and let it idle while writing the first chunk */
1029 retval = target_start_algorithm(target, num_mem_params, mem_params,
1030 num_reg_params, reg_params,
1035 if (retval != ERROR_OK) {
1036 LOG_ERROR("error starting target flash write algorithm");
1042 retval = target_read_u32(target, rp_addr, &rp);
1043 if (retval != ERROR_OK) {
1044 LOG_ERROR("failed to get read pointer");
1048 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1049 (size_t) (buffer - buffer_orig), count, wp, rp);
1052 LOG_ERROR("flash write algorithm aborted by target");
1053 retval = ERROR_FLASH_OPERATION_FAILED;
1057 if (!IS_ALIGNED(rp - fifo_start_addr, block_size) || rp < fifo_start_addr || rp >= fifo_end_addr) {
1058 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
1062 /* Count the number of bytes available in the fifo without
1063 * crossing the wrap around. Make sure to not fill it completely,
1064 * because that would make wp == rp and that's the empty condition. */
1065 uint32_t thisrun_bytes;
1067 thisrun_bytes = rp - wp - block_size;
1068 else if (rp > fifo_start_addr)
1069 thisrun_bytes = fifo_end_addr - wp;
1071 thisrun_bytes = fifo_end_addr - wp - block_size;
1073 if (thisrun_bytes == 0) {
1074 /* Throttle polling a bit if transfer is (much) faster than flash
1075 * programming. The exact delay shouldn't matter as long as it's
1076 * less than buffer size / flash speed. This is very unlikely to
1077 * run when using high latency connections such as USB. */
1080 /* to stop an infinite loop on some targets check and increment a timeout
1081 * this issue was observed on a stellaris using the new ICDI interface */
1082 if (timeout++ >= 2500) {
1083 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1084 return ERROR_FLASH_OPERATION_FAILED;
1089 /* reset our timeout */
1092 /* Limit to the amount of data we actually want to write */
1093 if (thisrun_bytes > count * block_size)
1094 thisrun_bytes = count * block_size;
1096 /* Force end of large blocks to be word aligned */
1097 if (thisrun_bytes >= 16)
1098 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1100 /* Write data to fifo */
1101 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
1102 if (retval != ERROR_OK)
1105 /* Update counters and wrap write pointer */
1106 buffer += thisrun_bytes;
1107 count -= thisrun_bytes / block_size;
1108 wp += thisrun_bytes;
1109 if (wp >= fifo_end_addr)
1110 wp = fifo_start_addr;
1112 /* Store updated write pointer to target */
1113 retval = target_write_u32(target, wp_addr, wp);
1114 if (retval != ERROR_OK)
1117 /* Avoid GDB timeouts */
1121 if (retval != ERROR_OK) {
1122 /* abort flash write algorithm on target */
1123 target_write_u32(target, wp_addr, 0);
1126 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1127 num_reg_params, reg_params,
1132 if (retval2 != ERROR_OK) {
1133 LOG_ERROR("error waiting for target flash write algorithm");
1137 if (retval == ERROR_OK) {
1138 /* check if algorithm set rp = 0 after fifo writer loop finished */
1139 retval = target_read_u32(target, rp_addr, &rp);
1140 if (retval == ERROR_OK && rp == 0) {
1141 LOG_ERROR("flash write algorithm aborted by target");
1142 retval = ERROR_FLASH_OPERATION_FAILED;
1149 int target_run_read_async_algorithm(struct target *target,
1150 uint8_t *buffer, uint32_t count, int block_size,
1151 int num_mem_params, struct mem_param *mem_params,
1152 int num_reg_params, struct reg_param *reg_params,
1153 uint32_t buffer_start, uint32_t buffer_size,
1154 uint32_t entry_point, uint32_t exit_point, void *arch_info)
1159 const uint8_t *buffer_orig = buffer;
1161 /* Set up working area. First word is write pointer, second word is read pointer,
1162 * rest is fifo data area. */
1163 uint32_t wp_addr = buffer_start;
1164 uint32_t rp_addr = buffer_start + 4;
1165 uint32_t fifo_start_addr = buffer_start + 8;
1166 uint32_t fifo_end_addr = buffer_start + buffer_size;
1168 uint32_t wp = fifo_start_addr;
1169 uint32_t rp = fifo_start_addr;
1171 /* validate block_size is 2^n */
1172 assert(IS_PWR_OF_2(block_size));
1174 retval = target_write_u32(target, wp_addr, wp);
1175 if (retval != ERROR_OK)
1177 retval = target_write_u32(target, rp_addr, rp);
1178 if (retval != ERROR_OK)
1181 /* Start up algorithm on target */
1182 retval = target_start_algorithm(target, num_mem_params, mem_params,
1183 num_reg_params, reg_params,
1188 if (retval != ERROR_OK) {
1189 LOG_ERROR("error starting target flash read algorithm");
1194 retval = target_read_u32(target, wp_addr, &wp);
1195 if (retval != ERROR_OK) {
1196 LOG_ERROR("failed to get write pointer");
1200 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1201 (size_t)(buffer - buffer_orig), count, wp, rp);
1204 LOG_ERROR("flash read algorithm aborted by target");
1205 retval = ERROR_FLASH_OPERATION_FAILED;
1209 if (!IS_ALIGNED(wp - fifo_start_addr, block_size) || wp < fifo_start_addr || wp >= fifo_end_addr) {
1210 LOG_ERROR("corrupted fifo write pointer 0x%" PRIx32, wp);
1214 /* Count the number of bytes available in the fifo without
1215 * crossing the wrap around. */
1216 uint32_t thisrun_bytes;
1218 thisrun_bytes = wp - rp;
1220 thisrun_bytes = fifo_end_addr - rp;
1222 if (thisrun_bytes == 0) {
1223 /* Throttle polling a bit if transfer is (much) faster than flash
1224 * reading. The exact delay shouldn't matter as long as it's
1225 * less than buffer size / flash speed. This is very unlikely to
1226 * run when using high latency connections such as USB. */
1229 /* to stop an infinite loop on some targets check and increment a timeout
1230 * this issue was observed on a stellaris using the new ICDI interface */
1231 if (timeout++ >= 2500) {
1232 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1233 return ERROR_FLASH_OPERATION_FAILED;
1238 /* Reset our timeout */
1241 /* Limit to the amount of data we actually want to read */
1242 if (thisrun_bytes > count * block_size)
1243 thisrun_bytes = count * block_size;
1245 /* Force end of large blocks to be word aligned */
1246 if (thisrun_bytes >= 16)
1247 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1249 /* Read data from fifo */
1250 retval = target_read_buffer(target, rp, thisrun_bytes, buffer);
1251 if (retval != ERROR_OK)
1254 /* Update counters and wrap write pointer */
1255 buffer += thisrun_bytes;
1256 count -= thisrun_bytes / block_size;
1257 rp += thisrun_bytes;
1258 if (rp >= fifo_end_addr)
1259 rp = fifo_start_addr;
1261 /* Store updated write pointer to target */
1262 retval = target_write_u32(target, rp_addr, rp);
1263 if (retval != ERROR_OK)
1266 /* Avoid GDB timeouts */
1271 if (retval != ERROR_OK) {
1272 /* abort flash write algorithm on target */
1273 target_write_u32(target, rp_addr, 0);
1276 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1277 num_reg_params, reg_params,
1282 if (retval2 != ERROR_OK) {
1283 LOG_ERROR("error waiting for target flash write algorithm");
1287 if (retval == ERROR_OK) {
1288 /* check if algorithm set wp = 0 after fifo writer loop finished */
1289 retval = target_read_u32(target, wp_addr, &wp);
1290 if (retval == ERROR_OK && wp == 0) {
1291 LOG_ERROR("flash read algorithm aborted by target");
1292 retval = ERROR_FLASH_OPERATION_FAILED;
1299 int target_read_memory(struct target *target,
1300 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1302 if (!target_was_examined(target)) {
1303 LOG_ERROR("Target not examined yet");
1306 if (!target->type->read_memory) {
1307 LOG_ERROR("Target %s doesn't support read_memory", target_name(target));
1310 return target->type->read_memory(target, address, size, count, buffer);
1313 int target_read_phys_memory(struct target *target,
1314 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1316 if (!target_was_examined(target)) {
1317 LOG_ERROR("Target not examined yet");
1320 if (!target->type->read_phys_memory) {
1321 LOG_ERROR("Target %s doesn't support read_phys_memory", target_name(target));
1324 return target->type->read_phys_memory(target, address, size, count, buffer);
1327 int target_write_memory(struct target *target,
1328 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1330 if (!target_was_examined(target)) {
1331 LOG_ERROR("Target not examined yet");
1334 if (!target->type->write_memory) {
1335 LOG_ERROR("Target %s doesn't support write_memory", target_name(target));
1338 return target->type->write_memory(target, address, size, count, buffer);
1341 int target_write_phys_memory(struct target *target,
1342 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1344 if (!target_was_examined(target)) {
1345 LOG_ERROR("Target not examined yet");
1348 if (!target->type->write_phys_memory) {
1349 LOG_ERROR("Target %s doesn't support write_phys_memory", target_name(target));
1352 return target->type->write_phys_memory(target, address, size, count, buffer);
1355 int target_add_breakpoint(struct target *target,
1356 struct breakpoint *breakpoint)
1358 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1359 LOG_WARNING("target %s is not halted (add breakpoint)", target_name(target));
1360 return ERROR_TARGET_NOT_HALTED;
1362 return target->type->add_breakpoint(target, breakpoint);
1365 int target_add_context_breakpoint(struct target *target,
1366 struct breakpoint *breakpoint)
1368 if (target->state != TARGET_HALTED) {
1369 LOG_WARNING("target %s is not halted (add context breakpoint)", target_name(target));
1370 return ERROR_TARGET_NOT_HALTED;
1372 return target->type->add_context_breakpoint(target, breakpoint);
1375 int target_add_hybrid_breakpoint(struct target *target,
1376 struct breakpoint *breakpoint)
1378 if (target->state != TARGET_HALTED) {
1379 LOG_WARNING("target %s is not halted (add hybrid breakpoint)", target_name(target));
1380 return ERROR_TARGET_NOT_HALTED;
1382 return target->type->add_hybrid_breakpoint(target, breakpoint);
1385 int target_remove_breakpoint(struct target *target,
1386 struct breakpoint *breakpoint)
1388 return target->type->remove_breakpoint(target, breakpoint);
1391 int target_add_watchpoint(struct target *target,
1392 struct watchpoint *watchpoint)
1394 if (target->state != TARGET_HALTED) {
1395 LOG_WARNING("target %s is not halted (add watchpoint)", target_name(target));
1396 return ERROR_TARGET_NOT_HALTED;
1398 return target->type->add_watchpoint(target, watchpoint);
1400 int target_remove_watchpoint(struct target *target,
1401 struct watchpoint *watchpoint)
1403 return target->type->remove_watchpoint(target, watchpoint);
1405 int target_hit_watchpoint(struct target *target,
1406 struct watchpoint **hit_watchpoint)
1408 if (target->state != TARGET_HALTED) {
1409 LOG_WARNING("target %s is not halted (hit watchpoint)", target->cmd_name);
1410 return ERROR_TARGET_NOT_HALTED;
1413 if (!target->type->hit_watchpoint) {
1414 /* For backward compatible, if hit_watchpoint is not implemented,
1415 * return ERROR_FAIL such that gdb_server will not take the nonsense
1420 return target->type->hit_watchpoint(target, hit_watchpoint);
1423 const char *target_get_gdb_arch(struct target *target)
1425 if (!target->type->get_gdb_arch)
1427 return target->type->get_gdb_arch(target);
1430 int target_get_gdb_reg_list(struct target *target,
1431 struct reg **reg_list[], int *reg_list_size,
1432 enum target_register_class reg_class)
1434 int result = ERROR_FAIL;
1436 if (!target_was_examined(target)) {
1437 LOG_ERROR("Target not examined yet");
1441 result = target->type->get_gdb_reg_list(target, reg_list,
1442 reg_list_size, reg_class);
1445 if (result != ERROR_OK) {
1452 int target_get_gdb_reg_list_noread(struct target *target,
1453 struct reg **reg_list[], int *reg_list_size,
1454 enum target_register_class reg_class)
1456 if (target->type->get_gdb_reg_list_noread &&
1457 target->type->get_gdb_reg_list_noread(target, reg_list,
1458 reg_list_size, reg_class) == ERROR_OK)
1460 return target_get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1463 bool target_supports_gdb_connection(struct target *target)
1466 * exclude all the targets that don't provide get_gdb_reg_list
1467 * or that have explicit gdb_max_connection == 0
1469 return !!target->type->get_gdb_reg_list && !!target->gdb_max_connections;
1472 int target_step(struct target *target,
1473 int current, target_addr_t address, int handle_breakpoints)
1477 target_call_event_callbacks(target, TARGET_EVENT_STEP_START);
1479 retval = target->type->step(target, current, address, handle_breakpoints);
1480 if (retval != ERROR_OK)
1483 target_call_event_callbacks(target, TARGET_EVENT_STEP_END);
1488 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1490 if (target->state != TARGET_HALTED) {
1491 LOG_WARNING("target %s is not halted (gdb fileio)", target->cmd_name);
1492 return ERROR_TARGET_NOT_HALTED;
1494 return target->type->get_gdb_fileio_info(target, fileio_info);
1497 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1499 if (target->state != TARGET_HALTED) {
1500 LOG_WARNING("target %s is not halted (gdb fileio end)", target->cmd_name);
1501 return ERROR_TARGET_NOT_HALTED;
1503 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1506 target_addr_t target_address_max(struct target *target)
1508 unsigned bits = target_address_bits(target);
1509 if (sizeof(target_addr_t) * 8 == bits)
1510 return (target_addr_t) -1;
1512 return (((target_addr_t) 1) << bits) - 1;
1515 unsigned target_address_bits(struct target *target)
1517 if (target->type->address_bits)
1518 return target->type->address_bits(target);
1522 unsigned int target_data_bits(struct target *target)
1524 if (target->type->data_bits)
1525 return target->type->data_bits(target);
1529 static int target_profiling(struct target *target, uint32_t *samples,
1530 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1532 return target->type->profiling(target, samples, max_num_samples,
1533 num_samples, seconds);
1536 static int handle_target(void *priv);
1538 static int target_init_one(struct command_context *cmd_ctx,
1539 struct target *target)
1541 target_reset_examined(target);
1543 struct target_type *type = target->type;
1545 type->examine = default_examine;
1547 if (!type->check_reset)
1548 type->check_reset = default_check_reset;
1550 assert(type->init_target);
1552 int retval = type->init_target(cmd_ctx, target);
1553 if (retval != ERROR_OK) {
1554 LOG_ERROR("target '%s' init failed", target_name(target));
1558 /* Sanity-check MMU support ... stub in what we must, to help
1559 * implement it in stages, but warn if we need to do so.
1562 if (!type->virt2phys) {
1563 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1564 type->virt2phys = identity_virt2phys;
1567 /* Make sure no-MMU targets all behave the same: make no
1568 * distinction between physical and virtual addresses, and
1569 * ensure that virt2phys() is always an identity mapping.
1571 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1572 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1575 type->write_phys_memory = type->write_memory;
1576 type->read_phys_memory = type->read_memory;
1577 type->virt2phys = identity_virt2phys;
1580 if (!target->type->read_buffer)
1581 target->type->read_buffer = target_read_buffer_default;
1583 if (!target->type->write_buffer)
1584 target->type->write_buffer = target_write_buffer_default;
1586 if (!target->type->get_gdb_fileio_info)
1587 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1589 if (!target->type->gdb_fileio_end)
1590 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1592 if (!target->type->profiling)
1593 target->type->profiling = target_profiling_default;
1598 static int target_init(struct command_context *cmd_ctx)
1600 struct target *target;
1603 for (target = all_targets; target; target = target->next) {
1604 retval = target_init_one(cmd_ctx, target);
1605 if (retval != ERROR_OK)
1612 retval = target_register_user_commands(cmd_ctx);
1613 if (retval != ERROR_OK)
1616 retval = target_register_timer_callback(&handle_target,
1617 polling_interval, TARGET_TIMER_TYPE_PERIODIC, cmd_ctx->interp);
1618 if (retval != ERROR_OK)
1624 COMMAND_HANDLER(handle_target_init_command)
1629 return ERROR_COMMAND_SYNTAX_ERROR;
1631 static bool target_initialized;
1632 if (target_initialized) {
1633 LOG_INFO("'target init' has already been called");
1636 target_initialized = true;
1638 retval = command_run_line(CMD_CTX, "init_targets");
1639 if (retval != ERROR_OK)
1642 retval = command_run_line(CMD_CTX, "init_target_events");
1643 if (retval != ERROR_OK)
1646 retval = command_run_line(CMD_CTX, "init_board");
1647 if (retval != ERROR_OK)
1650 LOG_DEBUG("Initializing targets...");
1651 return target_init(CMD_CTX);
1654 int target_register_event_callback(int (*callback)(struct target *target,
1655 enum target_event event, void *priv), void *priv)
1657 struct target_event_callback **callbacks_p = &target_event_callbacks;
1660 return ERROR_COMMAND_SYNTAX_ERROR;
1663 while ((*callbacks_p)->next)
1664 callbacks_p = &((*callbacks_p)->next);
1665 callbacks_p = &((*callbacks_p)->next);
1668 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1669 (*callbacks_p)->callback = callback;
1670 (*callbacks_p)->priv = priv;
1671 (*callbacks_p)->next = NULL;
1676 int target_register_reset_callback(int (*callback)(struct target *target,
1677 enum target_reset_mode reset_mode, void *priv), void *priv)
1679 struct target_reset_callback *entry;
1682 return ERROR_COMMAND_SYNTAX_ERROR;
1684 entry = malloc(sizeof(struct target_reset_callback));
1686 LOG_ERROR("error allocating buffer for reset callback entry");
1687 return ERROR_COMMAND_SYNTAX_ERROR;
1690 entry->callback = callback;
1692 list_add(&entry->list, &target_reset_callback_list);
1698 int target_register_trace_callback(int (*callback)(struct target *target,
1699 size_t len, uint8_t *data, void *priv), void *priv)
1701 struct target_trace_callback *entry;
1704 return ERROR_COMMAND_SYNTAX_ERROR;
1706 entry = malloc(sizeof(struct target_trace_callback));
1708 LOG_ERROR("error allocating buffer for trace callback entry");
1709 return ERROR_COMMAND_SYNTAX_ERROR;
1712 entry->callback = callback;
1714 list_add(&entry->list, &target_trace_callback_list);
1720 int target_register_timer_callback(int (*callback)(void *priv),
1721 unsigned int time_ms, enum target_timer_type type, void *priv)
1723 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1726 return ERROR_COMMAND_SYNTAX_ERROR;
1729 while ((*callbacks_p)->next)
1730 callbacks_p = &((*callbacks_p)->next);
1731 callbacks_p = &((*callbacks_p)->next);
1734 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1735 (*callbacks_p)->callback = callback;
1736 (*callbacks_p)->type = type;
1737 (*callbacks_p)->time_ms = time_ms;
1738 (*callbacks_p)->removed = false;
1740 (*callbacks_p)->when = timeval_ms() + time_ms;
1741 target_timer_next_event_value = MIN(target_timer_next_event_value, (*callbacks_p)->when);
1743 (*callbacks_p)->priv = priv;
1744 (*callbacks_p)->next = NULL;
1749 int target_unregister_event_callback(int (*callback)(struct target *target,
1750 enum target_event event, void *priv), void *priv)
1752 struct target_event_callback **p = &target_event_callbacks;
1753 struct target_event_callback *c = target_event_callbacks;
1756 return ERROR_COMMAND_SYNTAX_ERROR;
1759 struct target_event_callback *next = c->next;
1760 if ((c->callback == callback) && (c->priv == priv)) {
1772 int target_unregister_reset_callback(int (*callback)(struct target *target,
1773 enum target_reset_mode reset_mode, void *priv), void *priv)
1775 struct target_reset_callback *entry;
1778 return ERROR_COMMAND_SYNTAX_ERROR;
1780 list_for_each_entry(entry, &target_reset_callback_list, list) {
1781 if (entry->callback == callback && entry->priv == priv) {
1782 list_del(&entry->list);
1791 int target_unregister_trace_callback(int (*callback)(struct target *target,
1792 size_t len, uint8_t *data, void *priv), void *priv)
1794 struct target_trace_callback *entry;
1797 return ERROR_COMMAND_SYNTAX_ERROR;
1799 list_for_each_entry(entry, &target_trace_callback_list, list) {
1800 if (entry->callback == callback && entry->priv == priv) {
1801 list_del(&entry->list);
1810 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1813 return ERROR_COMMAND_SYNTAX_ERROR;
1815 for (struct target_timer_callback *c = target_timer_callbacks;
1817 if ((c->callback == callback) && (c->priv == priv)) {
1826 int target_call_event_callbacks(struct target *target, enum target_event event)
1828 struct target_event_callback *callback = target_event_callbacks;
1829 struct target_event_callback *next_callback;
1831 if (event == TARGET_EVENT_HALTED) {
1832 /* execute early halted first */
1833 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1836 LOG_DEBUG("target event %i (%s) for core %s", event,
1837 jim_nvp_value2name_simple(nvp_target_event, event)->name,
1838 target_name(target));
1840 target_handle_event(target, event);
1843 next_callback = callback->next;
1844 callback->callback(target, event, callback->priv);
1845 callback = next_callback;
1851 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1853 struct target_reset_callback *callback;
1855 LOG_DEBUG("target reset %i (%s)", reset_mode,
1856 jim_nvp_value2name_simple(nvp_reset_modes, reset_mode)->name);
1858 list_for_each_entry(callback, &target_reset_callback_list, list)
1859 callback->callback(target, reset_mode, callback->priv);
1864 int target_call_trace_callbacks(struct target *target, size_t len, uint8_t *data)
1866 struct target_trace_callback *callback;
1868 list_for_each_entry(callback, &target_trace_callback_list, list)
1869 callback->callback(target, len, data, callback->priv);
1874 static int target_timer_callback_periodic_restart(
1875 struct target_timer_callback *cb, int64_t *now)
1877 cb->when = *now + cb->time_ms;
1881 static int target_call_timer_callback(struct target_timer_callback *cb,
1884 cb->callback(cb->priv);
1886 if (cb->type == TARGET_TIMER_TYPE_PERIODIC)
1887 return target_timer_callback_periodic_restart(cb, now);
1889 return target_unregister_timer_callback(cb->callback, cb->priv);
1892 static int target_call_timer_callbacks_check_time(int checktime)
1894 static bool callback_processing;
1896 /* Do not allow nesting */
1897 if (callback_processing)
1900 callback_processing = true;
1904 int64_t now = timeval_ms();
1906 /* Initialize to a default value that's a ways into the future.
1907 * The loop below will make it closer to now if there are
1908 * callbacks that want to be called sooner. */
1909 target_timer_next_event_value = now + 1000;
1911 /* Store an address of the place containing a pointer to the
1912 * next item; initially, that's a standalone "root of the
1913 * list" variable. */
1914 struct target_timer_callback **callback = &target_timer_callbacks;
1915 while (callback && *callback) {
1916 if ((*callback)->removed) {
1917 struct target_timer_callback *p = *callback;
1918 *callback = (*callback)->next;
1923 bool call_it = (*callback)->callback &&
1924 ((!checktime && (*callback)->type == TARGET_TIMER_TYPE_PERIODIC) ||
1925 now >= (*callback)->when);
1928 target_call_timer_callback(*callback, &now);
1930 if (!(*callback)->removed && (*callback)->when < target_timer_next_event_value)
1931 target_timer_next_event_value = (*callback)->when;
1933 callback = &(*callback)->next;
1936 callback_processing = false;
1940 int target_call_timer_callbacks()
1942 return target_call_timer_callbacks_check_time(1);
1945 /* invoke periodic callbacks immediately */
1946 int target_call_timer_callbacks_now()
1948 return target_call_timer_callbacks_check_time(0);
1951 int64_t target_timer_next_event(void)
1953 return target_timer_next_event_value;
1956 /* Prints the working area layout for debug purposes */
1957 static void print_wa_layout(struct target *target)
1959 struct working_area *c = target->working_areas;
1962 LOG_DEBUG("%c%c " TARGET_ADDR_FMT "-" TARGET_ADDR_FMT " (%" PRIu32 " bytes)",
1963 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1964 c->address, c->address + c->size - 1, c->size);
1969 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1970 static void target_split_working_area(struct working_area *area, uint32_t size)
1972 assert(area->free); /* Shouldn't split an allocated area */
1973 assert(size <= area->size); /* Caller should guarantee this */
1975 /* Split only if not already the right size */
1976 if (size < area->size) {
1977 struct working_area *new_wa = malloc(sizeof(*new_wa));
1982 new_wa->next = area->next;
1983 new_wa->size = area->size - size;
1984 new_wa->address = area->address + size;
1985 new_wa->backup = NULL;
1986 new_wa->user = NULL;
1987 new_wa->free = true;
1989 area->next = new_wa;
1992 /* If backup memory was allocated to this area, it has the wrong size
1993 * now so free it and it will be reallocated if/when needed */
1995 area->backup = NULL;
1999 /* Merge all adjacent free areas into one */
2000 static void target_merge_working_areas(struct target *target)
2002 struct working_area *c = target->working_areas;
2004 while (c && c->next) {
2005 assert(c->next->address == c->address + c->size); /* This is an invariant */
2007 /* Find two adjacent free areas */
2008 if (c->free && c->next->free) {
2009 /* Merge the last into the first */
2010 c->size += c->next->size;
2012 /* Remove the last */
2013 struct working_area *to_be_freed = c->next;
2014 c->next = c->next->next;
2015 free(to_be_freed->backup);
2018 /* If backup memory was allocated to the remaining area, it's has
2019 * the wrong size now */
2028 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
2030 /* Reevaluate working area address based on MMU state*/
2031 if (!target->working_areas) {
2035 retval = target->type->mmu(target, &enabled);
2036 if (retval != ERROR_OK)
2040 if (target->working_area_phys_spec) {
2041 LOG_DEBUG("MMU disabled, using physical "
2042 "address for working memory " TARGET_ADDR_FMT,
2043 target->working_area_phys);
2044 target->working_area = target->working_area_phys;
2046 LOG_ERROR("No working memory available. "
2047 "Specify -work-area-phys to target.");
2048 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2051 if (target->working_area_virt_spec) {
2052 LOG_DEBUG("MMU enabled, using virtual "
2053 "address for working memory " TARGET_ADDR_FMT,
2054 target->working_area_virt);
2055 target->working_area = target->working_area_virt;
2057 LOG_ERROR("No working memory available. "
2058 "Specify -work-area-virt to target.");
2059 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2063 /* Set up initial working area on first call */
2064 struct working_area *new_wa = malloc(sizeof(*new_wa));
2066 new_wa->next = NULL;
2067 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
2068 new_wa->address = target->working_area;
2069 new_wa->backup = NULL;
2070 new_wa->user = NULL;
2071 new_wa->free = true;
2074 target->working_areas = new_wa;
2077 /* only allocate multiples of 4 byte */
2079 size = (size + 3) & (~3UL);
2081 struct working_area *c = target->working_areas;
2083 /* Find the first large enough working area */
2085 if (c->free && c->size >= size)
2091 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2093 /* Split the working area into the requested size */
2094 target_split_working_area(c, size);
2096 LOG_DEBUG("allocated new working area of %" PRIu32 " bytes at address " TARGET_ADDR_FMT,
2099 if (target->backup_working_area) {
2101 c->backup = malloc(c->size);
2106 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
2107 if (retval != ERROR_OK)
2111 /* mark as used, and return the new (reused) area */
2118 print_wa_layout(target);
2123 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
2127 retval = target_alloc_working_area_try(target, size, area);
2128 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
2129 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
2134 static int target_restore_working_area(struct target *target, struct working_area *area)
2136 int retval = ERROR_OK;
2138 if (target->backup_working_area && area->backup) {
2139 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
2140 if (retval != ERROR_OK)
2141 LOG_ERROR("failed to restore %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2142 area->size, area->address);
2148 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
2149 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
2151 int retval = ERROR_OK;
2157 retval = target_restore_working_area(target, area);
2158 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
2159 if (retval != ERROR_OK)
2165 LOG_DEBUG("freed %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2166 area->size, area->address);
2168 /* mark user pointer invalid */
2169 /* TODO: Is this really safe? It points to some previous caller's memory.
2170 * How could we know that the area pointer is still in that place and not
2171 * some other vital data? What's the purpose of this, anyway? */
2175 target_merge_working_areas(target);
2177 print_wa_layout(target);
2182 int target_free_working_area(struct target *target, struct working_area *area)
2184 return target_free_working_area_restore(target, area, 1);
2187 /* free resources and restore memory, if restoring memory fails,
2188 * free up resources anyway
2190 static void target_free_all_working_areas_restore(struct target *target, int restore)
2192 struct working_area *c = target->working_areas;
2194 LOG_DEBUG("freeing all working areas");
2196 /* Loop through all areas, restoring the allocated ones and marking them as free */
2200 target_restore_working_area(target, c);
2202 *c->user = NULL; /* Same as above */
2208 /* Run a merge pass to combine all areas into one */
2209 target_merge_working_areas(target);
2211 print_wa_layout(target);
2214 void target_free_all_working_areas(struct target *target)
2216 target_free_all_working_areas_restore(target, 1);
2218 /* Now we have none or only one working area marked as free */
2219 if (target->working_areas) {
2220 /* Free the last one to allow on-the-fly moving and resizing */
2221 free(target->working_areas->backup);
2222 free(target->working_areas);
2223 target->working_areas = NULL;
2227 /* Find the largest number of bytes that can be allocated */
2228 uint32_t target_get_working_area_avail(struct target *target)
2230 struct working_area *c = target->working_areas;
2231 uint32_t max_size = 0;
2234 return target->working_area_size;
2237 if (c->free && max_size < c->size)
2246 static void target_destroy(struct target *target)
2248 if (target->type->deinit_target)
2249 target->type->deinit_target(target);
2251 free(target->semihosting);
2253 jtag_unregister_event_callback(jtag_enable_callback, target);
2255 struct target_event_action *teap = target->event_action;
2257 struct target_event_action *next = teap->next;
2258 Jim_DecrRefCount(teap->interp, teap->body);
2263 target_free_all_working_areas(target);
2265 /* release the targets SMP list */
2267 struct target_list *head = target->head;
2269 struct target_list *pos = head->next;
2270 head->target->smp = 0;
2277 rtos_destroy(target);
2279 free(target->gdb_port_override);
2281 free(target->trace_info);
2282 free(target->fileio_info);
2283 free(target->cmd_name);
2287 void target_quit(void)
2289 struct target_event_callback *pe = target_event_callbacks;
2291 struct target_event_callback *t = pe->next;
2295 target_event_callbacks = NULL;
2297 struct target_timer_callback *pt = target_timer_callbacks;
2299 struct target_timer_callback *t = pt->next;
2303 target_timer_callbacks = NULL;
2305 for (struct target *target = all_targets; target;) {
2309 target_destroy(target);
2316 int target_arch_state(struct target *target)
2320 LOG_WARNING("No target has been configured");
2324 if (target->state != TARGET_HALTED)
2327 retval = target->type->arch_state(target);
2331 static int target_get_gdb_fileio_info_default(struct target *target,
2332 struct gdb_fileio_info *fileio_info)
2334 /* If target does not support semi-hosting function, target
2335 has no need to provide .get_gdb_fileio_info callback.
2336 It just return ERROR_FAIL and gdb_server will return "Txx"
2337 as target halted every time. */
2341 static int target_gdb_fileio_end_default(struct target *target,
2342 int retcode, int fileio_errno, bool ctrl_c)
2347 int target_profiling_default(struct target *target, uint32_t *samples,
2348 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
2350 struct timeval timeout, now;
2352 gettimeofday(&timeout, NULL);
2353 timeval_add_time(&timeout, seconds, 0);
2355 LOG_INFO("Starting profiling. Halting and resuming the"
2356 " target as often as we can...");
2358 uint32_t sample_count = 0;
2359 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2360 struct reg *reg = register_get_by_name(target->reg_cache, "pc", true);
2362 int retval = ERROR_OK;
2364 target_poll(target);
2365 if (target->state == TARGET_HALTED) {
2366 uint32_t t = buf_get_u32(reg->value, 0, 32);
2367 samples[sample_count++] = t;
2368 /* current pc, addr = 0, do not handle breakpoints, not debugging */
2369 retval = target_resume(target, 1, 0, 0, 0);
2370 target_poll(target);
2371 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2372 } else if (target->state == TARGET_RUNNING) {
2373 /* We want to quickly sample the PC. */
2374 retval = target_halt(target);
2376 LOG_INFO("Target not halted or running");
2381 if (retval != ERROR_OK)
2384 gettimeofday(&now, NULL);
2385 if ((sample_count >= max_num_samples) || timeval_compare(&now, &timeout) >= 0) {
2386 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2391 *num_samples = sample_count;
2395 /* Single aligned words are guaranteed to use 16 or 32 bit access
2396 * mode respectively, otherwise data is handled as quickly as
2399 int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
2401 LOG_DEBUG("writing buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2404 if (!target_was_examined(target)) {
2405 LOG_ERROR("Target not examined yet");
2412 if ((address + size - 1) < address) {
2413 /* GDB can request this when e.g. PC is 0xfffffffc */
2414 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2420 return target->type->write_buffer(target, address, size, buffer);
2423 static int target_write_buffer_default(struct target *target,
2424 target_addr_t address, uint32_t count, const uint8_t *buffer)
2427 unsigned int data_bytes = target_data_bits(target) / 8;
2429 /* Align up to maximum bytes. The loop condition makes sure the next pass
2430 * will have something to do with the size we leave to it. */
2432 size < data_bytes && count >= size * 2 + (address & size);
2434 if (address & size) {
2435 int retval = target_write_memory(target, address, size, 1, buffer);
2436 if (retval != ERROR_OK)
2444 /* Write the data with as large access size as possible. */
2445 for (; size > 0; size /= 2) {
2446 uint32_t aligned = count - count % size;
2448 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2449 if (retval != ERROR_OK)
2460 /* Single aligned words are guaranteed to use 16 or 32 bit access
2461 * mode respectively, otherwise data is handled as quickly as
2464 int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
2466 LOG_DEBUG("reading buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2469 if (!target_was_examined(target)) {
2470 LOG_ERROR("Target not examined yet");
2477 if ((address + size - 1) < address) {
2478 /* GDB can request this when e.g. PC is 0xfffffffc */
2479 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2485 return target->type->read_buffer(target, address, size, buffer);
2488 static int target_read_buffer_default(struct target *target, target_addr_t address, uint32_t count, uint8_t *buffer)
2491 unsigned int data_bytes = target_data_bits(target) / 8;
2493 /* Align up to maximum bytes. The loop condition makes sure the next pass
2494 * will have something to do with the size we leave to it. */
2496 size < data_bytes && count >= size * 2 + (address & size);
2498 if (address & size) {
2499 int retval = target_read_memory(target, address, size, 1, buffer);
2500 if (retval != ERROR_OK)
2508 /* Read the data with as large access size as possible. */
2509 for (; size > 0; size /= 2) {
2510 uint32_t aligned = count - count % size;
2512 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2513 if (retval != ERROR_OK)
2524 int target_checksum_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t *crc)
2529 uint32_t checksum = 0;
2530 if (!target_was_examined(target)) {
2531 LOG_ERROR("Target not examined yet");
2535 retval = target->type->checksum_memory(target, address, size, &checksum);
2536 if (retval != ERROR_OK) {
2537 buffer = malloc(size);
2539 LOG_ERROR("error allocating buffer for section (%" PRIu32 " bytes)", size);
2540 return ERROR_COMMAND_SYNTAX_ERROR;
2542 retval = target_read_buffer(target, address, size, buffer);
2543 if (retval != ERROR_OK) {
2548 /* convert to target endianness */
2549 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2550 uint32_t target_data;
2551 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2552 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2555 retval = image_calculate_checksum(buffer, size, &checksum);
2564 int target_blank_check_memory(struct target *target,
2565 struct target_memory_check_block *blocks, int num_blocks,
2566 uint8_t erased_value)
2568 if (!target_was_examined(target)) {
2569 LOG_ERROR("Target not examined yet");
2573 if (!target->type->blank_check_memory)
2574 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2576 return target->type->blank_check_memory(target, blocks, num_blocks, erased_value);
2579 int target_read_u64(struct target *target, target_addr_t address, uint64_t *value)
2581 uint8_t value_buf[8];
2582 if (!target_was_examined(target)) {
2583 LOG_ERROR("Target not examined yet");
2587 int retval = target_read_memory(target, address, 8, 1, value_buf);
2589 if (retval == ERROR_OK) {
2590 *value = target_buffer_get_u64(target, value_buf);
2591 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2596 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2603 int target_read_u32(struct target *target, target_addr_t address, uint32_t *value)
2605 uint8_t value_buf[4];
2606 if (!target_was_examined(target)) {
2607 LOG_ERROR("Target not examined yet");
2611 int retval = target_read_memory(target, address, 4, 1, value_buf);
2613 if (retval == ERROR_OK) {
2614 *value = target_buffer_get_u32(target, value_buf);
2615 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2620 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2627 int target_read_u16(struct target *target, target_addr_t address, uint16_t *value)
2629 uint8_t value_buf[2];
2630 if (!target_was_examined(target)) {
2631 LOG_ERROR("Target not examined yet");
2635 int retval = target_read_memory(target, address, 2, 1, value_buf);
2637 if (retval == ERROR_OK) {
2638 *value = target_buffer_get_u16(target, value_buf);
2639 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%4.4" PRIx16,
2644 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2651 int target_read_u8(struct target *target, target_addr_t address, uint8_t *value)
2653 if (!target_was_examined(target)) {
2654 LOG_ERROR("Target not examined yet");
2658 int retval = target_read_memory(target, address, 1, 1, value);
2660 if (retval == ERROR_OK) {
2661 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2666 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2673 int target_write_u64(struct target *target, target_addr_t address, uint64_t value)
2676 uint8_t value_buf[8];
2677 if (!target_was_examined(target)) {
2678 LOG_ERROR("Target not examined yet");
2682 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2686 target_buffer_set_u64(target, value_buf, value);
2687 retval = target_write_memory(target, address, 8, 1, value_buf);
2688 if (retval != ERROR_OK)
2689 LOG_DEBUG("failed: %i", retval);
2694 int target_write_u32(struct target *target, target_addr_t address, uint32_t value)
2697 uint8_t value_buf[4];
2698 if (!target_was_examined(target)) {
2699 LOG_ERROR("Target not examined yet");
2703 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2707 target_buffer_set_u32(target, value_buf, value);
2708 retval = target_write_memory(target, address, 4, 1, value_buf);
2709 if (retval != ERROR_OK)
2710 LOG_DEBUG("failed: %i", retval);
2715 int target_write_u16(struct target *target, target_addr_t address, uint16_t value)
2718 uint8_t value_buf[2];
2719 if (!target_was_examined(target)) {
2720 LOG_ERROR("Target not examined yet");
2724 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2728 target_buffer_set_u16(target, value_buf, value);
2729 retval = target_write_memory(target, address, 2, 1, value_buf);
2730 if (retval != ERROR_OK)
2731 LOG_DEBUG("failed: %i", retval);
2736 int target_write_u8(struct target *target, target_addr_t address, uint8_t value)
2739 if (!target_was_examined(target)) {
2740 LOG_ERROR("Target not examined yet");
2744 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2747 retval = target_write_memory(target, address, 1, 1, &value);
2748 if (retval != ERROR_OK)
2749 LOG_DEBUG("failed: %i", retval);
2754 int target_write_phys_u64(struct target *target, target_addr_t address, uint64_t value)
2757 uint8_t value_buf[8];
2758 if (!target_was_examined(target)) {
2759 LOG_ERROR("Target not examined yet");
2763 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2767 target_buffer_set_u64(target, value_buf, value);
2768 retval = target_write_phys_memory(target, address, 8, 1, value_buf);
2769 if (retval != ERROR_OK)
2770 LOG_DEBUG("failed: %i", retval);
2775 int target_write_phys_u32(struct target *target, target_addr_t address, uint32_t value)
2778 uint8_t value_buf[4];
2779 if (!target_was_examined(target)) {
2780 LOG_ERROR("Target not examined yet");
2784 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2788 target_buffer_set_u32(target, value_buf, value);
2789 retval = target_write_phys_memory(target, address, 4, 1, value_buf);
2790 if (retval != ERROR_OK)
2791 LOG_DEBUG("failed: %i", retval);
2796 int target_write_phys_u16(struct target *target, target_addr_t address, uint16_t value)
2799 uint8_t value_buf[2];
2800 if (!target_was_examined(target)) {
2801 LOG_ERROR("Target not examined yet");
2805 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2809 target_buffer_set_u16(target, value_buf, value);
2810 retval = target_write_phys_memory(target, address, 2, 1, value_buf);
2811 if (retval != ERROR_OK)
2812 LOG_DEBUG("failed: %i", retval);
2817 int target_write_phys_u8(struct target *target, target_addr_t address, uint8_t value)
2820 if (!target_was_examined(target)) {
2821 LOG_ERROR("Target not examined yet");
2825 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2828 retval = target_write_phys_memory(target, address, 1, 1, &value);
2829 if (retval != ERROR_OK)
2830 LOG_DEBUG("failed: %i", retval);
2835 static int find_target(struct command_invocation *cmd, const char *name)
2837 struct target *target = get_target(name);
2839 command_print(cmd, "Target: %s is unknown, try one of:\n", name);
2842 if (!target->tap->enabled) {
2843 command_print(cmd, "Target: TAP %s is disabled, "
2844 "can't be the current target\n",
2845 target->tap->dotted_name);
2849 cmd->ctx->current_target = target;
2850 if (cmd->ctx->current_target_override)
2851 cmd->ctx->current_target_override = target;
2857 COMMAND_HANDLER(handle_targets_command)
2859 int retval = ERROR_OK;
2860 if (CMD_ARGC == 1) {
2861 retval = find_target(CMD, CMD_ARGV[0]);
2862 if (retval == ERROR_OK) {
2868 struct target *target = all_targets;
2869 command_print(CMD, " TargetName Type Endian TapName State ");
2870 command_print(CMD, "-- ------------------ ---------- ------ ------------------ ------------");
2875 if (target->tap->enabled)
2876 state = target_state_name(target);
2878 state = "tap-disabled";
2880 if (CMD_CTX->current_target == target)
2883 /* keep columns lined up to match the headers above */
2885 "%2d%c %-18s %-10s %-6s %-18s %s",
2886 target->target_number,
2888 target_name(target),
2889 target_type_name(target),
2890 jim_nvp_value2name_simple(nvp_target_endian,
2891 target->endianness)->name,
2892 target->tap->dotted_name,
2894 target = target->next;
2900 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2902 static int power_dropout;
2903 static int srst_asserted;
2905 static int run_power_restore;
2906 static int run_power_dropout;
2907 static int run_srst_asserted;
2908 static int run_srst_deasserted;
2910 static int sense_handler(void)
2912 static int prev_srst_asserted;
2913 static int prev_power_dropout;
2915 int retval = jtag_power_dropout(&power_dropout);
2916 if (retval != ERROR_OK)
2920 power_restored = prev_power_dropout && !power_dropout;
2922 run_power_restore = 1;
2924 int64_t current = timeval_ms();
2925 static int64_t last_power;
2926 bool wait_more = last_power + 2000 > current;
2927 if (power_dropout && !wait_more) {
2928 run_power_dropout = 1;
2929 last_power = current;
2932 retval = jtag_srst_asserted(&srst_asserted);
2933 if (retval != ERROR_OK)
2936 int srst_deasserted;
2937 srst_deasserted = prev_srst_asserted && !srst_asserted;
2939 static int64_t last_srst;
2940 wait_more = last_srst + 2000 > current;
2941 if (srst_deasserted && !wait_more) {
2942 run_srst_deasserted = 1;
2943 last_srst = current;
2946 if (!prev_srst_asserted && srst_asserted)
2947 run_srst_asserted = 1;
2949 prev_srst_asserted = srst_asserted;
2950 prev_power_dropout = power_dropout;
2952 if (srst_deasserted || power_restored) {
2953 /* Other than logging the event we can't do anything here.
2954 * Issuing a reset is a particularly bad idea as we might
2955 * be inside a reset already.
2962 /* process target state changes */
2963 static int handle_target(void *priv)
2965 Jim_Interp *interp = (Jim_Interp *)priv;
2966 int retval = ERROR_OK;
2968 if (!is_jtag_poll_safe()) {
2969 /* polling is disabled currently */
2973 /* we do not want to recurse here... */
2974 static int recursive;
2978 /* danger! running these procedures can trigger srst assertions and power dropouts.
2979 * We need to avoid an infinite loop/recursion here and we do that by
2980 * clearing the flags after running these events.
2982 int did_something = 0;
2983 if (run_srst_asserted) {
2984 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2985 Jim_Eval(interp, "srst_asserted");
2988 if (run_srst_deasserted) {
2989 Jim_Eval(interp, "srst_deasserted");
2992 if (run_power_dropout) {
2993 LOG_INFO("Power dropout detected, running power_dropout proc.");
2994 Jim_Eval(interp, "power_dropout");
2997 if (run_power_restore) {
2998 Jim_Eval(interp, "power_restore");
3002 if (did_something) {
3003 /* clear detect flags */
3007 /* clear action flags */
3009 run_srst_asserted = 0;
3010 run_srst_deasserted = 0;
3011 run_power_restore = 0;
3012 run_power_dropout = 0;
3017 /* Poll targets for state changes unless that's globally disabled.
3018 * Skip targets that are currently disabled.
3020 for (struct target *target = all_targets;
3021 is_jtag_poll_safe() && target;
3022 target = target->next) {
3024 if (!target_was_examined(target))
3027 if (!target->tap->enabled)
3030 if (target->backoff.times > target->backoff.count) {
3031 /* do not poll this time as we failed previously */
3032 target->backoff.count++;
3035 target->backoff.count = 0;
3037 /* only poll target if we've got power and srst isn't asserted */
3038 if (!power_dropout && !srst_asserted) {
3039 /* polling may fail silently until the target has been examined */
3040 retval = target_poll(target);
3041 if (retval != ERROR_OK) {
3042 /* 100ms polling interval. Increase interval between polling up to 5000ms */
3043 if (target->backoff.times * polling_interval < 5000) {
3044 target->backoff.times *= 2;
3045 target->backoff.times++;
3048 /* Tell GDB to halt the debugger. This allows the user to
3049 * run monitor commands to handle the situation.
3051 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3053 if (target->backoff.times > 0) {
3054 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
3055 target_reset_examined(target);
3056 retval = target_examine_one(target);
3057 /* Target examination could have failed due to unstable connection,
3058 * but we set the examined flag anyway to repoll it later */
3059 if (retval != ERROR_OK) {
3060 target_set_examined(target);
3061 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
3062 target->backoff.times * polling_interval);
3067 /* Since we succeeded, we reset backoff count */
3068 target->backoff.times = 0;
3075 COMMAND_HANDLER(handle_reg_command)
3079 struct target *target = get_current_target(CMD_CTX);
3080 struct reg *reg = NULL;
3082 /* list all available registers for the current target */
3083 if (CMD_ARGC == 0) {
3084 struct reg_cache *cache = target->reg_cache;
3086 unsigned int count = 0;
3090 command_print(CMD, "===== %s", cache->name);
3092 for (i = 0, reg = cache->reg_list;
3093 i < cache->num_regs;
3094 i++, reg++, count++) {
3095 if (reg->exist == false || reg->hidden)
3097 /* only print cached values if they are valid */
3099 char *value = buf_to_hex_str(reg->value,
3102 "(%i) %s (/%" PRIu32 "): 0x%s%s",
3110 command_print(CMD, "(%i) %s (/%" PRIu32 ")",
3115 cache = cache->next;
3121 /* access a single register by its ordinal number */
3122 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
3124 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
3126 struct reg_cache *cache = target->reg_cache;
3127 unsigned int count = 0;
3130 for (i = 0; i < cache->num_regs; i++) {
3131 if (count++ == num) {
3132 reg = &cache->reg_list[i];
3138 cache = cache->next;
3142 command_print(CMD, "%i is out of bounds, the current target "
3143 "has only %i registers (0 - %i)", num, count, count - 1);
3147 /* access a single register by its name */
3148 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], true);
3154 assert(reg); /* give clang a hint that we *know* reg is != NULL here */
3159 /* display a register */
3160 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
3161 && (CMD_ARGV[1][0] <= '9')))) {
3162 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
3165 if (reg->valid == 0) {
3166 int retval = reg->type->get(reg);
3167 if (retval != ERROR_OK) {
3168 LOG_ERROR("Could not read register '%s'", reg->name);
3172 char *value = buf_to_hex_str(reg->value, reg->size);
3173 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3178 /* set register value */
3179 if (CMD_ARGC == 2) {
3180 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
3183 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
3185 int retval = reg->type->set(reg, buf);
3186 if (retval != ERROR_OK) {
3187 LOG_ERROR("Could not write to register '%s'", reg->name);
3189 char *value = buf_to_hex_str(reg->value, reg->size);
3190 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3199 return ERROR_COMMAND_SYNTAX_ERROR;
3202 command_print(CMD, "register %s not found in current target", CMD_ARGV[0]);
3206 COMMAND_HANDLER(handle_poll_command)
3208 int retval = ERROR_OK;
3209 struct target *target = get_current_target(CMD_CTX);
3211 if (CMD_ARGC == 0) {
3212 command_print(CMD, "background polling: %s",
3213 jtag_poll_get_enabled() ? "on" : "off");
3214 command_print(CMD, "TAP: %s (%s)",
3215 target->tap->dotted_name,
3216 target->tap->enabled ? "enabled" : "disabled");
3217 if (!target->tap->enabled)
3219 retval = target_poll(target);
3220 if (retval != ERROR_OK)
3222 retval = target_arch_state(target);
3223 if (retval != ERROR_OK)
3225 } else if (CMD_ARGC == 1) {
3227 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
3228 jtag_poll_set_enabled(enable);
3230 return ERROR_COMMAND_SYNTAX_ERROR;
3235 COMMAND_HANDLER(handle_wait_halt_command)
3238 return ERROR_COMMAND_SYNTAX_ERROR;
3240 unsigned ms = DEFAULT_HALT_TIMEOUT;
3241 if (1 == CMD_ARGC) {
3242 int retval = parse_uint(CMD_ARGV[0], &ms);
3243 if (retval != ERROR_OK)
3244 return ERROR_COMMAND_SYNTAX_ERROR;
3247 struct target *target = get_current_target(CMD_CTX);
3248 return target_wait_state(target, TARGET_HALTED, ms);
3251 /* wait for target state to change. The trick here is to have a low
3252 * latency for short waits and not to suck up all the CPU time
3255 * After 500ms, keep_alive() is invoked
3257 int target_wait_state(struct target *target, enum target_state state, int ms)
3260 int64_t then = 0, cur;
3264 retval = target_poll(target);
3265 if (retval != ERROR_OK)
3267 if (target->state == state)
3272 then = timeval_ms();
3273 LOG_DEBUG("waiting for target %s...",
3274 jim_nvp_value2name_simple(nvp_target_state, state)->name);
3280 if ((cur-then) > ms) {
3281 LOG_ERROR("timed out while waiting for target %s",
3282 jim_nvp_value2name_simple(nvp_target_state, state)->name);
3290 COMMAND_HANDLER(handle_halt_command)
3294 struct target *target = get_current_target(CMD_CTX);
3296 target->verbose_halt_msg = true;
3298 int retval = target_halt(target);
3299 if (retval != ERROR_OK)
3302 if (CMD_ARGC == 1) {
3303 unsigned wait_local;
3304 retval = parse_uint(CMD_ARGV[0], &wait_local);
3305 if (retval != ERROR_OK)
3306 return ERROR_COMMAND_SYNTAX_ERROR;
3311 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
3314 COMMAND_HANDLER(handle_soft_reset_halt_command)
3316 struct target *target = get_current_target(CMD_CTX);
3318 LOG_USER("requesting target halt and executing a soft reset");
3320 target_soft_reset_halt(target);
3325 COMMAND_HANDLER(handle_reset_command)
3328 return ERROR_COMMAND_SYNTAX_ERROR;
3330 enum target_reset_mode reset_mode = RESET_RUN;
3331 if (CMD_ARGC == 1) {
3332 const struct jim_nvp *n;
3333 n = jim_nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
3334 if ((!n->name) || (n->value == RESET_UNKNOWN))
3335 return ERROR_COMMAND_SYNTAX_ERROR;
3336 reset_mode = n->value;
3339 /* reset *all* targets */
3340 return target_process_reset(CMD, reset_mode);
3344 COMMAND_HANDLER(handle_resume_command)
3348 return ERROR_COMMAND_SYNTAX_ERROR;
3350 struct target *target = get_current_target(CMD_CTX);
3352 /* with no CMD_ARGV, resume from current pc, addr = 0,
3353 * with one arguments, addr = CMD_ARGV[0],
3354 * handle breakpoints, not debugging */
3355 target_addr_t addr = 0;
3356 if (CMD_ARGC == 1) {
3357 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3361 return target_resume(target, current, addr, 1, 0);
3364 COMMAND_HANDLER(handle_step_command)
3367 return ERROR_COMMAND_SYNTAX_ERROR;
3371 /* with no CMD_ARGV, step from current pc, addr = 0,
3372 * with one argument addr = CMD_ARGV[0],
3373 * handle breakpoints, debugging */
3374 target_addr_t addr = 0;
3376 if (CMD_ARGC == 1) {
3377 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3381 struct target *target = get_current_target(CMD_CTX);
3383 return target_step(target, current_pc, addr, 1);
3386 void target_handle_md_output(struct command_invocation *cmd,
3387 struct target *target, target_addr_t address, unsigned size,
3388 unsigned count, const uint8_t *buffer)
3390 const unsigned line_bytecnt = 32;
3391 unsigned line_modulo = line_bytecnt / size;
3393 char output[line_bytecnt * 4 + 1];
3394 unsigned output_len = 0;
3396 const char *value_fmt;
3399 value_fmt = "%16.16"PRIx64" ";
3402 value_fmt = "%8.8"PRIx64" ";
3405 value_fmt = "%4.4"PRIx64" ";
3408 value_fmt = "%2.2"PRIx64" ";
3411 /* "can't happen", caller checked */
3412 LOG_ERROR("invalid memory read size: %u", size);
3416 for (unsigned i = 0; i < count; i++) {
3417 if (i % line_modulo == 0) {
3418 output_len += snprintf(output + output_len,
3419 sizeof(output) - output_len,
3420 TARGET_ADDR_FMT ": ",
3421 (address + (i * size)));
3425 const uint8_t *value_ptr = buffer + i * size;
3428 value = target_buffer_get_u64(target, value_ptr);
3431 value = target_buffer_get_u32(target, value_ptr);
3434 value = target_buffer_get_u16(target, value_ptr);
3439 output_len += snprintf(output + output_len,
3440 sizeof(output) - output_len,
3443 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
3444 command_print(cmd, "%s", output);
3450 COMMAND_HANDLER(handle_md_command)
3453 return ERROR_COMMAND_SYNTAX_ERROR;
3456 switch (CMD_NAME[2]) {
3470 return ERROR_COMMAND_SYNTAX_ERROR;
3473 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3474 int (*fn)(struct target *target,
3475 target_addr_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
3479 fn = target_read_phys_memory;
3481 fn = target_read_memory;
3482 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
3483 return ERROR_COMMAND_SYNTAX_ERROR;
3485 target_addr_t address;
3486 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3490 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3492 uint8_t *buffer = calloc(count, size);
3494 LOG_ERROR("Failed to allocate md read buffer");
3498 struct target *target = get_current_target(CMD_CTX);
3499 int retval = fn(target, address, size, count, buffer);
3500 if (retval == ERROR_OK)
3501 target_handle_md_output(CMD, target, address, size, count, buffer);
3508 typedef int (*target_write_fn)(struct target *target,
3509 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3511 static int target_fill_mem(struct target *target,
3512 target_addr_t address,
3520 /* We have to write in reasonably large chunks to be able
3521 * to fill large memory areas with any sane speed */
3522 const unsigned chunk_size = 16384;
3523 uint8_t *target_buf = malloc(chunk_size * data_size);
3525 LOG_ERROR("Out of memory");
3529 for (unsigned i = 0; i < chunk_size; i++) {
3530 switch (data_size) {
3532 target_buffer_set_u64(target, target_buf + i * data_size, b);
3535 target_buffer_set_u32(target, target_buf + i * data_size, b);
3538 target_buffer_set_u16(target, target_buf + i * data_size, b);
3541 target_buffer_set_u8(target, target_buf + i * data_size, b);
3548 int retval = ERROR_OK;
3550 for (unsigned x = 0; x < c; x += chunk_size) {
3553 if (current > chunk_size)
3554 current = chunk_size;
3555 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3556 if (retval != ERROR_OK)
3558 /* avoid GDB timeouts */
3567 COMMAND_HANDLER(handle_mw_command)
3570 return ERROR_COMMAND_SYNTAX_ERROR;
3571 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3576 fn = target_write_phys_memory;
3578 fn = target_write_memory;
3579 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3580 return ERROR_COMMAND_SYNTAX_ERROR;
3582 target_addr_t address;
3583 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3586 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[1], value);
3590 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3592 struct target *target = get_current_target(CMD_CTX);
3594 switch (CMD_NAME[2]) {
3608 return ERROR_COMMAND_SYNTAX_ERROR;
3611 return target_fill_mem(target, address, fn, wordsize, value, count);
3614 static COMMAND_HELPER(parse_load_image_command, struct image *image,
3615 target_addr_t *min_address, target_addr_t *max_address)
3617 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3618 return ERROR_COMMAND_SYNTAX_ERROR;
3620 /* a base address isn't always necessary,
3621 * default to 0x0 (i.e. don't relocate) */
3622 if (CMD_ARGC >= 2) {
3624 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3625 image->base_address = addr;
3626 image->base_address_set = true;
3628 image->base_address_set = false;
3630 image->start_address_set = false;
3633 COMMAND_PARSE_ADDRESS(CMD_ARGV[3], *min_address);
3634 if (CMD_ARGC == 5) {
3635 COMMAND_PARSE_ADDRESS(CMD_ARGV[4], *max_address);
3636 /* use size (given) to find max (required) */
3637 *max_address += *min_address;
3640 if (*min_address > *max_address)
3641 return ERROR_COMMAND_SYNTAX_ERROR;
3646 COMMAND_HANDLER(handle_load_image_command)
3650 uint32_t image_size;
3651 target_addr_t min_address = 0;
3652 target_addr_t max_address = -1;
3655 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
3656 &image, &min_address, &max_address);
3657 if (retval != ERROR_OK)
3660 struct target *target = get_current_target(CMD_CTX);
3662 struct duration bench;
3663 duration_start(&bench);
3665 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3670 for (unsigned int i = 0; i < image.num_sections; i++) {
3671 buffer = malloc(image.sections[i].size);
3674 "error allocating buffer for section (%d bytes)",
3675 (int)(image.sections[i].size));
3676 retval = ERROR_FAIL;
3680 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3681 if (retval != ERROR_OK) {
3686 uint32_t offset = 0;
3687 uint32_t length = buf_cnt;
3689 /* DANGER!!! beware of unsigned comparison here!!! */
3691 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3692 (image.sections[i].base_address < max_address)) {
3694 if (image.sections[i].base_address < min_address) {
3695 /* clip addresses below */
3696 offset += min_address-image.sections[i].base_address;
3700 if (image.sections[i].base_address + buf_cnt > max_address)
3701 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3703 retval = target_write_buffer(target,
3704 image.sections[i].base_address + offset, length, buffer + offset);
3705 if (retval != ERROR_OK) {
3709 image_size += length;
3710 command_print(CMD, "%u bytes written at address " TARGET_ADDR_FMT "",
3711 (unsigned int)length,
3712 image.sections[i].base_address + offset);
3718 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3719 command_print(CMD, "downloaded %" PRIu32 " bytes "
3720 "in %fs (%0.3f KiB/s)", image_size,
3721 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3724 image_close(&image);
3730 COMMAND_HANDLER(handle_dump_image_command)
3732 struct fileio *fileio;
3734 int retval, retvaltemp;
3735 target_addr_t address, size;
3736 struct duration bench;
3737 struct target *target = get_current_target(CMD_CTX);
3740 return ERROR_COMMAND_SYNTAX_ERROR;
3742 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], address);
3743 COMMAND_PARSE_ADDRESS(CMD_ARGV[2], size);
3745 uint32_t buf_size = (size > 4096) ? 4096 : size;
3746 buffer = malloc(buf_size);
3750 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3751 if (retval != ERROR_OK) {
3756 duration_start(&bench);
3759 size_t size_written;
3760 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3761 retval = target_read_buffer(target, address, this_run_size, buffer);
3762 if (retval != ERROR_OK)
3765 retval = fileio_write(fileio, this_run_size, buffer, &size_written);
3766 if (retval != ERROR_OK)
3769 size -= this_run_size;
3770 address += this_run_size;
3775 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3777 retval = fileio_size(fileio, &filesize);
3778 if (retval != ERROR_OK)
3781 "dumped %zu bytes in %fs (%0.3f KiB/s)", filesize,
3782 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3785 retvaltemp = fileio_close(fileio);
3786 if (retvaltemp != ERROR_OK)
3795 IMAGE_CHECKSUM_ONLY = 2
3798 static COMMAND_HELPER(handle_verify_image_command_internal, enum verify_mode verify)
3802 uint32_t image_size;
3804 uint32_t checksum = 0;
3805 uint32_t mem_checksum = 0;
3809 struct target *target = get_current_target(CMD_CTX);
3812 return ERROR_COMMAND_SYNTAX_ERROR;
3815 LOG_ERROR("no target selected");
3819 struct duration bench;
3820 duration_start(&bench);
3822 if (CMD_ARGC >= 2) {
3824 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3825 image.base_address = addr;
3826 image.base_address_set = true;
3828 image.base_address_set = false;
3829 image.base_address = 0x0;
3832 image.start_address_set = false;
3834 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3835 if (retval != ERROR_OK)
3841 for (unsigned int i = 0; i < image.num_sections; i++) {
3842 buffer = malloc(image.sections[i].size);
3845 "error allocating buffer for section (%" PRIu32 " bytes)",
3846 image.sections[i].size);
3849 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3850 if (retval != ERROR_OK) {
3855 if (verify >= IMAGE_VERIFY) {
3856 /* calculate checksum of image */
3857 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3858 if (retval != ERROR_OK) {
3863 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3864 if (retval != ERROR_OK) {
3868 if ((checksum != mem_checksum) && (verify == IMAGE_CHECKSUM_ONLY)) {
3869 LOG_ERROR("checksum mismatch");
3871 retval = ERROR_FAIL;
3874 if (checksum != mem_checksum) {
3875 /* failed crc checksum, fall back to a binary compare */
3879 LOG_ERROR("checksum mismatch - attempting binary compare");
3881 data = malloc(buf_cnt);
3883 retval = target_read_buffer(target, image.sections[i].base_address, buf_cnt, data);
3884 if (retval == ERROR_OK) {
3886 for (t = 0; t < buf_cnt; t++) {
3887 if (data[t] != buffer[t]) {
3889 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3891 (unsigned)(t + image.sections[i].base_address),
3894 if (diffs++ >= 127) {
3895 command_print(CMD, "More than 128 errors, the rest are not printed.");
3907 command_print(CMD, "address " TARGET_ADDR_FMT " length 0x%08zx",
3908 image.sections[i].base_address,
3913 image_size += buf_cnt;
3916 command_print(CMD, "No more differences found.");
3919 retval = ERROR_FAIL;
3920 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3921 command_print(CMD, "verified %" PRIu32 " bytes "
3922 "in %fs (%0.3f KiB/s)", image_size,
3923 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3926 image_close(&image);
3931 COMMAND_HANDLER(handle_verify_image_checksum_command)
3933 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_CHECKSUM_ONLY);
3936 COMMAND_HANDLER(handle_verify_image_command)
3938 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_VERIFY);
3941 COMMAND_HANDLER(handle_test_image_command)
3943 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_TEST);
3946 static int handle_bp_command_list(struct command_invocation *cmd)
3948 struct target *target = get_current_target(cmd->ctx);
3949 struct breakpoint *breakpoint = target->breakpoints;
3950 while (breakpoint) {
3951 if (breakpoint->type == BKPT_SOFT) {
3952 char *buf = buf_to_hex_str(breakpoint->orig_instr,
3953 breakpoint->length);
3954 command_print(cmd, "IVA breakpoint: " TARGET_ADDR_FMT ", 0x%x, %i, 0x%s",
3955 breakpoint->address,
3957 breakpoint->set, buf);
3960 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3961 command_print(cmd, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3963 breakpoint->length, breakpoint->set);
3964 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3965 command_print(cmd, "Hybrid breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3966 breakpoint->address,
3967 breakpoint->length, breakpoint->set);
3968 command_print(cmd, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3971 command_print(cmd, "Breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3972 breakpoint->address,
3973 breakpoint->length, breakpoint->set);
3976 breakpoint = breakpoint->next;
3981 static int handle_bp_command_set(struct command_invocation *cmd,
3982 target_addr_t addr, uint32_t asid, uint32_t length, int hw)
3984 struct target *target = get_current_target(cmd->ctx);
3988 retval = breakpoint_add(target, addr, length, hw);
3989 /* error is always logged in breakpoint_add(), do not print it again */
3990 if (retval == ERROR_OK)
3991 command_print(cmd, "breakpoint set at " TARGET_ADDR_FMT "", addr);
3993 } else if (addr == 0) {
3994 if (!target->type->add_context_breakpoint) {
3995 LOG_ERROR("Context breakpoint not available");
3996 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
3998 retval = context_breakpoint_add(target, asid, length, hw);
3999 /* error is always logged in context_breakpoint_add(), do not print it again */
4000 if (retval == ERROR_OK)
4001 command_print(cmd, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
4004 if (!target->type->add_hybrid_breakpoint) {
4005 LOG_ERROR("Hybrid breakpoint not available");
4006 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
4008 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
4009 /* error is always logged in hybrid_breakpoint_add(), do not print it again */
4010 if (retval == ERROR_OK)
4011 command_print(cmd, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
4016 COMMAND_HANDLER(handle_bp_command)
4025 return handle_bp_command_list(CMD);
4029 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4030 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4031 return handle_bp_command_set(CMD, addr, asid, length, hw);
4034 if (strcmp(CMD_ARGV[2], "hw") == 0) {
4036 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4037 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4039 return handle_bp_command_set(CMD, addr, asid, length, hw);
4040 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
4042 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
4043 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4045 return handle_bp_command_set(CMD, addr, asid, length, hw);
4050 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4051 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
4052 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
4053 return handle_bp_command_set(CMD, addr, asid, length, hw);
4056 return ERROR_COMMAND_SYNTAX_ERROR;
4060 COMMAND_HANDLER(handle_rbp_command)
4063 return ERROR_COMMAND_SYNTAX_ERROR;
4065 struct target *target = get_current_target(CMD_CTX);
4067 if (!strcmp(CMD_ARGV[0], "all")) {
4068 breakpoint_remove_all(target);
4071 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4073 breakpoint_remove(target, addr);
4079 COMMAND_HANDLER(handle_wp_command)
4081 struct target *target = get_current_target(CMD_CTX);
4083 if (CMD_ARGC == 0) {
4084 struct watchpoint *watchpoint = target->watchpoints;
4086 while (watchpoint) {
4087 command_print(CMD, "address: " TARGET_ADDR_FMT
4088 ", len: 0x%8.8" PRIx32
4089 ", r/w/a: %i, value: 0x%8.8" PRIx32
4090 ", mask: 0x%8.8" PRIx32,
4091 watchpoint->address,
4093 (int)watchpoint->rw,
4096 watchpoint = watchpoint->next;
4101 enum watchpoint_rw type = WPT_ACCESS;
4102 target_addr_t addr = 0;
4103 uint32_t length = 0;
4104 uint32_t data_value = 0x0;
4105 uint32_t data_mask = 0xffffffff;
4109 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
4112 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
4115 switch (CMD_ARGV[2][0]) {
4126 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
4127 return ERROR_COMMAND_SYNTAX_ERROR;
4131 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4132 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4136 return ERROR_COMMAND_SYNTAX_ERROR;
4139 int retval = watchpoint_add(target, addr, length, type,
4140 data_value, data_mask);
4141 if (retval != ERROR_OK)
4142 LOG_ERROR("Failure setting watchpoints");
4147 COMMAND_HANDLER(handle_rwp_command)
4150 return ERROR_COMMAND_SYNTAX_ERROR;
4153 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4155 struct target *target = get_current_target(CMD_CTX);
4156 watchpoint_remove(target, addr);
4162 * Translate a virtual address to a physical address.
4164 * The low-level target implementation must have logged a detailed error
4165 * which is forwarded to telnet/GDB session.
4167 COMMAND_HANDLER(handle_virt2phys_command)
4170 return ERROR_COMMAND_SYNTAX_ERROR;
4173 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], va);
4176 struct target *target = get_current_target(CMD_CTX);
4177 int retval = target->type->virt2phys(target, va, &pa);
4178 if (retval == ERROR_OK)
4179 command_print(CMD, "Physical address " TARGET_ADDR_FMT "", pa);
4184 static void write_data(FILE *f, const void *data, size_t len)
4186 size_t written = fwrite(data, 1, len, f);
4188 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
4191 static void write_long(FILE *f, int l, struct target *target)
4195 target_buffer_set_u32(target, val, l);
4196 write_data(f, val, 4);
4199 static void write_string(FILE *f, char *s)
4201 write_data(f, s, strlen(s));
4204 typedef unsigned char UNIT[2]; /* unit of profiling */
4206 /* Dump a gmon.out histogram file. */
4207 static void write_gmon(uint32_t *samples, uint32_t sample_num, const char *filename, bool with_range,
4208 uint32_t start_address, uint32_t end_address, struct target *target, uint32_t duration_ms)
4211 FILE *f = fopen(filename, "w");
4214 write_string(f, "gmon");
4215 write_long(f, 0x00000001, target); /* Version */
4216 write_long(f, 0, target); /* padding */
4217 write_long(f, 0, target); /* padding */
4218 write_long(f, 0, target); /* padding */
4220 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
4221 write_data(f, &zero, 1);
4223 /* figure out bucket size */
4227 min = start_address;
4232 for (i = 0; i < sample_num; i++) {
4233 if (min > samples[i])
4235 if (max < samples[i])
4239 /* max should be (largest sample + 1)
4240 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
4244 int address_space = max - min;
4245 assert(address_space >= 2);
4247 /* FIXME: What is the reasonable number of buckets?
4248 * The profiling result will be more accurate if there are enough buckets. */
4249 static const uint32_t max_buckets = 128 * 1024; /* maximum buckets. */
4250 uint32_t num_buckets = address_space / sizeof(UNIT);
4251 if (num_buckets > max_buckets)
4252 num_buckets = max_buckets;
4253 int *buckets = malloc(sizeof(int) * num_buckets);
4258 memset(buckets, 0, sizeof(int) * num_buckets);
4259 for (i = 0; i < sample_num; i++) {
4260 uint32_t address = samples[i];
4262 if ((address < min) || (max <= address))
4265 long long a = address - min;
4266 long long b = num_buckets;
4267 long long c = address_space;
4268 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
4272 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
4273 write_long(f, min, target); /* low_pc */
4274 write_long(f, max, target); /* high_pc */
4275 write_long(f, num_buckets, target); /* # of buckets */
4276 float sample_rate = sample_num / (duration_ms / 1000.0);
4277 write_long(f, sample_rate, target);
4278 write_string(f, "seconds");
4279 for (i = 0; i < (15-strlen("seconds")); i++)
4280 write_data(f, &zero, 1);
4281 write_string(f, "s");
4283 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
4285 char *data = malloc(2 * num_buckets);
4287 for (i = 0; i < num_buckets; i++) {
4292 data[i * 2] = val&0xff;
4293 data[i * 2 + 1] = (val >> 8) & 0xff;
4296 write_data(f, data, num_buckets * 2);
4304 /* profiling samples the CPU PC as quickly as OpenOCD is able,
4305 * which will be used as a random sampling of PC */
4306 COMMAND_HANDLER(handle_profile_command)
4308 struct target *target = get_current_target(CMD_CTX);
4310 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
4311 return ERROR_COMMAND_SYNTAX_ERROR;
4313 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
4315 uint32_t num_of_samples;
4316 int retval = ERROR_OK;
4317 bool halted_before_profiling = target->state == TARGET_HALTED;
4319 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
4321 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
4323 LOG_ERROR("No memory to store samples.");
4327 uint64_t timestart_ms = timeval_ms();
4329 * Some cores let us sample the PC without the
4330 * annoying halt/resume step; for example, ARMv7 PCSR.
4331 * Provide a way to use that more efficient mechanism.
4333 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
4334 &num_of_samples, offset);
4335 if (retval != ERROR_OK) {
4339 uint32_t duration_ms = timeval_ms() - timestart_ms;
4341 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
4343 retval = target_poll(target);
4344 if (retval != ERROR_OK) {
4349 if (target->state == TARGET_RUNNING && halted_before_profiling) {
4350 /* The target was halted before we started and is running now. Halt it,
4351 * for consistency. */
4352 retval = target_halt(target);
4353 if (retval != ERROR_OK) {
4357 } else if (target->state == TARGET_HALTED && !halted_before_profiling) {
4358 /* The target was running before we started and is halted now. Resume
4359 * it, for consistency. */
4360 retval = target_resume(target, 1, 0, 0, 0);
4361 if (retval != ERROR_OK) {
4367 retval = target_poll(target);
4368 if (retval != ERROR_OK) {
4373 uint32_t start_address = 0;
4374 uint32_t end_address = 0;
4375 bool with_range = false;
4376 if (CMD_ARGC == 4) {
4378 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
4379 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
4382 write_gmon(samples, num_of_samples, CMD_ARGV[1],
4383 with_range, start_address, end_address, target, duration_ms);
4384 command_print(CMD, "Wrote %s", CMD_ARGV[1]);
4390 static int new_u64_array_element(Jim_Interp *interp, const char *varname, int idx, uint64_t val)
4393 Jim_Obj *obj_name, *obj_val;
4396 namebuf = alloc_printf("%s(%d)", varname, idx);
4400 obj_name = Jim_NewStringObj(interp, namebuf, -1);
4401 jim_wide wide_val = val;
4402 obj_val = Jim_NewWideObj(interp, wide_val);
4403 if (!obj_name || !obj_val) {
4408 Jim_IncrRefCount(obj_name);
4409 Jim_IncrRefCount(obj_val);
4410 result = Jim_SetVariable(interp, obj_name, obj_val);
4411 Jim_DecrRefCount(interp, obj_name);
4412 Jim_DecrRefCount(interp, obj_val);
4414 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
4418 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4420 struct command_context *context;
4421 struct target *target;
4423 context = current_command_context(interp);
4426 target = get_current_target(context);
4428 LOG_ERROR("mem2array: no current target");
4432 return target_mem2array(interp, target, argc - 1, argv + 1);
4435 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
4439 /* argv[0] = name of array to receive the data
4440 * argv[1] = desired element width in bits
4441 * argv[2] = memory address
4442 * argv[3] = count of times to read
4443 * argv[4] = optional "phys"
4445 if (argc < 4 || argc > 5) {
4446 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4450 /* Arg 0: Name of the array variable */
4451 const char *varname = Jim_GetString(argv[0], NULL);
4453 /* Arg 1: Bit width of one element */
4455 e = Jim_GetLong(interp, argv[1], &l);
4458 const unsigned int width_bits = l;
4460 if (width_bits != 8 &&
4464 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4465 Jim_AppendStrings(interp, Jim_GetResult(interp),
4466 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4469 const unsigned int width = width_bits / 8;
4471 /* Arg 2: Memory address */
4473 e = Jim_GetWide(interp, argv[2], &wide_addr);
4476 target_addr_t addr = (target_addr_t)wide_addr;
4478 /* Arg 3: Number of elements to read */
4479 e = Jim_GetLong(interp, argv[3], &l);
4485 bool is_phys = false;
4488 const char *phys = Jim_GetString(argv[4], &str_len);
4489 if (!strncmp(phys, "phys", str_len))
4495 /* Argument checks */
4497 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4498 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
4501 if ((addr + (len * width)) < addr) {
4502 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4503 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
4507 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4508 Jim_AppendStrings(interp, Jim_GetResult(interp),
4509 "mem2array: too large read request, exceeds 64K items", NULL);
4514 ((width == 2) && ((addr & 1) == 0)) ||
4515 ((width == 4) && ((addr & 3) == 0)) ||
4516 ((width == 8) && ((addr & 7) == 0))) {
4517 /* alignment correct */
4520 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4521 sprintf(buf, "mem2array address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4524 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4533 const size_t buffersize = 4096;
4534 uint8_t *buffer = malloc(buffersize);
4541 /* Slurp... in buffer size chunks */
4542 const unsigned int max_chunk_len = buffersize / width;
4543 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4547 retval = target_read_phys_memory(target, addr, width, chunk_len, buffer);
4549 retval = target_read_memory(target, addr, width, chunk_len, buffer);
4550 if (retval != ERROR_OK) {
4552 LOG_ERROR("mem2array: Read @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4556 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4557 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
4561 for (size_t i = 0; i < chunk_len ; i++, idx++) {
4565 v = target_buffer_get_u64(target, &buffer[i*width]);
4568 v = target_buffer_get_u32(target, &buffer[i*width]);
4571 v = target_buffer_get_u16(target, &buffer[i*width]);
4574 v = buffer[i] & 0x0ff;
4577 new_u64_array_element(interp, varname, idx, v);
4580 addr += chunk_len * width;
4586 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4591 static int get_u64_array_element(Jim_Interp *interp, const char *varname, size_t idx, uint64_t *val)
4593 char *namebuf = alloc_printf("%s(%zu)", varname, idx);
4597 Jim_Obj *obj_name = Jim_NewStringObj(interp, namebuf, -1);
4603 Jim_IncrRefCount(obj_name);
4604 Jim_Obj *obj_val = Jim_GetVariable(interp, obj_name, JIM_ERRMSG);
4605 Jim_DecrRefCount(interp, obj_name);
4611 int result = Jim_GetWide(interp, obj_val, &wide_val);
4616 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4618 struct command_context *context;
4619 struct target *target;
4621 context = current_command_context(interp);
4624 target = get_current_target(context);
4626 LOG_ERROR("array2mem: no current target");
4630 return target_array2mem(interp, target, argc-1, argv + 1);
4633 static int target_array2mem(Jim_Interp *interp, struct target *target,
4634 int argc, Jim_Obj *const *argv)
4638 /* argv[0] = name of array from which to read the data
4639 * argv[1] = desired element width in bits
4640 * argv[2] = memory address
4641 * argv[3] = number of elements to write
4642 * argv[4] = optional "phys"
4644 if (argc < 4 || argc > 5) {
4645 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4649 /* Arg 0: Name of the array variable */
4650 const char *varname = Jim_GetString(argv[0], NULL);
4652 /* Arg 1: Bit width of one element */
4654 e = Jim_GetLong(interp, argv[1], &l);
4657 const unsigned int width_bits = l;
4659 if (width_bits != 8 &&
4663 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4664 Jim_AppendStrings(interp, Jim_GetResult(interp),
4665 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4668 const unsigned int width = width_bits / 8;
4670 /* Arg 2: Memory address */
4672 e = Jim_GetWide(interp, argv[2], &wide_addr);
4675 target_addr_t addr = (target_addr_t)wide_addr;
4677 /* Arg 3: Number of elements to write */
4678 e = Jim_GetLong(interp, argv[3], &l);
4684 bool is_phys = false;
4687 const char *phys = Jim_GetString(argv[4], &str_len);
4688 if (!strncmp(phys, "phys", str_len))
4694 /* Argument checks */
4696 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4697 Jim_AppendStrings(interp, Jim_GetResult(interp),
4698 "array2mem: zero width read?", NULL);
4702 if ((addr + (len * width)) < addr) {
4703 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4704 Jim_AppendStrings(interp, Jim_GetResult(interp),
4705 "array2mem: addr + len - wraps to zero?", NULL);
4710 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4711 Jim_AppendStrings(interp, Jim_GetResult(interp),
4712 "array2mem: too large memory write request, exceeds 64K items", NULL);
4717 ((width == 2) && ((addr & 1) == 0)) ||
4718 ((width == 4) && ((addr & 3) == 0)) ||
4719 ((width == 8) && ((addr & 7) == 0))) {
4720 /* alignment correct */
4723 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4724 sprintf(buf, "array2mem address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4727 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4736 const size_t buffersize = 4096;
4737 uint8_t *buffer = malloc(buffersize);
4745 /* Slurp... in buffer size chunks */
4746 const unsigned int max_chunk_len = buffersize / width;
4748 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4750 /* Fill the buffer */
4751 for (size_t i = 0; i < chunk_len; i++, idx++) {
4753 if (get_u64_array_element(interp, varname, idx, &v) != JIM_OK) {
4759 target_buffer_set_u64(target, &buffer[i * width], v);
4762 target_buffer_set_u32(target, &buffer[i * width], v);
4765 target_buffer_set_u16(target, &buffer[i * width], v);
4768 buffer[i] = v & 0x0ff;
4774 /* Write the buffer to memory */
4777 retval = target_write_phys_memory(target, addr, width, chunk_len, buffer);
4779 retval = target_write_memory(target, addr, width, chunk_len, buffer);
4780 if (retval != ERROR_OK) {
4782 LOG_ERROR("array2mem: Write @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4786 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4787 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4791 addr += chunk_len * width;
4796 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4801 /* FIX? should we propagate errors here rather than printing them
4804 void target_handle_event(struct target *target, enum target_event e)
4806 struct target_event_action *teap;
4809 for (teap = target->event_action; teap; teap = teap->next) {
4810 if (teap->event == e) {
4811 LOG_DEBUG("target(%d): %s (%s) event: %d (%s) action: %s",
4812 target->target_number,
4813 target_name(target),
4814 target_type_name(target),
4816 jim_nvp_value2name_simple(nvp_target_event, e)->name,
4817 Jim_GetString(teap->body, NULL));
4819 /* Override current target by the target an event
4820 * is issued from (lot of scripts need it).
4821 * Return back to previous override as soon
4822 * as the handler processing is done */
4823 struct command_context *cmd_ctx = current_command_context(teap->interp);
4824 struct target *saved_target_override = cmd_ctx->current_target_override;
4825 cmd_ctx->current_target_override = target;
4827 retval = Jim_EvalObj(teap->interp, teap->body);
4829 cmd_ctx->current_target_override = saved_target_override;
4831 if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
4834 if (retval == JIM_RETURN)
4835 retval = teap->interp->returnCode;
4837 if (retval != JIM_OK) {
4838 Jim_MakeErrorMessage(teap->interp);
4839 LOG_USER("Error executing event %s on target %s:\n%s",
4840 jim_nvp_value2name_simple(nvp_target_event, e)->name,
4841 target_name(target),
4842 Jim_GetString(Jim_GetResult(teap->interp), NULL));
4843 /* clean both error code and stacktrace before return */
4844 Jim_Eval(teap->interp, "error \"\" \"\"");
4851 * Returns true only if the target has a handler for the specified event.
4853 bool target_has_event_action(struct target *target, enum target_event event)
4855 struct target_event_action *teap;
4857 for (teap = target->event_action; teap; teap = teap->next) {
4858 if (teap->event == event)
4864 enum target_cfg_param {
4867 TCFG_WORK_AREA_VIRT,
4868 TCFG_WORK_AREA_PHYS,
4869 TCFG_WORK_AREA_SIZE,
4870 TCFG_WORK_AREA_BACKUP,
4873 TCFG_CHAIN_POSITION,
4878 TCFG_GDB_MAX_CONNECTIONS,
4881 static struct jim_nvp nvp_config_opts[] = {
4882 { .name = "-type", .value = TCFG_TYPE },
4883 { .name = "-event", .value = TCFG_EVENT },
4884 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4885 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4886 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4887 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4888 { .name = "-endian", .value = TCFG_ENDIAN },
4889 { .name = "-coreid", .value = TCFG_COREID },
4890 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4891 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4892 { .name = "-rtos", .value = TCFG_RTOS },
4893 { .name = "-defer-examine", .value = TCFG_DEFER_EXAMINE },
4894 { .name = "-gdb-port", .value = TCFG_GDB_PORT },
4895 { .name = "-gdb-max-connections", .value = TCFG_GDB_MAX_CONNECTIONS },
4896 { .name = NULL, .value = -1 }
4899 static int target_configure(struct jim_getopt_info *goi, struct target *target)
4906 /* parse config or cget options ... */
4907 while (goi->argc > 0) {
4908 Jim_SetEmptyResult(goi->interp);
4909 /* jim_getopt_debug(goi); */
4911 if (target->type->target_jim_configure) {
4912 /* target defines a configure function */
4913 /* target gets first dibs on parameters */
4914 e = (*(target->type->target_jim_configure))(target, goi);
4923 /* otherwise we 'continue' below */
4925 e = jim_getopt_nvp(goi, nvp_config_opts, &n);
4927 jim_getopt_nvp_unknown(goi, nvp_config_opts, 0);
4933 if (goi->isconfigure) {
4934 Jim_SetResultFormatted(goi->interp,
4935 "not settable: %s", n->name);
4939 if (goi->argc != 0) {
4940 Jim_WrongNumArgs(goi->interp,
4941 goi->argc, goi->argv,
4946 Jim_SetResultString(goi->interp,
4947 target_type_name(target), -1);
4951 if (goi->argc == 0) {
4952 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4956 e = jim_getopt_nvp(goi, nvp_target_event, &n);
4958 jim_getopt_nvp_unknown(goi, nvp_target_event, 1);
4962 if (goi->isconfigure) {
4963 if (goi->argc != 1) {
4964 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4968 if (goi->argc != 0) {
4969 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4975 struct target_event_action *teap;
4977 teap = target->event_action;
4978 /* replace existing? */
4980 if (teap->event == (enum target_event)n->value)
4985 if (goi->isconfigure) {
4986 /* START_DEPRECATED_TPIU */
4987 if (n->value == TARGET_EVENT_TRACE_CONFIG)
4988 LOG_INFO("DEPRECATED target event %s; use TPIU events {pre,post}-{enable,disable}", n->name);
4989 /* END_DEPRECATED_TPIU */
4991 bool replace = true;
4994 teap = calloc(1, sizeof(*teap));
4997 teap->event = n->value;
4998 teap->interp = goi->interp;
4999 jim_getopt_obj(goi, &o);
5001 Jim_DecrRefCount(teap->interp, teap->body);
5002 teap->body = Jim_DuplicateObj(goi->interp, o);
5005 * Tcl/TK - "tk events" have a nice feature.
5006 * See the "BIND" command.
5007 * We should support that here.
5008 * You can specify %X and %Y in the event code.
5009 * The idea is: %T - target name.
5010 * The idea is: %N - target number
5011 * The idea is: %E - event name.
5013 Jim_IncrRefCount(teap->body);
5016 /* add to head of event list */
5017 teap->next = target->event_action;
5018 target->event_action = teap;
5020 Jim_SetEmptyResult(goi->interp);
5024 Jim_SetEmptyResult(goi->interp);
5026 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
5032 case TCFG_WORK_AREA_VIRT:
5033 if (goi->isconfigure) {
5034 target_free_all_working_areas(target);
5035 e = jim_getopt_wide(goi, &w);
5038 target->working_area_virt = w;
5039 target->working_area_virt_spec = true;
5044 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
5048 case TCFG_WORK_AREA_PHYS:
5049 if (goi->isconfigure) {
5050 target_free_all_working_areas(target);
5051 e = jim_getopt_wide(goi, &w);
5054 target->working_area_phys = w;
5055 target->working_area_phys_spec = true;
5060 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
5064 case TCFG_WORK_AREA_SIZE:
5065 if (goi->isconfigure) {
5066 target_free_all_working_areas(target);
5067 e = jim_getopt_wide(goi, &w);
5070 target->working_area_size = w;
5075 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
5079 case TCFG_WORK_AREA_BACKUP:
5080 if (goi->isconfigure) {
5081 target_free_all_working_areas(target);
5082 e = jim_getopt_wide(goi, &w);
5085 /* make this exactly 1 or 0 */
5086 target->backup_working_area = (!!w);
5091 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
5092 /* loop for more e*/
5097 if (goi->isconfigure) {
5098 e = jim_getopt_nvp(goi, nvp_target_endian, &n);
5100 jim_getopt_nvp_unknown(goi, nvp_target_endian, 1);
5103 target->endianness = n->value;
5108 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5110 target->endianness = TARGET_LITTLE_ENDIAN;
5111 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5113 Jim_SetResultString(goi->interp, n->name, -1);
5118 if (goi->isconfigure) {
5119 e = jim_getopt_wide(goi, &w);
5122 target->coreid = (int32_t)w;
5127 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->coreid));
5131 case TCFG_CHAIN_POSITION:
5132 if (goi->isconfigure) {
5134 struct jtag_tap *tap;
5136 if (target->has_dap) {
5137 Jim_SetResultString(goi->interp,
5138 "target requires -dap parameter instead of -chain-position!", -1);
5142 target_free_all_working_areas(target);
5143 e = jim_getopt_obj(goi, &o_t);
5146 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
5150 target->tap_configured = true;
5155 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
5156 /* loop for more e*/
5159 if (goi->isconfigure) {
5160 e = jim_getopt_wide(goi, &w);
5163 target->dbgbase = (uint32_t)w;
5164 target->dbgbase_set = true;
5169 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
5175 int result = rtos_create(goi, target);
5176 if (result != JIM_OK)
5182 case TCFG_DEFER_EXAMINE:
5184 target->defer_examine = true;
5189 if (goi->isconfigure) {
5190 struct command_context *cmd_ctx = current_command_context(goi->interp);
5191 if (cmd_ctx->mode != COMMAND_CONFIG) {
5192 Jim_SetResultString(goi->interp, "-gdb-port must be configured before 'init'", -1);
5197 e = jim_getopt_string(goi, &s, NULL);
5200 free(target->gdb_port_override);
5201 target->gdb_port_override = strdup(s);
5206 Jim_SetResultString(goi->interp, target->gdb_port_override ? target->gdb_port_override : "undefined", -1);
5210 case TCFG_GDB_MAX_CONNECTIONS:
5211 if (goi->isconfigure) {
5212 struct command_context *cmd_ctx = current_command_context(goi->interp);
5213 if (cmd_ctx->mode != COMMAND_CONFIG) {
5214 Jim_SetResultString(goi->interp, "-gdb-max-connections must be configured before 'init'", -1);
5218 e = jim_getopt_wide(goi, &w);
5221 target->gdb_max_connections = (w < 0) ? CONNECTION_LIMIT_UNLIMITED : (int)w;
5226 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->gdb_max_connections));
5229 } /* while (goi->argc) */
5232 /* done - we return */
5236 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5238 struct command *c = jim_to_command(interp);
5239 struct jim_getopt_info goi;
5241 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5242 goi.isconfigure = !strcmp(c->name, "configure");
5244 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5245 "missing: -option ...");
5248 struct command_context *cmd_ctx = current_command_context(interp);
5250 struct target *target = get_current_target(cmd_ctx);
5251 return target_configure(&goi, target);
5254 static int jim_target_mem2array(Jim_Interp *interp,
5255 int argc, Jim_Obj *const *argv)
5257 struct command_context *cmd_ctx = current_command_context(interp);
5259 struct target *target = get_current_target(cmd_ctx);
5260 return target_mem2array(interp, target, argc - 1, argv + 1);
5263 static int jim_target_array2mem(Jim_Interp *interp,
5264 int argc, Jim_Obj *const *argv)
5266 struct command_context *cmd_ctx = current_command_context(interp);
5268 struct target *target = get_current_target(cmd_ctx);
5269 return target_array2mem(interp, target, argc - 1, argv + 1);
5272 static int jim_target_tap_disabled(Jim_Interp *interp)
5274 Jim_SetResultFormatted(interp, "[TAP is disabled]");
5278 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5280 bool allow_defer = false;
5282 struct jim_getopt_info goi;
5283 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5285 const char *cmd_name = Jim_GetString(argv[0], NULL);
5286 Jim_SetResultFormatted(goi.interp,
5287 "usage: %s ['allow-defer']", cmd_name);
5291 strcmp(Jim_GetString(argv[1], NULL), "allow-defer") == 0) {
5294 int e = jim_getopt_obj(&goi, &obj);
5300 struct command_context *cmd_ctx = current_command_context(interp);
5302 struct target *target = get_current_target(cmd_ctx);
5303 if (!target->tap->enabled)
5304 return jim_target_tap_disabled(interp);
5306 if (allow_defer && target->defer_examine) {
5307 LOG_INFO("Deferring arp_examine of %s", target_name(target));
5308 LOG_INFO("Use arp_examine command to examine it manually!");
5312 int e = target->type->examine(target);
5313 if (e != ERROR_OK) {
5314 target_reset_examined(target);
5318 target_set_examined(target);
5323 static int jim_target_was_examined(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5325 struct command_context *cmd_ctx = current_command_context(interp);
5327 struct target *target = get_current_target(cmd_ctx);
5329 Jim_SetResultBool(interp, target_was_examined(target));
5333 static int jim_target_examine_deferred(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5335 struct command_context *cmd_ctx = current_command_context(interp);
5337 struct target *target = get_current_target(cmd_ctx);
5339 Jim_SetResultBool(interp, target->defer_examine);
5343 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5346 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5349 struct command_context *cmd_ctx = current_command_context(interp);
5351 struct target *target = get_current_target(cmd_ctx);
5353 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
5359 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5362 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5365 struct command_context *cmd_ctx = current_command_context(interp);
5367 struct target *target = get_current_target(cmd_ctx);
5368 if (!target->tap->enabled)
5369 return jim_target_tap_disabled(interp);
5372 if (!(target_was_examined(target)))
5373 e = ERROR_TARGET_NOT_EXAMINED;
5375 e = target->type->poll(target);
5381 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5383 struct jim_getopt_info goi;
5384 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5386 if (goi.argc != 2) {
5387 Jim_WrongNumArgs(interp, 0, argv,
5388 "([tT]|[fF]|assert|deassert) BOOL");
5393 int e = jim_getopt_nvp(&goi, nvp_assert, &n);
5395 jim_getopt_nvp_unknown(&goi, nvp_assert, 1);
5398 /* the halt or not param */
5400 e = jim_getopt_wide(&goi, &a);
5404 struct command_context *cmd_ctx = current_command_context(interp);
5406 struct target *target = get_current_target(cmd_ctx);
5407 if (!target->tap->enabled)
5408 return jim_target_tap_disabled(interp);
5410 if (!target->type->assert_reset || !target->type->deassert_reset) {
5411 Jim_SetResultFormatted(interp,
5412 "No target-specific reset for %s",
5413 target_name(target));
5417 if (target->defer_examine)
5418 target_reset_examined(target);
5420 /* determine if we should halt or not. */
5421 target->reset_halt = (a != 0);
5422 /* When this happens - all workareas are invalid. */
5423 target_free_all_working_areas_restore(target, 0);
5426 if (n->value == NVP_ASSERT)
5427 e = target->type->assert_reset(target);
5429 e = target->type->deassert_reset(target);
5430 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5433 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5436 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5439 struct command_context *cmd_ctx = current_command_context(interp);
5441 struct target *target = get_current_target(cmd_ctx);
5442 if (!target->tap->enabled)
5443 return jim_target_tap_disabled(interp);
5444 int e = target->type->halt(target);
5445 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5448 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5450 struct jim_getopt_info goi;
5451 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5453 /* params: <name> statename timeoutmsecs */
5454 if (goi.argc != 2) {
5455 const char *cmd_name = Jim_GetString(argv[0], NULL);
5456 Jim_SetResultFormatted(goi.interp,
5457 "%s <state_name> <timeout_in_msec>", cmd_name);
5462 int e = jim_getopt_nvp(&goi, nvp_target_state, &n);
5464 jim_getopt_nvp_unknown(&goi, nvp_target_state, 1);
5468 e = jim_getopt_wide(&goi, &a);
5471 struct command_context *cmd_ctx = current_command_context(interp);
5473 struct target *target = get_current_target(cmd_ctx);
5474 if (!target->tap->enabled)
5475 return jim_target_tap_disabled(interp);
5477 e = target_wait_state(target, n->value, a);
5478 if (e != ERROR_OK) {
5479 Jim_Obj *obj = Jim_NewIntObj(interp, e);
5480 Jim_SetResultFormatted(goi.interp,
5481 "target: %s wait %s fails (%#s) %s",
5482 target_name(target), n->name,
5483 obj, target_strerror_safe(e));
5488 /* List for human, Events defined for this target.
5489 * scripts/programs should use 'name cget -event NAME'
5491 COMMAND_HANDLER(handle_target_event_list)
5493 struct target *target = get_current_target(CMD_CTX);
5494 struct target_event_action *teap = target->event_action;
5496 command_print(CMD, "Event actions for target (%d) %s\n",
5497 target->target_number,
5498 target_name(target));
5499 command_print(CMD, "%-25s | Body", "Event");
5500 command_print(CMD, "------------------------- | "
5501 "----------------------------------------");
5503 struct jim_nvp *opt = jim_nvp_value2name_simple(nvp_target_event, teap->event);
5504 command_print(CMD, "%-25s | %s",
5505 opt->name, Jim_GetString(teap->body, NULL));
5508 command_print(CMD, "***END***");
5511 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5514 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5517 struct command_context *cmd_ctx = current_command_context(interp);
5519 struct target *target = get_current_target(cmd_ctx);
5520 Jim_SetResultString(interp, target_state_name(target), -1);
5523 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5525 struct jim_getopt_info goi;
5526 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5527 if (goi.argc != 1) {
5528 const char *cmd_name = Jim_GetString(argv[0], NULL);
5529 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5533 int e = jim_getopt_nvp(&goi, nvp_target_event, &n);
5535 jim_getopt_nvp_unknown(&goi, nvp_target_event, 1);
5538 struct command_context *cmd_ctx = current_command_context(interp);
5540 struct target *target = get_current_target(cmd_ctx);
5541 target_handle_event(target, n->value);
5545 static const struct command_registration target_instance_command_handlers[] = {
5547 .name = "configure",
5548 .mode = COMMAND_ANY,
5549 .jim_handler = jim_target_configure,
5550 .help = "configure a new target for use",
5551 .usage = "[target_attribute ...]",
5555 .mode = COMMAND_ANY,
5556 .jim_handler = jim_target_configure,
5557 .help = "returns the specified target attribute",
5558 .usage = "target_attribute",
5562 .handler = handle_mw_command,
5563 .mode = COMMAND_EXEC,
5564 .help = "Write 64-bit word(s) to target memory",
5565 .usage = "address data [count]",
5569 .handler = handle_mw_command,
5570 .mode = COMMAND_EXEC,
5571 .help = "Write 32-bit word(s) to target memory",
5572 .usage = "address data [count]",
5576 .handler = handle_mw_command,
5577 .mode = COMMAND_EXEC,
5578 .help = "Write 16-bit half-word(s) to target memory",
5579 .usage = "address data [count]",
5583 .handler = handle_mw_command,
5584 .mode = COMMAND_EXEC,
5585 .help = "Write byte(s) to target memory",
5586 .usage = "address data [count]",
5590 .handler = handle_md_command,
5591 .mode = COMMAND_EXEC,
5592 .help = "Display target memory as 64-bit words",
5593 .usage = "address [count]",
5597 .handler = handle_md_command,
5598 .mode = COMMAND_EXEC,
5599 .help = "Display target memory as 32-bit words",
5600 .usage = "address [count]",
5604 .handler = handle_md_command,
5605 .mode = COMMAND_EXEC,
5606 .help = "Display target memory as 16-bit half-words",
5607 .usage = "address [count]",
5611 .handler = handle_md_command,
5612 .mode = COMMAND_EXEC,
5613 .help = "Display target memory as 8-bit bytes",
5614 .usage = "address [count]",
5617 .name = "array2mem",
5618 .mode = COMMAND_EXEC,
5619 .jim_handler = jim_target_array2mem,
5620 .help = "Writes Tcl array of 8/16/32 bit numbers "
5622 .usage = "arrayname bitwidth address count",
5625 .name = "mem2array",
5626 .mode = COMMAND_EXEC,
5627 .jim_handler = jim_target_mem2array,
5628 .help = "Loads Tcl array of 8/16/32 bit numbers "
5629 "from target memory",
5630 .usage = "arrayname bitwidth address count",
5633 .name = "eventlist",
5634 .handler = handle_target_event_list,
5635 .mode = COMMAND_EXEC,
5636 .help = "displays a table of events defined for this target",
5641 .mode = COMMAND_EXEC,
5642 .jim_handler = jim_target_current_state,
5643 .help = "displays the current state of this target",
5646 .name = "arp_examine",
5647 .mode = COMMAND_EXEC,
5648 .jim_handler = jim_target_examine,
5649 .help = "used internally for reset processing",
5650 .usage = "['allow-defer']",
5653 .name = "was_examined",
5654 .mode = COMMAND_EXEC,
5655 .jim_handler = jim_target_was_examined,
5656 .help = "used internally for reset processing",
5659 .name = "examine_deferred",
5660 .mode = COMMAND_EXEC,
5661 .jim_handler = jim_target_examine_deferred,
5662 .help = "used internally for reset processing",
5665 .name = "arp_halt_gdb",
5666 .mode = COMMAND_EXEC,
5667 .jim_handler = jim_target_halt_gdb,
5668 .help = "used internally for reset processing to halt GDB",
5672 .mode = COMMAND_EXEC,
5673 .jim_handler = jim_target_poll,
5674 .help = "used internally for reset processing",
5677 .name = "arp_reset",
5678 .mode = COMMAND_EXEC,
5679 .jim_handler = jim_target_reset,
5680 .help = "used internally for reset processing",
5684 .mode = COMMAND_EXEC,
5685 .jim_handler = jim_target_halt,
5686 .help = "used internally for reset processing",
5689 .name = "arp_waitstate",
5690 .mode = COMMAND_EXEC,
5691 .jim_handler = jim_target_wait_state,
5692 .help = "used internally for reset processing",
5695 .name = "invoke-event",
5696 .mode = COMMAND_EXEC,
5697 .jim_handler = jim_target_invoke_event,
5698 .help = "invoke handler for specified event",
5699 .usage = "event_name",
5701 COMMAND_REGISTRATION_DONE
5704 static int target_create(struct jim_getopt_info *goi)
5711 struct target *target;
5712 struct command_context *cmd_ctx;
5714 cmd_ctx = current_command_context(goi->interp);
5717 if (goi->argc < 3) {
5718 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5723 jim_getopt_obj(goi, &new_cmd);
5724 /* does this command exist? */
5725 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_NONE);
5727 cp = Jim_GetString(new_cmd, NULL);
5728 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5733 e = jim_getopt_string(goi, &cp, NULL);
5736 struct transport *tr = get_current_transport();
5737 if (tr->override_target) {
5738 e = tr->override_target(&cp);
5739 if (e != ERROR_OK) {
5740 LOG_ERROR("The selected transport doesn't support this target");
5743 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5745 /* now does target type exist */
5746 for (x = 0 ; target_types[x] ; x++) {
5747 if (strcmp(cp, target_types[x]->name) == 0) {
5752 if (!target_types[x]) {
5753 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5754 for (x = 0 ; target_types[x] ; x++) {
5755 if (target_types[x + 1]) {
5756 Jim_AppendStrings(goi->interp,
5757 Jim_GetResult(goi->interp),
5758 target_types[x]->name,
5761 Jim_AppendStrings(goi->interp,
5762 Jim_GetResult(goi->interp),
5764 target_types[x]->name, NULL);
5771 target = calloc(1, sizeof(struct target));
5773 LOG_ERROR("Out of memory");
5777 /* set target number */
5778 target->target_number = new_target_number();
5780 /* allocate memory for each unique target type */
5781 target->type = malloc(sizeof(struct target_type));
5782 if (!target->type) {
5783 LOG_ERROR("Out of memory");
5788 memcpy(target->type, target_types[x], sizeof(struct target_type));
5790 /* default to first core, override with -coreid */
5793 target->working_area = 0x0;
5794 target->working_area_size = 0x0;
5795 target->working_areas = NULL;
5796 target->backup_working_area = 0;
5798 target->state = TARGET_UNKNOWN;
5799 target->debug_reason = DBG_REASON_UNDEFINED;
5800 target->reg_cache = NULL;
5801 target->breakpoints = NULL;
5802 target->watchpoints = NULL;
5803 target->next = NULL;
5804 target->arch_info = NULL;
5806 target->verbose_halt_msg = true;
5808 target->halt_issued = false;
5810 /* initialize trace information */
5811 target->trace_info = calloc(1, sizeof(struct trace));
5812 if (!target->trace_info) {
5813 LOG_ERROR("Out of memory");
5819 target->dbgmsg = NULL;
5820 target->dbg_msg_enabled = 0;
5822 target->endianness = TARGET_ENDIAN_UNKNOWN;
5824 target->rtos = NULL;
5825 target->rtos_auto_detect = false;
5827 target->gdb_port_override = NULL;
5828 target->gdb_max_connections = 1;
5830 /* Do the rest as "configure" options */
5831 goi->isconfigure = 1;
5832 e = target_configure(goi, target);
5835 if (target->has_dap) {
5836 if (!target->dap_configured) {
5837 Jim_SetResultString(goi->interp, "-dap ?name? required when creating target", -1);
5841 if (!target->tap_configured) {
5842 Jim_SetResultString(goi->interp, "-chain-position ?name? required when creating target", -1);
5846 /* tap must be set after target was configured */
5852 rtos_destroy(target);
5853 free(target->gdb_port_override);
5854 free(target->trace_info);
5860 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5861 /* default endian to little if not specified */
5862 target->endianness = TARGET_LITTLE_ENDIAN;
5865 cp = Jim_GetString(new_cmd, NULL);
5866 target->cmd_name = strdup(cp);
5867 if (!target->cmd_name) {
5868 LOG_ERROR("Out of memory");
5869 rtos_destroy(target);
5870 free(target->gdb_port_override);
5871 free(target->trace_info);
5877 if (target->type->target_create) {
5878 e = (*(target->type->target_create))(target, goi->interp);
5879 if (e != ERROR_OK) {
5880 LOG_DEBUG("target_create failed");
5881 free(target->cmd_name);
5882 rtos_destroy(target);
5883 free(target->gdb_port_override);
5884 free(target->trace_info);
5891 /* create the target specific commands */
5892 if (target->type->commands) {
5893 e = register_commands(cmd_ctx, NULL, target->type->commands);
5895 LOG_ERROR("unable to register '%s' commands", cp);
5898 /* now - create the new target name command */
5899 const struct command_registration target_subcommands[] = {
5901 .chain = target_instance_command_handlers,
5904 .chain = target->type->commands,
5906 COMMAND_REGISTRATION_DONE
5908 const struct command_registration target_commands[] = {
5911 .mode = COMMAND_ANY,
5912 .help = "target command group",
5914 .chain = target_subcommands,
5916 COMMAND_REGISTRATION_DONE
5918 e = register_commands_override_target(cmd_ctx, NULL, target_commands, target);
5919 if (e != ERROR_OK) {
5920 if (target->type->deinit_target)
5921 target->type->deinit_target(target);
5922 free(target->cmd_name);
5923 rtos_destroy(target);
5924 free(target->gdb_port_override);
5925 free(target->trace_info);
5931 /* append to end of list */
5932 append_to_list_all_targets(target);
5934 cmd_ctx->current_target = target;
5938 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5941 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5944 struct command_context *cmd_ctx = current_command_context(interp);
5947 struct target *target = get_current_target_or_null(cmd_ctx);
5949 Jim_SetResultString(interp, target_name(target), -1);
5953 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5956 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5959 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5960 for (unsigned x = 0; target_types[x]; x++) {
5961 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5962 Jim_NewStringObj(interp, target_types[x]->name, -1));
5967 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5970 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5973 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5974 struct target *target = all_targets;
5976 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5977 Jim_NewStringObj(interp, target_name(target), -1));
5978 target = target->next;
5983 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5986 const char *targetname;
5988 struct target *target = NULL;
5989 struct target_list *head, *curr, *new;
5994 LOG_DEBUG("%d", argc);
5995 /* argv[1] = target to associate in smp
5996 * argv[2] = target to associate in smp
6000 for (i = 1; i < argc; i++) {
6002 targetname = Jim_GetString(argv[i], &len);
6003 target = get_target(targetname);
6004 LOG_DEBUG("%s ", targetname);
6006 new = malloc(sizeof(struct target_list));
6007 new->target = target;
6018 /* now parse the list of cpu and put the target in smp mode*/
6022 target = curr->target;
6024 target->head = head;
6028 if (target && target->rtos)
6029 retval = rtos_smp_init(head->target);
6035 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6037 struct jim_getopt_info goi;
6038 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
6040 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
6041 "<name> <target_type> [<target_options> ...]");
6044 return target_create(&goi);
6047 static const struct command_registration target_subcommand_handlers[] = {
6050 .mode = COMMAND_CONFIG,
6051 .handler = handle_target_init_command,
6052 .help = "initialize targets",
6057 .mode = COMMAND_CONFIG,
6058 .jim_handler = jim_target_create,
6059 .usage = "name type '-chain-position' name [options ...]",
6060 .help = "Creates and selects a new target",
6064 .mode = COMMAND_ANY,
6065 .jim_handler = jim_target_current,
6066 .help = "Returns the currently selected target",
6070 .mode = COMMAND_ANY,
6071 .jim_handler = jim_target_types,
6072 .help = "Returns the available target types as "
6073 "a list of strings",
6077 .mode = COMMAND_ANY,
6078 .jim_handler = jim_target_names,
6079 .help = "Returns the names of all targets as a list of strings",
6083 .mode = COMMAND_ANY,
6084 .jim_handler = jim_target_smp,
6085 .usage = "targetname1 targetname2 ...",
6086 .help = "gather several target in a smp list"
6089 COMMAND_REGISTRATION_DONE
6093 target_addr_t address;
6099 static int fastload_num;
6100 static struct fast_load *fastload;
6102 static void free_fastload(void)
6105 for (int i = 0; i < fastload_num; i++)
6106 free(fastload[i].data);
6112 COMMAND_HANDLER(handle_fast_load_image_command)
6116 uint32_t image_size;
6117 target_addr_t min_address = 0;
6118 target_addr_t max_address = -1;
6122 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
6123 &image, &min_address, &max_address);
6124 if (retval != ERROR_OK)
6127 struct duration bench;
6128 duration_start(&bench);
6130 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
6131 if (retval != ERROR_OK)
6136 fastload_num = image.num_sections;
6137 fastload = malloc(sizeof(struct fast_load)*image.num_sections);
6139 command_print(CMD, "out of memory");
6140 image_close(&image);
6143 memset(fastload, 0, sizeof(struct fast_load)*image.num_sections);
6144 for (unsigned int i = 0; i < image.num_sections; i++) {
6145 buffer = malloc(image.sections[i].size);
6147 command_print(CMD, "error allocating buffer for section (%d bytes)",
6148 (int)(image.sections[i].size));
6149 retval = ERROR_FAIL;
6153 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
6154 if (retval != ERROR_OK) {
6159 uint32_t offset = 0;
6160 uint32_t length = buf_cnt;
6162 /* DANGER!!! beware of unsigned comparison here!!! */
6164 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
6165 (image.sections[i].base_address < max_address)) {
6166 if (image.sections[i].base_address < min_address) {
6167 /* clip addresses below */
6168 offset += min_address-image.sections[i].base_address;
6172 if (image.sections[i].base_address + buf_cnt > max_address)
6173 length -= (image.sections[i].base_address + buf_cnt)-max_address;
6175 fastload[i].address = image.sections[i].base_address + offset;
6176 fastload[i].data = malloc(length);
6177 if (!fastload[i].data) {
6179 command_print(CMD, "error allocating buffer for section (%" PRIu32 " bytes)",
6181 retval = ERROR_FAIL;
6184 memcpy(fastload[i].data, buffer + offset, length);
6185 fastload[i].length = length;
6187 image_size += length;
6188 command_print(CMD, "%u bytes written at address 0x%8.8x",
6189 (unsigned int)length,
6190 ((unsigned int)(image.sections[i].base_address + offset)));
6196 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
6197 command_print(CMD, "Loaded %" PRIu32 " bytes "
6198 "in %fs (%0.3f KiB/s)", image_size,
6199 duration_elapsed(&bench), duration_kbps(&bench, image_size));
6202 "WARNING: image has not been loaded to target!"
6203 "You can issue a 'fast_load' to finish loading.");
6206 image_close(&image);
6208 if (retval != ERROR_OK)
6214 COMMAND_HANDLER(handle_fast_load_command)
6217 return ERROR_COMMAND_SYNTAX_ERROR;
6219 LOG_ERROR("No image in memory");
6223 int64_t ms = timeval_ms();
6225 int retval = ERROR_OK;
6226 for (i = 0; i < fastload_num; i++) {
6227 struct target *target = get_current_target(CMD_CTX);
6228 command_print(CMD, "Write to 0x%08x, length 0x%08x",
6229 (unsigned int)(fastload[i].address),
6230 (unsigned int)(fastload[i].length));
6231 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
6232 if (retval != ERROR_OK)
6234 size += fastload[i].length;
6236 if (retval == ERROR_OK) {
6237 int64_t after = timeval_ms();
6238 command_print(CMD, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
6243 static const struct command_registration target_command_handlers[] = {
6246 .handler = handle_targets_command,
6247 .mode = COMMAND_ANY,
6248 .help = "change current default target (one parameter) "
6249 "or prints table of all targets (no parameters)",
6250 .usage = "[target]",
6254 .mode = COMMAND_CONFIG,
6255 .help = "configure target",
6256 .chain = target_subcommand_handlers,
6259 COMMAND_REGISTRATION_DONE
6262 int target_register_commands(struct command_context *cmd_ctx)
6264 return register_commands(cmd_ctx, NULL, target_command_handlers);
6267 static bool target_reset_nag = true;
6269 bool get_target_reset_nag(void)
6271 return target_reset_nag;
6274 COMMAND_HANDLER(handle_target_reset_nag)
6276 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
6277 &target_reset_nag, "Nag after each reset about options to improve "
6281 COMMAND_HANDLER(handle_ps_command)
6283 struct target *target = get_current_target(CMD_CTX);
6285 if (target->state != TARGET_HALTED) {
6286 LOG_INFO("target not halted !!");
6290 if ((target->rtos) && (target->rtos->type)
6291 && (target->rtos->type->ps_command)) {
6292 display = target->rtos->type->ps_command(target);
6293 command_print(CMD, "%s", display);
6298 return ERROR_TARGET_FAILURE;
6302 static void binprint(struct command_invocation *cmd, const char *text, const uint8_t *buf, int size)
6305 command_print_sameline(cmd, "%s", text);
6306 for (int i = 0; i < size; i++)
6307 command_print_sameline(cmd, " %02x", buf[i]);
6308 command_print(cmd, " ");
6311 COMMAND_HANDLER(handle_test_mem_access_command)
6313 struct target *target = get_current_target(CMD_CTX);
6315 int retval = ERROR_OK;
6317 if (target->state != TARGET_HALTED) {
6318 LOG_INFO("target not halted !!");
6323 return ERROR_COMMAND_SYNTAX_ERROR;
6325 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
6328 size_t num_bytes = test_size + 4;
6330 struct working_area *wa = NULL;
6331 retval = target_alloc_working_area(target, num_bytes, &wa);
6332 if (retval != ERROR_OK) {
6333 LOG_ERROR("Not enough working area");
6337 uint8_t *test_pattern = malloc(num_bytes);
6339 for (size_t i = 0; i < num_bytes; i++)
6340 test_pattern[i] = rand();
6342 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6343 if (retval != ERROR_OK) {
6344 LOG_ERROR("Test pattern write failed");
6348 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6349 for (int size = 1; size <= 4; size *= 2) {
6350 for (int offset = 0; offset < 4; offset++) {
6351 uint32_t count = test_size / size;
6352 size_t host_bufsiz = (count + 2) * size + host_offset;
6353 uint8_t *read_ref = malloc(host_bufsiz);
6354 uint8_t *read_buf = malloc(host_bufsiz);
6356 for (size_t i = 0; i < host_bufsiz; i++) {
6357 read_ref[i] = rand();
6358 read_buf[i] = read_ref[i];
6360 command_print_sameline(CMD,
6361 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
6362 size, offset, host_offset ? "un" : "");
6364 struct duration bench;
6365 duration_start(&bench);
6367 retval = target_read_memory(target, wa->address + offset, size, count,
6368 read_buf + size + host_offset);
6370 duration_measure(&bench);
6372 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6373 command_print(CMD, "Unsupported alignment");
6375 } else if (retval != ERROR_OK) {
6376 command_print(CMD, "Memory read failed");
6380 /* replay on host */
6381 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
6384 int result = memcmp(read_ref, read_buf, host_bufsiz);
6386 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6387 duration_elapsed(&bench),
6388 duration_kbps(&bench, count * size));
6390 command_print(CMD, "Compare failed");
6391 binprint(CMD, "ref:", read_ref, host_bufsiz);
6392 binprint(CMD, "buf:", read_buf, host_bufsiz);
6405 target_free_working_area(target, wa);
6408 num_bytes = test_size + 4 + 4 + 4;
6410 retval = target_alloc_working_area(target, num_bytes, &wa);
6411 if (retval != ERROR_OK) {
6412 LOG_ERROR("Not enough working area");
6416 test_pattern = malloc(num_bytes);
6418 for (size_t i = 0; i < num_bytes; i++)
6419 test_pattern[i] = rand();
6421 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6422 for (int size = 1; size <= 4; size *= 2) {
6423 for (int offset = 0; offset < 4; offset++) {
6424 uint32_t count = test_size / size;
6425 size_t host_bufsiz = count * size + host_offset;
6426 uint8_t *read_ref = malloc(num_bytes);
6427 uint8_t *read_buf = malloc(num_bytes);
6428 uint8_t *write_buf = malloc(host_bufsiz);
6430 for (size_t i = 0; i < host_bufsiz; i++)
6431 write_buf[i] = rand();
6432 command_print_sameline(CMD,
6433 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
6434 size, offset, host_offset ? "un" : "");
6436 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6437 if (retval != ERROR_OK) {
6438 command_print(CMD, "Test pattern write failed");
6442 /* replay on host */
6443 memcpy(read_ref, test_pattern, num_bytes);
6444 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
6446 struct duration bench;
6447 duration_start(&bench);
6449 retval = target_write_memory(target, wa->address + size + offset, size, count,
6450 write_buf + host_offset);
6452 duration_measure(&bench);
6454 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6455 command_print(CMD, "Unsupported alignment");
6457 } else if (retval != ERROR_OK) {
6458 command_print(CMD, "Memory write failed");
6463 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
6464 if (retval != ERROR_OK) {
6465 command_print(CMD, "Test pattern write failed");
6470 int result = memcmp(read_ref, read_buf, num_bytes);
6472 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6473 duration_elapsed(&bench),
6474 duration_kbps(&bench, count * size));
6476 command_print(CMD, "Compare failed");
6477 binprint(CMD, "ref:", read_ref, num_bytes);
6478 binprint(CMD, "buf:", read_buf, num_bytes);
6490 target_free_working_area(target, wa);
6494 static const struct command_registration target_exec_command_handlers[] = {
6496 .name = "fast_load_image",
6497 .handler = handle_fast_load_image_command,
6498 .mode = COMMAND_ANY,
6499 .help = "Load image into server memory for later use by "
6500 "fast_load; primarily for profiling",
6501 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6502 "[min_address [max_length]]",
6505 .name = "fast_load",
6506 .handler = handle_fast_load_command,
6507 .mode = COMMAND_EXEC,
6508 .help = "loads active fast load image to current target "
6509 "- mainly for profiling purposes",
6514 .handler = handle_profile_command,
6515 .mode = COMMAND_EXEC,
6516 .usage = "seconds filename [start end]",
6517 .help = "profiling samples the CPU PC",
6519 /** @todo don't register virt2phys() unless target supports it */
6521 .name = "virt2phys",
6522 .handler = handle_virt2phys_command,
6523 .mode = COMMAND_ANY,
6524 .help = "translate a virtual address into a physical address",
6525 .usage = "virtual_address",
6529 .handler = handle_reg_command,
6530 .mode = COMMAND_EXEC,
6531 .help = "display (reread from target with \"force\") or set a register; "
6532 "with no arguments, displays all registers and their values",
6533 .usage = "[(register_number|register_name) [(value|'force')]]",
6537 .handler = handle_poll_command,
6538 .mode = COMMAND_EXEC,
6539 .help = "poll target state; or reconfigure background polling",
6540 .usage = "['on'|'off']",
6543 .name = "wait_halt",
6544 .handler = handle_wait_halt_command,
6545 .mode = COMMAND_EXEC,
6546 .help = "wait up to the specified number of milliseconds "
6547 "(default 5000) for a previously requested halt",
6548 .usage = "[milliseconds]",
6552 .handler = handle_halt_command,
6553 .mode = COMMAND_EXEC,
6554 .help = "request target to halt, then wait up to the specified "
6555 "number of milliseconds (default 5000) for it to complete",
6556 .usage = "[milliseconds]",
6560 .handler = handle_resume_command,
6561 .mode = COMMAND_EXEC,
6562 .help = "resume target execution from current PC or address",
6563 .usage = "[address]",
6567 .handler = handle_reset_command,
6568 .mode = COMMAND_EXEC,
6569 .usage = "[run|halt|init]",
6570 .help = "Reset all targets into the specified mode. "
6571 "Default reset mode is run, if not given.",
6574 .name = "soft_reset_halt",
6575 .handler = handle_soft_reset_halt_command,
6576 .mode = COMMAND_EXEC,
6578 .help = "halt the target and do a soft reset",
6582 .handler = handle_step_command,
6583 .mode = COMMAND_EXEC,
6584 .help = "step one instruction from current PC or address",
6585 .usage = "[address]",
6589 .handler = handle_md_command,
6590 .mode = COMMAND_EXEC,
6591 .help = "display memory double-words",
6592 .usage = "['phys'] address [count]",
6596 .handler = handle_md_command,
6597 .mode = COMMAND_EXEC,
6598 .help = "display memory words",
6599 .usage = "['phys'] address [count]",
6603 .handler = handle_md_command,
6604 .mode = COMMAND_EXEC,
6605 .help = "display memory half-words",
6606 .usage = "['phys'] address [count]",
6610 .handler = handle_md_command,
6611 .mode = COMMAND_EXEC,
6612 .help = "display memory bytes",
6613 .usage = "['phys'] address [count]",
6617 .handler = handle_mw_command,
6618 .mode = COMMAND_EXEC,
6619 .help = "write memory double-word",
6620 .usage = "['phys'] address value [count]",
6624 .handler = handle_mw_command,
6625 .mode = COMMAND_EXEC,
6626 .help = "write memory word",
6627 .usage = "['phys'] address value [count]",
6631 .handler = handle_mw_command,
6632 .mode = COMMAND_EXEC,
6633 .help = "write memory half-word",
6634 .usage = "['phys'] address value [count]",
6638 .handler = handle_mw_command,
6639 .mode = COMMAND_EXEC,
6640 .help = "write memory byte",
6641 .usage = "['phys'] address value [count]",
6645 .handler = handle_bp_command,
6646 .mode = COMMAND_EXEC,
6647 .help = "list or set hardware or software breakpoint",
6648 .usage = "[<address> [<asid>] <length> ['hw'|'hw_ctx']]",
6652 .handler = handle_rbp_command,
6653 .mode = COMMAND_EXEC,
6654 .help = "remove breakpoint",
6655 .usage = "'all' | address",
6659 .handler = handle_wp_command,
6660 .mode = COMMAND_EXEC,
6661 .help = "list (no params) or create watchpoints",
6662 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
6666 .handler = handle_rwp_command,
6667 .mode = COMMAND_EXEC,
6668 .help = "remove watchpoint",
6672 .name = "load_image",
6673 .handler = handle_load_image_command,
6674 .mode = COMMAND_EXEC,
6675 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6676 "[min_address] [max_length]",
6679 .name = "dump_image",
6680 .handler = handle_dump_image_command,
6681 .mode = COMMAND_EXEC,
6682 .usage = "filename address size",
6685 .name = "verify_image_checksum",
6686 .handler = handle_verify_image_checksum_command,
6687 .mode = COMMAND_EXEC,
6688 .usage = "filename [offset [type]]",
6691 .name = "verify_image",
6692 .handler = handle_verify_image_command,
6693 .mode = COMMAND_EXEC,
6694 .usage = "filename [offset [type]]",
6697 .name = "test_image",
6698 .handler = handle_test_image_command,
6699 .mode = COMMAND_EXEC,
6700 .usage = "filename [offset [type]]",
6703 .name = "mem2array",
6704 .mode = COMMAND_EXEC,
6705 .jim_handler = jim_mem2array,
6706 .help = "read 8/16/32 bit memory and return as a TCL array "
6707 "for script processing",
6708 .usage = "arrayname bitwidth address count",
6711 .name = "array2mem",
6712 .mode = COMMAND_EXEC,
6713 .jim_handler = jim_array2mem,
6714 .help = "convert a TCL array to memory locations "
6715 "and write the 8/16/32 bit values",
6716 .usage = "arrayname bitwidth address count",
6719 .name = "reset_nag",
6720 .handler = handle_target_reset_nag,
6721 .mode = COMMAND_ANY,
6722 .help = "Nag after each reset about options that could have been "
6723 "enabled to improve performance.",
6724 .usage = "['enable'|'disable']",
6728 .handler = handle_ps_command,
6729 .mode = COMMAND_EXEC,
6730 .help = "list all tasks",
6734 .name = "test_mem_access",
6735 .handler = handle_test_mem_access_command,
6736 .mode = COMMAND_EXEC,
6737 .help = "Test the target's memory access functions",
6741 COMMAND_REGISTRATION_DONE
6743 static int target_register_user_commands(struct command_context *cmd_ctx)
6745 int retval = ERROR_OK;
6746 retval = target_request_register_commands(cmd_ctx);
6747 if (retval != ERROR_OK)
6750 retval = trace_register_commands(cmd_ctx);
6751 if (retval != ERROR_OK)
6755 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);