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)
720 static int default_examine(struct target *target)
722 target_set_examined(target);
726 /* no check by default */
727 static int default_check_reset(struct target *target)
732 /* Equivalent Tcl code arp_examine_one is in src/target/startup.tcl
734 int target_examine_one(struct target *target)
736 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
738 int retval = target->type->examine(target);
739 if (retval != ERROR_OK) {
740 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_FAIL);
744 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
749 static int jtag_enable_callback(enum jtag_event event, void *priv)
751 struct target *target = priv;
753 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
756 jtag_unregister_event_callback(jtag_enable_callback, target);
758 return target_examine_one(target);
761 /* Targets that correctly implement init + examine, i.e.
762 * no communication with target during init:
766 int target_examine(void)
768 int retval = ERROR_OK;
769 struct target *target;
771 for (target = all_targets; target; target = target->next) {
772 /* defer examination, but don't skip it */
773 if (!target->tap->enabled) {
774 jtag_register_event_callback(jtag_enable_callback,
779 if (target->defer_examine)
782 int retval2 = target_examine_one(target);
783 if (retval2 != ERROR_OK) {
784 LOG_WARNING("target %s examination failed", target_name(target));
791 const char *target_type_name(struct target *target)
793 return target->type->name;
796 static int target_soft_reset_halt(struct target *target)
798 if (!target_was_examined(target)) {
799 LOG_ERROR("Target not examined yet");
802 if (!target->type->soft_reset_halt) {
803 LOG_ERROR("Target %s does not support soft_reset_halt",
804 target_name(target));
807 return target->type->soft_reset_halt(target);
811 * Downloads a target-specific native code algorithm to the target,
812 * and executes it. * Note that some targets may need to set up, enable,
813 * and tear down a breakpoint (hard or * soft) to detect algorithm
814 * termination, while others may support lower overhead schemes where
815 * soft breakpoints embedded in the algorithm automatically terminate the
818 * @param target used to run the algorithm
819 * @param num_mem_params
821 * @param num_reg_params
826 * @param arch_info target-specific description of the algorithm.
828 int target_run_algorithm(struct target *target,
829 int num_mem_params, struct mem_param *mem_params,
830 int num_reg_params, struct reg_param *reg_param,
831 uint32_t entry_point, uint32_t exit_point,
832 int timeout_ms, void *arch_info)
834 int retval = ERROR_FAIL;
836 if (!target_was_examined(target)) {
837 LOG_ERROR("Target not examined yet");
840 if (!target->type->run_algorithm) {
841 LOG_ERROR("Target type '%s' does not support %s",
842 target_type_name(target), __func__);
846 target->running_alg = true;
847 retval = target->type->run_algorithm(target,
848 num_mem_params, mem_params,
849 num_reg_params, reg_param,
850 entry_point, exit_point, timeout_ms, arch_info);
851 target->running_alg = false;
858 * Executes a target-specific native code algorithm and leaves it running.
860 * @param target used to run the algorithm
861 * @param num_mem_params
863 * @param num_reg_params
867 * @param arch_info target-specific description of the algorithm.
869 int target_start_algorithm(struct target *target,
870 int num_mem_params, struct mem_param *mem_params,
871 int num_reg_params, struct reg_param *reg_params,
872 uint32_t entry_point, uint32_t exit_point,
875 int retval = ERROR_FAIL;
877 if (!target_was_examined(target)) {
878 LOG_ERROR("Target not examined yet");
881 if (!target->type->start_algorithm) {
882 LOG_ERROR("Target type '%s' does not support %s",
883 target_type_name(target), __func__);
886 if (target->running_alg) {
887 LOG_ERROR("Target is already running an algorithm");
891 target->running_alg = true;
892 retval = target->type->start_algorithm(target,
893 num_mem_params, mem_params,
894 num_reg_params, reg_params,
895 entry_point, exit_point, arch_info);
902 * Waits for an algorithm started with target_start_algorithm() to complete.
904 * @param target used to run the algorithm
905 * @param num_mem_params
907 * @param num_reg_params
911 * @param arch_info target-specific description of the algorithm.
913 int target_wait_algorithm(struct target *target,
914 int num_mem_params, struct mem_param *mem_params,
915 int num_reg_params, struct reg_param *reg_params,
916 uint32_t exit_point, int timeout_ms,
919 int retval = ERROR_FAIL;
921 if (!target->type->wait_algorithm) {
922 LOG_ERROR("Target type '%s' does not support %s",
923 target_type_name(target), __func__);
926 if (!target->running_alg) {
927 LOG_ERROR("Target is not running an algorithm");
931 retval = target->type->wait_algorithm(target,
932 num_mem_params, mem_params,
933 num_reg_params, reg_params,
934 exit_point, timeout_ms, arch_info);
935 if (retval != ERROR_TARGET_TIMEOUT)
936 target->running_alg = false;
943 * Streams data to a circular buffer on target intended for consumption by code
944 * running asynchronously on target.
946 * This is intended for applications where target-specific native code runs
947 * on the target, receives data from the circular buffer, does something with
948 * it (most likely writing it to a flash memory), and advances the circular
951 * This assumes that the helper algorithm has already been loaded to the target,
952 * but has not been started yet. Given memory and register parameters are passed
955 * The buffer is defined by (buffer_start, buffer_size) arguments and has the
958 * [buffer_start + 0, buffer_start + 4):
959 * Write Pointer address (aka head). Written and updated by this
960 * routine when new data is written to the circular buffer.
961 * [buffer_start + 4, buffer_start + 8):
962 * Read Pointer address (aka tail). Updated by code running on the
963 * target after it consumes data.
964 * [buffer_start + 8, buffer_start + buffer_size):
965 * Circular buffer contents.
967 * See contrib/loaders/flash/stm32f1x.S for an example.
969 * @param target used to run the algorithm
970 * @param buffer address on the host where data to be sent is located
971 * @param count number of blocks to send
972 * @param block_size size in bytes of each block
973 * @param num_mem_params count of memory-based params to pass to algorithm
974 * @param mem_params memory-based params to pass to algorithm
975 * @param num_reg_params count of register-based params to pass to algorithm
976 * @param reg_params memory-based params to pass to algorithm
977 * @param buffer_start address on the target of the circular buffer structure
978 * @param buffer_size size of the circular buffer structure
979 * @param entry_point address on the target to execute to start the algorithm
980 * @param exit_point address at which to set a breakpoint to catch the
981 * end of the algorithm; can be 0 if target triggers a breakpoint itself
985 int target_run_flash_async_algorithm(struct target *target,
986 const uint8_t *buffer, uint32_t count, int block_size,
987 int num_mem_params, struct mem_param *mem_params,
988 int num_reg_params, struct reg_param *reg_params,
989 uint32_t buffer_start, uint32_t buffer_size,
990 uint32_t entry_point, uint32_t exit_point, void *arch_info)
995 const uint8_t *buffer_orig = buffer;
997 /* Set up working area. First word is write pointer, second word is read pointer,
998 * rest is fifo data area. */
999 uint32_t wp_addr = buffer_start;
1000 uint32_t rp_addr = buffer_start + 4;
1001 uint32_t fifo_start_addr = buffer_start + 8;
1002 uint32_t fifo_end_addr = buffer_start + buffer_size;
1004 uint32_t wp = fifo_start_addr;
1005 uint32_t rp = fifo_start_addr;
1007 /* validate block_size is 2^n */
1008 assert(IS_PWR_OF_2(block_size));
1010 retval = target_write_u32(target, wp_addr, wp);
1011 if (retval != ERROR_OK)
1013 retval = target_write_u32(target, rp_addr, rp);
1014 if (retval != ERROR_OK)
1017 /* Start up algorithm on target and let it idle while writing the first chunk */
1018 retval = target_start_algorithm(target, num_mem_params, mem_params,
1019 num_reg_params, reg_params,
1024 if (retval != ERROR_OK) {
1025 LOG_ERROR("error starting target flash write algorithm");
1031 retval = target_read_u32(target, rp_addr, &rp);
1032 if (retval != ERROR_OK) {
1033 LOG_ERROR("failed to get read pointer");
1037 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1038 (size_t) (buffer - buffer_orig), count, wp, rp);
1041 LOG_ERROR("flash write algorithm aborted by target");
1042 retval = ERROR_FLASH_OPERATION_FAILED;
1046 if (!IS_ALIGNED(rp - fifo_start_addr, block_size) || rp < fifo_start_addr || rp >= fifo_end_addr) {
1047 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
1051 /* Count the number of bytes available in the fifo without
1052 * crossing the wrap around. Make sure to not fill it completely,
1053 * because that would make wp == rp and that's the empty condition. */
1054 uint32_t thisrun_bytes;
1056 thisrun_bytes = rp - wp - block_size;
1057 else if (rp > fifo_start_addr)
1058 thisrun_bytes = fifo_end_addr - wp;
1060 thisrun_bytes = fifo_end_addr - wp - block_size;
1062 if (thisrun_bytes == 0) {
1063 /* Throttle polling a bit if transfer is (much) faster than flash
1064 * programming. The exact delay shouldn't matter as long as it's
1065 * less than buffer size / flash speed. This is very unlikely to
1066 * run when using high latency connections such as USB. */
1069 /* to stop an infinite loop on some targets check and increment a timeout
1070 * this issue was observed on a stellaris using the new ICDI interface */
1071 if (timeout++ >= 2500) {
1072 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1073 return ERROR_FLASH_OPERATION_FAILED;
1078 /* reset our timeout */
1081 /* Limit to the amount of data we actually want to write */
1082 if (thisrun_bytes > count * block_size)
1083 thisrun_bytes = count * block_size;
1085 /* Force end of large blocks to be word aligned */
1086 if (thisrun_bytes >= 16)
1087 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1089 /* Write data to fifo */
1090 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
1091 if (retval != ERROR_OK)
1094 /* Update counters and wrap write pointer */
1095 buffer += thisrun_bytes;
1096 count -= thisrun_bytes / block_size;
1097 wp += thisrun_bytes;
1098 if (wp >= fifo_end_addr)
1099 wp = fifo_start_addr;
1101 /* Store updated write pointer to target */
1102 retval = target_write_u32(target, wp_addr, wp);
1103 if (retval != ERROR_OK)
1106 /* Avoid GDB timeouts */
1110 if (retval != ERROR_OK) {
1111 /* abort flash write algorithm on target */
1112 target_write_u32(target, wp_addr, 0);
1115 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1116 num_reg_params, reg_params,
1121 if (retval2 != ERROR_OK) {
1122 LOG_ERROR("error waiting for target flash write algorithm");
1126 if (retval == ERROR_OK) {
1127 /* check if algorithm set rp = 0 after fifo writer loop finished */
1128 retval = target_read_u32(target, rp_addr, &rp);
1129 if (retval == ERROR_OK && rp == 0) {
1130 LOG_ERROR("flash write algorithm aborted by target");
1131 retval = ERROR_FLASH_OPERATION_FAILED;
1138 int target_run_read_async_algorithm(struct target *target,
1139 uint8_t *buffer, uint32_t count, int block_size,
1140 int num_mem_params, struct mem_param *mem_params,
1141 int num_reg_params, struct reg_param *reg_params,
1142 uint32_t buffer_start, uint32_t buffer_size,
1143 uint32_t entry_point, uint32_t exit_point, void *arch_info)
1148 const uint8_t *buffer_orig = buffer;
1150 /* Set up working area. First word is write pointer, second word is read pointer,
1151 * rest is fifo data area. */
1152 uint32_t wp_addr = buffer_start;
1153 uint32_t rp_addr = buffer_start + 4;
1154 uint32_t fifo_start_addr = buffer_start + 8;
1155 uint32_t fifo_end_addr = buffer_start + buffer_size;
1157 uint32_t wp = fifo_start_addr;
1158 uint32_t rp = fifo_start_addr;
1160 /* validate block_size is 2^n */
1161 assert(IS_PWR_OF_2(block_size));
1163 retval = target_write_u32(target, wp_addr, wp);
1164 if (retval != ERROR_OK)
1166 retval = target_write_u32(target, rp_addr, rp);
1167 if (retval != ERROR_OK)
1170 /* Start up algorithm on target */
1171 retval = target_start_algorithm(target, num_mem_params, mem_params,
1172 num_reg_params, reg_params,
1177 if (retval != ERROR_OK) {
1178 LOG_ERROR("error starting target flash read algorithm");
1183 retval = target_read_u32(target, wp_addr, &wp);
1184 if (retval != ERROR_OK) {
1185 LOG_ERROR("failed to get write pointer");
1189 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1190 (size_t)(buffer - buffer_orig), count, wp, rp);
1193 LOG_ERROR("flash read algorithm aborted by target");
1194 retval = ERROR_FLASH_OPERATION_FAILED;
1198 if (!IS_ALIGNED(wp - fifo_start_addr, block_size) || wp < fifo_start_addr || wp >= fifo_end_addr) {
1199 LOG_ERROR("corrupted fifo write pointer 0x%" PRIx32, wp);
1203 /* Count the number of bytes available in the fifo without
1204 * crossing the wrap around. */
1205 uint32_t thisrun_bytes;
1207 thisrun_bytes = wp - rp;
1209 thisrun_bytes = fifo_end_addr - rp;
1211 if (thisrun_bytes == 0) {
1212 /* Throttle polling a bit if transfer is (much) faster than flash
1213 * reading. The exact delay shouldn't matter as long as it's
1214 * less than buffer size / flash speed. This is very unlikely to
1215 * run when using high latency connections such as USB. */
1218 /* to stop an infinite loop on some targets check and increment a timeout
1219 * this issue was observed on a stellaris using the new ICDI interface */
1220 if (timeout++ >= 2500) {
1221 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1222 return ERROR_FLASH_OPERATION_FAILED;
1227 /* Reset our timeout */
1230 /* Limit to the amount of data we actually want to read */
1231 if (thisrun_bytes > count * block_size)
1232 thisrun_bytes = count * block_size;
1234 /* Force end of large blocks to be word aligned */
1235 if (thisrun_bytes >= 16)
1236 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1238 /* Read data from fifo */
1239 retval = target_read_buffer(target, rp, thisrun_bytes, buffer);
1240 if (retval != ERROR_OK)
1243 /* Update counters and wrap write pointer */
1244 buffer += thisrun_bytes;
1245 count -= thisrun_bytes / block_size;
1246 rp += thisrun_bytes;
1247 if (rp >= fifo_end_addr)
1248 rp = fifo_start_addr;
1250 /* Store updated write pointer to target */
1251 retval = target_write_u32(target, rp_addr, rp);
1252 if (retval != ERROR_OK)
1255 /* Avoid GDB timeouts */
1260 if (retval != ERROR_OK) {
1261 /* abort flash write algorithm on target */
1262 target_write_u32(target, rp_addr, 0);
1265 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1266 num_reg_params, reg_params,
1271 if (retval2 != ERROR_OK) {
1272 LOG_ERROR("error waiting for target flash write algorithm");
1276 if (retval == ERROR_OK) {
1277 /* check if algorithm set wp = 0 after fifo writer loop finished */
1278 retval = target_read_u32(target, wp_addr, &wp);
1279 if (retval == ERROR_OK && wp == 0) {
1280 LOG_ERROR("flash read algorithm aborted by target");
1281 retval = ERROR_FLASH_OPERATION_FAILED;
1288 int target_read_memory(struct target *target,
1289 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1291 if (!target_was_examined(target)) {
1292 LOG_ERROR("Target not examined yet");
1295 if (!target->type->read_memory) {
1296 LOG_ERROR("Target %s doesn't support read_memory", target_name(target));
1299 return target->type->read_memory(target, address, size, count, buffer);
1302 int target_read_phys_memory(struct target *target,
1303 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1305 if (!target_was_examined(target)) {
1306 LOG_ERROR("Target not examined yet");
1309 if (!target->type->read_phys_memory) {
1310 LOG_ERROR("Target %s doesn't support read_phys_memory", target_name(target));
1313 return target->type->read_phys_memory(target, address, size, count, buffer);
1316 int target_write_memory(struct target *target,
1317 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1319 if (!target_was_examined(target)) {
1320 LOG_ERROR("Target not examined yet");
1323 if (!target->type->write_memory) {
1324 LOG_ERROR("Target %s doesn't support write_memory", target_name(target));
1327 return target->type->write_memory(target, address, size, count, buffer);
1330 int target_write_phys_memory(struct target *target,
1331 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1333 if (!target_was_examined(target)) {
1334 LOG_ERROR("Target not examined yet");
1337 if (!target->type->write_phys_memory) {
1338 LOG_ERROR("Target %s doesn't support write_phys_memory", target_name(target));
1341 return target->type->write_phys_memory(target, address, size, count, buffer);
1344 int target_add_breakpoint(struct target *target,
1345 struct breakpoint *breakpoint)
1347 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1348 LOG_WARNING("target %s is not halted (add breakpoint)", target_name(target));
1349 return ERROR_TARGET_NOT_HALTED;
1351 return target->type->add_breakpoint(target, breakpoint);
1354 int target_add_context_breakpoint(struct target *target,
1355 struct breakpoint *breakpoint)
1357 if (target->state != TARGET_HALTED) {
1358 LOG_WARNING("target %s is not halted (add context breakpoint)", target_name(target));
1359 return ERROR_TARGET_NOT_HALTED;
1361 return target->type->add_context_breakpoint(target, breakpoint);
1364 int target_add_hybrid_breakpoint(struct target *target,
1365 struct breakpoint *breakpoint)
1367 if (target->state != TARGET_HALTED) {
1368 LOG_WARNING("target %s is not halted (add hybrid breakpoint)", target_name(target));
1369 return ERROR_TARGET_NOT_HALTED;
1371 return target->type->add_hybrid_breakpoint(target, breakpoint);
1374 int target_remove_breakpoint(struct target *target,
1375 struct breakpoint *breakpoint)
1377 return target->type->remove_breakpoint(target, breakpoint);
1380 int target_add_watchpoint(struct target *target,
1381 struct watchpoint *watchpoint)
1383 if (target->state != TARGET_HALTED) {
1384 LOG_WARNING("target %s is not halted (add watchpoint)", target_name(target));
1385 return ERROR_TARGET_NOT_HALTED;
1387 return target->type->add_watchpoint(target, watchpoint);
1389 int target_remove_watchpoint(struct target *target,
1390 struct watchpoint *watchpoint)
1392 return target->type->remove_watchpoint(target, watchpoint);
1394 int target_hit_watchpoint(struct target *target,
1395 struct watchpoint **hit_watchpoint)
1397 if (target->state != TARGET_HALTED) {
1398 LOG_WARNING("target %s is not halted (hit watchpoint)", target->cmd_name);
1399 return ERROR_TARGET_NOT_HALTED;
1402 if (!target->type->hit_watchpoint) {
1403 /* For backward compatible, if hit_watchpoint is not implemented,
1404 * return ERROR_FAIL such that gdb_server will not take the nonsense
1409 return target->type->hit_watchpoint(target, hit_watchpoint);
1412 const char *target_get_gdb_arch(struct target *target)
1414 if (!target->type->get_gdb_arch)
1416 return target->type->get_gdb_arch(target);
1419 int target_get_gdb_reg_list(struct target *target,
1420 struct reg **reg_list[], int *reg_list_size,
1421 enum target_register_class reg_class)
1423 int result = ERROR_FAIL;
1425 if (!target_was_examined(target)) {
1426 LOG_ERROR("Target not examined yet");
1430 result = target->type->get_gdb_reg_list(target, reg_list,
1431 reg_list_size, reg_class);
1434 if (result != ERROR_OK) {
1441 int target_get_gdb_reg_list_noread(struct target *target,
1442 struct reg **reg_list[], int *reg_list_size,
1443 enum target_register_class reg_class)
1445 if (target->type->get_gdb_reg_list_noread &&
1446 target->type->get_gdb_reg_list_noread(target, reg_list,
1447 reg_list_size, reg_class) == ERROR_OK)
1449 return target_get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1452 bool target_supports_gdb_connection(struct target *target)
1455 * exclude all the targets that don't provide get_gdb_reg_list
1456 * or that have explicit gdb_max_connection == 0
1458 return !!target->type->get_gdb_reg_list && !!target->gdb_max_connections;
1461 int target_step(struct target *target,
1462 int current, target_addr_t address, int handle_breakpoints)
1466 target_call_event_callbacks(target, TARGET_EVENT_STEP_START);
1468 retval = target->type->step(target, current, address, handle_breakpoints);
1469 if (retval != ERROR_OK)
1472 target_call_event_callbacks(target, TARGET_EVENT_STEP_END);
1477 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1479 if (target->state != TARGET_HALTED) {
1480 LOG_WARNING("target %s is not halted (gdb fileio)", target->cmd_name);
1481 return ERROR_TARGET_NOT_HALTED;
1483 return target->type->get_gdb_fileio_info(target, fileio_info);
1486 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1488 if (target->state != TARGET_HALTED) {
1489 LOG_WARNING("target %s is not halted (gdb fileio end)", target->cmd_name);
1490 return ERROR_TARGET_NOT_HALTED;
1492 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1495 target_addr_t target_address_max(struct target *target)
1497 unsigned bits = target_address_bits(target);
1498 if (sizeof(target_addr_t) * 8 == bits)
1499 return (target_addr_t) -1;
1501 return (((target_addr_t) 1) << bits) - 1;
1504 unsigned target_address_bits(struct target *target)
1506 if (target->type->address_bits)
1507 return target->type->address_bits(target);
1511 unsigned int target_data_bits(struct target *target)
1513 if (target->type->data_bits)
1514 return target->type->data_bits(target);
1518 static int target_profiling(struct target *target, uint32_t *samples,
1519 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1521 return target->type->profiling(target, samples, max_num_samples,
1522 num_samples, seconds);
1526 * Reset the @c examined flag for the given target.
1527 * Pure paranoia -- targets are zeroed on allocation.
1529 static void target_reset_examined(struct target *target)
1531 target->examined = false;
1534 static int handle_target(void *priv);
1536 static int target_init_one(struct command_context *cmd_ctx,
1537 struct target *target)
1539 target_reset_examined(target);
1541 struct target_type *type = target->type;
1543 type->examine = default_examine;
1545 if (!type->check_reset)
1546 type->check_reset = default_check_reset;
1548 assert(type->init_target);
1550 int retval = type->init_target(cmd_ctx, target);
1551 if (retval != ERROR_OK) {
1552 LOG_ERROR("target '%s' init failed", target_name(target));
1556 /* Sanity-check MMU support ... stub in what we must, to help
1557 * implement it in stages, but warn if we need to do so.
1560 if (!type->virt2phys) {
1561 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1562 type->virt2phys = identity_virt2phys;
1565 /* Make sure no-MMU targets all behave the same: make no
1566 * distinction between physical and virtual addresses, and
1567 * ensure that virt2phys() is always an identity mapping.
1569 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1570 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1573 type->write_phys_memory = type->write_memory;
1574 type->read_phys_memory = type->read_memory;
1575 type->virt2phys = identity_virt2phys;
1578 if (!target->type->read_buffer)
1579 target->type->read_buffer = target_read_buffer_default;
1581 if (!target->type->write_buffer)
1582 target->type->write_buffer = target_write_buffer_default;
1584 if (!target->type->get_gdb_fileio_info)
1585 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1587 if (!target->type->gdb_fileio_end)
1588 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1590 if (!target->type->profiling)
1591 target->type->profiling = target_profiling_default;
1596 static int target_init(struct command_context *cmd_ctx)
1598 struct target *target;
1601 for (target = all_targets; target; target = target->next) {
1602 retval = target_init_one(cmd_ctx, target);
1603 if (retval != ERROR_OK)
1610 retval = target_register_user_commands(cmd_ctx);
1611 if (retval != ERROR_OK)
1614 retval = target_register_timer_callback(&handle_target,
1615 polling_interval, TARGET_TIMER_TYPE_PERIODIC, cmd_ctx->interp);
1616 if (retval != ERROR_OK)
1622 COMMAND_HANDLER(handle_target_init_command)
1627 return ERROR_COMMAND_SYNTAX_ERROR;
1629 static bool target_initialized;
1630 if (target_initialized) {
1631 LOG_INFO("'target init' has already been called");
1634 target_initialized = true;
1636 retval = command_run_line(CMD_CTX, "init_targets");
1637 if (retval != ERROR_OK)
1640 retval = command_run_line(CMD_CTX, "init_target_events");
1641 if (retval != ERROR_OK)
1644 retval = command_run_line(CMD_CTX, "init_board");
1645 if (retval != ERROR_OK)
1648 LOG_DEBUG("Initializing targets...");
1649 return target_init(CMD_CTX);
1652 int target_register_event_callback(int (*callback)(struct target *target,
1653 enum target_event event, void *priv), void *priv)
1655 struct target_event_callback **callbacks_p = &target_event_callbacks;
1658 return ERROR_COMMAND_SYNTAX_ERROR;
1661 while ((*callbacks_p)->next)
1662 callbacks_p = &((*callbacks_p)->next);
1663 callbacks_p = &((*callbacks_p)->next);
1666 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1667 (*callbacks_p)->callback = callback;
1668 (*callbacks_p)->priv = priv;
1669 (*callbacks_p)->next = NULL;
1674 int target_register_reset_callback(int (*callback)(struct target *target,
1675 enum target_reset_mode reset_mode, void *priv), void *priv)
1677 struct target_reset_callback *entry;
1680 return ERROR_COMMAND_SYNTAX_ERROR;
1682 entry = malloc(sizeof(struct target_reset_callback));
1684 LOG_ERROR("error allocating buffer for reset callback entry");
1685 return ERROR_COMMAND_SYNTAX_ERROR;
1688 entry->callback = callback;
1690 list_add(&entry->list, &target_reset_callback_list);
1696 int target_register_trace_callback(int (*callback)(struct target *target,
1697 size_t len, uint8_t *data, void *priv), void *priv)
1699 struct target_trace_callback *entry;
1702 return ERROR_COMMAND_SYNTAX_ERROR;
1704 entry = malloc(sizeof(struct target_trace_callback));
1706 LOG_ERROR("error allocating buffer for trace callback entry");
1707 return ERROR_COMMAND_SYNTAX_ERROR;
1710 entry->callback = callback;
1712 list_add(&entry->list, &target_trace_callback_list);
1718 int target_register_timer_callback(int (*callback)(void *priv),
1719 unsigned int time_ms, enum target_timer_type type, void *priv)
1721 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1724 return ERROR_COMMAND_SYNTAX_ERROR;
1727 while ((*callbacks_p)->next)
1728 callbacks_p = &((*callbacks_p)->next);
1729 callbacks_p = &((*callbacks_p)->next);
1732 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1733 (*callbacks_p)->callback = callback;
1734 (*callbacks_p)->type = type;
1735 (*callbacks_p)->time_ms = time_ms;
1736 (*callbacks_p)->removed = false;
1738 (*callbacks_p)->when = timeval_ms() + time_ms;
1739 target_timer_next_event_value = MIN(target_timer_next_event_value, (*callbacks_p)->when);
1741 (*callbacks_p)->priv = priv;
1742 (*callbacks_p)->next = NULL;
1747 int target_unregister_event_callback(int (*callback)(struct target *target,
1748 enum target_event event, void *priv), void *priv)
1750 struct target_event_callback **p = &target_event_callbacks;
1751 struct target_event_callback *c = target_event_callbacks;
1754 return ERROR_COMMAND_SYNTAX_ERROR;
1757 struct target_event_callback *next = c->next;
1758 if ((c->callback == callback) && (c->priv == priv)) {
1770 int target_unregister_reset_callback(int (*callback)(struct target *target,
1771 enum target_reset_mode reset_mode, void *priv), void *priv)
1773 struct target_reset_callback *entry;
1776 return ERROR_COMMAND_SYNTAX_ERROR;
1778 list_for_each_entry(entry, &target_reset_callback_list, list) {
1779 if (entry->callback == callback && entry->priv == priv) {
1780 list_del(&entry->list);
1789 int target_unregister_trace_callback(int (*callback)(struct target *target,
1790 size_t len, uint8_t *data, void *priv), void *priv)
1792 struct target_trace_callback *entry;
1795 return ERROR_COMMAND_SYNTAX_ERROR;
1797 list_for_each_entry(entry, &target_trace_callback_list, list) {
1798 if (entry->callback == callback && entry->priv == priv) {
1799 list_del(&entry->list);
1808 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1811 return ERROR_COMMAND_SYNTAX_ERROR;
1813 for (struct target_timer_callback *c = target_timer_callbacks;
1815 if ((c->callback == callback) && (c->priv == priv)) {
1824 int target_call_event_callbacks(struct target *target, enum target_event event)
1826 struct target_event_callback *callback = target_event_callbacks;
1827 struct target_event_callback *next_callback;
1829 if (event == TARGET_EVENT_HALTED) {
1830 /* execute early halted first */
1831 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1834 LOG_DEBUG("target event %i (%s) for core %s", event,
1835 jim_nvp_value2name_simple(nvp_target_event, event)->name,
1836 target_name(target));
1838 target_handle_event(target, event);
1841 next_callback = callback->next;
1842 callback->callback(target, event, callback->priv);
1843 callback = next_callback;
1849 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1851 struct target_reset_callback *callback;
1853 LOG_DEBUG("target reset %i (%s)", reset_mode,
1854 jim_nvp_value2name_simple(nvp_reset_modes, reset_mode)->name);
1856 list_for_each_entry(callback, &target_reset_callback_list, list)
1857 callback->callback(target, reset_mode, callback->priv);
1862 int target_call_trace_callbacks(struct target *target, size_t len, uint8_t *data)
1864 struct target_trace_callback *callback;
1866 list_for_each_entry(callback, &target_trace_callback_list, list)
1867 callback->callback(target, len, data, callback->priv);
1872 static int target_timer_callback_periodic_restart(
1873 struct target_timer_callback *cb, int64_t *now)
1875 cb->when = *now + cb->time_ms;
1879 static int target_call_timer_callback(struct target_timer_callback *cb,
1882 cb->callback(cb->priv);
1884 if (cb->type == TARGET_TIMER_TYPE_PERIODIC)
1885 return target_timer_callback_periodic_restart(cb, now);
1887 return target_unregister_timer_callback(cb->callback, cb->priv);
1890 static int target_call_timer_callbacks_check_time(int checktime)
1892 static bool callback_processing;
1894 /* Do not allow nesting */
1895 if (callback_processing)
1898 callback_processing = true;
1902 int64_t now = timeval_ms();
1904 /* Initialize to a default value that's a ways into the future.
1905 * The loop below will make it closer to now if there are
1906 * callbacks that want to be called sooner. */
1907 target_timer_next_event_value = now + 1000;
1909 /* Store an address of the place containing a pointer to the
1910 * next item; initially, that's a standalone "root of the
1911 * list" variable. */
1912 struct target_timer_callback **callback = &target_timer_callbacks;
1913 while (callback && *callback) {
1914 if ((*callback)->removed) {
1915 struct target_timer_callback *p = *callback;
1916 *callback = (*callback)->next;
1921 bool call_it = (*callback)->callback &&
1922 ((!checktime && (*callback)->type == TARGET_TIMER_TYPE_PERIODIC) ||
1923 now >= (*callback)->when);
1926 target_call_timer_callback(*callback, &now);
1928 if (!(*callback)->removed && (*callback)->when < target_timer_next_event_value)
1929 target_timer_next_event_value = (*callback)->when;
1931 callback = &(*callback)->next;
1934 callback_processing = false;
1938 int target_call_timer_callbacks()
1940 return target_call_timer_callbacks_check_time(1);
1943 /* invoke periodic callbacks immediately */
1944 int target_call_timer_callbacks_now()
1946 return target_call_timer_callbacks_check_time(0);
1949 int64_t target_timer_next_event(void)
1951 return target_timer_next_event_value;
1954 /* Prints the working area layout for debug purposes */
1955 static void print_wa_layout(struct target *target)
1957 struct working_area *c = target->working_areas;
1960 LOG_DEBUG("%c%c " TARGET_ADDR_FMT "-" TARGET_ADDR_FMT " (%" PRIu32 " bytes)",
1961 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1962 c->address, c->address + c->size - 1, c->size);
1967 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1968 static void target_split_working_area(struct working_area *area, uint32_t size)
1970 assert(area->free); /* Shouldn't split an allocated area */
1971 assert(size <= area->size); /* Caller should guarantee this */
1973 /* Split only if not already the right size */
1974 if (size < area->size) {
1975 struct working_area *new_wa = malloc(sizeof(*new_wa));
1980 new_wa->next = area->next;
1981 new_wa->size = area->size - size;
1982 new_wa->address = area->address + size;
1983 new_wa->backup = NULL;
1984 new_wa->user = NULL;
1985 new_wa->free = true;
1987 area->next = new_wa;
1990 /* If backup memory was allocated to this area, it has the wrong size
1991 * now so free it and it will be reallocated if/when needed */
1993 area->backup = NULL;
1997 /* Merge all adjacent free areas into one */
1998 static void target_merge_working_areas(struct target *target)
2000 struct working_area *c = target->working_areas;
2002 while (c && c->next) {
2003 assert(c->next->address == c->address + c->size); /* This is an invariant */
2005 /* Find two adjacent free areas */
2006 if (c->free && c->next->free) {
2007 /* Merge the last into the first */
2008 c->size += c->next->size;
2010 /* Remove the last */
2011 struct working_area *to_be_freed = c->next;
2012 c->next = c->next->next;
2013 free(to_be_freed->backup);
2016 /* If backup memory was allocated to the remaining area, it's has
2017 * the wrong size now */
2026 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
2028 /* Reevaluate working area address based on MMU state*/
2029 if (!target->working_areas) {
2033 retval = target->type->mmu(target, &enabled);
2034 if (retval != ERROR_OK)
2038 if (target->working_area_phys_spec) {
2039 LOG_DEBUG("MMU disabled, using physical "
2040 "address for working memory " TARGET_ADDR_FMT,
2041 target->working_area_phys);
2042 target->working_area = target->working_area_phys;
2044 LOG_ERROR("No working memory available. "
2045 "Specify -work-area-phys to target.");
2046 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2049 if (target->working_area_virt_spec) {
2050 LOG_DEBUG("MMU enabled, using virtual "
2051 "address for working memory " TARGET_ADDR_FMT,
2052 target->working_area_virt);
2053 target->working_area = target->working_area_virt;
2055 LOG_ERROR("No working memory available. "
2056 "Specify -work-area-virt to target.");
2057 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2061 /* Set up initial working area on first call */
2062 struct working_area *new_wa = malloc(sizeof(*new_wa));
2064 new_wa->next = NULL;
2065 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
2066 new_wa->address = target->working_area;
2067 new_wa->backup = NULL;
2068 new_wa->user = NULL;
2069 new_wa->free = true;
2072 target->working_areas = new_wa;
2075 /* only allocate multiples of 4 byte */
2077 size = (size + 3) & (~3UL);
2079 struct working_area *c = target->working_areas;
2081 /* Find the first large enough working area */
2083 if (c->free && c->size >= size)
2089 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2091 /* Split the working area into the requested size */
2092 target_split_working_area(c, size);
2094 LOG_DEBUG("allocated new working area of %" PRIu32 " bytes at address " TARGET_ADDR_FMT,
2097 if (target->backup_working_area) {
2099 c->backup = malloc(c->size);
2104 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
2105 if (retval != ERROR_OK)
2109 /* mark as used, and return the new (reused) area */
2116 print_wa_layout(target);
2121 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
2125 retval = target_alloc_working_area_try(target, size, area);
2126 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
2127 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
2132 static int target_restore_working_area(struct target *target, struct working_area *area)
2134 int retval = ERROR_OK;
2136 if (target->backup_working_area && area->backup) {
2137 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
2138 if (retval != ERROR_OK)
2139 LOG_ERROR("failed to restore %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2140 area->size, area->address);
2146 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
2147 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
2149 int retval = ERROR_OK;
2155 retval = target_restore_working_area(target, area);
2156 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
2157 if (retval != ERROR_OK)
2163 LOG_DEBUG("freed %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2164 area->size, area->address);
2166 /* mark user pointer invalid */
2167 /* TODO: Is this really safe? It points to some previous caller's memory.
2168 * How could we know that the area pointer is still in that place and not
2169 * some other vital data? What's the purpose of this, anyway? */
2173 target_merge_working_areas(target);
2175 print_wa_layout(target);
2180 int target_free_working_area(struct target *target, struct working_area *area)
2182 return target_free_working_area_restore(target, area, 1);
2185 /* free resources and restore memory, if restoring memory fails,
2186 * free up resources anyway
2188 static void target_free_all_working_areas_restore(struct target *target, int restore)
2190 struct working_area *c = target->working_areas;
2192 LOG_DEBUG("freeing all working areas");
2194 /* Loop through all areas, restoring the allocated ones and marking them as free */
2198 target_restore_working_area(target, c);
2200 *c->user = NULL; /* Same as above */
2206 /* Run a merge pass to combine all areas into one */
2207 target_merge_working_areas(target);
2209 print_wa_layout(target);
2212 void target_free_all_working_areas(struct target *target)
2214 target_free_all_working_areas_restore(target, 1);
2216 /* Now we have none or only one working area marked as free */
2217 if (target->working_areas) {
2218 /* Free the last one to allow on-the-fly moving and resizing */
2219 free(target->working_areas->backup);
2220 free(target->working_areas);
2221 target->working_areas = NULL;
2225 /* Find the largest number of bytes that can be allocated */
2226 uint32_t target_get_working_area_avail(struct target *target)
2228 struct working_area *c = target->working_areas;
2229 uint32_t max_size = 0;
2232 return target->working_area_size;
2235 if (c->free && max_size < c->size)
2244 static void target_destroy(struct target *target)
2246 if (target->type->deinit_target)
2247 target->type->deinit_target(target);
2249 free(target->semihosting);
2251 jtag_unregister_event_callback(jtag_enable_callback, target);
2253 struct target_event_action *teap = target->event_action;
2255 struct target_event_action *next = teap->next;
2256 Jim_DecrRefCount(teap->interp, teap->body);
2261 target_free_all_working_areas(target);
2263 /* release the targets SMP list */
2265 struct target_list *head = target->head;
2267 struct target_list *pos = head->next;
2268 head->target->smp = 0;
2275 rtos_destroy(target);
2277 free(target->gdb_port_override);
2279 free(target->trace_info);
2280 free(target->fileio_info);
2281 free(target->cmd_name);
2285 void target_quit(void)
2287 struct target_event_callback *pe = target_event_callbacks;
2289 struct target_event_callback *t = pe->next;
2293 target_event_callbacks = NULL;
2295 struct target_timer_callback *pt = target_timer_callbacks;
2297 struct target_timer_callback *t = pt->next;
2301 target_timer_callbacks = NULL;
2303 for (struct target *target = all_targets; target;) {
2307 target_destroy(target);
2314 int target_arch_state(struct target *target)
2318 LOG_WARNING("No target has been configured");
2322 if (target->state != TARGET_HALTED)
2325 retval = target->type->arch_state(target);
2329 static int target_get_gdb_fileio_info_default(struct target *target,
2330 struct gdb_fileio_info *fileio_info)
2332 /* If target does not support semi-hosting function, target
2333 has no need to provide .get_gdb_fileio_info callback.
2334 It just return ERROR_FAIL and gdb_server will return "Txx"
2335 as target halted every time. */
2339 static int target_gdb_fileio_end_default(struct target *target,
2340 int retcode, int fileio_errno, bool ctrl_c)
2345 int target_profiling_default(struct target *target, uint32_t *samples,
2346 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
2348 struct timeval timeout, now;
2350 gettimeofday(&timeout, NULL);
2351 timeval_add_time(&timeout, seconds, 0);
2353 LOG_INFO("Starting profiling. Halting and resuming the"
2354 " target as often as we can...");
2356 uint32_t sample_count = 0;
2357 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2358 struct reg *reg = register_get_by_name(target->reg_cache, "pc", true);
2360 int retval = ERROR_OK;
2362 target_poll(target);
2363 if (target->state == TARGET_HALTED) {
2364 uint32_t t = buf_get_u32(reg->value, 0, 32);
2365 samples[sample_count++] = t;
2366 /* current pc, addr = 0, do not handle breakpoints, not debugging */
2367 retval = target_resume(target, 1, 0, 0, 0);
2368 target_poll(target);
2369 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2370 } else if (target->state == TARGET_RUNNING) {
2371 /* We want to quickly sample the PC. */
2372 retval = target_halt(target);
2374 LOG_INFO("Target not halted or running");
2379 if (retval != ERROR_OK)
2382 gettimeofday(&now, NULL);
2383 if ((sample_count >= max_num_samples) || timeval_compare(&now, &timeout) >= 0) {
2384 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2389 *num_samples = sample_count;
2393 /* Single aligned words are guaranteed to use 16 or 32 bit access
2394 * mode respectively, otherwise data is handled as quickly as
2397 int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
2399 LOG_DEBUG("writing buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2402 if (!target_was_examined(target)) {
2403 LOG_ERROR("Target not examined yet");
2410 if ((address + size - 1) < address) {
2411 /* GDB can request this when e.g. PC is 0xfffffffc */
2412 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2418 return target->type->write_buffer(target, address, size, buffer);
2421 static int target_write_buffer_default(struct target *target,
2422 target_addr_t address, uint32_t count, const uint8_t *buffer)
2425 unsigned int data_bytes = target_data_bits(target) / 8;
2427 /* Align up to maximum bytes. The loop condition makes sure the next pass
2428 * will have something to do with the size we leave to it. */
2430 size < data_bytes && count >= size * 2 + (address & size);
2432 if (address & size) {
2433 int retval = target_write_memory(target, address, size, 1, buffer);
2434 if (retval != ERROR_OK)
2442 /* Write the data with as large access size as possible. */
2443 for (; size > 0; size /= 2) {
2444 uint32_t aligned = count - count % size;
2446 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2447 if (retval != ERROR_OK)
2458 /* Single aligned words are guaranteed to use 16 or 32 bit access
2459 * mode respectively, otherwise data is handled as quickly as
2462 int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
2464 LOG_DEBUG("reading buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2467 if (!target_was_examined(target)) {
2468 LOG_ERROR("Target not examined yet");
2475 if ((address + size - 1) < address) {
2476 /* GDB can request this when e.g. PC is 0xfffffffc */
2477 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2483 return target->type->read_buffer(target, address, size, buffer);
2486 static int target_read_buffer_default(struct target *target, target_addr_t address, uint32_t count, uint8_t *buffer)
2489 unsigned int data_bytes = target_data_bits(target) / 8;
2491 /* Align up to maximum bytes. The loop condition makes sure the next pass
2492 * will have something to do with the size we leave to it. */
2494 size < data_bytes && count >= size * 2 + (address & size);
2496 if (address & size) {
2497 int retval = target_read_memory(target, address, size, 1, buffer);
2498 if (retval != ERROR_OK)
2506 /* Read the data with as large access size as possible. */
2507 for (; size > 0; size /= 2) {
2508 uint32_t aligned = count - count % size;
2510 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2511 if (retval != ERROR_OK)
2522 int target_checksum_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t *crc)
2527 uint32_t checksum = 0;
2528 if (!target_was_examined(target)) {
2529 LOG_ERROR("Target not examined yet");
2533 retval = target->type->checksum_memory(target, address, size, &checksum);
2534 if (retval != ERROR_OK) {
2535 buffer = malloc(size);
2537 LOG_ERROR("error allocating buffer for section (%" PRIu32 " bytes)", size);
2538 return ERROR_COMMAND_SYNTAX_ERROR;
2540 retval = target_read_buffer(target, address, size, buffer);
2541 if (retval != ERROR_OK) {
2546 /* convert to target endianness */
2547 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2548 uint32_t target_data;
2549 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2550 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2553 retval = image_calculate_checksum(buffer, size, &checksum);
2562 int target_blank_check_memory(struct target *target,
2563 struct target_memory_check_block *blocks, int num_blocks,
2564 uint8_t erased_value)
2566 if (!target_was_examined(target)) {
2567 LOG_ERROR("Target not examined yet");
2571 if (!target->type->blank_check_memory)
2572 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2574 return target->type->blank_check_memory(target, blocks, num_blocks, erased_value);
2577 int target_read_u64(struct target *target, target_addr_t address, uint64_t *value)
2579 uint8_t value_buf[8];
2580 if (!target_was_examined(target)) {
2581 LOG_ERROR("Target not examined yet");
2585 int retval = target_read_memory(target, address, 8, 1, value_buf);
2587 if (retval == ERROR_OK) {
2588 *value = target_buffer_get_u64(target, value_buf);
2589 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2594 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2601 int target_read_u32(struct target *target, target_addr_t address, uint32_t *value)
2603 uint8_t value_buf[4];
2604 if (!target_was_examined(target)) {
2605 LOG_ERROR("Target not examined yet");
2609 int retval = target_read_memory(target, address, 4, 1, value_buf);
2611 if (retval == ERROR_OK) {
2612 *value = target_buffer_get_u32(target, value_buf);
2613 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2618 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2625 int target_read_u16(struct target *target, target_addr_t address, uint16_t *value)
2627 uint8_t value_buf[2];
2628 if (!target_was_examined(target)) {
2629 LOG_ERROR("Target not examined yet");
2633 int retval = target_read_memory(target, address, 2, 1, value_buf);
2635 if (retval == ERROR_OK) {
2636 *value = target_buffer_get_u16(target, value_buf);
2637 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%4.4" PRIx16,
2642 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2649 int target_read_u8(struct target *target, target_addr_t address, uint8_t *value)
2651 if (!target_was_examined(target)) {
2652 LOG_ERROR("Target not examined yet");
2656 int retval = target_read_memory(target, address, 1, 1, value);
2658 if (retval == ERROR_OK) {
2659 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2664 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2671 int target_write_u64(struct target *target, target_addr_t address, uint64_t value)
2674 uint8_t value_buf[8];
2675 if (!target_was_examined(target)) {
2676 LOG_ERROR("Target not examined yet");
2680 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2684 target_buffer_set_u64(target, value_buf, value);
2685 retval = target_write_memory(target, address, 8, 1, value_buf);
2686 if (retval != ERROR_OK)
2687 LOG_DEBUG("failed: %i", retval);
2692 int target_write_u32(struct target *target, target_addr_t address, uint32_t value)
2695 uint8_t value_buf[4];
2696 if (!target_was_examined(target)) {
2697 LOG_ERROR("Target not examined yet");
2701 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2705 target_buffer_set_u32(target, value_buf, value);
2706 retval = target_write_memory(target, address, 4, 1, value_buf);
2707 if (retval != ERROR_OK)
2708 LOG_DEBUG("failed: %i", retval);
2713 int target_write_u16(struct target *target, target_addr_t address, uint16_t value)
2716 uint8_t value_buf[2];
2717 if (!target_was_examined(target)) {
2718 LOG_ERROR("Target not examined yet");
2722 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2726 target_buffer_set_u16(target, value_buf, value);
2727 retval = target_write_memory(target, address, 2, 1, value_buf);
2728 if (retval != ERROR_OK)
2729 LOG_DEBUG("failed: %i", retval);
2734 int target_write_u8(struct target *target, target_addr_t address, uint8_t value)
2737 if (!target_was_examined(target)) {
2738 LOG_ERROR("Target not examined yet");
2742 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2745 retval = target_write_memory(target, address, 1, 1, &value);
2746 if (retval != ERROR_OK)
2747 LOG_DEBUG("failed: %i", retval);
2752 int target_write_phys_u64(struct target *target, target_addr_t address, uint64_t value)
2755 uint8_t value_buf[8];
2756 if (!target_was_examined(target)) {
2757 LOG_ERROR("Target not examined yet");
2761 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2765 target_buffer_set_u64(target, value_buf, value);
2766 retval = target_write_phys_memory(target, address, 8, 1, value_buf);
2767 if (retval != ERROR_OK)
2768 LOG_DEBUG("failed: %i", retval);
2773 int target_write_phys_u32(struct target *target, target_addr_t address, uint32_t value)
2776 uint8_t value_buf[4];
2777 if (!target_was_examined(target)) {
2778 LOG_ERROR("Target not examined yet");
2782 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2786 target_buffer_set_u32(target, value_buf, value);
2787 retval = target_write_phys_memory(target, address, 4, 1, value_buf);
2788 if (retval != ERROR_OK)
2789 LOG_DEBUG("failed: %i", retval);
2794 int target_write_phys_u16(struct target *target, target_addr_t address, uint16_t value)
2797 uint8_t value_buf[2];
2798 if (!target_was_examined(target)) {
2799 LOG_ERROR("Target not examined yet");
2803 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2807 target_buffer_set_u16(target, value_buf, value);
2808 retval = target_write_phys_memory(target, address, 2, 1, value_buf);
2809 if (retval != ERROR_OK)
2810 LOG_DEBUG("failed: %i", retval);
2815 int target_write_phys_u8(struct target *target, target_addr_t address, uint8_t value)
2818 if (!target_was_examined(target)) {
2819 LOG_ERROR("Target not examined yet");
2823 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2826 retval = target_write_phys_memory(target, address, 1, 1, &value);
2827 if (retval != ERROR_OK)
2828 LOG_DEBUG("failed: %i", retval);
2833 static int find_target(struct command_invocation *cmd, const char *name)
2835 struct target *target = get_target(name);
2837 command_print(cmd, "Target: %s is unknown, try one of:\n", name);
2840 if (!target->tap->enabled) {
2841 command_print(cmd, "Target: TAP %s is disabled, "
2842 "can't be the current target\n",
2843 target->tap->dotted_name);
2847 cmd->ctx->current_target = target;
2848 if (cmd->ctx->current_target_override)
2849 cmd->ctx->current_target_override = target;
2855 COMMAND_HANDLER(handle_targets_command)
2857 int retval = ERROR_OK;
2858 if (CMD_ARGC == 1) {
2859 retval = find_target(CMD, CMD_ARGV[0]);
2860 if (retval == ERROR_OK) {
2866 struct target *target = all_targets;
2867 command_print(CMD, " TargetName Type Endian TapName State ");
2868 command_print(CMD, "-- ------------------ ---------- ------ ------------------ ------------");
2873 if (target->tap->enabled)
2874 state = target_state_name(target);
2876 state = "tap-disabled";
2878 if (CMD_CTX->current_target == target)
2881 /* keep columns lined up to match the headers above */
2883 "%2d%c %-18s %-10s %-6s %-18s %s",
2884 target->target_number,
2886 target_name(target),
2887 target_type_name(target),
2888 jim_nvp_value2name_simple(nvp_target_endian,
2889 target->endianness)->name,
2890 target->tap->dotted_name,
2892 target = target->next;
2898 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2900 static int power_dropout;
2901 static int srst_asserted;
2903 static int run_power_restore;
2904 static int run_power_dropout;
2905 static int run_srst_asserted;
2906 static int run_srst_deasserted;
2908 static int sense_handler(void)
2910 static int prev_srst_asserted;
2911 static int prev_power_dropout;
2913 int retval = jtag_power_dropout(&power_dropout);
2914 if (retval != ERROR_OK)
2918 power_restored = prev_power_dropout && !power_dropout;
2920 run_power_restore = 1;
2922 int64_t current = timeval_ms();
2923 static int64_t last_power;
2924 bool wait_more = last_power + 2000 > current;
2925 if (power_dropout && !wait_more) {
2926 run_power_dropout = 1;
2927 last_power = current;
2930 retval = jtag_srst_asserted(&srst_asserted);
2931 if (retval != ERROR_OK)
2934 int srst_deasserted;
2935 srst_deasserted = prev_srst_asserted && !srst_asserted;
2937 static int64_t last_srst;
2938 wait_more = last_srst + 2000 > current;
2939 if (srst_deasserted && !wait_more) {
2940 run_srst_deasserted = 1;
2941 last_srst = current;
2944 if (!prev_srst_asserted && srst_asserted)
2945 run_srst_asserted = 1;
2947 prev_srst_asserted = srst_asserted;
2948 prev_power_dropout = power_dropout;
2950 if (srst_deasserted || power_restored) {
2951 /* Other than logging the event we can't do anything here.
2952 * Issuing a reset is a particularly bad idea as we might
2953 * be inside a reset already.
2960 /* process target state changes */
2961 static int handle_target(void *priv)
2963 Jim_Interp *interp = (Jim_Interp *)priv;
2964 int retval = ERROR_OK;
2966 if (!is_jtag_poll_safe()) {
2967 /* polling is disabled currently */
2971 /* we do not want to recurse here... */
2972 static int recursive;
2976 /* danger! running these procedures can trigger srst assertions and power dropouts.
2977 * We need to avoid an infinite loop/recursion here and we do that by
2978 * clearing the flags after running these events.
2980 int did_something = 0;
2981 if (run_srst_asserted) {
2982 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2983 Jim_Eval(interp, "srst_asserted");
2986 if (run_srst_deasserted) {
2987 Jim_Eval(interp, "srst_deasserted");
2990 if (run_power_dropout) {
2991 LOG_INFO("Power dropout detected, running power_dropout proc.");
2992 Jim_Eval(interp, "power_dropout");
2995 if (run_power_restore) {
2996 Jim_Eval(interp, "power_restore");
3000 if (did_something) {
3001 /* clear detect flags */
3005 /* clear action flags */
3007 run_srst_asserted = 0;
3008 run_srst_deasserted = 0;
3009 run_power_restore = 0;
3010 run_power_dropout = 0;
3015 /* Poll targets for state changes unless that's globally disabled.
3016 * Skip targets that are currently disabled.
3018 for (struct target *target = all_targets;
3019 is_jtag_poll_safe() && target;
3020 target = target->next) {
3022 if (!target_was_examined(target))
3025 if (!target->tap->enabled)
3028 if (target->backoff.times > target->backoff.count) {
3029 /* do not poll this time as we failed previously */
3030 target->backoff.count++;
3033 target->backoff.count = 0;
3035 /* only poll target if we've got power and srst isn't asserted */
3036 if (!power_dropout && !srst_asserted) {
3037 /* polling may fail silently until the target has been examined */
3038 retval = target_poll(target);
3039 if (retval != ERROR_OK) {
3040 /* 100ms polling interval. Increase interval between polling up to 5000ms */
3041 if (target->backoff.times * polling_interval < 5000) {
3042 target->backoff.times *= 2;
3043 target->backoff.times++;
3046 /* Tell GDB to halt the debugger. This allows the user to
3047 * run monitor commands to handle the situation.
3049 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3051 if (target->backoff.times > 0) {
3052 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
3053 target_reset_examined(target);
3054 retval = target_examine_one(target);
3055 /* Target examination could have failed due to unstable connection,
3056 * but we set the examined flag anyway to repoll it later */
3057 if (retval != ERROR_OK) {
3058 target->examined = true;
3059 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
3060 target->backoff.times * polling_interval);
3065 /* Since we succeeded, we reset backoff count */
3066 target->backoff.times = 0;
3073 COMMAND_HANDLER(handle_reg_command)
3077 struct target *target = get_current_target(CMD_CTX);
3078 struct reg *reg = NULL;
3080 /* list all available registers for the current target */
3081 if (CMD_ARGC == 0) {
3082 struct reg_cache *cache = target->reg_cache;
3084 unsigned int count = 0;
3088 command_print(CMD, "===== %s", cache->name);
3090 for (i = 0, reg = cache->reg_list;
3091 i < cache->num_regs;
3092 i++, reg++, count++) {
3093 if (reg->exist == false || reg->hidden)
3095 /* only print cached values if they are valid */
3097 char *value = buf_to_hex_str(reg->value,
3100 "(%i) %s (/%" PRIu32 "): 0x%s%s",
3108 command_print(CMD, "(%i) %s (/%" PRIu32 ")",
3113 cache = cache->next;
3119 /* access a single register by its ordinal number */
3120 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
3122 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
3124 struct reg_cache *cache = target->reg_cache;
3125 unsigned int count = 0;
3128 for (i = 0; i < cache->num_regs; i++) {
3129 if (count++ == num) {
3130 reg = &cache->reg_list[i];
3136 cache = cache->next;
3140 command_print(CMD, "%i is out of bounds, the current target "
3141 "has only %i registers (0 - %i)", num, count, count - 1);
3145 /* access a single register by its name */
3146 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], true);
3152 assert(reg); /* give clang a hint that we *know* reg is != NULL here */
3157 /* display a register */
3158 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
3159 && (CMD_ARGV[1][0] <= '9')))) {
3160 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
3163 if (reg->valid == 0) {
3164 int retval = reg->type->get(reg);
3165 if (retval != ERROR_OK) {
3166 LOG_ERROR("Could not read register '%s'", reg->name);
3170 char *value = buf_to_hex_str(reg->value, reg->size);
3171 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3176 /* set register value */
3177 if (CMD_ARGC == 2) {
3178 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
3181 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
3183 int retval = reg->type->set(reg, buf);
3184 if (retval != ERROR_OK) {
3185 LOG_ERROR("Could not write to register '%s'", reg->name);
3187 char *value = buf_to_hex_str(reg->value, reg->size);
3188 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3197 return ERROR_COMMAND_SYNTAX_ERROR;
3200 command_print(CMD, "register %s not found in current target", CMD_ARGV[0]);
3204 COMMAND_HANDLER(handle_poll_command)
3206 int retval = ERROR_OK;
3207 struct target *target = get_current_target(CMD_CTX);
3209 if (CMD_ARGC == 0) {
3210 command_print(CMD, "background polling: %s",
3211 jtag_poll_get_enabled() ? "on" : "off");
3212 command_print(CMD, "TAP: %s (%s)",
3213 target->tap->dotted_name,
3214 target->tap->enabled ? "enabled" : "disabled");
3215 if (!target->tap->enabled)
3217 retval = target_poll(target);
3218 if (retval != ERROR_OK)
3220 retval = target_arch_state(target);
3221 if (retval != ERROR_OK)
3223 } else if (CMD_ARGC == 1) {
3225 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
3226 jtag_poll_set_enabled(enable);
3228 return ERROR_COMMAND_SYNTAX_ERROR;
3233 COMMAND_HANDLER(handle_wait_halt_command)
3236 return ERROR_COMMAND_SYNTAX_ERROR;
3238 unsigned ms = DEFAULT_HALT_TIMEOUT;
3239 if (1 == CMD_ARGC) {
3240 int retval = parse_uint(CMD_ARGV[0], &ms);
3241 if (retval != ERROR_OK)
3242 return ERROR_COMMAND_SYNTAX_ERROR;
3245 struct target *target = get_current_target(CMD_CTX);
3246 return target_wait_state(target, TARGET_HALTED, ms);
3249 /* wait for target state to change. The trick here is to have a low
3250 * latency for short waits and not to suck up all the CPU time
3253 * After 500ms, keep_alive() is invoked
3255 int target_wait_state(struct target *target, enum target_state state, int ms)
3258 int64_t then = 0, cur;
3262 retval = target_poll(target);
3263 if (retval != ERROR_OK)
3265 if (target->state == state)
3270 then = timeval_ms();
3271 LOG_DEBUG("waiting for target %s...",
3272 jim_nvp_value2name_simple(nvp_target_state, state)->name);
3278 if ((cur-then) > ms) {
3279 LOG_ERROR("timed out while waiting for target %s",
3280 jim_nvp_value2name_simple(nvp_target_state, state)->name);
3288 COMMAND_HANDLER(handle_halt_command)
3292 struct target *target = get_current_target(CMD_CTX);
3294 target->verbose_halt_msg = true;
3296 int retval = target_halt(target);
3297 if (retval != ERROR_OK)
3300 if (CMD_ARGC == 1) {
3301 unsigned wait_local;
3302 retval = parse_uint(CMD_ARGV[0], &wait_local);
3303 if (retval != ERROR_OK)
3304 return ERROR_COMMAND_SYNTAX_ERROR;
3309 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
3312 COMMAND_HANDLER(handle_soft_reset_halt_command)
3314 struct target *target = get_current_target(CMD_CTX);
3316 LOG_USER("requesting target halt and executing a soft reset");
3318 target_soft_reset_halt(target);
3323 COMMAND_HANDLER(handle_reset_command)
3326 return ERROR_COMMAND_SYNTAX_ERROR;
3328 enum target_reset_mode reset_mode = RESET_RUN;
3329 if (CMD_ARGC == 1) {
3330 const struct jim_nvp *n;
3331 n = jim_nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
3332 if ((!n->name) || (n->value == RESET_UNKNOWN))
3333 return ERROR_COMMAND_SYNTAX_ERROR;
3334 reset_mode = n->value;
3337 /* reset *all* targets */
3338 return target_process_reset(CMD, reset_mode);
3342 COMMAND_HANDLER(handle_resume_command)
3346 return ERROR_COMMAND_SYNTAX_ERROR;
3348 struct target *target = get_current_target(CMD_CTX);
3350 /* with no CMD_ARGV, resume from current pc, addr = 0,
3351 * with one arguments, addr = CMD_ARGV[0],
3352 * handle breakpoints, not debugging */
3353 target_addr_t addr = 0;
3354 if (CMD_ARGC == 1) {
3355 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3359 return target_resume(target, current, addr, 1, 0);
3362 COMMAND_HANDLER(handle_step_command)
3365 return ERROR_COMMAND_SYNTAX_ERROR;
3369 /* with no CMD_ARGV, step from current pc, addr = 0,
3370 * with one argument addr = CMD_ARGV[0],
3371 * handle breakpoints, debugging */
3372 target_addr_t addr = 0;
3374 if (CMD_ARGC == 1) {
3375 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3379 struct target *target = get_current_target(CMD_CTX);
3381 return target_step(target, current_pc, addr, 1);
3384 void target_handle_md_output(struct command_invocation *cmd,
3385 struct target *target, target_addr_t address, unsigned size,
3386 unsigned count, const uint8_t *buffer)
3388 const unsigned line_bytecnt = 32;
3389 unsigned line_modulo = line_bytecnt / size;
3391 char output[line_bytecnt * 4 + 1];
3392 unsigned output_len = 0;
3394 const char *value_fmt;
3397 value_fmt = "%16.16"PRIx64" ";
3400 value_fmt = "%8.8"PRIx64" ";
3403 value_fmt = "%4.4"PRIx64" ";
3406 value_fmt = "%2.2"PRIx64" ";
3409 /* "can't happen", caller checked */
3410 LOG_ERROR("invalid memory read size: %u", size);
3414 for (unsigned i = 0; i < count; i++) {
3415 if (i % line_modulo == 0) {
3416 output_len += snprintf(output + output_len,
3417 sizeof(output) - output_len,
3418 TARGET_ADDR_FMT ": ",
3419 (address + (i * size)));
3423 const uint8_t *value_ptr = buffer + i * size;
3426 value = target_buffer_get_u64(target, value_ptr);
3429 value = target_buffer_get_u32(target, value_ptr);
3432 value = target_buffer_get_u16(target, value_ptr);
3437 output_len += snprintf(output + output_len,
3438 sizeof(output) - output_len,
3441 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
3442 command_print(cmd, "%s", output);
3448 COMMAND_HANDLER(handle_md_command)
3451 return ERROR_COMMAND_SYNTAX_ERROR;
3454 switch (CMD_NAME[2]) {
3468 return ERROR_COMMAND_SYNTAX_ERROR;
3471 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3472 int (*fn)(struct target *target,
3473 target_addr_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
3477 fn = target_read_phys_memory;
3479 fn = target_read_memory;
3480 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
3481 return ERROR_COMMAND_SYNTAX_ERROR;
3483 target_addr_t address;
3484 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3488 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3490 uint8_t *buffer = calloc(count, size);
3492 LOG_ERROR("Failed to allocate md read buffer");
3496 struct target *target = get_current_target(CMD_CTX);
3497 int retval = fn(target, address, size, count, buffer);
3498 if (retval == ERROR_OK)
3499 target_handle_md_output(CMD, target, address, size, count, buffer);
3506 typedef int (*target_write_fn)(struct target *target,
3507 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3509 static int target_fill_mem(struct target *target,
3510 target_addr_t address,
3518 /* We have to write in reasonably large chunks to be able
3519 * to fill large memory areas with any sane speed */
3520 const unsigned chunk_size = 16384;
3521 uint8_t *target_buf = malloc(chunk_size * data_size);
3523 LOG_ERROR("Out of memory");
3527 for (unsigned i = 0; i < chunk_size; i++) {
3528 switch (data_size) {
3530 target_buffer_set_u64(target, target_buf + i * data_size, b);
3533 target_buffer_set_u32(target, target_buf + i * data_size, b);
3536 target_buffer_set_u16(target, target_buf + i * data_size, b);
3539 target_buffer_set_u8(target, target_buf + i * data_size, b);
3546 int retval = ERROR_OK;
3548 for (unsigned x = 0; x < c; x += chunk_size) {
3551 if (current > chunk_size)
3552 current = chunk_size;
3553 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3554 if (retval != ERROR_OK)
3556 /* avoid GDB timeouts */
3565 COMMAND_HANDLER(handle_mw_command)
3568 return ERROR_COMMAND_SYNTAX_ERROR;
3569 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3574 fn = target_write_phys_memory;
3576 fn = target_write_memory;
3577 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3578 return ERROR_COMMAND_SYNTAX_ERROR;
3580 target_addr_t address;
3581 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3584 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[1], value);
3588 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3590 struct target *target = get_current_target(CMD_CTX);
3592 switch (CMD_NAME[2]) {
3606 return ERROR_COMMAND_SYNTAX_ERROR;
3609 return target_fill_mem(target, address, fn, wordsize, value, count);
3612 static COMMAND_HELPER(parse_load_image_command, struct image *image,
3613 target_addr_t *min_address, target_addr_t *max_address)
3615 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3616 return ERROR_COMMAND_SYNTAX_ERROR;
3618 /* a base address isn't always necessary,
3619 * default to 0x0 (i.e. don't relocate) */
3620 if (CMD_ARGC >= 2) {
3622 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3623 image->base_address = addr;
3624 image->base_address_set = true;
3626 image->base_address_set = false;
3628 image->start_address_set = false;
3631 COMMAND_PARSE_ADDRESS(CMD_ARGV[3], *min_address);
3632 if (CMD_ARGC == 5) {
3633 COMMAND_PARSE_ADDRESS(CMD_ARGV[4], *max_address);
3634 /* use size (given) to find max (required) */
3635 *max_address += *min_address;
3638 if (*min_address > *max_address)
3639 return ERROR_COMMAND_SYNTAX_ERROR;
3644 COMMAND_HANDLER(handle_load_image_command)
3648 uint32_t image_size;
3649 target_addr_t min_address = 0;
3650 target_addr_t max_address = -1;
3653 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
3654 &image, &min_address, &max_address);
3655 if (retval != ERROR_OK)
3658 struct target *target = get_current_target(CMD_CTX);
3660 struct duration bench;
3661 duration_start(&bench);
3663 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3668 for (unsigned int i = 0; i < image.num_sections; i++) {
3669 buffer = malloc(image.sections[i].size);
3672 "error allocating buffer for section (%d bytes)",
3673 (int)(image.sections[i].size));
3674 retval = ERROR_FAIL;
3678 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3679 if (retval != ERROR_OK) {
3684 uint32_t offset = 0;
3685 uint32_t length = buf_cnt;
3687 /* DANGER!!! beware of unsigned comparison here!!! */
3689 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3690 (image.sections[i].base_address < max_address)) {
3692 if (image.sections[i].base_address < min_address) {
3693 /* clip addresses below */
3694 offset += min_address-image.sections[i].base_address;
3698 if (image.sections[i].base_address + buf_cnt > max_address)
3699 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3701 retval = target_write_buffer(target,
3702 image.sections[i].base_address + offset, length, buffer + offset);
3703 if (retval != ERROR_OK) {
3707 image_size += length;
3708 command_print(CMD, "%u bytes written at address " TARGET_ADDR_FMT "",
3709 (unsigned int)length,
3710 image.sections[i].base_address + offset);
3716 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3717 command_print(CMD, "downloaded %" PRIu32 " bytes "
3718 "in %fs (%0.3f KiB/s)", image_size,
3719 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3722 image_close(&image);
3728 COMMAND_HANDLER(handle_dump_image_command)
3730 struct fileio *fileio;
3732 int retval, retvaltemp;
3733 target_addr_t address, size;
3734 struct duration bench;
3735 struct target *target = get_current_target(CMD_CTX);
3738 return ERROR_COMMAND_SYNTAX_ERROR;
3740 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], address);
3741 COMMAND_PARSE_ADDRESS(CMD_ARGV[2], size);
3743 uint32_t buf_size = (size > 4096) ? 4096 : size;
3744 buffer = malloc(buf_size);
3748 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3749 if (retval != ERROR_OK) {
3754 duration_start(&bench);
3757 size_t size_written;
3758 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3759 retval = target_read_buffer(target, address, this_run_size, buffer);
3760 if (retval != ERROR_OK)
3763 retval = fileio_write(fileio, this_run_size, buffer, &size_written);
3764 if (retval != ERROR_OK)
3767 size -= this_run_size;
3768 address += this_run_size;
3773 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3775 retval = fileio_size(fileio, &filesize);
3776 if (retval != ERROR_OK)
3779 "dumped %zu bytes in %fs (%0.3f KiB/s)", filesize,
3780 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3783 retvaltemp = fileio_close(fileio);
3784 if (retvaltemp != ERROR_OK)
3793 IMAGE_CHECKSUM_ONLY = 2
3796 static COMMAND_HELPER(handle_verify_image_command_internal, enum verify_mode verify)
3800 uint32_t image_size;
3802 uint32_t checksum = 0;
3803 uint32_t mem_checksum = 0;
3807 struct target *target = get_current_target(CMD_CTX);
3810 return ERROR_COMMAND_SYNTAX_ERROR;
3813 LOG_ERROR("no target selected");
3817 struct duration bench;
3818 duration_start(&bench);
3820 if (CMD_ARGC >= 2) {
3822 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3823 image.base_address = addr;
3824 image.base_address_set = true;
3826 image.base_address_set = false;
3827 image.base_address = 0x0;
3830 image.start_address_set = false;
3832 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3833 if (retval != ERROR_OK)
3839 for (unsigned int i = 0; i < image.num_sections; i++) {
3840 buffer = malloc(image.sections[i].size);
3843 "error allocating buffer for section (%" PRIu32 " bytes)",
3844 image.sections[i].size);
3847 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3848 if (retval != ERROR_OK) {
3853 if (verify >= IMAGE_VERIFY) {
3854 /* calculate checksum of image */
3855 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3856 if (retval != ERROR_OK) {
3861 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3862 if (retval != ERROR_OK) {
3866 if ((checksum != mem_checksum) && (verify == IMAGE_CHECKSUM_ONLY)) {
3867 LOG_ERROR("checksum mismatch");
3869 retval = ERROR_FAIL;
3872 if (checksum != mem_checksum) {
3873 /* failed crc checksum, fall back to a binary compare */
3877 LOG_ERROR("checksum mismatch - attempting binary compare");
3879 data = malloc(buf_cnt);
3881 retval = target_read_buffer(target, image.sections[i].base_address, buf_cnt, data);
3882 if (retval == ERROR_OK) {
3884 for (t = 0; t < buf_cnt; t++) {
3885 if (data[t] != buffer[t]) {
3887 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3889 (unsigned)(t + image.sections[i].base_address),
3892 if (diffs++ >= 127) {
3893 command_print(CMD, "More than 128 errors, the rest are not printed.");
3905 command_print(CMD, "address " TARGET_ADDR_FMT " length 0x%08zx",
3906 image.sections[i].base_address,
3911 image_size += buf_cnt;
3914 command_print(CMD, "No more differences found.");
3917 retval = ERROR_FAIL;
3918 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3919 command_print(CMD, "verified %" PRIu32 " bytes "
3920 "in %fs (%0.3f KiB/s)", image_size,
3921 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3924 image_close(&image);
3929 COMMAND_HANDLER(handle_verify_image_checksum_command)
3931 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_CHECKSUM_ONLY);
3934 COMMAND_HANDLER(handle_verify_image_command)
3936 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_VERIFY);
3939 COMMAND_HANDLER(handle_test_image_command)
3941 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_TEST);
3944 static int handle_bp_command_list(struct command_invocation *cmd)
3946 struct target *target = get_current_target(cmd->ctx);
3947 struct breakpoint *breakpoint = target->breakpoints;
3948 while (breakpoint) {
3949 if (breakpoint->type == BKPT_SOFT) {
3950 char *buf = buf_to_hex_str(breakpoint->orig_instr,
3951 breakpoint->length);
3952 command_print(cmd, "IVA breakpoint: " TARGET_ADDR_FMT ", 0x%x, %i, 0x%s",
3953 breakpoint->address,
3955 breakpoint->set, buf);
3958 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3959 command_print(cmd, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3961 breakpoint->length, breakpoint->set);
3962 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3963 command_print(cmd, "Hybrid breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3964 breakpoint->address,
3965 breakpoint->length, breakpoint->set);
3966 command_print(cmd, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3969 command_print(cmd, "Breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3970 breakpoint->address,
3971 breakpoint->length, breakpoint->set);
3974 breakpoint = breakpoint->next;
3979 static int handle_bp_command_set(struct command_invocation *cmd,
3980 target_addr_t addr, uint32_t asid, uint32_t length, int hw)
3982 struct target *target = get_current_target(cmd->ctx);
3986 retval = breakpoint_add(target, addr, length, hw);
3987 /* error is always logged in breakpoint_add(), do not print it again */
3988 if (retval == ERROR_OK)
3989 command_print(cmd, "breakpoint set at " TARGET_ADDR_FMT "", addr);
3991 } else if (addr == 0) {
3992 if (!target->type->add_context_breakpoint) {
3993 LOG_ERROR("Context breakpoint not available");
3994 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
3996 retval = context_breakpoint_add(target, asid, length, hw);
3997 /* error is always logged in context_breakpoint_add(), do not print it again */
3998 if (retval == ERROR_OK)
3999 command_print(cmd, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
4002 if (!target->type->add_hybrid_breakpoint) {
4003 LOG_ERROR("Hybrid breakpoint not available");
4004 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
4006 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
4007 /* error is always logged in hybrid_breakpoint_add(), do not print it again */
4008 if (retval == ERROR_OK)
4009 command_print(cmd, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
4014 COMMAND_HANDLER(handle_bp_command)
4023 return handle_bp_command_list(CMD);
4027 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4028 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4029 return handle_bp_command_set(CMD, addr, asid, length, hw);
4032 if (strcmp(CMD_ARGV[2], "hw") == 0) {
4034 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4035 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4037 return handle_bp_command_set(CMD, addr, asid, length, hw);
4038 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
4040 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
4041 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4043 return handle_bp_command_set(CMD, addr, asid, length, hw);
4048 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4049 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
4050 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
4051 return handle_bp_command_set(CMD, addr, asid, length, hw);
4054 return ERROR_COMMAND_SYNTAX_ERROR;
4058 COMMAND_HANDLER(handle_rbp_command)
4061 return ERROR_COMMAND_SYNTAX_ERROR;
4063 struct target *target = get_current_target(CMD_CTX);
4065 if (!strcmp(CMD_ARGV[0], "all")) {
4066 breakpoint_remove_all(target);
4069 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4071 breakpoint_remove(target, addr);
4077 COMMAND_HANDLER(handle_wp_command)
4079 struct target *target = get_current_target(CMD_CTX);
4081 if (CMD_ARGC == 0) {
4082 struct watchpoint *watchpoint = target->watchpoints;
4084 while (watchpoint) {
4085 command_print(CMD, "address: " TARGET_ADDR_FMT
4086 ", len: 0x%8.8" PRIx32
4087 ", r/w/a: %i, value: 0x%8.8" PRIx32
4088 ", mask: 0x%8.8" PRIx32,
4089 watchpoint->address,
4091 (int)watchpoint->rw,
4094 watchpoint = watchpoint->next;
4099 enum watchpoint_rw type = WPT_ACCESS;
4100 target_addr_t addr = 0;
4101 uint32_t length = 0;
4102 uint32_t data_value = 0x0;
4103 uint32_t data_mask = 0xffffffff;
4107 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
4110 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
4113 switch (CMD_ARGV[2][0]) {
4124 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
4125 return ERROR_COMMAND_SYNTAX_ERROR;
4129 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4130 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4134 return ERROR_COMMAND_SYNTAX_ERROR;
4137 int retval = watchpoint_add(target, addr, length, type,
4138 data_value, data_mask);
4139 if (retval != ERROR_OK)
4140 LOG_ERROR("Failure setting watchpoints");
4145 COMMAND_HANDLER(handle_rwp_command)
4148 return ERROR_COMMAND_SYNTAX_ERROR;
4151 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4153 struct target *target = get_current_target(CMD_CTX);
4154 watchpoint_remove(target, addr);
4160 * Translate a virtual address to a physical address.
4162 * The low-level target implementation must have logged a detailed error
4163 * which is forwarded to telnet/GDB session.
4165 COMMAND_HANDLER(handle_virt2phys_command)
4168 return ERROR_COMMAND_SYNTAX_ERROR;
4171 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], va);
4174 struct target *target = get_current_target(CMD_CTX);
4175 int retval = target->type->virt2phys(target, va, &pa);
4176 if (retval == ERROR_OK)
4177 command_print(CMD, "Physical address " TARGET_ADDR_FMT "", pa);
4182 static void write_data(FILE *f, const void *data, size_t len)
4184 size_t written = fwrite(data, 1, len, f);
4186 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
4189 static void write_long(FILE *f, int l, struct target *target)
4193 target_buffer_set_u32(target, val, l);
4194 write_data(f, val, 4);
4197 static void write_string(FILE *f, char *s)
4199 write_data(f, s, strlen(s));
4202 typedef unsigned char UNIT[2]; /* unit of profiling */
4204 /* Dump a gmon.out histogram file. */
4205 static void write_gmon(uint32_t *samples, uint32_t sample_num, const char *filename, bool with_range,
4206 uint32_t start_address, uint32_t end_address, struct target *target, uint32_t duration_ms)
4209 FILE *f = fopen(filename, "w");
4212 write_string(f, "gmon");
4213 write_long(f, 0x00000001, target); /* Version */
4214 write_long(f, 0, target); /* padding */
4215 write_long(f, 0, target); /* padding */
4216 write_long(f, 0, target); /* padding */
4218 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
4219 write_data(f, &zero, 1);
4221 /* figure out bucket size */
4225 min = start_address;
4230 for (i = 0; i < sample_num; i++) {
4231 if (min > samples[i])
4233 if (max < samples[i])
4237 /* max should be (largest sample + 1)
4238 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
4242 int address_space = max - min;
4243 assert(address_space >= 2);
4245 /* FIXME: What is the reasonable number of buckets?
4246 * The profiling result will be more accurate if there are enough buckets. */
4247 static const uint32_t max_buckets = 128 * 1024; /* maximum buckets. */
4248 uint32_t num_buckets = address_space / sizeof(UNIT);
4249 if (num_buckets > max_buckets)
4250 num_buckets = max_buckets;
4251 int *buckets = malloc(sizeof(int) * num_buckets);
4256 memset(buckets, 0, sizeof(int) * num_buckets);
4257 for (i = 0; i < sample_num; i++) {
4258 uint32_t address = samples[i];
4260 if ((address < min) || (max <= address))
4263 long long a = address - min;
4264 long long b = num_buckets;
4265 long long c = address_space;
4266 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
4270 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
4271 write_long(f, min, target); /* low_pc */
4272 write_long(f, max, target); /* high_pc */
4273 write_long(f, num_buckets, target); /* # of buckets */
4274 float sample_rate = sample_num / (duration_ms / 1000.0);
4275 write_long(f, sample_rate, target);
4276 write_string(f, "seconds");
4277 for (i = 0; i < (15-strlen("seconds")); i++)
4278 write_data(f, &zero, 1);
4279 write_string(f, "s");
4281 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
4283 char *data = malloc(2 * num_buckets);
4285 for (i = 0; i < num_buckets; i++) {
4290 data[i * 2] = val&0xff;
4291 data[i * 2 + 1] = (val >> 8) & 0xff;
4294 write_data(f, data, num_buckets * 2);
4302 /* profiling samples the CPU PC as quickly as OpenOCD is able,
4303 * which will be used as a random sampling of PC */
4304 COMMAND_HANDLER(handle_profile_command)
4306 struct target *target = get_current_target(CMD_CTX);
4308 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
4309 return ERROR_COMMAND_SYNTAX_ERROR;
4311 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
4313 uint32_t num_of_samples;
4314 int retval = ERROR_OK;
4315 bool halted_before_profiling = target->state == TARGET_HALTED;
4317 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
4319 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
4321 LOG_ERROR("No memory to store samples.");
4325 uint64_t timestart_ms = timeval_ms();
4327 * Some cores let us sample the PC without the
4328 * annoying halt/resume step; for example, ARMv7 PCSR.
4329 * Provide a way to use that more efficient mechanism.
4331 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
4332 &num_of_samples, offset);
4333 if (retval != ERROR_OK) {
4337 uint32_t duration_ms = timeval_ms() - timestart_ms;
4339 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
4341 retval = target_poll(target);
4342 if (retval != ERROR_OK) {
4347 if (target->state == TARGET_RUNNING && halted_before_profiling) {
4348 /* The target was halted before we started and is running now. Halt it,
4349 * for consistency. */
4350 retval = target_halt(target);
4351 if (retval != ERROR_OK) {
4355 } else if (target->state == TARGET_HALTED && !halted_before_profiling) {
4356 /* The target was running before we started and is halted now. Resume
4357 * it, for consistency. */
4358 retval = target_resume(target, 1, 0, 0, 0);
4359 if (retval != ERROR_OK) {
4365 retval = target_poll(target);
4366 if (retval != ERROR_OK) {
4371 uint32_t start_address = 0;
4372 uint32_t end_address = 0;
4373 bool with_range = false;
4374 if (CMD_ARGC == 4) {
4376 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
4377 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
4380 write_gmon(samples, num_of_samples, CMD_ARGV[1],
4381 with_range, start_address, end_address, target, duration_ms);
4382 command_print(CMD, "Wrote %s", CMD_ARGV[1]);
4388 static int new_u64_array_element(Jim_Interp *interp, const char *varname, int idx, uint64_t val)
4391 Jim_Obj *obj_name, *obj_val;
4394 namebuf = alloc_printf("%s(%d)", varname, idx);
4398 obj_name = Jim_NewStringObj(interp, namebuf, -1);
4399 jim_wide wide_val = val;
4400 obj_val = Jim_NewWideObj(interp, wide_val);
4401 if (!obj_name || !obj_val) {
4406 Jim_IncrRefCount(obj_name);
4407 Jim_IncrRefCount(obj_val);
4408 result = Jim_SetVariable(interp, obj_name, obj_val);
4409 Jim_DecrRefCount(interp, obj_name);
4410 Jim_DecrRefCount(interp, obj_val);
4412 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
4416 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4418 struct command_context *context;
4419 struct target *target;
4421 context = current_command_context(interp);
4424 target = get_current_target(context);
4426 LOG_ERROR("mem2array: no current target");
4430 return target_mem2array(interp, target, argc - 1, argv + 1);
4433 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
4437 /* argv[0] = name of array to receive the data
4438 * argv[1] = desired element width in bits
4439 * argv[2] = memory address
4440 * argv[3] = count of times to read
4441 * argv[4] = optional "phys"
4443 if (argc < 4 || argc > 5) {
4444 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4448 /* Arg 0: Name of the array variable */
4449 const char *varname = Jim_GetString(argv[0], NULL);
4451 /* Arg 1: Bit width of one element */
4453 e = Jim_GetLong(interp, argv[1], &l);
4456 const unsigned int width_bits = l;
4458 if (width_bits != 8 &&
4462 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4463 Jim_AppendStrings(interp, Jim_GetResult(interp),
4464 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4467 const unsigned int width = width_bits / 8;
4469 /* Arg 2: Memory address */
4471 e = Jim_GetWide(interp, argv[2], &wide_addr);
4474 target_addr_t addr = (target_addr_t)wide_addr;
4476 /* Arg 3: Number of elements to read */
4477 e = Jim_GetLong(interp, argv[3], &l);
4483 bool is_phys = false;
4486 const char *phys = Jim_GetString(argv[4], &str_len);
4487 if (!strncmp(phys, "phys", str_len))
4493 /* Argument checks */
4495 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4496 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
4499 if ((addr + (len * width)) < addr) {
4500 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4501 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
4505 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4506 Jim_AppendStrings(interp, Jim_GetResult(interp),
4507 "mem2array: too large read request, exceeds 64K items", NULL);
4512 ((width == 2) && ((addr & 1) == 0)) ||
4513 ((width == 4) && ((addr & 3) == 0)) ||
4514 ((width == 8) && ((addr & 7) == 0))) {
4515 /* alignment correct */
4518 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4519 sprintf(buf, "mem2array address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4522 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4531 const size_t buffersize = 4096;
4532 uint8_t *buffer = malloc(buffersize);
4539 /* Slurp... in buffer size chunks */
4540 const unsigned int max_chunk_len = buffersize / width;
4541 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4545 retval = target_read_phys_memory(target, addr, width, chunk_len, buffer);
4547 retval = target_read_memory(target, addr, width, chunk_len, buffer);
4548 if (retval != ERROR_OK) {
4550 LOG_ERROR("mem2array: Read @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4554 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4555 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
4559 for (size_t i = 0; i < chunk_len ; i++, idx++) {
4563 v = target_buffer_get_u64(target, &buffer[i*width]);
4566 v = target_buffer_get_u32(target, &buffer[i*width]);
4569 v = target_buffer_get_u16(target, &buffer[i*width]);
4572 v = buffer[i] & 0x0ff;
4575 new_u64_array_element(interp, varname, idx, v);
4578 addr += chunk_len * width;
4584 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4589 static int get_u64_array_element(Jim_Interp *interp, const char *varname, size_t idx, uint64_t *val)
4591 char *namebuf = alloc_printf("%s(%zu)", varname, idx);
4595 Jim_Obj *obj_name = Jim_NewStringObj(interp, namebuf, -1);
4601 Jim_IncrRefCount(obj_name);
4602 Jim_Obj *obj_val = Jim_GetVariable(interp, obj_name, JIM_ERRMSG);
4603 Jim_DecrRefCount(interp, obj_name);
4609 int result = Jim_GetWide(interp, obj_val, &wide_val);
4614 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4616 struct command_context *context;
4617 struct target *target;
4619 context = current_command_context(interp);
4622 target = get_current_target(context);
4624 LOG_ERROR("array2mem: no current target");
4628 return target_array2mem(interp, target, argc-1, argv + 1);
4631 static int target_array2mem(Jim_Interp *interp, struct target *target,
4632 int argc, Jim_Obj *const *argv)
4636 /* argv[0] = name of array from which to read the data
4637 * argv[1] = desired element width in bits
4638 * argv[2] = memory address
4639 * argv[3] = number of elements to write
4640 * argv[4] = optional "phys"
4642 if (argc < 4 || argc > 5) {
4643 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4647 /* Arg 0: Name of the array variable */
4648 const char *varname = Jim_GetString(argv[0], NULL);
4650 /* Arg 1: Bit width of one element */
4652 e = Jim_GetLong(interp, argv[1], &l);
4655 const unsigned int width_bits = l;
4657 if (width_bits != 8 &&
4661 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4662 Jim_AppendStrings(interp, Jim_GetResult(interp),
4663 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4666 const unsigned int width = width_bits / 8;
4668 /* Arg 2: Memory address */
4670 e = Jim_GetWide(interp, argv[2], &wide_addr);
4673 target_addr_t addr = (target_addr_t)wide_addr;
4675 /* Arg 3: Number of elements to write */
4676 e = Jim_GetLong(interp, argv[3], &l);
4682 bool is_phys = false;
4685 const char *phys = Jim_GetString(argv[4], &str_len);
4686 if (!strncmp(phys, "phys", str_len))
4692 /* Argument checks */
4694 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4695 Jim_AppendStrings(interp, Jim_GetResult(interp),
4696 "array2mem: zero width read?", NULL);
4700 if ((addr + (len * width)) < addr) {
4701 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4702 Jim_AppendStrings(interp, Jim_GetResult(interp),
4703 "array2mem: addr + len - wraps to zero?", NULL);
4708 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4709 Jim_AppendStrings(interp, Jim_GetResult(interp),
4710 "array2mem: too large memory write request, exceeds 64K items", NULL);
4715 ((width == 2) && ((addr & 1) == 0)) ||
4716 ((width == 4) && ((addr & 3) == 0)) ||
4717 ((width == 8) && ((addr & 7) == 0))) {
4718 /* alignment correct */
4721 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4722 sprintf(buf, "array2mem address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4725 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4734 const size_t buffersize = 4096;
4735 uint8_t *buffer = malloc(buffersize);
4743 /* Slurp... in buffer size chunks */
4744 const unsigned int max_chunk_len = buffersize / width;
4746 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4748 /* Fill the buffer */
4749 for (size_t i = 0; i < chunk_len; i++, idx++) {
4751 if (get_u64_array_element(interp, varname, idx, &v) != JIM_OK) {
4757 target_buffer_set_u64(target, &buffer[i * width], v);
4760 target_buffer_set_u32(target, &buffer[i * width], v);
4763 target_buffer_set_u16(target, &buffer[i * width], v);
4766 buffer[i] = v & 0x0ff;
4772 /* Write the buffer to memory */
4775 retval = target_write_phys_memory(target, addr, width, chunk_len, buffer);
4777 retval = target_write_memory(target, addr, width, chunk_len, buffer);
4778 if (retval != ERROR_OK) {
4780 LOG_ERROR("array2mem: Write @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4784 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4785 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4789 addr += chunk_len * width;
4794 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4799 /* FIX? should we propagate errors here rather than printing them
4802 void target_handle_event(struct target *target, enum target_event e)
4804 struct target_event_action *teap;
4807 for (teap = target->event_action; teap; teap = teap->next) {
4808 if (teap->event == e) {
4809 LOG_DEBUG("target(%d): %s (%s) event: %d (%s) action: %s",
4810 target->target_number,
4811 target_name(target),
4812 target_type_name(target),
4814 jim_nvp_value2name_simple(nvp_target_event, e)->name,
4815 Jim_GetString(teap->body, NULL));
4817 /* Override current target by the target an event
4818 * is issued from (lot of scripts need it).
4819 * Return back to previous override as soon
4820 * as the handler processing is done */
4821 struct command_context *cmd_ctx = current_command_context(teap->interp);
4822 struct target *saved_target_override = cmd_ctx->current_target_override;
4823 cmd_ctx->current_target_override = target;
4825 retval = Jim_EvalObj(teap->interp, teap->body);
4827 cmd_ctx->current_target_override = saved_target_override;
4829 if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
4832 if (retval == JIM_RETURN)
4833 retval = teap->interp->returnCode;
4835 if (retval != JIM_OK) {
4836 Jim_MakeErrorMessage(teap->interp);
4837 LOG_USER("Error executing event %s on target %s:\n%s",
4838 jim_nvp_value2name_simple(nvp_target_event, e)->name,
4839 target_name(target),
4840 Jim_GetString(Jim_GetResult(teap->interp), NULL));
4841 /* clean both error code and stacktrace before return */
4842 Jim_Eval(teap->interp, "error \"\" \"\"");
4849 * Returns true only if the target has a handler for the specified event.
4851 bool target_has_event_action(struct target *target, enum target_event event)
4853 struct target_event_action *teap;
4855 for (teap = target->event_action; teap; teap = teap->next) {
4856 if (teap->event == event)
4862 enum target_cfg_param {
4865 TCFG_WORK_AREA_VIRT,
4866 TCFG_WORK_AREA_PHYS,
4867 TCFG_WORK_AREA_SIZE,
4868 TCFG_WORK_AREA_BACKUP,
4871 TCFG_CHAIN_POSITION,
4876 TCFG_GDB_MAX_CONNECTIONS,
4879 static struct jim_nvp nvp_config_opts[] = {
4880 { .name = "-type", .value = TCFG_TYPE },
4881 { .name = "-event", .value = TCFG_EVENT },
4882 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4883 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4884 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4885 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4886 { .name = "-endian", .value = TCFG_ENDIAN },
4887 { .name = "-coreid", .value = TCFG_COREID },
4888 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4889 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4890 { .name = "-rtos", .value = TCFG_RTOS },
4891 { .name = "-defer-examine", .value = TCFG_DEFER_EXAMINE },
4892 { .name = "-gdb-port", .value = TCFG_GDB_PORT },
4893 { .name = "-gdb-max-connections", .value = TCFG_GDB_MAX_CONNECTIONS },
4894 { .name = NULL, .value = -1 }
4897 static int target_configure(struct jim_getopt_info *goi, struct target *target)
4904 /* parse config or cget options ... */
4905 while (goi->argc > 0) {
4906 Jim_SetEmptyResult(goi->interp);
4907 /* jim_getopt_debug(goi); */
4909 if (target->type->target_jim_configure) {
4910 /* target defines a configure function */
4911 /* target gets first dibs on parameters */
4912 e = (*(target->type->target_jim_configure))(target, goi);
4921 /* otherwise we 'continue' below */
4923 e = jim_getopt_nvp(goi, nvp_config_opts, &n);
4925 jim_getopt_nvp_unknown(goi, nvp_config_opts, 0);
4931 if (goi->isconfigure) {
4932 Jim_SetResultFormatted(goi->interp,
4933 "not settable: %s", n->name);
4937 if (goi->argc != 0) {
4938 Jim_WrongNumArgs(goi->interp,
4939 goi->argc, goi->argv,
4944 Jim_SetResultString(goi->interp,
4945 target_type_name(target), -1);
4949 if (goi->argc == 0) {
4950 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4954 e = jim_getopt_nvp(goi, nvp_target_event, &n);
4956 jim_getopt_nvp_unknown(goi, nvp_target_event, 1);
4960 if (goi->isconfigure) {
4961 if (goi->argc != 1) {
4962 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4966 if (goi->argc != 0) {
4967 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4973 struct target_event_action *teap;
4975 teap = target->event_action;
4976 /* replace existing? */
4978 if (teap->event == (enum target_event)n->value)
4983 if (goi->isconfigure) {
4984 /* START_DEPRECATED_TPIU */
4985 if (n->value == TARGET_EVENT_TRACE_CONFIG)
4986 LOG_INFO("DEPRECATED target event %s", n->name);
4987 /* END_DEPRECATED_TPIU */
4989 bool replace = true;
4992 teap = calloc(1, sizeof(*teap));
4995 teap->event = n->value;
4996 teap->interp = goi->interp;
4997 jim_getopt_obj(goi, &o);
4999 Jim_DecrRefCount(teap->interp, teap->body);
5000 teap->body = Jim_DuplicateObj(goi->interp, o);
5003 * Tcl/TK - "tk events" have a nice feature.
5004 * See the "BIND" command.
5005 * We should support that here.
5006 * You can specify %X and %Y in the event code.
5007 * The idea is: %T - target name.
5008 * The idea is: %N - target number
5009 * The idea is: %E - event name.
5011 Jim_IncrRefCount(teap->body);
5014 /* add to head of event list */
5015 teap->next = target->event_action;
5016 target->event_action = teap;
5018 Jim_SetEmptyResult(goi->interp);
5022 Jim_SetEmptyResult(goi->interp);
5024 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
5030 case TCFG_WORK_AREA_VIRT:
5031 if (goi->isconfigure) {
5032 target_free_all_working_areas(target);
5033 e = jim_getopt_wide(goi, &w);
5036 target->working_area_virt = w;
5037 target->working_area_virt_spec = true;
5042 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
5046 case TCFG_WORK_AREA_PHYS:
5047 if (goi->isconfigure) {
5048 target_free_all_working_areas(target);
5049 e = jim_getopt_wide(goi, &w);
5052 target->working_area_phys = w;
5053 target->working_area_phys_spec = true;
5058 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
5062 case TCFG_WORK_AREA_SIZE:
5063 if (goi->isconfigure) {
5064 target_free_all_working_areas(target);
5065 e = jim_getopt_wide(goi, &w);
5068 target->working_area_size = w;
5073 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
5077 case TCFG_WORK_AREA_BACKUP:
5078 if (goi->isconfigure) {
5079 target_free_all_working_areas(target);
5080 e = jim_getopt_wide(goi, &w);
5083 /* make this exactly 1 or 0 */
5084 target->backup_working_area = (!!w);
5089 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
5090 /* loop for more e*/
5095 if (goi->isconfigure) {
5096 e = jim_getopt_nvp(goi, nvp_target_endian, &n);
5098 jim_getopt_nvp_unknown(goi, nvp_target_endian, 1);
5101 target->endianness = n->value;
5106 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5108 target->endianness = TARGET_LITTLE_ENDIAN;
5109 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5111 Jim_SetResultString(goi->interp, n->name, -1);
5116 if (goi->isconfigure) {
5117 e = jim_getopt_wide(goi, &w);
5120 target->coreid = (int32_t)w;
5125 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->coreid));
5129 case TCFG_CHAIN_POSITION:
5130 if (goi->isconfigure) {
5132 struct jtag_tap *tap;
5134 if (target->has_dap) {
5135 Jim_SetResultString(goi->interp,
5136 "target requires -dap parameter instead of -chain-position!", -1);
5140 target_free_all_working_areas(target);
5141 e = jim_getopt_obj(goi, &o_t);
5144 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
5148 target->tap_configured = true;
5153 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
5154 /* loop for more e*/
5157 if (goi->isconfigure) {
5158 e = jim_getopt_wide(goi, &w);
5161 target->dbgbase = (uint32_t)w;
5162 target->dbgbase_set = true;
5167 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
5173 int result = rtos_create(goi, target);
5174 if (result != JIM_OK)
5180 case TCFG_DEFER_EXAMINE:
5182 target->defer_examine = true;
5187 if (goi->isconfigure) {
5188 struct command_context *cmd_ctx = current_command_context(goi->interp);
5189 if (cmd_ctx->mode != COMMAND_CONFIG) {
5190 Jim_SetResultString(goi->interp, "-gdb-port must be configured before 'init'", -1);
5195 e = jim_getopt_string(goi, &s, NULL);
5198 free(target->gdb_port_override);
5199 target->gdb_port_override = strdup(s);
5204 Jim_SetResultString(goi->interp, target->gdb_port_override ? target->gdb_port_override : "undefined", -1);
5208 case TCFG_GDB_MAX_CONNECTIONS:
5209 if (goi->isconfigure) {
5210 struct command_context *cmd_ctx = current_command_context(goi->interp);
5211 if (cmd_ctx->mode != COMMAND_CONFIG) {
5212 Jim_SetResultString(goi->interp, "-gdb-max-connections must be configured before 'init'", -1);
5216 e = jim_getopt_wide(goi, &w);
5219 target->gdb_max_connections = (w < 0) ? CONNECTION_LIMIT_UNLIMITED : (int)w;
5224 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->gdb_max_connections));
5227 } /* while (goi->argc) */
5230 /* done - we return */
5234 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5236 struct command *c = jim_to_command(interp);
5237 struct jim_getopt_info goi;
5239 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5240 goi.isconfigure = !strcmp(c->name, "configure");
5242 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5243 "missing: -option ...");
5246 struct command_context *cmd_ctx = current_command_context(interp);
5248 struct target *target = get_current_target(cmd_ctx);
5249 return target_configure(&goi, target);
5252 static int jim_target_mem2array(Jim_Interp *interp,
5253 int argc, Jim_Obj *const *argv)
5255 struct command_context *cmd_ctx = current_command_context(interp);
5257 struct target *target = get_current_target(cmd_ctx);
5258 return target_mem2array(interp, target, argc - 1, argv + 1);
5261 static int jim_target_array2mem(Jim_Interp *interp,
5262 int argc, Jim_Obj *const *argv)
5264 struct command_context *cmd_ctx = current_command_context(interp);
5266 struct target *target = get_current_target(cmd_ctx);
5267 return target_array2mem(interp, target, argc - 1, argv + 1);
5270 static int jim_target_tap_disabled(Jim_Interp *interp)
5272 Jim_SetResultFormatted(interp, "[TAP is disabled]");
5276 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5278 bool allow_defer = false;
5280 struct jim_getopt_info goi;
5281 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5283 const char *cmd_name = Jim_GetString(argv[0], NULL);
5284 Jim_SetResultFormatted(goi.interp,
5285 "usage: %s ['allow-defer']", cmd_name);
5289 strcmp(Jim_GetString(argv[1], NULL), "allow-defer") == 0) {
5292 int e = jim_getopt_obj(&goi, &obj);
5298 struct command_context *cmd_ctx = current_command_context(interp);
5300 struct target *target = get_current_target(cmd_ctx);
5301 if (!target->tap->enabled)
5302 return jim_target_tap_disabled(interp);
5304 if (allow_defer && target->defer_examine) {
5305 LOG_INFO("Deferring arp_examine of %s", target_name(target));
5306 LOG_INFO("Use arp_examine command to examine it manually!");
5310 int e = target->type->examine(target);
5316 static int jim_target_was_examined(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5318 struct command_context *cmd_ctx = current_command_context(interp);
5320 struct target *target = get_current_target(cmd_ctx);
5322 Jim_SetResultBool(interp, target_was_examined(target));
5326 static int jim_target_examine_deferred(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->defer_examine);
5336 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5339 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5342 struct command_context *cmd_ctx = current_command_context(interp);
5344 struct target *target = get_current_target(cmd_ctx);
5346 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
5352 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5355 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5358 struct command_context *cmd_ctx = current_command_context(interp);
5360 struct target *target = get_current_target(cmd_ctx);
5361 if (!target->tap->enabled)
5362 return jim_target_tap_disabled(interp);
5365 if (!(target_was_examined(target)))
5366 e = ERROR_TARGET_NOT_EXAMINED;
5368 e = target->type->poll(target);
5374 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5376 struct jim_getopt_info goi;
5377 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5379 if (goi.argc != 2) {
5380 Jim_WrongNumArgs(interp, 0, argv,
5381 "([tT]|[fF]|assert|deassert) BOOL");
5386 int e = jim_getopt_nvp(&goi, nvp_assert, &n);
5388 jim_getopt_nvp_unknown(&goi, nvp_assert, 1);
5391 /* the halt or not param */
5393 e = jim_getopt_wide(&goi, &a);
5397 struct command_context *cmd_ctx = current_command_context(interp);
5399 struct target *target = get_current_target(cmd_ctx);
5400 if (!target->tap->enabled)
5401 return jim_target_tap_disabled(interp);
5403 if (!target->type->assert_reset || !target->type->deassert_reset) {
5404 Jim_SetResultFormatted(interp,
5405 "No target-specific reset for %s",
5406 target_name(target));
5410 if (target->defer_examine)
5411 target_reset_examined(target);
5413 /* determine if we should halt or not. */
5414 target->reset_halt = (a != 0);
5415 /* When this happens - all workareas are invalid. */
5416 target_free_all_working_areas_restore(target, 0);
5419 if (n->value == NVP_ASSERT)
5420 e = target->type->assert_reset(target);
5422 e = target->type->deassert_reset(target);
5423 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5426 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5429 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5432 struct command_context *cmd_ctx = current_command_context(interp);
5434 struct target *target = get_current_target(cmd_ctx);
5435 if (!target->tap->enabled)
5436 return jim_target_tap_disabled(interp);
5437 int e = target->type->halt(target);
5438 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5441 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5443 struct jim_getopt_info goi;
5444 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5446 /* params: <name> statename timeoutmsecs */
5447 if (goi.argc != 2) {
5448 const char *cmd_name = Jim_GetString(argv[0], NULL);
5449 Jim_SetResultFormatted(goi.interp,
5450 "%s <state_name> <timeout_in_msec>", cmd_name);
5455 int e = jim_getopt_nvp(&goi, nvp_target_state, &n);
5457 jim_getopt_nvp_unknown(&goi, nvp_target_state, 1);
5461 e = jim_getopt_wide(&goi, &a);
5464 struct command_context *cmd_ctx = current_command_context(interp);
5466 struct target *target = get_current_target(cmd_ctx);
5467 if (!target->tap->enabled)
5468 return jim_target_tap_disabled(interp);
5470 e = target_wait_state(target, n->value, a);
5471 if (e != ERROR_OK) {
5472 Jim_Obj *obj = Jim_NewIntObj(interp, e);
5473 Jim_SetResultFormatted(goi.interp,
5474 "target: %s wait %s fails (%#s) %s",
5475 target_name(target), n->name,
5476 obj, target_strerror_safe(e));
5481 /* List for human, Events defined for this target.
5482 * scripts/programs should use 'name cget -event NAME'
5484 COMMAND_HANDLER(handle_target_event_list)
5486 struct target *target = get_current_target(CMD_CTX);
5487 struct target_event_action *teap = target->event_action;
5489 command_print(CMD, "Event actions for target (%d) %s\n",
5490 target->target_number,
5491 target_name(target));
5492 command_print(CMD, "%-25s | Body", "Event");
5493 command_print(CMD, "------------------------- | "
5494 "----------------------------------------");
5496 struct jim_nvp *opt = jim_nvp_value2name_simple(nvp_target_event, teap->event);
5497 command_print(CMD, "%-25s | %s",
5498 opt->name, Jim_GetString(teap->body, NULL));
5501 command_print(CMD, "***END***");
5504 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5507 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5510 struct command_context *cmd_ctx = current_command_context(interp);
5512 struct target *target = get_current_target(cmd_ctx);
5513 Jim_SetResultString(interp, target_state_name(target), -1);
5516 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5518 struct jim_getopt_info goi;
5519 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5520 if (goi.argc != 1) {
5521 const char *cmd_name = Jim_GetString(argv[0], NULL);
5522 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5526 int e = jim_getopt_nvp(&goi, nvp_target_event, &n);
5528 jim_getopt_nvp_unknown(&goi, nvp_target_event, 1);
5531 struct command_context *cmd_ctx = current_command_context(interp);
5533 struct target *target = get_current_target(cmd_ctx);
5534 target_handle_event(target, n->value);
5538 static const struct command_registration target_instance_command_handlers[] = {
5540 .name = "configure",
5541 .mode = COMMAND_ANY,
5542 .jim_handler = jim_target_configure,
5543 .help = "configure a new target for use",
5544 .usage = "[target_attribute ...]",
5548 .mode = COMMAND_ANY,
5549 .jim_handler = jim_target_configure,
5550 .help = "returns the specified target attribute",
5551 .usage = "target_attribute",
5555 .handler = handle_mw_command,
5556 .mode = COMMAND_EXEC,
5557 .help = "Write 64-bit word(s) to target memory",
5558 .usage = "address data [count]",
5562 .handler = handle_mw_command,
5563 .mode = COMMAND_EXEC,
5564 .help = "Write 32-bit word(s) to target memory",
5565 .usage = "address data [count]",
5569 .handler = handle_mw_command,
5570 .mode = COMMAND_EXEC,
5571 .help = "Write 16-bit half-word(s) to target memory",
5572 .usage = "address data [count]",
5576 .handler = handle_mw_command,
5577 .mode = COMMAND_EXEC,
5578 .help = "Write byte(s) to target memory",
5579 .usage = "address data [count]",
5583 .handler = handle_md_command,
5584 .mode = COMMAND_EXEC,
5585 .help = "Display target memory as 64-bit words",
5586 .usage = "address [count]",
5590 .handler = handle_md_command,
5591 .mode = COMMAND_EXEC,
5592 .help = "Display target memory as 32-bit words",
5593 .usage = "address [count]",
5597 .handler = handle_md_command,
5598 .mode = COMMAND_EXEC,
5599 .help = "Display target memory as 16-bit half-words",
5600 .usage = "address [count]",
5604 .handler = handle_md_command,
5605 .mode = COMMAND_EXEC,
5606 .help = "Display target memory as 8-bit bytes",
5607 .usage = "address [count]",
5610 .name = "array2mem",
5611 .mode = COMMAND_EXEC,
5612 .jim_handler = jim_target_array2mem,
5613 .help = "Writes Tcl array of 8/16/32 bit numbers "
5615 .usage = "arrayname bitwidth address count",
5618 .name = "mem2array",
5619 .mode = COMMAND_EXEC,
5620 .jim_handler = jim_target_mem2array,
5621 .help = "Loads Tcl array of 8/16/32 bit numbers "
5622 "from target memory",
5623 .usage = "arrayname bitwidth address count",
5626 .name = "eventlist",
5627 .handler = handle_target_event_list,
5628 .mode = COMMAND_EXEC,
5629 .help = "displays a table of events defined for this target",
5634 .mode = COMMAND_EXEC,
5635 .jim_handler = jim_target_current_state,
5636 .help = "displays the current state of this target",
5639 .name = "arp_examine",
5640 .mode = COMMAND_EXEC,
5641 .jim_handler = jim_target_examine,
5642 .help = "used internally for reset processing",
5643 .usage = "['allow-defer']",
5646 .name = "was_examined",
5647 .mode = COMMAND_EXEC,
5648 .jim_handler = jim_target_was_examined,
5649 .help = "used internally for reset processing",
5652 .name = "examine_deferred",
5653 .mode = COMMAND_EXEC,
5654 .jim_handler = jim_target_examine_deferred,
5655 .help = "used internally for reset processing",
5658 .name = "arp_halt_gdb",
5659 .mode = COMMAND_EXEC,
5660 .jim_handler = jim_target_halt_gdb,
5661 .help = "used internally for reset processing to halt GDB",
5665 .mode = COMMAND_EXEC,
5666 .jim_handler = jim_target_poll,
5667 .help = "used internally for reset processing",
5670 .name = "arp_reset",
5671 .mode = COMMAND_EXEC,
5672 .jim_handler = jim_target_reset,
5673 .help = "used internally for reset processing",
5677 .mode = COMMAND_EXEC,
5678 .jim_handler = jim_target_halt,
5679 .help = "used internally for reset processing",
5682 .name = "arp_waitstate",
5683 .mode = COMMAND_EXEC,
5684 .jim_handler = jim_target_wait_state,
5685 .help = "used internally for reset processing",
5688 .name = "invoke-event",
5689 .mode = COMMAND_EXEC,
5690 .jim_handler = jim_target_invoke_event,
5691 .help = "invoke handler for specified event",
5692 .usage = "event_name",
5694 COMMAND_REGISTRATION_DONE
5697 static int target_create(struct jim_getopt_info *goi)
5704 struct target *target;
5705 struct command_context *cmd_ctx;
5707 cmd_ctx = current_command_context(goi->interp);
5710 if (goi->argc < 3) {
5711 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5716 jim_getopt_obj(goi, &new_cmd);
5717 /* does this command exist? */
5718 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
5720 cp = Jim_GetString(new_cmd, NULL);
5721 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5726 e = jim_getopt_string(goi, &cp, NULL);
5729 struct transport *tr = get_current_transport();
5730 if (tr->override_target) {
5731 e = tr->override_target(&cp);
5732 if (e != ERROR_OK) {
5733 LOG_ERROR("The selected transport doesn't support this target");
5736 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5738 /* now does target type exist */
5739 for (x = 0 ; target_types[x] ; x++) {
5740 if (strcmp(cp, target_types[x]->name) == 0) {
5745 if (!target_types[x]) {
5746 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5747 for (x = 0 ; target_types[x] ; x++) {
5748 if (target_types[x + 1]) {
5749 Jim_AppendStrings(goi->interp,
5750 Jim_GetResult(goi->interp),
5751 target_types[x]->name,
5754 Jim_AppendStrings(goi->interp,
5755 Jim_GetResult(goi->interp),
5757 target_types[x]->name, NULL);
5764 target = calloc(1, sizeof(struct target));
5766 LOG_ERROR("Out of memory");
5770 /* set target number */
5771 target->target_number = new_target_number();
5773 /* allocate memory for each unique target type */
5774 target->type = malloc(sizeof(struct target_type));
5775 if (!target->type) {
5776 LOG_ERROR("Out of memory");
5781 memcpy(target->type, target_types[x], sizeof(struct target_type));
5783 /* default to first core, override with -coreid */
5786 target->working_area = 0x0;
5787 target->working_area_size = 0x0;
5788 target->working_areas = NULL;
5789 target->backup_working_area = 0;
5791 target->state = TARGET_UNKNOWN;
5792 target->debug_reason = DBG_REASON_UNDEFINED;
5793 target->reg_cache = NULL;
5794 target->breakpoints = NULL;
5795 target->watchpoints = NULL;
5796 target->next = NULL;
5797 target->arch_info = NULL;
5799 target->verbose_halt_msg = true;
5801 target->halt_issued = false;
5803 /* initialize trace information */
5804 target->trace_info = calloc(1, sizeof(struct trace));
5805 if (!target->trace_info) {
5806 LOG_ERROR("Out of memory");
5812 target->dbgmsg = NULL;
5813 target->dbg_msg_enabled = 0;
5815 target->endianness = TARGET_ENDIAN_UNKNOWN;
5817 target->rtos = NULL;
5818 target->rtos_auto_detect = false;
5820 target->gdb_port_override = NULL;
5821 target->gdb_max_connections = 1;
5823 /* Do the rest as "configure" options */
5824 goi->isconfigure = 1;
5825 e = target_configure(goi, target);
5828 if (target->has_dap) {
5829 if (!target->dap_configured) {
5830 Jim_SetResultString(goi->interp, "-dap ?name? required when creating target", -1);
5834 if (!target->tap_configured) {
5835 Jim_SetResultString(goi->interp, "-chain-position ?name? required when creating target", -1);
5839 /* tap must be set after target was configured */
5845 rtos_destroy(target);
5846 free(target->gdb_port_override);
5847 free(target->trace_info);
5853 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5854 /* default endian to little if not specified */
5855 target->endianness = TARGET_LITTLE_ENDIAN;
5858 cp = Jim_GetString(new_cmd, NULL);
5859 target->cmd_name = strdup(cp);
5860 if (!target->cmd_name) {
5861 LOG_ERROR("Out of memory");
5862 rtos_destroy(target);
5863 free(target->gdb_port_override);
5864 free(target->trace_info);
5870 if (target->type->target_create) {
5871 e = (*(target->type->target_create))(target, goi->interp);
5872 if (e != ERROR_OK) {
5873 LOG_DEBUG("target_create failed");
5874 free(target->cmd_name);
5875 rtos_destroy(target);
5876 free(target->gdb_port_override);
5877 free(target->trace_info);
5884 /* create the target specific commands */
5885 if (target->type->commands) {
5886 e = register_commands(cmd_ctx, NULL, target->type->commands);
5888 LOG_ERROR("unable to register '%s' commands", cp);
5891 /* now - create the new target name command */
5892 const struct command_registration target_subcommands[] = {
5894 .chain = target_instance_command_handlers,
5897 .chain = target->type->commands,
5899 COMMAND_REGISTRATION_DONE
5901 const struct command_registration target_commands[] = {
5904 .mode = COMMAND_ANY,
5905 .help = "target command group",
5907 .chain = target_subcommands,
5909 COMMAND_REGISTRATION_DONE
5911 e = register_commands_override_target(cmd_ctx, NULL, target_commands, target);
5912 if (e != ERROR_OK) {
5913 if (target->type->deinit_target)
5914 target->type->deinit_target(target);
5915 free(target->cmd_name);
5916 rtos_destroy(target);
5917 free(target->gdb_port_override);
5918 free(target->trace_info);
5924 /* append to end of list */
5925 append_to_list_all_targets(target);
5927 cmd_ctx->current_target = target;
5931 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5934 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5937 struct command_context *cmd_ctx = current_command_context(interp);
5940 struct target *target = get_current_target_or_null(cmd_ctx);
5942 Jim_SetResultString(interp, target_name(target), -1);
5946 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5949 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5952 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5953 for (unsigned x = 0; target_types[x]; x++) {
5954 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5955 Jim_NewStringObj(interp, target_types[x]->name, -1));
5960 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5963 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5966 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5967 struct target *target = all_targets;
5969 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5970 Jim_NewStringObj(interp, target_name(target), -1));
5971 target = target->next;
5976 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5979 const char *targetname;
5981 struct target *target = NULL;
5982 struct target_list *head, *curr, *new;
5987 LOG_DEBUG("%d", argc);
5988 /* argv[1] = target to associate in smp
5989 * argv[2] = target to associate in smp
5993 for (i = 1; i < argc; i++) {
5995 targetname = Jim_GetString(argv[i], &len);
5996 target = get_target(targetname);
5997 LOG_DEBUG("%s ", targetname);
5999 new = malloc(sizeof(struct target_list));
6000 new->target = target;
6011 /* now parse the list of cpu and put the target in smp mode*/
6015 target = curr->target;
6017 target->head = head;
6021 if (target && target->rtos)
6022 retval = rtos_smp_init(head->target);
6028 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6030 struct jim_getopt_info goi;
6031 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
6033 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
6034 "<name> <target_type> [<target_options> ...]");
6037 return target_create(&goi);
6040 static const struct command_registration target_subcommand_handlers[] = {
6043 .mode = COMMAND_CONFIG,
6044 .handler = handle_target_init_command,
6045 .help = "initialize targets",
6050 .mode = COMMAND_CONFIG,
6051 .jim_handler = jim_target_create,
6052 .usage = "name type '-chain-position' name [options ...]",
6053 .help = "Creates and selects a new target",
6057 .mode = COMMAND_ANY,
6058 .jim_handler = jim_target_current,
6059 .help = "Returns the currently selected target",
6063 .mode = COMMAND_ANY,
6064 .jim_handler = jim_target_types,
6065 .help = "Returns the available target types as "
6066 "a list of strings",
6070 .mode = COMMAND_ANY,
6071 .jim_handler = jim_target_names,
6072 .help = "Returns the names of all targets as a list of strings",
6076 .mode = COMMAND_ANY,
6077 .jim_handler = jim_target_smp,
6078 .usage = "targetname1 targetname2 ...",
6079 .help = "gather several target in a smp list"
6082 COMMAND_REGISTRATION_DONE
6086 target_addr_t address;
6092 static int fastload_num;
6093 static struct fast_load *fastload;
6095 static void free_fastload(void)
6098 for (int i = 0; i < fastload_num; i++)
6099 free(fastload[i].data);
6105 COMMAND_HANDLER(handle_fast_load_image_command)
6109 uint32_t image_size;
6110 target_addr_t min_address = 0;
6111 target_addr_t max_address = -1;
6115 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
6116 &image, &min_address, &max_address);
6117 if (retval != ERROR_OK)
6120 struct duration bench;
6121 duration_start(&bench);
6123 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
6124 if (retval != ERROR_OK)
6129 fastload_num = image.num_sections;
6130 fastload = malloc(sizeof(struct fast_load)*image.num_sections);
6132 command_print(CMD, "out of memory");
6133 image_close(&image);
6136 memset(fastload, 0, sizeof(struct fast_load)*image.num_sections);
6137 for (unsigned int i = 0; i < image.num_sections; i++) {
6138 buffer = malloc(image.sections[i].size);
6140 command_print(CMD, "error allocating buffer for section (%d bytes)",
6141 (int)(image.sections[i].size));
6142 retval = ERROR_FAIL;
6146 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
6147 if (retval != ERROR_OK) {
6152 uint32_t offset = 0;
6153 uint32_t length = buf_cnt;
6155 /* DANGER!!! beware of unsigned comparison here!!! */
6157 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
6158 (image.sections[i].base_address < max_address)) {
6159 if (image.sections[i].base_address < min_address) {
6160 /* clip addresses below */
6161 offset += min_address-image.sections[i].base_address;
6165 if (image.sections[i].base_address + buf_cnt > max_address)
6166 length -= (image.sections[i].base_address + buf_cnt)-max_address;
6168 fastload[i].address = image.sections[i].base_address + offset;
6169 fastload[i].data = malloc(length);
6170 if (!fastload[i].data) {
6172 command_print(CMD, "error allocating buffer for section (%" PRIu32 " bytes)",
6174 retval = ERROR_FAIL;
6177 memcpy(fastload[i].data, buffer + offset, length);
6178 fastload[i].length = length;
6180 image_size += length;
6181 command_print(CMD, "%u bytes written at address 0x%8.8x",
6182 (unsigned int)length,
6183 ((unsigned int)(image.sections[i].base_address + offset)));
6189 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
6190 command_print(CMD, "Loaded %" PRIu32 " bytes "
6191 "in %fs (%0.3f KiB/s)", image_size,
6192 duration_elapsed(&bench), duration_kbps(&bench, image_size));
6195 "WARNING: image has not been loaded to target!"
6196 "You can issue a 'fast_load' to finish loading.");
6199 image_close(&image);
6201 if (retval != ERROR_OK)
6207 COMMAND_HANDLER(handle_fast_load_command)
6210 return ERROR_COMMAND_SYNTAX_ERROR;
6212 LOG_ERROR("No image in memory");
6216 int64_t ms = timeval_ms();
6218 int retval = ERROR_OK;
6219 for (i = 0; i < fastload_num; i++) {
6220 struct target *target = get_current_target(CMD_CTX);
6221 command_print(CMD, "Write to 0x%08x, length 0x%08x",
6222 (unsigned int)(fastload[i].address),
6223 (unsigned int)(fastload[i].length));
6224 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
6225 if (retval != ERROR_OK)
6227 size += fastload[i].length;
6229 if (retval == ERROR_OK) {
6230 int64_t after = timeval_ms();
6231 command_print(CMD, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
6236 static const struct command_registration target_command_handlers[] = {
6239 .handler = handle_targets_command,
6240 .mode = COMMAND_ANY,
6241 .help = "change current default target (one parameter) "
6242 "or prints table of all targets (no parameters)",
6243 .usage = "[target]",
6247 .mode = COMMAND_CONFIG,
6248 .help = "configure target",
6249 .chain = target_subcommand_handlers,
6252 COMMAND_REGISTRATION_DONE
6255 int target_register_commands(struct command_context *cmd_ctx)
6257 return register_commands(cmd_ctx, NULL, target_command_handlers);
6260 static bool target_reset_nag = true;
6262 bool get_target_reset_nag(void)
6264 return target_reset_nag;
6267 COMMAND_HANDLER(handle_target_reset_nag)
6269 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
6270 &target_reset_nag, "Nag after each reset about options to improve "
6274 COMMAND_HANDLER(handle_ps_command)
6276 struct target *target = get_current_target(CMD_CTX);
6278 if (target->state != TARGET_HALTED) {
6279 LOG_INFO("target not halted !!");
6283 if ((target->rtos) && (target->rtos->type)
6284 && (target->rtos->type->ps_command)) {
6285 display = target->rtos->type->ps_command(target);
6286 command_print(CMD, "%s", display);
6291 return ERROR_TARGET_FAILURE;
6295 static void binprint(struct command_invocation *cmd, const char *text, const uint8_t *buf, int size)
6298 command_print_sameline(cmd, "%s", text);
6299 for (int i = 0; i < size; i++)
6300 command_print_sameline(cmd, " %02x", buf[i]);
6301 command_print(cmd, " ");
6304 COMMAND_HANDLER(handle_test_mem_access_command)
6306 struct target *target = get_current_target(CMD_CTX);
6308 int retval = ERROR_OK;
6310 if (target->state != TARGET_HALTED) {
6311 LOG_INFO("target not halted !!");
6316 return ERROR_COMMAND_SYNTAX_ERROR;
6318 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
6321 size_t num_bytes = test_size + 4;
6323 struct working_area *wa = NULL;
6324 retval = target_alloc_working_area(target, num_bytes, &wa);
6325 if (retval != ERROR_OK) {
6326 LOG_ERROR("Not enough working area");
6330 uint8_t *test_pattern = malloc(num_bytes);
6332 for (size_t i = 0; i < num_bytes; i++)
6333 test_pattern[i] = rand();
6335 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6336 if (retval != ERROR_OK) {
6337 LOG_ERROR("Test pattern write failed");
6341 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6342 for (int size = 1; size <= 4; size *= 2) {
6343 for (int offset = 0; offset < 4; offset++) {
6344 uint32_t count = test_size / size;
6345 size_t host_bufsiz = (count + 2) * size + host_offset;
6346 uint8_t *read_ref = malloc(host_bufsiz);
6347 uint8_t *read_buf = malloc(host_bufsiz);
6349 for (size_t i = 0; i < host_bufsiz; i++) {
6350 read_ref[i] = rand();
6351 read_buf[i] = read_ref[i];
6353 command_print_sameline(CMD,
6354 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
6355 size, offset, host_offset ? "un" : "");
6357 struct duration bench;
6358 duration_start(&bench);
6360 retval = target_read_memory(target, wa->address + offset, size, count,
6361 read_buf + size + host_offset);
6363 duration_measure(&bench);
6365 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6366 command_print(CMD, "Unsupported alignment");
6368 } else if (retval != ERROR_OK) {
6369 command_print(CMD, "Memory read failed");
6373 /* replay on host */
6374 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
6377 int result = memcmp(read_ref, read_buf, host_bufsiz);
6379 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6380 duration_elapsed(&bench),
6381 duration_kbps(&bench, count * size));
6383 command_print(CMD, "Compare failed");
6384 binprint(CMD, "ref:", read_ref, host_bufsiz);
6385 binprint(CMD, "buf:", read_buf, host_bufsiz);
6398 target_free_working_area(target, wa);
6401 num_bytes = test_size + 4 + 4 + 4;
6403 retval = target_alloc_working_area(target, num_bytes, &wa);
6404 if (retval != ERROR_OK) {
6405 LOG_ERROR("Not enough working area");
6409 test_pattern = malloc(num_bytes);
6411 for (size_t i = 0; i < num_bytes; i++)
6412 test_pattern[i] = rand();
6414 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6415 for (int size = 1; size <= 4; size *= 2) {
6416 for (int offset = 0; offset < 4; offset++) {
6417 uint32_t count = test_size / size;
6418 size_t host_bufsiz = count * size + host_offset;
6419 uint8_t *read_ref = malloc(num_bytes);
6420 uint8_t *read_buf = malloc(num_bytes);
6421 uint8_t *write_buf = malloc(host_bufsiz);
6423 for (size_t i = 0; i < host_bufsiz; i++)
6424 write_buf[i] = rand();
6425 command_print_sameline(CMD,
6426 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
6427 size, offset, host_offset ? "un" : "");
6429 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6430 if (retval != ERROR_OK) {
6431 command_print(CMD, "Test pattern write failed");
6435 /* replay on host */
6436 memcpy(read_ref, test_pattern, num_bytes);
6437 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
6439 struct duration bench;
6440 duration_start(&bench);
6442 retval = target_write_memory(target, wa->address + size + offset, size, count,
6443 write_buf + host_offset);
6445 duration_measure(&bench);
6447 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6448 command_print(CMD, "Unsupported alignment");
6450 } else if (retval != ERROR_OK) {
6451 command_print(CMD, "Memory write failed");
6456 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
6457 if (retval != ERROR_OK) {
6458 command_print(CMD, "Test pattern write failed");
6463 int result = memcmp(read_ref, read_buf, num_bytes);
6465 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6466 duration_elapsed(&bench),
6467 duration_kbps(&bench, count * size));
6469 command_print(CMD, "Compare failed");
6470 binprint(CMD, "ref:", read_ref, num_bytes);
6471 binprint(CMD, "buf:", read_buf, num_bytes);
6483 target_free_working_area(target, wa);
6487 static const struct command_registration target_exec_command_handlers[] = {
6489 .name = "fast_load_image",
6490 .handler = handle_fast_load_image_command,
6491 .mode = COMMAND_ANY,
6492 .help = "Load image into server memory for later use by "
6493 "fast_load; primarily for profiling",
6494 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6495 "[min_address [max_length]]",
6498 .name = "fast_load",
6499 .handler = handle_fast_load_command,
6500 .mode = COMMAND_EXEC,
6501 .help = "loads active fast load image to current target "
6502 "- mainly for profiling purposes",
6507 .handler = handle_profile_command,
6508 .mode = COMMAND_EXEC,
6509 .usage = "seconds filename [start end]",
6510 .help = "profiling samples the CPU PC",
6512 /** @todo don't register virt2phys() unless target supports it */
6514 .name = "virt2phys",
6515 .handler = handle_virt2phys_command,
6516 .mode = COMMAND_ANY,
6517 .help = "translate a virtual address into a physical address",
6518 .usage = "virtual_address",
6522 .handler = handle_reg_command,
6523 .mode = COMMAND_EXEC,
6524 .help = "display (reread from target with \"force\") or set a register; "
6525 "with no arguments, displays all registers and their values",
6526 .usage = "[(register_number|register_name) [(value|'force')]]",
6530 .handler = handle_poll_command,
6531 .mode = COMMAND_EXEC,
6532 .help = "poll target state; or reconfigure background polling",
6533 .usage = "['on'|'off']",
6536 .name = "wait_halt",
6537 .handler = handle_wait_halt_command,
6538 .mode = COMMAND_EXEC,
6539 .help = "wait up to the specified number of milliseconds "
6540 "(default 5000) for a previously requested halt",
6541 .usage = "[milliseconds]",
6545 .handler = handle_halt_command,
6546 .mode = COMMAND_EXEC,
6547 .help = "request target to halt, then wait up to the specified "
6548 "number of milliseconds (default 5000) for it to complete",
6549 .usage = "[milliseconds]",
6553 .handler = handle_resume_command,
6554 .mode = COMMAND_EXEC,
6555 .help = "resume target execution from current PC or address",
6556 .usage = "[address]",
6560 .handler = handle_reset_command,
6561 .mode = COMMAND_EXEC,
6562 .usage = "[run|halt|init]",
6563 .help = "Reset all targets into the specified mode. "
6564 "Default reset mode is run, if not given.",
6567 .name = "soft_reset_halt",
6568 .handler = handle_soft_reset_halt_command,
6569 .mode = COMMAND_EXEC,
6571 .help = "halt the target and do a soft reset",
6575 .handler = handle_step_command,
6576 .mode = COMMAND_EXEC,
6577 .help = "step one instruction from current PC or address",
6578 .usage = "[address]",
6582 .handler = handle_md_command,
6583 .mode = COMMAND_EXEC,
6584 .help = "display memory double-words",
6585 .usage = "['phys'] address [count]",
6589 .handler = handle_md_command,
6590 .mode = COMMAND_EXEC,
6591 .help = "display memory words",
6592 .usage = "['phys'] address [count]",
6596 .handler = handle_md_command,
6597 .mode = COMMAND_EXEC,
6598 .help = "display memory half-words",
6599 .usage = "['phys'] address [count]",
6603 .handler = handle_md_command,
6604 .mode = COMMAND_EXEC,
6605 .help = "display memory bytes",
6606 .usage = "['phys'] address [count]",
6610 .handler = handle_mw_command,
6611 .mode = COMMAND_EXEC,
6612 .help = "write memory double-word",
6613 .usage = "['phys'] address value [count]",
6617 .handler = handle_mw_command,
6618 .mode = COMMAND_EXEC,
6619 .help = "write memory word",
6620 .usage = "['phys'] address value [count]",
6624 .handler = handle_mw_command,
6625 .mode = COMMAND_EXEC,
6626 .help = "write memory half-word",
6627 .usage = "['phys'] address value [count]",
6631 .handler = handle_mw_command,
6632 .mode = COMMAND_EXEC,
6633 .help = "write memory byte",
6634 .usage = "['phys'] address value [count]",
6638 .handler = handle_bp_command,
6639 .mode = COMMAND_EXEC,
6640 .help = "list or set hardware or software breakpoint",
6641 .usage = "[<address> [<asid>] <length> ['hw'|'hw_ctx']]",
6645 .handler = handle_rbp_command,
6646 .mode = COMMAND_EXEC,
6647 .help = "remove breakpoint",
6648 .usage = "'all' | address",
6652 .handler = handle_wp_command,
6653 .mode = COMMAND_EXEC,
6654 .help = "list (no params) or create watchpoints",
6655 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
6659 .handler = handle_rwp_command,
6660 .mode = COMMAND_EXEC,
6661 .help = "remove watchpoint",
6665 .name = "load_image",
6666 .handler = handle_load_image_command,
6667 .mode = COMMAND_EXEC,
6668 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6669 "[min_address] [max_length]",
6672 .name = "dump_image",
6673 .handler = handle_dump_image_command,
6674 .mode = COMMAND_EXEC,
6675 .usage = "filename address size",
6678 .name = "verify_image_checksum",
6679 .handler = handle_verify_image_checksum_command,
6680 .mode = COMMAND_EXEC,
6681 .usage = "filename [offset [type]]",
6684 .name = "verify_image",
6685 .handler = handle_verify_image_command,
6686 .mode = COMMAND_EXEC,
6687 .usage = "filename [offset [type]]",
6690 .name = "test_image",
6691 .handler = handle_test_image_command,
6692 .mode = COMMAND_EXEC,
6693 .usage = "filename [offset [type]]",
6696 .name = "mem2array",
6697 .mode = COMMAND_EXEC,
6698 .jim_handler = jim_mem2array,
6699 .help = "read 8/16/32 bit memory and return as a TCL array "
6700 "for script processing",
6701 .usage = "arrayname bitwidth address count",
6704 .name = "array2mem",
6705 .mode = COMMAND_EXEC,
6706 .jim_handler = jim_array2mem,
6707 .help = "convert a TCL array to memory locations "
6708 "and write the 8/16/32 bit values",
6709 .usage = "arrayname bitwidth address count",
6712 .name = "reset_nag",
6713 .handler = handle_target_reset_nag,
6714 .mode = COMMAND_ANY,
6715 .help = "Nag after each reset about options that could have been "
6716 "enabled to improve performance.",
6717 .usage = "['enable'|'disable']",
6721 .handler = handle_ps_command,
6722 .mode = COMMAND_EXEC,
6723 .help = "list all tasks",
6727 .name = "test_mem_access",
6728 .handler = handle_test_mem_access_command,
6729 .mode = COMMAND_EXEC,
6730 .help = "Test the target's memory access functions",
6734 COMMAND_REGISTRATION_DONE
6736 static int target_register_user_commands(struct command_context *cmd_ctx)
6738 int retval = ERROR_OK;
6739 retval = target_request_register_commands(cmd_ctx);
6740 if (retval != ERROR_OK)
6743 retval = trace_register_commands(cmd_ctx);
6744 if (retval != ERROR_OK)
6748 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);