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/time_support.h>
45 #include <jtag/jtag.h>
46 #include <flash/nor/core.h>
49 #include "target_type.h"
50 #include "target_request.h"
51 #include "breakpoints.h"
55 #include "rtos/rtos.h"
56 #include "transport/transport.h"
59 /* default halt wait timeout (ms) */
60 #define DEFAULT_HALT_TIMEOUT 5000
62 static int target_read_buffer_default(struct target *target, target_addr_t address,
63 uint32_t count, uint8_t *buffer);
64 static int target_write_buffer_default(struct target *target, target_addr_t address,
65 uint32_t count, const uint8_t *buffer);
66 static int target_array2mem(Jim_Interp *interp, struct target *target,
67 int argc, Jim_Obj * const *argv);
68 static int target_mem2array(Jim_Interp *interp, struct target *target,
69 int argc, Jim_Obj * const *argv);
70 static int target_register_user_commands(struct command_context *cmd_ctx);
71 static int target_get_gdb_fileio_info_default(struct target *target,
72 struct gdb_fileio_info *fileio_info);
73 static int target_gdb_fileio_end_default(struct target *target, int retcode,
74 int fileio_errno, bool ctrl_c);
77 extern struct target_type arm7tdmi_target;
78 extern struct target_type arm720t_target;
79 extern struct target_type arm9tdmi_target;
80 extern struct target_type arm920t_target;
81 extern struct target_type arm966e_target;
82 extern struct target_type arm946e_target;
83 extern struct target_type arm926ejs_target;
84 extern struct target_type fa526_target;
85 extern struct target_type feroceon_target;
86 extern struct target_type dragonite_target;
87 extern struct target_type xscale_target;
88 extern struct target_type cortexm_target;
89 extern struct target_type cortexa_target;
90 extern struct target_type aarch64_target;
91 extern struct target_type cortexr4_target;
92 extern struct target_type arm11_target;
93 extern struct target_type ls1_sap_target;
94 extern struct target_type mips_m4k_target;
95 extern struct target_type mips_mips64_target;
96 extern struct target_type avr_target;
97 extern struct target_type dsp563xx_target;
98 extern struct target_type dsp5680xx_target;
99 extern struct target_type testee_target;
100 extern struct target_type avr32_ap7k_target;
101 extern struct target_type hla_target;
102 extern struct target_type nds32_v2_target;
103 extern struct target_type nds32_v3_target;
104 extern struct target_type nds32_v3m_target;
105 extern struct target_type or1k_target;
106 extern struct target_type quark_x10xx_target;
107 extern struct target_type quark_d20xx_target;
108 extern struct target_type stm8_target;
109 extern struct target_type riscv_target;
110 extern struct target_type mem_ap_target;
111 extern struct target_type esirisc_target;
112 extern struct target_type arcv2_target;
114 static struct target_type *target_types[] = {
154 struct target *all_targets;
155 static struct target_event_callback *target_event_callbacks;
156 static struct target_timer_callback *target_timer_callbacks;
157 static LIST_HEAD(target_reset_callback_list);
158 static LIST_HEAD(target_trace_callback_list);
159 static const int polling_interval = 100;
161 static const struct jim_nvp nvp_assert[] = {
162 { .name = "assert", NVP_ASSERT },
163 { .name = "deassert", NVP_DEASSERT },
164 { .name = "T", NVP_ASSERT },
165 { .name = "F", NVP_DEASSERT },
166 { .name = "t", NVP_ASSERT },
167 { .name = "f", NVP_DEASSERT },
168 { .name = NULL, .value = -1 }
171 static const struct jim_nvp nvp_error_target[] = {
172 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
173 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
174 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
175 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
176 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
177 { .value = ERROR_TARGET_UNALIGNED_ACCESS, .name = "err-unaligned-access" },
178 { .value = ERROR_TARGET_DATA_ABORT, .name = "err-data-abort" },
179 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE, .name = "err-resource-not-available" },
180 { .value = ERROR_TARGET_TRANSLATION_FAULT, .name = "err-translation-fault" },
181 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
182 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
183 { .value = -1, .name = NULL }
186 static const char *target_strerror_safe(int err)
188 const struct jim_nvp *n;
190 n = jim_nvp_value2name_simple(nvp_error_target, err);
197 static const struct jim_nvp nvp_target_event[] = {
199 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
200 { .value = TARGET_EVENT_HALTED, .name = "halted" },
201 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
202 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
203 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
204 { .value = TARGET_EVENT_STEP_START, .name = "step-start" },
205 { .value = TARGET_EVENT_STEP_END, .name = "step-end" },
207 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
208 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
210 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
211 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
212 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
213 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
214 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
215 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
216 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
217 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
219 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
220 { .value = TARGET_EVENT_EXAMINE_FAIL, .name = "examine-fail" },
221 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
223 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
224 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
226 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
227 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
229 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
230 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END, .name = "gdb-flash-write-end" },
232 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
233 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END, .name = "gdb-flash-erase-end" },
235 { .value = TARGET_EVENT_TRACE_CONFIG, .name = "trace-config" },
237 { .name = NULL, .value = -1 }
240 static const struct jim_nvp nvp_target_state[] = {
241 { .name = "unknown", .value = TARGET_UNKNOWN },
242 { .name = "running", .value = TARGET_RUNNING },
243 { .name = "halted", .value = TARGET_HALTED },
244 { .name = "reset", .value = TARGET_RESET },
245 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
246 { .name = NULL, .value = -1 },
249 static const struct jim_nvp nvp_target_debug_reason[] = {
250 { .name = "debug-request", .value = DBG_REASON_DBGRQ },
251 { .name = "breakpoint", .value = DBG_REASON_BREAKPOINT },
252 { .name = "watchpoint", .value = DBG_REASON_WATCHPOINT },
253 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
254 { .name = "single-step", .value = DBG_REASON_SINGLESTEP },
255 { .name = "target-not-halted", .value = DBG_REASON_NOTHALTED },
256 { .name = "program-exit", .value = DBG_REASON_EXIT },
257 { .name = "exception-catch", .value = DBG_REASON_EXC_CATCH },
258 { .name = "undefined", .value = DBG_REASON_UNDEFINED },
259 { .name = NULL, .value = -1 },
262 static const struct jim_nvp nvp_target_endian[] = {
263 { .name = "big", .value = TARGET_BIG_ENDIAN },
264 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
265 { .name = "be", .value = TARGET_BIG_ENDIAN },
266 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
267 { .name = NULL, .value = -1 },
270 static const struct jim_nvp nvp_reset_modes[] = {
271 { .name = "unknown", .value = RESET_UNKNOWN },
272 { .name = "run", .value = RESET_RUN },
273 { .name = "halt", .value = RESET_HALT },
274 { .name = "init", .value = RESET_INIT },
275 { .name = NULL, .value = -1 },
278 const char *debug_reason_name(struct target *t)
282 cp = jim_nvp_value2name_simple(nvp_target_debug_reason,
283 t->debug_reason)->name;
285 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
286 cp = "(*BUG*unknown*BUG*)";
291 const char *target_state_name(struct target *t)
294 cp = jim_nvp_value2name_simple(nvp_target_state, t->state)->name;
296 LOG_ERROR("Invalid target state: %d", (int)(t->state));
297 cp = "(*BUG*unknown*BUG*)";
300 if (!target_was_examined(t) && t->defer_examine)
301 cp = "examine deferred";
306 const char *target_event_name(enum target_event event)
309 cp = jim_nvp_value2name_simple(nvp_target_event, event)->name;
311 LOG_ERROR("Invalid target event: %d", (int)(event));
312 cp = "(*BUG*unknown*BUG*)";
317 const char *target_reset_mode_name(enum target_reset_mode reset_mode)
320 cp = jim_nvp_value2name_simple(nvp_reset_modes, reset_mode)->name;
322 LOG_ERROR("Invalid target reset mode: %d", (int)(reset_mode));
323 cp = "(*BUG*unknown*BUG*)";
328 /* determine the number of the new target */
329 static int new_target_number(void)
334 /* number is 0 based */
338 if (x < t->target_number)
339 x = t->target_number;
345 static void append_to_list_all_targets(struct target *target)
347 struct target **t = &all_targets;
354 /* read a uint64_t from a buffer in target memory endianness */
355 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
357 if (target->endianness == TARGET_LITTLE_ENDIAN)
358 return le_to_h_u64(buffer);
360 return be_to_h_u64(buffer);
363 /* read a uint32_t from a buffer in target memory endianness */
364 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
366 if (target->endianness == TARGET_LITTLE_ENDIAN)
367 return le_to_h_u32(buffer);
369 return be_to_h_u32(buffer);
372 /* read a uint24_t from a buffer in target memory endianness */
373 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
375 if (target->endianness == TARGET_LITTLE_ENDIAN)
376 return le_to_h_u24(buffer);
378 return be_to_h_u24(buffer);
381 /* read a uint16_t from a buffer in target memory endianness */
382 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
384 if (target->endianness == TARGET_LITTLE_ENDIAN)
385 return le_to_h_u16(buffer);
387 return be_to_h_u16(buffer);
390 /* write a uint64_t to a buffer in target memory endianness */
391 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
393 if (target->endianness == TARGET_LITTLE_ENDIAN)
394 h_u64_to_le(buffer, value);
396 h_u64_to_be(buffer, value);
399 /* write a uint32_t to a buffer in target memory endianness */
400 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
402 if (target->endianness == TARGET_LITTLE_ENDIAN)
403 h_u32_to_le(buffer, value);
405 h_u32_to_be(buffer, value);
408 /* write a uint24_t to a buffer in target memory endianness */
409 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
411 if (target->endianness == TARGET_LITTLE_ENDIAN)
412 h_u24_to_le(buffer, value);
414 h_u24_to_be(buffer, value);
417 /* write a uint16_t to a buffer in target memory endianness */
418 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
420 if (target->endianness == TARGET_LITTLE_ENDIAN)
421 h_u16_to_le(buffer, value);
423 h_u16_to_be(buffer, value);
426 /* write a uint8_t to a buffer in target memory endianness */
427 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
432 /* write a uint64_t array to a buffer in target memory endianness */
433 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
436 for (i = 0; i < count; i++)
437 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
440 /* write a uint32_t array to a buffer in target memory endianness */
441 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
444 for (i = 0; i < count; i++)
445 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
448 /* write a uint16_t array to a buffer in target memory endianness */
449 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
452 for (i = 0; i < count; i++)
453 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
456 /* write a uint64_t array to a buffer in target memory endianness */
457 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
460 for (i = 0; i < count; i++)
461 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
464 /* write a uint32_t array to a buffer in target memory endianness */
465 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
468 for (i = 0; i < count; i++)
469 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
472 /* write a uint16_t array to a buffer in target memory endianness */
473 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
476 for (i = 0; i < count; i++)
477 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
480 /* return a pointer to a configured target; id is name or number */
481 struct target *get_target(const char *id)
483 struct target *target;
485 /* try as tcltarget name */
486 for (target = all_targets; target; target = target->next) {
487 if (target_name(target) == NULL)
489 if (strcmp(id, target_name(target)) == 0)
493 /* It's OK to remove this fallback sometime after August 2010 or so */
495 /* no match, try as number */
497 if (parse_uint(id, &num) != ERROR_OK)
500 for (target = all_targets; target; target = target->next) {
501 if (target->target_number == (int)num) {
502 LOG_WARNING("use '%s' as target identifier, not '%u'",
503 target_name(target), num);
511 /* returns a pointer to the n-th configured target */
512 struct target *get_target_by_num(int num)
514 struct target *target = all_targets;
517 if (target->target_number == num)
519 target = target->next;
525 struct target *get_current_target(struct command_context *cmd_ctx)
527 struct target *target = get_current_target_or_null(cmd_ctx);
529 if (target == NULL) {
530 LOG_ERROR("BUG: current_target out of bounds");
537 struct target *get_current_target_or_null(struct command_context *cmd_ctx)
539 return cmd_ctx->current_target_override
540 ? cmd_ctx->current_target_override
541 : cmd_ctx->current_target;
544 int target_poll(struct target *target)
548 /* We can't poll until after examine */
549 if (!target_was_examined(target)) {
550 /* Fail silently lest we pollute the log */
554 retval = target->type->poll(target);
555 if (retval != ERROR_OK)
558 if (target->halt_issued) {
559 if (target->state == TARGET_HALTED)
560 target->halt_issued = false;
562 int64_t t = timeval_ms() - target->halt_issued_time;
563 if (t > DEFAULT_HALT_TIMEOUT) {
564 target->halt_issued = false;
565 LOG_INFO("Halt timed out, wake up GDB.");
566 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
574 int target_halt(struct target *target)
577 /* We can't poll until after examine */
578 if (!target_was_examined(target)) {
579 LOG_ERROR("Target not examined yet");
583 retval = target->type->halt(target);
584 if (retval != ERROR_OK)
587 target->halt_issued = true;
588 target->halt_issued_time = timeval_ms();
594 * Make the target (re)start executing using its saved execution
595 * context (possibly with some modifications).
597 * @param target Which target should start executing.
598 * @param current True to use the target's saved program counter instead
599 * of the address parameter
600 * @param address Optionally used as the program counter.
601 * @param handle_breakpoints True iff breakpoints at the resumption PC
602 * should be skipped. (For example, maybe execution was stopped by
603 * such a breakpoint, in which case it would be counterproductive to
605 * @param debug_execution False if all working areas allocated by OpenOCD
606 * should be released and/or restored to their original contents.
607 * (This would for example be true to run some downloaded "helper"
608 * algorithm code, which resides in one such working buffer and uses
609 * another for data storage.)
611 * @todo Resolve the ambiguity about what the "debug_execution" flag
612 * signifies. For example, Target implementations don't agree on how
613 * it relates to invalidation of the register cache, or to whether
614 * breakpoints and watchpoints should be enabled. (It would seem wrong
615 * to enable breakpoints when running downloaded "helper" algorithms
616 * (debug_execution true), since the breakpoints would be set to match
617 * target firmware being debugged, not the helper algorithm.... and
618 * enabling them could cause such helpers to malfunction (for example,
619 * by overwriting data with a breakpoint instruction. On the other
620 * hand the infrastructure for running such helpers might use this
621 * procedure but rely on hardware breakpoint to detect termination.)
623 int target_resume(struct target *target, int current, target_addr_t address,
624 int handle_breakpoints, int debug_execution)
628 /* We can't poll until after examine */
629 if (!target_was_examined(target)) {
630 LOG_ERROR("Target not examined yet");
634 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
636 /* note that resume *must* be asynchronous. The CPU can halt before
637 * we poll. The CPU can even halt at the current PC as a result of
638 * a software breakpoint being inserted by (a bug?) the application.
641 * resume() triggers the event 'resumed'. The execution of TCL commands
642 * in the event handler causes the polling of targets. If the target has
643 * already halted for a breakpoint, polling will run the 'halted' event
644 * handler before the pending 'resumed' handler.
645 * Disable polling during resume() to guarantee the execution of handlers
646 * in the correct order.
648 bool save_poll = jtag_poll_get_enabled();
649 jtag_poll_set_enabled(false);
650 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
651 jtag_poll_set_enabled(save_poll);
652 if (retval != ERROR_OK)
655 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
660 static int target_process_reset(struct command_invocation *cmd, enum target_reset_mode reset_mode)
665 n = jim_nvp_value2name_simple(nvp_reset_modes, reset_mode);
666 if (n->name == NULL) {
667 LOG_ERROR("invalid reset mode");
671 struct target *target;
672 for (target = all_targets; target; target = target->next)
673 target_call_reset_callbacks(target, reset_mode);
675 /* disable polling during reset to make reset event scripts
676 * more predictable, i.e. dr/irscan & pathmove in events will
677 * not have JTAG operations injected into the middle of a sequence.
679 bool save_poll = jtag_poll_get_enabled();
681 jtag_poll_set_enabled(false);
683 sprintf(buf, "ocd_process_reset %s", n->name);
684 retval = Jim_Eval(cmd->ctx->interp, buf);
686 jtag_poll_set_enabled(save_poll);
688 if (retval != JIM_OK) {
689 Jim_MakeErrorMessage(cmd->ctx->interp);
690 command_print(cmd, "%s", Jim_GetString(Jim_GetResult(cmd->ctx->interp), NULL));
694 /* We want any events to be processed before the prompt */
695 retval = target_call_timer_callbacks_now();
697 for (target = all_targets; target; target = target->next) {
698 target->type->check_reset(target);
699 target->running_alg = false;
705 static int identity_virt2phys(struct target *target,
706 target_addr_t virtual, target_addr_t *physical)
712 static int no_mmu(struct target *target, int *enabled)
718 static int default_examine(struct target *target)
720 target_set_examined(target);
724 /* no check by default */
725 static int default_check_reset(struct target *target)
730 /* Equivalent Tcl code arp_examine_one is in src/target/startup.tcl
732 int target_examine_one(struct target *target)
734 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
736 int retval = target->type->examine(target);
737 if (retval != ERROR_OK) {
738 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_FAIL);
742 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
747 static int jtag_enable_callback(enum jtag_event event, void *priv)
749 struct target *target = priv;
751 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
754 jtag_unregister_event_callback(jtag_enable_callback, target);
756 return target_examine_one(target);
759 /* Targets that correctly implement init + examine, i.e.
760 * no communication with target during init:
764 int target_examine(void)
766 int retval = ERROR_OK;
767 struct target *target;
769 for (target = all_targets; target; target = target->next) {
770 /* defer examination, but don't skip it */
771 if (!target->tap->enabled) {
772 jtag_register_event_callback(jtag_enable_callback,
777 if (target->defer_examine)
780 int retval2 = target_examine_one(target);
781 if (retval2 != ERROR_OK) {
782 LOG_WARNING("target %s examination failed", target_name(target));
789 const char *target_type_name(struct target *target)
791 return target->type->name;
794 static int target_soft_reset_halt(struct target *target)
796 if (!target_was_examined(target)) {
797 LOG_ERROR("Target not examined yet");
800 if (!target->type->soft_reset_halt) {
801 LOG_ERROR("Target %s does not support soft_reset_halt",
802 target_name(target));
805 return target->type->soft_reset_halt(target);
809 * Downloads a target-specific native code algorithm to the target,
810 * and executes it. * Note that some targets may need to set up, enable,
811 * and tear down a breakpoint (hard or * soft) to detect algorithm
812 * termination, while others may support lower overhead schemes where
813 * soft breakpoints embedded in the algorithm automatically terminate the
816 * @param target used to run the algorithm
817 * @param num_mem_params
819 * @param num_reg_params
824 * @param arch_info target-specific description of the algorithm.
826 int target_run_algorithm(struct target *target,
827 int num_mem_params, struct mem_param *mem_params,
828 int num_reg_params, struct reg_param *reg_param,
829 uint32_t entry_point, uint32_t exit_point,
830 int timeout_ms, void *arch_info)
832 int retval = ERROR_FAIL;
834 if (!target_was_examined(target)) {
835 LOG_ERROR("Target not examined yet");
838 if (!target->type->run_algorithm) {
839 LOG_ERROR("Target type '%s' does not support %s",
840 target_type_name(target), __func__);
844 target->running_alg = true;
845 retval = target->type->run_algorithm(target,
846 num_mem_params, mem_params,
847 num_reg_params, reg_param,
848 entry_point, exit_point, timeout_ms, arch_info);
849 target->running_alg = false;
856 * Executes a target-specific native code algorithm and leaves it running.
858 * @param target used to run the algorithm
859 * @param num_mem_params
861 * @param num_reg_params
865 * @param arch_info target-specific description of the algorithm.
867 int target_start_algorithm(struct target *target,
868 int num_mem_params, struct mem_param *mem_params,
869 int num_reg_params, struct reg_param *reg_params,
870 uint32_t entry_point, uint32_t exit_point,
873 int retval = ERROR_FAIL;
875 if (!target_was_examined(target)) {
876 LOG_ERROR("Target not examined yet");
879 if (!target->type->start_algorithm) {
880 LOG_ERROR("Target type '%s' does not support %s",
881 target_type_name(target), __func__);
884 if (target->running_alg) {
885 LOG_ERROR("Target is already running an algorithm");
889 target->running_alg = true;
890 retval = target->type->start_algorithm(target,
891 num_mem_params, mem_params,
892 num_reg_params, reg_params,
893 entry_point, exit_point, arch_info);
900 * Waits for an algorithm started with target_start_algorithm() to complete.
902 * @param target used to run the algorithm
903 * @param num_mem_params
905 * @param num_reg_params
909 * @param arch_info target-specific description of the algorithm.
911 int target_wait_algorithm(struct target *target,
912 int num_mem_params, struct mem_param *mem_params,
913 int num_reg_params, struct reg_param *reg_params,
914 uint32_t exit_point, int timeout_ms,
917 int retval = ERROR_FAIL;
919 if (!target->type->wait_algorithm) {
920 LOG_ERROR("Target type '%s' does not support %s",
921 target_type_name(target), __func__);
924 if (!target->running_alg) {
925 LOG_ERROR("Target is not running an algorithm");
929 retval = target->type->wait_algorithm(target,
930 num_mem_params, mem_params,
931 num_reg_params, reg_params,
932 exit_point, timeout_ms, arch_info);
933 if (retval != ERROR_TARGET_TIMEOUT)
934 target->running_alg = false;
941 * Streams data to a circular buffer on target intended for consumption by code
942 * running asynchronously on target.
944 * This is intended for applications where target-specific native code runs
945 * on the target, receives data from the circular buffer, does something with
946 * it (most likely writing it to a flash memory), and advances the circular
949 * This assumes that the helper algorithm has already been loaded to the target,
950 * but has not been started yet. Given memory and register parameters are passed
953 * The buffer is defined by (buffer_start, buffer_size) arguments and has the
956 * [buffer_start + 0, buffer_start + 4):
957 * Write Pointer address (aka head). Written and updated by this
958 * routine when new data is written to the circular buffer.
959 * [buffer_start + 4, buffer_start + 8):
960 * Read Pointer address (aka tail). Updated by code running on the
961 * target after it consumes data.
962 * [buffer_start + 8, buffer_start + buffer_size):
963 * Circular buffer contents.
965 * See contrib/loaders/flash/stm32f1x.S for an example.
967 * @param target used to run the algorithm
968 * @param buffer address on the host where data to be sent is located
969 * @param count number of blocks to send
970 * @param block_size size in bytes of each block
971 * @param num_mem_params count of memory-based params to pass to algorithm
972 * @param mem_params memory-based params to pass to algorithm
973 * @param num_reg_params count of register-based params to pass to algorithm
974 * @param reg_params memory-based params to pass to algorithm
975 * @param buffer_start address on the target of the circular buffer structure
976 * @param buffer_size size of the circular buffer structure
977 * @param entry_point address on the target to execute to start the algorithm
978 * @param exit_point address at which to set a breakpoint to catch the
979 * end of the algorithm; can be 0 if target triggers a breakpoint itself
983 int target_run_flash_async_algorithm(struct target *target,
984 const uint8_t *buffer, uint32_t count, int block_size,
985 int num_mem_params, struct mem_param *mem_params,
986 int num_reg_params, struct reg_param *reg_params,
987 uint32_t buffer_start, uint32_t buffer_size,
988 uint32_t entry_point, uint32_t exit_point, void *arch_info)
993 const uint8_t *buffer_orig = buffer;
995 /* Set up working area. First word is write pointer, second word is read pointer,
996 * rest is fifo data area. */
997 uint32_t wp_addr = buffer_start;
998 uint32_t rp_addr = buffer_start + 4;
999 uint32_t fifo_start_addr = buffer_start + 8;
1000 uint32_t fifo_end_addr = buffer_start + buffer_size;
1002 uint32_t wp = fifo_start_addr;
1003 uint32_t rp = fifo_start_addr;
1005 /* validate block_size is 2^n */
1006 assert(!block_size || !(block_size & (block_size - 1)));
1008 retval = target_write_u32(target, wp_addr, wp);
1009 if (retval != ERROR_OK)
1011 retval = target_write_u32(target, rp_addr, rp);
1012 if (retval != ERROR_OK)
1015 /* Start up algorithm on target and let it idle while writing the first chunk */
1016 retval = target_start_algorithm(target, num_mem_params, mem_params,
1017 num_reg_params, reg_params,
1022 if (retval != ERROR_OK) {
1023 LOG_ERROR("error starting target flash write algorithm");
1029 retval = target_read_u32(target, rp_addr, &rp);
1030 if (retval != ERROR_OK) {
1031 LOG_ERROR("failed to get read pointer");
1035 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1036 (size_t) (buffer - buffer_orig), count, wp, rp);
1039 LOG_ERROR("flash write algorithm aborted by target");
1040 retval = ERROR_FLASH_OPERATION_FAILED;
1044 if (((rp - fifo_start_addr) & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
1045 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
1049 /* Count the number of bytes available in the fifo without
1050 * crossing the wrap around. Make sure to not fill it completely,
1051 * because that would make wp == rp and that's the empty condition. */
1052 uint32_t thisrun_bytes;
1054 thisrun_bytes = rp - wp - block_size;
1055 else if (rp > fifo_start_addr)
1056 thisrun_bytes = fifo_end_addr - wp;
1058 thisrun_bytes = fifo_end_addr - wp - block_size;
1060 if (thisrun_bytes == 0) {
1061 /* Throttle polling a bit if transfer is (much) faster than flash
1062 * programming. The exact delay shouldn't matter as long as it's
1063 * less than buffer size / flash speed. This is very unlikely to
1064 * run when using high latency connections such as USB. */
1067 /* to stop an infinite loop on some targets check and increment a timeout
1068 * this issue was observed on a stellaris using the new ICDI interface */
1069 if (timeout++ >= 2500) {
1070 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1071 return ERROR_FLASH_OPERATION_FAILED;
1076 /* reset our timeout */
1079 /* Limit to the amount of data we actually want to write */
1080 if (thisrun_bytes > count * block_size)
1081 thisrun_bytes = count * block_size;
1083 /* Force end of large blocks to be word aligned */
1084 if (thisrun_bytes >= 16)
1085 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1087 /* Write data to fifo */
1088 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
1089 if (retval != ERROR_OK)
1092 /* Update counters and wrap write pointer */
1093 buffer += thisrun_bytes;
1094 count -= thisrun_bytes / block_size;
1095 wp += thisrun_bytes;
1096 if (wp >= fifo_end_addr)
1097 wp = fifo_start_addr;
1099 /* Store updated write pointer to target */
1100 retval = target_write_u32(target, wp_addr, wp);
1101 if (retval != ERROR_OK)
1104 /* Avoid GDB timeouts */
1108 if (retval != ERROR_OK) {
1109 /* abort flash write algorithm on target */
1110 target_write_u32(target, wp_addr, 0);
1113 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1114 num_reg_params, reg_params,
1119 if (retval2 != ERROR_OK) {
1120 LOG_ERROR("error waiting for target flash write algorithm");
1124 if (retval == ERROR_OK) {
1125 /* check if algorithm set rp = 0 after fifo writer loop finished */
1126 retval = target_read_u32(target, rp_addr, &rp);
1127 if (retval == ERROR_OK && rp == 0) {
1128 LOG_ERROR("flash write algorithm aborted by target");
1129 retval = ERROR_FLASH_OPERATION_FAILED;
1136 int target_run_read_async_algorithm(struct target *target,
1137 uint8_t *buffer, uint32_t count, int block_size,
1138 int num_mem_params, struct mem_param *mem_params,
1139 int num_reg_params, struct reg_param *reg_params,
1140 uint32_t buffer_start, uint32_t buffer_size,
1141 uint32_t entry_point, uint32_t exit_point, void *arch_info)
1146 const uint8_t *buffer_orig = buffer;
1148 /* Set up working area. First word is write pointer, second word is read pointer,
1149 * rest is fifo data area. */
1150 uint32_t wp_addr = buffer_start;
1151 uint32_t rp_addr = buffer_start + 4;
1152 uint32_t fifo_start_addr = buffer_start + 8;
1153 uint32_t fifo_end_addr = buffer_start + buffer_size;
1155 uint32_t wp = fifo_start_addr;
1156 uint32_t rp = fifo_start_addr;
1158 /* validate block_size is 2^n */
1159 assert(!block_size || !(block_size & (block_size - 1)));
1161 retval = target_write_u32(target, wp_addr, wp);
1162 if (retval != ERROR_OK)
1164 retval = target_write_u32(target, rp_addr, rp);
1165 if (retval != ERROR_OK)
1168 /* Start up algorithm on target */
1169 retval = target_start_algorithm(target, num_mem_params, mem_params,
1170 num_reg_params, reg_params,
1175 if (retval != ERROR_OK) {
1176 LOG_ERROR("error starting target flash read algorithm");
1181 retval = target_read_u32(target, wp_addr, &wp);
1182 if (retval != ERROR_OK) {
1183 LOG_ERROR("failed to get write pointer");
1187 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1188 (size_t)(buffer - buffer_orig), count, wp, rp);
1191 LOG_ERROR("flash read algorithm aborted by target");
1192 retval = ERROR_FLASH_OPERATION_FAILED;
1196 if (((wp - fifo_start_addr) & (block_size - 1)) || wp < fifo_start_addr || wp >= fifo_end_addr) {
1197 LOG_ERROR("corrupted fifo write pointer 0x%" PRIx32, wp);
1201 /* Count the number of bytes available in the fifo without
1202 * crossing the wrap around. */
1203 uint32_t thisrun_bytes;
1205 thisrun_bytes = wp - rp;
1207 thisrun_bytes = fifo_end_addr - rp;
1209 if (thisrun_bytes == 0) {
1210 /* Throttle polling a bit if transfer is (much) faster than flash
1211 * reading. The exact delay shouldn't matter as long as it's
1212 * less than buffer size / flash speed. This is very unlikely to
1213 * run when using high latency connections such as USB. */
1216 /* to stop an infinite loop on some targets check and increment a timeout
1217 * this issue was observed on a stellaris using the new ICDI interface */
1218 if (timeout++ >= 2500) {
1219 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1220 return ERROR_FLASH_OPERATION_FAILED;
1225 /* Reset our timeout */
1228 /* Limit to the amount of data we actually want to read */
1229 if (thisrun_bytes > count * block_size)
1230 thisrun_bytes = count * block_size;
1232 /* Force end of large blocks to be word aligned */
1233 if (thisrun_bytes >= 16)
1234 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1236 /* Read data from fifo */
1237 retval = target_read_buffer(target, rp, thisrun_bytes, buffer);
1238 if (retval != ERROR_OK)
1241 /* Update counters and wrap write pointer */
1242 buffer += thisrun_bytes;
1243 count -= thisrun_bytes / block_size;
1244 rp += thisrun_bytes;
1245 if (rp >= fifo_end_addr)
1246 rp = fifo_start_addr;
1248 /* Store updated write pointer to target */
1249 retval = target_write_u32(target, rp_addr, rp);
1250 if (retval != ERROR_OK)
1253 /* Avoid GDB timeouts */
1258 if (retval != ERROR_OK) {
1259 /* abort flash write algorithm on target */
1260 target_write_u32(target, rp_addr, 0);
1263 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1264 num_reg_params, reg_params,
1269 if (retval2 != ERROR_OK) {
1270 LOG_ERROR("error waiting for target flash write algorithm");
1274 if (retval == ERROR_OK) {
1275 /* check if algorithm set wp = 0 after fifo writer loop finished */
1276 retval = target_read_u32(target, wp_addr, &wp);
1277 if (retval == ERROR_OK && wp == 0) {
1278 LOG_ERROR("flash read algorithm aborted by target");
1279 retval = ERROR_FLASH_OPERATION_FAILED;
1286 int target_read_memory(struct target *target,
1287 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1289 if (!target_was_examined(target)) {
1290 LOG_ERROR("Target not examined yet");
1293 if (!target->type->read_memory) {
1294 LOG_ERROR("Target %s doesn't support read_memory", target_name(target));
1297 return target->type->read_memory(target, address, size, count, buffer);
1300 int target_read_phys_memory(struct target *target,
1301 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1303 if (!target_was_examined(target)) {
1304 LOG_ERROR("Target not examined yet");
1307 if (!target->type->read_phys_memory) {
1308 LOG_ERROR("Target %s doesn't support read_phys_memory", target_name(target));
1311 return target->type->read_phys_memory(target, address, size, count, buffer);
1314 int target_write_memory(struct target *target,
1315 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1317 if (!target_was_examined(target)) {
1318 LOG_ERROR("Target not examined yet");
1321 if (!target->type->write_memory) {
1322 LOG_ERROR("Target %s doesn't support write_memory", target_name(target));
1325 return target->type->write_memory(target, address, size, count, buffer);
1328 int target_write_phys_memory(struct target *target,
1329 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1331 if (!target_was_examined(target)) {
1332 LOG_ERROR("Target not examined yet");
1335 if (!target->type->write_phys_memory) {
1336 LOG_ERROR("Target %s doesn't support write_phys_memory", target_name(target));
1339 return target->type->write_phys_memory(target, address, size, count, buffer);
1342 int target_add_breakpoint(struct target *target,
1343 struct breakpoint *breakpoint)
1345 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1346 LOG_WARNING("target %s is not halted (add breakpoint)", target_name(target));
1347 return ERROR_TARGET_NOT_HALTED;
1349 return target->type->add_breakpoint(target, breakpoint);
1352 int target_add_context_breakpoint(struct target *target,
1353 struct breakpoint *breakpoint)
1355 if (target->state != TARGET_HALTED) {
1356 LOG_WARNING("target %s is not halted (add context breakpoint)", target_name(target));
1357 return ERROR_TARGET_NOT_HALTED;
1359 return target->type->add_context_breakpoint(target, breakpoint);
1362 int target_add_hybrid_breakpoint(struct target *target,
1363 struct breakpoint *breakpoint)
1365 if (target->state != TARGET_HALTED) {
1366 LOG_WARNING("target %s is not halted (add hybrid breakpoint)", target_name(target));
1367 return ERROR_TARGET_NOT_HALTED;
1369 return target->type->add_hybrid_breakpoint(target, breakpoint);
1372 int target_remove_breakpoint(struct target *target,
1373 struct breakpoint *breakpoint)
1375 return target->type->remove_breakpoint(target, breakpoint);
1378 int target_add_watchpoint(struct target *target,
1379 struct watchpoint *watchpoint)
1381 if (target->state != TARGET_HALTED) {
1382 LOG_WARNING("target %s is not halted (add watchpoint)", target_name(target));
1383 return ERROR_TARGET_NOT_HALTED;
1385 return target->type->add_watchpoint(target, watchpoint);
1387 int target_remove_watchpoint(struct target *target,
1388 struct watchpoint *watchpoint)
1390 return target->type->remove_watchpoint(target, watchpoint);
1392 int target_hit_watchpoint(struct target *target,
1393 struct watchpoint **hit_watchpoint)
1395 if (target->state != TARGET_HALTED) {
1396 LOG_WARNING("target %s is not halted (hit watchpoint)", target->cmd_name);
1397 return ERROR_TARGET_NOT_HALTED;
1400 if (target->type->hit_watchpoint == NULL) {
1401 /* For backward compatible, if hit_watchpoint is not implemented,
1402 * return ERROR_FAIL such that gdb_server will not take the nonsense
1407 return target->type->hit_watchpoint(target, hit_watchpoint);
1410 const char *target_get_gdb_arch(struct target *target)
1412 if (target->type->get_gdb_arch == NULL)
1414 return target->type->get_gdb_arch(target);
1417 int target_get_gdb_reg_list(struct target *target,
1418 struct reg **reg_list[], int *reg_list_size,
1419 enum target_register_class reg_class)
1421 int result = ERROR_FAIL;
1423 if (!target_was_examined(target)) {
1424 LOG_ERROR("Target not examined yet");
1428 result = target->type->get_gdb_reg_list(target, reg_list,
1429 reg_list_size, reg_class);
1432 if (result != ERROR_OK) {
1439 int target_get_gdb_reg_list_noread(struct target *target,
1440 struct reg **reg_list[], int *reg_list_size,
1441 enum target_register_class reg_class)
1443 if (target->type->get_gdb_reg_list_noread &&
1444 target->type->get_gdb_reg_list_noread(target, reg_list,
1445 reg_list_size, reg_class) == ERROR_OK)
1447 return target_get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1450 bool target_supports_gdb_connection(struct target *target)
1453 * exclude all the targets that don't provide get_gdb_reg_list
1454 * or that have explicit gdb_max_connection == 0
1456 return !!target->type->get_gdb_reg_list && !!target->gdb_max_connections;
1459 int target_step(struct target *target,
1460 int current, target_addr_t address, int handle_breakpoints)
1464 target_call_event_callbacks(target, TARGET_EVENT_STEP_START);
1466 retval = target->type->step(target, current, address, handle_breakpoints);
1467 if (retval != ERROR_OK)
1470 target_call_event_callbacks(target, TARGET_EVENT_STEP_END);
1475 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1477 if (target->state != TARGET_HALTED) {
1478 LOG_WARNING("target %s is not halted (gdb fileio)", target->cmd_name);
1479 return ERROR_TARGET_NOT_HALTED;
1481 return target->type->get_gdb_fileio_info(target, fileio_info);
1484 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1486 if (target->state != TARGET_HALTED) {
1487 LOG_WARNING("target %s is not halted (gdb fileio end)", target->cmd_name);
1488 return ERROR_TARGET_NOT_HALTED;
1490 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1493 target_addr_t target_address_max(struct target *target)
1495 unsigned bits = target_address_bits(target);
1496 if (sizeof(target_addr_t) * 8 == bits)
1497 return (target_addr_t) -1;
1499 return (((target_addr_t) 1) << bits) - 1;
1502 unsigned target_address_bits(struct target *target)
1504 if (target->type->address_bits)
1505 return target->type->address_bits(target);
1509 unsigned int target_data_bits(struct target *target)
1511 if (target->type->data_bits)
1512 return target->type->data_bits(target);
1516 static int target_profiling(struct target *target, uint32_t *samples,
1517 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1519 return target->type->profiling(target, samples, max_num_samples,
1520 num_samples, seconds);
1524 * Reset the @c examined flag for the given target.
1525 * Pure paranoia -- targets are zeroed on allocation.
1527 static void target_reset_examined(struct target *target)
1529 target->examined = false;
1532 static int handle_target(void *priv);
1534 static int target_init_one(struct command_context *cmd_ctx,
1535 struct target *target)
1537 target_reset_examined(target);
1539 struct target_type *type = target->type;
1540 if (type->examine == NULL)
1541 type->examine = default_examine;
1543 if (type->check_reset == NULL)
1544 type->check_reset = default_check_reset;
1546 assert(type->init_target != NULL);
1548 int retval = type->init_target(cmd_ctx, target);
1549 if (ERROR_OK != retval) {
1550 LOG_ERROR("target '%s' init failed", target_name(target));
1554 /* Sanity-check MMU support ... stub in what we must, to help
1555 * implement it in stages, but warn if we need to do so.
1558 if (type->virt2phys == NULL) {
1559 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1560 type->virt2phys = identity_virt2phys;
1563 /* Make sure no-MMU targets all behave the same: make no
1564 * distinction between physical and virtual addresses, and
1565 * ensure that virt2phys() is always an identity mapping.
1567 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1568 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1571 type->write_phys_memory = type->write_memory;
1572 type->read_phys_memory = type->read_memory;
1573 type->virt2phys = identity_virt2phys;
1576 if (target->type->read_buffer == NULL)
1577 target->type->read_buffer = target_read_buffer_default;
1579 if (target->type->write_buffer == NULL)
1580 target->type->write_buffer = target_write_buffer_default;
1582 if (target->type->get_gdb_fileio_info == NULL)
1583 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1585 if (target->type->gdb_fileio_end == NULL)
1586 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1588 if (target->type->profiling == NULL)
1589 target->type->profiling = target_profiling_default;
1594 static int target_init(struct command_context *cmd_ctx)
1596 struct target *target;
1599 for (target = all_targets; target; target = target->next) {
1600 retval = target_init_one(cmd_ctx, target);
1601 if (ERROR_OK != retval)
1608 retval = target_register_user_commands(cmd_ctx);
1609 if (ERROR_OK != retval)
1612 retval = target_register_timer_callback(&handle_target,
1613 polling_interval, TARGET_TIMER_TYPE_PERIODIC, cmd_ctx->interp);
1614 if (ERROR_OK != retval)
1620 COMMAND_HANDLER(handle_target_init_command)
1625 return ERROR_COMMAND_SYNTAX_ERROR;
1627 static bool target_initialized;
1628 if (target_initialized) {
1629 LOG_INFO("'target init' has already been called");
1632 target_initialized = true;
1634 retval = command_run_line(CMD_CTX, "init_targets");
1635 if (ERROR_OK != retval)
1638 retval = command_run_line(CMD_CTX, "init_target_events");
1639 if (ERROR_OK != retval)
1642 retval = command_run_line(CMD_CTX, "init_board");
1643 if (ERROR_OK != retval)
1646 LOG_DEBUG("Initializing targets...");
1647 return target_init(CMD_CTX);
1650 int target_register_event_callback(int (*callback)(struct target *target,
1651 enum target_event event, void *priv), void *priv)
1653 struct target_event_callback **callbacks_p = &target_event_callbacks;
1655 if (callback == NULL)
1656 return ERROR_COMMAND_SYNTAX_ERROR;
1659 while ((*callbacks_p)->next)
1660 callbacks_p = &((*callbacks_p)->next);
1661 callbacks_p = &((*callbacks_p)->next);
1664 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1665 (*callbacks_p)->callback = callback;
1666 (*callbacks_p)->priv = priv;
1667 (*callbacks_p)->next = NULL;
1672 int target_register_reset_callback(int (*callback)(struct target *target,
1673 enum target_reset_mode reset_mode, void *priv), void *priv)
1675 struct target_reset_callback *entry;
1677 if (callback == NULL)
1678 return ERROR_COMMAND_SYNTAX_ERROR;
1680 entry = malloc(sizeof(struct target_reset_callback));
1681 if (entry == NULL) {
1682 LOG_ERROR("error allocating buffer for reset callback entry");
1683 return ERROR_COMMAND_SYNTAX_ERROR;
1686 entry->callback = callback;
1688 list_add(&entry->list, &target_reset_callback_list);
1694 int target_register_trace_callback(int (*callback)(struct target *target,
1695 size_t len, uint8_t *data, void *priv), void *priv)
1697 struct target_trace_callback *entry;
1699 if (callback == NULL)
1700 return ERROR_COMMAND_SYNTAX_ERROR;
1702 entry = malloc(sizeof(struct target_trace_callback));
1703 if (entry == NULL) {
1704 LOG_ERROR("error allocating buffer for trace callback entry");
1705 return ERROR_COMMAND_SYNTAX_ERROR;
1708 entry->callback = callback;
1710 list_add(&entry->list, &target_trace_callback_list);
1716 int target_register_timer_callback(int (*callback)(void *priv),
1717 unsigned int time_ms, enum target_timer_type type, void *priv)
1719 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1721 if (callback == NULL)
1722 return ERROR_COMMAND_SYNTAX_ERROR;
1725 while ((*callbacks_p)->next)
1726 callbacks_p = &((*callbacks_p)->next);
1727 callbacks_p = &((*callbacks_p)->next);
1730 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1731 (*callbacks_p)->callback = callback;
1732 (*callbacks_p)->type = type;
1733 (*callbacks_p)->time_ms = time_ms;
1734 (*callbacks_p)->removed = false;
1736 gettimeofday(&(*callbacks_p)->when, NULL);
1737 timeval_add_time(&(*callbacks_p)->when, 0, time_ms * 1000);
1739 (*callbacks_p)->priv = priv;
1740 (*callbacks_p)->next = NULL;
1745 int target_unregister_event_callback(int (*callback)(struct target *target,
1746 enum target_event event, void *priv), void *priv)
1748 struct target_event_callback **p = &target_event_callbacks;
1749 struct target_event_callback *c = target_event_callbacks;
1751 if (callback == NULL)
1752 return ERROR_COMMAND_SYNTAX_ERROR;
1755 struct target_event_callback *next = c->next;
1756 if ((c->callback == callback) && (c->priv == priv)) {
1768 int target_unregister_reset_callback(int (*callback)(struct target *target,
1769 enum target_reset_mode reset_mode, void *priv), void *priv)
1771 struct target_reset_callback *entry;
1773 if (callback == NULL)
1774 return ERROR_COMMAND_SYNTAX_ERROR;
1776 list_for_each_entry(entry, &target_reset_callback_list, list) {
1777 if (entry->callback == callback && entry->priv == priv) {
1778 list_del(&entry->list);
1787 int target_unregister_trace_callback(int (*callback)(struct target *target,
1788 size_t len, uint8_t *data, void *priv), void *priv)
1790 struct target_trace_callback *entry;
1792 if (callback == NULL)
1793 return ERROR_COMMAND_SYNTAX_ERROR;
1795 list_for_each_entry(entry, &target_trace_callback_list, list) {
1796 if (entry->callback == callback && entry->priv == priv) {
1797 list_del(&entry->list);
1806 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1808 if (callback == NULL)
1809 return ERROR_COMMAND_SYNTAX_ERROR;
1811 for (struct target_timer_callback *c = target_timer_callbacks;
1813 if ((c->callback == callback) && (c->priv == priv)) {
1822 int target_call_event_callbacks(struct target *target, enum target_event event)
1824 struct target_event_callback *callback = target_event_callbacks;
1825 struct target_event_callback *next_callback;
1827 if (event == TARGET_EVENT_HALTED) {
1828 /* execute early halted first */
1829 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1832 LOG_DEBUG("target event %i (%s) for core %s", event,
1833 jim_nvp_value2name_simple(nvp_target_event, event)->name,
1834 target_name(target));
1836 target_handle_event(target, event);
1839 next_callback = callback->next;
1840 callback->callback(target, event, callback->priv);
1841 callback = next_callback;
1847 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1849 struct target_reset_callback *callback;
1851 LOG_DEBUG("target reset %i (%s)", reset_mode,
1852 jim_nvp_value2name_simple(nvp_reset_modes, reset_mode)->name);
1854 list_for_each_entry(callback, &target_reset_callback_list, list)
1855 callback->callback(target, reset_mode, callback->priv);
1860 int target_call_trace_callbacks(struct target *target, size_t len, uint8_t *data)
1862 struct target_trace_callback *callback;
1864 list_for_each_entry(callback, &target_trace_callback_list, list)
1865 callback->callback(target, len, data, callback->priv);
1870 static int target_timer_callback_periodic_restart(
1871 struct target_timer_callback *cb, struct timeval *now)
1874 timeval_add_time(&cb->when, 0, cb->time_ms * 1000L);
1878 static int target_call_timer_callback(struct target_timer_callback *cb,
1879 struct timeval *now)
1881 cb->callback(cb->priv);
1883 if (cb->type == TARGET_TIMER_TYPE_PERIODIC)
1884 return target_timer_callback_periodic_restart(cb, now);
1886 return target_unregister_timer_callback(cb->callback, cb->priv);
1889 static int target_call_timer_callbacks_check_time(int checktime)
1891 static bool callback_processing;
1893 /* Do not allow nesting */
1894 if (callback_processing)
1897 callback_processing = true;
1902 gettimeofday(&now, NULL);
1904 /* Store an address of the place containing a pointer to the
1905 * next item; initially, that's a standalone "root of the
1906 * list" variable. */
1907 struct target_timer_callback **callback = &target_timer_callbacks;
1908 while (callback && *callback) {
1909 if ((*callback)->removed) {
1910 struct target_timer_callback *p = *callback;
1911 *callback = (*callback)->next;
1916 bool call_it = (*callback)->callback &&
1917 ((!checktime && (*callback)->type == TARGET_TIMER_TYPE_PERIODIC) ||
1918 timeval_compare(&now, &(*callback)->when) >= 0);
1921 target_call_timer_callback(*callback, &now);
1923 callback = &(*callback)->next;
1926 callback_processing = false;
1930 int target_call_timer_callbacks(void)
1932 return target_call_timer_callbacks_check_time(1);
1935 /* invoke periodic callbacks immediately */
1936 int target_call_timer_callbacks_now(void)
1938 return target_call_timer_callbacks_check_time(0);
1941 /* Prints the working area layout for debug purposes */
1942 static void print_wa_layout(struct target *target)
1944 struct working_area *c = target->working_areas;
1947 LOG_DEBUG("%c%c " TARGET_ADDR_FMT "-" TARGET_ADDR_FMT " (%" PRIu32 " bytes)",
1948 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1949 c->address, c->address + c->size - 1, c->size);
1954 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1955 static void target_split_working_area(struct working_area *area, uint32_t size)
1957 assert(area->free); /* Shouldn't split an allocated area */
1958 assert(size <= area->size); /* Caller should guarantee this */
1960 /* Split only if not already the right size */
1961 if (size < area->size) {
1962 struct working_area *new_wa = malloc(sizeof(*new_wa));
1967 new_wa->next = area->next;
1968 new_wa->size = area->size - size;
1969 new_wa->address = area->address + size;
1970 new_wa->backup = NULL;
1971 new_wa->user = NULL;
1972 new_wa->free = true;
1974 area->next = new_wa;
1977 /* If backup memory was allocated to this area, it has the wrong size
1978 * now so free it and it will be reallocated if/when needed */
1980 area->backup = NULL;
1984 /* Merge all adjacent free areas into one */
1985 static void target_merge_working_areas(struct target *target)
1987 struct working_area *c = target->working_areas;
1989 while (c && c->next) {
1990 assert(c->next->address == c->address + c->size); /* This is an invariant */
1992 /* Find two adjacent free areas */
1993 if (c->free && c->next->free) {
1994 /* Merge the last into the first */
1995 c->size += c->next->size;
1997 /* Remove the last */
1998 struct working_area *to_be_freed = c->next;
1999 c->next = c->next->next;
2000 free(to_be_freed->backup);
2003 /* If backup memory was allocated to the remaining area, it's has
2004 * the wrong size now */
2013 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
2015 /* Reevaluate working area address based on MMU state*/
2016 if (target->working_areas == NULL) {
2020 retval = target->type->mmu(target, &enabled);
2021 if (retval != ERROR_OK)
2025 if (target->working_area_phys_spec) {
2026 LOG_DEBUG("MMU disabled, using physical "
2027 "address for working memory " TARGET_ADDR_FMT,
2028 target->working_area_phys);
2029 target->working_area = target->working_area_phys;
2031 LOG_ERROR("No working memory available. "
2032 "Specify -work-area-phys to target.");
2033 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2036 if (target->working_area_virt_spec) {
2037 LOG_DEBUG("MMU enabled, using virtual "
2038 "address for working memory " TARGET_ADDR_FMT,
2039 target->working_area_virt);
2040 target->working_area = target->working_area_virt;
2042 LOG_ERROR("No working memory available. "
2043 "Specify -work-area-virt to target.");
2044 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2048 /* Set up initial working area on first call */
2049 struct working_area *new_wa = malloc(sizeof(*new_wa));
2051 new_wa->next = NULL;
2052 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
2053 new_wa->address = target->working_area;
2054 new_wa->backup = NULL;
2055 new_wa->user = NULL;
2056 new_wa->free = true;
2059 target->working_areas = new_wa;
2062 /* only allocate multiples of 4 byte */
2064 size = (size + 3) & (~3UL);
2066 struct working_area *c = target->working_areas;
2068 /* Find the first large enough working area */
2070 if (c->free && c->size >= size)
2076 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2078 /* Split the working area into the requested size */
2079 target_split_working_area(c, size);
2081 LOG_DEBUG("allocated new working area of %" PRIu32 " bytes at address " TARGET_ADDR_FMT,
2084 if (target->backup_working_area) {
2085 if (c->backup == NULL) {
2086 c->backup = malloc(c->size);
2087 if (c->backup == NULL)
2091 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
2092 if (retval != ERROR_OK)
2096 /* mark as used, and return the new (reused) area */
2103 print_wa_layout(target);
2108 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
2112 retval = target_alloc_working_area_try(target, size, area);
2113 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
2114 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
2119 static int target_restore_working_area(struct target *target, struct working_area *area)
2121 int retval = ERROR_OK;
2123 if (target->backup_working_area && area->backup != NULL) {
2124 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
2125 if (retval != ERROR_OK)
2126 LOG_ERROR("failed to restore %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2127 area->size, area->address);
2133 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
2134 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
2136 int retval = ERROR_OK;
2142 retval = target_restore_working_area(target, area);
2143 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
2144 if (retval != ERROR_OK)
2150 LOG_DEBUG("freed %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2151 area->size, area->address);
2153 /* mark user pointer invalid */
2154 /* TODO: Is this really safe? It points to some previous caller's memory.
2155 * How could we know that the area pointer is still in that place and not
2156 * some other vital data? What's the purpose of this, anyway? */
2160 target_merge_working_areas(target);
2162 print_wa_layout(target);
2167 int target_free_working_area(struct target *target, struct working_area *area)
2169 return target_free_working_area_restore(target, area, 1);
2172 /* free resources and restore memory, if restoring memory fails,
2173 * free up resources anyway
2175 static void target_free_all_working_areas_restore(struct target *target, int restore)
2177 struct working_area *c = target->working_areas;
2179 LOG_DEBUG("freeing all working areas");
2181 /* Loop through all areas, restoring the allocated ones and marking them as free */
2185 target_restore_working_area(target, c);
2187 *c->user = NULL; /* Same as above */
2193 /* Run a merge pass to combine all areas into one */
2194 target_merge_working_areas(target);
2196 print_wa_layout(target);
2199 void target_free_all_working_areas(struct target *target)
2201 target_free_all_working_areas_restore(target, 1);
2203 /* Now we have none or only one working area marked as free */
2204 if (target->working_areas) {
2205 /* Free the last one to allow on-the-fly moving and resizing */
2206 free(target->working_areas->backup);
2207 free(target->working_areas);
2208 target->working_areas = NULL;
2212 /* Find the largest number of bytes that can be allocated */
2213 uint32_t target_get_working_area_avail(struct target *target)
2215 struct working_area *c = target->working_areas;
2216 uint32_t max_size = 0;
2219 return target->working_area_size;
2222 if (c->free && max_size < c->size)
2231 static void target_destroy(struct target *target)
2233 if (target->type->deinit_target)
2234 target->type->deinit_target(target);
2236 free(target->semihosting);
2238 jtag_unregister_event_callback(jtag_enable_callback, target);
2240 struct target_event_action *teap = target->event_action;
2242 struct target_event_action *next = teap->next;
2243 Jim_DecrRefCount(teap->interp, teap->body);
2248 target_free_all_working_areas(target);
2250 /* release the targets SMP list */
2252 struct target_list *head = target->head;
2253 while (head != NULL) {
2254 struct target_list *pos = head->next;
2255 head->target->smp = 0;
2262 rtos_destroy(target);
2264 free(target->gdb_port_override);
2266 free(target->trace_info);
2267 free(target->fileio_info);
2268 free(target->cmd_name);
2272 void target_quit(void)
2274 struct target_event_callback *pe = target_event_callbacks;
2276 struct target_event_callback *t = pe->next;
2280 target_event_callbacks = NULL;
2282 struct target_timer_callback *pt = target_timer_callbacks;
2284 struct target_timer_callback *t = pt->next;
2288 target_timer_callbacks = NULL;
2290 for (struct target *target = all_targets; target;) {
2294 target_destroy(target);
2301 int target_arch_state(struct target *target)
2304 if (target == NULL) {
2305 LOG_WARNING("No target has been configured");
2309 if (target->state != TARGET_HALTED)
2312 retval = target->type->arch_state(target);
2316 static int target_get_gdb_fileio_info_default(struct target *target,
2317 struct gdb_fileio_info *fileio_info)
2319 /* If target does not support semi-hosting function, target
2320 has no need to provide .get_gdb_fileio_info callback.
2321 It just return ERROR_FAIL and gdb_server will return "Txx"
2322 as target halted every time. */
2326 static int target_gdb_fileio_end_default(struct target *target,
2327 int retcode, int fileio_errno, bool ctrl_c)
2332 int target_profiling_default(struct target *target, uint32_t *samples,
2333 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
2335 struct timeval timeout, now;
2337 gettimeofday(&timeout, NULL);
2338 timeval_add_time(&timeout, seconds, 0);
2340 LOG_INFO("Starting profiling. Halting and resuming the"
2341 " target as often as we can...");
2343 uint32_t sample_count = 0;
2344 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2345 struct reg *reg = register_get_by_name(target->reg_cache, "pc", true);
2347 int retval = ERROR_OK;
2349 target_poll(target);
2350 if (target->state == TARGET_HALTED) {
2351 uint32_t t = buf_get_u32(reg->value, 0, 32);
2352 samples[sample_count++] = t;
2353 /* current pc, addr = 0, do not handle breakpoints, not debugging */
2354 retval = target_resume(target, 1, 0, 0, 0);
2355 target_poll(target);
2356 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2357 } else if (target->state == TARGET_RUNNING) {
2358 /* We want to quickly sample the PC. */
2359 retval = target_halt(target);
2361 LOG_INFO("Target not halted or running");
2366 if (retval != ERROR_OK)
2369 gettimeofday(&now, NULL);
2370 if ((sample_count >= max_num_samples) || timeval_compare(&now, &timeout) >= 0) {
2371 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2376 *num_samples = sample_count;
2380 /* Single aligned words are guaranteed to use 16 or 32 bit access
2381 * mode respectively, otherwise data is handled as quickly as
2384 int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
2386 LOG_DEBUG("writing buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2389 if (!target_was_examined(target)) {
2390 LOG_ERROR("Target not examined yet");
2397 if ((address + size - 1) < address) {
2398 /* GDB can request this when e.g. PC is 0xfffffffc */
2399 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2405 return target->type->write_buffer(target, address, size, buffer);
2408 static int target_write_buffer_default(struct target *target,
2409 target_addr_t address, uint32_t count, const uint8_t *buffer)
2412 unsigned int data_bytes = target_data_bits(target) / 8;
2414 /* Align up to maximum bytes. The loop condition makes sure the next pass
2415 * will have something to do with the size we leave to it. */
2417 size < data_bytes && count >= size * 2 + (address & size);
2419 if (address & size) {
2420 int retval = target_write_memory(target, address, size, 1, buffer);
2421 if (retval != ERROR_OK)
2429 /* Write the data with as large access size as possible. */
2430 for (; size > 0; size /= 2) {
2431 uint32_t aligned = count - count % size;
2433 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2434 if (retval != ERROR_OK)
2445 /* Single aligned words are guaranteed to use 16 or 32 bit access
2446 * mode respectively, otherwise data is handled as quickly as
2449 int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
2451 LOG_DEBUG("reading buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2454 if (!target_was_examined(target)) {
2455 LOG_ERROR("Target not examined yet");
2462 if ((address + size - 1) < address) {
2463 /* GDB can request this when e.g. PC is 0xfffffffc */
2464 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2470 return target->type->read_buffer(target, address, size, buffer);
2473 static int target_read_buffer_default(struct target *target, target_addr_t address, uint32_t count, uint8_t *buffer)
2476 unsigned int data_bytes = target_data_bits(target) / 8;
2478 /* Align up to maximum bytes. The loop condition makes sure the next pass
2479 * will have something to do with the size we leave to it. */
2481 size < data_bytes && count >= size * 2 + (address & size);
2483 if (address & size) {
2484 int retval = target_read_memory(target, address, size, 1, buffer);
2485 if (retval != ERROR_OK)
2493 /* Read the data with as large access size as possible. */
2494 for (; size > 0; size /= 2) {
2495 uint32_t aligned = count - count % size;
2497 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2498 if (retval != ERROR_OK)
2509 int target_checksum_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t *crc)
2514 uint32_t checksum = 0;
2515 if (!target_was_examined(target)) {
2516 LOG_ERROR("Target not examined yet");
2520 retval = target->type->checksum_memory(target, address, size, &checksum);
2521 if (retval != ERROR_OK) {
2522 buffer = malloc(size);
2523 if (buffer == NULL) {
2524 LOG_ERROR("error allocating buffer for section (%" PRIu32 " bytes)", size);
2525 return ERROR_COMMAND_SYNTAX_ERROR;
2527 retval = target_read_buffer(target, address, size, buffer);
2528 if (retval != ERROR_OK) {
2533 /* convert to target endianness */
2534 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2535 uint32_t target_data;
2536 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2537 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2540 retval = image_calculate_checksum(buffer, size, &checksum);
2549 int target_blank_check_memory(struct target *target,
2550 struct target_memory_check_block *blocks, int num_blocks,
2551 uint8_t erased_value)
2553 if (!target_was_examined(target)) {
2554 LOG_ERROR("Target not examined yet");
2558 if (target->type->blank_check_memory == NULL)
2559 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2561 return target->type->blank_check_memory(target, blocks, num_blocks, erased_value);
2564 int target_read_u64(struct target *target, target_addr_t address, uint64_t *value)
2566 uint8_t value_buf[8];
2567 if (!target_was_examined(target)) {
2568 LOG_ERROR("Target not examined yet");
2572 int retval = target_read_memory(target, address, 8, 1, value_buf);
2574 if (retval == ERROR_OK) {
2575 *value = target_buffer_get_u64(target, value_buf);
2576 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2581 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2588 int target_read_u32(struct target *target, target_addr_t address, uint32_t *value)
2590 uint8_t value_buf[4];
2591 if (!target_was_examined(target)) {
2592 LOG_ERROR("Target not examined yet");
2596 int retval = target_read_memory(target, address, 4, 1, value_buf);
2598 if (retval == ERROR_OK) {
2599 *value = target_buffer_get_u32(target, value_buf);
2600 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2605 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2612 int target_read_u16(struct target *target, target_addr_t address, uint16_t *value)
2614 uint8_t value_buf[2];
2615 if (!target_was_examined(target)) {
2616 LOG_ERROR("Target not examined yet");
2620 int retval = target_read_memory(target, address, 2, 1, value_buf);
2622 if (retval == ERROR_OK) {
2623 *value = target_buffer_get_u16(target, value_buf);
2624 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%4.4" PRIx16,
2629 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2636 int target_read_u8(struct target *target, target_addr_t address, uint8_t *value)
2638 if (!target_was_examined(target)) {
2639 LOG_ERROR("Target not examined yet");
2643 int retval = target_read_memory(target, address, 1, 1, value);
2645 if (retval == ERROR_OK) {
2646 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2651 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2658 int target_write_u64(struct target *target, target_addr_t address, uint64_t value)
2661 uint8_t value_buf[8];
2662 if (!target_was_examined(target)) {
2663 LOG_ERROR("Target not examined yet");
2667 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2671 target_buffer_set_u64(target, value_buf, value);
2672 retval = target_write_memory(target, address, 8, 1, value_buf);
2673 if (retval != ERROR_OK)
2674 LOG_DEBUG("failed: %i", retval);
2679 int target_write_u32(struct target *target, target_addr_t address, uint32_t value)
2682 uint8_t value_buf[4];
2683 if (!target_was_examined(target)) {
2684 LOG_ERROR("Target not examined yet");
2688 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2692 target_buffer_set_u32(target, value_buf, value);
2693 retval = target_write_memory(target, address, 4, 1, value_buf);
2694 if (retval != ERROR_OK)
2695 LOG_DEBUG("failed: %i", retval);
2700 int target_write_u16(struct target *target, target_addr_t address, uint16_t value)
2703 uint8_t value_buf[2];
2704 if (!target_was_examined(target)) {
2705 LOG_ERROR("Target not examined yet");
2709 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2713 target_buffer_set_u16(target, value_buf, value);
2714 retval = target_write_memory(target, address, 2, 1, value_buf);
2715 if (retval != ERROR_OK)
2716 LOG_DEBUG("failed: %i", retval);
2721 int target_write_u8(struct target *target, target_addr_t address, uint8_t value)
2724 if (!target_was_examined(target)) {
2725 LOG_ERROR("Target not examined yet");
2729 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2732 retval = target_write_memory(target, address, 1, 1, &value);
2733 if (retval != ERROR_OK)
2734 LOG_DEBUG("failed: %i", retval);
2739 int target_write_phys_u64(struct target *target, target_addr_t address, uint64_t value)
2742 uint8_t value_buf[8];
2743 if (!target_was_examined(target)) {
2744 LOG_ERROR("Target not examined yet");
2748 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2752 target_buffer_set_u64(target, value_buf, value);
2753 retval = target_write_phys_memory(target, address, 8, 1, value_buf);
2754 if (retval != ERROR_OK)
2755 LOG_DEBUG("failed: %i", retval);
2760 int target_write_phys_u32(struct target *target, target_addr_t address, uint32_t value)
2763 uint8_t value_buf[4];
2764 if (!target_was_examined(target)) {
2765 LOG_ERROR("Target not examined yet");
2769 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2773 target_buffer_set_u32(target, value_buf, value);
2774 retval = target_write_phys_memory(target, address, 4, 1, value_buf);
2775 if (retval != ERROR_OK)
2776 LOG_DEBUG("failed: %i", retval);
2781 int target_write_phys_u16(struct target *target, target_addr_t address, uint16_t value)
2784 uint8_t value_buf[2];
2785 if (!target_was_examined(target)) {
2786 LOG_ERROR("Target not examined yet");
2790 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2794 target_buffer_set_u16(target, value_buf, value);
2795 retval = target_write_phys_memory(target, address, 2, 1, value_buf);
2796 if (retval != ERROR_OK)
2797 LOG_DEBUG("failed: %i", retval);
2802 int target_write_phys_u8(struct target *target, target_addr_t address, uint8_t value)
2805 if (!target_was_examined(target)) {
2806 LOG_ERROR("Target not examined yet");
2810 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2813 retval = target_write_phys_memory(target, address, 1, 1, &value);
2814 if (retval != ERROR_OK)
2815 LOG_DEBUG("failed: %i", retval);
2820 static int find_target(struct command_invocation *cmd, const char *name)
2822 struct target *target = get_target(name);
2823 if (target == NULL) {
2824 command_print(cmd, "Target: %s is unknown, try one of:\n", name);
2827 if (!target->tap->enabled) {
2828 command_print(cmd, "Target: TAP %s is disabled, "
2829 "can't be the current target\n",
2830 target->tap->dotted_name);
2834 cmd->ctx->current_target = target;
2835 if (cmd->ctx->current_target_override)
2836 cmd->ctx->current_target_override = target;
2842 COMMAND_HANDLER(handle_targets_command)
2844 int retval = ERROR_OK;
2845 if (CMD_ARGC == 1) {
2846 retval = find_target(CMD, CMD_ARGV[0]);
2847 if (retval == ERROR_OK) {
2853 struct target *target = all_targets;
2854 command_print(CMD, " TargetName Type Endian TapName State ");
2855 command_print(CMD, "-- ------------------ ---------- ------ ------------------ ------------");
2860 if (target->tap->enabled)
2861 state = target_state_name(target);
2863 state = "tap-disabled";
2865 if (CMD_CTX->current_target == target)
2868 /* keep columns lined up to match the headers above */
2870 "%2d%c %-18s %-10s %-6s %-18s %s",
2871 target->target_number,
2873 target_name(target),
2874 target_type_name(target),
2875 jim_nvp_value2name_simple(nvp_target_endian,
2876 target->endianness)->name,
2877 target->tap->dotted_name,
2879 target = target->next;
2885 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2887 static int powerDropout;
2888 static int srstAsserted;
2890 static int runPowerRestore;
2891 static int runPowerDropout;
2892 static int runSrstAsserted;
2893 static int runSrstDeasserted;
2895 static int sense_handler(void)
2897 static int prevSrstAsserted;
2898 static int prevPowerdropout;
2900 int retval = jtag_power_dropout(&powerDropout);
2901 if (retval != ERROR_OK)
2905 powerRestored = prevPowerdropout && !powerDropout;
2907 runPowerRestore = 1;
2909 int64_t current = timeval_ms();
2910 static int64_t lastPower;
2911 bool waitMore = lastPower + 2000 > current;
2912 if (powerDropout && !waitMore) {
2913 runPowerDropout = 1;
2914 lastPower = current;
2917 retval = jtag_srst_asserted(&srstAsserted);
2918 if (retval != ERROR_OK)
2922 srstDeasserted = prevSrstAsserted && !srstAsserted;
2924 static int64_t lastSrst;
2925 waitMore = lastSrst + 2000 > current;
2926 if (srstDeasserted && !waitMore) {
2927 runSrstDeasserted = 1;
2931 if (!prevSrstAsserted && srstAsserted)
2932 runSrstAsserted = 1;
2934 prevSrstAsserted = srstAsserted;
2935 prevPowerdropout = powerDropout;
2937 if (srstDeasserted || powerRestored) {
2938 /* Other than logging the event we can't do anything here.
2939 * Issuing a reset is a particularly bad idea as we might
2940 * be inside a reset already.
2947 /* process target state changes */
2948 static int handle_target(void *priv)
2950 Jim_Interp *interp = (Jim_Interp *)priv;
2951 int retval = ERROR_OK;
2953 if (!is_jtag_poll_safe()) {
2954 /* polling is disabled currently */
2958 /* we do not want to recurse here... */
2959 static int recursive;
2963 /* danger! running these procedures can trigger srst assertions and power dropouts.
2964 * We need to avoid an infinite loop/recursion here and we do that by
2965 * clearing the flags after running these events.
2967 int did_something = 0;
2968 if (runSrstAsserted) {
2969 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2970 Jim_Eval(interp, "srst_asserted");
2973 if (runSrstDeasserted) {
2974 Jim_Eval(interp, "srst_deasserted");
2977 if (runPowerDropout) {
2978 LOG_INFO("Power dropout detected, running power_dropout proc.");
2979 Jim_Eval(interp, "power_dropout");
2982 if (runPowerRestore) {
2983 Jim_Eval(interp, "power_restore");
2987 if (did_something) {
2988 /* clear detect flags */
2992 /* clear action flags */
2994 runSrstAsserted = 0;
2995 runSrstDeasserted = 0;
2996 runPowerRestore = 0;
2997 runPowerDropout = 0;
3002 /* Poll targets for state changes unless that's globally disabled.
3003 * Skip targets that are currently disabled.
3005 for (struct target *target = all_targets;
3006 is_jtag_poll_safe() && target;
3007 target = target->next) {
3009 if (!target_was_examined(target))
3012 if (!target->tap->enabled)
3015 if (target->backoff.times > target->backoff.count) {
3016 /* do not poll this time as we failed previously */
3017 target->backoff.count++;
3020 target->backoff.count = 0;
3022 /* only poll target if we've got power and srst isn't asserted */
3023 if (!powerDropout && !srstAsserted) {
3024 /* polling may fail silently until the target has been examined */
3025 retval = target_poll(target);
3026 if (retval != ERROR_OK) {
3027 /* 100ms polling interval. Increase interval between polling up to 5000ms */
3028 if (target->backoff.times * polling_interval < 5000) {
3029 target->backoff.times *= 2;
3030 target->backoff.times++;
3033 /* Tell GDB to halt the debugger. This allows the user to
3034 * run monitor commands to handle the situation.
3036 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3038 if (target->backoff.times > 0) {
3039 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
3040 target_reset_examined(target);
3041 retval = target_examine_one(target);
3042 /* Target examination could have failed due to unstable connection,
3043 * but we set the examined flag anyway to repoll it later */
3044 if (retval != ERROR_OK) {
3045 target->examined = true;
3046 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
3047 target->backoff.times * polling_interval);
3052 /* Since we succeeded, we reset backoff count */
3053 target->backoff.times = 0;
3060 COMMAND_HANDLER(handle_reg_command)
3064 struct target *target = get_current_target(CMD_CTX);
3065 struct reg *reg = NULL;
3067 /* list all available registers for the current target */
3068 if (CMD_ARGC == 0) {
3069 struct reg_cache *cache = target->reg_cache;
3071 unsigned int count = 0;
3075 command_print(CMD, "===== %s", cache->name);
3077 for (i = 0, reg = cache->reg_list;
3078 i < cache->num_regs;
3079 i++, reg++, count++) {
3080 if (reg->exist == false || reg->hidden)
3082 /* only print cached values if they are valid */
3084 char *value = buf_to_hex_str(reg->value,
3087 "(%i) %s (/%" PRIu32 "): 0x%s%s",
3095 command_print(CMD, "(%i) %s (/%" PRIu32 ")",
3100 cache = cache->next;
3106 /* access a single register by its ordinal number */
3107 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
3109 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
3111 struct reg_cache *cache = target->reg_cache;
3112 unsigned int count = 0;
3115 for (i = 0; i < cache->num_regs; i++) {
3116 if (count++ == num) {
3117 reg = &cache->reg_list[i];
3123 cache = cache->next;
3127 command_print(CMD, "%i is out of bounds, the current target "
3128 "has only %i registers (0 - %i)", num, count, count - 1);
3132 /* access a single register by its name */
3133 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], true);
3139 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
3144 /* display a register */
3145 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
3146 && (CMD_ARGV[1][0] <= '9')))) {
3147 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
3150 if (reg->valid == 0) {
3151 int retval = reg->type->get(reg);
3152 if (retval != ERROR_OK) {
3153 LOG_ERROR("Could not read register '%s'", reg->name);
3157 char *value = buf_to_hex_str(reg->value, reg->size);
3158 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3163 /* set register value */
3164 if (CMD_ARGC == 2) {
3165 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
3168 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
3170 int retval = reg->type->set(reg, buf);
3171 if (retval != ERROR_OK) {
3172 LOG_ERROR("Could not write to register '%s'", reg->name);
3174 char *value = buf_to_hex_str(reg->value, reg->size);
3175 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3184 return ERROR_COMMAND_SYNTAX_ERROR;
3187 command_print(CMD, "register %s not found in current target", CMD_ARGV[0]);
3191 COMMAND_HANDLER(handle_poll_command)
3193 int retval = ERROR_OK;
3194 struct target *target = get_current_target(CMD_CTX);
3196 if (CMD_ARGC == 0) {
3197 command_print(CMD, "background polling: %s",
3198 jtag_poll_get_enabled() ? "on" : "off");
3199 command_print(CMD, "TAP: %s (%s)",
3200 target->tap->dotted_name,
3201 target->tap->enabled ? "enabled" : "disabled");
3202 if (!target->tap->enabled)
3204 retval = target_poll(target);
3205 if (retval != ERROR_OK)
3207 retval = target_arch_state(target);
3208 if (retval != ERROR_OK)
3210 } else if (CMD_ARGC == 1) {
3212 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
3213 jtag_poll_set_enabled(enable);
3215 return ERROR_COMMAND_SYNTAX_ERROR;
3220 COMMAND_HANDLER(handle_wait_halt_command)
3223 return ERROR_COMMAND_SYNTAX_ERROR;
3225 unsigned ms = DEFAULT_HALT_TIMEOUT;
3226 if (1 == CMD_ARGC) {
3227 int retval = parse_uint(CMD_ARGV[0], &ms);
3228 if (ERROR_OK != retval)
3229 return ERROR_COMMAND_SYNTAX_ERROR;
3232 struct target *target = get_current_target(CMD_CTX);
3233 return target_wait_state(target, TARGET_HALTED, ms);
3236 /* wait for target state to change. The trick here is to have a low
3237 * latency for short waits and not to suck up all the CPU time
3240 * After 500ms, keep_alive() is invoked
3242 int target_wait_state(struct target *target, enum target_state state, int ms)
3245 int64_t then = 0, cur;
3249 retval = target_poll(target);
3250 if (retval != ERROR_OK)
3252 if (target->state == state)
3257 then = timeval_ms();
3258 LOG_DEBUG("waiting for target %s...",
3259 jim_nvp_value2name_simple(nvp_target_state, state)->name);
3265 if ((cur-then) > ms) {
3266 LOG_ERROR("timed out while waiting for target %s",
3267 jim_nvp_value2name_simple(nvp_target_state, state)->name);
3275 COMMAND_HANDLER(handle_halt_command)
3279 struct target *target = get_current_target(CMD_CTX);
3281 target->verbose_halt_msg = true;
3283 int retval = target_halt(target);
3284 if (ERROR_OK != retval)
3287 if (CMD_ARGC == 1) {
3288 unsigned wait_local;
3289 retval = parse_uint(CMD_ARGV[0], &wait_local);
3290 if (ERROR_OK != retval)
3291 return ERROR_COMMAND_SYNTAX_ERROR;
3296 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
3299 COMMAND_HANDLER(handle_soft_reset_halt_command)
3301 struct target *target = get_current_target(CMD_CTX);
3303 LOG_USER("requesting target halt and executing a soft reset");
3305 target_soft_reset_halt(target);
3310 COMMAND_HANDLER(handle_reset_command)
3313 return ERROR_COMMAND_SYNTAX_ERROR;
3315 enum target_reset_mode reset_mode = RESET_RUN;
3316 if (CMD_ARGC == 1) {
3317 const struct jim_nvp *n;
3318 n = jim_nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
3319 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
3320 return ERROR_COMMAND_SYNTAX_ERROR;
3321 reset_mode = n->value;
3324 /* reset *all* targets */
3325 return target_process_reset(CMD, reset_mode);
3329 COMMAND_HANDLER(handle_resume_command)
3333 return ERROR_COMMAND_SYNTAX_ERROR;
3335 struct target *target = get_current_target(CMD_CTX);
3337 /* with no CMD_ARGV, resume from current pc, addr = 0,
3338 * with one arguments, addr = CMD_ARGV[0],
3339 * handle breakpoints, not debugging */
3340 target_addr_t addr = 0;
3341 if (CMD_ARGC == 1) {
3342 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3346 return target_resume(target, current, addr, 1, 0);
3349 COMMAND_HANDLER(handle_step_command)
3352 return ERROR_COMMAND_SYNTAX_ERROR;
3356 /* with no CMD_ARGV, step from current pc, addr = 0,
3357 * with one argument addr = CMD_ARGV[0],
3358 * handle breakpoints, debugging */
3359 target_addr_t addr = 0;
3361 if (CMD_ARGC == 1) {
3362 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3366 struct target *target = get_current_target(CMD_CTX);
3368 return target_step(target, current_pc, addr, 1);
3371 void target_handle_md_output(struct command_invocation *cmd,
3372 struct target *target, target_addr_t address, unsigned size,
3373 unsigned count, const uint8_t *buffer)
3375 const unsigned line_bytecnt = 32;
3376 unsigned line_modulo = line_bytecnt / size;
3378 char output[line_bytecnt * 4 + 1];
3379 unsigned output_len = 0;
3381 const char *value_fmt;
3384 value_fmt = "%16.16"PRIx64" ";
3387 value_fmt = "%8.8"PRIx64" ";
3390 value_fmt = "%4.4"PRIx64" ";
3393 value_fmt = "%2.2"PRIx64" ";
3396 /* "can't happen", caller checked */
3397 LOG_ERROR("invalid memory read size: %u", size);
3401 for (unsigned i = 0; i < count; i++) {
3402 if (i % line_modulo == 0) {
3403 output_len += snprintf(output + output_len,
3404 sizeof(output) - output_len,
3405 TARGET_ADDR_FMT ": ",
3406 (address + (i * size)));
3410 const uint8_t *value_ptr = buffer + i * size;
3413 value = target_buffer_get_u64(target, value_ptr);
3416 value = target_buffer_get_u32(target, value_ptr);
3419 value = target_buffer_get_u16(target, value_ptr);
3424 output_len += snprintf(output + output_len,
3425 sizeof(output) - output_len,
3428 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
3429 command_print(cmd, "%s", output);
3435 COMMAND_HANDLER(handle_md_command)
3438 return ERROR_COMMAND_SYNTAX_ERROR;
3441 switch (CMD_NAME[2]) {
3455 return ERROR_COMMAND_SYNTAX_ERROR;
3458 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3459 int (*fn)(struct target *target,
3460 target_addr_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
3464 fn = target_read_phys_memory;
3466 fn = target_read_memory;
3467 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
3468 return ERROR_COMMAND_SYNTAX_ERROR;
3470 target_addr_t address;
3471 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3475 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3477 uint8_t *buffer = calloc(count, size);
3478 if (buffer == NULL) {
3479 LOG_ERROR("Failed to allocate md read buffer");
3483 struct target *target = get_current_target(CMD_CTX);
3484 int retval = fn(target, address, size, count, buffer);
3485 if (ERROR_OK == retval)
3486 target_handle_md_output(CMD, target, address, size, count, buffer);
3493 typedef int (*target_write_fn)(struct target *target,
3494 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3496 static int target_fill_mem(struct target *target,
3497 target_addr_t address,
3505 /* We have to write in reasonably large chunks to be able
3506 * to fill large memory areas with any sane speed */
3507 const unsigned chunk_size = 16384;
3508 uint8_t *target_buf = malloc(chunk_size * data_size);
3509 if (target_buf == NULL) {
3510 LOG_ERROR("Out of memory");
3514 for (unsigned i = 0; i < chunk_size; i++) {
3515 switch (data_size) {
3517 target_buffer_set_u64(target, target_buf + i * data_size, b);
3520 target_buffer_set_u32(target, target_buf + i * data_size, b);
3523 target_buffer_set_u16(target, target_buf + i * data_size, b);
3526 target_buffer_set_u8(target, target_buf + i * data_size, b);
3533 int retval = ERROR_OK;
3535 for (unsigned x = 0; x < c; x += chunk_size) {
3538 if (current > chunk_size)
3539 current = chunk_size;
3540 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3541 if (retval != ERROR_OK)
3543 /* avoid GDB timeouts */
3552 COMMAND_HANDLER(handle_mw_command)
3555 return ERROR_COMMAND_SYNTAX_ERROR;
3556 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3561 fn = target_write_phys_memory;
3563 fn = target_write_memory;
3564 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3565 return ERROR_COMMAND_SYNTAX_ERROR;
3567 target_addr_t address;
3568 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3571 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[1], value);
3575 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3577 struct target *target = get_current_target(CMD_CTX);
3579 switch (CMD_NAME[2]) {
3593 return ERROR_COMMAND_SYNTAX_ERROR;
3596 return target_fill_mem(target, address, fn, wordsize, value, count);
3599 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
3600 target_addr_t *min_address, target_addr_t *max_address)
3602 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3603 return ERROR_COMMAND_SYNTAX_ERROR;
3605 /* a base address isn't always necessary,
3606 * default to 0x0 (i.e. don't relocate) */
3607 if (CMD_ARGC >= 2) {
3609 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3610 image->base_address = addr;
3611 image->base_address_set = true;
3613 image->base_address_set = false;
3615 image->start_address_set = false;
3618 COMMAND_PARSE_ADDRESS(CMD_ARGV[3], *min_address);
3619 if (CMD_ARGC == 5) {
3620 COMMAND_PARSE_ADDRESS(CMD_ARGV[4], *max_address);
3621 /* use size (given) to find max (required) */
3622 *max_address += *min_address;
3625 if (*min_address > *max_address)
3626 return ERROR_COMMAND_SYNTAX_ERROR;
3631 COMMAND_HANDLER(handle_load_image_command)
3635 uint32_t image_size;
3636 target_addr_t min_address = 0;
3637 target_addr_t max_address = -1;
3640 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
3641 &image, &min_address, &max_address);
3642 if (ERROR_OK != retval)
3645 struct target *target = get_current_target(CMD_CTX);
3647 struct duration bench;
3648 duration_start(&bench);
3650 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3655 for (unsigned int i = 0; i < image.num_sections; i++) {
3656 buffer = malloc(image.sections[i].size);
3657 if (buffer == NULL) {
3659 "error allocating buffer for section (%d bytes)",
3660 (int)(image.sections[i].size));
3661 retval = ERROR_FAIL;
3665 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3666 if (retval != ERROR_OK) {
3671 uint32_t offset = 0;
3672 uint32_t length = buf_cnt;
3674 /* DANGER!!! beware of unsigned comparison here!!! */
3676 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3677 (image.sections[i].base_address < max_address)) {
3679 if (image.sections[i].base_address < min_address) {
3680 /* clip addresses below */
3681 offset += min_address-image.sections[i].base_address;
3685 if (image.sections[i].base_address + buf_cnt > max_address)
3686 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3688 retval = target_write_buffer(target,
3689 image.sections[i].base_address + offset, length, buffer + offset);
3690 if (retval != ERROR_OK) {
3694 image_size += length;
3695 command_print(CMD, "%u bytes written at address " TARGET_ADDR_FMT "",
3696 (unsigned int)length,
3697 image.sections[i].base_address + offset);
3703 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3704 command_print(CMD, "downloaded %" PRIu32 " bytes "
3705 "in %fs (%0.3f KiB/s)", image_size,
3706 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3709 image_close(&image);
3715 COMMAND_HANDLER(handle_dump_image_command)
3717 struct fileio *fileio;
3719 int retval, retvaltemp;
3720 target_addr_t address, size;
3721 struct duration bench;
3722 struct target *target = get_current_target(CMD_CTX);
3725 return ERROR_COMMAND_SYNTAX_ERROR;
3727 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], address);
3728 COMMAND_PARSE_ADDRESS(CMD_ARGV[2], size);
3730 uint32_t buf_size = (size > 4096) ? 4096 : size;
3731 buffer = malloc(buf_size);
3735 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3736 if (retval != ERROR_OK) {
3741 duration_start(&bench);
3744 size_t size_written;
3745 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3746 retval = target_read_buffer(target, address, this_run_size, buffer);
3747 if (retval != ERROR_OK)
3750 retval = fileio_write(fileio, this_run_size, buffer, &size_written);
3751 if (retval != ERROR_OK)
3754 size -= this_run_size;
3755 address += this_run_size;
3760 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3762 retval = fileio_size(fileio, &filesize);
3763 if (retval != ERROR_OK)
3766 "dumped %zu bytes in %fs (%0.3f KiB/s)", filesize,
3767 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3770 retvaltemp = fileio_close(fileio);
3771 if (retvaltemp != ERROR_OK)
3780 IMAGE_CHECKSUM_ONLY = 2
3783 static COMMAND_HELPER(handle_verify_image_command_internal, enum verify_mode verify)
3787 uint32_t image_size;
3789 uint32_t checksum = 0;
3790 uint32_t mem_checksum = 0;
3794 struct target *target = get_current_target(CMD_CTX);
3797 return ERROR_COMMAND_SYNTAX_ERROR;
3800 LOG_ERROR("no target selected");
3804 struct duration bench;
3805 duration_start(&bench);
3807 if (CMD_ARGC >= 2) {
3809 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3810 image.base_address = addr;
3811 image.base_address_set = true;
3813 image.base_address_set = false;
3814 image.base_address = 0x0;
3817 image.start_address_set = false;
3819 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3820 if (retval != ERROR_OK)
3826 for (unsigned int i = 0; i < image.num_sections; i++) {
3827 buffer = malloc(image.sections[i].size);
3828 if (buffer == NULL) {
3830 "error allocating buffer for section (%" PRIu32 " bytes)",
3831 image.sections[i].size);
3834 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3835 if (retval != ERROR_OK) {
3840 if (verify >= IMAGE_VERIFY) {
3841 /* calculate checksum of image */
3842 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3843 if (retval != ERROR_OK) {
3848 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3849 if (retval != ERROR_OK) {
3853 if ((checksum != mem_checksum) && (verify == IMAGE_CHECKSUM_ONLY)) {
3854 LOG_ERROR("checksum mismatch");
3856 retval = ERROR_FAIL;
3859 if (checksum != mem_checksum) {
3860 /* failed crc checksum, fall back to a binary compare */
3864 LOG_ERROR("checksum mismatch - attempting binary compare");
3866 data = malloc(buf_cnt);
3868 retval = target_read_buffer(target, image.sections[i].base_address, buf_cnt, data);
3869 if (retval == ERROR_OK) {
3871 for (t = 0; t < buf_cnt; t++) {
3872 if (data[t] != buffer[t]) {
3874 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3876 (unsigned)(t + image.sections[i].base_address),
3879 if (diffs++ >= 127) {
3880 command_print(CMD, "More than 128 errors, the rest are not printed.");
3892 command_print(CMD, "address " TARGET_ADDR_FMT " length 0x%08zx",
3893 image.sections[i].base_address,
3898 image_size += buf_cnt;
3901 command_print(CMD, "No more differences found.");
3904 retval = ERROR_FAIL;
3905 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3906 command_print(CMD, "verified %" PRIu32 " bytes "
3907 "in %fs (%0.3f KiB/s)", image_size,
3908 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3911 image_close(&image);
3916 COMMAND_HANDLER(handle_verify_image_checksum_command)
3918 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_CHECKSUM_ONLY);
3921 COMMAND_HANDLER(handle_verify_image_command)
3923 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_VERIFY);
3926 COMMAND_HANDLER(handle_test_image_command)
3928 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_TEST);
3931 static int handle_bp_command_list(struct command_invocation *cmd)
3933 struct target *target = get_current_target(cmd->ctx);
3934 struct breakpoint *breakpoint = target->breakpoints;
3935 while (breakpoint) {
3936 if (breakpoint->type == BKPT_SOFT) {
3937 char *buf = buf_to_hex_str(breakpoint->orig_instr,
3938 breakpoint->length);
3939 command_print(cmd, "IVA breakpoint: " TARGET_ADDR_FMT ", 0x%x, %i, 0x%s",
3940 breakpoint->address,
3942 breakpoint->set, buf);
3945 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3946 command_print(cmd, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3948 breakpoint->length, breakpoint->set);
3949 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3950 command_print(cmd, "Hybrid breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3951 breakpoint->address,
3952 breakpoint->length, breakpoint->set);
3953 command_print(cmd, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3956 command_print(cmd, "Breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3957 breakpoint->address,
3958 breakpoint->length, breakpoint->set);
3961 breakpoint = breakpoint->next;
3966 static int handle_bp_command_set(struct command_invocation *cmd,
3967 target_addr_t addr, uint32_t asid, uint32_t length, int hw)
3969 struct target *target = get_current_target(cmd->ctx);
3973 retval = breakpoint_add(target, addr, length, hw);
3974 /* error is always logged in breakpoint_add(), do not print it again */
3975 if (ERROR_OK == retval)
3976 command_print(cmd, "breakpoint set at " TARGET_ADDR_FMT "", addr);
3978 } else if (addr == 0) {
3979 if (target->type->add_context_breakpoint == NULL) {
3980 LOG_ERROR("Context breakpoint not available");
3981 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
3983 retval = context_breakpoint_add(target, asid, length, hw);
3984 /* error is always logged in context_breakpoint_add(), do not print it again */
3985 if (ERROR_OK == retval)
3986 command_print(cmd, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3989 if (target->type->add_hybrid_breakpoint == NULL) {
3990 LOG_ERROR("Hybrid breakpoint not available");
3991 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
3993 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3994 /* error is always logged in hybrid_breakpoint_add(), do not print it again */
3995 if (ERROR_OK == retval)
3996 command_print(cmd, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
4001 COMMAND_HANDLER(handle_bp_command)
4010 return handle_bp_command_list(CMD);
4014 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4015 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4016 return handle_bp_command_set(CMD, addr, asid, length, hw);
4019 if (strcmp(CMD_ARGV[2], "hw") == 0) {
4021 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4022 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4024 return handle_bp_command_set(CMD, addr, asid, length, hw);
4025 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
4027 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
4028 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4030 return handle_bp_command_set(CMD, addr, asid, length, hw);
4035 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4036 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
4037 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
4038 return handle_bp_command_set(CMD, addr, asid, length, hw);
4041 return ERROR_COMMAND_SYNTAX_ERROR;
4045 COMMAND_HANDLER(handle_rbp_command)
4048 return ERROR_COMMAND_SYNTAX_ERROR;
4050 struct target *target = get_current_target(CMD_CTX);
4052 if (!strcmp(CMD_ARGV[0], "all")) {
4053 breakpoint_remove_all(target);
4056 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4058 breakpoint_remove(target, addr);
4064 COMMAND_HANDLER(handle_wp_command)
4066 struct target *target = get_current_target(CMD_CTX);
4068 if (CMD_ARGC == 0) {
4069 struct watchpoint *watchpoint = target->watchpoints;
4071 while (watchpoint) {
4072 command_print(CMD, "address: " TARGET_ADDR_FMT
4073 ", len: 0x%8.8" PRIx32
4074 ", r/w/a: %i, value: 0x%8.8" PRIx32
4075 ", mask: 0x%8.8" PRIx32,
4076 watchpoint->address,
4078 (int)watchpoint->rw,
4081 watchpoint = watchpoint->next;
4086 enum watchpoint_rw type = WPT_ACCESS;
4087 target_addr_t addr = 0;
4088 uint32_t length = 0;
4089 uint32_t data_value = 0x0;
4090 uint32_t data_mask = 0xffffffff;
4094 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
4097 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
4100 switch (CMD_ARGV[2][0]) {
4111 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
4112 return ERROR_COMMAND_SYNTAX_ERROR;
4116 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4117 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4121 return ERROR_COMMAND_SYNTAX_ERROR;
4124 int retval = watchpoint_add(target, addr, length, type,
4125 data_value, data_mask);
4126 if (ERROR_OK != retval)
4127 LOG_ERROR("Failure setting watchpoints");
4132 COMMAND_HANDLER(handle_rwp_command)
4135 return ERROR_COMMAND_SYNTAX_ERROR;
4138 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4140 struct target *target = get_current_target(CMD_CTX);
4141 watchpoint_remove(target, addr);
4147 * Translate a virtual address to a physical address.
4149 * The low-level target implementation must have logged a detailed error
4150 * which is forwarded to telnet/GDB session.
4152 COMMAND_HANDLER(handle_virt2phys_command)
4155 return ERROR_COMMAND_SYNTAX_ERROR;
4158 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], va);
4161 struct target *target = get_current_target(CMD_CTX);
4162 int retval = target->type->virt2phys(target, va, &pa);
4163 if (retval == ERROR_OK)
4164 command_print(CMD, "Physical address " TARGET_ADDR_FMT "", pa);
4169 static void writeData(FILE *f, const void *data, size_t len)
4171 size_t written = fwrite(data, 1, len, f);
4173 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
4176 static void writeLong(FILE *f, int l, struct target *target)
4180 target_buffer_set_u32(target, val, l);
4181 writeData(f, val, 4);
4184 static void writeString(FILE *f, char *s)
4186 writeData(f, s, strlen(s));
4189 typedef unsigned char UNIT[2]; /* unit of profiling */
4191 /* Dump a gmon.out histogram file. */
4192 static void write_gmon(uint32_t *samples, uint32_t sampleNum, const char *filename, bool with_range,
4193 uint32_t start_address, uint32_t end_address, struct target *target, uint32_t duration_ms)
4196 FILE *f = fopen(filename, "w");
4199 writeString(f, "gmon");
4200 writeLong(f, 0x00000001, target); /* Version */
4201 writeLong(f, 0, target); /* padding */
4202 writeLong(f, 0, target); /* padding */
4203 writeLong(f, 0, target); /* padding */
4205 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
4206 writeData(f, &zero, 1);
4208 /* figure out bucket size */
4212 min = start_address;
4217 for (i = 0; i < sampleNum; i++) {
4218 if (min > samples[i])
4220 if (max < samples[i])
4224 /* max should be (largest sample + 1)
4225 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
4229 int addressSpace = max - min;
4230 assert(addressSpace >= 2);
4232 /* FIXME: What is the reasonable number of buckets?
4233 * The profiling result will be more accurate if there are enough buckets. */
4234 static const uint32_t maxBuckets = 128 * 1024; /* maximum buckets. */
4235 uint32_t numBuckets = addressSpace / sizeof(UNIT);
4236 if (numBuckets > maxBuckets)
4237 numBuckets = maxBuckets;
4238 int *buckets = malloc(sizeof(int) * numBuckets);
4239 if (buckets == NULL) {
4243 memset(buckets, 0, sizeof(int) * numBuckets);
4244 for (i = 0; i < sampleNum; i++) {
4245 uint32_t address = samples[i];
4247 if ((address < min) || (max <= address))
4250 long long a = address - min;
4251 long long b = numBuckets;
4252 long long c = addressSpace;
4253 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
4257 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
4258 writeLong(f, min, target); /* low_pc */
4259 writeLong(f, max, target); /* high_pc */
4260 writeLong(f, numBuckets, target); /* # of buckets */
4261 float sample_rate = sampleNum / (duration_ms / 1000.0);
4262 writeLong(f, sample_rate, target);
4263 writeString(f, "seconds");
4264 for (i = 0; i < (15-strlen("seconds")); i++)
4265 writeData(f, &zero, 1);
4266 writeString(f, "s");
4268 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
4270 char *data = malloc(2 * numBuckets);
4272 for (i = 0; i < numBuckets; i++) {
4277 data[i * 2] = val&0xff;
4278 data[i * 2 + 1] = (val >> 8) & 0xff;
4281 writeData(f, data, numBuckets * 2);
4289 /* profiling samples the CPU PC as quickly as OpenOCD is able,
4290 * which will be used as a random sampling of PC */
4291 COMMAND_HANDLER(handle_profile_command)
4293 struct target *target = get_current_target(CMD_CTX);
4295 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
4296 return ERROR_COMMAND_SYNTAX_ERROR;
4298 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
4300 uint32_t num_of_samples;
4301 int retval = ERROR_OK;
4302 bool halted_before_profiling = target->state == TARGET_HALTED;
4304 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
4306 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
4307 if (samples == NULL) {
4308 LOG_ERROR("No memory to store samples.");
4312 uint64_t timestart_ms = timeval_ms();
4314 * Some cores let us sample the PC without the
4315 * annoying halt/resume step; for example, ARMv7 PCSR.
4316 * Provide a way to use that more efficient mechanism.
4318 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
4319 &num_of_samples, offset);
4320 if (retval != ERROR_OK) {
4324 uint32_t duration_ms = timeval_ms() - timestart_ms;
4326 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
4328 retval = target_poll(target);
4329 if (retval != ERROR_OK) {
4334 if (target->state == TARGET_RUNNING && halted_before_profiling) {
4335 /* The target was halted before we started and is running now. Halt it,
4336 * for consistency. */
4337 retval = target_halt(target);
4338 if (retval != ERROR_OK) {
4342 } else if (target->state == TARGET_HALTED && !halted_before_profiling) {
4343 /* The target was running before we started and is halted now. Resume
4344 * it, for consistency. */
4345 retval = target_resume(target, 1, 0, 0, 0);
4346 if (retval != ERROR_OK) {
4352 retval = target_poll(target);
4353 if (retval != ERROR_OK) {
4358 uint32_t start_address = 0;
4359 uint32_t end_address = 0;
4360 bool with_range = false;
4361 if (CMD_ARGC == 4) {
4363 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
4364 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
4367 write_gmon(samples, num_of_samples, CMD_ARGV[1],
4368 with_range, start_address, end_address, target, duration_ms);
4369 command_print(CMD, "Wrote %s", CMD_ARGV[1]);
4375 static int new_u64_array_element(Jim_Interp *interp, const char *varname, int idx, uint64_t val)
4378 Jim_Obj *nameObjPtr, *valObjPtr;
4381 namebuf = alloc_printf("%s(%d)", varname, idx);
4385 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
4386 jim_wide wide_val = val;
4387 valObjPtr = Jim_NewWideObj(interp, wide_val);
4388 if (!nameObjPtr || !valObjPtr) {
4393 Jim_IncrRefCount(nameObjPtr);
4394 Jim_IncrRefCount(valObjPtr);
4395 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
4396 Jim_DecrRefCount(interp, nameObjPtr);
4397 Jim_DecrRefCount(interp, valObjPtr);
4399 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
4403 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4405 struct command_context *context;
4406 struct target *target;
4408 context = current_command_context(interp);
4409 assert(context != NULL);
4411 target = get_current_target(context);
4412 if (target == NULL) {
4413 LOG_ERROR("mem2array: no current target");
4417 return target_mem2array(interp, target, argc - 1, argv + 1);
4420 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
4424 /* argv[0] = name of array to receive the data
4425 * argv[1] = desired element width in bits
4426 * argv[2] = memory address
4427 * argv[3] = count of times to read
4428 * argv[4] = optional "phys"
4430 if (argc < 4 || argc > 5) {
4431 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4435 /* Arg 0: Name of the array variable */
4436 const char *varname = Jim_GetString(argv[0], NULL);
4438 /* Arg 1: Bit width of one element */
4440 e = Jim_GetLong(interp, argv[1], &l);
4443 const unsigned int width_bits = l;
4445 if (width_bits != 8 &&
4449 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4450 Jim_AppendStrings(interp, Jim_GetResult(interp),
4451 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4454 const unsigned int width = width_bits / 8;
4456 /* Arg 2: Memory address */
4458 e = Jim_GetWide(interp, argv[2], &wide_addr);
4461 target_addr_t addr = (target_addr_t)wide_addr;
4463 /* Arg 3: Number of elements to read */
4464 e = Jim_GetLong(interp, argv[3], &l);
4470 bool is_phys = false;
4473 const char *phys = Jim_GetString(argv[4], &str_len);
4474 if (!strncmp(phys, "phys", str_len))
4480 /* Argument checks */
4482 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4483 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
4486 if ((addr + (len * width)) < addr) {
4487 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4488 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
4492 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4493 Jim_AppendStrings(interp, Jim_GetResult(interp),
4494 "mem2array: too large read request, exceeds 64K items", NULL);
4499 ((width == 2) && ((addr & 1) == 0)) ||
4500 ((width == 4) && ((addr & 3) == 0)) ||
4501 ((width == 8) && ((addr & 7) == 0))) {
4502 /* alignment correct */
4505 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4506 sprintf(buf, "mem2array address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4509 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4518 const size_t buffersize = 4096;
4519 uint8_t *buffer = malloc(buffersize);
4526 /* Slurp... in buffer size chunks */
4527 const unsigned int max_chunk_len = buffersize / width;
4528 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4532 retval = target_read_phys_memory(target, addr, width, chunk_len, buffer);
4534 retval = target_read_memory(target, addr, width, chunk_len, buffer);
4535 if (retval != ERROR_OK) {
4537 LOG_ERROR("mem2array: Read @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4541 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4542 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
4546 for (size_t i = 0; i < chunk_len ; i++, idx++) {
4550 v = target_buffer_get_u64(target, &buffer[i*width]);
4553 v = target_buffer_get_u32(target, &buffer[i*width]);
4556 v = target_buffer_get_u16(target, &buffer[i*width]);
4559 v = buffer[i] & 0x0ff;
4562 new_u64_array_element(interp, varname, idx, v);
4565 addr += chunk_len * width;
4571 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4576 static int get_u64_array_element(Jim_Interp *interp, const char *varname, size_t idx, uint64_t *val)
4578 char *namebuf = alloc_printf("%s(%zu)", varname, idx);
4582 Jim_Obj *nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
4588 Jim_IncrRefCount(nameObjPtr);
4589 Jim_Obj *valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
4590 Jim_DecrRefCount(interp, nameObjPtr);
4592 if (valObjPtr == NULL)
4596 int result = Jim_GetWide(interp, valObjPtr, &wide_val);
4601 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4603 struct command_context *context;
4604 struct target *target;
4606 context = current_command_context(interp);
4607 assert(context != NULL);
4609 target = get_current_target(context);
4610 if (target == NULL) {
4611 LOG_ERROR("array2mem: no current target");
4615 return target_array2mem(interp, target, argc-1, argv + 1);
4618 static int target_array2mem(Jim_Interp *interp, struct target *target,
4619 int argc, Jim_Obj *const *argv)
4623 /* argv[0] = name of array from which to read the data
4624 * argv[1] = desired element width in bits
4625 * argv[2] = memory address
4626 * argv[3] = number of elements to write
4627 * argv[4] = optional "phys"
4629 if (argc < 4 || argc > 5) {
4630 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4634 /* Arg 0: Name of the array variable */
4635 const char *varname = Jim_GetString(argv[0], NULL);
4637 /* Arg 1: Bit width of one element */
4639 e = Jim_GetLong(interp, argv[1], &l);
4642 const unsigned int width_bits = l;
4644 if (width_bits != 8 &&
4648 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4649 Jim_AppendStrings(interp, Jim_GetResult(interp),
4650 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4653 const unsigned int width = width_bits / 8;
4655 /* Arg 2: Memory address */
4657 e = Jim_GetWide(interp, argv[2], &wide_addr);
4660 target_addr_t addr = (target_addr_t)wide_addr;
4662 /* Arg 3: Number of elements to write */
4663 e = Jim_GetLong(interp, argv[3], &l);
4669 bool is_phys = false;
4672 const char *phys = Jim_GetString(argv[4], &str_len);
4673 if (!strncmp(phys, "phys", str_len))
4679 /* Argument checks */
4681 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4682 Jim_AppendStrings(interp, Jim_GetResult(interp),
4683 "array2mem: zero width read?", NULL);
4687 if ((addr + (len * width)) < addr) {
4688 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4689 Jim_AppendStrings(interp, Jim_GetResult(interp),
4690 "array2mem: addr + len - wraps to zero?", NULL);
4695 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4696 Jim_AppendStrings(interp, Jim_GetResult(interp),
4697 "array2mem: too large memory write request, exceeds 64K items", NULL);
4702 ((width == 2) && ((addr & 1) == 0)) ||
4703 ((width == 4) && ((addr & 3) == 0)) ||
4704 ((width == 8) && ((addr & 7) == 0))) {
4705 /* alignment correct */
4708 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4709 sprintf(buf, "array2mem address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4712 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4721 const size_t buffersize = 4096;
4722 uint8_t *buffer = malloc(buffersize);
4730 /* Slurp... in buffer size chunks */
4731 const unsigned int max_chunk_len = buffersize / width;
4733 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4735 /* Fill the buffer */
4736 for (size_t i = 0; i < chunk_len; i++, idx++) {
4738 if (get_u64_array_element(interp, varname, idx, &v) != JIM_OK) {
4744 target_buffer_set_u64(target, &buffer[i * width], v);
4747 target_buffer_set_u32(target, &buffer[i * width], v);
4750 target_buffer_set_u16(target, &buffer[i * width], v);
4753 buffer[i] = v & 0x0ff;
4759 /* Write the buffer to memory */
4762 retval = target_write_phys_memory(target, addr, width, chunk_len, buffer);
4764 retval = target_write_memory(target, addr, width, chunk_len, buffer);
4765 if (retval != ERROR_OK) {
4767 LOG_ERROR("array2mem: Write @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4771 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4772 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4776 addr += chunk_len * width;
4781 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4786 /* FIX? should we propagate errors here rather than printing them
4789 void target_handle_event(struct target *target, enum target_event e)
4791 struct target_event_action *teap;
4794 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4795 if (teap->event == e) {
4796 LOG_DEBUG("target(%d): %s (%s) event: %d (%s) action: %s",
4797 target->target_number,
4798 target_name(target),
4799 target_type_name(target),
4801 jim_nvp_value2name_simple(nvp_target_event, e)->name,
4802 Jim_GetString(teap->body, NULL));
4804 /* Override current target by the target an event
4805 * is issued from (lot of scripts need it).
4806 * Return back to previous override as soon
4807 * as the handler processing is done */
4808 struct command_context *cmd_ctx = current_command_context(teap->interp);
4809 struct target *saved_target_override = cmd_ctx->current_target_override;
4810 cmd_ctx->current_target_override = target;
4812 retval = Jim_EvalObj(teap->interp, teap->body);
4814 cmd_ctx->current_target_override = saved_target_override;
4816 if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
4819 if (retval == JIM_RETURN)
4820 retval = teap->interp->returnCode;
4822 if (retval != JIM_OK) {
4823 Jim_MakeErrorMessage(teap->interp);
4824 LOG_USER("Error executing event %s on target %s:\n%s",
4825 jim_nvp_value2name_simple(nvp_target_event, e)->name,
4826 target_name(target),
4827 Jim_GetString(Jim_GetResult(teap->interp), NULL));
4828 /* clean both error code and stacktrace before return */
4829 Jim_Eval(teap->interp, "error \"\" \"\"");
4836 * Returns true only if the target has a handler for the specified event.
4838 bool target_has_event_action(struct target *target, enum target_event event)
4840 struct target_event_action *teap;
4842 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4843 if (teap->event == event)
4849 enum target_cfg_param {
4852 TCFG_WORK_AREA_VIRT,
4853 TCFG_WORK_AREA_PHYS,
4854 TCFG_WORK_AREA_SIZE,
4855 TCFG_WORK_AREA_BACKUP,
4858 TCFG_CHAIN_POSITION,
4863 TCFG_GDB_MAX_CONNECTIONS,
4866 static struct jim_nvp nvp_config_opts[] = {
4867 { .name = "-type", .value = TCFG_TYPE },
4868 { .name = "-event", .value = TCFG_EVENT },
4869 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4870 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4871 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4872 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4873 { .name = "-endian", .value = TCFG_ENDIAN },
4874 { .name = "-coreid", .value = TCFG_COREID },
4875 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4876 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4877 { .name = "-rtos", .value = TCFG_RTOS },
4878 { .name = "-defer-examine", .value = TCFG_DEFER_EXAMINE },
4879 { .name = "-gdb-port", .value = TCFG_GDB_PORT },
4880 { .name = "-gdb-max-connections", .value = TCFG_GDB_MAX_CONNECTIONS },
4881 { .name = NULL, .value = -1 }
4884 static int target_configure(struct jim_getopt_info *goi, struct target *target)
4891 /* parse config or cget options ... */
4892 while (goi->argc > 0) {
4893 Jim_SetEmptyResult(goi->interp);
4894 /* jim_getopt_debug(goi); */
4896 if (target->type->target_jim_configure) {
4897 /* target defines a configure function */
4898 /* target gets first dibs on parameters */
4899 e = (*(target->type->target_jim_configure))(target, goi);
4908 /* otherwise we 'continue' below */
4910 e = jim_getopt_nvp(goi, nvp_config_opts, &n);
4912 jim_getopt_nvp_unknown(goi, nvp_config_opts, 0);
4918 if (goi->isconfigure) {
4919 Jim_SetResultFormatted(goi->interp,
4920 "not settable: %s", n->name);
4924 if (goi->argc != 0) {
4925 Jim_WrongNumArgs(goi->interp,
4926 goi->argc, goi->argv,
4931 Jim_SetResultString(goi->interp,
4932 target_type_name(target), -1);
4936 if (goi->argc == 0) {
4937 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4941 e = jim_getopt_nvp(goi, nvp_target_event, &n);
4943 jim_getopt_nvp_unknown(goi, nvp_target_event, 1);
4947 if (goi->isconfigure) {
4948 if (goi->argc != 1) {
4949 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4953 if (goi->argc != 0) {
4954 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4960 struct target_event_action *teap;
4962 teap = target->event_action;
4963 /* replace existing? */
4965 if (teap->event == (enum target_event)n->value)
4970 if (goi->isconfigure) {
4971 /* START_DEPRECATED_TPIU */
4972 if (n->value == TARGET_EVENT_TRACE_CONFIG)
4973 LOG_INFO("DEPRECATED target event %s", n->name);
4974 /* END_DEPRECATED_TPIU */
4976 bool replace = true;
4979 teap = calloc(1, sizeof(*teap));
4982 teap->event = n->value;
4983 teap->interp = goi->interp;
4984 jim_getopt_obj(goi, &o);
4986 Jim_DecrRefCount(teap->interp, teap->body);
4987 teap->body = Jim_DuplicateObj(goi->interp, o);
4990 * Tcl/TK - "tk events" have a nice feature.
4991 * See the "BIND" command.
4992 * We should support that here.
4993 * You can specify %X and %Y in the event code.
4994 * The idea is: %T - target name.
4995 * The idea is: %N - target number
4996 * The idea is: %E - event name.
4998 Jim_IncrRefCount(teap->body);
5001 /* add to head of event list */
5002 teap->next = target->event_action;
5003 target->event_action = teap;
5005 Jim_SetEmptyResult(goi->interp);
5009 Jim_SetEmptyResult(goi->interp);
5011 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
5017 case TCFG_WORK_AREA_VIRT:
5018 if (goi->isconfigure) {
5019 target_free_all_working_areas(target);
5020 e = jim_getopt_wide(goi, &w);
5023 target->working_area_virt = w;
5024 target->working_area_virt_spec = true;
5029 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
5033 case TCFG_WORK_AREA_PHYS:
5034 if (goi->isconfigure) {
5035 target_free_all_working_areas(target);
5036 e = jim_getopt_wide(goi, &w);
5039 target->working_area_phys = w;
5040 target->working_area_phys_spec = true;
5045 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
5049 case TCFG_WORK_AREA_SIZE:
5050 if (goi->isconfigure) {
5051 target_free_all_working_areas(target);
5052 e = jim_getopt_wide(goi, &w);
5055 target->working_area_size = w;
5060 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
5064 case TCFG_WORK_AREA_BACKUP:
5065 if (goi->isconfigure) {
5066 target_free_all_working_areas(target);
5067 e = jim_getopt_wide(goi, &w);
5070 /* make this exactly 1 or 0 */
5071 target->backup_working_area = (!!w);
5076 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
5077 /* loop for more e*/
5082 if (goi->isconfigure) {
5083 e = jim_getopt_nvp(goi, nvp_target_endian, &n);
5085 jim_getopt_nvp_unknown(goi, nvp_target_endian, 1);
5088 target->endianness = n->value;
5093 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5094 if (n->name == NULL) {
5095 target->endianness = TARGET_LITTLE_ENDIAN;
5096 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5098 Jim_SetResultString(goi->interp, n->name, -1);
5103 if (goi->isconfigure) {
5104 e = jim_getopt_wide(goi, &w);
5107 target->coreid = (int32_t)w;
5112 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->coreid));
5116 case TCFG_CHAIN_POSITION:
5117 if (goi->isconfigure) {
5119 struct jtag_tap *tap;
5121 if (target->has_dap) {
5122 Jim_SetResultString(goi->interp,
5123 "target requires -dap parameter instead of -chain-position!", -1);
5127 target_free_all_working_areas(target);
5128 e = jim_getopt_obj(goi, &o_t);
5131 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
5135 target->tap_configured = true;
5140 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
5141 /* loop for more e*/
5144 if (goi->isconfigure) {
5145 e = jim_getopt_wide(goi, &w);
5148 target->dbgbase = (uint32_t)w;
5149 target->dbgbase_set = true;
5154 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
5160 int result = rtos_create(goi, target);
5161 if (result != JIM_OK)
5167 case TCFG_DEFER_EXAMINE:
5169 target->defer_examine = true;
5174 if (goi->isconfigure) {
5175 struct command_context *cmd_ctx = current_command_context(goi->interp);
5176 if (cmd_ctx->mode != COMMAND_CONFIG) {
5177 Jim_SetResultString(goi->interp, "-gdb-port must be configured before 'init'", -1);
5182 e = jim_getopt_string(goi, &s, NULL);
5185 free(target->gdb_port_override);
5186 target->gdb_port_override = strdup(s);
5191 Jim_SetResultString(goi->interp, target->gdb_port_override ? target->gdb_port_override : "undefined", -1);
5195 case TCFG_GDB_MAX_CONNECTIONS:
5196 if (goi->isconfigure) {
5197 struct command_context *cmd_ctx = current_command_context(goi->interp);
5198 if (cmd_ctx->mode != COMMAND_CONFIG) {
5199 Jim_SetResultString(goi->interp, "-gdb-max-connections must be configured before 'init'", -1);
5203 e = jim_getopt_wide(goi, &w);
5206 target->gdb_max_connections = (w < 0) ? CONNECTION_LIMIT_UNLIMITED : (int)w;
5211 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->gdb_max_connections));
5214 } /* while (goi->argc) */
5217 /* done - we return */
5221 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5223 struct command *c = jim_to_command(interp);
5224 struct jim_getopt_info goi;
5226 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5227 goi.isconfigure = !strcmp(c->name, "configure");
5229 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5230 "missing: -option ...");
5233 struct command_context *cmd_ctx = current_command_context(interp);
5235 struct target *target = get_current_target(cmd_ctx);
5236 return target_configure(&goi, target);
5239 static int jim_target_mem2array(Jim_Interp *interp,
5240 int argc, Jim_Obj *const *argv)
5242 struct command_context *cmd_ctx = current_command_context(interp);
5244 struct target *target = get_current_target(cmd_ctx);
5245 return target_mem2array(interp, target, argc - 1, argv + 1);
5248 static int jim_target_array2mem(Jim_Interp *interp,
5249 int argc, Jim_Obj *const *argv)
5251 struct command_context *cmd_ctx = current_command_context(interp);
5253 struct target *target = get_current_target(cmd_ctx);
5254 return target_array2mem(interp, target, argc - 1, argv + 1);
5257 static int jim_target_tap_disabled(Jim_Interp *interp)
5259 Jim_SetResultFormatted(interp, "[TAP is disabled]");
5263 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5265 bool allow_defer = false;
5267 struct jim_getopt_info goi;
5268 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5270 const char *cmd_name = Jim_GetString(argv[0], NULL);
5271 Jim_SetResultFormatted(goi.interp,
5272 "usage: %s ['allow-defer']", cmd_name);
5276 strcmp(Jim_GetString(argv[1], NULL), "allow-defer") == 0) {
5279 int e = jim_getopt_obj(&goi, &obj);
5285 struct command_context *cmd_ctx = current_command_context(interp);
5287 struct target *target = get_current_target(cmd_ctx);
5288 if (!target->tap->enabled)
5289 return jim_target_tap_disabled(interp);
5291 if (allow_defer && target->defer_examine) {
5292 LOG_INFO("Deferring arp_examine of %s", target_name(target));
5293 LOG_INFO("Use arp_examine command to examine it manually!");
5297 int e = target->type->examine(target);
5303 static int jim_target_was_examined(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5305 struct command_context *cmd_ctx = current_command_context(interp);
5307 struct target *target = get_current_target(cmd_ctx);
5309 Jim_SetResultBool(interp, target_was_examined(target));
5313 static int jim_target_examine_deferred(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5315 struct command_context *cmd_ctx = current_command_context(interp);
5317 struct target *target = get_current_target(cmd_ctx);
5319 Jim_SetResultBool(interp, target->defer_examine);
5323 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5326 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5329 struct command_context *cmd_ctx = current_command_context(interp);
5331 struct target *target = get_current_target(cmd_ctx);
5333 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
5339 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5342 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5345 struct command_context *cmd_ctx = current_command_context(interp);
5347 struct target *target = get_current_target(cmd_ctx);
5348 if (!target->tap->enabled)
5349 return jim_target_tap_disabled(interp);
5352 if (!(target_was_examined(target)))
5353 e = ERROR_TARGET_NOT_EXAMINED;
5355 e = target->type->poll(target);
5361 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5363 struct jim_getopt_info goi;
5364 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5366 if (goi.argc != 2) {
5367 Jim_WrongNumArgs(interp, 0, argv,
5368 "([tT]|[fF]|assert|deassert) BOOL");
5373 int e = jim_getopt_nvp(&goi, nvp_assert, &n);
5375 jim_getopt_nvp_unknown(&goi, nvp_assert, 1);
5378 /* the halt or not param */
5380 e = jim_getopt_wide(&goi, &a);
5384 struct command_context *cmd_ctx = current_command_context(interp);
5386 struct target *target = get_current_target(cmd_ctx);
5387 if (!target->tap->enabled)
5388 return jim_target_tap_disabled(interp);
5390 if (!target->type->assert_reset || !target->type->deassert_reset) {
5391 Jim_SetResultFormatted(interp,
5392 "No target-specific reset for %s",
5393 target_name(target));
5397 if (target->defer_examine)
5398 target_reset_examined(target);
5400 /* determine if we should halt or not. */
5401 target->reset_halt = (a != 0);
5402 /* When this happens - all workareas are invalid. */
5403 target_free_all_working_areas_restore(target, 0);
5406 if (n->value == NVP_ASSERT)
5407 e = target->type->assert_reset(target);
5409 e = target->type->deassert_reset(target);
5410 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5413 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5416 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5419 struct command_context *cmd_ctx = current_command_context(interp);
5421 struct target *target = get_current_target(cmd_ctx);
5422 if (!target->tap->enabled)
5423 return jim_target_tap_disabled(interp);
5424 int e = target->type->halt(target);
5425 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5428 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5430 struct jim_getopt_info goi;
5431 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5433 /* params: <name> statename timeoutmsecs */
5434 if (goi.argc != 2) {
5435 const char *cmd_name = Jim_GetString(argv[0], NULL);
5436 Jim_SetResultFormatted(goi.interp,
5437 "%s <state_name> <timeout_in_msec>", cmd_name);
5442 int e = jim_getopt_nvp(&goi, nvp_target_state, &n);
5444 jim_getopt_nvp_unknown(&goi, nvp_target_state, 1);
5448 e = jim_getopt_wide(&goi, &a);
5451 struct command_context *cmd_ctx = current_command_context(interp);
5453 struct target *target = get_current_target(cmd_ctx);
5454 if (!target->tap->enabled)
5455 return jim_target_tap_disabled(interp);
5457 e = target_wait_state(target, n->value, a);
5458 if (e != ERROR_OK) {
5459 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
5460 Jim_SetResultFormatted(goi.interp,
5461 "target: %s wait %s fails (%#s) %s",
5462 target_name(target), n->name,
5463 eObj, target_strerror_safe(e));
5468 /* List for human, Events defined for this target.
5469 * scripts/programs should use 'name cget -event NAME'
5471 COMMAND_HANDLER(handle_target_event_list)
5473 struct target *target = get_current_target(CMD_CTX);
5474 struct target_event_action *teap = target->event_action;
5476 command_print(CMD, "Event actions for target (%d) %s\n",
5477 target->target_number,
5478 target_name(target));
5479 command_print(CMD, "%-25s | Body", "Event");
5480 command_print(CMD, "------------------------- | "
5481 "----------------------------------------");
5483 struct jim_nvp *opt = jim_nvp_value2name_simple(nvp_target_event, teap->event);
5484 command_print(CMD, "%-25s | %s",
5485 opt->name, Jim_GetString(teap->body, NULL));
5488 command_print(CMD, "***END***");
5491 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5494 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5497 struct command_context *cmd_ctx = current_command_context(interp);
5499 struct target *target = get_current_target(cmd_ctx);
5500 Jim_SetResultString(interp, target_state_name(target), -1);
5503 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5505 struct jim_getopt_info goi;
5506 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5507 if (goi.argc != 1) {
5508 const char *cmd_name = Jim_GetString(argv[0], NULL);
5509 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5513 int e = jim_getopt_nvp(&goi, nvp_target_event, &n);
5515 jim_getopt_nvp_unknown(&goi, nvp_target_event, 1);
5518 struct command_context *cmd_ctx = current_command_context(interp);
5520 struct target *target = get_current_target(cmd_ctx);
5521 target_handle_event(target, n->value);
5525 static const struct command_registration target_instance_command_handlers[] = {
5527 .name = "configure",
5528 .mode = COMMAND_ANY,
5529 .jim_handler = jim_target_configure,
5530 .help = "configure a new target for use",
5531 .usage = "[target_attribute ...]",
5535 .mode = COMMAND_ANY,
5536 .jim_handler = jim_target_configure,
5537 .help = "returns the specified target attribute",
5538 .usage = "target_attribute",
5542 .handler = handle_mw_command,
5543 .mode = COMMAND_EXEC,
5544 .help = "Write 64-bit word(s) to target memory",
5545 .usage = "address data [count]",
5549 .handler = handle_mw_command,
5550 .mode = COMMAND_EXEC,
5551 .help = "Write 32-bit word(s) to target memory",
5552 .usage = "address data [count]",
5556 .handler = handle_mw_command,
5557 .mode = COMMAND_EXEC,
5558 .help = "Write 16-bit half-word(s) to target memory",
5559 .usage = "address data [count]",
5563 .handler = handle_mw_command,
5564 .mode = COMMAND_EXEC,
5565 .help = "Write byte(s) to target memory",
5566 .usage = "address data [count]",
5570 .handler = handle_md_command,
5571 .mode = COMMAND_EXEC,
5572 .help = "Display target memory as 64-bit words",
5573 .usage = "address [count]",
5577 .handler = handle_md_command,
5578 .mode = COMMAND_EXEC,
5579 .help = "Display target memory as 32-bit words",
5580 .usage = "address [count]",
5584 .handler = handle_md_command,
5585 .mode = COMMAND_EXEC,
5586 .help = "Display target memory as 16-bit half-words",
5587 .usage = "address [count]",
5591 .handler = handle_md_command,
5592 .mode = COMMAND_EXEC,
5593 .help = "Display target memory as 8-bit bytes",
5594 .usage = "address [count]",
5597 .name = "array2mem",
5598 .mode = COMMAND_EXEC,
5599 .jim_handler = jim_target_array2mem,
5600 .help = "Writes Tcl array of 8/16/32 bit numbers "
5602 .usage = "arrayname bitwidth address count",
5605 .name = "mem2array",
5606 .mode = COMMAND_EXEC,
5607 .jim_handler = jim_target_mem2array,
5608 .help = "Loads Tcl array of 8/16/32 bit numbers "
5609 "from target memory",
5610 .usage = "arrayname bitwidth address count",
5613 .name = "eventlist",
5614 .handler = handle_target_event_list,
5615 .mode = COMMAND_EXEC,
5616 .help = "displays a table of events defined for this target",
5621 .mode = COMMAND_EXEC,
5622 .jim_handler = jim_target_current_state,
5623 .help = "displays the current state of this target",
5626 .name = "arp_examine",
5627 .mode = COMMAND_EXEC,
5628 .jim_handler = jim_target_examine,
5629 .help = "used internally for reset processing",
5630 .usage = "['allow-defer']",
5633 .name = "was_examined",
5634 .mode = COMMAND_EXEC,
5635 .jim_handler = jim_target_was_examined,
5636 .help = "used internally for reset processing",
5639 .name = "examine_deferred",
5640 .mode = COMMAND_EXEC,
5641 .jim_handler = jim_target_examine_deferred,
5642 .help = "used internally for reset processing",
5645 .name = "arp_halt_gdb",
5646 .mode = COMMAND_EXEC,
5647 .jim_handler = jim_target_halt_gdb,
5648 .help = "used internally for reset processing to halt GDB",
5652 .mode = COMMAND_EXEC,
5653 .jim_handler = jim_target_poll,
5654 .help = "used internally for reset processing",
5657 .name = "arp_reset",
5658 .mode = COMMAND_EXEC,
5659 .jim_handler = jim_target_reset,
5660 .help = "used internally for reset processing",
5664 .mode = COMMAND_EXEC,
5665 .jim_handler = jim_target_halt,
5666 .help = "used internally for reset processing",
5669 .name = "arp_waitstate",
5670 .mode = COMMAND_EXEC,
5671 .jim_handler = jim_target_wait_state,
5672 .help = "used internally for reset processing",
5675 .name = "invoke-event",
5676 .mode = COMMAND_EXEC,
5677 .jim_handler = jim_target_invoke_event,
5678 .help = "invoke handler for specified event",
5679 .usage = "event_name",
5681 COMMAND_REGISTRATION_DONE
5684 static int target_create(struct jim_getopt_info *goi)
5691 struct target *target;
5692 struct command_context *cmd_ctx;
5694 cmd_ctx = current_command_context(goi->interp);
5695 assert(cmd_ctx != NULL);
5697 if (goi->argc < 3) {
5698 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5703 jim_getopt_obj(goi, &new_cmd);
5704 /* does this command exist? */
5705 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
5707 cp = Jim_GetString(new_cmd, NULL);
5708 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5713 e = jim_getopt_string(goi, &cp, NULL);
5716 struct transport *tr = get_current_transport();
5717 if (tr->override_target) {
5718 e = tr->override_target(&cp);
5719 if (e != ERROR_OK) {
5720 LOG_ERROR("The selected transport doesn't support this target");
5723 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5725 /* now does target type exist */
5726 for (x = 0 ; target_types[x] ; x++) {
5727 if (0 == strcmp(cp, target_types[x]->name)) {
5732 if (target_types[x] == NULL) {
5733 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5734 for (x = 0 ; target_types[x] ; x++) {
5735 if (target_types[x + 1]) {
5736 Jim_AppendStrings(goi->interp,
5737 Jim_GetResult(goi->interp),
5738 target_types[x]->name,
5741 Jim_AppendStrings(goi->interp,
5742 Jim_GetResult(goi->interp),
5744 target_types[x]->name, NULL);
5751 target = calloc(1, sizeof(struct target));
5753 LOG_ERROR("Out of memory");
5757 /* set target number */
5758 target->target_number = new_target_number();
5760 /* allocate memory for each unique target type */
5761 target->type = malloc(sizeof(struct target_type));
5762 if (!target->type) {
5763 LOG_ERROR("Out of memory");
5768 memcpy(target->type, target_types[x], sizeof(struct target_type));
5770 /* default to first core, override with -coreid */
5773 target->working_area = 0x0;
5774 target->working_area_size = 0x0;
5775 target->working_areas = NULL;
5776 target->backup_working_area = 0;
5778 target->state = TARGET_UNKNOWN;
5779 target->debug_reason = DBG_REASON_UNDEFINED;
5780 target->reg_cache = NULL;
5781 target->breakpoints = NULL;
5782 target->watchpoints = NULL;
5783 target->next = NULL;
5784 target->arch_info = NULL;
5786 target->verbose_halt_msg = true;
5788 target->halt_issued = false;
5790 /* initialize trace information */
5791 target->trace_info = calloc(1, sizeof(struct trace));
5792 if (!target->trace_info) {
5793 LOG_ERROR("Out of memory");
5799 target->dbgmsg = NULL;
5800 target->dbg_msg_enabled = 0;
5802 target->endianness = TARGET_ENDIAN_UNKNOWN;
5804 target->rtos = NULL;
5805 target->rtos_auto_detect = false;
5807 target->gdb_port_override = NULL;
5808 target->gdb_max_connections = 1;
5810 /* Do the rest as "configure" options */
5811 goi->isconfigure = 1;
5812 e = target_configure(goi, target);
5815 if (target->has_dap) {
5816 if (!target->dap_configured) {
5817 Jim_SetResultString(goi->interp, "-dap ?name? required when creating target", -1);
5821 if (!target->tap_configured) {
5822 Jim_SetResultString(goi->interp, "-chain-position ?name? required when creating target", -1);
5826 /* tap must be set after target was configured */
5827 if (target->tap == NULL)
5832 rtos_destroy(target);
5833 free(target->gdb_port_override);
5834 free(target->trace_info);
5840 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5841 /* default endian to little if not specified */
5842 target->endianness = TARGET_LITTLE_ENDIAN;
5845 cp = Jim_GetString(new_cmd, NULL);
5846 target->cmd_name = strdup(cp);
5847 if (!target->cmd_name) {
5848 LOG_ERROR("Out of memory");
5849 rtos_destroy(target);
5850 free(target->gdb_port_override);
5851 free(target->trace_info);
5857 if (target->type->target_create) {
5858 e = (*(target->type->target_create))(target, goi->interp);
5859 if (e != ERROR_OK) {
5860 LOG_DEBUG("target_create failed");
5861 free(target->cmd_name);
5862 rtos_destroy(target);
5863 free(target->gdb_port_override);
5864 free(target->trace_info);
5871 /* create the target specific commands */
5872 if (target->type->commands) {
5873 e = register_commands(cmd_ctx, NULL, target->type->commands);
5875 LOG_ERROR("unable to register '%s' commands", cp);
5878 /* now - create the new target name command */
5879 const struct command_registration target_subcommands[] = {
5881 .chain = target_instance_command_handlers,
5884 .chain = target->type->commands,
5886 COMMAND_REGISTRATION_DONE
5888 const struct command_registration target_commands[] = {
5891 .mode = COMMAND_ANY,
5892 .help = "target command group",
5894 .chain = target_subcommands,
5896 COMMAND_REGISTRATION_DONE
5898 e = register_commands_override_target(cmd_ctx, NULL, target_commands, target);
5899 if (e != ERROR_OK) {
5900 if (target->type->deinit_target)
5901 target->type->deinit_target(target);
5902 free(target->cmd_name);
5903 rtos_destroy(target);
5904 free(target->gdb_port_override);
5905 free(target->trace_info);
5911 /* append to end of list */
5912 append_to_list_all_targets(target);
5914 cmd_ctx->current_target = target;
5918 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5921 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5924 struct command_context *cmd_ctx = current_command_context(interp);
5925 assert(cmd_ctx != NULL);
5927 struct target *target = get_current_target_or_null(cmd_ctx);
5929 Jim_SetResultString(interp, target_name(target), -1);
5933 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5936 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5939 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5940 for (unsigned x = 0; NULL != target_types[x]; x++) {
5941 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5942 Jim_NewStringObj(interp, target_types[x]->name, -1));
5947 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5950 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5953 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5954 struct target *target = all_targets;
5956 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5957 Jim_NewStringObj(interp, target_name(target), -1));
5958 target = target->next;
5963 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5966 const char *targetname;
5968 struct target *target = (struct target *) NULL;
5969 struct target_list *head, *curr, *new;
5970 curr = (struct target_list *) NULL;
5971 head = (struct target_list *) NULL;
5974 LOG_DEBUG("%d", argc);
5975 /* argv[1] = target to associate in smp
5976 * argv[2] = target to associate in smp
5980 for (i = 1; i < argc; i++) {
5982 targetname = Jim_GetString(argv[i], &len);
5983 target = get_target(targetname);
5984 LOG_DEBUG("%s ", targetname);
5986 new = malloc(sizeof(struct target_list));
5987 new->target = target;
5988 new->next = (struct target_list *)NULL;
5989 if (head == (struct target_list *)NULL) {
5998 /* now parse the list of cpu and put the target in smp mode*/
6001 while (curr != (struct target_list *)NULL) {
6002 target = curr->target;
6004 target->head = head;
6008 if (target && target->rtos)
6009 retval = rtos_smp_init(head->target);
6015 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6017 struct jim_getopt_info goi;
6018 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
6020 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
6021 "<name> <target_type> [<target_options> ...]");
6024 return target_create(&goi);
6027 static const struct command_registration target_subcommand_handlers[] = {
6030 .mode = COMMAND_CONFIG,
6031 .handler = handle_target_init_command,
6032 .help = "initialize targets",
6037 .mode = COMMAND_CONFIG,
6038 .jim_handler = jim_target_create,
6039 .usage = "name type '-chain-position' name [options ...]",
6040 .help = "Creates and selects a new target",
6044 .mode = COMMAND_ANY,
6045 .jim_handler = jim_target_current,
6046 .help = "Returns the currently selected target",
6050 .mode = COMMAND_ANY,
6051 .jim_handler = jim_target_types,
6052 .help = "Returns the available target types as "
6053 "a list of strings",
6057 .mode = COMMAND_ANY,
6058 .jim_handler = jim_target_names,
6059 .help = "Returns the names of all targets as a list of strings",
6063 .mode = COMMAND_ANY,
6064 .jim_handler = jim_target_smp,
6065 .usage = "targetname1 targetname2 ...",
6066 .help = "gather several target in a smp list"
6069 COMMAND_REGISTRATION_DONE
6073 target_addr_t address;
6079 static int fastload_num;
6080 static struct FastLoad *fastload;
6082 static void free_fastload(void)
6084 if (fastload != NULL) {
6085 for (int i = 0; i < fastload_num; i++)
6086 free(fastload[i].data);
6092 COMMAND_HANDLER(handle_fast_load_image_command)
6096 uint32_t image_size;
6097 target_addr_t min_address = 0;
6098 target_addr_t max_address = -1;
6102 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
6103 &image, &min_address, &max_address);
6104 if (ERROR_OK != retval)
6107 struct duration bench;
6108 duration_start(&bench);
6110 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
6111 if (retval != ERROR_OK)
6116 fastload_num = image.num_sections;
6117 fastload = malloc(sizeof(struct FastLoad)*image.num_sections);
6118 if (fastload == NULL) {
6119 command_print(CMD, "out of memory");
6120 image_close(&image);
6123 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
6124 for (unsigned int i = 0; i < image.num_sections; i++) {
6125 buffer = malloc(image.sections[i].size);
6126 if (buffer == NULL) {
6127 command_print(CMD, "error allocating buffer for section (%d bytes)",
6128 (int)(image.sections[i].size));
6129 retval = ERROR_FAIL;
6133 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
6134 if (retval != ERROR_OK) {
6139 uint32_t offset = 0;
6140 uint32_t length = buf_cnt;
6142 /* DANGER!!! beware of unsigned comparison here!!! */
6144 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
6145 (image.sections[i].base_address < max_address)) {
6146 if (image.sections[i].base_address < min_address) {
6147 /* clip addresses below */
6148 offset += min_address-image.sections[i].base_address;
6152 if (image.sections[i].base_address + buf_cnt > max_address)
6153 length -= (image.sections[i].base_address + buf_cnt)-max_address;
6155 fastload[i].address = image.sections[i].base_address + offset;
6156 fastload[i].data = malloc(length);
6157 if (fastload[i].data == NULL) {
6159 command_print(CMD, "error allocating buffer for section (%" PRIu32 " bytes)",
6161 retval = ERROR_FAIL;
6164 memcpy(fastload[i].data, buffer + offset, length);
6165 fastload[i].length = length;
6167 image_size += length;
6168 command_print(CMD, "%u bytes written at address 0x%8.8x",
6169 (unsigned int)length,
6170 ((unsigned int)(image.sections[i].base_address + offset)));
6176 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
6177 command_print(CMD, "Loaded %" PRIu32 " bytes "
6178 "in %fs (%0.3f KiB/s)", image_size,
6179 duration_elapsed(&bench), duration_kbps(&bench, image_size));
6182 "WARNING: image has not been loaded to target!"
6183 "You can issue a 'fast_load' to finish loading.");
6186 image_close(&image);
6188 if (retval != ERROR_OK)
6194 COMMAND_HANDLER(handle_fast_load_command)
6197 return ERROR_COMMAND_SYNTAX_ERROR;
6198 if (fastload == NULL) {
6199 LOG_ERROR("No image in memory");
6203 int64_t ms = timeval_ms();
6205 int retval = ERROR_OK;
6206 for (i = 0; i < fastload_num; i++) {
6207 struct target *target = get_current_target(CMD_CTX);
6208 command_print(CMD, "Write to 0x%08x, length 0x%08x",
6209 (unsigned int)(fastload[i].address),
6210 (unsigned int)(fastload[i].length));
6211 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
6212 if (retval != ERROR_OK)
6214 size += fastload[i].length;
6216 if (retval == ERROR_OK) {
6217 int64_t after = timeval_ms();
6218 command_print(CMD, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
6223 static const struct command_registration target_command_handlers[] = {
6226 .handler = handle_targets_command,
6227 .mode = COMMAND_ANY,
6228 .help = "change current default target (one parameter) "
6229 "or prints table of all targets (no parameters)",
6230 .usage = "[target]",
6234 .mode = COMMAND_CONFIG,
6235 .help = "configure target",
6236 .chain = target_subcommand_handlers,
6239 COMMAND_REGISTRATION_DONE
6242 int target_register_commands(struct command_context *cmd_ctx)
6244 return register_commands(cmd_ctx, NULL, target_command_handlers);
6247 static bool target_reset_nag = true;
6249 bool get_target_reset_nag(void)
6251 return target_reset_nag;
6254 COMMAND_HANDLER(handle_target_reset_nag)
6256 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
6257 &target_reset_nag, "Nag after each reset about options to improve "
6261 COMMAND_HANDLER(handle_ps_command)
6263 struct target *target = get_current_target(CMD_CTX);
6265 if (target->state != TARGET_HALTED) {
6266 LOG_INFO("target not halted !!");
6270 if ((target->rtos) && (target->rtos->type)
6271 && (target->rtos->type->ps_command)) {
6272 display = target->rtos->type->ps_command(target);
6273 command_print(CMD, "%s", display);
6278 return ERROR_TARGET_FAILURE;
6282 static void binprint(struct command_invocation *cmd, const char *text, const uint8_t *buf, int size)
6285 command_print_sameline(cmd, "%s", text);
6286 for (int i = 0; i < size; i++)
6287 command_print_sameline(cmd, " %02x", buf[i]);
6288 command_print(cmd, " ");
6291 COMMAND_HANDLER(handle_test_mem_access_command)
6293 struct target *target = get_current_target(CMD_CTX);
6295 int retval = ERROR_OK;
6297 if (target->state != TARGET_HALTED) {
6298 LOG_INFO("target not halted !!");
6303 return ERROR_COMMAND_SYNTAX_ERROR;
6305 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
6308 size_t num_bytes = test_size + 4;
6310 struct working_area *wa = NULL;
6311 retval = target_alloc_working_area(target, num_bytes, &wa);
6312 if (retval != ERROR_OK) {
6313 LOG_ERROR("Not enough working area");
6317 uint8_t *test_pattern = malloc(num_bytes);
6319 for (size_t i = 0; i < num_bytes; i++)
6320 test_pattern[i] = rand();
6322 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6323 if (retval != ERROR_OK) {
6324 LOG_ERROR("Test pattern write failed");
6328 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6329 for (int size = 1; size <= 4; size *= 2) {
6330 for (int offset = 0; offset < 4; offset++) {
6331 uint32_t count = test_size / size;
6332 size_t host_bufsiz = (count + 2) * size + host_offset;
6333 uint8_t *read_ref = malloc(host_bufsiz);
6334 uint8_t *read_buf = malloc(host_bufsiz);
6336 for (size_t i = 0; i < host_bufsiz; i++) {
6337 read_ref[i] = rand();
6338 read_buf[i] = read_ref[i];
6340 command_print_sameline(CMD,
6341 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
6342 size, offset, host_offset ? "un" : "");
6344 struct duration bench;
6345 duration_start(&bench);
6347 retval = target_read_memory(target, wa->address + offset, size, count,
6348 read_buf + size + host_offset);
6350 duration_measure(&bench);
6352 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6353 command_print(CMD, "Unsupported alignment");
6355 } else if (retval != ERROR_OK) {
6356 command_print(CMD, "Memory read failed");
6360 /* replay on host */
6361 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
6364 int result = memcmp(read_ref, read_buf, host_bufsiz);
6366 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6367 duration_elapsed(&bench),
6368 duration_kbps(&bench, count * size));
6370 command_print(CMD, "Compare failed");
6371 binprint(CMD, "ref:", read_ref, host_bufsiz);
6372 binprint(CMD, "buf:", read_buf, host_bufsiz);
6385 target_free_working_area(target, wa);
6388 num_bytes = test_size + 4 + 4 + 4;
6390 retval = target_alloc_working_area(target, num_bytes, &wa);
6391 if (retval != ERROR_OK) {
6392 LOG_ERROR("Not enough working area");
6396 test_pattern = malloc(num_bytes);
6398 for (size_t i = 0; i < num_bytes; i++)
6399 test_pattern[i] = rand();
6401 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6402 for (int size = 1; size <= 4; size *= 2) {
6403 for (int offset = 0; offset < 4; offset++) {
6404 uint32_t count = test_size / size;
6405 size_t host_bufsiz = count * size + host_offset;
6406 uint8_t *read_ref = malloc(num_bytes);
6407 uint8_t *read_buf = malloc(num_bytes);
6408 uint8_t *write_buf = malloc(host_bufsiz);
6410 for (size_t i = 0; i < host_bufsiz; i++)
6411 write_buf[i] = rand();
6412 command_print_sameline(CMD,
6413 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
6414 size, offset, host_offset ? "un" : "");
6416 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6417 if (retval != ERROR_OK) {
6418 command_print(CMD, "Test pattern write failed");
6422 /* replay on host */
6423 memcpy(read_ref, test_pattern, num_bytes);
6424 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
6426 struct duration bench;
6427 duration_start(&bench);
6429 retval = target_write_memory(target, wa->address + size + offset, size, count,
6430 write_buf + host_offset);
6432 duration_measure(&bench);
6434 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6435 command_print(CMD, "Unsupported alignment");
6437 } else if (retval != ERROR_OK) {
6438 command_print(CMD, "Memory write failed");
6443 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
6444 if (retval != ERROR_OK) {
6445 command_print(CMD, "Test pattern write failed");
6450 int result = memcmp(read_ref, read_buf, num_bytes);
6452 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6453 duration_elapsed(&bench),
6454 duration_kbps(&bench, count * size));
6456 command_print(CMD, "Compare failed");
6457 binprint(CMD, "ref:", read_ref, num_bytes);
6458 binprint(CMD, "buf:", read_buf, num_bytes);
6470 target_free_working_area(target, wa);
6474 static const struct command_registration target_exec_command_handlers[] = {
6476 .name = "fast_load_image",
6477 .handler = handle_fast_load_image_command,
6478 .mode = COMMAND_ANY,
6479 .help = "Load image into server memory for later use by "
6480 "fast_load; primarily for profiling",
6481 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6482 "[min_address [max_length]]",
6485 .name = "fast_load",
6486 .handler = handle_fast_load_command,
6487 .mode = COMMAND_EXEC,
6488 .help = "loads active fast load image to current target "
6489 "- mainly for profiling purposes",
6494 .handler = handle_profile_command,
6495 .mode = COMMAND_EXEC,
6496 .usage = "seconds filename [start end]",
6497 .help = "profiling samples the CPU PC",
6499 /** @todo don't register virt2phys() unless target supports it */
6501 .name = "virt2phys",
6502 .handler = handle_virt2phys_command,
6503 .mode = COMMAND_ANY,
6504 .help = "translate a virtual address into a physical address",
6505 .usage = "virtual_address",
6509 .handler = handle_reg_command,
6510 .mode = COMMAND_EXEC,
6511 .help = "display (reread from target with \"force\") or set a register; "
6512 "with no arguments, displays all registers and their values",
6513 .usage = "[(register_number|register_name) [(value|'force')]]",
6517 .handler = handle_poll_command,
6518 .mode = COMMAND_EXEC,
6519 .help = "poll target state; or reconfigure background polling",
6520 .usage = "['on'|'off']",
6523 .name = "wait_halt",
6524 .handler = handle_wait_halt_command,
6525 .mode = COMMAND_EXEC,
6526 .help = "wait up to the specified number of milliseconds "
6527 "(default 5000) for a previously requested halt",
6528 .usage = "[milliseconds]",
6532 .handler = handle_halt_command,
6533 .mode = COMMAND_EXEC,
6534 .help = "request target to halt, then wait up to the specified "
6535 "number of milliseconds (default 5000) for it to complete",
6536 .usage = "[milliseconds]",
6540 .handler = handle_resume_command,
6541 .mode = COMMAND_EXEC,
6542 .help = "resume target execution from current PC or address",
6543 .usage = "[address]",
6547 .handler = handle_reset_command,
6548 .mode = COMMAND_EXEC,
6549 .usage = "[run|halt|init]",
6550 .help = "Reset all targets into the specified mode. "
6551 "Default reset mode is run, if not given.",
6554 .name = "soft_reset_halt",
6555 .handler = handle_soft_reset_halt_command,
6556 .mode = COMMAND_EXEC,
6558 .help = "halt the target and do a soft reset",
6562 .handler = handle_step_command,
6563 .mode = COMMAND_EXEC,
6564 .help = "step one instruction from current PC or address",
6565 .usage = "[address]",
6569 .handler = handle_md_command,
6570 .mode = COMMAND_EXEC,
6571 .help = "display memory double-words",
6572 .usage = "['phys'] address [count]",
6576 .handler = handle_md_command,
6577 .mode = COMMAND_EXEC,
6578 .help = "display memory words",
6579 .usage = "['phys'] address [count]",
6583 .handler = handle_md_command,
6584 .mode = COMMAND_EXEC,
6585 .help = "display memory half-words",
6586 .usage = "['phys'] address [count]",
6590 .handler = handle_md_command,
6591 .mode = COMMAND_EXEC,
6592 .help = "display memory bytes",
6593 .usage = "['phys'] address [count]",
6597 .handler = handle_mw_command,
6598 .mode = COMMAND_EXEC,
6599 .help = "write memory double-word",
6600 .usage = "['phys'] address value [count]",
6604 .handler = handle_mw_command,
6605 .mode = COMMAND_EXEC,
6606 .help = "write memory word",
6607 .usage = "['phys'] address value [count]",
6611 .handler = handle_mw_command,
6612 .mode = COMMAND_EXEC,
6613 .help = "write memory half-word",
6614 .usage = "['phys'] address value [count]",
6618 .handler = handle_mw_command,
6619 .mode = COMMAND_EXEC,
6620 .help = "write memory byte",
6621 .usage = "['phys'] address value [count]",
6625 .handler = handle_bp_command,
6626 .mode = COMMAND_EXEC,
6627 .help = "list or set hardware or software breakpoint",
6628 .usage = "[<address> [<asid>] <length> ['hw'|'hw_ctx']]",
6632 .handler = handle_rbp_command,
6633 .mode = COMMAND_EXEC,
6634 .help = "remove breakpoint",
6635 .usage = "'all' | address",
6639 .handler = handle_wp_command,
6640 .mode = COMMAND_EXEC,
6641 .help = "list (no params) or create watchpoints",
6642 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
6646 .handler = handle_rwp_command,
6647 .mode = COMMAND_EXEC,
6648 .help = "remove watchpoint",
6652 .name = "load_image",
6653 .handler = handle_load_image_command,
6654 .mode = COMMAND_EXEC,
6655 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6656 "[min_address] [max_length]",
6659 .name = "dump_image",
6660 .handler = handle_dump_image_command,
6661 .mode = COMMAND_EXEC,
6662 .usage = "filename address size",
6665 .name = "verify_image_checksum",
6666 .handler = handle_verify_image_checksum_command,
6667 .mode = COMMAND_EXEC,
6668 .usage = "filename [offset [type]]",
6671 .name = "verify_image",
6672 .handler = handle_verify_image_command,
6673 .mode = COMMAND_EXEC,
6674 .usage = "filename [offset [type]]",
6677 .name = "test_image",
6678 .handler = handle_test_image_command,
6679 .mode = COMMAND_EXEC,
6680 .usage = "filename [offset [type]]",
6683 .name = "mem2array",
6684 .mode = COMMAND_EXEC,
6685 .jim_handler = jim_mem2array,
6686 .help = "read 8/16/32 bit memory and return as a TCL array "
6687 "for script processing",
6688 .usage = "arrayname bitwidth address count",
6691 .name = "array2mem",
6692 .mode = COMMAND_EXEC,
6693 .jim_handler = jim_array2mem,
6694 .help = "convert a TCL array to memory locations "
6695 "and write the 8/16/32 bit values",
6696 .usage = "arrayname bitwidth address count",
6699 .name = "reset_nag",
6700 .handler = handle_target_reset_nag,
6701 .mode = COMMAND_ANY,
6702 .help = "Nag after each reset about options that could have been "
6703 "enabled to improve performance.",
6704 .usage = "['enable'|'disable']",
6708 .handler = handle_ps_command,
6709 .mode = COMMAND_EXEC,
6710 .help = "list all tasks",
6714 .name = "test_mem_access",
6715 .handler = handle_test_mem_access_command,
6716 .mode = COMMAND_EXEC,
6717 .help = "Test the target's memory access functions",
6721 COMMAND_REGISTRATION_DONE
6723 static int target_register_user_commands(struct command_context *cmd_ctx)
6725 int retval = ERROR_OK;
6726 retval = target_request_register_commands(cmd_ctx);
6727 if (retval != ERROR_OK)
6730 retval = trace_register_commands(cmd_ctx);
6731 if (retval != ERROR_OK)
6735 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);