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 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 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)
190 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
197 static const 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 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 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 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 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 static int target_profiling(struct target *target, uint32_t *samples,
1510 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1512 return target->type->profiling(target, samples, max_num_samples,
1513 num_samples, seconds);
1517 * Reset the @c examined flag for the given target.
1518 * Pure paranoia -- targets are zeroed on allocation.
1520 static void target_reset_examined(struct target *target)
1522 target->examined = false;
1525 static int handle_target(void *priv);
1527 static int target_init_one(struct command_context *cmd_ctx,
1528 struct target *target)
1530 target_reset_examined(target);
1532 struct target_type *type = target->type;
1533 if (type->examine == NULL)
1534 type->examine = default_examine;
1536 if (type->check_reset == NULL)
1537 type->check_reset = default_check_reset;
1539 assert(type->init_target != NULL);
1541 int retval = type->init_target(cmd_ctx, target);
1542 if (ERROR_OK != retval) {
1543 LOG_ERROR("target '%s' init failed", target_name(target));
1547 /* Sanity-check MMU support ... stub in what we must, to help
1548 * implement it in stages, but warn if we need to do so.
1551 if (type->virt2phys == NULL) {
1552 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1553 type->virt2phys = identity_virt2phys;
1556 /* Make sure no-MMU targets all behave the same: make no
1557 * distinction between physical and virtual addresses, and
1558 * ensure that virt2phys() is always an identity mapping.
1560 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1561 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1564 type->write_phys_memory = type->write_memory;
1565 type->read_phys_memory = type->read_memory;
1566 type->virt2phys = identity_virt2phys;
1569 if (target->type->read_buffer == NULL)
1570 target->type->read_buffer = target_read_buffer_default;
1572 if (target->type->write_buffer == NULL)
1573 target->type->write_buffer = target_write_buffer_default;
1575 if (target->type->get_gdb_fileio_info == NULL)
1576 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1578 if (target->type->gdb_fileio_end == NULL)
1579 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1581 if (target->type->profiling == NULL)
1582 target->type->profiling = target_profiling_default;
1587 static int target_init(struct command_context *cmd_ctx)
1589 struct target *target;
1592 for (target = all_targets; target; target = target->next) {
1593 retval = target_init_one(cmd_ctx, target);
1594 if (ERROR_OK != retval)
1601 retval = target_register_user_commands(cmd_ctx);
1602 if (ERROR_OK != retval)
1605 retval = target_register_timer_callback(&handle_target,
1606 polling_interval, TARGET_TIMER_TYPE_PERIODIC, cmd_ctx->interp);
1607 if (ERROR_OK != retval)
1613 COMMAND_HANDLER(handle_target_init_command)
1618 return ERROR_COMMAND_SYNTAX_ERROR;
1620 static bool target_initialized;
1621 if (target_initialized) {
1622 LOG_INFO("'target init' has already been called");
1625 target_initialized = true;
1627 retval = command_run_line(CMD_CTX, "init_targets");
1628 if (ERROR_OK != retval)
1631 retval = command_run_line(CMD_CTX, "init_target_events");
1632 if (ERROR_OK != retval)
1635 retval = command_run_line(CMD_CTX, "init_board");
1636 if (ERROR_OK != retval)
1639 LOG_DEBUG("Initializing targets...");
1640 return target_init(CMD_CTX);
1643 int target_register_event_callback(int (*callback)(struct target *target,
1644 enum target_event event, void *priv), void *priv)
1646 struct target_event_callback **callbacks_p = &target_event_callbacks;
1648 if (callback == NULL)
1649 return ERROR_COMMAND_SYNTAX_ERROR;
1652 while ((*callbacks_p)->next)
1653 callbacks_p = &((*callbacks_p)->next);
1654 callbacks_p = &((*callbacks_p)->next);
1657 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1658 (*callbacks_p)->callback = callback;
1659 (*callbacks_p)->priv = priv;
1660 (*callbacks_p)->next = NULL;
1665 int target_register_reset_callback(int (*callback)(struct target *target,
1666 enum target_reset_mode reset_mode, void *priv), void *priv)
1668 struct target_reset_callback *entry;
1670 if (callback == NULL)
1671 return ERROR_COMMAND_SYNTAX_ERROR;
1673 entry = malloc(sizeof(struct target_reset_callback));
1674 if (entry == NULL) {
1675 LOG_ERROR("error allocating buffer for reset callback entry");
1676 return ERROR_COMMAND_SYNTAX_ERROR;
1679 entry->callback = callback;
1681 list_add(&entry->list, &target_reset_callback_list);
1687 int target_register_trace_callback(int (*callback)(struct target *target,
1688 size_t len, uint8_t *data, void *priv), void *priv)
1690 struct target_trace_callback *entry;
1692 if (callback == NULL)
1693 return ERROR_COMMAND_SYNTAX_ERROR;
1695 entry = malloc(sizeof(struct target_trace_callback));
1696 if (entry == NULL) {
1697 LOG_ERROR("error allocating buffer for trace callback entry");
1698 return ERROR_COMMAND_SYNTAX_ERROR;
1701 entry->callback = callback;
1703 list_add(&entry->list, &target_trace_callback_list);
1709 int target_register_timer_callback(int (*callback)(void *priv),
1710 unsigned int time_ms, enum target_timer_type type, void *priv)
1712 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1714 if (callback == NULL)
1715 return ERROR_COMMAND_SYNTAX_ERROR;
1718 while ((*callbacks_p)->next)
1719 callbacks_p = &((*callbacks_p)->next);
1720 callbacks_p = &((*callbacks_p)->next);
1723 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1724 (*callbacks_p)->callback = callback;
1725 (*callbacks_p)->type = type;
1726 (*callbacks_p)->time_ms = time_ms;
1727 (*callbacks_p)->removed = false;
1729 gettimeofday(&(*callbacks_p)->when, NULL);
1730 timeval_add_time(&(*callbacks_p)->when, 0, time_ms * 1000);
1732 (*callbacks_p)->priv = priv;
1733 (*callbacks_p)->next = NULL;
1738 int target_unregister_event_callback(int (*callback)(struct target *target,
1739 enum target_event event, void *priv), void *priv)
1741 struct target_event_callback **p = &target_event_callbacks;
1742 struct target_event_callback *c = target_event_callbacks;
1744 if (callback == NULL)
1745 return ERROR_COMMAND_SYNTAX_ERROR;
1748 struct target_event_callback *next = c->next;
1749 if ((c->callback == callback) && (c->priv == priv)) {
1761 int target_unregister_reset_callback(int (*callback)(struct target *target,
1762 enum target_reset_mode reset_mode, void *priv), void *priv)
1764 struct target_reset_callback *entry;
1766 if (callback == NULL)
1767 return ERROR_COMMAND_SYNTAX_ERROR;
1769 list_for_each_entry(entry, &target_reset_callback_list, list) {
1770 if (entry->callback == callback && entry->priv == priv) {
1771 list_del(&entry->list);
1780 int target_unregister_trace_callback(int (*callback)(struct target *target,
1781 size_t len, uint8_t *data, void *priv), void *priv)
1783 struct target_trace_callback *entry;
1785 if (callback == NULL)
1786 return ERROR_COMMAND_SYNTAX_ERROR;
1788 list_for_each_entry(entry, &target_trace_callback_list, list) {
1789 if (entry->callback == callback && entry->priv == priv) {
1790 list_del(&entry->list);
1799 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1801 if (callback == NULL)
1802 return ERROR_COMMAND_SYNTAX_ERROR;
1804 for (struct target_timer_callback *c = target_timer_callbacks;
1806 if ((c->callback == callback) && (c->priv == priv)) {
1815 int target_call_event_callbacks(struct target *target, enum target_event event)
1817 struct target_event_callback *callback = target_event_callbacks;
1818 struct target_event_callback *next_callback;
1820 if (event == TARGET_EVENT_HALTED) {
1821 /* execute early halted first */
1822 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1825 LOG_DEBUG("target event %i (%s) for core %s", event,
1826 Jim_Nvp_value2name_simple(nvp_target_event, event)->name,
1827 target_name(target));
1829 target_handle_event(target, event);
1832 next_callback = callback->next;
1833 callback->callback(target, event, callback->priv);
1834 callback = next_callback;
1840 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1842 struct target_reset_callback *callback;
1844 LOG_DEBUG("target reset %i (%s)", reset_mode,
1845 Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name);
1847 list_for_each_entry(callback, &target_reset_callback_list, list)
1848 callback->callback(target, reset_mode, callback->priv);
1853 int target_call_trace_callbacks(struct target *target, size_t len, uint8_t *data)
1855 struct target_trace_callback *callback;
1857 list_for_each_entry(callback, &target_trace_callback_list, list)
1858 callback->callback(target, len, data, callback->priv);
1863 static int target_timer_callback_periodic_restart(
1864 struct target_timer_callback *cb, struct timeval *now)
1867 timeval_add_time(&cb->when, 0, cb->time_ms * 1000L);
1871 static int target_call_timer_callback(struct target_timer_callback *cb,
1872 struct timeval *now)
1874 cb->callback(cb->priv);
1876 if (cb->type == TARGET_TIMER_TYPE_PERIODIC)
1877 return target_timer_callback_periodic_restart(cb, now);
1879 return target_unregister_timer_callback(cb->callback, cb->priv);
1882 static int target_call_timer_callbacks_check_time(int checktime)
1884 static bool callback_processing;
1886 /* Do not allow nesting */
1887 if (callback_processing)
1890 callback_processing = true;
1895 gettimeofday(&now, NULL);
1897 /* Store an address of the place containing a pointer to the
1898 * next item; initially, that's a standalone "root of the
1899 * list" variable. */
1900 struct target_timer_callback **callback = &target_timer_callbacks;
1901 while (callback && *callback) {
1902 if ((*callback)->removed) {
1903 struct target_timer_callback *p = *callback;
1904 *callback = (*callback)->next;
1909 bool call_it = (*callback)->callback &&
1910 ((!checktime && (*callback)->type == TARGET_TIMER_TYPE_PERIODIC) ||
1911 timeval_compare(&now, &(*callback)->when) >= 0);
1914 target_call_timer_callback(*callback, &now);
1916 callback = &(*callback)->next;
1919 callback_processing = false;
1923 int target_call_timer_callbacks(void)
1925 return target_call_timer_callbacks_check_time(1);
1928 /* invoke periodic callbacks immediately */
1929 int target_call_timer_callbacks_now(void)
1931 return target_call_timer_callbacks_check_time(0);
1934 /* Prints the working area layout for debug purposes */
1935 static void print_wa_layout(struct target *target)
1937 struct working_area *c = target->working_areas;
1940 LOG_DEBUG("%c%c " TARGET_ADDR_FMT "-" TARGET_ADDR_FMT " (%" PRIu32 " bytes)",
1941 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1942 c->address, c->address + c->size - 1, c->size);
1947 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1948 static void target_split_working_area(struct working_area *area, uint32_t size)
1950 assert(area->free); /* Shouldn't split an allocated area */
1951 assert(size <= area->size); /* Caller should guarantee this */
1953 /* Split only if not already the right size */
1954 if (size < area->size) {
1955 struct working_area *new_wa = malloc(sizeof(*new_wa));
1960 new_wa->next = area->next;
1961 new_wa->size = area->size - size;
1962 new_wa->address = area->address + size;
1963 new_wa->backup = NULL;
1964 new_wa->user = NULL;
1965 new_wa->free = true;
1967 area->next = new_wa;
1970 /* If backup memory was allocated to this area, it has the wrong size
1971 * now so free it and it will be reallocated if/when needed */
1973 area->backup = NULL;
1977 /* Merge all adjacent free areas into one */
1978 static void target_merge_working_areas(struct target *target)
1980 struct working_area *c = target->working_areas;
1982 while (c && c->next) {
1983 assert(c->next->address == c->address + c->size); /* This is an invariant */
1985 /* Find two adjacent free areas */
1986 if (c->free && c->next->free) {
1987 /* Merge the last into the first */
1988 c->size += c->next->size;
1990 /* Remove the last */
1991 struct working_area *to_be_freed = c->next;
1992 c->next = c->next->next;
1993 free(to_be_freed->backup);
1996 /* If backup memory was allocated to the remaining area, it's has
1997 * the wrong size now */
2006 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
2008 /* Reevaluate working area address based on MMU state*/
2009 if (target->working_areas == NULL) {
2013 retval = target->type->mmu(target, &enabled);
2014 if (retval != ERROR_OK)
2018 if (target->working_area_phys_spec) {
2019 LOG_DEBUG("MMU disabled, using physical "
2020 "address for working memory " TARGET_ADDR_FMT,
2021 target->working_area_phys);
2022 target->working_area = target->working_area_phys;
2024 LOG_ERROR("No working memory available. "
2025 "Specify -work-area-phys to target.");
2026 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2029 if (target->working_area_virt_spec) {
2030 LOG_DEBUG("MMU enabled, using virtual "
2031 "address for working memory " TARGET_ADDR_FMT,
2032 target->working_area_virt);
2033 target->working_area = target->working_area_virt;
2035 LOG_ERROR("No working memory available. "
2036 "Specify -work-area-virt to target.");
2037 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2041 /* Set up initial working area on first call */
2042 struct working_area *new_wa = malloc(sizeof(*new_wa));
2044 new_wa->next = NULL;
2045 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
2046 new_wa->address = target->working_area;
2047 new_wa->backup = NULL;
2048 new_wa->user = NULL;
2049 new_wa->free = true;
2052 target->working_areas = new_wa;
2055 /* only allocate multiples of 4 byte */
2057 size = (size + 3) & (~3UL);
2059 struct working_area *c = target->working_areas;
2061 /* Find the first large enough working area */
2063 if (c->free && c->size >= size)
2069 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2071 /* Split the working area into the requested size */
2072 target_split_working_area(c, size);
2074 LOG_DEBUG("allocated new working area of %" PRIu32 " bytes at address " TARGET_ADDR_FMT,
2077 if (target->backup_working_area) {
2078 if (c->backup == NULL) {
2079 c->backup = malloc(c->size);
2080 if (c->backup == NULL)
2084 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
2085 if (retval != ERROR_OK)
2089 /* mark as used, and return the new (reused) area */
2096 print_wa_layout(target);
2101 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
2105 retval = target_alloc_working_area_try(target, size, area);
2106 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
2107 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
2112 static int target_restore_working_area(struct target *target, struct working_area *area)
2114 int retval = ERROR_OK;
2116 if (target->backup_working_area && area->backup != NULL) {
2117 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
2118 if (retval != ERROR_OK)
2119 LOG_ERROR("failed to restore %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2120 area->size, area->address);
2126 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
2127 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
2129 int retval = ERROR_OK;
2135 retval = target_restore_working_area(target, area);
2136 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
2137 if (retval != ERROR_OK)
2143 LOG_DEBUG("freed %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2144 area->size, area->address);
2146 /* mark user pointer invalid */
2147 /* TODO: Is this really safe? It points to some previous caller's memory.
2148 * How could we know that the area pointer is still in that place and not
2149 * some other vital data? What's the purpose of this, anyway? */
2153 target_merge_working_areas(target);
2155 print_wa_layout(target);
2160 int target_free_working_area(struct target *target, struct working_area *area)
2162 return target_free_working_area_restore(target, area, 1);
2165 /* free resources and restore memory, if restoring memory fails,
2166 * free up resources anyway
2168 static void target_free_all_working_areas_restore(struct target *target, int restore)
2170 struct working_area *c = target->working_areas;
2172 LOG_DEBUG("freeing all working areas");
2174 /* Loop through all areas, restoring the allocated ones and marking them as free */
2178 target_restore_working_area(target, c);
2180 *c->user = NULL; /* Same as above */
2186 /* Run a merge pass to combine all areas into one */
2187 target_merge_working_areas(target);
2189 print_wa_layout(target);
2192 void target_free_all_working_areas(struct target *target)
2194 target_free_all_working_areas_restore(target, 1);
2196 /* Now we have none or only one working area marked as free */
2197 if (target->working_areas) {
2198 /* Free the last one to allow on-the-fly moving and resizing */
2199 free(target->working_areas->backup);
2200 free(target->working_areas);
2201 target->working_areas = NULL;
2205 /* Find the largest number of bytes that can be allocated */
2206 uint32_t target_get_working_area_avail(struct target *target)
2208 struct working_area *c = target->working_areas;
2209 uint32_t max_size = 0;
2212 return target->working_area_size;
2215 if (c->free && max_size < c->size)
2224 static void target_destroy(struct target *target)
2226 if (target->type->deinit_target)
2227 target->type->deinit_target(target);
2229 free(target->semihosting);
2231 jtag_unregister_event_callback(jtag_enable_callback, target);
2233 struct target_event_action *teap = target->event_action;
2235 struct target_event_action *next = teap->next;
2236 Jim_DecrRefCount(teap->interp, teap->body);
2241 target_free_all_working_areas(target);
2243 /* release the targets SMP list */
2245 struct target_list *head = target->head;
2246 while (head != NULL) {
2247 struct target_list *pos = head->next;
2248 head->target->smp = 0;
2255 rtos_destroy(target);
2257 free(target->gdb_port_override);
2259 free(target->trace_info);
2260 free(target->fileio_info);
2261 free(target->cmd_name);
2265 void target_quit(void)
2267 struct target_event_callback *pe = target_event_callbacks;
2269 struct target_event_callback *t = pe->next;
2273 target_event_callbacks = NULL;
2275 struct target_timer_callback *pt = target_timer_callbacks;
2277 struct target_timer_callback *t = pt->next;
2281 target_timer_callbacks = NULL;
2283 for (struct target *target = all_targets; target;) {
2287 target_destroy(target);
2294 int target_arch_state(struct target *target)
2297 if (target == NULL) {
2298 LOG_WARNING("No target has been configured");
2302 if (target->state != TARGET_HALTED)
2305 retval = target->type->arch_state(target);
2309 static int target_get_gdb_fileio_info_default(struct target *target,
2310 struct gdb_fileio_info *fileio_info)
2312 /* If target does not support semi-hosting function, target
2313 has no need to provide .get_gdb_fileio_info callback.
2314 It just return ERROR_FAIL and gdb_server will return "Txx"
2315 as target halted every time. */
2319 static int target_gdb_fileio_end_default(struct target *target,
2320 int retcode, int fileio_errno, bool ctrl_c)
2325 int target_profiling_default(struct target *target, uint32_t *samples,
2326 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
2328 struct timeval timeout, now;
2330 gettimeofday(&timeout, NULL);
2331 timeval_add_time(&timeout, seconds, 0);
2333 LOG_INFO("Starting profiling. Halting and resuming the"
2334 " target as often as we can...");
2336 uint32_t sample_count = 0;
2337 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2338 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
2340 int retval = ERROR_OK;
2342 target_poll(target);
2343 if (target->state == TARGET_HALTED) {
2344 uint32_t t = buf_get_u32(reg->value, 0, 32);
2345 samples[sample_count++] = t;
2346 /* current pc, addr = 0, do not handle breakpoints, not debugging */
2347 retval = target_resume(target, 1, 0, 0, 0);
2348 target_poll(target);
2349 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2350 } else if (target->state == TARGET_RUNNING) {
2351 /* We want to quickly sample the PC. */
2352 retval = target_halt(target);
2354 LOG_INFO("Target not halted or running");
2359 if (retval != ERROR_OK)
2362 gettimeofday(&now, NULL);
2363 if ((sample_count >= max_num_samples) || timeval_compare(&now, &timeout) >= 0) {
2364 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2369 *num_samples = sample_count;
2373 /* Single aligned words are guaranteed to use 16 or 32 bit access
2374 * mode respectively, otherwise data is handled as quickly as
2377 int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
2379 LOG_DEBUG("writing buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2382 if (!target_was_examined(target)) {
2383 LOG_ERROR("Target not examined yet");
2390 if ((address + size - 1) < address) {
2391 /* GDB can request this when e.g. PC is 0xfffffffc */
2392 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2398 return target->type->write_buffer(target, address, size, buffer);
2401 static int target_write_buffer_default(struct target *target,
2402 target_addr_t address, uint32_t count, const uint8_t *buffer)
2406 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2407 * will have something to do with the size we leave to it. */
2408 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2409 if (address & size) {
2410 int retval = target_write_memory(target, address, size, 1, buffer);
2411 if (retval != ERROR_OK)
2419 /* Write the data with as large access size as possible. */
2420 for (; size > 0; size /= 2) {
2421 uint32_t aligned = count - count % size;
2423 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2424 if (retval != ERROR_OK)
2435 /* Single aligned words are guaranteed to use 16 or 32 bit access
2436 * mode respectively, otherwise data is handled as quickly as
2439 int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
2441 LOG_DEBUG("reading buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2444 if (!target_was_examined(target)) {
2445 LOG_ERROR("Target not examined yet");
2452 if ((address + size - 1) < address) {
2453 /* GDB can request this when e.g. PC is 0xfffffffc */
2454 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2460 return target->type->read_buffer(target, address, size, buffer);
2463 static int target_read_buffer_default(struct target *target, target_addr_t address, uint32_t count, uint8_t *buffer)
2467 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2468 * will have something to do with the size we leave to it. */
2469 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2470 if (address & size) {
2471 int retval = target_read_memory(target, address, size, 1, buffer);
2472 if (retval != ERROR_OK)
2480 /* Read the data with as large access size as possible. */
2481 for (; size > 0; size /= 2) {
2482 uint32_t aligned = count - count % size;
2484 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2485 if (retval != ERROR_OK)
2496 int target_checksum_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t *crc)
2501 uint32_t checksum = 0;
2502 if (!target_was_examined(target)) {
2503 LOG_ERROR("Target not examined yet");
2507 retval = target->type->checksum_memory(target, address, size, &checksum);
2508 if (retval != ERROR_OK) {
2509 buffer = malloc(size);
2510 if (buffer == NULL) {
2511 LOG_ERROR("error allocating buffer for section (%" PRIu32 " bytes)", size);
2512 return ERROR_COMMAND_SYNTAX_ERROR;
2514 retval = target_read_buffer(target, address, size, buffer);
2515 if (retval != ERROR_OK) {
2520 /* convert to target endianness */
2521 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2522 uint32_t target_data;
2523 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2524 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2527 retval = image_calculate_checksum(buffer, size, &checksum);
2536 int target_blank_check_memory(struct target *target,
2537 struct target_memory_check_block *blocks, int num_blocks,
2538 uint8_t erased_value)
2540 if (!target_was_examined(target)) {
2541 LOG_ERROR("Target not examined yet");
2545 if (target->type->blank_check_memory == NULL)
2546 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2548 return target->type->blank_check_memory(target, blocks, num_blocks, erased_value);
2551 int target_read_u64(struct target *target, target_addr_t address, uint64_t *value)
2553 uint8_t value_buf[8];
2554 if (!target_was_examined(target)) {
2555 LOG_ERROR("Target not examined yet");
2559 int retval = target_read_memory(target, address, 8, 1, value_buf);
2561 if (retval == ERROR_OK) {
2562 *value = target_buffer_get_u64(target, value_buf);
2563 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2568 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2575 int target_read_u32(struct target *target, target_addr_t address, uint32_t *value)
2577 uint8_t value_buf[4];
2578 if (!target_was_examined(target)) {
2579 LOG_ERROR("Target not examined yet");
2583 int retval = target_read_memory(target, address, 4, 1, value_buf);
2585 if (retval == ERROR_OK) {
2586 *value = target_buffer_get_u32(target, value_buf);
2587 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2592 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2599 int target_read_u16(struct target *target, target_addr_t address, uint16_t *value)
2601 uint8_t value_buf[2];
2602 if (!target_was_examined(target)) {
2603 LOG_ERROR("Target not examined yet");
2607 int retval = target_read_memory(target, address, 2, 1, value_buf);
2609 if (retval == ERROR_OK) {
2610 *value = target_buffer_get_u16(target, value_buf);
2611 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%4.4" PRIx16,
2616 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2623 int target_read_u8(struct target *target, target_addr_t address, uint8_t *value)
2625 if (!target_was_examined(target)) {
2626 LOG_ERROR("Target not examined yet");
2630 int retval = target_read_memory(target, address, 1, 1, value);
2632 if (retval == ERROR_OK) {
2633 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2638 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2645 int target_write_u64(struct target *target, target_addr_t address, uint64_t value)
2648 uint8_t value_buf[8];
2649 if (!target_was_examined(target)) {
2650 LOG_ERROR("Target not examined yet");
2654 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2658 target_buffer_set_u64(target, value_buf, value);
2659 retval = target_write_memory(target, address, 8, 1, value_buf);
2660 if (retval != ERROR_OK)
2661 LOG_DEBUG("failed: %i", retval);
2666 int target_write_u32(struct target *target, target_addr_t address, uint32_t value)
2669 uint8_t value_buf[4];
2670 if (!target_was_examined(target)) {
2671 LOG_ERROR("Target not examined yet");
2675 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2679 target_buffer_set_u32(target, value_buf, value);
2680 retval = target_write_memory(target, address, 4, 1, value_buf);
2681 if (retval != ERROR_OK)
2682 LOG_DEBUG("failed: %i", retval);
2687 int target_write_u16(struct target *target, target_addr_t address, uint16_t value)
2690 uint8_t value_buf[2];
2691 if (!target_was_examined(target)) {
2692 LOG_ERROR("Target not examined yet");
2696 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2700 target_buffer_set_u16(target, value_buf, value);
2701 retval = target_write_memory(target, address, 2, 1, value_buf);
2702 if (retval != ERROR_OK)
2703 LOG_DEBUG("failed: %i", retval);
2708 int target_write_u8(struct target *target, target_addr_t address, uint8_t value)
2711 if (!target_was_examined(target)) {
2712 LOG_ERROR("Target not examined yet");
2716 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2719 retval = target_write_memory(target, address, 1, 1, &value);
2720 if (retval != ERROR_OK)
2721 LOG_DEBUG("failed: %i", retval);
2726 int target_write_phys_u64(struct target *target, target_addr_t address, uint64_t value)
2729 uint8_t value_buf[8];
2730 if (!target_was_examined(target)) {
2731 LOG_ERROR("Target not examined yet");
2735 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2739 target_buffer_set_u64(target, value_buf, value);
2740 retval = target_write_phys_memory(target, address, 8, 1, value_buf);
2741 if (retval != ERROR_OK)
2742 LOG_DEBUG("failed: %i", retval);
2747 int target_write_phys_u32(struct target *target, target_addr_t address, uint32_t value)
2750 uint8_t value_buf[4];
2751 if (!target_was_examined(target)) {
2752 LOG_ERROR("Target not examined yet");
2756 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2760 target_buffer_set_u32(target, value_buf, value);
2761 retval = target_write_phys_memory(target, address, 4, 1, value_buf);
2762 if (retval != ERROR_OK)
2763 LOG_DEBUG("failed: %i", retval);
2768 int target_write_phys_u16(struct target *target, target_addr_t address, uint16_t value)
2771 uint8_t value_buf[2];
2772 if (!target_was_examined(target)) {
2773 LOG_ERROR("Target not examined yet");
2777 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2781 target_buffer_set_u16(target, value_buf, value);
2782 retval = target_write_phys_memory(target, address, 2, 1, value_buf);
2783 if (retval != ERROR_OK)
2784 LOG_DEBUG("failed: %i", retval);
2789 int target_write_phys_u8(struct target *target, target_addr_t address, uint8_t value)
2792 if (!target_was_examined(target)) {
2793 LOG_ERROR("Target not examined yet");
2797 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2800 retval = target_write_phys_memory(target, address, 1, 1, &value);
2801 if (retval != ERROR_OK)
2802 LOG_DEBUG("failed: %i", retval);
2807 static int find_target(struct command_invocation *cmd, const char *name)
2809 struct target *target = get_target(name);
2810 if (target == NULL) {
2811 command_print(cmd, "Target: %s is unknown, try one of:\n", name);
2814 if (!target->tap->enabled) {
2815 command_print(cmd, "Target: TAP %s is disabled, "
2816 "can't be the current target\n",
2817 target->tap->dotted_name);
2821 cmd->ctx->current_target = target;
2822 if (cmd->ctx->current_target_override)
2823 cmd->ctx->current_target_override = target;
2829 COMMAND_HANDLER(handle_targets_command)
2831 int retval = ERROR_OK;
2832 if (CMD_ARGC == 1) {
2833 retval = find_target(CMD, CMD_ARGV[0]);
2834 if (retval == ERROR_OK) {
2840 struct target *target = all_targets;
2841 command_print(CMD, " TargetName Type Endian TapName State ");
2842 command_print(CMD, "-- ------------------ ---------- ------ ------------------ ------------");
2847 if (target->tap->enabled)
2848 state = target_state_name(target);
2850 state = "tap-disabled";
2852 if (CMD_CTX->current_target == target)
2855 /* keep columns lined up to match the headers above */
2857 "%2d%c %-18s %-10s %-6s %-18s %s",
2858 target->target_number,
2860 target_name(target),
2861 target_type_name(target),
2862 Jim_Nvp_value2name_simple(nvp_target_endian,
2863 target->endianness)->name,
2864 target->tap->dotted_name,
2866 target = target->next;
2872 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2874 static int powerDropout;
2875 static int srstAsserted;
2877 static int runPowerRestore;
2878 static int runPowerDropout;
2879 static int runSrstAsserted;
2880 static int runSrstDeasserted;
2882 static int sense_handler(void)
2884 static int prevSrstAsserted;
2885 static int prevPowerdropout;
2887 int retval = jtag_power_dropout(&powerDropout);
2888 if (retval != ERROR_OK)
2892 powerRestored = prevPowerdropout && !powerDropout;
2894 runPowerRestore = 1;
2896 int64_t current = timeval_ms();
2897 static int64_t lastPower;
2898 bool waitMore = lastPower + 2000 > current;
2899 if (powerDropout && !waitMore) {
2900 runPowerDropout = 1;
2901 lastPower = current;
2904 retval = jtag_srst_asserted(&srstAsserted);
2905 if (retval != ERROR_OK)
2909 srstDeasserted = prevSrstAsserted && !srstAsserted;
2911 static int64_t lastSrst;
2912 waitMore = lastSrst + 2000 > current;
2913 if (srstDeasserted && !waitMore) {
2914 runSrstDeasserted = 1;
2918 if (!prevSrstAsserted && srstAsserted)
2919 runSrstAsserted = 1;
2921 prevSrstAsserted = srstAsserted;
2922 prevPowerdropout = powerDropout;
2924 if (srstDeasserted || powerRestored) {
2925 /* Other than logging the event we can't do anything here.
2926 * Issuing a reset is a particularly bad idea as we might
2927 * be inside a reset already.
2934 /* process target state changes */
2935 static int handle_target(void *priv)
2937 Jim_Interp *interp = (Jim_Interp *)priv;
2938 int retval = ERROR_OK;
2940 if (!is_jtag_poll_safe()) {
2941 /* polling is disabled currently */
2945 /* we do not want to recurse here... */
2946 static int recursive;
2950 /* danger! running these procedures can trigger srst assertions and power dropouts.
2951 * We need to avoid an infinite loop/recursion here and we do that by
2952 * clearing the flags after running these events.
2954 int did_something = 0;
2955 if (runSrstAsserted) {
2956 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2957 Jim_Eval(interp, "srst_asserted");
2960 if (runSrstDeasserted) {
2961 Jim_Eval(interp, "srst_deasserted");
2964 if (runPowerDropout) {
2965 LOG_INFO("Power dropout detected, running power_dropout proc.");
2966 Jim_Eval(interp, "power_dropout");
2969 if (runPowerRestore) {
2970 Jim_Eval(interp, "power_restore");
2974 if (did_something) {
2975 /* clear detect flags */
2979 /* clear action flags */
2981 runSrstAsserted = 0;
2982 runSrstDeasserted = 0;
2983 runPowerRestore = 0;
2984 runPowerDropout = 0;
2989 /* Poll targets for state changes unless that's globally disabled.
2990 * Skip targets that are currently disabled.
2992 for (struct target *target = all_targets;
2993 is_jtag_poll_safe() && target;
2994 target = target->next) {
2996 if (!target_was_examined(target))
2999 if (!target->tap->enabled)
3002 if (target->backoff.times > target->backoff.count) {
3003 /* do not poll this time as we failed previously */
3004 target->backoff.count++;
3007 target->backoff.count = 0;
3009 /* only poll target if we've got power and srst isn't asserted */
3010 if (!powerDropout && !srstAsserted) {
3011 /* polling may fail silently until the target has been examined */
3012 retval = target_poll(target);
3013 if (retval != ERROR_OK) {
3014 /* 100ms polling interval. Increase interval between polling up to 5000ms */
3015 if (target->backoff.times * polling_interval < 5000) {
3016 target->backoff.times *= 2;
3017 target->backoff.times++;
3020 /* Tell GDB to halt the debugger. This allows the user to
3021 * run monitor commands to handle the situation.
3023 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3025 if (target->backoff.times > 0) {
3026 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
3027 target_reset_examined(target);
3028 retval = target_examine_one(target);
3029 /* Target examination could have failed due to unstable connection,
3030 * but we set the examined flag anyway to repoll it later */
3031 if (retval != ERROR_OK) {
3032 target->examined = true;
3033 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
3034 target->backoff.times * polling_interval);
3039 /* Since we succeeded, we reset backoff count */
3040 target->backoff.times = 0;
3047 COMMAND_HANDLER(handle_reg_command)
3049 struct target *target;
3050 struct reg *reg = NULL;
3056 target = get_current_target(CMD_CTX);
3058 /* list all available registers for the current target */
3059 if (CMD_ARGC == 0) {
3060 struct reg_cache *cache = target->reg_cache;
3066 command_print(CMD, "===== %s", cache->name);
3068 for (i = 0, reg = cache->reg_list;
3069 i < cache->num_regs;
3070 i++, reg++, count++) {
3071 if (reg->exist == false || reg->hidden)
3073 /* only print cached values if they are valid */
3075 value = buf_to_hex_str(reg->value,
3078 "(%i) %s (/%" PRIu32 "): 0x%s%s",
3086 command_print(CMD, "(%i) %s (/%" PRIu32 ")",
3091 cache = cache->next;
3097 /* access a single register by its ordinal number */
3098 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
3100 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
3102 struct reg_cache *cache = target->reg_cache;
3106 for (i = 0; i < cache->num_regs; i++) {
3107 if (count++ == num) {
3108 reg = &cache->reg_list[i];
3114 cache = cache->next;
3118 command_print(CMD, "%i is out of bounds, the current target "
3119 "has only %i registers (0 - %i)", num, count, count - 1);
3123 /* access a single register by its name */
3124 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
3130 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
3135 /* display a register */
3136 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
3137 && (CMD_ARGV[1][0] <= '9')))) {
3138 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
3141 if (reg->valid == 0)
3142 reg->type->get(reg);
3143 value = buf_to_hex_str(reg->value, reg->size);
3144 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3149 /* set register value */
3150 if (CMD_ARGC == 2) {
3151 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
3154 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
3156 reg->type->set(reg, buf);
3158 value = buf_to_hex_str(reg->value, reg->size);
3159 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3167 return ERROR_COMMAND_SYNTAX_ERROR;
3170 command_print(CMD, "register %s not found in current target", CMD_ARGV[0]);
3174 COMMAND_HANDLER(handle_poll_command)
3176 int retval = ERROR_OK;
3177 struct target *target = get_current_target(CMD_CTX);
3179 if (CMD_ARGC == 0) {
3180 command_print(CMD, "background polling: %s",
3181 jtag_poll_get_enabled() ? "on" : "off");
3182 command_print(CMD, "TAP: %s (%s)",
3183 target->tap->dotted_name,
3184 target->tap->enabled ? "enabled" : "disabled");
3185 if (!target->tap->enabled)
3187 retval = target_poll(target);
3188 if (retval != ERROR_OK)
3190 retval = target_arch_state(target);
3191 if (retval != ERROR_OK)
3193 } else if (CMD_ARGC == 1) {
3195 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
3196 jtag_poll_set_enabled(enable);
3198 return ERROR_COMMAND_SYNTAX_ERROR;
3203 COMMAND_HANDLER(handle_wait_halt_command)
3206 return ERROR_COMMAND_SYNTAX_ERROR;
3208 unsigned ms = DEFAULT_HALT_TIMEOUT;
3209 if (1 == CMD_ARGC) {
3210 int retval = parse_uint(CMD_ARGV[0], &ms);
3211 if (ERROR_OK != retval)
3212 return ERROR_COMMAND_SYNTAX_ERROR;
3215 struct target *target = get_current_target(CMD_CTX);
3216 return target_wait_state(target, TARGET_HALTED, ms);
3219 /* wait for target state to change. The trick here is to have a low
3220 * latency for short waits and not to suck up all the CPU time
3223 * After 500ms, keep_alive() is invoked
3225 int target_wait_state(struct target *target, enum target_state state, int ms)
3228 int64_t then = 0, cur;
3232 retval = target_poll(target);
3233 if (retval != ERROR_OK)
3235 if (target->state == state)
3240 then = timeval_ms();
3241 LOG_DEBUG("waiting for target %s...",
3242 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
3248 if ((cur-then) > ms) {
3249 LOG_ERROR("timed out while waiting for target %s",
3250 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
3258 COMMAND_HANDLER(handle_halt_command)
3262 struct target *target = get_current_target(CMD_CTX);
3264 target->verbose_halt_msg = true;
3266 int retval = target_halt(target);
3267 if (ERROR_OK != retval)
3270 if (CMD_ARGC == 1) {
3271 unsigned wait_local;
3272 retval = parse_uint(CMD_ARGV[0], &wait_local);
3273 if (ERROR_OK != retval)
3274 return ERROR_COMMAND_SYNTAX_ERROR;
3279 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
3282 COMMAND_HANDLER(handle_soft_reset_halt_command)
3284 struct target *target = get_current_target(CMD_CTX);
3286 LOG_USER("requesting target halt and executing a soft reset");
3288 target_soft_reset_halt(target);
3293 COMMAND_HANDLER(handle_reset_command)
3296 return ERROR_COMMAND_SYNTAX_ERROR;
3298 enum target_reset_mode reset_mode = RESET_RUN;
3299 if (CMD_ARGC == 1) {
3301 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
3302 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
3303 return ERROR_COMMAND_SYNTAX_ERROR;
3304 reset_mode = n->value;
3307 /* reset *all* targets */
3308 return target_process_reset(CMD, reset_mode);
3312 COMMAND_HANDLER(handle_resume_command)
3316 return ERROR_COMMAND_SYNTAX_ERROR;
3318 struct target *target = get_current_target(CMD_CTX);
3320 /* with no CMD_ARGV, resume from current pc, addr = 0,
3321 * with one arguments, addr = CMD_ARGV[0],
3322 * handle breakpoints, not debugging */
3323 target_addr_t addr = 0;
3324 if (CMD_ARGC == 1) {
3325 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3329 return target_resume(target, current, addr, 1, 0);
3332 COMMAND_HANDLER(handle_step_command)
3335 return ERROR_COMMAND_SYNTAX_ERROR;
3339 /* with no CMD_ARGV, step from current pc, addr = 0,
3340 * with one argument addr = CMD_ARGV[0],
3341 * handle breakpoints, debugging */
3342 target_addr_t addr = 0;
3344 if (CMD_ARGC == 1) {
3345 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3349 struct target *target = get_current_target(CMD_CTX);
3351 return target_step(target, current_pc, addr, 1);
3354 void target_handle_md_output(struct command_invocation *cmd,
3355 struct target *target, target_addr_t address, unsigned size,
3356 unsigned count, const uint8_t *buffer)
3358 const unsigned line_bytecnt = 32;
3359 unsigned line_modulo = line_bytecnt / size;
3361 char output[line_bytecnt * 4 + 1];
3362 unsigned output_len = 0;
3364 const char *value_fmt;
3367 value_fmt = "%16.16"PRIx64" ";
3370 value_fmt = "%8.8"PRIx64" ";
3373 value_fmt = "%4.4"PRIx64" ";
3376 value_fmt = "%2.2"PRIx64" ";
3379 /* "can't happen", caller checked */
3380 LOG_ERROR("invalid memory read size: %u", size);
3384 for (unsigned i = 0; i < count; i++) {
3385 if (i % line_modulo == 0) {
3386 output_len += snprintf(output + output_len,
3387 sizeof(output) - output_len,
3388 TARGET_ADDR_FMT ": ",
3389 (address + (i * size)));
3393 const uint8_t *value_ptr = buffer + i * size;
3396 value = target_buffer_get_u64(target, value_ptr);
3399 value = target_buffer_get_u32(target, value_ptr);
3402 value = target_buffer_get_u16(target, value_ptr);
3407 output_len += snprintf(output + output_len,
3408 sizeof(output) - output_len,
3411 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
3412 command_print(cmd, "%s", output);
3418 COMMAND_HANDLER(handle_md_command)
3421 return ERROR_COMMAND_SYNTAX_ERROR;
3424 switch (CMD_NAME[2]) {
3438 return ERROR_COMMAND_SYNTAX_ERROR;
3441 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3442 int (*fn)(struct target *target,
3443 target_addr_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
3447 fn = target_read_phys_memory;
3449 fn = target_read_memory;
3450 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
3451 return ERROR_COMMAND_SYNTAX_ERROR;
3453 target_addr_t address;
3454 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3458 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3460 uint8_t *buffer = calloc(count, size);
3461 if (buffer == NULL) {
3462 LOG_ERROR("Failed to allocate md read buffer");
3466 struct target *target = get_current_target(CMD_CTX);
3467 int retval = fn(target, address, size, count, buffer);
3468 if (ERROR_OK == retval)
3469 target_handle_md_output(CMD, target, address, size, count, buffer);
3476 typedef int (*target_write_fn)(struct target *target,
3477 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3479 static int target_fill_mem(struct target *target,
3480 target_addr_t address,
3488 /* We have to write in reasonably large chunks to be able
3489 * to fill large memory areas with any sane speed */
3490 const unsigned chunk_size = 16384;
3491 uint8_t *target_buf = malloc(chunk_size * data_size);
3492 if (target_buf == NULL) {
3493 LOG_ERROR("Out of memory");
3497 for (unsigned i = 0; i < chunk_size; i++) {
3498 switch (data_size) {
3500 target_buffer_set_u64(target, target_buf + i * data_size, b);
3503 target_buffer_set_u32(target, target_buf + i * data_size, b);
3506 target_buffer_set_u16(target, target_buf + i * data_size, b);
3509 target_buffer_set_u8(target, target_buf + i * data_size, b);
3516 int retval = ERROR_OK;
3518 for (unsigned x = 0; x < c; x += chunk_size) {
3521 if (current > chunk_size)
3522 current = chunk_size;
3523 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3524 if (retval != ERROR_OK)
3526 /* avoid GDB timeouts */
3535 COMMAND_HANDLER(handle_mw_command)
3538 return ERROR_COMMAND_SYNTAX_ERROR;
3539 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3544 fn = target_write_phys_memory;
3546 fn = target_write_memory;
3547 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3548 return ERROR_COMMAND_SYNTAX_ERROR;
3550 target_addr_t address;
3551 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3554 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[1], value);
3558 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3560 struct target *target = get_current_target(CMD_CTX);
3562 switch (CMD_NAME[2]) {
3576 return ERROR_COMMAND_SYNTAX_ERROR;
3579 return target_fill_mem(target, address, fn, wordsize, value, count);
3582 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
3583 target_addr_t *min_address, target_addr_t *max_address)
3585 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3586 return ERROR_COMMAND_SYNTAX_ERROR;
3588 /* a base address isn't always necessary,
3589 * default to 0x0 (i.e. don't relocate) */
3590 if (CMD_ARGC >= 2) {
3592 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3593 image->base_address = addr;
3594 image->base_address_set = true;
3596 image->base_address_set = false;
3598 image->start_address_set = false;
3601 COMMAND_PARSE_ADDRESS(CMD_ARGV[3], *min_address);
3602 if (CMD_ARGC == 5) {
3603 COMMAND_PARSE_ADDRESS(CMD_ARGV[4], *max_address);
3604 /* use size (given) to find max (required) */
3605 *max_address += *min_address;
3608 if (*min_address > *max_address)
3609 return ERROR_COMMAND_SYNTAX_ERROR;
3614 COMMAND_HANDLER(handle_load_image_command)
3618 uint32_t image_size;
3619 target_addr_t min_address = 0;
3620 target_addr_t max_address = -1;
3623 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
3624 &image, &min_address, &max_address);
3625 if (ERROR_OK != retval)
3628 struct target *target = get_current_target(CMD_CTX);
3630 struct duration bench;
3631 duration_start(&bench);
3633 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3638 for (unsigned int i = 0; i < image.num_sections; i++) {
3639 buffer = malloc(image.sections[i].size);
3640 if (buffer == NULL) {
3642 "error allocating buffer for section (%d bytes)",
3643 (int)(image.sections[i].size));
3644 retval = ERROR_FAIL;
3648 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3649 if (retval != ERROR_OK) {
3654 uint32_t offset = 0;
3655 uint32_t length = buf_cnt;
3657 /* DANGER!!! beware of unsigned comparison here!!! */
3659 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3660 (image.sections[i].base_address < max_address)) {
3662 if (image.sections[i].base_address < min_address) {
3663 /* clip addresses below */
3664 offset += min_address-image.sections[i].base_address;
3668 if (image.sections[i].base_address + buf_cnt > max_address)
3669 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3671 retval = target_write_buffer(target,
3672 image.sections[i].base_address + offset, length, buffer + offset);
3673 if (retval != ERROR_OK) {
3677 image_size += length;
3678 command_print(CMD, "%u bytes written at address " TARGET_ADDR_FMT "",
3679 (unsigned int)length,
3680 image.sections[i].base_address + offset);
3686 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3687 command_print(CMD, "downloaded %" PRIu32 " bytes "
3688 "in %fs (%0.3f KiB/s)", image_size,
3689 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3692 image_close(&image);
3698 COMMAND_HANDLER(handle_dump_image_command)
3700 struct fileio *fileio;
3702 int retval, retvaltemp;
3703 target_addr_t address, size;
3704 struct duration bench;
3705 struct target *target = get_current_target(CMD_CTX);
3708 return ERROR_COMMAND_SYNTAX_ERROR;
3710 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], address);
3711 COMMAND_PARSE_ADDRESS(CMD_ARGV[2], size);
3713 uint32_t buf_size = (size > 4096) ? 4096 : size;
3714 buffer = malloc(buf_size);
3718 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3719 if (retval != ERROR_OK) {
3724 duration_start(&bench);
3727 size_t size_written;
3728 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3729 retval = target_read_buffer(target, address, this_run_size, buffer);
3730 if (retval != ERROR_OK)
3733 retval = fileio_write(fileio, this_run_size, buffer, &size_written);
3734 if (retval != ERROR_OK)
3737 size -= this_run_size;
3738 address += this_run_size;
3743 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3745 retval = fileio_size(fileio, &filesize);
3746 if (retval != ERROR_OK)
3749 "dumped %zu bytes in %fs (%0.3f KiB/s)", filesize,
3750 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3753 retvaltemp = fileio_close(fileio);
3754 if (retvaltemp != ERROR_OK)
3763 IMAGE_CHECKSUM_ONLY = 2
3766 static COMMAND_HELPER(handle_verify_image_command_internal, enum verify_mode verify)
3770 uint32_t image_size;
3772 uint32_t checksum = 0;
3773 uint32_t mem_checksum = 0;
3777 struct target *target = get_current_target(CMD_CTX);
3780 return ERROR_COMMAND_SYNTAX_ERROR;
3783 LOG_ERROR("no target selected");
3787 struct duration bench;
3788 duration_start(&bench);
3790 if (CMD_ARGC >= 2) {
3792 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3793 image.base_address = addr;
3794 image.base_address_set = true;
3796 image.base_address_set = false;
3797 image.base_address = 0x0;
3800 image.start_address_set = false;
3802 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3803 if (retval != ERROR_OK)
3809 for (unsigned int i = 0; i < image.num_sections; i++) {
3810 buffer = malloc(image.sections[i].size);
3811 if (buffer == NULL) {
3813 "error allocating buffer for section (%" PRIu32 " bytes)",
3814 image.sections[i].size);
3817 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3818 if (retval != ERROR_OK) {
3823 if (verify >= IMAGE_VERIFY) {
3824 /* calculate checksum of image */
3825 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3826 if (retval != ERROR_OK) {
3831 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3832 if (retval != ERROR_OK) {
3836 if ((checksum != mem_checksum) && (verify == IMAGE_CHECKSUM_ONLY)) {
3837 LOG_ERROR("checksum mismatch");
3839 retval = ERROR_FAIL;
3842 if (checksum != mem_checksum) {
3843 /* failed crc checksum, fall back to a binary compare */
3847 LOG_ERROR("checksum mismatch - attempting binary compare");
3849 data = malloc(buf_cnt);
3851 retval = target_read_buffer(target, image.sections[i].base_address, buf_cnt, data);
3852 if (retval == ERROR_OK) {
3854 for (t = 0; t < buf_cnt; t++) {
3855 if (data[t] != buffer[t]) {
3857 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3859 (unsigned)(t + image.sections[i].base_address),
3862 if (diffs++ >= 127) {
3863 command_print(CMD, "More than 128 errors, the rest are not printed.");
3875 command_print(CMD, "address " TARGET_ADDR_FMT " length 0x%08zx",
3876 image.sections[i].base_address,
3881 image_size += buf_cnt;
3884 command_print(CMD, "No more differences found.");
3887 retval = ERROR_FAIL;
3888 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3889 command_print(CMD, "verified %" PRIu32 " bytes "
3890 "in %fs (%0.3f KiB/s)", image_size,
3891 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3894 image_close(&image);
3899 COMMAND_HANDLER(handle_verify_image_checksum_command)
3901 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_CHECKSUM_ONLY);
3904 COMMAND_HANDLER(handle_verify_image_command)
3906 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_VERIFY);
3909 COMMAND_HANDLER(handle_test_image_command)
3911 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_TEST);
3914 static int handle_bp_command_list(struct command_invocation *cmd)
3916 struct target *target = get_current_target(cmd->ctx);
3917 struct breakpoint *breakpoint = target->breakpoints;
3918 while (breakpoint) {
3919 if (breakpoint->type == BKPT_SOFT) {
3920 char *buf = buf_to_hex_str(breakpoint->orig_instr,
3921 breakpoint->length);
3922 command_print(cmd, "IVA breakpoint: " TARGET_ADDR_FMT ", 0x%x, %i, 0x%s",
3923 breakpoint->address,
3925 breakpoint->set, buf);
3928 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3929 command_print(cmd, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3931 breakpoint->length, breakpoint->set);
3932 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3933 command_print(cmd, "Hybrid breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3934 breakpoint->address,
3935 breakpoint->length, breakpoint->set);
3936 command_print(cmd, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3939 command_print(cmd, "Breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3940 breakpoint->address,
3941 breakpoint->length, breakpoint->set);
3944 breakpoint = breakpoint->next;
3949 static int handle_bp_command_set(struct command_invocation *cmd,
3950 target_addr_t addr, uint32_t asid, uint32_t length, int hw)
3952 struct target *target = get_current_target(cmd->ctx);
3956 retval = breakpoint_add(target, addr, length, hw);
3957 /* error is always logged in breakpoint_add(), do not print it again */
3958 if (ERROR_OK == retval)
3959 command_print(cmd, "breakpoint set at " TARGET_ADDR_FMT "", addr);
3961 } else if (addr == 0) {
3962 if (target->type->add_context_breakpoint == NULL) {
3963 LOG_ERROR("Context breakpoint not available");
3964 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
3966 retval = context_breakpoint_add(target, asid, length, hw);
3967 /* error is always logged in context_breakpoint_add(), do not print it again */
3968 if (ERROR_OK == retval)
3969 command_print(cmd, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3972 if (target->type->add_hybrid_breakpoint == NULL) {
3973 LOG_ERROR("Hybrid breakpoint not available");
3974 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
3976 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3977 /* error is always logged in hybrid_breakpoint_add(), do not print it again */
3978 if (ERROR_OK == retval)
3979 command_print(cmd, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3984 COMMAND_HANDLER(handle_bp_command)
3993 return handle_bp_command_list(CMD);
3997 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3998 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3999 return handle_bp_command_set(CMD, addr, asid, length, hw);
4002 if (strcmp(CMD_ARGV[2], "hw") == 0) {
4004 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4005 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4007 return handle_bp_command_set(CMD, addr, asid, length, hw);
4008 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
4010 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
4011 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4013 return handle_bp_command_set(CMD, addr, asid, length, hw);
4018 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4019 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
4020 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
4021 return handle_bp_command_set(CMD, addr, asid, length, hw);
4024 return ERROR_COMMAND_SYNTAX_ERROR;
4028 COMMAND_HANDLER(handle_rbp_command)
4031 return ERROR_COMMAND_SYNTAX_ERROR;
4033 struct target *target = get_current_target(CMD_CTX);
4035 if (!strcmp(CMD_ARGV[0], "all")) {
4036 breakpoint_remove_all(target);
4039 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4041 breakpoint_remove(target, addr);
4047 COMMAND_HANDLER(handle_wp_command)
4049 struct target *target = get_current_target(CMD_CTX);
4051 if (CMD_ARGC == 0) {
4052 struct watchpoint *watchpoint = target->watchpoints;
4054 while (watchpoint) {
4055 command_print(CMD, "address: " TARGET_ADDR_FMT
4056 ", len: 0x%8.8" PRIx32
4057 ", r/w/a: %i, value: 0x%8.8" PRIx32
4058 ", mask: 0x%8.8" PRIx32,
4059 watchpoint->address,
4061 (int)watchpoint->rw,
4064 watchpoint = watchpoint->next;
4069 enum watchpoint_rw type = WPT_ACCESS;
4070 target_addr_t addr = 0;
4071 uint32_t length = 0;
4072 uint32_t data_value = 0x0;
4073 uint32_t data_mask = 0xffffffff;
4077 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
4080 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
4083 switch (CMD_ARGV[2][0]) {
4094 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
4095 return ERROR_COMMAND_SYNTAX_ERROR;
4099 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4100 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4104 return ERROR_COMMAND_SYNTAX_ERROR;
4107 int retval = watchpoint_add(target, addr, length, type,
4108 data_value, data_mask);
4109 if (ERROR_OK != retval)
4110 LOG_ERROR("Failure setting watchpoints");
4115 COMMAND_HANDLER(handle_rwp_command)
4118 return ERROR_COMMAND_SYNTAX_ERROR;
4121 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4123 struct target *target = get_current_target(CMD_CTX);
4124 watchpoint_remove(target, addr);
4130 * Translate a virtual address to a physical address.
4132 * The low-level target implementation must have logged a detailed error
4133 * which is forwarded to telnet/GDB session.
4135 COMMAND_HANDLER(handle_virt2phys_command)
4138 return ERROR_COMMAND_SYNTAX_ERROR;
4141 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], va);
4144 struct target *target = get_current_target(CMD_CTX);
4145 int retval = target->type->virt2phys(target, va, &pa);
4146 if (retval == ERROR_OK)
4147 command_print(CMD, "Physical address " TARGET_ADDR_FMT "", pa);
4152 static void writeData(FILE *f, const void *data, size_t len)
4154 size_t written = fwrite(data, 1, len, f);
4156 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
4159 static void writeLong(FILE *f, int l, struct target *target)
4163 target_buffer_set_u32(target, val, l);
4164 writeData(f, val, 4);
4167 static void writeString(FILE *f, char *s)
4169 writeData(f, s, strlen(s));
4172 typedef unsigned char UNIT[2]; /* unit of profiling */
4174 /* Dump a gmon.out histogram file. */
4175 static void write_gmon(uint32_t *samples, uint32_t sampleNum, const char *filename, bool with_range,
4176 uint32_t start_address, uint32_t end_address, struct target *target, uint32_t duration_ms)
4179 FILE *f = fopen(filename, "w");
4182 writeString(f, "gmon");
4183 writeLong(f, 0x00000001, target); /* Version */
4184 writeLong(f, 0, target); /* padding */
4185 writeLong(f, 0, target); /* padding */
4186 writeLong(f, 0, target); /* padding */
4188 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
4189 writeData(f, &zero, 1);
4191 /* figure out bucket size */
4195 min = start_address;
4200 for (i = 0; i < sampleNum; i++) {
4201 if (min > samples[i])
4203 if (max < samples[i])
4207 /* max should be (largest sample + 1)
4208 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
4212 int addressSpace = max - min;
4213 assert(addressSpace >= 2);
4215 /* FIXME: What is the reasonable number of buckets?
4216 * The profiling result will be more accurate if there are enough buckets. */
4217 static const uint32_t maxBuckets = 128 * 1024; /* maximum buckets. */
4218 uint32_t numBuckets = addressSpace / sizeof(UNIT);
4219 if (numBuckets > maxBuckets)
4220 numBuckets = maxBuckets;
4221 int *buckets = malloc(sizeof(int) * numBuckets);
4222 if (buckets == NULL) {
4226 memset(buckets, 0, sizeof(int) * numBuckets);
4227 for (i = 0; i < sampleNum; i++) {
4228 uint32_t address = samples[i];
4230 if ((address < min) || (max <= address))
4233 long long a = address - min;
4234 long long b = numBuckets;
4235 long long c = addressSpace;
4236 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
4240 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
4241 writeLong(f, min, target); /* low_pc */
4242 writeLong(f, max, target); /* high_pc */
4243 writeLong(f, numBuckets, target); /* # of buckets */
4244 float sample_rate = sampleNum / (duration_ms / 1000.0);
4245 writeLong(f, sample_rate, target);
4246 writeString(f, "seconds");
4247 for (i = 0; i < (15-strlen("seconds")); i++)
4248 writeData(f, &zero, 1);
4249 writeString(f, "s");
4251 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
4253 char *data = malloc(2 * numBuckets);
4255 for (i = 0; i < numBuckets; i++) {
4260 data[i * 2] = val&0xff;
4261 data[i * 2 + 1] = (val >> 8) & 0xff;
4264 writeData(f, data, numBuckets * 2);
4272 /* profiling samples the CPU PC as quickly as OpenOCD is able,
4273 * which will be used as a random sampling of PC */
4274 COMMAND_HANDLER(handle_profile_command)
4276 struct target *target = get_current_target(CMD_CTX);
4278 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
4279 return ERROR_COMMAND_SYNTAX_ERROR;
4281 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
4283 uint32_t num_of_samples;
4284 int retval = ERROR_OK;
4285 bool halted_before_profiling = target->state == TARGET_HALTED;
4287 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
4289 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
4290 if (samples == NULL) {
4291 LOG_ERROR("No memory to store samples.");
4295 uint64_t timestart_ms = timeval_ms();
4297 * Some cores let us sample the PC without the
4298 * annoying halt/resume step; for example, ARMv7 PCSR.
4299 * Provide a way to use that more efficient mechanism.
4301 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
4302 &num_of_samples, offset);
4303 if (retval != ERROR_OK) {
4307 uint32_t duration_ms = timeval_ms() - timestart_ms;
4309 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
4311 retval = target_poll(target);
4312 if (retval != ERROR_OK) {
4317 if (target->state == TARGET_RUNNING && halted_before_profiling) {
4318 /* The target was halted before we started and is running now. Halt it,
4319 * for consistency. */
4320 retval = target_halt(target);
4321 if (retval != ERROR_OK) {
4325 } else if (target->state == TARGET_HALTED && !halted_before_profiling) {
4326 /* The target was running before we started and is halted now. Resume
4327 * it, for consistency. */
4328 retval = target_resume(target, 1, 0, 0, 0);
4329 if (retval != ERROR_OK) {
4335 retval = target_poll(target);
4336 if (retval != ERROR_OK) {
4341 uint32_t start_address = 0;
4342 uint32_t end_address = 0;
4343 bool with_range = false;
4344 if (CMD_ARGC == 4) {
4346 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
4347 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
4350 write_gmon(samples, num_of_samples, CMD_ARGV[1],
4351 with_range, start_address, end_address, target, duration_ms);
4352 command_print(CMD, "Wrote %s", CMD_ARGV[1]);
4358 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
4361 Jim_Obj *nameObjPtr, *valObjPtr;
4364 namebuf = alloc_printf("%s(%d)", varname, idx);
4368 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
4369 valObjPtr = Jim_NewIntObj(interp, val);
4370 if (!nameObjPtr || !valObjPtr) {
4375 Jim_IncrRefCount(nameObjPtr);
4376 Jim_IncrRefCount(valObjPtr);
4377 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
4378 Jim_DecrRefCount(interp, nameObjPtr);
4379 Jim_DecrRefCount(interp, valObjPtr);
4381 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
4385 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4387 struct command_context *context;
4388 struct target *target;
4390 context = current_command_context(interp);
4391 assert(context != NULL);
4393 target = get_current_target(context);
4394 if (target == NULL) {
4395 LOG_ERROR("mem2array: no current target");
4399 return target_mem2array(interp, target, argc - 1, argv + 1);
4402 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
4410 const char *varname;
4416 /* argv[1] = name of array to receive the data
4417 * argv[2] = desired width
4418 * argv[3] = memory address
4419 * argv[4] = count of times to read
4422 if (argc < 4 || argc > 5) {
4423 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4426 varname = Jim_GetString(argv[0], &len);
4427 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
4429 e = Jim_GetLong(interp, argv[1], &l);
4434 e = Jim_GetLong(interp, argv[2], &l);
4438 e = Jim_GetLong(interp, argv[3], &l);
4444 phys = Jim_GetString(argv[4], &n);
4445 if (!strncmp(phys, "phys", n))
4461 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4462 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
4466 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4467 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
4470 if ((addr + (len * width)) < addr) {
4471 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4472 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
4475 /* absurd transfer size? */
4477 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4478 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
4483 ((width == 2) && ((addr & 1) == 0)) ||
4484 ((width == 4) && ((addr & 3) == 0))) {
4488 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4489 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRIu32 " byte reads",
4492 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4501 size_t buffersize = 4096;
4502 uint8_t *buffer = malloc(buffersize);
4509 /* Slurp... in buffer size chunks */
4511 count = len; /* in objects.. */
4512 if (count > (buffersize / width))
4513 count = (buffersize / width);
4516 retval = target_read_phys_memory(target, addr, width, count, buffer);
4518 retval = target_read_memory(target, addr, width, count, buffer);
4519 if (retval != ERROR_OK) {
4521 LOG_ERROR("mem2array: Read @ 0x%08" PRIx32 ", w=%" PRIu32 ", cnt=%" PRIu32 ", failed",
4525 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4526 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
4530 v = 0; /* shut up gcc */
4531 for (i = 0; i < count ; i++, n++) {
4534 v = target_buffer_get_u32(target, &buffer[i*width]);
4537 v = target_buffer_get_u16(target, &buffer[i*width]);
4540 v = buffer[i] & 0x0ff;
4543 new_int_array_element(interp, varname, n, v);
4546 addr += count * width;
4552 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4557 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
4560 Jim_Obj *nameObjPtr, *valObjPtr;
4564 namebuf = alloc_printf("%s(%d)", varname, idx);
4568 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
4574 Jim_IncrRefCount(nameObjPtr);
4575 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
4576 Jim_DecrRefCount(interp, nameObjPtr);
4578 if (valObjPtr == NULL)
4581 result = Jim_GetLong(interp, valObjPtr, &l);
4582 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
4587 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4589 struct command_context *context;
4590 struct target *target;
4592 context = current_command_context(interp);
4593 assert(context != NULL);
4595 target = get_current_target(context);
4596 if (target == NULL) {
4597 LOG_ERROR("array2mem: no current target");
4601 return target_array2mem(interp, target, argc-1, argv + 1);
4604 static int target_array2mem(Jim_Interp *interp, struct target *target,
4605 int argc, Jim_Obj *const *argv)
4613 const char *varname;
4619 /* argv[1] = name of array to get the data
4620 * argv[2] = desired width
4621 * argv[3] = memory address
4622 * argv[4] = count to write
4624 if (argc < 4 || argc > 5) {
4625 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4628 varname = Jim_GetString(argv[0], &len);
4629 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
4631 e = Jim_GetLong(interp, argv[1], &l);
4636 e = Jim_GetLong(interp, argv[2], &l);
4640 e = Jim_GetLong(interp, argv[3], &l);
4646 phys = Jim_GetString(argv[4], &n);
4647 if (!strncmp(phys, "phys", n))
4663 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4664 Jim_AppendStrings(interp, Jim_GetResult(interp),
4665 "Invalid width param, must be 8/16/32", NULL);
4669 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4670 Jim_AppendStrings(interp, Jim_GetResult(interp),
4671 "array2mem: zero width read?", NULL);
4674 if ((addr + (len * width)) < addr) {
4675 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4676 Jim_AppendStrings(interp, Jim_GetResult(interp),
4677 "array2mem: addr + len - wraps to zero?", NULL);
4680 /* absurd transfer size? */
4682 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4683 Jim_AppendStrings(interp, Jim_GetResult(interp),
4684 "array2mem: absurd > 64K item request", NULL);
4689 ((width == 2) && ((addr & 1) == 0)) ||
4690 ((width == 4) && ((addr & 3) == 0))) {
4694 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4695 sprintf(buf, "array2mem address: 0x%08" PRIx32 " is not aligned for %" PRIu32 " byte reads",
4698 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4709 size_t buffersize = 4096;
4710 uint8_t *buffer = malloc(buffersize);
4715 /* Slurp... in buffer size chunks */
4717 count = len; /* in objects.. */
4718 if (count > (buffersize / width))
4719 count = (buffersize / width);
4721 v = 0; /* shut up gcc */
4722 for (i = 0; i < count; i++, n++) {
4723 get_int_array_element(interp, varname, n, &v);
4726 target_buffer_set_u32(target, &buffer[i * width], v);
4729 target_buffer_set_u16(target, &buffer[i * width], v);
4732 buffer[i] = v & 0x0ff;
4739 retval = target_write_phys_memory(target, addr, width, count, buffer);
4741 retval = target_write_memory(target, addr, width, count, buffer);
4742 if (retval != ERROR_OK) {
4744 LOG_ERROR("array2mem: Write @ 0x%08" PRIx32 ", w=%" PRIu32 ", cnt=%" PRIu32 ", failed",
4748 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4749 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4753 addr += count * width;
4758 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4763 /* FIX? should we propagate errors here rather than printing them
4766 void target_handle_event(struct target *target, enum target_event e)
4768 struct target_event_action *teap;
4771 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4772 if (teap->event == e) {
4773 LOG_DEBUG("target(%d): %s (%s) event: %d (%s) action: %s",
4774 target->target_number,
4775 target_name(target),
4776 target_type_name(target),
4778 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
4779 Jim_GetString(teap->body, NULL));
4781 /* Override current target by the target an event
4782 * is issued from (lot of scripts need it).
4783 * Return back to previous override as soon
4784 * as the handler processing is done */
4785 struct command_context *cmd_ctx = current_command_context(teap->interp);
4786 struct target *saved_target_override = cmd_ctx->current_target_override;
4787 cmd_ctx->current_target_override = target;
4789 retval = Jim_EvalObj(teap->interp, teap->body);
4791 cmd_ctx->current_target_override = saved_target_override;
4793 if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
4796 if (retval == JIM_RETURN)
4797 retval = teap->interp->returnCode;
4799 if (retval != JIM_OK) {
4800 Jim_MakeErrorMessage(teap->interp);
4801 LOG_USER("Error executing event %s on target %s:\n%s",
4802 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
4803 target_name(target),
4804 Jim_GetString(Jim_GetResult(teap->interp), NULL));
4805 /* clean both error code and stacktrace before return */
4806 Jim_Eval(teap->interp, "error \"\" \"\"");
4813 * Returns true only if the target has a handler for the specified event.
4815 bool target_has_event_action(struct target *target, enum target_event event)
4817 struct target_event_action *teap;
4819 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4820 if (teap->event == event)
4826 enum target_cfg_param {
4829 TCFG_WORK_AREA_VIRT,
4830 TCFG_WORK_AREA_PHYS,
4831 TCFG_WORK_AREA_SIZE,
4832 TCFG_WORK_AREA_BACKUP,
4835 TCFG_CHAIN_POSITION,
4840 TCFG_GDB_MAX_CONNECTIONS,
4843 static Jim_Nvp nvp_config_opts[] = {
4844 { .name = "-type", .value = TCFG_TYPE },
4845 { .name = "-event", .value = TCFG_EVENT },
4846 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4847 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4848 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4849 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4850 { .name = "-endian", .value = TCFG_ENDIAN },
4851 { .name = "-coreid", .value = TCFG_COREID },
4852 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4853 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4854 { .name = "-rtos", .value = TCFG_RTOS },
4855 { .name = "-defer-examine", .value = TCFG_DEFER_EXAMINE },
4856 { .name = "-gdb-port", .value = TCFG_GDB_PORT },
4857 { .name = "-gdb-max-connections", .value = TCFG_GDB_MAX_CONNECTIONS },
4858 { .name = NULL, .value = -1 }
4861 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
4868 /* parse config or cget options ... */
4869 while (goi->argc > 0) {
4870 Jim_SetEmptyResult(goi->interp);
4871 /* Jim_GetOpt_Debug(goi); */
4873 if (target->type->target_jim_configure) {
4874 /* target defines a configure function */
4875 /* target gets first dibs on parameters */
4876 e = (*(target->type->target_jim_configure))(target, goi);
4885 /* otherwise we 'continue' below */
4887 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
4889 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
4895 if (goi->isconfigure) {
4896 Jim_SetResultFormatted(goi->interp,
4897 "not settable: %s", n->name);
4901 if (goi->argc != 0) {
4902 Jim_WrongNumArgs(goi->interp,
4903 goi->argc, goi->argv,
4908 Jim_SetResultString(goi->interp,
4909 target_type_name(target), -1);
4913 if (goi->argc == 0) {
4914 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4918 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4920 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4924 if (goi->isconfigure) {
4925 if (goi->argc != 1) {
4926 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4930 if (goi->argc != 0) {
4931 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4937 struct target_event_action *teap;
4939 teap = target->event_action;
4940 /* replace existing? */
4942 if (teap->event == (enum target_event)n->value)
4947 if (goi->isconfigure) {
4948 bool replace = true;
4951 teap = calloc(1, sizeof(*teap));
4954 teap->event = n->value;
4955 teap->interp = goi->interp;
4956 Jim_GetOpt_Obj(goi, &o);
4958 Jim_DecrRefCount(teap->interp, teap->body);
4959 teap->body = Jim_DuplicateObj(goi->interp, o);
4962 * Tcl/TK - "tk events" have a nice feature.
4963 * See the "BIND" command.
4964 * We should support that here.
4965 * You can specify %X and %Y in the event code.
4966 * The idea is: %T - target name.
4967 * The idea is: %N - target number
4968 * The idea is: %E - event name.
4970 Jim_IncrRefCount(teap->body);
4973 /* add to head of event list */
4974 teap->next = target->event_action;
4975 target->event_action = teap;
4977 Jim_SetEmptyResult(goi->interp);
4981 Jim_SetEmptyResult(goi->interp);
4983 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4989 case TCFG_WORK_AREA_VIRT:
4990 if (goi->isconfigure) {
4991 target_free_all_working_areas(target);
4992 e = Jim_GetOpt_Wide(goi, &w);
4995 target->working_area_virt = w;
4996 target->working_area_virt_spec = true;
5001 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
5005 case TCFG_WORK_AREA_PHYS:
5006 if (goi->isconfigure) {
5007 target_free_all_working_areas(target);
5008 e = Jim_GetOpt_Wide(goi, &w);
5011 target->working_area_phys = w;
5012 target->working_area_phys_spec = true;
5017 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
5021 case TCFG_WORK_AREA_SIZE:
5022 if (goi->isconfigure) {
5023 target_free_all_working_areas(target);
5024 e = Jim_GetOpt_Wide(goi, &w);
5027 target->working_area_size = w;
5032 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
5036 case TCFG_WORK_AREA_BACKUP:
5037 if (goi->isconfigure) {
5038 target_free_all_working_areas(target);
5039 e = Jim_GetOpt_Wide(goi, &w);
5042 /* make this exactly 1 or 0 */
5043 target->backup_working_area = (!!w);
5048 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
5049 /* loop for more e*/
5054 if (goi->isconfigure) {
5055 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
5057 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
5060 target->endianness = n->value;
5065 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
5066 if (n->name == NULL) {
5067 target->endianness = TARGET_LITTLE_ENDIAN;
5068 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
5070 Jim_SetResultString(goi->interp, n->name, -1);
5075 if (goi->isconfigure) {
5076 e = Jim_GetOpt_Wide(goi, &w);
5079 target->coreid = (int32_t)w;
5084 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->coreid));
5088 case TCFG_CHAIN_POSITION:
5089 if (goi->isconfigure) {
5091 struct jtag_tap *tap;
5093 if (target->has_dap) {
5094 Jim_SetResultString(goi->interp,
5095 "target requires -dap parameter instead of -chain-position!", -1);
5099 target_free_all_working_areas(target);
5100 e = Jim_GetOpt_Obj(goi, &o_t);
5103 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
5107 target->tap_configured = true;
5112 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
5113 /* loop for more e*/
5116 if (goi->isconfigure) {
5117 e = Jim_GetOpt_Wide(goi, &w);
5120 target->dbgbase = (uint32_t)w;
5121 target->dbgbase_set = true;
5126 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
5132 int result = rtos_create(goi, target);
5133 if (result != JIM_OK)
5139 case TCFG_DEFER_EXAMINE:
5141 target->defer_examine = true;
5146 if (goi->isconfigure) {
5147 struct command_context *cmd_ctx = current_command_context(goi->interp);
5148 if (cmd_ctx->mode != COMMAND_CONFIG) {
5149 Jim_SetResultString(goi->interp, "-gdb-port must be configured before 'init'", -1);
5154 e = Jim_GetOpt_String(goi, &s, NULL);
5157 free(target->gdb_port_override);
5158 target->gdb_port_override = strdup(s);
5163 Jim_SetResultString(goi->interp, target->gdb_port_override ? : "undefined", -1);
5167 case TCFG_GDB_MAX_CONNECTIONS:
5168 if (goi->isconfigure) {
5169 struct command_context *cmd_ctx = current_command_context(goi->interp);
5170 if (cmd_ctx->mode != COMMAND_CONFIG) {
5171 Jim_SetResultString(goi->interp, "-gdb-max-conenctions must be configured before 'init'", -1);
5175 e = Jim_GetOpt_Wide(goi, &w);
5178 target->gdb_max_connections = (w < 0) ? CONNECTION_LIMIT_UNLIMITED : (int)w;
5183 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->gdb_max_connections));
5186 } /* while (goi->argc) */
5189 /* done - we return */
5193 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5197 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5198 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
5200 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5201 "missing: -option ...");
5204 struct target *target = Jim_CmdPrivData(goi.interp);
5205 return target_configure(&goi, target);
5208 static int jim_target_mem2array(Jim_Interp *interp,
5209 int argc, Jim_Obj *const *argv)
5211 struct target *target = Jim_CmdPrivData(interp);
5212 return target_mem2array(interp, target, argc - 1, argv + 1);
5215 static int jim_target_array2mem(Jim_Interp *interp,
5216 int argc, Jim_Obj *const *argv)
5218 struct target *target = Jim_CmdPrivData(interp);
5219 return target_array2mem(interp, target, argc - 1, argv + 1);
5222 static int jim_target_tap_disabled(Jim_Interp *interp)
5224 Jim_SetResultFormatted(interp, "[TAP is disabled]");
5228 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5230 bool allow_defer = false;
5233 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5235 const char *cmd_name = Jim_GetString(argv[0], NULL);
5236 Jim_SetResultFormatted(goi.interp,
5237 "usage: %s ['allow-defer']", cmd_name);
5241 strcmp(Jim_GetString(argv[1], NULL), "allow-defer") == 0) {
5244 int e = Jim_GetOpt_Obj(&goi, &obj);
5250 struct target *target = Jim_CmdPrivData(interp);
5251 if (!target->tap->enabled)
5252 return jim_target_tap_disabled(interp);
5254 if (allow_defer && target->defer_examine) {
5255 LOG_INFO("Deferring arp_examine of %s", target_name(target));
5256 LOG_INFO("Use arp_examine command to examine it manually!");
5260 int e = target->type->examine(target);
5266 static int jim_target_was_examined(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5268 struct target *target = Jim_CmdPrivData(interp);
5270 Jim_SetResultBool(interp, target_was_examined(target));
5274 static int jim_target_examine_deferred(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5276 struct target *target = Jim_CmdPrivData(interp);
5278 Jim_SetResultBool(interp, target->defer_examine);
5282 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5285 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5288 struct target *target = Jim_CmdPrivData(interp);
5290 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
5296 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5299 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5302 struct target *target = Jim_CmdPrivData(interp);
5303 if (!target->tap->enabled)
5304 return jim_target_tap_disabled(interp);
5307 if (!(target_was_examined(target)))
5308 e = ERROR_TARGET_NOT_EXAMINED;
5310 e = target->type->poll(target);
5316 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5319 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5321 if (goi.argc != 2) {
5322 Jim_WrongNumArgs(interp, 0, argv,
5323 "([tT]|[fF]|assert|deassert) BOOL");
5328 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
5330 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
5333 /* the halt or not param */
5335 e = Jim_GetOpt_Wide(&goi, &a);
5339 struct target *target = Jim_CmdPrivData(goi.interp);
5340 if (!target->tap->enabled)
5341 return jim_target_tap_disabled(interp);
5343 if (!target->type->assert_reset || !target->type->deassert_reset) {
5344 Jim_SetResultFormatted(interp,
5345 "No target-specific reset for %s",
5346 target_name(target));
5350 if (target->defer_examine)
5351 target_reset_examined(target);
5353 /* determine if we should halt or not. */
5354 target->reset_halt = !!a;
5355 /* When this happens - all workareas are invalid. */
5356 target_free_all_working_areas_restore(target, 0);
5359 if (n->value == NVP_ASSERT)
5360 e = target->type->assert_reset(target);
5362 e = target->type->deassert_reset(target);
5363 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5366 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5369 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5372 struct target *target = Jim_CmdPrivData(interp);
5373 if (!target->tap->enabled)
5374 return jim_target_tap_disabled(interp);
5375 int e = target->type->halt(target);
5376 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5379 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5382 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5384 /* params: <name> statename timeoutmsecs */
5385 if (goi.argc != 2) {
5386 const char *cmd_name = Jim_GetString(argv[0], NULL);
5387 Jim_SetResultFormatted(goi.interp,
5388 "%s <state_name> <timeout_in_msec>", cmd_name);
5393 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
5395 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
5399 e = Jim_GetOpt_Wide(&goi, &a);
5402 struct target *target = Jim_CmdPrivData(interp);
5403 if (!target->tap->enabled)
5404 return jim_target_tap_disabled(interp);
5406 e = target_wait_state(target, n->value, a);
5407 if (e != ERROR_OK) {
5408 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
5409 Jim_SetResultFormatted(goi.interp,
5410 "target: %s wait %s fails (%#s) %s",
5411 target_name(target), n->name,
5412 eObj, target_strerror_safe(e));
5417 /* List for human, Events defined for this target.
5418 * scripts/programs should use 'name cget -event NAME'
5420 COMMAND_HANDLER(handle_target_event_list)
5422 struct target *target = get_current_target(CMD_CTX);
5423 struct target_event_action *teap = target->event_action;
5425 command_print(CMD, "Event actions for target (%d) %s\n",
5426 target->target_number,
5427 target_name(target));
5428 command_print(CMD, "%-25s | Body", "Event");
5429 command_print(CMD, "------------------------- | "
5430 "----------------------------------------");
5432 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
5433 command_print(CMD, "%-25s | %s",
5434 opt->name, Jim_GetString(teap->body, NULL));
5437 command_print(CMD, "***END***");
5440 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5443 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5446 struct target *target = Jim_CmdPrivData(interp);
5447 Jim_SetResultString(interp, target_state_name(target), -1);
5450 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5453 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5454 if (goi.argc != 1) {
5455 const char *cmd_name = Jim_GetString(argv[0], NULL);
5456 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5460 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
5462 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
5465 struct target *target = Jim_CmdPrivData(interp);
5466 target_handle_event(target, n->value);
5470 static const struct command_registration target_instance_command_handlers[] = {
5472 .name = "configure",
5473 .mode = COMMAND_ANY,
5474 .jim_handler = jim_target_configure,
5475 .help = "configure a new target for use",
5476 .usage = "[target_attribute ...]",
5480 .mode = COMMAND_ANY,
5481 .jim_handler = jim_target_configure,
5482 .help = "returns the specified target attribute",
5483 .usage = "target_attribute",
5487 .handler = handle_mw_command,
5488 .mode = COMMAND_EXEC,
5489 .help = "Write 64-bit word(s) to target memory",
5490 .usage = "address data [count]",
5494 .handler = handle_mw_command,
5495 .mode = COMMAND_EXEC,
5496 .help = "Write 32-bit word(s) to target memory",
5497 .usage = "address data [count]",
5501 .handler = handle_mw_command,
5502 .mode = COMMAND_EXEC,
5503 .help = "Write 16-bit half-word(s) to target memory",
5504 .usage = "address data [count]",
5508 .handler = handle_mw_command,
5509 .mode = COMMAND_EXEC,
5510 .help = "Write byte(s) to target memory",
5511 .usage = "address data [count]",
5515 .handler = handle_md_command,
5516 .mode = COMMAND_EXEC,
5517 .help = "Display target memory as 64-bit words",
5518 .usage = "address [count]",
5522 .handler = handle_md_command,
5523 .mode = COMMAND_EXEC,
5524 .help = "Display target memory as 32-bit words",
5525 .usage = "address [count]",
5529 .handler = handle_md_command,
5530 .mode = COMMAND_EXEC,
5531 .help = "Display target memory as 16-bit half-words",
5532 .usage = "address [count]",
5536 .handler = handle_md_command,
5537 .mode = COMMAND_EXEC,
5538 .help = "Display target memory as 8-bit bytes",
5539 .usage = "address [count]",
5542 .name = "array2mem",
5543 .mode = COMMAND_EXEC,
5544 .jim_handler = jim_target_array2mem,
5545 .help = "Writes Tcl array of 8/16/32 bit numbers "
5547 .usage = "arrayname bitwidth address count",
5550 .name = "mem2array",
5551 .mode = COMMAND_EXEC,
5552 .jim_handler = jim_target_mem2array,
5553 .help = "Loads Tcl array of 8/16/32 bit numbers "
5554 "from target memory",
5555 .usage = "arrayname bitwidth address count",
5558 .name = "eventlist",
5559 .handler = handle_target_event_list,
5560 .mode = COMMAND_EXEC,
5561 .help = "displays a table of events defined for this target",
5566 .mode = COMMAND_EXEC,
5567 .jim_handler = jim_target_current_state,
5568 .help = "displays the current state of this target",
5571 .name = "arp_examine",
5572 .mode = COMMAND_EXEC,
5573 .jim_handler = jim_target_examine,
5574 .help = "used internally for reset processing",
5575 .usage = "['allow-defer']",
5578 .name = "was_examined",
5579 .mode = COMMAND_EXEC,
5580 .jim_handler = jim_target_was_examined,
5581 .help = "used internally for reset processing",
5584 .name = "examine_deferred",
5585 .mode = COMMAND_EXEC,
5586 .jim_handler = jim_target_examine_deferred,
5587 .help = "used internally for reset processing",
5590 .name = "arp_halt_gdb",
5591 .mode = COMMAND_EXEC,
5592 .jim_handler = jim_target_halt_gdb,
5593 .help = "used internally for reset processing to halt GDB",
5597 .mode = COMMAND_EXEC,
5598 .jim_handler = jim_target_poll,
5599 .help = "used internally for reset processing",
5602 .name = "arp_reset",
5603 .mode = COMMAND_EXEC,
5604 .jim_handler = jim_target_reset,
5605 .help = "used internally for reset processing",
5609 .mode = COMMAND_EXEC,
5610 .jim_handler = jim_target_halt,
5611 .help = "used internally for reset processing",
5614 .name = "arp_waitstate",
5615 .mode = COMMAND_EXEC,
5616 .jim_handler = jim_target_wait_state,
5617 .help = "used internally for reset processing",
5620 .name = "invoke-event",
5621 .mode = COMMAND_EXEC,
5622 .jim_handler = jim_target_invoke_event,
5623 .help = "invoke handler for specified event",
5624 .usage = "event_name",
5626 COMMAND_REGISTRATION_DONE
5629 static int target_create(Jim_GetOptInfo *goi)
5636 struct target *target;
5637 struct command_context *cmd_ctx;
5639 cmd_ctx = current_command_context(goi->interp);
5640 assert(cmd_ctx != NULL);
5642 if (goi->argc < 3) {
5643 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5648 Jim_GetOpt_Obj(goi, &new_cmd);
5649 /* does this command exist? */
5650 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
5652 cp = Jim_GetString(new_cmd, NULL);
5653 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5658 e = Jim_GetOpt_String(goi, &cp, NULL);
5661 struct transport *tr = get_current_transport();
5662 if (tr->override_target) {
5663 e = tr->override_target(&cp);
5664 if (e != ERROR_OK) {
5665 LOG_ERROR("The selected transport doesn't support this target");
5668 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5670 /* now does target type exist */
5671 for (x = 0 ; target_types[x] ; x++) {
5672 if (0 == strcmp(cp, target_types[x]->name)) {
5677 /* check for deprecated name */
5678 if (target_types[x]->deprecated_name) {
5679 if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
5681 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
5686 if (target_types[x] == NULL) {
5687 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5688 for (x = 0 ; target_types[x] ; x++) {
5689 if (target_types[x + 1]) {
5690 Jim_AppendStrings(goi->interp,
5691 Jim_GetResult(goi->interp),
5692 target_types[x]->name,
5695 Jim_AppendStrings(goi->interp,
5696 Jim_GetResult(goi->interp),
5698 target_types[x]->name, NULL);
5705 target = calloc(1, sizeof(struct target));
5707 LOG_ERROR("Out of memory");
5711 /* set target number */
5712 target->target_number = new_target_number();
5714 /* allocate memory for each unique target type */
5715 target->type = malloc(sizeof(struct target_type));
5716 if (!target->type) {
5717 LOG_ERROR("Out of memory");
5722 memcpy(target->type, target_types[x], sizeof(struct target_type));
5724 /* default to first core, override with -coreid */
5727 target->working_area = 0x0;
5728 target->working_area_size = 0x0;
5729 target->working_areas = NULL;
5730 target->backup_working_area = 0;
5732 target->state = TARGET_UNKNOWN;
5733 target->debug_reason = DBG_REASON_UNDEFINED;
5734 target->reg_cache = NULL;
5735 target->breakpoints = NULL;
5736 target->watchpoints = NULL;
5737 target->next = NULL;
5738 target->arch_info = NULL;
5740 target->verbose_halt_msg = true;
5742 target->halt_issued = false;
5744 /* initialize trace information */
5745 target->trace_info = calloc(1, sizeof(struct trace));
5746 if (!target->trace_info) {
5747 LOG_ERROR("Out of memory");
5753 target->dbgmsg = NULL;
5754 target->dbg_msg_enabled = 0;
5756 target->endianness = TARGET_ENDIAN_UNKNOWN;
5758 target->rtos = NULL;
5759 target->rtos_auto_detect = false;
5761 target->gdb_port_override = NULL;
5762 target->gdb_max_connections = 1;
5764 /* Do the rest as "configure" options */
5765 goi->isconfigure = 1;
5766 e = target_configure(goi, target);
5769 if (target->has_dap) {
5770 if (!target->dap_configured) {
5771 Jim_SetResultString(goi->interp, "-dap ?name? required when creating target", -1);
5775 if (!target->tap_configured) {
5776 Jim_SetResultString(goi->interp, "-chain-position ?name? required when creating target", -1);
5780 /* tap must be set after target was configured */
5781 if (target->tap == NULL)
5786 rtos_destroy(target);
5787 free(target->gdb_port_override);
5788 free(target->trace_info);
5794 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5795 /* default endian to little if not specified */
5796 target->endianness = TARGET_LITTLE_ENDIAN;
5799 cp = Jim_GetString(new_cmd, NULL);
5800 target->cmd_name = strdup(cp);
5801 if (!target->cmd_name) {
5802 LOG_ERROR("Out of memory");
5803 rtos_destroy(target);
5804 free(target->gdb_port_override);
5805 free(target->trace_info);
5811 if (target->type->target_create) {
5812 e = (*(target->type->target_create))(target, goi->interp);
5813 if (e != ERROR_OK) {
5814 LOG_DEBUG("target_create failed");
5815 free(target->cmd_name);
5816 rtos_destroy(target);
5817 free(target->gdb_port_override);
5818 free(target->trace_info);
5825 /* create the target specific commands */
5826 if (target->type->commands) {
5827 e = register_commands(cmd_ctx, NULL, target->type->commands);
5829 LOG_ERROR("unable to register '%s' commands", cp);
5832 /* now - create the new target name command */
5833 const struct command_registration target_subcommands[] = {
5835 .chain = target_instance_command_handlers,
5838 .chain = target->type->commands,
5840 COMMAND_REGISTRATION_DONE
5842 const struct command_registration target_commands[] = {
5845 .mode = COMMAND_ANY,
5846 .help = "target command group",
5848 .chain = target_subcommands,
5850 COMMAND_REGISTRATION_DONE
5852 e = register_commands(cmd_ctx, NULL, target_commands);
5853 if (e != ERROR_OK) {
5854 if (target->type->deinit_target)
5855 target->type->deinit_target(target);
5856 free(target->cmd_name);
5857 rtos_destroy(target);
5858 free(target->gdb_port_override);
5859 free(target->trace_info);
5865 struct command *c = command_find_in_context(cmd_ctx, cp);
5867 command_set_handler_data(c, target);
5869 /* append to end of list */
5870 append_to_list_all_targets(target);
5872 cmd_ctx->current_target = target;
5876 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5879 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5882 struct command_context *cmd_ctx = current_command_context(interp);
5883 assert(cmd_ctx != NULL);
5885 struct target *target = get_current_target_or_null(cmd_ctx);
5887 Jim_SetResultString(interp, target_name(target), -1);
5891 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5894 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5897 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5898 for (unsigned x = 0; NULL != target_types[x]; x++) {
5899 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5900 Jim_NewStringObj(interp, target_types[x]->name, -1));
5905 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5908 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5911 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5912 struct target *target = all_targets;
5914 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5915 Jim_NewStringObj(interp, target_name(target), -1));
5916 target = target->next;
5921 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5924 const char *targetname;
5926 struct target *target = (struct target *) NULL;
5927 struct target_list *head, *curr, *new;
5928 curr = (struct target_list *) NULL;
5929 head = (struct target_list *) NULL;
5932 LOG_DEBUG("%d", argc);
5933 /* argv[1] = target to associate in smp
5934 * argv[2] = target to associate in smp
5938 for (i = 1; i < argc; i++) {
5940 targetname = Jim_GetString(argv[i], &len);
5941 target = get_target(targetname);
5942 LOG_DEBUG("%s ", targetname);
5944 new = malloc(sizeof(struct target_list));
5945 new->target = target;
5946 new->next = (struct target_list *)NULL;
5947 if (head == (struct target_list *)NULL) {
5956 /* now parse the list of cpu and put the target in smp mode*/
5959 while (curr != (struct target_list *)NULL) {
5960 target = curr->target;
5962 target->head = head;
5966 if (target && target->rtos)
5967 retval = rtos_smp_init(head->target);
5973 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5976 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5978 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5979 "<name> <target_type> [<target_options> ...]");
5982 return target_create(&goi);
5985 static const struct command_registration target_subcommand_handlers[] = {
5988 .mode = COMMAND_CONFIG,
5989 .handler = handle_target_init_command,
5990 .help = "initialize targets",
5995 .mode = COMMAND_CONFIG,
5996 .jim_handler = jim_target_create,
5997 .usage = "name type '-chain-position' name [options ...]",
5998 .help = "Creates and selects a new target",
6002 .mode = COMMAND_ANY,
6003 .jim_handler = jim_target_current,
6004 .help = "Returns the currently selected target",
6008 .mode = COMMAND_ANY,
6009 .jim_handler = jim_target_types,
6010 .help = "Returns the available target types as "
6011 "a list of strings",
6015 .mode = COMMAND_ANY,
6016 .jim_handler = jim_target_names,
6017 .help = "Returns the names of all targets as a list of strings",
6021 .mode = COMMAND_ANY,
6022 .jim_handler = jim_target_smp,
6023 .usage = "targetname1 targetname2 ...",
6024 .help = "gather several target in a smp list"
6027 COMMAND_REGISTRATION_DONE
6031 target_addr_t address;
6037 static int fastload_num;
6038 static struct FastLoad *fastload;
6040 static void free_fastload(void)
6042 if (fastload != NULL) {
6043 for (int i = 0; i < fastload_num; i++)
6044 free(fastload[i].data);
6050 COMMAND_HANDLER(handle_fast_load_image_command)
6054 uint32_t image_size;
6055 target_addr_t min_address = 0;
6056 target_addr_t max_address = -1;
6060 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
6061 &image, &min_address, &max_address);
6062 if (ERROR_OK != retval)
6065 struct duration bench;
6066 duration_start(&bench);
6068 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
6069 if (retval != ERROR_OK)
6074 fastload_num = image.num_sections;
6075 fastload = malloc(sizeof(struct FastLoad)*image.num_sections);
6076 if (fastload == NULL) {
6077 command_print(CMD, "out of memory");
6078 image_close(&image);
6081 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
6082 for (unsigned int i = 0; i < image.num_sections; i++) {
6083 buffer = malloc(image.sections[i].size);
6084 if (buffer == NULL) {
6085 command_print(CMD, "error allocating buffer for section (%d bytes)",
6086 (int)(image.sections[i].size));
6087 retval = ERROR_FAIL;
6091 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
6092 if (retval != ERROR_OK) {
6097 uint32_t offset = 0;
6098 uint32_t length = buf_cnt;
6100 /* DANGER!!! beware of unsigned comparison here!!! */
6102 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
6103 (image.sections[i].base_address < max_address)) {
6104 if (image.sections[i].base_address < min_address) {
6105 /* clip addresses below */
6106 offset += min_address-image.sections[i].base_address;
6110 if (image.sections[i].base_address + buf_cnt > max_address)
6111 length -= (image.sections[i].base_address + buf_cnt)-max_address;
6113 fastload[i].address = image.sections[i].base_address + offset;
6114 fastload[i].data = malloc(length);
6115 if (fastload[i].data == NULL) {
6117 command_print(CMD, "error allocating buffer for section (%" PRIu32 " bytes)",
6119 retval = ERROR_FAIL;
6122 memcpy(fastload[i].data, buffer + offset, length);
6123 fastload[i].length = length;
6125 image_size += length;
6126 command_print(CMD, "%u bytes written at address 0x%8.8x",
6127 (unsigned int)length,
6128 ((unsigned int)(image.sections[i].base_address + offset)));
6134 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
6135 command_print(CMD, "Loaded %" PRIu32 " bytes "
6136 "in %fs (%0.3f KiB/s)", image_size,
6137 duration_elapsed(&bench), duration_kbps(&bench, image_size));
6140 "WARNING: image has not been loaded to target!"
6141 "You can issue a 'fast_load' to finish loading.");
6144 image_close(&image);
6146 if (retval != ERROR_OK)
6152 COMMAND_HANDLER(handle_fast_load_command)
6155 return ERROR_COMMAND_SYNTAX_ERROR;
6156 if (fastload == NULL) {
6157 LOG_ERROR("No image in memory");
6161 int64_t ms = timeval_ms();
6163 int retval = ERROR_OK;
6164 for (i = 0; i < fastload_num; i++) {
6165 struct target *target = get_current_target(CMD_CTX);
6166 command_print(CMD, "Write to 0x%08x, length 0x%08x",
6167 (unsigned int)(fastload[i].address),
6168 (unsigned int)(fastload[i].length));
6169 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
6170 if (retval != ERROR_OK)
6172 size += fastload[i].length;
6174 if (retval == ERROR_OK) {
6175 int64_t after = timeval_ms();
6176 command_print(CMD, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
6181 static const struct command_registration target_command_handlers[] = {
6184 .handler = handle_targets_command,
6185 .mode = COMMAND_ANY,
6186 .help = "change current default target (one parameter) "
6187 "or prints table of all targets (no parameters)",
6188 .usage = "[target]",
6192 .mode = COMMAND_CONFIG,
6193 .help = "configure target",
6194 .chain = target_subcommand_handlers,
6197 COMMAND_REGISTRATION_DONE
6200 int target_register_commands(struct command_context *cmd_ctx)
6202 return register_commands(cmd_ctx, NULL, target_command_handlers);
6205 static bool target_reset_nag = true;
6207 bool get_target_reset_nag(void)
6209 return target_reset_nag;
6212 COMMAND_HANDLER(handle_target_reset_nag)
6214 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
6215 &target_reset_nag, "Nag after each reset about options to improve "
6219 COMMAND_HANDLER(handle_ps_command)
6221 struct target *target = get_current_target(CMD_CTX);
6223 if (target->state != TARGET_HALTED) {
6224 LOG_INFO("target not halted !!");
6228 if ((target->rtos) && (target->rtos->type)
6229 && (target->rtos->type->ps_command)) {
6230 display = target->rtos->type->ps_command(target);
6231 command_print(CMD, "%s", display);
6236 return ERROR_TARGET_FAILURE;
6240 static void binprint(struct command_invocation *cmd, const char *text, const uint8_t *buf, int size)
6243 command_print_sameline(cmd, "%s", text);
6244 for (int i = 0; i < size; i++)
6245 command_print_sameline(cmd, " %02x", buf[i]);
6246 command_print(cmd, " ");
6249 COMMAND_HANDLER(handle_test_mem_access_command)
6251 struct target *target = get_current_target(CMD_CTX);
6253 int retval = ERROR_OK;
6255 if (target->state != TARGET_HALTED) {
6256 LOG_INFO("target not halted !!");
6261 return ERROR_COMMAND_SYNTAX_ERROR;
6263 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
6266 size_t num_bytes = test_size + 4;
6268 struct working_area *wa = NULL;
6269 retval = target_alloc_working_area(target, num_bytes, &wa);
6270 if (retval != ERROR_OK) {
6271 LOG_ERROR("Not enough working area");
6275 uint8_t *test_pattern = malloc(num_bytes);
6277 for (size_t i = 0; i < num_bytes; i++)
6278 test_pattern[i] = rand();
6280 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6281 if (retval != ERROR_OK) {
6282 LOG_ERROR("Test pattern write failed");
6286 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6287 for (int size = 1; size <= 4; size *= 2) {
6288 for (int offset = 0; offset < 4; offset++) {
6289 uint32_t count = test_size / size;
6290 size_t host_bufsiz = (count + 2) * size + host_offset;
6291 uint8_t *read_ref = malloc(host_bufsiz);
6292 uint8_t *read_buf = malloc(host_bufsiz);
6294 for (size_t i = 0; i < host_bufsiz; i++) {
6295 read_ref[i] = rand();
6296 read_buf[i] = read_ref[i];
6298 command_print_sameline(CMD,
6299 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
6300 size, offset, host_offset ? "un" : "");
6302 struct duration bench;
6303 duration_start(&bench);
6305 retval = target_read_memory(target, wa->address + offset, size, count,
6306 read_buf + size + host_offset);
6308 duration_measure(&bench);
6310 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6311 command_print(CMD, "Unsupported alignment");
6313 } else if (retval != ERROR_OK) {
6314 command_print(CMD, "Memory read failed");
6318 /* replay on host */
6319 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
6322 int result = memcmp(read_ref, read_buf, host_bufsiz);
6324 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6325 duration_elapsed(&bench),
6326 duration_kbps(&bench, count * size));
6328 command_print(CMD, "Compare failed");
6329 binprint(CMD, "ref:", read_ref, host_bufsiz);
6330 binprint(CMD, "buf:", read_buf, host_bufsiz);
6343 target_free_working_area(target, wa);
6346 num_bytes = test_size + 4 + 4 + 4;
6348 retval = target_alloc_working_area(target, num_bytes, &wa);
6349 if (retval != ERROR_OK) {
6350 LOG_ERROR("Not enough working area");
6354 test_pattern = malloc(num_bytes);
6356 for (size_t i = 0; i < num_bytes; i++)
6357 test_pattern[i] = rand();
6359 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6360 for (int size = 1; size <= 4; size *= 2) {
6361 for (int offset = 0; offset < 4; offset++) {
6362 uint32_t count = test_size / size;
6363 size_t host_bufsiz = count * size + host_offset;
6364 uint8_t *read_ref = malloc(num_bytes);
6365 uint8_t *read_buf = malloc(num_bytes);
6366 uint8_t *write_buf = malloc(host_bufsiz);
6368 for (size_t i = 0; i < host_bufsiz; i++)
6369 write_buf[i] = rand();
6370 command_print_sameline(CMD,
6371 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
6372 size, offset, host_offset ? "un" : "");
6374 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6375 if (retval != ERROR_OK) {
6376 command_print(CMD, "Test pattern write failed");
6380 /* replay on host */
6381 memcpy(read_ref, test_pattern, num_bytes);
6382 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
6384 struct duration bench;
6385 duration_start(&bench);
6387 retval = target_write_memory(target, wa->address + size + offset, size, count,
6388 write_buf + host_offset);
6390 duration_measure(&bench);
6392 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6393 command_print(CMD, "Unsupported alignment");
6395 } else if (retval != ERROR_OK) {
6396 command_print(CMD, "Memory write failed");
6401 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
6402 if (retval != ERROR_OK) {
6403 command_print(CMD, "Test pattern write failed");
6408 int result = memcmp(read_ref, read_buf, num_bytes);
6410 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6411 duration_elapsed(&bench),
6412 duration_kbps(&bench, count * size));
6414 command_print(CMD, "Compare failed");
6415 binprint(CMD, "ref:", read_ref, num_bytes);
6416 binprint(CMD, "buf:", read_buf, num_bytes);
6428 target_free_working_area(target, wa);
6432 static const struct command_registration target_exec_command_handlers[] = {
6434 .name = "fast_load_image",
6435 .handler = handle_fast_load_image_command,
6436 .mode = COMMAND_ANY,
6437 .help = "Load image into server memory for later use by "
6438 "fast_load; primarily for profiling",
6439 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6440 "[min_address [max_length]]",
6443 .name = "fast_load",
6444 .handler = handle_fast_load_command,
6445 .mode = COMMAND_EXEC,
6446 .help = "loads active fast load image to current target "
6447 "- mainly for profiling purposes",
6452 .handler = handle_profile_command,
6453 .mode = COMMAND_EXEC,
6454 .usage = "seconds filename [start end]",
6455 .help = "profiling samples the CPU PC",
6457 /** @todo don't register virt2phys() unless target supports it */
6459 .name = "virt2phys",
6460 .handler = handle_virt2phys_command,
6461 .mode = COMMAND_ANY,
6462 .help = "translate a virtual address into a physical address",
6463 .usage = "virtual_address",
6467 .handler = handle_reg_command,
6468 .mode = COMMAND_EXEC,
6469 .help = "display (reread from target with \"force\") or set a register; "
6470 "with no arguments, displays all registers and their values",
6471 .usage = "[(register_number|register_name) [(value|'force')]]",
6475 .handler = handle_poll_command,
6476 .mode = COMMAND_EXEC,
6477 .help = "poll target state; or reconfigure background polling",
6478 .usage = "['on'|'off']",
6481 .name = "wait_halt",
6482 .handler = handle_wait_halt_command,
6483 .mode = COMMAND_EXEC,
6484 .help = "wait up to the specified number of milliseconds "
6485 "(default 5000) for a previously requested halt",
6486 .usage = "[milliseconds]",
6490 .handler = handle_halt_command,
6491 .mode = COMMAND_EXEC,
6492 .help = "request target to halt, then wait up to the specified "
6493 "number of milliseconds (default 5000) for it to complete",
6494 .usage = "[milliseconds]",
6498 .handler = handle_resume_command,
6499 .mode = COMMAND_EXEC,
6500 .help = "resume target execution from current PC or address",
6501 .usage = "[address]",
6505 .handler = handle_reset_command,
6506 .mode = COMMAND_EXEC,
6507 .usage = "[run|halt|init]",
6508 .help = "Reset all targets into the specified mode. "
6509 "Default reset mode is run, if not given.",
6512 .name = "soft_reset_halt",
6513 .handler = handle_soft_reset_halt_command,
6514 .mode = COMMAND_EXEC,
6516 .help = "halt the target and do a soft reset",
6520 .handler = handle_step_command,
6521 .mode = COMMAND_EXEC,
6522 .help = "step one instruction from current PC or address",
6523 .usage = "[address]",
6527 .handler = handle_md_command,
6528 .mode = COMMAND_EXEC,
6529 .help = "display memory double-words",
6530 .usage = "['phys'] address [count]",
6534 .handler = handle_md_command,
6535 .mode = COMMAND_EXEC,
6536 .help = "display memory words",
6537 .usage = "['phys'] address [count]",
6541 .handler = handle_md_command,
6542 .mode = COMMAND_EXEC,
6543 .help = "display memory half-words",
6544 .usage = "['phys'] address [count]",
6548 .handler = handle_md_command,
6549 .mode = COMMAND_EXEC,
6550 .help = "display memory bytes",
6551 .usage = "['phys'] address [count]",
6555 .handler = handle_mw_command,
6556 .mode = COMMAND_EXEC,
6557 .help = "write memory double-word",
6558 .usage = "['phys'] address value [count]",
6562 .handler = handle_mw_command,
6563 .mode = COMMAND_EXEC,
6564 .help = "write memory word",
6565 .usage = "['phys'] address value [count]",
6569 .handler = handle_mw_command,
6570 .mode = COMMAND_EXEC,
6571 .help = "write memory half-word",
6572 .usage = "['phys'] address value [count]",
6576 .handler = handle_mw_command,
6577 .mode = COMMAND_EXEC,
6578 .help = "write memory byte",
6579 .usage = "['phys'] address value [count]",
6583 .handler = handle_bp_command,
6584 .mode = COMMAND_EXEC,
6585 .help = "list or set hardware or software breakpoint",
6586 .usage = "[<address> [<asid>] <length> ['hw'|'hw_ctx']]",
6590 .handler = handle_rbp_command,
6591 .mode = COMMAND_EXEC,
6592 .help = "remove breakpoint",
6593 .usage = "'all' | address",
6597 .handler = handle_wp_command,
6598 .mode = COMMAND_EXEC,
6599 .help = "list (no params) or create watchpoints",
6600 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
6604 .handler = handle_rwp_command,
6605 .mode = COMMAND_EXEC,
6606 .help = "remove watchpoint",
6610 .name = "load_image",
6611 .handler = handle_load_image_command,
6612 .mode = COMMAND_EXEC,
6613 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6614 "[min_address] [max_length]",
6617 .name = "dump_image",
6618 .handler = handle_dump_image_command,
6619 .mode = COMMAND_EXEC,
6620 .usage = "filename address size",
6623 .name = "verify_image_checksum",
6624 .handler = handle_verify_image_checksum_command,
6625 .mode = COMMAND_EXEC,
6626 .usage = "filename [offset [type]]",
6629 .name = "verify_image",
6630 .handler = handle_verify_image_command,
6631 .mode = COMMAND_EXEC,
6632 .usage = "filename [offset [type]]",
6635 .name = "test_image",
6636 .handler = handle_test_image_command,
6637 .mode = COMMAND_EXEC,
6638 .usage = "filename [offset [type]]",
6641 .name = "mem2array",
6642 .mode = COMMAND_EXEC,
6643 .jim_handler = jim_mem2array,
6644 .help = "read 8/16/32 bit memory and return as a TCL array "
6645 "for script processing",
6646 .usage = "arrayname bitwidth address count",
6649 .name = "array2mem",
6650 .mode = COMMAND_EXEC,
6651 .jim_handler = jim_array2mem,
6652 .help = "convert a TCL array to memory locations "
6653 "and write the 8/16/32 bit values",
6654 .usage = "arrayname bitwidth address count",
6657 .name = "reset_nag",
6658 .handler = handle_target_reset_nag,
6659 .mode = COMMAND_ANY,
6660 .help = "Nag after each reset about options that could have been "
6661 "enabled to improve performance. ",
6662 .usage = "['enable'|'disable']",
6666 .handler = handle_ps_command,
6667 .mode = COMMAND_EXEC,
6668 .help = "list all tasks ",
6672 .name = "test_mem_access",
6673 .handler = handle_test_mem_access_command,
6674 .mode = COMMAND_EXEC,
6675 .help = "Test the target's memory access functions",
6679 COMMAND_REGISTRATION_DONE
6681 static int target_register_user_commands(struct command_context *cmd_ctx)
6683 int retval = ERROR_OK;
6684 retval = target_request_register_commands(cmd_ctx);
6685 if (retval != ERROR_OK)
6688 retval = trace_register_commands(cmd_ctx);
6689 if (retval != ERROR_OK)
6693 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);