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 target_event_name(event),
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 if (!area || area->free)
2154 int retval = ERROR_OK;
2156 retval = target_restore_working_area(target, area);
2157 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
2158 if (retval != ERROR_OK)
2164 LOG_DEBUG("freed %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2165 area->size, area->address);
2167 /* mark user pointer invalid */
2168 /* TODO: Is this really safe? It points to some previous caller's memory.
2169 * How could we know that the area pointer is still in that place and not
2170 * some other vital data? What's the purpose of this, anyway? */
2174 target_merge_working_areas(target);
2176 print_wa_layout(target);
2181 int target_free_working_area(struct target *target, struct working_area *area)
2183 return target_free_working_area_restore(target, area, 1);
2186 /* free resources and restore memory, if restoring memory fails,
2187 * free up resources anyway
2189 static void target_free_all_working_areas_restore(struct target *target, int restore)
2191 struct working_area *c = target->working_areas;
2193 LOG_DEBUG("freeing all working areas");
2195 /* Loop through all areas, restoring the allocated ones and marking them as free */
2199 target_restore_working_area(target, c);
2201 *c->user = NULL; /* Same as above */
2207 /* Run a merge pass to combine all areas into one */
2208 target_merge_working_areas(target);
2210 print_wa_layout(target);
2213 void target_free_all_working_areas(struct target *target)
2215 target_free_all_working_areas_restore(target, 1);
2217 /* Now we have none or only one working area marked as free */
2218 if (target->working_areas) {
2219 /* Free the last one to allow on-the-fly moving and resizing */
2220 free(target->working_areas->backup);
2221 free(target->working_areas);
2222 target->working_areas = NULL;
2226 /* Find the largest number of bytes that can be allocated */
2227 uint32_t target_get_working_area_avail(struct target *target)
2229 struct working_area *c = target->working_areas;
2230 uint32_t max_size = 0;
2233 return target->working_area_size;
2236 if (c->free && max_size < c->size)
2245 static void target_destroy(struct target *target)
2247 if (target->type->deinit_target)
2248 target->type->deinit_target(target);
2250 free(target->semihosting);
2252 jtag_unregister_event_callback(jtag_enable_callback, target);
2254 struct target_event_action *teap = target->event_action;
2256 struct target_event_action *next = teap->next;
2257 Jim_DecrRefCount(teap->interp, teap->body);
2262 target_free_all_working_areas(target);
2264 /* release the targets SMP list */
2266 struct target_list *head = target->head;
2268 struct target_list *pos = head->next;
2269 head->target->smp = 0;
2276 rtos_destroy(target);
2278 free(target->gdb_port_override);
2280 free(target->trace_info);
2281 free(target->fileio_info);
2282 free(target->cmd_name);
2286 void target_quit(void)
2288 struct target_event_callback *pe = target_event_callbacks;
2290 struct target_event_callback *t = pe->next;
2294 target_event_callbacks = NULL;
2296 struct target_timer_callback *pt = target_timer_callbacks;
2298 struct target_timer_callback *t = pt->next;
2302 target_timer_callbacks = NULL;
2304 for (struct target *target = all_targets; target;) {
2308 target_destroy(target);
2315 int target_arch_state(struct target *target)
2319 LOG_WARNING("No target has been configured");
2323 if (target->state != TARGET_HALTED)
2326 retval = target->type->arch_state(target);
2330 static int target_get_gdb_fileio_info_default(struct target *target,
2331 struct gdb_fileio_info *fileio_info)
2333 /* If target does not support semi-hosting function, target
2334 has no need to provide .get_gdb_fileio_info callback.
2335 It just return ERROR_FAIL and gdb_server will return "Txx"
2336 as target halted every time. */
2340 static int target_gdb_fileio_end_default(struct target *target,
2341 int retcode, int fileio_errno, bool ctrl_c)
2346 int target_profiling_default(struct target *target, uint32_t *samples,
2347 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
2349 struct timeval timeout, now;
2351 gettimeofday(&timeout, NULL);
2352 timeval_add_time(&timeout, seconds, 0);
2354 LOG_INFO("Starting profiling. Halting and resuming the"
2355 " target as often as we can...");
2357 uint32_t sample_count = 0;
2358 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2359 struct reg *reg = register_get_by_name(target->reg_cache, "pc", true);
2361 int retval = ERROR_OK;
2363 target_poll(target);
2364 if (target->state == TARGET_HALTED) {
2365 uint32_t t = buf_get_u32(reg->value, 0, 32);
2366 samples[sample_count++] = t;
2367 /* current pc, addr = 0, do not handle breakpoints, not debugging */
2368 retval = target_resume(target, 1, 0, 0, 0);
2369 target_poll(target);
2370 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2371 } else if (target->state == TARGET_RUNNING) {
2372 /* We want to quickly sample the PC. */
2373 retval = target_halt(target);
2375 LOG_INFO("Target not halted or running");
2380 if (retval != ERROR_OK)
2383 gettimeofday(&now, NULL);
2384 if ((sample_count >= max_num_samples) || timeval_compare(&now, &timeout) >= 0) {
2385 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2390 *num_samples = sample_count;
2394 /* Single aligned words are guaranteed to use 16 or 32 bit access
2395 * mode respectively, otherwise data is handled as quickly as
2398 int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
2400 LOG_DEBUG("writing buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2403 if (!target_was_examined(target)) {
2404 LOG_ERROR("Target not examined yet");
2411 if ((address + size - 1) < address) {
2412 /* GDB can request this when e.g. PC is 0xfffffffc */
2413 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2419 return target->type->write_buffer(target, address, size, buffer);
2422 static int target_write_buffer_default(struct target *target,
2423 target_addr_t address, uint32_t count, const uint8_t *buffer)
2426 unsigned int data_bytes = target_data_bits(target) / 8;
2428 /* Align up to maximum bytes. The loop condition makes sure the next pass
2429 * will have something to do with the size we leave to it. */
2431 size < data_bytes && count >= size * 2 + (address & size);
2433 if (address & size) {
2434 int retval = target_write_memory(target, address, size, 1, buffer);
2435 if (retval != ERROR_OK)
2443 /* Write the data with as large access size as possible. */
2444 for (; size > 0; size /= 2) {
2445 uint32_t aligned = count - count % size;
2447 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2448 if (retval != ERROR_OK)
2459 /* Single aligned words are guaranteed to use 16 or 32 bit access
2460 * mode respectively, otherwise data is handled as quickly as
2463 int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
2465 LOG_DEBUG("reading buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2468 if (!target_was_examined(target)) {
2469 LOG_ERROR("Target not examined yet");
2476 if ((address + size - 1) < address) {
2477 /* GDB can request this when e.g. PC is 0xfffffffc */
2478 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2484 return target->type->read_buffer(target, address, size, buffer);
2487 static int target_read_buffer_default(struct target *target, target_addr_t address, uint32_t count, uint8_t *buffer)
2490 unsigned int data_bytes = target_data_bits(target) / 8;
2492 /* Align up to maximum bytes. The loop condition makes sure the next pass
2493 * will have something to do with the size we leave to it. */
2495 size < data_bytes && count >= size * 2 + (address & size);
2497 if (address & size) {
2498 int retval = target_read_memory(target, address, size, 1, buffer);
2499 if (retval != ERROR_OK)
2507 /* Read the data with as large access size as possible. */
2508 for (; size > 0; size /= 2) {
2509 uint32_t aligned = count - count % size;
2511 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2512 if (retval != ERROR_OK)
2523 int target_checksum_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t *crc)
2528 uint32_t checksum = 0;
2529 if (!target_was_examined(target)) {
2530 LOG_ERROR("Target not examined yet");
2533 if (!target->type->checksum_memory) {
2534 LOG_ERROR("Target %s doesn't support checksum_memory", target_name(target));
2538 retval = target->type->checksum_memory(target, address, size, &checksum);
2539 if (retval != ERROR_OK) {
2540 buffer = malloc(size);
2542 LOG_ERROR("error allocating buffer for section (%" PRIu32 " bytes)", size);
2543 return ERROR_COMMAND_SYNTAX_ERROR;
2545 retval = target_read_buffer(target, address, size, buffer);
2546 if (retval != ERROR_OK) {
2551 /* convert to target endianness */
2552 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2553 uint32_t target_data;
2554 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2555 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2558 retval = image_calculate_checksum(buffer, size, &checksum);
2567 int target_blank_check_memory(struct target *target,
2568 struct target_memory_check_block *blocks, int num_blocks,
2569 uint8_t erased_value)
2571 if (!target_was_examined(target)) {
2572 LOG_ERROR("Target not examined yet");
2576 if (!target->type->blank_check_memory)
2577 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2579 return target->type->blank_check_memory(target, blocks, num_blocks, erased_value);
2582 int target_read_u64(struct target *target, target_addr_t address, uint64_t *value)
2584 uint8_t value_buf[8];
2585 if (!target_was_examined(target)) {
2586 LOG_ERROR("Target not examined yet");
2590 int retval = target_read_memory(target, address, 8, 1, value_buf);
2592 if (retval == ERROR_OK) {
2593 *value = target_buffer_get_u64(target, value_buf);
2594 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2599 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2606 int target_read_u32(struct target *target, target_addr_t address, uint32_t *value)
2608 uint8_t value_buf[4];
2609 if (!target_was_examined(target)) {
2610 LOG_ERROR("Target not examined yet");
2614 int retval = target_read_memory(target, address, 4, 1, value_buf);
2616 if (retval == ERROR_OK) {
2617 *value = target_buffer_get_u32(target, value_buf);
2618 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2623 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2630 int target_read_u16(struct target *target, target_addr_t address, uint16_t *value)
2632 uint8_t value_buf[2];
2633 if (!target_was_examined(target)) {
2634 LOG_ERROR("Target not examined yet");
2638 int retval = target_read_memory(target, address, 2, 1, value_buf);
2640 if (retval == ERROR_OK) {
2641 *value = target_buffer_get_u16(target, value_buf);
2642 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%4.4" PRIx16,
2647 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2654 int target_read_u8(struct target *target, target_addr_t address, uint8_t *value)
2656 if (!target_was_examined(target)) {
2657 LOG_ERROR("Target not examined yet");
2661 int retval = target_read_memory(target, address, 1, 1, value);
2663 if (retval == ERROR_OK) {
2664 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2669 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2676 int target_write_u64(struct target *target, target_addr_t address, uint64_t value)
2679 uint8_t value_buf[8];
2680 if (!target_was_examined(target)) {
2681 LOG_ERROR("Target not examined yet");
2685 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2689 target_buffer_set_u64(target, value_buf, value);
2690 retval = target_write_memory(target, address, 8, 1, value_buf);
2691 if (retval != ERROR_OK)
2692 LOG_DEBUG("failed: %i", retval);
2697 int target_write_u32(struct target *target, target_addr_t address, uint32_t value)
2700 uint8_t value_buf[4];
2701 if (!target_was_examined(target)) {
2702 LOG_ERROR("Target not examined yet");
2706 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2710 target_buffer_set_u32(target, value_buf, value);
2711 retval = target_write_memory(target, address, 4, 1, value_buf);
2712 if (retval != ERROR_OK)
2713 LOG_DEBUG("failed: %i", retval);
2718 int target_write_u16(struct target *target, target_addr_t address, uint16_t value)
2721 uint8_t value_buf[2];
2722 if (!target_was_examined(target)) {
2723 LOG_ERROR("Target not examined yet");
2727 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2731 target_buffer_set_u16(target, value_buf, value);
2732 retval = target_write_memory(target, address, 2, 1, value_buf);
2733 if (retval != ERROR_OK)
2734 LOG_DEBUG("failed: %i", retval);
2739 int target_write_u8(struct target *target, target_addr_t address, uint8_t value)
2742 if (!target_was_examined(target)) {
2743 LOG_ERROR("Target not examined yet");
2747 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2750 retval = target_write_memory(target, address, 1, 1, &value);
2751 if (retval != ERROR_OK)
2752 LOG_DEBUG("failed: %i", retval);
2757 int target_write_phys_u64(struct target *target, target_addr_t address, uint64_t value)
2760 uint8_t value_buf[8];
2761 if (!target_was_examined(target)) {
2762 LOG_ERROR("Target not examined yet");
2766 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2770 target_buffer_set_u64(target, value_buf, value);
2771 retval = target_write_phys_memory(target, address, 8, 1, value_buf);
2772 if (retval != ERROR_OK)
2773 LOG_DEBUG("failed: %i", retval);
2778 int target_write_phys_u32(struct target *target, target_addr_t address, uint32_t value)
2781 uint8_t value_buf[4];
2782 if (!target_was_examined(target)) {
2783 LOG_ERROR("Target not examined yet");
2787 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2791 target_buffer_set_u32(target, value_buf, value);
2792 retval = target_write_phys_memory(target, address, 4, 1, value_buf);
2793 if (retval != ERROR_OK)
2794 LOG_DEBUG("failed: %i", retval);
2799 int target_write_phys_u16(struct target *target, target_addr_t address, uint16_t value)
2802 uint8_t value_buf[2];
2803 if (!target_was_examined(target)) {
2804 LOG_ERROR("Target not examined yet");
2808 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2812 target_buffer_set_u16(target, value_buf, value);
2813 retval = target_write_phys_memory(target, address, 2, 1, value_buf);
2814 if (retval != ERROR_OK)
2815 LOG_DEBUG("failed: %i", retval);
2820 int target_write_phys_u8(struct target *target, target_addr_t address, uint8_t value)
2823 if (!target_was_examined(target)) {
2824 LOG_ERROR("Target not examined yet");
2828 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2831 retval = target_write_phys_memory(target, address, 1, 1, &value);
2832 if (retval != ERROR_OK)
2833 LOG_DEBUG("failed: %i", retval);
2838 static int find_target(struct command_invocation *cmd, const char *name)
2840 struct target *target = get_target(name);
2842 command_print(cmd, "Target: %s is unknown, try one of:\n", name);
2845 if (!target->tap->enabled) {
2846 command_print(cmd, "Target: TAP %s is disabled, "
2847 "can't be the current target\n",
2848 target->tap->dotted_name);
2852 cmd->ctx->current_target = target;
2853 if (cmd->ctx->current_target_override)
2854 cmd->ctx->current_target_override = target;
2860 COMMAND_HANDLER(handle_targets_command)
2862 int retval = ERROR_OK;
2863 if (CMD_ARGC == 1) {
2864 retval = find_target(CMD, CMD_ARGV[0]);
2865 if (retval == ERROR_OK) {
2871 struct target *target = all_targets;
2872 command_print(CMD, " TargetName Type Endian TapName State ");
2873 command_print(CMD, "-- ------------------ ---------- ------ ------------------ ------------");
2878 if (target->tap->enabled)
2879 state = target_state_name(target);
2881 state = "tap-disabled";
2883 if (CMD_CTX->current_target == target)
2886 /* keep columns lined up to match the headers above */
2888 "%2d%c %-18s %-10s %-6s %-18s %s",
2889 target->target_number,
2891 target_name(target),
2892 target_type_name(target),
2893 jim_nvp_value2name_simple(nvp_target_endian,
2894 target->endianness)->name,
2895 target->tap->dotted_name,
2897 target = target->next;
2903 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2905 static int power_dropout;
2906 static int srst_asserted;
2908 static int run_power_restore;
2909 static int run_power_dropout;
2910 static int run_srst_asserted;
2911 static int run_srst_deasserted;
2913 static int sense_handler(void)
2915 static int prev_srst_asserted;
2916 static int prev_power_dropout;
2918 int retval = jtag_power_dropout(&power_dropout);
2919 if (retval != ERROR_OK)
2923 power_restored = prev_power_dropout && !power_dropout;
2925 run_power_restore = 1;
2927 int64_t current = timeval_ms();
2928 static int64_t last_power;
2929 bool wait_more = last_power + 2000 > current;
2930 if (power_dropout && !wait_more) {
2931 run_power_dropout = 1;
2932 last_power = current;
2935 retval = jtag_srst_asserted(&srst_asserted);
2936 if (retval != ERROR_OK)
2939 int srst_deasserted;
2940 srst_deasserted = prev_srst_asserted && !srst_asserted;
2942 static int64_t last_srst;
2943 wait_more = last_srst + 2000 > current;
2944 if (srst_deasserted && !wait_more) {
2945 run_srst_deasserted = 1;
2946 last_srst = current;
2949 if (!prev_srst_asserted && srst_asserted)
2950 run_srst_asserted = 1;
2952 prev_srst_asserted = srst_asserted;
2953 prev_power_dropout = power_dropout;
2955 if (srst_deasserted || power_restored) {
2956 /* Other than logging the event we can't do anything here.
2957 * Issuing a reset is a particularly bad idea as we might
2958 * be inside a reset already.
2965 /* process target state changes */
2966 static int handle_target(void *priv)
2968 Jim_Interp *interp = (Jim_Interp *)priv;
2969 int retval = ERROR_OK;
2971 if (!is_jtag_poll_safe()) {
2972 /* polling is disabled currently */
2976 /* we do not want to recurse here... */
2977 static int recursive;
2981 /* danger! running these procedures can trigger srst assertions and power dropouts.
2982 * We need to avoid an infinite loop/recursion here and we do that by
2983 * clearing the flags after running these events.
2985 int did_something = 0;
2986 if (run_srst_asserted) {
2987 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2988 Jim_Eval(interp, "srst_asserted");
2991 if (run_srst_deasserted) {
2992 Jim_Eval(interp, "srst_deasserted");
2995 if (run_power_dropout) {
2996 LOG_INFO("Power dropout detected, running power_dropout proc.");
2997 Jim_Eval(interp, "power_dropout");
3000 if (run_power_restore) {
3001 Jim_Eval(interp, "power_restore");
3005 if (did_something) {
3006 /* clear detect flags */
3010 /* clear action flags */
3012 run_srst_asserted = 0;
3013 run_srst_deasserted = 0;
3014 run_power_restore = 0;
3015 run_power_dropout = 0;
3020 /* Poll targets for state changes unless that's globally disabled.
3021 * Skip targets that are currently disabled.
3023 for (struct target *target = all_targets;
3024 is_jtag_poll_safe() && target;
3025 target = target->next) {
3027 if (!target_was_examined(target))
3030 if (!target->tap->enabled)
3033 if (target->backoff.times > target->backoff.count) {
3034 /* do not poll this time as we failed previously */
3035 target->backoff.count++;
3038 target->backoff.count = 0;
3040 /* only poll target if we've got power and srst isn't asserted */
3041 if (!power_dropout && !srst_asserted) {
3042 /* polling may fail silently until the target has been examined */
3043 retval = target_poll(target);
3044 if (retval != ERROR_OK) {
3045 /* 100ms polling interval. Increase interval between polling up to 5000ms */
3046 if (target->backoff.times * polling_interval < 5000) {
3047 target->backoff.times *= 2;
3048 target->backoff.times++;
3051 /* Tell GDB to halt the debugger. This allows the user to
3052 * run monitor commands to handle the situation.
3054 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3056 if (target->backoff.times > 0) {
3057 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
3058 target_reset_examined(target);
3059 retval = target_examine_one(target);
3060 /* Target examination could have failed due to unstable connection,
3061 * but we set the examined flag anyway to repoll it later */
3062 if (retval != ERROR_OK) {
3063 target_set_examined(target);
3064 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
3065 target->backoff.times * polling_interval);
3070 /* Since we succeeded, we reset backoff count */
3071 target->backoff.times = 0;
3078 COMMAND_HANDLER(handle_reg_command)
3082 struct target *target = get_current_target(CMD_CTX);
3083 struct reg *reg = NULL;
3085 /* list all available registers for the current target */
3086 if (CMD_ARGC == 0) {
3087 struct reg_cache *cache = target->reg_cache;
3089 unsigned int count = 0;
3093 command_print(CMD, "===== %s", cache->name);
3095 for (i = 0, reg = cache->reg_list;
3096 i < cache->num_regs;
3097 i++, reg++, count++) {
3098 if (reg->exist == false || reg->hidden)
3100 /* only print cached values if they are valid */
3102 char *value = buf_to_hex_str(reg->value,
3105 "(%i) %s (/%" PRIu32 "): 0x%s%s",
3113 command_print(CMD, "(%i) %s (/%" PRIu32 ")",
3118 cache = cache->next;
3124 /* access a single register by its ordinal number */
3125 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
3127 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
3129 struct reg_cache *cache = target->reg_cache;
3130 unsigned int count = 0;
3133 for (i = 0; i < cache->num_regs; i++) {
3134 if (count++ == num) {
3135 reg = &cache->reg_list[i];
3141 cache = cache->next;
3145 command_print(CMD, "%i is out of bounds, the current target "
3146 "has only %i registers (0 - %i)", num, count, count - 1);
3150 /* access a single register by its name */
3151 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], true);
3157 assert(reg); /* give clang a hint that we *know* reg is != NULL here */
3162 /* display a register */
3163 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
3164 && (CMD_ARGV[1][0] <= '9')))) {
3165 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
3168 if (reg->valid == 0) {
3169 int retval = reg->type->get(reg);
3170 if (retval != ERROR_OK) {
3171 LOG_ERROR("Could not read register '%s'", reg->name);
3175 char *value = buf_to_hex_str(reg->value, reg->size);
3176 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3181 /* set register value */
3182 if (CMD_ARGC == 2) {
3183 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
3186 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
3188 int retval = reg->type->set(reg, buf);
3189 if (retval != ERROR_OK) {
3190 LOG_ERROR("Could not write to register '%s'", reg->name);
3192 char *value = buf_to_hex_str(reg->value, reg->size);
3193 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3202 return ERROR_COMMAND_SYNTAX_ERROR;
3205 command_print(CMD, "register %s not found in current target", CMD_ARGV[0]);
3209 COMMAND_HANDLER(handle_poll_command)
3211 int retval = ERROR_OK;
3212 struct target *target = get_current_target(CMD_CTX);
3214 if (CMD_ARGC == 0) {
3215 command_print(CMD, "background polling: %s",
3216 jtag_poll_get_enabled() ? "on" : "off");
3217 command_print(CMD, "TAP: %s (%s)",
3218 target->tap->dotted_name,
3219 target->tap->enabled ? "enabled" : "disabled");
3220 if (!target->tap->enabled)
3222 retval = target_poll(target);
3223 if (retval != ERROR_OK)
3225 retval = target_arch_state(target);
3226 if (retval != ERROR_OK)
3228 } else if (CMD_ARGC == 1) {
3230 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
3231 jtag_poll_set_enabled(enable);
3233 return ERROR_COMMAND_SYNTAX_ERROR;
3238 COMMAND_HANDLER(handle_wait_halt_command)
3241 return ERROR_COMMAND_SYNTAX_ERROR;
3243 unsigned ms = DEFAULT_HALT_TIMEOUT;
3244 if (1 == CMD_ARGC) {
3245 int retval = parse_uint(CMD_ARGV[0], &ms);
3246 if (retval != ERROR_OK)
3247 return ERROR_COMMAND_SYNTAX_ERROR;
3250 struct target *target = get_current_target(CMD_CTX);
3251 return target_wait_state(target, TARGET_HALTED, ms);
3254 /* wait for target state to change. The trick here is to have a low
3255 * latency for short waits and not to suck up all the CPU time
3258 * After 500ms, keep_alive() is invoked
3260 int target_wait_state(struct target *target, enum target_state state, int ms)
3263 int64_t then = 0, cur;
3267 retval = target_poll(target);
3268 if (retval != ERROR_OK)
3270 if (target->state == state)
3275 then = timeval_ms();
3276 LOG_DEBUG("waiting for target %s...",
3277 jim_nvp_value2name_simple(nvp_target_state, state)->name);
3283 if ((cur-then) > ms) {
3284 LOG_ERROR("timed out while waiting for target %s",
3285 jim_nvp_value2name_simple(nvp_target_state, state)->name);
3293 COMMAND_HANDLER(handle_halt_command)
3297 struct target *target = get_current_target(CMD_CTX);
3299 target->verbose_halt_msg = true;
3301 int retval = target_halt(target);
3302 if (retval != ERROR_OK)
3305 if (CMD_ARGC == 1) {
3306 unsigned wait_local;
3307 retval = parse_uint(CMD_ARGV[0], &wait_local);
3308 if (retval != ERROR_OK)
3309 return ERROR_COMMAND_SYNTAX_ERROR;
3314 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
3317 COMMAND_HANDLER(handle_soft_reset_halt_command)
3319 struct target *target = get_current_target(CMD_CTX);
3321 LOG_USER("requesting target halt and executing a soft reset");
3323 target_soft_reset_halt(target);
3328 COMMAND_HANDLER(handle_reset_command)
3331 return ERROR_COMMAND_SYNTAX_ERROR;
3333 enum target_reset_mode reset_mode = RESET_RUN;
3334 if (CMD_ARGC == 1) {
3335 const struct jim_nvp *n;
3336 n = jim_nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
3337 if ((!n->name) || (n->value == RESET_UNKNOWN))
3338 return ERROR_COMMAND_SYNTAX_ERROR;
3339 reset_mode = n->value;
3342 /* reset *all* targets */
3343 return target_process_reset(CMD, reset_mode);
3347 COMMAND_HANDLER(handle_resume_command)
3351 return ERROR_COMMAND_SYNTAX_ERROR;
3353 struct target *target = get_current_target(CMD_CTX);
3355 /* with no CMD_ARGV, resume from current pc, addr = 0,
3356 * with one arguments, addr = CMD_ARGV[0],
3357 * handle breakpoints, not debugging */
3358 target_addr_t addr = 0;
3359 if (CMD_ARGC == 1) {
3360 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3364 return target_resume(target, current, addr, 1, 0);
3367 COMMAND_HANDLER(handle_step_command)
3370 return ERROR_COMMAND_SYNTAX_ERROR;
3374 /* with no CMD_ARGV, step from current pc, addr = 0,
3375 * with one argument addr = CMD_ARGV[0],
3376 * handle breakpoints, debugging */
3377 target_addr_t addr = 0;
3379 if (CMD_ARGC == 1) {
3380 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3384 struct target *target = get_current_target(CMD_CTX);
3386 return target_step(target, current_pc, addr, 1);
3389 void target_handle_md_output(struct command_invocation *cmd,
3390 struct target *target, target_addr_t address, unsigned size,
3391 unsigned count, const uint8_t *buffer)
3393 const unsigned line_bytecnt = 32;
3394 unsigned line_modulo = line_bytecnt / size;
3396 char output[line_bytecnt * 4 + 1];
3397 unsigned output_len = 0;
3399 const char *value_fmt;
3402 value_fmt = "%16.16"PRIx64" ";
3405 value_fmt = "%8.8"PRIx64" ";
3408 value_fmt = "%4.4"PRIx64" ";
3411 value_fmt = "%2.2"PRIx64" ";
3414 /* "can't happen", caller checked */
3415 LOG_ERROR("invalid memory read size: %u", size);
3419 for (unsigned i = 0; i < count; i++) {
3420 if (i % line_modulo == 0) {
3421 output_len += snprintf(output + output_len,
3422 sizeof(output) - output_len,
3423 TARGET_ADDR_FMT ": ",
3424 (address + (i * size)));
3428 const uint8_t *value_ptr = buffer + i * size;
3431 value = target_buffer_get_u64(target, value_ptr);
3434 value = target_buffer_get_u32(target, value_ptr);
3437 value = target_buffer_get_u16(target, value_ptr);
3442 output_len += snprintf(output + output_len,
3443 sizeof(output) - output_len,
3446 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
3447 command_print(cmd, "%s", output);
3453 COMMAND_HANDLER(handle_md_command)
3456 return ERROR_COMMAND_SYNTAX_ERROR;
3459 switch (CMD_NAME[2]) {
3473 return ERROR_COMMAND_SYNTAX_ERROR;
3476 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3477 int (*fn)(struct target *target,
3478 target_addr_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
3482 fn = target_read_phys_memory;
3484 fn = target_read_memory;
3485 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
3486 return ERROR_COMMAND_SYNTAX_ERROR;
3488 target_addr_t address;
3489 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3493 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3495 uint8_t *buffer = calloc(count, size);
3497 LOG_ERROR("Failed to allocate md read buffer");
3501 struct target *target = get_current_target(CMD_CTX);
3502 int retval = fn(target, address, size, count, buffer);
3503 if (retval == ERROR_OK)
3504 target_handle_md_output(CMD, target, address, size, count, buffer);
3511 typedef int (*target_write_fn)(struct target *target,
3512 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3514 static int target_fill_mem(struct target *target,
3515 target_addr_t address,
3523 /* We have to write in reasonably large chunks to be able
3524 * to fill large memory areas with any sane speed */
3525 const unsigned chunk_size = 16384;
3526 uint8_t *target_buf = malloc(chunk_size * data_size);
3528 LOG_ERROR("Out of memory");
3532 for (unsigned i = 0; i < chunk_size; i++) {
3533 switch (data_size) {
3535 target_buffer_set_u64(target, target_buf + i * data_size, b);
3538 target_buffer_set_u32(target, target_buf + i * data_size, b);
3541 target_buffer_set_u16(target, target_buf + i * data_size, b);
3544 target_buffer_set_u8(target, target_buf + i * data_size, b);
3551 int retval = ERROR_OK;
3553 for (unsigned x = 0; x < c; x += chunk_size) {
3556 if (current > chunk_size)
3557 current = chunk_size;
3558 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3559 if (retval != ERROR_OK)
3561 /* avoid GDB timeouts */
3570 COMMAND_HANDLER(handle_mw_command)
3573 return ERROR_COMMAND_SYNTAX_ERROR;
3574 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3579 fn = target_write_phys_memory;
3581 fn = target_write_memory;
3582 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3583 return ERROR_COMMAND_SYNTAX_ERROR;
3585 target_addr_t address;
3586 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3589 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[1], value);
3593 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3595 struct target *target = get_current_target(CMD_CTX);
3597 switch (CMD_NAME[2]) {
3611 return ERROR_COMMAND_SYNTAX_ERROR;
3614 return target_fill_mem(target, address, fn, wordsize, value, count);
3617 static COMMAND_HELPER(parse_load_image_command, struct image *image,
3618 target_addr_t *min_address, target_addr_t *max_address)
3620 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3621 return ERROR_COMMAND_SYNTAX_ERROR;
3623 /* a base address isn't always necessary,
3624 * default to 0x0 (i.e. don't relocate) */
3625 if (CMD_ARGC >= 2) {
3627 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3628 image->base_address = addr;
3629 image->base_address_set = true;
3631 image->base_address_set = false;
3633 image->start_address_set = false;
3636 COMMAND_PARSE_ADDRESS(CMD_ARGV[3], *min_address);
3637 if (CMD_ARGC == 5) {
3638 COMMAND_PARSE_ADDRESS(CMD_ARGV[4], *max_address);
3639 /* use size (given) to find max (required) */
3640 *max_address += *min_address;
3643 if (*min_address > *max_address)
3644 return ERROR_COMMAND_SYNTAX_ERROR;
3649 COMMAND_HANDLER(handle_load_image_command)
3653 uint32_t image_size;
3654 target_addr_t min_address = 0;
3655 target_addr_t max_address = -1;
3658 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
3659 &image, &min_address, &max_address);
3660 if (retval != ERROR_OK)
3663 struct target *target = get_current_target(CMD_CTX);
3665 struct duration bench;
3666 duration_start(&bench);
3668 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3673 for (unsigned int i = 0; i < image.num_sections; i++) {
3674 buffer = malloc(image.sections[i].size);
3677 "error allocating buffer for section (%d bytes)",
3678 (int)(image.sections[i].size));
3679 retval = ERROR_FAIL;
3683 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3684 if (retval != ERROR_OK) {
3689 uint32_t offset = 0;
3690 uint32_t length = buf_cnt;
3692 /* DANGER!!! beware of unsigned comparison here!!! */
3694 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3695 (image.sections[i].base_address < max_address)) {
3697 if (image.sections[i].base_address < min_address) {
3698 /* clip addresses below */
3699 offset += min_address-image.sections[i].base_address;
3703 if (image.sections[i].base_address + buf_cnt > max_address)
3704 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3706 retval = target_write_buffer(target,
3707 image.sections[i].base_address + offset, length, buffer + offset);
3708 if (retval != ERROR_OK) {
3712 image_size += length;
3713 command_print(CMD, "%u bytes written at address " TARGET_ADDR_FMT "",
3714 (unsigned int)length,
3715 image.sections[i].base_address + offset);
3721 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3722 command_print(CMD, "downloaded %" PRIu32 " bytes "
3723 "in %fs (%0.3f KiB/s)", image_size,
3724 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3727 image_close(&image);
3733 COMMAND_HANDLER(handle_dump_image_command)
3735 struct fileio *fileio;
3737 int retval, retvaltemp;
3738 target_addr_t address, size;
3739 struct duration bench;
3740 struct target *target = get_current_target(CMD_CTX);
3743 return ERROR_COMMAND_SYNTAX_ERROR;
3745 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], address);
3746 COMMAND_PARSE_ADDRESS(CMD_ARGV[2], size);
3748 uint32_t buf_size = (size > 4096) ? 4096 : size;
3749 buffer = malloc(buf_size);
3753 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3754 if (retval != ERROR_OK) {
3759 duration_start(&bench);
3762 size_t size_written;
3763 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3764 retval = target_read_buffer(target, address, this_run_size, buffer);
3765 if (retval != ERROR_OK)
3768 retval = fileio_write(fileio, this_run_size, buffer, &size_written);
3769 if (retval != ERROR_OK)
3772 size -= this_run_size;
3773 address += this_run_size;
3778 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3780 retval = fileio_size(fileio, &filesize);
3781 if (retval != ERROR_OK)
3784 "dumped %zu bytes in %fs (%0.3f KiB/s)", filesize,
3785 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3788 retvaltemp = fileio_close(fileio);
3789 if (retvaltemp != ERROR_OK)
3798 IMAGE_CHECKSUM_ONLY = 2
3801 static COMMAND_HELPER(handle_verify_image_command_internal, enum verify_mode verify)
3805 uint32_t image_size;
3807 uint32_t checksum = 0;
3808 uint32_t mem_checksum = 0;
3812 struct target *target = get_current_target(CMD_CTX);
3815 return ERROR_COMMAND_SYNTAX_ERROR;
3818 LOG_ERROR("no target selected");
3822 struct duration bench;
3823 duration_start(&bench);
3825 if (CMD_ARGC >= 2) {
3827 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3828 image.base_address = addr;
3829 image.base_address_set = true;
3831 image.base_address_set = false;
3832 image.base_address = 0x0;
3835 image.start_address_set = false;
3837 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3838 if (retval != ERROR_OK)
3844 for (unsigned int i = 0; i < image.num_sections; i++) {
3845 buffer = malloc(image.sections[i].size);
3848 "error allocating buffer for section (%" PRIu32 " bytes)",
3849 image.sections[i].size);
3852 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3853 if (retval != ERROR_OK) {
3858 if (verify >= IMAGE_VERIFY) {
3859 /* calculate checksum of image */
3860 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3861 if (retval != ERROR_OK) {
3866 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3867 if (retval != ERROR_OK) {
3871 if ((checksum != mem_checksum) && (verify == IMAGE_CHECKSUM_ONLY)) {
3872 LOG_ERROR("checksum mismatch");
3874 retval = ERROR_FAIL;
3877 if (checksum != mem_checksum) {
3878 /* failed crc checksum, fall back to a binary compare */
3882 LOG_ERROR("checksum mismatch - attempting binary compare");
3884 data = malloc(buf_cnt);
3886 retval = target_read_buffer(target, image.sections[i].base_address, buf_cnt, data);
3887 if (retval == ERROR_OK) {
3889 for (t = 0; t < buf_cnt; t++) {
3890 if (data[t] != buffer[t]) {
3892 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3894 (unsigned)(t + image.sections[i].base_address),
3897 if (diffs++ >= 127) {
3898 command_print(CMD, "More than 128 errors, the rest are not printed.");
3910 command_print(CMD, "address " TARGET_ADDR_FMT " length 0x%08zx",
3911 image.sections[i].base_address,
3916 image_size += buf_cnt;
3919 command_print(CMD, "No more differences found.");
3922 retval = ERROR_FAIL;
3923 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3924 command_print(CMD, "verified %" PRIu32 " bytes "
3925 "in %fs (%0.3f KiB/s)", image_size,
3926 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3929 image_close(&image);
3934 COMMAND_HANDLER(handle_verify_image_checksum_command)
3936 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_CHECKSUM_ONLY);
3939 COMMAND_HANDLER(handle_verify_image_command)
3941 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_VERIFY);
3944 COMMAND_HANDLER(handle_test_image_command)
3946 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_TEST);
3949 static int handle_bp_command_list(struct command_invocation *cmd)
3951 struct target *target = get_current_target(cmd->ctx);
3952 struct breakpoint *breakpoint = target->breakpoints;
3953 while (breakpoint) {
3954 if (breakpoint->type == BKPT_SOFT) {
3955 char *buf = buf_to_hex_str(breakpoint->orig_instr,
3956 breakpoint->length);
3957 command_print(cmd, "IVA breakpoint: " TARGET_ADDR_FMT ", 0x%x, %i, 0x%s",
3958 breakpoint->address,
3960 breakpoint->set, buf);
3963 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3964 command_print(cmd, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3966 breakpoint->length, breakpoint->set);
3967 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3968 command_print(cmd, "Hybrid breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3969 breakpoint->address,
3970 breakpoint->length, breakpoint->set);
3971 command_print(cmd, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3974 command_print(cmd, "Breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3975 breakpoint->address,
3976 breakpoint->length, breakpoint->set);
3979 breakpoint = breakpoint->next;
3984 static int handle_bp_command_set(struct command_invocation *cmd,
3985 target_addr_t addr, uint32_t asid, uint32_t length, int hw)
3987 struct target *target = get_current_target(cmd->ctx);
3991 retval = breakpoint_add(target, addr, length, hw);
3992 /* error is always logged in breakpoint_add(), do not print it again */
3993 if (retval == ERROR_OK)
3994 command_print(cmd, "breakpoint set at " TARGET_ADDR_FMT "", addr);
3996 } else if (addr == 0) {
3997 if (!target->type->add_context_breakpoint) {
3998 LOG_ERROR("Context breakpoint not available");
3999 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
4001 retval = context_breakpoint_add(target, asid, length, hw);
4002 /* error is always logged in context_breakpoint_add(), do not print it again */
4003 if (retval == ERROR_OK)
4004 command_print(cmd, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
4007 if (!target->type->add_hybrid_breakpoint) {
4008 LOG_ERROR("Hybrid breakpoint not available");
4009 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
4011 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
4012 /* error is always logged in hybrid_breakpoint_add(), do not print it again */
4013 if (retval == ERROR_OK)
4014 command_print(cmd, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
4019 COMMAND_HANDLER(handle_bp_command)
4028 return handle_bp_command_list(CMD);
4032 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4033 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4034 return handle_bp_command_set(CMD, addr, asid, length, hw);
4037 if (strcmp(CMD_ARGV[2], "hw") == 0) {
4039 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4040 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4042 return handle_bp_command_set(CMD, addr, asid, length, hw);
4043 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
4045 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
4046 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4048 return handle_bp_command_set(CMD, addr, asid, length, hw);
4053 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4054 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
4055 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
4056 return handle_bp_command_set(CMD, addr, asid, length, hw);
4059 return ERROR_COMMAND_SYNTAX_ERROR;
4063 COMMAND_HANDLER(handle_rbp_command)
4066 return ERROR_COMMAND_SYNTAX_ERROR;
4068 struct target *target = get_current_target(CMD_CTX);
4070 if (!strcmp(CMD_ARGV[0], "all")) {
4071 breakpoint_remove_all(target);
4074 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4076 breakpoint_remove(target, addr);
4082 COMMAND_HANDLER(handle_wp_command)
4084 struct target *target = get_current_target(CMD_CTX);
4086 if (CMD_ARGC == 0) {
4087 struct watchpoint *watchpoint = target->watchpoints;
4089 while (watchpoint) {
4090 command_print(CMD, "address: " TARGET_ADDR_FMT
4091 ", len: 0x%8.8" PRIx32
4092 ", r/w/a: %i, value: 0x%8.8" PRIx32
4093 ", mask: 0x%8.8" PRIx32,
4094 watchpoint->address,
4096 (int)watchpoint->rw,
4099 watchpoint = watchpoint->next;
4104 enum watchpoint_rw type = WPT_ACCESS;
4105 target_addr_t addr = 0;
4106 uint32_t length = 0;
4107 uint32_t data_value = 0x0;
4108 uint32_t data_mask = 0xffffffff;
4112 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
4115 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
4118 switch (CMD_ARGV[2][0]) {
4129 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
4130 return ERROR_COMMAND_SYNTAX_ERROR;
4134 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4135 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4139 return ERROR_COMMAND_SYNTAX_ERROR;
4142 int retval = watchpoint_add(target, addr, length, type,
4143 data_value, data_mask);
4144 if (retval != ERROR_OK)
4145 LOG_ERROR("Failure setting watchpoints");
4150 COMMAND_HANDLER(handle_rwp_command)
4153 return ERROR_COMMAND_SYNTAX_ERROR;
4156 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4158 struct target *target = get_current_target(CMD_CTX);
4159 watchpoint_remove(target, addr);
4165 * Translate a virtual address to a physical address.
4167 * The low-level target implementation must have logged a detailed error
4168 * which is forwarded to telnet/GDB session.
4170 COMMAND_HANDLER(handle_virt2phys_command)
4173 return ERROR_COMMAND_SYNTAX_ERROR;
4176 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], va);
4179 struct target *target = get_current_target(CMD_CTX);
4180 int retval = target->type->virt2phys(target, va, &pa);
4181 if (retval == ERROR_OK)
4182 command_print(CMD, "Physical address " TARGET_ADDR_FMT "", pa);
4187 static void write_data(FILE *f, const void *data, size_t len)
4189 size_t written = fwrite(data, 1, len, f);
4191 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
4194 static void write_long(FILE *f, int l, struct target *target)
4198 target_buffer_set_u32(target, val, l);
4199 write_data(f, val, 4);
4202 static void write_string(FILE *f, char *s)
4204 write_data(f, s, strlen(s));
4207 typedef unsigned char UNIT[2]; /* unit of profiling */
4209 /* Dump a gmon.out histogram file. */
4210 static void write_gmon(uint32_t *samples, uint32_t sample_num, const char *filename, bool with_range,
4211 uint32_t start_address, uint32_t end_address, struct target *target, uint32_t duration_ms)
4214 FILE *f = fopen(filename, "w");
4217 write_string(f, "gmon");
4218 write_long(f, 0x00000001, target); /* Version */
4219 write_long(f, 0, target); /* padding */
4220 write_long(f, 0, target); /* padding */
4221 write_long(f, 0, target); /* padding */
4223 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
4224 write_data(f, &zero, 1);
4226 /* figure out bucket size */
4230 min = start_address;
4235 for (i = 0; i < sample_num; i++) {
4236 if (min > samples[i])
4238 if (max < samples[i])
4242 /* max should be (largest sample + 1)
4243 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
4247 int address_space = max - min;
4248 assert(address_space >= 2);
4250 /* FIXME: What is the reasonable number of buckets?
4251 * The profiling result will be more accurate if there are enough buckets. */
4252 static const uint32_t max_buckets = 128 * 1024; /* maximum buckets. */
4253 uint32_t num_buckets = address_space / sizeof(UNIT);
4254 if (num_buckets > max_buckets)
4255 num_buckets = max_buckets;
4256 int *buckets = malloc(sizeof(int) * num_buckets);
4261 memset(buckets, 0, sizeof(int) * num_buckets);
4262 for (i = 0; i < sample_num; i++) {
4263 uint32_t address = samples[i];
4265 if ((address < min) || (max <= address))
4268 long long a = address - min;
4269 long long b = num_buckets;
4270 long long c = address_space;
4271 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
4275 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
4276 write_long(f, min, target); /* low_pc */
4277 write_long(f, max, target); /* high_pc */
4278 write_long(f, num_buckets, target); /* # of buckets */
4279 float sample_rate = sample_num / (duration_ms / 1000.0);
4280 write_long(f, sample_rate, target);
4281 write_string(f, "seconds");
4282 for (i = 0; i < (15-strlen("seconds")); i++)
4283 write_data(f, &zero, 1);
4284 write_string(f, "s");
4286 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
4288 char *data = malloc(2 * num_buckets);
4290 for (i = 0; i < num_buckets; i++) {
4295 data[i * 2] = val&0xff;
4296 data[i * 2 + 1] = (val >> 8) & 0xff;
4299 write_data(f, data, num_buckets * 2);
4307 /* profiling samples the CPU PC as quickly as OpenOCD is able,
4308 * which will be used as a random sampling of PC */
4309 COMMAND_HANDLER(handle_profile_command)
4311 struct target *target = get_current_target(CMD_CTX);
4313 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
4314 return ERROR_COMMAND_SYNTAX_ERROR;
4316 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
4318 uint32_t num_of_samples;
4319 int retval = ERROR_OK;
4320 bool halted_before_profiling = target->state == TARGET_HALTED;
4322 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
4324 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
4326 LOG_ERROR("No memory to store samples.");
4330 uint64_t timestart_ms = timeval_ms();
4332 * Some cores let us sample the PC without the
4333 * annoying halt/resume step; for example, ARMv7 PCSR.
4334 * Provide a way to use that more efficient mechanism.
4336 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
4337 &num_of_samples, offset);
4338 if (retval != ERROR_OK) {
4342 uint32_t duration_ms = timeval_ms() - timestart_ms;
4344 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
4346 retval = target_poll(target);
4347 if (retval != ERROR_OK) {
4352 if (target->state == TARGET_RUNNING && halted_before_profiling) {
4353 /* The target was halted before we started and is running now. Halt it,
4354 * for consistency. */
4355 retval = target_halt(target);
4356 if (retval != ERROR_OK) {
4360 } else if (target->state == TARGET_HALTED && !halted_before_profiling) {
4361 /* The target was running before we started and is halted now. Resume
4362 * it, for consistency. */
4363 retval = target_resume(target, 1, 0, 0, 0);
4364 if (retval != ERROR_OK) {
4370 retval = target_poll(target);
4371 if (retval != ERROR_OK) {
4376 uint32_t start_address = 0;
4377 uint32_t end_address = 0;
4378 bool with_range = false;
4379 if (CMD_ARGC == 4) {
4381 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
4382 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
4385 write_gmon(samples, num_of_samples, CMD_ARGV[1],
4386 with_range, start_address, end_address, target, duration_ms);
4387 command_print(CMD, "Wrote %s", CMD_ARGV[1]);
4393 static int new_u64_array_element(Jim_Interp *interp, const char *varname, int idx, uint64_t val)
4396 Jim_Obj *obj_name, *obj_val;
4399 namebuf = alloc_printf("%s(%d)", varname, idx);
4403 obj_name = Jim_NewStringObj(interp, namebuf, -1);
4404 jim_wide wide_val = val;
4405 obj_val = Jim_NewWideObj(interp, wide_val);
4406 if (!obj_name || !obj_val) {
4411 Jim_IncrRefCount(obj_name);
4412 Jim_IncrRefCount(obj_val);
4413 result = Jim_SetVariable(interp, obj_name, obj_val);
4414 Jim_DecrRefCount(interp, obj_name);
4415 Jim_DecrRefCount(interp, obj_val);
4417 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
4421 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4423 struct command_context *context;
4424 struct target *target;
4426 context = current_command_context(interp);
4429 target = get_current_target(context);
4431 LOG_ERROR("mem2array: no current target");
4435 return target_mem2array(interp, target, argc - 1, argv + 1);
4438 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
4442 /* argv[0] = name of array to receive the data
4443 * argv[1] = desired element width in bits
4444 * argv[2] = memory address
4445 * argv[3] = count of times to read
4446 * argv[4] = optional "phys"
4448 if (argc < 4 || argc > 5) {
4449 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4453 /* Arg 0: Name of the array variable */
4454 const char *varname = Jim_GetString(argv[0], NULL);
4456 /* Arg 1: Bit width of one element */
4458 e = Jim_GetLong(interp, argv[1], &l);
4461 const unsigned int width_bits = l;
4463 if (width_bits != 8 &&
4467 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4468 Jim_AppendStrings(interp, Jim_GetResult(interp),
4469 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4472 const unsigned int width = width_bits / 8;
4474 /* Arg 2: Memory address */
4476 e = Jim_GetWide(interp, argv[2], &wide_addr);
4479 target_addr_t addr = (target_addr_t)wide_addr;
4481 /* Arg 3: Number of elements to read */
4482 e = Jim_GetLong(interp, argv[3], &l);
4488 bool is_phys = false;
4491 const char *phys = Jim_GetString(argv[4], &str_len);
4492 if (!strncmp(phys, "phys", str_len))
4498 /* Argument checks */
4500 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4501 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
4504 if ((addr + (len * width)) < addr) {
4505 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4506 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
4510 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4511 Jim_AppendStrings(interp, Jim_GetResult(interp),
4512 "mem2array: too large read request, exceeds 64K items", NULL);
4517 ((width == 2) && ((addr & 1) == 0)) ||
4518 ((width == 4) && ((addr & 3) == 0)) ||
4519 ((width == 8) && ((addr & 7) == 0))) {
4520 /* alignment correct */
4523 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4524 sprintf(buf, "mem2array address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4527 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4536 const size_t buffersize = 4096;
4537 uint8_t *buffer = malloc(buffersize);
4544 /* Slurp... in buffer size chunks */
4545 const unsigned int max_chunk_len = buffersize / width;
4546 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4550 retval = target_read_phys_memory(target, addr, width, chunk_len, buffer);
4552 retval = target_read_memory(target, addr, width, chunk_len, buffer);
4553 if (retval != ERROR_OK) {
4555 LOG_ERROR("mem2array: Read @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4559 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4560 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
4564 for (size_t i = 0; i < chunk_len ; i++, idx++) {
4568 v = target_buffer_get_u64(target, &buffer[i*width]);
4571 v = target_buffer_get_u32(target, &buffer[i*width]);
4574 v = target_buffer_get_u16(target, &buffer[i*width]);
4577 v = buffer[i] & 0x0ff;
4580 new_u64_array_element(interp, varname, idx, v);
4583 addr += chunk_len * width;
4589 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4594 static int get_u64_array_element(Jim_Interp *interp, const char *varname, size_t idx, uint64_t *val)
4596 char *namebuf = alloc_printf("%s(%zu)", varname, idx);
4600 Jim_Obj *obj_name = Jim_NewStringObj(interp, namebuf, -1);
4606 Jim_IncrRefCount(obj_name);
4607 Jim_Obj *obj_val = Jim_GetVariable(interp, obj_name, JIM_ERRMSG);
4608 Jim_DecrRefCount(interp, obj_name);
4614 int result = Jim_GetWide(interp, obj_val, &wide_val);
4619 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4621 struct command_context *context;
4622 struct target *target;
4624 context = current_command_context(interp);
4627 target = get_current_target(context);
4629 LOG_ERROR("array2mem: no current target");
4633 return target_array2mem(interp, target, argc-1, argv + 1);
4636 static int target_array2mem(Jim_Interp *interp, struct target *target,
4637 int argc, Jim_Obj *const *argv)
4641 /* argv[0] = name of array from which to read the data
4642 * argv[1] = desired element width in bits
4643 * argv[2] = memory address
4644 * argv[3] = number of elements to write
4645 * argv[4] = optional "phys"
4647 if (argc < 4 || argc > 5) {
4648 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4652 /* Arg 0: Name of the array variable */
4653 const char *varname = Jim_GetString(argv[0], NULL);
4655 /* Arg 1: Bit width of one element */
4657 e = Jim_GetLong(interp, argv[1], &l);
4660 const unsigned int width_bits = l;
4662 if (width_bits != 8 &&
4666 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4667 Jim_AppendStrings(interp, Jim_GetResult(interp),
4668 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4671 const unsigned int width = width_bits / 8;
4673 /* Arg 2: Memory address */
4675 e = Jim_GetWide(interp, argv[2], &wide_addr);
4678 target_addr_t addr = (target_addr_t)wide_addr;
4680 /* Arg 3: Number of elements to write */
4681 e = Jim_GetLong(interp, argv[3], &l);
4687 bool is_phys = false;
4690 const char *phys = Jim_GetString(argv[4], &str_len);
4691 if (!strncmp(phys, "phys", str_len))
4697 /* Argument checks */
4699 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4700 Jim_AppendStrings(interp, Jim_GetResult(interp),
4701 "array2mem: zero width read?", NULL);
4705 if ((addr + (len * width)) < addr) {
4706 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4707 Jim_AppendStrings(interp, Jim_GetResult(interp),
4708 "array2mem: addr + len - wraps to zero?", NULL);
4713 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4714 Jim_AppendStrings(interp, Jim_GetResult(interp),
4715 "array2mem: too large memory write request, exceeds 64K items", NULL);
4720 ((width == 2) && ((addr & 1) == 0)) ||
4721 ((width == 4) && ((addr & 3) == 0)) ||
4722 ((width == 8) && ((addr & 7) == 0))) {
4723 /* alignment correct */
4726 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4727 sprintf(buf, "array2mem address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4730 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4739 const size_t buffersize = 4096;
4740 uint8_t *buffer = malloc(buffersize);
4748 /* Slurp... in buffer size chunks */
4749 const unsigned int max_chunk_len = buffersize / width;
4751 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4753 /* Fill the buffer */
4754 for (size_t i = 0; i < chunk_len; i++, idx++) {
4756 if (get_u64_array_element(interp, varname, idx, &v) != JIM_OK) {
4762 target_buffer_set_u64(target, &buffer[i * width], v);
4765 target_buffer_set_u32(target, &buffer[i * width], v);
4768 target_buffer_set_u16(target, &buffer[i * width], v);
4771 buffer[i] = v & 0x0ff;
4777 /* Write the buffer to memory */
4780 retval = target_write_phys_memory(target, addr, width, chunk_len, buffer);
4782 retval = target_write_memory(target, addr, width, chunk_len, buffer);
4783 if (retval != ERROR_OK) {
4785 LOG_ERROR("array2mem: Write @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4789 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4790 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4794 addr += chunk_len * width;
4799 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4804 /* FIX? should we propagate errors here rather than printing them
4807 void target_handle_event(struct target *target, enum target_event e)
4809 struct target_event_action *teap;
4812 for (teap = target->event_action; teap; teap = teap->next) {
4813 if (teap->event == e) {
4814 LOG_DEBUG("target(%d): %s (%s) event: %d (%s) action: %s",
4815 target->target_number,
4816 target_name(target),
4817 target_type_name(target),
4819 target_event_name(e),
4820 Jim_GetString(teap->body, NULL));
4822 /* Override current target by the target an event
4823 * is issued from (lot of scripts need it).
4824 * Return back to previous override as soon
4825 * as the handler processing is done */
4826 struct command_context *cmd_ctx = current_command_context(teap->interp);
4827 struct target *saved_target_override = cmd_ctx->current_target_override;
4828 cmd_ctx->current_target_override = target;
4830 retval = Jim_EvalObj(teap->interp, teap->body);
4832 cmd_ctx->current_target_override = saved_target_override;
4834 if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
4837 if (retval == JIM_RETURN)
4838 retval = teap->interp->returnCode;
4840 if (retval != JIM_OK) {
4841 Jim_MakeErrorMessage(teap->interp);
4842 LOG_USER("Error executing event %s on target %s:\n%s",
4843 target_event_name(e),
4844 target_name(target),
4845 Jim_GetString(Jim_GetResult(teap->interp), NULL));
4846 /* clean both error code and stacktrace before return */
4847 Jim_Eval(teap->interp, "error \"\" \"\"");
4854 * Returns true only if the target has a handler for the specified event.
4856 bool target_has_event_action(struct target *target, enum target_event event)
4858 struct target_event_action *teap;
4860 for (teap = target->event_action; teap; teap = teap->next) {
4861 if (teap->event == event)
4867 enum target_cfg_param {
4870 TCFG_WORK_AREA_VIRT,
4871 TCFG_WORK_AREA_PHYS,
4872 TCFG_WORK_AREA_SIZE,
4873 TCFG_WORK_AREA_BACKUP,
4876 TCFG_CHAIN_POSITION,
4881 TCFG_GDB_MAX_CONNECTIONS,
4884 static struct jim_nvp nvp_config_opts[] = {
4885 { .name = "-type", .value = TCFG_TYPE },
4886 { .name = "-event", .value = TCFG_EVENT },
4887 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4888 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4889 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4890 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4891 { .name = "-endian", .value = TCFG_ENDIAN },
4892 { .name = "-coreid", .value = TCFG_COREID },
4893 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4894 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4895 { .name = "-rtos", .value = TCFG_RTOS },
4896 { .name = "-defer-examine", .value = TCFG_DEFER_EXAMINE },
4897 { .name = "-gdb-port", .value = TCFG_GDB_PORT },
4898 { .name = "-gdb-max-connections", .value = TCFG_GDB_MAX_CONNECTIONS },
4899 { .name = NULL, .value = -1 }
4902 static int target_configure(struct jim_getopt_info *goi, struct target *target)
4909 /* parse config or cget options ... */
4910 while (goi->argc > 0) {
4911 Jim_SetEmptyResult(goi->interp);
4912 /* jim_getopt_debug(goi); */
4914 if (target->type->target_jim_configure) {
4915 /* target defines a configure function */
4916 /* target gets first dibs on parameters */
4917 e = (*(target->type->target_jim_configure))(target, goi);
4926 /* otherwise we 'continue' below */
4928 e = jim_getopt_nvp(goi, nvp_config_opts, &n);
4930 jim_getopt_nvp_unknown(goi, nvp_config_opts, 0);
4936 if (goi->isconfigure) {
4937 Jim_SetResultFormatted(goi->interp,
4938 "not settable: %s", n->name);
4942 if (goi->argc != 0) {
4943 Jim_WrongNumArgs(goi->interp,
4944 goi->argc, goi->argv,
4949 Jim_SetResultString(goi->interp,
4950 target_type_name(target), -1);
4954 if (goi->argc == 0) {
4955 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4959 e = jim_getopt_nvp(goi, nvp_target_event, &n);
4961 jim_getopt_nvp_unknown(goi, nvp_target_event, 1);
4965 if (goi->isconfigure) {
4966 if (goi->argc != 1) {
4967 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4971 if (goi->argc != 0) {
4972 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4978 struct target_event_action *teap;
4980 teap = target->event_action;
4981 /* replace existing? */
4983 if (teap->event == (enum target_event)n->value)
4988 if (goi->isconfigure) {
4989 /* START_DEPRECATED_TPIU */
4990 if (n->value == TARGET_EVENT_TRACE_CONFIG)
4991 LOG_INFO("DEPRECATED target event %s; use TPIU events {pre,post}-{enable,disable}", n->name);
4992 /* END_DEPRECATED_TPIU */
4994 bool replace = true;
4997 teap = calloc(1, sizeof(*teap));
5000 teap->event = n->value;
5001 teap->interp = goi->interp;
5002 jim_getopt_obj(goi, &o);
5004 Jim_DecrRefCount(teap->interp, teap->body);
5005 teap->body = Jim_DuplicateObj(goi->interp, o);
5008 * Tcl/TK - "tk events" have a nice feature.
5009 * See the "BIND" command.
5010 * We should support that here.
5011 * You can specify %X and %Y in the event code.
5012 * The idea is: %T - target name.
5013 * The idea is: %N - target number
5014 * The idea is: %E - event name.
5016 Jim_IncrRefCount(teap->body);
5019 /* add to head of event list */
5020 teap->next = target->event_action;
5021 target->event_action = teap;
5023 Jim_SetEmptyResult(goi->interp);
5027 Jim_SetEmptyResult(goi->interp);
5029 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
5035 case TCFG_WORK_AREA_VIRT:
5036 if (goi->isconfigure) {
5037 target_free_all_working_areas(target);
5038 e = jim_getopt_wide(goi, &w);
5041 target->working_area_virt = w;
5042 target->working_area_virt_spec = true;
5047 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
5051 case TCFG_WORK_AREA_PHYS:
5052 if (goi->isconfigure) {
5053 target_free_all_working_areas(target);
5054 e = jim_getopt_wide(goi, &w);
5057 target->working_area_phys = w;
5058 target->working_area_phys_spec = true;
5063 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
5067 case TCFG_WORK_AREA_SIZE:
5068 if (goi->isconfigure) {
5069 target_free_all_working_areas(target);
5070 e = jim_getopt_wide(goi, &w);
5073 target->working_area_size = w;
5078 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
5082 case TCFG_WORK_AREA_BACKUP:
5083 if (goi->isconfigure) {
5084 target_free_all_working_areas(target);
5085 e = jim_getopt_wide(goi, &w);
5088 /* make this exactly 1 or 0 */
5089 target->backup_working_area = (!!w);
5094 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
5095 /* loop for more e*/
5100 if (goi->isconfigure) {
5101 e = jim_getopt_nvp(goi, nvp_target_endian, &n);
5103 jim_getopt_nvp_unknown(goi, nvp_target_endian, 1);
5106 target->endianness = n->value;
5111 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5113 target->endianness = TARGET_LITTLE_ENDIAN;
5114 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5116 Jim_SetResultString(goi->interp, n->name, -1);
5121 if (goi->isconfigure) {
5122 e = jim_getopt_wide(goi, &w);
5125 target->coreid = (int32_t)w;
5130 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->coreid));
5134 case TCFG_CHAIN_POSITION:
5135 if (goi->isconfigure) {
5137 struct jtag_tap *tap;
5139 if (target->has_dap) {
5140 Jim_SetResultString(goi->interp,
5141 "target requires -dap parameter instead of -chain-position!", -1);
5145 target_free_all_working_areas(target);
5146 e = jim_getopt_obj(goi, &o_t);
5149 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
5153 target->tap_configured = true;
5158 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
5159 /* loop for more e*/
5162 if (goi->isconfigure) {
5163 e = jim_getopt_wide(goi, &w);
5166 target->dbgbase = (uint32_t)w;
5167 target->dbgbase_set = true;
5172 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
5178 int result = rtos_create(goi, target);
5179 if (result != JIM_OK)
5185 case TCFG_DEFER_EXAMINE:
5187 target->defer_examine = true;
5192 if (goi->isconfigure) {
5193 struct command_context *cmd_ctx = current_command_context(goi->interp);
5194 if (cmd_ctx->mode != COMMAND_CONFIG) {
5195 Jim_SetResultString(goi->interp, "-gdb-port must be configured before 'init'", -1);
5200 e = jim_getopt_string(goi, &s, NULL);
5203 free(target->gdb_port_override);
5204 target->gdb_port_override = strdup(s);
5209 Jim_SetResultString(goi->interp, target->gdb_port_override ? target->gdb_port_override : "undefined", -1);
5213 case TCFG_GDB_MAX_CONNECTIONS:
5214 if (goi->isconfigure) {
5215 struct command_context *cmd_ctx = current_command_context(goi->interp);
5216 if (cmd_ctx->mode != COMMAND_CONFIG) {
5217 Jim_SetResultString(goi->interp, "-gdb-max-connections must be configured before 'init'", -1);
5221 e = jim_getopt_wide(goi, &w);
5224 target->gdb_max_connections = (w < 0) ? CONNECTION_LIMIT_UNLIMITED : (int)w;
5229 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->gdb_max_connections));
5232 } /* while (goi->argc) */
5235 /* done - we return */
5239 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5241 struct command *c = jim_to_command(interp);
5242 struct jim_getopt_info goi;
5244 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5245 goi.isconfigure = !strcmp(c->name, "configure");
5247 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5248 "missing: -option ...");
5251 struct command_context *cmd_ctx = current_command_context(interp);
5253 struct target *target = get_current_target(cmd_ctx);
5254 return target_configure(&goi, target);
5257 static int jim_target_mem2array(Jim_Interp *interp,
5258 int argc, Jim_Obj *const *argv)
5260 struct command_context *cmd_ctx = current_command_context(interp);
5262 struct target *target = get_current_target(cmd_ctx);
5263 return target_mem2array(interp, target, argc - 1, argv + 1);
5266 static int jim_target_array2mem(Jim_Interp *interp,
5267 int argc, Jim_Obj *const *argv)
5269 struct command_context *cmd_ctx = current_command_context(interp);
5271 struct target *target = get_current_target(cmd_ctx);
5272 return target_array2mem(interp, target, argc - 1, argv + 1);
5275 static int jim_target_tap_disabled(Jim_Interp *interp)
5277 Jim_SetResultFormatted(interp, "[TAP is disabled]");
5281 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5283 bool allow_defer = false;
5285 struct jim_getopt_info goi;
5286 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5288 const char *cmd_name = Jim_GetString(argv[0], NULL);
5289 Jim_SetResultFormatted(goi.interp,
5290 "usage: %s ['allow-defer']", cmd_name);
5294 strcmp(Jim_GetString(argv[1], NULL), "allow-defer") == 0) {
5297 int e = jim_getopt_obj(&goi, &obj);
5303 struct command_context *cmd_ctx = current_command_context(interp);
5305 struct target *target = get_current_target(cmd_ctx);
5306 if (!target->tap->enabled)
5307 return jim_target_tap_disabled(interp);
5309 if (allow_defer && target->defer_examine) {
5310 LOG_INFO("Deferring arp_examine of %s", target_name(target));
5311 LOG_INFO("Use arp_examine command to examine it manually!");
5315 int e = target->type->examine(target);
5316 if (e != ERROR_OK) {
5317 target_reset_examined(target);
5321 target_set_examined(target);
5326 static int jim_target_was_examined(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5328 struct command_context *cmd_ctx = current_command_context(interp);
5330 struct target *target = get_current_target(cmd_ctx);
5332 Jim_SetResultBool(interp, target_was_examined(target));
5336 static int jim_target_examine_deferred(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5338 struct command_context *cmd_ctx = current_command_context(interp);
5340 struct target *target = get_current_target(cmd_ctx);
5342 Jim_SetResultBool(interp, target->defer_examine);
5346 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5349 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5352 struct command_context *cmd_ctx = current_command_context(interp);
5354 struct target *target = get_current_target(cmd_ctx);
5356 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
5362 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5365 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5368 struct command_context *cmd_ctx = current_command_context(interp);
5370 struct target *target = get_current_target(cmd_ctx);
5371 if (!target->tap->enabled)
5372 return jim_target_tap_disabled(interp);
5375 if (!(target_was_examined(target)))
5376 e = ERROR_TARGET_NOT_EXAMINED;
5378 e = target->type->poll(target);
5384 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5386 struct jim_getopt_info goi;
5387 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5389 if (goi.argc != 2) {
5390 Jim_WrongNumArgs(interp, 0, argv,
5391 "([tT]|[fF]|assert|deassert) BOOL");
5396 int e = jim_getopt_nvp(&goi, nvp_assert, &n);
5398 jim_getopt_nvp_unknown(&goi, nvp_assert, 1);
5401 /* the halt or not param */
5403 e = jim_getopt_wide(&goi, &a);
5407 struct command_context *cmd_ctx = current_command_context(interp);
5409 struct target *target = get_current_target(cmd_ctx);
5410 if (!target->tap->enabled)
5411 return jim_target_tap_disabled(interp);
5413 if (!target->type->assert_reset || !target->type->deassert_reset) {
5414 Jim_SetResultFormatted(interp,
5415 "No target-specific reset for %s",
5416 target_name(target));
5420 if (target->defer_examine)
5421 target_reset_examined(target);
5423 /* determine if we should halt or not. */
5424 target->reset_halt = (a != 0);
5425 /* When this happens - all workareas are invalid. */
5426 target_free_all_working_areas_restore(target, 0);
5429 if (n->value == NVP_ASSERT)
5430 e = target->type->assert_reset(target);
5432 e = target->type->deassert_reset(target);
5433 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5436 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5439 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5442 struct command_context *cmd_ctx = current_command_context(interp);
5444 struct target *target = get_current_target(cmd_ctx);
5445 if (!target->tap->enabled)
5446 return jim_target_tap_disabled(interp);
5447 int e = target->type->halt(target);
5448 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5451 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5453 struct jim_getopt_info goi;
5454 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5456 /* params: <name> statename timeoutmsecs */
5457 if (goi.argc != 2) {
5458 const char *cmd_name = Jim_GetString(argv[0], NULL);
5459 Jim_SetResultFormatted(goi.interp,
5460 "%s <state_name> <timeout_in_msec>", cmd_name);
5465 int e = jim_getopt_nvp(&goi, nvp_target_state, &n);
5467 jim_getopt_nvp_unknown(&goi, nvp_target_state, 1);
5471 e = jim_getopt_wide(&goi, &a);
5474 struct command_context *cmd_ctx = current_command_context(interp);
5476 struct target *target = get_current_target(cmd_ctx);
5477 if (!target->tap->enabled)
5478 return jim_target_tap_disabled(interp);
5480 e = target_wait_state(target, n->value, a);
5481 if (e != ERROR_OK) {
5482 Jim_Obj *obj = Jim_NewIntObj(interp, e);
5483 Jim_SetResultFormatted(goi.interp,
5484 "target: %s wait %s fails (%#s) %s",
5485 target_name(target), n->name,
5486 obj, target_strerror_safe(e));
5491 /* List for human, Events defined for this target.
5492 * scripts/programs should use 'name cget -event NAME'
5494 COMMAND_HANDLER(handle_target_event_list)
5496 struct target *target = get_current_target(CMD_CTX);
5497 struct target_event_action *teap = target->event_action;
5499 command_print(CMD, "Event actions for target (%d) %s\n",
5500 target->target_number,
5501 target_name(target));
5502 command_print(CMD, "%-25s | Body", "Event");
5503 command_print(CMD, "------------------------- | "
5504 "----------------------------------------");
5506 command_print(CMD, "%-25s | %s",
5507 target_event_name(teap->event),
5508 Jim_GetString(teap->body, NULL));
5511 command_print(CMD, "***END***");
5514 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5517 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5520 struct command_context *cmd_ctx = current_command_context(interp);
5522 struct target *target = get_current_target(cmd_ctx);
5523 Jim_SetResultString(interp, target_state_name(target), -1);
5526 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5528 struct jim_getopt_info goi;
5529 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5530 if (goi.argc != 1) {
5531 const char *cmd_name = Jim_GetString(argv[0], NULL);
5532 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5536 int e = jim_getopt_nvp(&goi, nvp_target_event, &n);
5538 jim_getopt_nvp_unknown(&goi, nvp_target_event, 1);
5541 struct command_context *cmd_ctx = current_command_context(interp);
5543 struct target *target = get_current_target(cmd_ctx);
5544 target_handle_event(target, n->value);
5548 static const struct command_registration target_instance_command_handlers[] = {
5550 .name = "configure",
5551 .mode = COMMAND_ANY,
5552 .jim_handler = jim_target_configure,
5553 .help = "configure a new target for use",
5554 .usage = "[target_attribute ...]",
5558 .mode = COMMAND_ANY,
5559 .jim_handler = jim_target_configure,
5560 .help = "returns the specified target attribute",
5561 .usage = "target_attribute",
5565 .handler = handle_mw_command,
5566 .mode = COMMAND_EXEC,
5567 .help = "Write 64-bit word(s) to target memory",
5568 .usage = "address data [count]",
5572 .handler = handle_mw_command,
5573 .mode = COMMAND_EXEC,
5574 .help = "Write 32-bit word(s) to target memory",
5575 .usage = "address data [count]",
5579 .handler = handle_mw_command,
5580 .mode = COMMAND_EXEC,
5581 .help = "Write 16-bit half-word(s) to target memory",
5582 .usage = "address data [count]",
5586 .handler = handle_mw_command,
5587 .mode = COMMAND_EXEC,
5588 .help = "Write byte(s) to target memory",
5589 .usage = "address data [count]",
5593 .handler = handle_md_command,
5594 .mode = COMMAND_EXEC,
5595 .help = "Display target memory as 64-bit words",
5596 .usage = "address [count]",
5600 .handler = handle_md_command,
5601 .mode = COMMAND_EXEC,
5602 .help = "Display target memory as 32-bit words",
5603 .usage = "address [count]",
5607 .handler = handle_md_command,
5608 .mode = COMMAND_EXEC,
5609 .help = "Display target memory as 16-bit half-words",
5610 .usage = "address [count]",
5614 .handler = handle_md_command,
5615 .mode = COMMAND_EXEC,
5616 .help = "Display target memory as 8-bit bytes",
5617 .usage = "address [count]",
5620 .name = "array2mem",
5621 .mode = COMMAND_EXEC,
5622 .jim_handler = jim_target_array2mem,
5623 .help = "Writes Tcl array of 8/16/32 bit numbers "
5625 .usage = "arrayname bitwidth address count",
5628 .name = "mem2array",
5629 .mode = COMMAND_EXEC,
5630 .jim_handler = jim_target_mem2array,
5631 .help = "Loads Tcl array of 8/16/32 bit numbers "
5632 "from target memory",
5633 .usage = "arrayname bitwidth address count",
5636 .name = "eventlist",
5637 .handler = handle_target_event_list,
5638 .mode = COMMAND_EXEC,
5639 .help = "displays a table of events defined for this target",
5644 .mode = COMMAND_EXEC,
5645 .jim_handler = jim_target_current_state,
5646 .help = "displays the current state of this target",
5649 .name = "arp_examine",
5650 .mode = COMMAND_EXEC,
5651 .jim_handler = jim_target_examine,
5652 .help = "used internally for reset processing",
5653 .usage = "['allow-defer']",
5656 .name = "was_examined",
5657 .mode = COMMAND_EXEC,
5658 .jim_handler = jim_target_was_examined,
5659 .help = "used internally for reset processing",
5662 .name = "examine_deferred",
5663 .mode = COMMAND_EXEC,
5664 .jim_handler = jim_target_examine_deferred,
5665 .help = "used internally for reset processing",
5668 .name = "arp_halt_gdb",
5669 .mode = COMMAND_EXEC,
5670 .jim_handler = jim_target_halt_gdb,
5671 .help = "used internally for reset processing to halt GDB",
5675 .mode = COMMAND_EXEC,
5676 .jim_handler = jim_target_poll,
5677 .help = "used internally for reset processing",
5680 .name = "arp_reset",
5681 .mode = COMMAND_EXEC,
5682 .jim_handler = jim_target_reset,
5683 .help = "used internally for reset processing",
5687 .mode = COMMAND_EXEC,
5688 .jim_handler = jim_target_halt,
5689 .help = "used internally for reset processing",
5692 .name = "arp_waitstate",
5693 .mode = COMMAND_EXEC,
5694 .jim_handler = jim_target_wait_state,
5695 .help = "used internally for reset processing",
5698 .name = "invoke-event",
5699 .mode = COMMAND_EXEC,
5700 .jim_handler = jim_target_invoke_event,
5701 .help = "invoke handler for specified event",
5702 .usage = "event_name",
5704 COMMAND_REGISTRATION_DONE
5707 static int target_create(struct jim_getopt_info *goi)
5714 struct target *target;
5715 struct command_context *cmd_ctx;
5717 cmd_ctx = current_command_context(goi->interp);
5720 if (goi->argc < 3) {
5721 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5726 jim_getopt_obj(goi, &new_cmd);
5727 /* does this command exist? */
5728 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_NONE);
5730 cp = Jim_GetString(new_cmd, NULL);
5731 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5736 e = jim_getopt_string(goi, &cp, NULL);
5739 struct transport *tr = get_current_transport();
5740 if (tr->override_target) {
5741 e = tr->override_target(&cp);
5742 if (e != ERROR_OK) {
5743 LOG_ERROR("The selected transport doesn't support this target");
5746 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5748 /* now does target type exist */
5749 for (x = 0 ; target_types[x] ; x++) {
5750 if (strcmp(cp, target_types[x]->name) == 0) {
5755 if (!target_types[x]) {
5756 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5757 for (x = 0 ; target_types[x] ; x++) {
5758 if (target_types[x + 1]) {
5759 Jim_AppendStrings(goi->interp,
5760 Jim_GetResult(goi->interp),
5761 target_types[x]->name,
5764 Jim_AppendStrings(goi->interp,
5765 Jim_GetResult(goi->interp),
5767 target_types[x]->name, NULL);
5774 target = calloc(1, sizeof(struct target));
5776 LOG_ERROR("Out of memory");
5780 /* set target number */
5781 target->target_number = new_target_number();
5783 /* allocate memory for each unique target type */
5784 target->type = malloc(sizeof(struct target_type));
5785 if (!target->type) {
5786 LOG_ERROR("Out of memory");
5791 memcpy(target->type, target_types[x], sizeof(struct target_type));
5793 /* default to first core, override with -coreid */
5796 target->working_area = 0x0;
5797 target->working_area_size = 0x0;
5798 target->working_areas = NULL;
5799 target->backup_working_area = 0;
5801 target->state = TARGET_UNKNOWN;
5802 target->debug_reason = DBG_REASON_UNDEFINED;
5803 target->reg_cache = NULL;
5804 target->breakpoints = NULL;
5805 target->watchpoints = NULL;
5806 target->next = NULL;
5807 target->arch_info = NULL;
5809 target->verbose_halt_msg = true;
5811 target->halt_issued = false;
5813 /* initialize trace information */
5814 target->trace_info = calloc(1, sizeof(struct trace));
5815 if (!target->trace_info) {
5816 LOG_ERROR("Out of memory");
5822 target->dbgmsg = NULL;
5823 target->dbg_msg_enabled = 0;
5825 target->endianness = TARGET_ENDIAN_UNKNOWN;
5827 target->rtos = NULL;
5828 target->rtos_auto_detect = false;
5830 target->gdb_port_override = NULL;
5831 target->gdb_max_connections = 1;
5833 /* Do the rest as "configure" options */
5834 goi->isconfigure = 1;
5835 e = target_configure(goi, target);
5838 if (target->has_dap) {
5839 if (!target->dap_configured) {
5840 Jim_SetResultString(goi->interp, "-dap ?name? required when creating target", -1);
5844 if (!target->tap_configured) {
5845 Jim_SetResultString(goi->interp, "-chain-position ?name? required when creating target", -1);
5849 /* tap must be set after target was configured */
5855 rtos_destroy(target);
5856 free(target->gdb_port_override);
5857 free(target->trace_info);
5863 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5864 /* default endian to little if not specified */
5865 target->endianness = TARGET_LITTLE_ENDIAN;
5868 cp = Jim_GetString(new_cmd, NULL);
5869 target->cmd_name = strdup(cp);
5870 if (!target->cmd_name) {
5871 LOG_ERROR("Out of memory");
5872 rtos_destroy(target);
5873 free(target->gdb_port_override);
5874 free(target->trace_info);
5880 if (target->type->target_create) {
5881 e = (*(target->type->target_create))(target, goi->interp);
5882 if (e != ERROR_OK) {
5883 LOG_DEBUG("target_create failed");
5884 free(target->cmd_name);
5885 rtos_destroy(target);
5886 free(target->gdb_port_override);
5887 free(target->trace_info);
5894 /* create the target specific commands */
5895 if (target->type->commands) {
5896 e = register_commands(cmd_ctx, NULL, target->type->commands);
5898 LOG_ERROR("unable to register '%s' commands", cp);
5901 /* now - create the new target name command */
5902 const struct command_registration target_subcommands[] = {
5904 .chain = target_instance_command_handlers,
5907 .chain = target->type->commands,
5909 COMMAND_REGISTRATION_DONE
5911 const struct command_registration target_commands[] = {
5914 .mode = COMMAND_ANY,
5915 .help = "target command group",
5917 .chain = target_subcommands,
5919 COMMAND_REGISTRATION_DONE
5921 e = register_commands_override_target(cmd_ctx, NULL, target_commands, target);
5922 if (e != ERROR_OK) {
5923 if (target->type->deinit_target)
5924 target->type->deinit_target(target);
5925 free(target->cmd_name);
5926 rtos_destroy(target);
5927 free(target->gdb_port_override);
5928 free(target->trace_info);
5934 /* append to end of list */
5935 append_to_list_all_targets(target);
5937 cmd_ctx->current_target = target;
5941 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5944 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5947 struct command_context *cmd_ctx = current_command_context(interp);
5950 struct target *target = get_current_target_or_null(cmd_ctx);
5952 Jim_SetResultString(interp, target_name(target), -1);
5956 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5959 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5962 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5963 for (unsigned x = 0; target_types[x]; x++) {
5964 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5965 Jim_NewStringObj(interp, target_types[x]->name, -1));
5970 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5973 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5976 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5977 struct target *target = all_targets;
5979 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5980 Jim_NewStringObj(interp, target_name(target), -1));
5981 target = target->next;
5986 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5989 const char *targetname;
5991 struct target *target = NULL;
5992 struct target_list *head, *curr, *new;
5997 LOG_DEBUG("%d", argc);
5998 /* argv[1] = target to associate in smp
5999 * argv[2] = target to associate in smp
6003 for (i = 1; i < argc; i++) {
6005 targetname = Jim_GetString(argv[i], &len);
6006 target = get_target(targetname);
6007 LOG_DEBUG("%s ", targetname);
6009 new = malloc(sizeof(struct target_list));
6010 new->target = target;
6021 /* now parse the list of cpu and put the target in smp mode*/
6025 target = curr->target;
6027 target->head = head;
6031 if (target && target->rtos)
6032 retval = rtos_smp_init(head->target);
6038 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6040 struct jim_getopt_info goi;
6041 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
6043 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
6044 "<name> <target_type> [<target_options> ...]");
6047 return target_create(&goi);
6050 static const struct command_registration target_subcommand_handlers[] = {
6053 .mode = COMMAND_CONFIG,
6054 .handler = handle_target_init_command,
6055 .help = "initialize targets",
6060 .mode = COMMAND_CONFIG,
6061 .jim_handler = jim_target_create,
6062 .usage = "name type '-chain-position' name [options ...]",
6063 .help = "Creates and selects a new target",
6067 .mode = COMMAND_ANY,
6068 .jim_handler = jim_target_current,
6069 .help = "Returns the currently selected target",
6073 .mode = COMMAND_ANY,
6074 .jim_handler = jim_target_types,
6075 .help = "Returns the available target types as "
6076 "a list of strings",
6080 .mode = COMMAND_ANY,
6081 .jim_handler = jim_target_names,
6082 .help = "Returns the names of all targets as a list of strings",
6086 .mode = COMMAND_ANY,
6087 .jim_handler = jim_target_smp,
6088 .usage = "targetname1 targetname2 ...",
6089 .help = "gather several target in a smp list"
6092 COMMAND_REGISTRATION_DONE
6096 target_addr_t address;
6102 static int fastload_num;
6103 static struct fast_load *fastload;
6105 static void free_fastload(void)
6108 for (int i = 0; i < fastload_num; i++)
6109 free(fastload[i].data);
6115 COMMAND_HANDLER(handle_fast_load_image_command)
6119 uint32_t image_size;
6120 target_addr_t min_address = 0;
6121 target_addr_t max_address = -1;
6125 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
6126 &image, &min_address, &max_address);
6127 if (retval != ERROR_OK)
6130 struct duration bench;
6131 duration_start(&bench);
6133 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
6134 if (retval != ERROR_OK)
6139 fastload_num = image.num_sections;
6140 fastload = malloc(sizeof(struct fast_load)*image.num_sections);
6142 command_print(CMD, "out of memory");
6143 image_close(&image);
6146 memset(fastload, 0, sizeof(struct fast_load)*image.num_sections);
6147 for (unsigned int i = 0; i < image.num_sections; i++) {
6148 buffer = malloc(image.sections[i].size);
6150 command_print(CMD, "error allocating buffer for section (%d bytes)",
6151 (int)(image.sections[i].size));
6152 retval = ERROR_FAIL;
6156 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
6157 if (retval != ERROR_OK) {
6162 uint32_t offset = 0;
6163 uint32_t length = buf_cnt;
6165 /* DANGER!!! beware of unsigned comparison here!!! */
6167 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
6168 (image.sections[i].base_address < max_address)) {
6169 if (image.sections[i].base_address < min_address) {
6170 /* clip addresses below */
6171 offset += min_address-image.sections[i].base_address;
6175 if (image.sections[i].base_address + buf_cnt > max_address)
6176 length -= (image.sections[i].base_address + buf_cnt)-max_address;
6178 fastload[i].address = image.sections[i].base_address + offset;
6179 fastload[i].data = malloc(length);
6180 if (!fastload[i].data) {
6182 command_print(CMD, "error allocating buffer for section (%" PRIu32 " bytes)",
6184 retval = ERROR_FAIL;
6187 memcpy(fastload[i].data, buffer + offset, length);
6188 fastload[i].length = length;
6190 image_size += length;
6191 command_print(CMD, "%u bytes written at address 0x%8.8x",
6192 (unsigned int)length,
6193 ((unsigned int)(image.sections[i].base_address + offset)));
6199 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
6200 command_print(CMD, "Loaded %" PRIu32 " bytes "
6201 "in %fs (%0.3f KiB/s)", image_size,
6202 duration_elapsed(&bench), duration_kbps(&bench, image_size));
6205 "WARNING: image has not been loaded to target!"
6206 "You can issue a 'fast_load' to finish loading.");
6209 image_close(&image);
6211 if (retval != ERROR_OK)
6217 COMMAND_HANDLER(handle_fast_load_command)
6220 return ERROR_COMMAND_SYNTAX_ERROR;
6222 LOG_ERROR("No image in memory");
6226 int64_t ms = timeval_ms();
6228 int retval = ERROR_OK;
6229 for (i = 0; i < fastload_num; i++) {
6230 struct target *target = get_current_target(CMD_CTX);
6231 command_print(CMD, "Write to 0x%08x, length 0x%08x",
6232 (unsigned int)(fastload[i].address),
6233 (unsigned int)(fastload[i].length));
6234 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
6235 if (retval != ERROR_OK)
6237 size += fastload[i].length;
6239 if (retval == ERROR_OK) {
6240 int64_t after = timeval_ms();
6241 command_print(CMD, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
6246 static const struct command_registration target_command_handlers[] = {
6249 .handler = handle_targets_command,
6250 .mode = COMMAND_ANY,
6251 .help = "change current default target (one parameter) "
6252 "or prints table of all targets (no parameters)",
6253 .usage = "[target]",
6257 .mode = COMMAND_CONFIG,
6258 .help = "configure target",
6259 .chain = target_subcommand_handlers,
6262 COMMAND_REGISTRATION_DONE
6265 int target_register_commands(struct command_context *cmd_ctx)
6267 return register_commands(cmd_ctx, NULL, target_command_handlers);
6270 static bool target_reset_nag = true;
6272 bool get_target_reset_nag(void)
6274 return target_reset_nag;
6277 COMMAND_HANDLER(handle_target_reset_nag)
6279 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
6280 &target_reset_nag, "Nag after each reset about options to improve "
6284 COMMAND_HANDLER(handle_ps_command)
6286 struct target *target = get_current_target(CMD_CTX);
6288 if (target->state != TARGET_HALTED) {
6289 LOG_INFO("target not halted !!");
6293 if ((target->rtos) && (target->rtos->type)
6294 && (target->rtos->type->ps_command)) {
6295 display = target->rtos->type->ps_command(target);
6296 command_print(CMD, "%s", display);
6301 return ERROR_TARGET_FAILURE;
6305 static void binprint(struct command_invocation *cmd, const char *text, const uint8_t *buf, int size)
6308 command_print_sameline(cmd, "%s", text);
6309 for (int i = 0; i < size; i++)
6310 command_print_sameline(cmd, " %02x", buf[i]);
6311 command_print(cmd, " ");
6314 COMMAND_HANDLER(handle_test_mem_access_command)
6316 struct target *target = get_current_target(CMD_CTX);
6318 int retval = ERROR_OK;
6320 if (target->state != TARGET_HALTED) {
6321 LOG_INFO("target not halted !!");
6326 return ERROR_COMMAND_SYNTAX_ERROR;
6328 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
6331 size_t num_bytes = test_size + 4;
6333 struct working_area *wa = NULL;
6334 retval = target_alloc_working_area(target, num_bytes, &wa);
6335 if (retval != ERROR_OK) {
6336 LOG_ERROR("Not enough working area");
6340 uint8_t *test_pattern = malloc(num_bytes);
6342 for (size_t i = 0; i < num_bytes; i++)
6343 test_pattern[i] = rand();
6345 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6346 if (retval != ERROR_OK) {
6347 LOG_ERROR("Test pattern write failed");
6351 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6352 for (int size = 1; size <= 4; size *= 2) {
6353 for (int offset = 0; offset < 4; offset++) {
6354 uint32_t count = test_size / size;
6355 size_t host_bufsiz = (count + 2) * size + host_offset;
6356 uint8_t *read_ref = malloc(host_bufsiz);
6357 uint8_t *read_buf = malloc(host_bufsiz);
6359 for (size_t i = 0; i < host_bufsiz; i++) {
6360 read_ref[i] = rand();
6361 read_buf[i] = read_ref[i];
6363 command_print_sameline(CMD,
6364 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
6365 size, offset, host_offset ? "un" : "");
6367 struct duration bench;
6368 duration_start(&bench);
6370 retval = target_read_memory(target, wa->address + offset, size, count,
6371 read_buf + size + host_offset);
6373 duration_measure(&bench);
6375 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6376 command_print(CMD, "Unsupported alignment");
6378 } else if (retval != ERROR_OK) {
6379 command_print(CMD, "Memory read failed");
6383 /* replay on host */
6384 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
6387 int result = memcmp(read_ref, read_buf, host_bufsiz);
6389 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6390 duration_elapsed(&bench),
6391 duration_kbps(&bench, count * size));
6393 command_print(CMD, "Compare failed");
6394 binprint(CMD, "ref:", read_ref, host_bufsiz);
6395 binprint(CMD, "buf:", read_buf, host_bufsiz);
6407 target_free_working_area(target, wa);
6410 num_bytes = test_size + 4 + 4 + 4;
6412 retval = target_alloc_working_area(target, num_bytes, &wa);
6413 if (retval != ERROR_OK) {
6414 LOG_ERROR("Not enough working area");
6418 test_pattern = malloc(num_bytes);
6420 for (size_t i = 0; i < num_bytes; i++)
6421 test_pattern[i] = rand();
6423 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6424 for (int size = 1; size <= 4; size *= 2) {
6425 for (int offset = 0; offset < 4; offset++) {
6426 uint32_t count = test_size / size;
6427 size_t host_bufsiz = count * size + host_offset;
6428 uint8_t *read_ref = malloc(num_bytes);
6429 uint8_t *read_buf = malloc(num_bytes);
6430 uint8_t *write_buf = malloc(host_bufsiz);
6432 for (size_t i = 0; i < host_bufsiz; i++)
6433 write_buf[i] = rand();
6434 command_print_sameline(CMD,
6435 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
6436 size, offset, host_offset ? "un" : "");
6438 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6439 if (retval != ERROR_OK) {
6440 command_print(CMD, "Test pattern write failed");
6444 /* replay on host */
6445 memcpy(read_ref, test_pattern, num_bytes);
6446 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
6448 struct duration bench;
6449 duration_start(&bench);
6451 retval = target_write_memory(target, wa->address + size + offset, size, count,
6452 write_buf + host_offset);
6454 duration_measure(&bench);
6456 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6457 command_print(CMD, "Unsupported alignment");
6459 } else if (retval != ERROR_OK) {
6460 command_print(CMD, "Memory write failed");
6465 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
6466 if (retval != ERROR_OK) {
6467 command_print(CMD, "Test pattern write failed");
6472 int result = memcmp(read_ref, read_buf, num_bytes);
6474 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6475 duration_elapsed(&bench),
6476 duration_kbps(&bench, count * size));
6478 command_print(CMD, "Compare failed");
6479 binprint(CMD, "ref:", read_ref, num_bytes);
6480 binprint(CMD, "buf:", read_buf, num_bytes);
6491 target_free_working_area(target, wa);
6495 static const struct command_registration target_exec_command_handlers[] = {
6497 .name = "fast_load_image",
6498 .handler = handle_fast_load_image_command,
6499 .mode = COMMAND_ANY,
6500 .help = "Load image into server memory for later use by "
6501 "fast_load; primarily for profiling",
6502 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6503 "[min_address [max_length]]",
6506 .name = "fast_load",
6507 .handler = handle_fast_load_command,
6508 .mode = COMMAND_EXEC,
6509 .help = "loads active fast load image to current target "
6510 "- mainly for profiling purposes",
6515 .handler = handle_profile_command,
6516 .mode = COMMAND_EXEC,
6517 .usage = "seconds filename [start end]",
6518 .help = "profiling samples the CPU PC",
6520 /** @todo don't register virt2phys() unless target supports it */
6522 .name = "virt2phys",
6523 .handler = handle_virt2phys_command,
6524 .mode = COMMAND_ANY,
6525 .help = "translate a virtual address into a physical address",
6526 .usage = "virtual_address",
6530 .handler = handle_reg_command,
6531 .mode = COMMAND_EXEC,
6532 .help = "display (reread from target with \"force\") or set a register; "
6533 "with no arguments, displays all registers and their values",
6534 .usage = "[(register_number|register_name) [(value|'force')]]",
6538 .handler = handle_poll_command,
6539 .mode = COMMAND_EXEC,
6540 .help = "poll target state; or reconfigure background polling",
6541 .usage = "['on'|'off']",
6544 .name = "wait_halt",
6545 .handler = handle_wait_halt_command,
6546 .mode = COMMAND_EXEC,
6547 .help = "wait up to the specified number of milliseconds "
6548 "(default 5000) for a previously requested halt",
6549 .usage = "[milliseconds]",
6553 .handler = handle_halt_command,
6554 .mode = COMMAND_EXEC,
6555 .help = "request target to halt, then wait up to the specified "
6556 "number of milliseconds (default 5000) for it to complete",
6557 .usage = "[milliseconds]",
6561 .handler = handle_resume_command,
6562 .mode = COMMAND_EXEC,
6563 .help = "resume target execution from current PC or address",
6564 .usage = "[address]",
6568 .handler = handle_reset_command,
6569 .mode = COMMAND_EXEC,
6570 .usage = "[run|halt|init]",
6571 .help = "Reset all targets into the specified mode. "
6572 "Default reset mode is run, if not given.",
6575 .name = "soft_reset_halt",
6576 .handler = handle_soft_reset_halt_command,
6577 .mode = COMMAND_EXEC,
6579 .help = "halt the target and do a soft reset",
6583 .handler = handle_step_command,
6584 .mode = COMMAND_EXEC,
6585 .help = "step one instruction from current PC or address",
6586 .usage = "[address]",
6590 .handler = handle_md_command,
6591 .mode = COMMAND_EXEC,
6592 .help = "display memory double-words",
6593 .usage = "['phys'] address [count]",
6597 .handler = handle_md_command,
6598 .mode = COMMAND_EXEC,
6599 .help = "display memory words",
6600 .usage = "['phys'] address [count]",
6604 .handler = handle_md_command,
6605 .mode = COMMAND_EXEC,
6606 .help = "display memory half-words",
6607 .usage = "['phys'] address [count]",
6611 .handler = handle_md_command,
6612 .mode = COMMAND_EXEC,
6613 .help = "display memory bytes",
6614 .usage = "['phys'] address [count]",
6618 .handler = handle_mw_command,
6619 .mode = COMMAND_EXEC,
6620 .help = "write memory double-word",
6621 .usage = "['phys'] address value [count]",
6625 .handler = handle_mw_command,
6626 .mode = COMMAND_EXEC,
6627 .help = "write memory word",
6628 .usage = "['phys'] address value [count]",
6632 .handler = handle_mw_command,
6633 .mode = COMMAND_EXEC,
6634 .help = "write memory half-word",
6635 .usage = "['phys'] address value [count]",
6639 .handler = handle_mw_command,
6640 .mode = COMMAND_EXEC,
6641 .help = "write memory byte",
6642 .usage = "['phys'] address value [count]",
6646 .handler = handle_bp_command,
6647 .mode = COMMAND_EXEC,
6648 .help = "list or set hardware or software breakpoint",
6649 .usage = "[<address> [<asid>] <length> ['hw'|'hw_ctx']]",
6653 .handler = handle_rbp_command,
6654 .mode = COMMAND_EXEC,
6655 .help = "remove breakpoint",
6656 .usage = "'all' | address",
6660 .handler = handle_wp_command,
6661 .mode = COMMAND_EXEC,
6662 .help = "list (no params) or create watchpoints",
6663 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
6667 .handler = handle_rwp_command,
6668 .mode = COMMAND_EXEC,
6669 .help = "remove watchpoint",
6673 .name = "load_image",
6674 .handler = handle_load_image_command,
6675 .mode = COMMAND_EXEC,
6676 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6677 "[min_address] [max_length]",
6680 .name = "dump_image",
6681 .handler = handle_dump_image_command,
6682 .mode = COMMAND_EXEC,
6683 .usage = "filename address size",
6686 .name = "verify_image_checksum",
6687 .handler = handle_verify_image_checksum_command,
6688 .mode = COMMAND_EXEC,
6689 .usage = "filename [offset [type]]",
6692 .name = "verify_image",
6693 .handler = handle_verify_image_command,
6694 .mode = COMMAND_EXEC,
6695 .usage = "filename [offset [type]]",
6698 .name = "test_image",
6699 .handler = handle_test_image_command,
6700 .mode = COMMAND_EXEC,
6701 .usage = "filename [offset [type]]",
6704 .name = "mem2array",
6705 .mode = COMMAND_EXEC,
6706 .jim_handler = jim_mem2array,
6707 .help = "read 8/16/32 bit memory and return as a TCL array "
6708 "for script processing",
6709 .usage = "arrayname bitwidth address count",
6712 .name = "array2mem",
6713 .mode = COMMAND_EXEC,
6714 .jim_handler = jim_array2mem,
6715 .help = "convert a TCL array to memory locations "
6716 "and write the 8/16/32 bit values",
6717 .usage = "arrayname bitwidth address count",
6720 .name = "reset_nag",
6721 .handler = handle_target_reset_nag,
6722 .mode = COMMAND_ANY,
6723 .help = "Nag after each reset about options that could have been "
6724 "enabled to improve performance.",
6725 .usage = "['enable'|'disable']",
6729 .handler = handle_ps_command,
6730 .mode = COMMAND_EXEC,
6731 .help = "list all tasks",
6735 .name = "test_mem_access",
6736 .handler = handle_test_mem_access_command,
6737 .mode = COMMAND_EXEC,
6738 .help = "Test the target's memory access functions",
6742 COMMAND_REGISTRATION_DONE
6744 static int target_register_user_commands(struct command_context *cmd_ctx)
6746 int retval = ERROR_OK;
6747 retval = target_request_register_commands(cmd_ctx);
6748 if (retval != ERROR_OK)
6751 retval = trace_register_commands(cmd_ctx);
6752 if (retval != ERROR_OK)
6756 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);