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 int64_t target_timer_next_event_value;
158 static LIST_HEAD(target_reset_callback_list);
159 static LIST_HEAD(target_trace_callback_list);
160 static const int polling_interval = TARGET_DEFAULT_POLLING_INTERVAL;
162 static const struct jim_nvp nvp_assert[] = {
163 { .name = "assert", NVP_ASSERT },
164 { .name = "deassert", NVP_DEASSERT },
165 { .name = "T", NVP_ASSERT },
166 { .name = "F", NVP_DEASSERT },
167 { .name = "t", NVP_ASSERT },
168 { .name = "f", NVP_DEASSERT },
169 { .name = NULL, .value = -1 }
172 static const struct jim_nvp nvp_error_target[] = {
173 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
174 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
175 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
176 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
177 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
178 { .value = ERROR_TARGET_UNALIGNED_ACCESS, .name = "err-unaligned-access" },
179 { .value = ERROR_TARGET_DATA_ABORT, .name = "err-data-abort" },
180 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE, .name = "err-resource-not-available" },
181 { .value = ERROR_TARGET_TRANSLATION_FAULT, .name = "err-translation-fault" },
182 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
183 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
184 { .value = -1, .name = NULL }
187 static const char *target_strerror_safe(int err)
189 const struct jim_nvp *n;
191 n = jim_nvp_value2name_simple(nvp_error_target, err);
198 static const struct jim_nvp nvp_target_event[] = {
200 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
201 { .value = TARGET_EVENT_HALTED, .name = "halted" },
202 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
203 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
204 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
205 { .value = TARGET_EVENT_STEP_START, .name = "step-start" },
206 { .value = TARGET_EVENT_STEP_END, .name = "step-end" },
208 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
209 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
211 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
212 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
213 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
214 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
215 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
216 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
217 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
218 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
220 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
221 { .value = TARGET_EVENT_EXAMINE_FAIL, .name = "examine-fail" },
222 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
224 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
225 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
227 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
228 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
230 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
231 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END, .name = "gdb-flash-write-end" },
233 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
234 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END, .name = "gdb-flash-erase-end" },
236 { .value = TARGET_EVENT_TRACE_CONFIG, .name = "trace-config" },
238 { .name = NULL, .value = -1 }
241 static const struct jim_nvp nvp_target_state[] = {
242 { .name = "unknown", .value = TARGET_UNKNOWN },
243 { .name = "running", .value = TARGET_RUNNING },
244 { .name = "halted", .value = TARGET_HALTED },
245 { .name = "reset", .value = TARGET_RESET },
246 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
247 { .name = NULL, .value = -1 },
250 static const struct jim_nvp nvp_target_debug_reason[] = {
251 { .name = "debug-request", .value = DBG_REASON_DBGRQ },
252 { .name = "breakpoint", .value = DBG_REASON_BREAKPOINT },
253 { .name = "watchpoint", .value = DBG_REASON_WATCHPOINT },
254 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
255 { .name = "single-step", .value = DBG_REASON_SINGLESTEP },
256 { .name = "target-not-halted", .value = DBG_REASON_NOTHALTED },
257 { .name = "program-exit", .value = DBG_REASON_EXIT },
258 { .name = "exception-catch", .value = DBG_REASON_EXC_CATCH },
259 { .name = "undefined", .value = DBG_REASON_UNDEFINED },
260 { .name = NULL, .value = -1 },
263 static const struct jim_nvp nvp_target_endian[] = {
264 { .name = "big", .value = TARGET_BIG_ENDIAN },
265 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
266 { .name = "be", .value = TARGET_BIG_ENDIAN },
267 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
268 { .name = NULL, .value = -1 },
271 static const struct jim_nvp nvp_reset_modes[] = {
272 { .name = "unknown", .value = RESET_UNKNOWN },
273 { .name = "run", .value = RESET_RUN },
274 { .name = "halt", .value = RESET_HALT },
275 { .name = "init", .value = RESET_INIT },
276 { .name = NULL, .value = -1 },
279 const char *debug_reason_name(struct target *t)
283 cp = jim_nvp_value2name_simple(nvp_target_debug_reason,
284 t->debug_reason)->name;
286 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
287 cp = "(*BUG*unknown*BUG*)";
292 const char *target_state_name(struct target *t)
295 cp = jim_nvp_value2name_simple(nvp_target_state, t->state)->name;
297 LOG_ERROR("Invalid target state: %d", (int)(t->state));
298 cp = "(*BUG*unknown*BUG*)";
301 if (!target_was_examined(t) && t->defer_examine)
302 cp = "examine deferred";
307 const char *target_event_name(enum target_event event)
310 cp = jim_nvp_value2name_simple(nvp_target_event, event)->name;
312 LOG_ERROR("Invalid target event: %d", (int)(event));
313 cp = "(*BUG*unknown*BUG*)";
318 const char *target_reset_mode_name(enum target_reset_mode reset_mode)
321 cp = jim_nvp_value2name_simple(nvp_reset_modes, reset_mode)->name;
323 LOG_ERROR("Invalid target reset mode: %d", (int)(reset_mode));
324 cp = "(*BUG*unknown*BUG*)";
329 /* determine the number of the new target */
330 static int new_target_number(void)
335 /* number is 0 based */
339 if (x < t->target_number)
340 x = t->target_number;
346 static void append_to_list_all_targets(struct target *target)
348 struct target **t = &all_targets;
355 /* read a uint64_t from a buffer in target memory endianness */
356 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
358 if (target->endianness == TARGET_LITTLE_ENDIAN)
359 return le_to_h_u64(buffer);
361 return be_to_h_u64(buffer);
364 /* read a uint32_t from a buffer in target memory endianness */
365 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
367 if (target->endianness == TARGET_LITTLE_ENDIAN)
368 return le_to_h_u32(buffer);
370 return be_to_h_u32(buffer);
373 /* read a uint24_t from a buffer in target memory endianness */
374 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
376 if (target->endianness == TARGET_LITTLE_ENDIAN)
377 return le_to_h_u24(buffer);
379 return be_to_h_u24(buffer);
382 /* read a uint16_t from a buffer in target memory endianness */
383 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
385 if (target->endianness == TARGET_LITTLE_ENDIAN)
386 return le_to_h_u16(buffer);
388 return be_to_h_u16(buffer);
391 /* write a uint64_t to a buffer in target memory endianness */
392 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
394 if (target->endianness == TARGET_LITTLE_ENDIAN)
395 h_u64_to_le(buffer, value);
397 h_u64_to_be(buffer, value);
400 /* write a uint32_t to a buffer in target memory endianness */
401 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
403 if (target->endianness == TARGET_LITTLE_ENDIAN)
404 h_u32_to_le(buffer, value);
406 h_u32_to_be(buffer, value);
409 /* write a uint24_t to a buffer in target memory endianness */
410 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
412 if (target->endianness == TARGET_LITTLE_ENDIAN)
413 h_u24_to_le(buffer, value);
415 h_u24_to_be(buffer, value);
418 /* write a uint16_t to a buffer in target memory endianness */
419 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
421 if (target->endianness == TARGET_LITTLE_ENDIAN)
422 h_u16_to_le(buffer, value);
424 h_u16_to_be(buffer, value);
427 /* write a uint8_t to a buffer in target memory endianness */
428 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
433 /* write a uint64_t array to a buffer in target memory endianness */
434 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
437 for (i = 0; i < count; i++)
438 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
441 /* write a uint32_t array to a buffer in target memory endianness */
442 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
445 for (i = 0; i < count; i++)
446 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
449 /* write a uint16_t array to a buffer in target memory endianness */
450 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
453 for (i = 0; i < count; i++)
454 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
457 /* write a uint64_t array to a buffer in target memory endianness */
458 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
461 for (i = 0; i < count; i++)
462 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
465 /* write a uint32_t array to a buffer in target memory endianness */
466 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
469 for (i = 0; i < count; i++)
470 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
473 /* write a uint16_t array to a buffer in target memory endianness */
474 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
477 for (i = 0; i < count; i++)
478 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
481 /* return a pointer to a configured target; id is name or number */
482 struct target *get_target(const char *id)
484 struct target *target;
486 /* try as tcltarget name */
487 for (target = all_targets; target; target = target->next) {
488 if (!target_name(target))
490 if (strcmp(id, target_name(target)) == 0)
494 /* It's OK to remove this fallback sometime after August 2010 or so */
496 /* no match, try as number */
498 if (parse_uint(id, &num) != ERROR_OK)
501 for (target = all_targets; target; target = target->next) {
502 if (target->target_number == (int)num) {
503 LOG_WARNING("use '%s' as target identifier, not '%u'",
504 target_name(target), num);
512 /* returns a pointer to the n-th configured target */
513 struct target *get_target_by_num(int num)
515 struct target *target = all_targets;
518 if (target->target_number == num)
520 target = target->next;
526 struct target *get_current_target(struct command_context *cmd_ctx)
528 struct target *target = get_current_target_or_null(cmd_ctx);
531 LOG_ERROR("BUG: current_target out of bounds");
538 struct target *get_current_target_or_null(struct command_context *cmd_ctx)
540 return cmd_ctx->current_target_override
541 ? cmd_ctx->current_target_override
542 : cmd_ctx->current_target;
545 int target_poll(struct target *target)
549 /* We can't poll until after examine */
550 if (!target_was_examined(target)) {
551 /* Fail silently lest we pollute the log */
555 retval = target->type->poll(target);
556 if (retval != ERROR_OK)
559 if (target->halt_issued) {
560 if (target->state == TARGET_HALTED)
561 target->halt_issued = false;
563 int64_t t = timeval_ms() - target->halt_issued_time;
564 if (t > DEFAULT_HALT_TIMEOUT) {
565 target->halt_issued = false;
566 LOG_INFO("Halt timed out, wake up GDB.");
567 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
575 int target_halt(struct target *target)
578 /* We can't poll until after examine */
579 if (!target_was_examined(target)) {
580 LOG_ERROR("Target not examined yet");
584 retval = target->type->halt(target);
585 if (retval != ERROR_OK)
588 target->halt_issued = true;
589 target->halt_issued_time = timeval_ms();
595 * Make the target (re)start executing using its saved execution
596 * context (possibly with some modifications).
598 * @param target Which target should start executing.
599 * @param current True to use the target's saved program counter instead
600 * of the address parameter
601 * @param address Optionally used as the program counter.
602 * @param handle_breakpoints True iff breakpoints at the resumption PC
603 * should be skipped. (For example, maybe execution was stopped by
604 * such a breakpoint, in which case it would be counterproductive to
606 * @param debug_execution False if all working areas allocated by OpenOCD
607 * should be released and/or restored to their original contents.
608 * (This would for example be true to run some downloaded "helper"
609 * algorithm code, which resides in one such working buffer and uses
610 * another for data storage.)
612 * @todo Resolve the ambiguity about what the "debug_execution" flag
613 * signifies. For example, Target implementations don't agree on how
614 * it relates to invalidation of the register cache, or to whether
615 * breakpoints and watchpoints should be enabled. (It would seem wrong
616 * to enable breakpoints when running downloaded "helper" algorithms
617 * (debug_execution true), since the breakpoints would be set to match
618 * target firmware being debugged, not the helper algorithm.... and
619 * enabling them could cause such helpers to malfunction (for example,
620 * by overwriting data with a breakpoint instruction. On the other
621 * hand the infrastructure for running such helpers might use this
622 * procedure but rely on hardware breakpoint to detect termination.)
624 int target_resume(struct target *target, int current, target_addr_t address,
625 int handle_breakpoints, int debug_execution)
629 /* We can't poll until after examine */
630 if (!target_was_examined(target)) {
631 LOG_ERROR("Target not examined yet");
635 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
637 /* note that resume *must* be asynchronous. The CPU can halt before
638 * we poll. The CPU can even halt at the current PC as a result of
639 * a software breakpoint being inserted by (a bug?) the application.
642 * resume() triggers the event 'resumed'. The execution of TCL commands
643 * in the event handler causes the polling of targets. If the target has
644 * already halted for a breakpoint, polling will run the 'halted' event
645 * handler before the pending 'resumed' handler.
646 * Disable polling during resume() to guarantee the execution of handlers
647 * in the correct order.
649 bool save_poll = jtag_poll_get_enabled();
650 jtag_poll_set_enabled(false);
651 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
652 jtag_poll_set_enabled(save_poll);
653 if (retval != ERROR_OK)
656 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
661 static int target_process_reset(struct command_invocation *cmd, enum target_reset_mode reset_mode)
666 n = jim_nvp_value2name_simple(nvp_reset_modes, reset_mode);
668 LOG_ERROR("invalid reset mode");
672 struct target *target;
673 for (target = all_targets; target; target = target->next)
674 target_call_reset_callbacks(target, reset_mode);
676 /* disable polling during reset to make reset event scripts
677 * more predictable, i.e. dr/irscan & pathmove in events will
678 * not have JTAG operations injected into the middle of a sequence.
680 bool save_poll = jtag_poll_get_enabled();
682 jtag_poll_set_enabled(false);
684 sprintf(buf, "ocd_process_reset %s", n->name);
685 retval = Jim_Eval(cmd->ctx->interp, buf);
687 jtag_poll_set_enabled(save_poll);
689 if (retval != JIM_OK) {
690 Jim_MakeErrorMessage(cmd->ctx->interp);
691 command_print(cmd, "%s", Jim_GetString(Jim_GetResult(cmd->ctx->interp), NULL));
695 /* We want any events to be processed before the prompt */
696 retval = target_call_timer_callbacks_now();
698 for (target = all_targets; target; target = target->next) {
699 target->type->check_reset(target);
700 target->running_alg = false;
706 static int identity_virt2phys(struct target *target,
707 target_addr_t virtual, target_addr_t *physical)
713 static int no_mmu(struct target *target, int *enabled)
719 static int default_examine(struct target *target)
721 target_set_examined(target);
725 /* no check by default */
726 static int default_check_reset(struct target *target)
731 /* Equivalent Tcl code arp_examine_one is in src/target/startup.tcl
733 int target_examine_one(struct target *target)
735 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
737 int retval = target->type->examine(target);
738 if (retval != ERROR_OK) {
739 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_FAIL);
743 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
748 static int jtag_enable_callback(enum jtag_event event, void *priv)
750 struct target *target = priv;
752 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
755 jtag_unregister_event_callback(jtag_enable_callback, target);
757 return target_examine_one(target);
760 /* Targets that correctly implement init + examine, i.e.
761 * no communication with target during init:
765 int target_examine(void)
767 int retval = ERROR_OK;
768 struct target *target;
770 for (target = all_targets; target; target = target->next) {
771 /* defer examination, but don't skip it */
772 if (!target->tap->enabled) {
773 jtag_register_event_callback(jtag_enable_callback,
778 if (target->defer_examine)
781 int retval2 = target_examine_one(target);
782 if (retval2 != ERROR_OK) {
783 LOG_WARNING("target %s examination failed", target_name(target));
790 const char *target_type_name(struct target *target)
792 return target->type->name;
795 static int target_soft_reset_halt(struct target *target)
797 if (!target_was_examined(target)) {
798 LOG_ERROR("Target not examined yet");
801 if (!target->type->soft_reset_halt) {
802 LOG_ERROR("Target %s does not support soft_reset_halt",
803 target_name(target));
806 return target->type->soft_reset_halt(target);
810 * Downloads a target-specific native code algorithm to the target,
811 * and executes it. * Note that some targets may need to set up, enable,
812 * and tear down a breakpoint (hard or * soft) to detect algorithm
813 * termination, while others may support lower overhead schemes where
814 * soft breakpoints embedded in the algorithm automatically terminate the
817 * @param target used to run the algorithm
818 * @param num_mem_params
820 * @param num_reg_params
825 * @param arch_info target-specific description of the algorithm.
827 int target_run_algorithm(struct target *target,
828 int num_mem_params, struct mem_param *mem_params,
829 int num_reg_params, struct reg_param *reg_param,
830 uint32_t entry_point, uint32_t exit_point,
831 int timeout_ms, void *arch_info)
833 int retval = ERROR_FAIL;
835 if (!target_was_examined(target)) {
836 LOG_ERROR("Target not examined yet");
839 if (!target->type->run_algorithm) {
840 LOG_ERROR("Target type '%s' does not support %s",
841 target_type_name(target), __func__);
845 target->running_alg = true;
846 retval = target->type->run_algorithm(target,
847 num_mem_params, mem_params,
848 num_reg_params, reg_param,
849 entry_point, exit_point, timeout_ms, arch_info);
850 target->running_alg = false;
857 * Executes a target-specific native code algorithm and leaves it running.
859 * @param target used to run the algorithm
860 * @param num_mem_params
862 * @param num_reg_params
866 * @param arch_info target-specific description of the algorithm.
868 int target_start_algorithm(struct target *target,
869 int num_mem_params, struct mem_param *mem_params,
870 int num_reg_params, struct reg_param *reg_params,
871 uint32_t entry_point, uint32_t exit_point,
874 int retval = ERROR_FAIL;
876 if (!target_was_examined(target)) {
877 LOG_ERROR("Target not examined yet");
880 if (!target->type->start_algorithm) {
881 LOG_ERROR("Target type '%s' does not support %s",
882 target_type_name(target), __func__);
885 if (target->running_alg) {
886 LOG_ERROR("Target is already running an algorithm");
890 target->running_alg = true;
891 retval = target->type->start_algorithm(target,
892 num_mem_params, mem_params,
893 num_reg_params, reg_params,
894 entry_point, exit_point, arch_info);
901 * Waits for an algorithm started with target_start_algorithm() to complete.
903 * @param target used to run the algorithm
904 * @param num_mem_params
906 * @param num_reg_params
910 * @param arch_info target-specific description of the algorithm.
912 int target_wait_algorithm(struct target *target,
913 int num_mem_params, struct mem_param *mem_params,
914 int num_reg_params, struct reg_param *reg_params,
915 uint32_t exit_point, int timeout_ms,
918 int retval = ERROR_FAIL;
920 if (!target->type->wait_algorithm) {
921 LOG_ERROR("Target type '%s' does not support %s",
922 target_type_name(target), __func__);
925 if (!target->running_alg) {
926 LOG_ERROR("Target is not running an algorithm");
930 retval = target->type->wait_algorithm(target,
931 num_mem_params, mem_params,
932 num_reg_params, reg_params,
933 exit_point, timeout_ms, arch_info);
934 if (retval != ERROR_TARGET_TIMEOUT)
935 target->running_alg = false;
942 * Streams data to a circular buffer on target intended for consumption by code
943 * running asynchronously on target.
945 * This is intended for applications where target-specific native code runs
946 * on the target, receives data from the circular buffer, does something with
947 * it (most likely writing it to a flash memory), and advances the circular
950 * This assumes that the helper algorithm has already been loaded to the target,
951 * but has not been started yet. Given memory and register parameters are passed
954 * The buffer is defined by (buffer_start, buffer_size) arguments and has the
957 * [buffer_start + 0, buffer_start + 4):
958 * Write Pointer address (aka head). Written and updated by this
959 * routine when new data is written to the circular buffer.
960 * [buffer_start + 4, buffer_start + 8):
961 * Read Pointer address (aka tail). Updated by code running on the
962 * target after it consumes data.
963 * [buffer_start + 8, buffer_start + buffer_size):
964 * Circular buffer contents.
966 * See contrib/loaders/flash/stm32f1x.S for an example.
968 * @param target used to run the algorithm
969 * @param buffer address on the host where data to be sent is located
970 * @param count number of blocks to send
971 * @param block_size size in bytes of each block
972 * @param num_mem_params count of memory-based params to pass to algorithm
973 * @param mem_params memory-based params to pass to algorithm
974 * @param num_reg_params count of register-based params to pass to algorithm
975 * @param reg_params memory-based params to pass to algorithm
976 * @param buffer_start address on the target of the circular buffer structure
977 * @param buffer_size size of the circular buffer structure
978 * @param entry_point address on the target to execute to start the algorithm
979 * @param exit_point address at which to set a breakpoint to catch the
980 * end of the algorithm; can be 0 if target triggers a breakpoint itself
984 int target_run_flash_async_algorithm(struct target *target,
985 const uint8_t *buffer, uint32_t count, int block_size,
986 int num_mem_params, struct mem_param *mem_params,
987 int num_reg_params, struct reg_param *reg_params,
988 uint32_t buffer_start, uint32_t buffer_size,
989 uint32_t entry_point, uint32_t exit_point, void *arch_info)
994 const uint8_t *buffer_orig = buffer;
996 /* Set up working area. First word is write pointer, second word is read pointer,
997 * rest is fifo data area. */
998 uint32_t wp_addr = buffer_start;
999 uint32_t rp_addr = buffer_start + 4;
1000 uint32_t fifo_start_addr = buffer_start + 8;
1001 uint32_t fifo_end_addr = buffer_start + buffer_size;
1003 uint32_t wp = fifo_start_addr;
1004 uint32_t rp = fifo_start_addr;
1006 /* validate block_size is 2^n */
1007 assert(!block_size || !(block_size & (block_size - 1)));
1009 retval = target_write_u32(target, wp_addr, wp);
1010 if (retval != ERROR_OK)
1012 retval = target_write_u32(target, rp_addr, rp);
1013 if (retval != ERROR_OK)
1016 /* Start up algorithm on target and let it idle while writing the first chunk */
1017 retval = target_start_algorithm(target, num_mem_params, mem_params,
1018 num_reg_params, reg_params,
1023 if (retval != ERROR_OK) {
1024 LOG_ERROR("error starting target flash write algorithm");
1030 retval = target_read_u32(target, rp_addr, &rp);
1031 if (retval != ERROR_OK) {
1032 LOG_ERROR("failed to get read pointer");
1036 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1037 (size_t) (buffer - buffer_orig), count, wp, rp);
1040 LOG_ERROR("flash write algorithm aborted by target");
1041 retval = ERROR_FLASH_OPERATION_FAILED;
1045 if (((rp - fifo_start_addr) & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
1046 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
1050 /* Count the number of bytes available in the fifo without
1051 * crossing the wrap around. Make sure to not fill it completely,
1052 * because that would make wp == rp and that's the empty condition. */
1053 uint32_t thisrun_bytes;
1055 thisrun_bytes = rp - wp - block_size;
1056 else if (rp > fifo_start_addr)
1057 thisrun_bytes = fifo_end_addr - wp;
1059 thisrun_bytes = fifo_end_addr - wp - block_size;
1061 if (thisrun_bytes == 0) {
1062 /* Throttle polling a bit if transfer is (much) faster than flash
1063 * programming. The exact delay shouldn't matter as long as it's
1064 * less than buffer size / flash speed. This is very unlikely to
1065 * run when using high latency connections such as USB. */
1068 /* to stop an infinite loop on some targets check and increment a timeout
1069 * this issue was observed on a stellaris using the new ICDI interface */
1070 if (timeout++ >= 2500) {
1071 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1072 return ERROR_FLASH_OPERATION_FAILED;
1077 /* reset our timeout */
1080 /* Limit to the amount of data we actually want to write */
1081 if (thisrun_bytes > count * block_size)
1082 thisrun_bytes = count * block_size;
1084 /* Force end of large blocks to be word aligned */
1085 if (thisrun_bytes >= 16)
1086 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1088 /* Write data to fifo */
1089 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
1090 if (retval != ERROR_OK)
1093 /* Update counters and wrap write pointer */
1094 buffer += thisrun_bytes;
1095 count -= thisrun_bytes / block_size;
1096 wp += thisrun_bytes;
1097 if (wp >= fifo_end_addr)
1098 wp = fifo_start_addr;
1100 /* Store updated write pointer to target */
1101 retval = target_write_u32(target, wp_addr, wp);
1102 if (retval != ERROR_OK)
1105 /* Avoid GDB timeouts */
1109 if (retval != ERROR_OK) {
1110 /* abort flash write algorithm on target */
1111 target_write_u32(target, wp_addr, 0);
1114 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1115 num_reg_params, reg_params,
1120 if (retval2 != ERROR_OK) {
1121 LOG_ERROR("error waiting for target flash write algorithm");
1125 if (retval == ERROR_OK) {
1126 /* check if algorithm set rp = 0 after fifo writer loop finished */
1127 retval = target_read_u32(target, rp_addr, &rp);
1128 if (retval == ERROR_OK && rp == 0) {
1129 LOG_ERROR("flash write algorithm aborted by target");
1130 retval = ERROR_FLASH_OPERATION_FAILED;
1137 int target_run_read_async_algorithm(struct target *target,
1138 uint8_t *buffer, uint32_t count, int block_size,
1139 int num_mem_params, struct mem_param *mem_params,
1140 int num_reg_params, struct reg_param *reg_params,
1141 uint32_t buffer_start, uint32_t buffer_size,
1142 uint32_t entry_point, uint32_t exit_point, void *arch_info)
1147 const uint8_t *buffer_orig = buffer;
1149 /* Set up working area. First word is write pointer, second word is read pointer,
1150 * rest is fifo data area. */
1151 uint32_t wp_addr = buffer_start;
1152 uint32_t rp_addr = buffer_start + 4;
1153 uint32_t fifo_start_addr = buffer_start + 8;
1154 uint32_t fifo_end_addr = buffer_start + buffer_size;
1156 uint32_t wp = fifo_start_addr;
1157 uint32_t rp = fifo_start_addr;
1159 /* validate block_size is 2^n */
1160 assert(!block_size || !(block_size & (block_size - 1)));
1162 retval = target_write_u32(target, wp_addr, wp);
1163 if (retval != ERROR_OK)
1165 retval = target_write_u32(target, rp_addr, rp);
1166 if (retval != ERROR_OK)
1169 /* Start up algorithm on target */
1170 retval = target_start_algorithm(target, num_mem_params, mem_params,
1171 num_reg_params, reg_params,
1176 if (retval != ERROR_OK) {
1177 LOG_ERROR("error starting target flash read algorithm");
1182 retval = target_read_u32(target, wp_addr, &wp);
1183 if (retval != ERROR_OK) {
1184 LOG_ERROR("failed to get write pointer");
1188 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1189 (size_t)(buffer - buffer_orig), count, wp, rp);
1192 LOG_ERROR("flash read algorithm aborted by target");
1193 retval = ERROR_FLASH_OPERATION_FAILED;
1197 if (((wp - fifo_start_addr) & (block_size - 1)) || wp < fifo_start_addr || wp >= fifo_end_addr) {
1198 LOG_ERROR("corrupted fifo write pointer 0x%" PRIx32, wp);
1202 /* Count the number of bytes available in the fifo without
1203 * crossing the wrap around. */
1204 uint32_t thisrun_bytes;
1206 thisrun_bytes = wp - rp;
1208 thisrun_bytes = fifo_end_addr - rp;
1210 if (thisrun_bytes == 0) {
1211 /* Throttle polling a bit if transfer is (much) faster than flash
1212 * reading. The exact delay shouldn't matter as long as it's
1213 * less than buffer size / flash speed. This is very unlikely to
1214 * run when using high latency connections such as USB. */
1217 /* to stop an infinite loop on some targets check and increment a timeout
1218 * this issue was observed on a stellaris using the new ICDI interface */
1219 if (timeout++ >= 2500) {
1220 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1221 return ERROR_FLASH_OPERATION_FAILED;
1226 /* Reset our timeout */
1229 /* Limit to the amount of data we actually want to read */
1230 if (thisrun_bytes > count * block_size)
1231 thisrun_bytes = count * block_size;
1233 /* Force end of large blocks to be word aligned */
1234 if (thisrun_bytes >= 16)
1235 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1237 /* Read data from fifo */
1238 retval = target_read_buffer(target, rp, thisrun_bytes, buffer);
1239 if (retval != ERROR_OK)
1242 /* Update counters and wrap write pointer */
1243 buffer += thisrun_bytes;
1244 count -= thisrun_bytes / block_size;
1245 rp += thisrun_bytes;
1246 if (rp >= fifo_end_addr)
1247 rp = fifo_start_addr;
1249 /* Store updated write pointer to target */
1250 retval = target_write_u32(target, rp_addr, rp);
1251 if (retval != ERROR_OK)
1254 /* Avoid GDB timeouts */
1259 if (retval != ERROR_OK) {
1260 /* abort flash write algorithm on target */
1261 target_write_u32(target, rp_addr, 0);
1264 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1265 num_reg_params, reg_params,
1270 if (retval2 != ERROR_OK) {
1271 LOG_ERROR("error waiting for target flash write algorithm");
1275 if (retval == ERROR_OK) {
1276 /* check if algorithm set wp = 0 after fifo writer loop finished */
1277 retval = target_read_u32(target, wp_addr, &wp);
1278 if (retval == ERROR_OK && wp == 0) {
1279 LOG_ERROR("flash read algorithm aborted by target");
1280 retval = ERROR_FLASH_OPERATION_FAILED;
1287 int target_read_memory(struct target *target,
1288 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1290 if (!target_was_examined(target)) {
1291 LOG_ERROR("Target not examined yet");
1294 if (!target->type->read_memory) {
1295 LOG_ERROR("Target %s doesn't support read_memory", target_name(target));
1298 return target->type->read_memory(target, address, size, count, buffer);
1301 int target_read_phys_memory(struct target *target,
1302 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1304 if (!target_was_examined(target)) {
1305 LOG_ERROR("Target not examined yet");
1308 if (!target->type->read_phys_memory) {
1309 LOG_ERROR("Target %s doesn't support read_phys_memory", target_name(target));
1312 return target->type->read_phys_memory(target, address, size, count, buffer);
1315 int target_write_memory(struct target *target,
1316 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1318 if (!target_was_examined(target)) {
1319 LOG_ERROR("Target not examined yet");
1322 if (!target->type->write_memory) {
1323 LOG_ERROR("Target %s doesn't support write_memory", target_name(target));
1326 return target->type->write_memory(target, address, size, count, buffer);
1329 int target_write_phys_memory(struct target *target,
1330 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1332 if (!target_was_examined(target)) {
1333 LOG_ERROR("Target not examined yet");
1336 if (!target->type->write_phys_memory) {
1337 LOG_ERROR("Target %s doesn't support write_phys_memory", target_name(target));
1340 return target->type->write_phys_memory(target, address, size, count, buffer);
1343 int target_add_breakpoint(struct target *target,
1344 struct breakpoint *breakpoint)
1346 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1347 LOG_WARNING("target %s is not halted (add breakpoint)", target_name(target));
1348 return ERROR_TARGET_NOT_HALTED;
1350 return target->type->add_breakpoint(target, breakpoint);
1353 int target_add_context_breakpoint(struct target *target,
1354 struct breakpoint *breakpoint)
1356 if (target->state != TARGET_HALTED) {
1357 LOG_WARNING("target %s is not halted (add context breakpoint)", target_name(target));
1358 return ERROR_TARGET_NOT_HALTED;
1360 return target->type->add_context_breakpoint(target, breakpoint);
1363 int target_add_hybrid_breakpoint(struct target *target,
1364 struct breakpoint *breakpoint)
1366 if (target->state != TARGET_HALTED) {
1367 LOG_WARNING("target %s is not halted (add hybrid breakpoint)", target_name(target));
1368 return ERROR_TARGET_NOT_HALTED;
1370 return target->type->add_hybrid_breakpoint(target, breakpoint);
1373 int target_remove_breakpoint(struct target *target,
1374 struct breakpoint *breakpoint)
1376 return target->type->remove_breakpoint(target, breakpoint);
1379 int target_add_watchpoint(struct target *target,
1380 struct watchpoint *watchpoint)
1382 if (target->state != TARGET_HALTED) {
1383 LOG_WARNING("target %s is not halted (add watchpoint)", target_name(target));
1384 return ERROR_TARGET_NOT_HALTED;
1386 return target->type->add_watchpoint(target, watchpoint);
1388 int target_remove_watchpoint(struct target *target,
1389 struct watchpoint *watchpoint)
1391 return target->type->remove_watchpoint(target, watchpoint);
1393 int target_hit_watchpoint(struct target *target,
1394 struct watchpoint **hit_watchpoint)
1396 if (target->state != TARGET_HALTED) {
1397 LOG_WARNING("target %s is not halted (hit watchpoint)", target->cmd_name);
1398 return ERROR_TARGET_NOT_HALTED;
1401 if (!target->type->hit_watchpoint) {
1402 /* For backward compatible, if hit_watchpoint is not implemented,
1403 * return ERROR_FAIL such that gdb_server will not take the nonsense
1408 return target->type->hit_watchpoint(target, hit_watchpoint);
1411 const char *target_get_gdb_arch(struct target *target)
1413 if (!target->type->get_gdb_arch)
1415 return target->type->get_gdb_arch(target);
1418 int target_get_gdb_reg_list(struct target *target,
1419 struct reg **reg_list[], int *reg_list_size,
1420 enum target_register_class reg_class)
1422 int result = ERROR_FAIL;
1424 if (!target_was_examined(target)) {
1425 LOG_ERROR("Target not examined yet");
1429 result = target->type->get_gdb_reg_list(target, reg_list,
1430 reg_list_size, reg_class);
1433 if (result != ERROR_OK) {
1440 int target_get_gdb_reg_list_noread(struct target *target,
1441 struct reg **reg_list[], int *reg_list_size,
1442 enum target_register_class reg_class)
1444 if (target->type->get_gdb_reg_list_noread &&
1445 target->type->get_gdb_reg_list_noread(target, reg_list,
1446 reg_list_size, reg_class) == ERROR_OK)
1448 return target_get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1451 bool target_supports_gdb_connection(struct target *target)
1454 * exclude all the targets that don't provide get_gdb_reg_list
1455 * or that have explicit gdb_max_connection == 0
1457 return !!target->type->get_gdb_reg_list && !!target->gdb_max_connections;
1460 int target_step(struct target *target,
1461 int current, target_addr_t address, int handle_breakpoints)
1465 target_call_event_callbacks(target, TARGET_EVENT_STEP_START);
1467 retval = target->type->step(target, current, address, handle_breakpoints);
1468 if (retval != ERROR_OK)
1471 target_call_event_callbacks(target, TARGET_EVENT_STEP_END);
1476 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1478 if (target->state != TARGET_HALTED) {
1479 LOG_WARNING("target %s is not halted (gdb fileio)", target->cmd_name);
1480 return ERROR_TARGET_NOT_HALTED;
1482 return target->type->get_gdb_fileio_info(target, fileio_info);
1485 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1487 if (target->state != TARGET_HALTED) {
1488 LOG_WARNING("target %s is not halted (gdb fileio end)", target->cmd_name);
1489 return ERROR_TARGET_NOT_HALTED;
1491 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1494 target_addr_t target_address_max(struct target *target)
1496 unsigned bits = target_address_bits(target);
1497 if (sizeof(target_addr_t) * 8 == bits)
1498 return (target_addr_t) -1;
1500 return (((target_addr_t) 1) << bits) - 1;
1503 unsigned target_address_bits(struct target *target)
1505 if (target->type->address_bits)
1506 return target->type->address_bits(target);
1510 unsigned int target_data_bits(struct target *target)
1512 if (target->type->data_bits)
1513 return target->type->data_bits(target);
1517 static int target_profiling(struct target *target, uint32_t *samples,
1518 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1520 return target->type->profiling(target, samples, max_num_samples,
1521 num_samples, seconds);
1525 * Reset the @c examined flag for the given target.
1526 * Pure paranoia -- targets are zeroed on allocation.
1528 static void target_reset_examined(struct target *target)
1530 target->examined = false;
1533 static int handle_target(void *priv);
1535 static int target_init_one(struct command_context *cmd_ctx,
1536 struct target *target)
1538 target_reset_examined(target);
1540 struct target_type *type = target->type;
1542 type->examine = default_examine;
1544 if (!type->check_reset)
1545 type->check_reset = default_check_reset;
1547 assert(type->init_target);
1549 int retval = type->init_target(cmd_ctx, target);
1550 if (retval != ERROR_OK) {
1551 LOG_ERROR("target '%s' init failed", target_name(target));
1555 /* Sanity-check MMU support ... stub in what we must, to help
1556 * implement it in stages, but warn if we need to do so.
1559 if (!type->virt2phys) {
1560 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1561 type->virt2phys = identity_virt2phys;
1564 /* Make sure no-MMU targets all behave the same: make no
1565 * distinction between physical and virtual addresses, and
1566 * ensure that virt2phys() is always an identity mapping.
1568 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1569 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1572 type->write_phys_memory = type->write_memory;
1573 type->read_phys_memory = type->read_memory;
1574 type->virt2phys = identity_virt2phys;
1577 if (!target->type->read_buffer)
1578 target->type->read_buffer = target_read_buffer_default;
1580 if (!target->type->write_buffer)
1581 target->type->write_buffer = target_write_buffer_default;
1583 if (!target->type->get_gdb_fileio_info)
1584 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1586 if (!target->type->gdb_fileio_end)
1587 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1589 if (!target->type->profiling)
1590 target->type->profiling = target_profiling_default;
1595 static int target_init(struct command_context *cmd_ctx)
1597 struct target *target;
1600 for (target = all_targets; target; target = target->next) {
1601 retval = target_init_one(cmd_ctx, target);
1602 if (retval != ERROR_OK)
1609 retval = target_register_user_commands(cmd_ctx);
1610 if (retval != ERROR_OK)
1613 retval = target_register_timer_callback(&handle_target,
1614 polling_interval, TARGET_TIMER_TYPE_PERIODIC, cmd_ctx->interp);
1615 if (retval != ERROR_OK)
1621 COMMAND_HANDLER(handle_target_init_command)
1626 return ERROR_COMMAND_SYNTAX_ERROR;
1628 static bool target_initialized;
1629 if (target_initialized) {
1630 LOG_INFO("'target init' has already been called");
1633 target_initialized = true;
1635 retval = command_run_line(CMD_CTX, "init_targets");
1636 if (retval != ERROR_OK)
1639 retval = command_run_line(CMD_CTX, "init_target_events");
1640 if (retval != ERROR_OK)
1643 retval = command_run_line(CMD_CTX, "init_board");
1644 if (retval != ERROR_OK)
1647 LOG_DEBUG("Initializing targets...");
1648 return target_init(CMD_CTX);
1651 int target_register_event_callback(int (*callback)(struct target *target,
1652 enum target_event event, void *priv), void *priv)
1654 struct target_event_callback **callbacks_p = &target_event_callbacks;
1657 return ERROR_COMMAND_SYNTAX_ERROR;
1660 while ((*callbacks_p)->next)
1661 callbacks_p = &((*callbacks_p)->next);
1662 callbacks_p = &((*callbacks_p)->next);
1665 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1666 (*callbacks_p)->callback = callback;
1667 (*callbacks_p)->priv = priv;
1668 (*callbacks_p)->next = NULL;
1673 int target_register_reset_callback(int (*callback)(struct target *target,
1674 enum target_reset_mode reset_mode, void *priv), void *priv)
1676 struct target_reset_callback *entry;
1679 return ERROR_COMMAND_SYNTAX_ERROR;
1681 entry = malloc(sizeof(struct target_reset_callback));
1683 LOG_ERROR("error allocating buffer for reset callback entry");
1684 return ERROR_COMMAND_SYNTAX_ERROR;
1687 entry->callback = callback;
1689 list_add(&entry->list, &target_reset_callback_list);
1695 int target_register_trace_callback(int (*callback)(struct target *target,
1696 size_t len, uint8_t *data, void *priv), void *priv)
1698 struct target_trace_callback *entry;
1701 return ERROR_COMMAND_SYNTAX_ERROR;
1703 entry = malloc(sizeof(struct target_trace_callback));
1705 LOG_ERROR("error allocating buffer for trace callback entry");
1706 return ERROR_COMMAND_SYNTAX_ERROR;
1709 entry->callback = callback;
1711 list_add(&entry->list, &target_trace_callback_list);
1717 int target_register_timer_callback(int (*callback)(void *priv),
1718 unsigned int time_ms, enum target_timer_type type, void *priv)
1720 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1723 return ERROR_COMMAND_SYNTAX_ERROR;
1726 while ((*callbacks_p)->next)
1727 callbacks_p = &((*callbacks_p)->next);
1728 callbacks_p = &((*callbacks_p)->next);
1731 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1732 (*callbacks_p)->callback = callback;
1733 (*callbacks_p)->type = type;
1734 (*callbacks_p)->time_ms = time_ms;
1735 (*callbacks_p)->removed = false;
1737 (*callbacks_p)->when = timeval_ms() + time_ms;
1738 target_timer_next_event_value = MIN(target_timer_next_event_value, (*callbacks_p)->when);
1740 (*callbacks_p)->priv = priv;
1741 (*callbacks_p)->next = NULL;
1746 int target_unregister_event_callback(int (*callback)(struct target *target,
1747 enum target_event event, void *priv), void *priv)
1749 struct target_event_callback **p = &target_event_callbacks;
1750 struct target_event_callback *c = target_event_callbacks;
1753 return ERROR_COMMAND_SYNTAX_ERROR;
1756 struct target_event_callback *next = c->next;
1757 if ((c->callback == callback) && (c->priv == priv)) {
1769 int target_unregister_reset_callback(int (*callback)(struct target *target,
1770 enum target_reset_mode reset_mode, void *priv), void *priv)
1772 struct target_reset_callback *entry;
1775 return ERROR_COMMAND_SYNTAX_ERROR;
1777 list_for_each_entry(entry, &target_reset_callback_list, list) {
1778 if (entry->callback == callback && entry->priv == priv) {
1779 list_del(&entry->list);
1788 int target_unregister_trace_callback(int (*callback)(struct target *target,
1789 size_t len, uint8_t *data, void *priv), void *priv)
1791 struct target_trace_callback *entry;
1794 return ERROR_COMMAND_SYNTAX_ERROR;
1796 list_for_each_entry(entry, &target_trace_callback_list, list) {
1797 if (entry->callback == callback && entry->priv == priv) {
1798 list_del(&entry->list);
1807 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1810 return ERROR_COMMAND_SYNTAX_ERROR;
1812 for (struct target_timer_callback *c = target_timer_callbacks;
1814 if ((c->callback == callback) && (c->priv == priv)) {
1823 int target_call_event_callbacks(struct target *target, enum target_event event)
1825 struct target_event_callback *callback = target_event_callbacks;
1826 struct target_event_callback *next_callback;
1828 if (event == TARGET_EVENT_HALTED) {
1829 /* execute early halted first */
1830 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1833 LOG_DEBUG("target event %i (%s) for core %s", event,
1834 jim_nvp_value2name_simple(nvp_target_event, event)->name,
1835 target_name(target));
1837 target_handle_event(target, event);
1840 next_callback = callback->next;
1841 callback->callback(target, event, callback->priv);
1842 callback = next_callback;
1848 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1850 struct target_reset_callback *callback;
1852 LOG_DEBUG("target reset %i (%s)", reset_mode,
1853 jim_nvp_value2name_simple(nvp_reset_modes, reset_mode)->name);
1855 list_for_each_entry(callback, &target_reset_callback_list, list)
1856 callback->callback(target, reset_mode, callback->priv);
1861 int target_call_trace_callbacks(struct target *target, size_t len, uint8_t *data)
1863 struct target_trace_callback *callback;
1865 list_for_each_entry(callback, &target_trace_callback_list, list)
1866 callback->callback(target, len, data, callback->priv);
1871 static int target_timer_callback_periodic_restart(
1872 struct target_timer_callback *cb, int64_t *now)
1874 cb->when = *now + cb->time_ms;
1878 static int target_call_timer_callback(struct target_timer_callback *cb,
1881 cb->callback(cb->priv);
1883 if (cb->type == TARGET_TIMER_TYPE_PERIODIC)
1884 return target_timer_callback_periodic_restart(cb, now);
1886 return target_unregister_timer_callback(cb->callback, cb->priv);
1889 static int target_call_timer_callbacks_check_time(int checktime)
1891 static bool callback_processing;
1893 /* Do not allow nesting */
1894 if (callback_processing)
1897 callback_processing = true;
1901 int64_t now = timeval_ms();
1903 /* Initialize to a default value that's a ways into the future.
1904 * The loop below will make it closer to now if there are
1905 * callbacks that want to be called sooner. */
1906 target_timer_next_event_value = now + 1000;
1908 /* Store an address of the place containing a pointer to the
1909 * next item; initially, that's a standalone "root of the
1910 * list" variable. */
1911 struct target_timer_callback **callback = &target_timer_callbacks;
1912 while (callback && *callback) {
1913 if ((*callback)->removed) {
1914 struct target_timer_callback *p = *callback;
1915 *callback = (*callback)->next;
1920 bool call_it = (*callback)->callback &&
1921 ((!checktime && (*callback)->type == TARGET_TIMER_TYPE_PERIODIC) ||
1922 now >= (*callback)->when);
1925 target_call_timer_callback(*callback, &now);
1927 if (!(*callback)->removed && (*callback)->when < target_timer_next_event_value)
1928 target_timer_next_event_value = (*callback)->when;
1930 callback = &(*callback)->next;
1933 callback_processing = false;
1937 int target_call_timer_callbacks()
1939 return target_call_timer_callbacks_check_time(1);
1942 /* invoke periodic callbacks immediately */
1943 int target_call_timer_callbacks_now()
1945 return target_call_timer_callbacks_check_time(0);
1948 int64_t target_timer_next_event(void)
1950 return target_timer_next_event_value;
1953 /* Prints the working area layout for debug purposes */
1954 static void print_wa_layout(struct target *target)
1956 struct working_area *c = target->working_areas;
1959 LOG_DEBUG("%c%c " TARGET_ADDR_FMT "-" TARGET_ADDR_FMT " (%" PRIu32 " bytes)",
1960 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1961 c->address, c->address + c->size - 1, c->size);
1966 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1967 static void target_split_working_area(struct working_area *area, uint32_t size)
1969 assert(area->free); /* Shouldn't split an allocated area */
1970 assert(size <= area->size); /* Caller should guarantee this */
1972 /* Split only if not already the right size */
1973 if (size < area->size) {
1974 struct working_area *new_wa = malloc(sizeof(*new_wa));
1979 new_wa->next = area->next;
1980 new_wa->size = area->size - size;
1981 new_wa->address = area->address + size;
1982 new_wa->backup = NULL;
1983 new_wa->user = NULL;
1984 new_wa->free = true;
1986 area->next = new_wa;
1989 /* If backup memory was allocated to this area, it has the wrong size
1990 * now so free it and it will be reallocated if/when needed */
1992 area->backup = NULL;
1996 /* Merge all adjacent free areas into one */
1997 static void target_merge_working_areas(struct target *target)
1999 struct working_area *c = target->working_areas;
2001 while (c && c->next) {
2002 assert(c->next->address == c->address + c->size); /* This is an invariant */
2004 /* Find two adjacent free areas */
2005 if (c->free && c->next->free) {
2006 /* Merge the last into the first */
2007 c->size += c->next->size;
2009 /* Remove the last */
2010 struct working_area *to_be_freed = c->next;
2011 c->next = c->next->next;
2012 free(to_be_freed->backup);
2015 /* If backup memory was allocated to the remaining area, it's has
2016 * the wrong size now */
2025 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
2027 /* Reevaluate working area address based on MMU state*/
2028 if (!target->working_areas) {
2032 retval = target->type->mmu(target, &enabled);
2033 if (retval != ERROR_OK)
2037 if (target->working_area_phys_spec) {
2038 LOG_DEBUG("MMU disabled, using physical "
2039 "address for working memory " TARGET_ADDR_FMT,
2040 target->working_area_phys);
2041 target->working_area = target->working_area_phys;
2043 LOG_ERROR("No working memory available. "
2044 "Specify -work-area-phys to target.");
2045 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2048 if (target->working_area_virt_spec) {
2049 LOG_DEBUG("MMU enabled, using virtual "
2050 "address for working memory " TARGET_ADDR_FMT,
2051 target->working_area_virt);
2052 target->working_area = target->working_area_virt;
2054 LOG_ERROR("No working memory available. "
2055 "Specify -work-area-virt to target.");
2056 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2060 /* Set up initial working area on first call */
2061 struct working_area *new_wa = malloc(sizeof(*new_wa));
2063 new_wa->next = NULL;
2064 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
2065 new_wa->address = target->working_area;
2066 new_wa->backup = NULL;
2067 new_wa->user = NULL;
2068 new_wa->free = true;
2071 target->working_areas = new_wa;
2074 /* only allocate multiples of 4 byte */
2076 size = (size + 3) & (~3UL);
2078 struct working_area *c = target->working_areas;
2080 /* Find the first large enough working area */
2082 if (c->free && c->size >= size)
2088 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2090 /* Split the working area into the requested size */
2091 target_split_working_area(c, size);
2093 LOG_DEBUG("allocated new working area of %" PRIu32 " bytes at address " TARGET_ADDR_FMT,
2096 if (target->backup_working_area) {
2098 c->backup = malloc(c->size);
2103 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
2104 if (retval != ERROR_OK)
2108 /* mark as used, and return the new (reused) area */
2115 print_wa_layout(target);
2120 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
2124 retval = target_alloc_working_area_try(target, size, area);
2125 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
2126 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
2131 static int target_restore_working_area(struct target *target, struct working_area *area)
2133 int retval = ERROR_OK;
2135 if (target->backup_working_area && area->backup) {
2136 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
2137 if (retval != ERROR_OK)
2138 LOG_ERROR("failed to restore %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2139 area->size, area->address);
2145 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
2146 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
2148 int retval = ERROR_OK;
2154 retval = target_restore_working_area(target, area);
2155 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
2156 if (retval != ERROR_OK)
2162 LOG_DEBUG("freed %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2163 area->size, area->address);
2165 /* mark user pointer invalid */
2166 /* TODO: Is this really safe? It points to some previous caller's memory.
2167 * How could we know that the area pointer is still in that place and not
2168 * some other vital data? What's the purpose of this, anyway? */
2172 target_merge_working_areas(target);
2174 print_wa_layout(target);
2179 int target_free_working_area(struct target *target, struct working_area *area)
2181 return target_free_working_area_restore(target, area, 1);
2184 /* free resources and restore memory, if restoring memory fails,
2185 * free up resources anyway
2187 static void target_free_all_working_areas_restore(struct target *target, int restore)
2189 struct working_area *c = target->working_areas;
2191 LOG_DEBUG("freeing all working areas");
2193 /* Loop through all areas, restoring the allocated ones and marking them as free */
2197 target_restore_working_area(target, c);
2199 *c->user = NULL; /* Same as above */
2205 /* Run a merge pass to combine all areas into one */
2206 target_merge_working_areas(target);
2208 print_wa_layout(target);
2211 void target_free_all_working_areas(struct target *target)
2213 target_free_all_working_areas_restore(target, 1);
2215 /* Now we have none or only one working area marked as free */
2216 if (target->working_areas) {
2217 /* Free the last one to allow on-the-fly moving and resizing */
2218 free(target->working_areas->backup);
2219 free(target->working_areas);
2220 target->working_areas = NULL;
2224 /* Find the largest number of bytes that can be allocated */
2225 uint32_t target_get_working_area_avail(struct target *target)
2227 struct working_area *c = target->working_areas;
2228 uint32_t max_size = 0;
2231 return target->working_area_size;
2234 if (c->free && max_size < c->size)
2243 static void target_destroy(struct target *target)
2245 if (target->type->deinit_target)
2246 target->type->deinit_target(target);
2248 free(target->semihosting);
2250 jtag_unregister_event_callback(jtag_enable_callback, target);
2252 struct target_event_action *teap = target->event_action;
2254 struct target_event_action *next = teap->next;
2255 Jim_DecrRefCount(teap->interp, teap->body);
2260 target_free_all_working_areas(target);
2262 /* release the targets SMP list */
2264 struct target_list *head = target->head;
2266 struct target_list *pos = head->next;
2267 head->target->smp = 0;
2274 rtos_destroy(target);
2276 free(target->gdb_port_override);
2278 free(target->trace_info);
2279 free(target->fileio_info);
2280 free(target->cmd_name);
2284 void target_quit(void)
2286 struct target_event_callback *pe = target_event_callbacks;
2288 struct target_event_callback *t = pe->next;
2292 target_event_callbacks = NULL;
2294 struct target_timer_callback *pt = target_timer_callbacks;
2296 struct target_timer_callback *t = pt->next;
2300 target_timer_callbacks = NULL;
2302 for (struct target *target = all_targets; target;) {
2306 target_destroy(target);
2313 int target_arch_state(struct target *target)
2317 LOG_WARNING("No target has been configured");
2321 if (target->state != TARGET_HALTED)
2324 retval = target->type->arch_state(target);
2328 static int target_get_gdb_fileio_info_default(struct target *target,
2329 struct gdb_fileio_info *fileio_info)
2331 /* If target does not support semi-hosting function, target
2332 has no need to provide .get_gdb_fileio_info callback.
2333 It just return ERROR_FAIL and gdb_server will return "Txx"
2334 as target halted every time. */
2338 static int target_gdb_fileio_end_default(struct target *target,
2339 int retcode, int fileio_errno, bool ctrl_c)
2344 int target_profiling_default(struct target *target, uint32_t *samples,
2345 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
2347 struct timeval timeout, now;
2349 gettimeofday(&timeout, NULL);
2350 timeval_add_time(&timeout, seconds, 0);
2352 LOG_INFO("Starting profiling. Halting and resuming the"
2353 " target as often as we can...");
2355 uint32_t sample_count = 0;
2356 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2357 struct reg *reg = register_get_by_name(target->reg_cache, "pc", true);
2359 int retval = ERROR_OK;
2361 target_poll(target);
2362 if (target->state == TARGET_HALTED) {
2363 uint32_t t = buf_get_u32(reg->value, 0, 32);
2364 samples[sample_count++] = t;
2365 /* current pc, addr = 0, do not handle breakpoints, not debugging */
2366 retval = target_resume(target, 1, 0, 0, 0);
2367 target_poll(target);
2368 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2369 } else if (target->state == TARGET_RUNNING) {
2370 /* We want to quickly sample the PC. */
2371 retval = target_halt(target);
2373 LOG_INFO("Target not halted or running");
2378 if (retval != ERROR_OK)
2381 gettimeofday(&now, NULL);
2382 if ((sample_count >= max_num_samples) || timeval_compare(&now, &timeout) >= 0) {
2383 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2388 *num_samples = sample_count;
2392 /* Single aligned words are guaranteed to use 16 or 32 bit access
2393 * mode respectively, otherwise data is handled as quickly as
2396 int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
2398 LOG_DEBUG("writing buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2401 if (!target_was_examined(target)) {
2402 LOG_ERROR("Target not examined yet");
2409 if ((address + size - 1) < address) {
2410 /* GDB can request this when e.g. PC is 0xfffffffc */
2411 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2417 return target->type->write_buffer(target, address, size, buffer);
2420 static int target_write_buffer_default(struct target *target,
2421 target_addr_t address, uint32_t count, const uint8_t *buffer)
2424 unsigned int data_bytes = target_data_bits(target) / 8;
2426 /* Align up to maximum bytes. The loop condition makes sure the next pass
2427 * will have something to do with the size we leave to it. */
2429 size < data_bytes && count >= size * 2 + (address & size);
2431 if (address & size) {
2432 int retval = target_write_memory(target, address, size, 1, buffer);
2433 if (retval != ERROR_OK)
2441 /* Write the data with as large access size as possible. */
2442 for (; size > 0; size /= 2) {
2443 uint32_t aligned = count - count % size;
2445 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2446 if (retval != ERROR_OK)
2457 /* Single aligned words are guaranteed to use 16 or 32 bit access
2458 * mode respectively, otherwise data is handled as quickly as
2461 int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
2463 LOG_DEBUG("reading buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2466 if (!target_was_examined(target)) {
2467 LOG_ERROR("Target not examined yet");
2474 if ((address + size - 1) < address) {
2475 /* GDB can request this when e.g. PC is 0xfffffffc */
2476 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2482 return target->type->read_buffer(target, address, size, buffer);
2485 static int target_read_buffer_default(struct target *target, target_addr_t address, uint32_t count, uint8_t *buffer)
2488 unsigned int data_bytes = target_data_bits(target) / 8;
2490 /* Align up to maximum bytes. The loop condition makes sure the next pass
2491 * will have something to do with the size we leave to it. */
2493 size < data_bytes && count >= size * 2 + (address & size);
2495 if (address & size) {
2496 int retval = target_read_memory(target, address, size, 1, buffer);
2497 if (retval != ERROR_OK)
2505 /* Read the data with as large access size as possible. */
2506 for (; size > 0; size /= 2) {
2507 uint32_t aligned = count - count % size;
2509 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2510 if (retval != ERROR_OK)
2521 int target_checksum_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t *crc)
2526 uint32_t checksum = 0;
2527 if (!target_was_examined(target)) {
2528 LOG_ERROR("Target not examined yet");
2532 retval = target->type->checksum_memory(target, address, size, &checksum);
2533 if (retval != ERROR_OK) {
2534 buffer = malloc(size);
2536 LOG_ERROR("error allocating buffer for section (%" PRIu32 " bytes)", size);
2537 return ERROR_COMMAND_SYNTAX_ERROR;
2539 retval = target_read_buffer(target, address, size, buffer);
2540 if (retval != ERROR_OK) {
2545 /* convert to target endianness */
2546 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2547 uint32_t target_data;
2548 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2549 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2552 retval = image_calculate_checksum(buffer, size, &checksum);
2561 int target_blank_check_memory(struct target *target,
2562 struct target_memory_check_block *blocks, int num_blocks,
2563 uint8_t erased_value)
2565 if (!target_was_examined(target)) {
2566 LOG_ERROR("Target not examined yet");
2570 if (!target->type->blank_check_memory)
2571 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2573 return target->type->blank_check_memory(target, blocks, num_blocks, erased_value);
2576 int target_read_u64(struct target *target, target_addr_t address, uint64_t *value)
2578 uint8_t value_buf[8];
2579 if (!target_was_examined(target)) {
2580 LOG_ERROR("Target not examined yet");
2584 int retval = target_read_memory(target, address, 8, 1, value_buf);
2586 if (retval == ERROR_OK) {
2587 *value = target_buffer_get_u64(target, value_buf);
2588 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2593 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2600 int target_read_u32(struct target *target, target_addr_t address, uint32_t *value)
2602 uint8_t value_buf[4];
2603 if (!target_was_examined(target)) {
2604 LOG_ERROR("Target not examined yet");
2608 int retval = target_read_memory(target, address, 4, 1, value_buf);
2610 if (retval == ERROR_OK) {
2611 *value = target_buffer_get_u32(target, value_buf);
2612 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2617 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2624 int target_read_u16(struct target *target, target_addr_t address, uint16_t *value)
2626 uint8_t value_buf[2];
2627 if (!target_was_examined(target)) {
2628 LOG_ERROR("Target not examined yet");
2632 int retval = target_read_memory(target, address, 2, 1, value_buf);
2634 if (retval == ERROR_OK) {
2635 *value = target_buffer_get_u16(target, value_buf);
2636 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%4.4" PRIx16,
2641 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2648 int target_read_u8(struct target *target, target_addr_t address, uint8_t *value)
2650 if (!target_was_examined(target)) {
2651 LOG_ERROR("Target not examined yet");
2655 int retval = target_read_memory(target, address, 1, 1, value);
2657 if (retval == ERROR_OK) {
2658 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2663 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2670 int target_write_u64(struct target *target, target_addr_t address, uint64_t value)
2673 uint8_t value_buf[8];
2674 if (!target_was_examined(target)) {
2675 LOG_ERROR("Target not examined yet");
2679 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2683 target_buffer_set_u64(target, value_buf, value);
2684 retval = target_write_memory(target, address, 8, 1, value_buf);
2685 if (retval != ERROR_OK)
2686 LOG_DEBUG("failed: %i", retval);
2691 int target_write_u32(struct target *target, target_addr_t address, uint32_t value)
2694 uint8_t value_buf[4];
2695 if (!target_was_examined(target)) {
2696 LOG_ERROR("Target not examined yet");
2700 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2704 target_buffer_set_u32(target, value_buf, value);
2705 retval = target_write_memory(target, address, 4, 1, value_buf);
2706 if (retval != ERROR_OK)
2707 LOG_DEBUG("failed: %i", retval);
2712 int target_write_u16(struct target *target, target_addr_t address, uint16_t value)
2715 uint8_t value_buf[2];
2716 if (!target_was_examined(target)) {
2717 LOG_ERROR("Target not examined yet");
2721 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2725 target_buffer_set_u16(target, value_buf, value);
2726 retval = target_write_memory(target, address, 2, 1, value_buf);
2727 if (retval != ERROR_OK)
2728 LOG_DEBUG("failed: %i", retval);
2733 int target_write_u8(struct target *target, target_addr_t address, uint8_t value)
2736 if (!target_was_examined(target)) {
2737 LOG_ERROR("Target not examined yet");
2741 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2744 retval = target_write_memory(target, address, 1, 1, &value);
2745 if (retval != ERROR_OK)
2746 LOG_DEBUG("failed: %i", retval);
2751 int target_write_phys_u64(struct target *target, target_addr_t address, uint64_t value)
2754 uint8_t value_buf[8];
2755 if (!target_was_examined(target)) {
2756 LOG_ERROR("Target not examined yet");
2760 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2764 target_buffer_set_u64(target, value_buf, value);
2765 retval = target_write_phys_memory(target, address, 8, 1, value_buf);
2766 if (retval != ERROR_OK)
2767 LOG_DEBUG("failed: %i", retval);
2772 int target_write_phys_u32(struct target *target, target_addr_t address, uint32_t value)
2775 uint8_t value_buf[4];
2776 if (!target_was_examined(target)) {
2777 LOG_ERROR("Target not examined yet");
2781 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2785 target_buffer_set_u32(target, value_buf, value);
2786 retval = target_write_phys_memory(target, address, 4, 1, value_buf);
2787 if (retval != ERROR_OK)
2788 LOG_DEBUG("failed: %i", retval);
2793 int target_write_phys_u16(struct target *target, target_addr_t address, uint16_t value)
2796 uint8_t value_buf[2];
2797 if (!target_was_examined(target)) {
2798 LOG_ERROR("Target not examined yet");
2802 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2806 target_buffer_set_u16(target, value_buf, value);
2807 retval = target_write_phys_memory(target, address, 2, 1, value_buf);
2808 if (retval != ERROR_OK)
2809 LOG_DEBUG("failed: %i", retval);
2814 int target_write_phys_u8(struct target *target, target_addr_t address, uint8_t value)
2817 if (!target_was_examined(target)) {
2818 LOG_ERROR("Target not examined yet");
2822 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2825 retval = target_write_phys_memory(target, address, 1, 1, &value);
2826 if (retval != ERROR_OK)
2827 LOG_DEBUG("failed: %i", retval);
2832 static int find_target(struct command_invocation *cmd, const char *name)
2834 struct target *target = get_target(name);
2836 command_print(cmd, "Target: %s is unknown, try one of:\n", name);
2839 if (!target->tap->enabled) {
2840 command_print(cmd, "Target: TAP %s is disabled, "
2841 "can't be the current target\n",
2842 target->tap->dotted_name);
2846 cmd->ctx->current_target = target;
2847 if (cmd->ctx->current_target_override)
2848 cmd->ctx->current_target_override = target;
2854 COMMAND_HANDLER(handle_targets_command)
2856 int retval = ERROR_OK;
2857 if (CMD_ARGC == 1) {
2858 retval = find_target(CMD, CMD_ARGV[0]);
2859 if (retval == ERROR_OK) {
2865 struct target *target = all_targets;
2866 command_print(CMD, " TargetName Type Endian TapName State ");
2867 command_print(CMD, "-- ------------------ ---------- ------ ------------------ ------------");
2872 if (target->tap->enabled)
2873 state = target_state_name(target);
2875 state = "tap-disabled";
2877 if (CMD_CTX->current_target == target)
2880 /* keep columns lined up to match the headers above */
2882 "%2d%c %-18s %-10s %-6s %-18s %s",
2883 target->target_number,
2885 target_name(target),
2886 target_type_name(target),
2887 jim_nvp_value2name_simple(nvp_target_endian,
2888 target->endianness)->name,
2889 target->tap->dotted_name,
2891 target = target->next;
2897 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2899 static int power_dropout;
2900 static int srst_asserted;
2902 static int run_power_restore;
2903 static int run_power_dropout;
2904 static int run_srst_asserted;
2905 static int run_srst_deasserted;
2907 static int sense_handler(void)
2909 static int prev_srst_asserted;
2910 static int prev_power_dropout;
2912 int retval = jtag_power_dropout(&power_dropout);
2913 if (retval != ERROR_OK)
2917 power_restored = prev_power_dropout && !power_dropout;
2919 run_power_restore = 1;
2921 int64_t current = timeval_ms();
2922 static int64_t last_power;
2923 bool wait_more = last_power + 2000 > current;
2924 if (power_dropout && !wait_more) {
2925 run_power_dropout = 1;
2926 last_power = current;
2929 retval = jtag_srst_asserted(&srst_asserted);
2930 if (retval != ERROR_OK)
2933 int srst_deasserted;
2934 srst_deasserted = prev_srst_asserted && !srst_asserted;
2936 static int64_t last_srst;
2937 wait_more = last_srst + 2000 > current;
2938 if (srst_deasserted && !wait_more) {
2939 run_srst_deasserted = 1;
2940 last_srst = current;
2943 if (!prev_srst_asserted && srst_asserted)
2944 run_srst_asserted = 1;
2946 prev_srst_asserted = srst_asserted;
2947 prev_power_dropout = power_dropout;
2949 if (srst_deasserted || power_restored) {
2950 /* Other than logging the event we can't do anything here.
2951 * Issuing a reset is a particularly bad idea as we might
2952 * be inside a reset already.
2959 /* process target state changes */
2960 static int handle_target(void *priv)
2962 Jim_Interp *interp = (Jim_Interp *)priv;
2963 int retval = ERROR_OK;
2965 if (!is_jtag_poll_safe()) {
2966 /* polling is disabled currently */
2970 /* we do not want to recurse here... */
2971 static int recursive;
2975 /* danger! running these procedures can trigger srst assertions and power dropouts.
2976 * We need to avoid an infinite loop/recursion here and we do that by
2977 * clearing the flags after running these events.
2979 int did_something = 0;
2980 if (run_srst_asserted) {
2981 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2982 Jim_Eval(interp, "srst_asserted");
2985 if (run_srst_deasserted) {
2986 Jim_Eval(interp, "srst_deasserted");
2989 if (run_power_dropout) {
2990 LOG_INFO("Power dropout detected, running power_dropout proc.");
2991 Jim_Eval(interp, "power_dropout");
2994 if (run_power_restore) {
2995 Jim_Eval(interp, "power_restore");
2999 if (did_something) {
3000 /* clear detect flags */
3004 /* clear action flags */
3006 run_srst_asserted = 0;
3007 run_srst_deasserted = 0;
3008 run_power_restore = 0;
3009 run_power_dropout = 0;
3014 /* Poll targets for state changes unless that's globally disabled.
3015 * Skip targets that are currently disabled.
3017 for (struct target *target = all_targets;
3018 is_jtag_poll_safe() && target;
3019 target = target->next) {
3021 if (!target_was_examined(target))
3024 if (!target->tap->enabled)
3027 if (target->backoff.times > target->backoff.count) {
3028 /* do not poll this time as we failed previously */
3029 target->backoff.count++;
3032 target->backoff.count = 0;
3034 /* only poll target if we've got power and srst isn't asserted */
3035 if (!power_dropout && !srst_asserted) {
3036 /* polling may fail silently until the target has been examined */
3037 retval = target_poll(target);
3038 if (retval != ERROR_OK) {
3039 /* 100ms polling interval. Increase interval between polling up to 5000ms */
3040 if (target->backoff.times * polling_interval < 5000) {
3041 target->backoff.times *= 2;
3042 target->backoff.times++;
3045 /* Tell GDB to halt the debugger. This allows the user to
3046 * run monitor commands to handle the situation.
3048 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3050 if (target->backoff.times > 0) {
3051 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
3052 target_reset_examined(target);
3053 retval = target_examine_one(target);
3054 /* Target examination could have failed due to unstable connection,
3055 * but we set the examined flag anyway to repoll it later */
3056 if (retval != ERROR_OK) {
3057 target->examined = true;
3058 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
3059 target->backoff.times * polling_interval);
3064 /* Since we succeeded, we reset backoff count */
3065 target->backoff.times = 0;
3072 COMMAND_HANDLER(handle_reg_command)
3076 struct target *target = get_current_target(CMD_CTX);
3077 struct reg *reg = NULL;
3079 /* list all available registers for the current target */
3080 if (CMD_ARGC == 0) {
3081 struct reg_cache *cache = target->reg_cache;
3083 unsigned int count = 0;
3087 command_print(CMD, "===== %s", cache->name);
3089 for (i = 0, reg = cache->reg_list;
3090 i < cache->num_regs;
3091 i++, reg++, count++) {
3092 if (reg->exist == false || reg->hidden)
3094 /* only print cached values if they are valid */
3096 char *value = buf_to_hex_str(reg->value,
3099 "(%i) %s (/%" PRIu32 "): 0x%s%s",
3107 command_print(CMD, "(%i) %s (/%" PRIu32 ")",
3112 cache = cache->next;
3118 /* access a single register by its ordinal number */
3119 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
3121 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
3123 struct reg_cache *cache = target->reg_cache;
3124 unsigned int count = 0;
3127 for (i = 0; i < cache->num_regs; i++) {
3128 if (count++ == num) {
3129 reg = &cache->reg_list[i];
3135 cache = cache->next;
3139 command_print(CMD, "%i is out of bounds, the current target "
3140 "has only %i registers (0 - %i)", num, count, count - 1);
3144 /* access a single register by its name */
3145 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], true);
3151 assert(reg); /* give clang a hint that we *know* reg is != NULL here */
3156 /* display a register */
3157 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
3158 && (CMD_ARGV[1][0] <= '9')))) {
3159 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
3162 if (reg->valid == 0) {
3163 int retval = reg->type->get(reg);
3164 if (retval != ERROR_OK) {
3165 LOG_ERROR("Could not read register '%s'", reg->name);
3169 char *value = buf_to_hex_str(reg->value, reg->size);
3170 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3175 /* set register value */
3176 if (CMD_ARGC == 2) {
3177 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
3180 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
3182 int retval = reg->type->set(reg, buf);
3183 if (retval != ERROR_OK) {
3184 LOG_ERROR("Could not write to register '%s'", reg->name);
3186 char *value = buf_to_hex_str(reg->value, reg->size);
3187 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3196 return ERROR_COMMAND_SYNTAX_ERROR;
3199 command_print(CMD, "register %s not found in current target", CMD_ARGV[0]);
3203 COMMAND_HANDLER(handle_poll_command)
3205 int retval = ERROR_OK;
3206 struct target *target = get_current_target(CMD_CTX);
3208 if (CMD_ARGC == 0) {
3209 command_print(CMD, "background polling: %s",
3210 jtag_poll_get_enabled() ? "on" : "off");
3211 command_print(CMD, "TAP: %s (%s)",
3212 target->tap->dotted_name,
3213 target->tap->enabled ? "enabled" : "disabled");
3214 if (!target->tap->enabled)
3216 retval = target_poll(target);
3217 if (retval != ERROR_OK)
3219 retval = target_arch_state(target);
3220 if (retval != ERROR_OK)
3222 } else if (CMD_ARGC == 1) {
3224 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
3225 jtag_poll_set_enabled(enable);
3227 return ERROR_COMMAND_SYNTAX_ERROR;
3232 COMMAND_HANDLER(handle_wait_halt_command)
3235 return ERROR_COMMAND_SYNTAX_ERROR;
3237 unsigned ms = DEFAULT_HALT_TIMEOUT;
3238 if (1 == CMD_ARGC) {
3239 int retval = parse_uint(CMD_ARGV[0], &ms);
3240 if (retval != ERROR_OK)
3241 return ERROR_COMMAND_SYNTAX_ERROR;
3244 struct target *target = get_current_target(CMD_CTX);
3245 return target_wait_state(target, TARGET_HALTED, ms);
3248 /* wait for target state to change. The trick here is to have a low
3249 * latency for short waits and not to suck up all the CPU time
3252 * After 500ms, keep_alive() is invoked
3254 int target_wait_state(struct target *target, enum target_state state, int ms)
3257 int64_t then = 0, cur;
3261 retval = target_poll(target);
3262 if (retval != ERROR_OK)
3264 if (target->state == state)
3269 then = timeval_ms();
3270 LOG_DEBUG("waiting for target %s...",
3271 jim_nvp_value2name_simple(nvp_target_state, state)->name);
3277 if ((cur-then) > ms) {
3278 LOG_ERROR("timed out while waiting for target %s",
3279 jim_nvp_value2name_simple(nvp_target_state, state)->name);
3287 COMMAND_HANDLER(handle_halt_command)
3291 struct target *target = get_current_target(CMD_CTX);
3293 target->verbose_halt_msg = true;
3295 int retval = target_halt(target);
3296 if (retval != ERROR_OK)
3299 if (CMD_ARGC == 1) {
3300 unsigned wait_local;
3301 retval = parse_uint(CMD_ARGV[0], &wait_local);
3302 if (retval != ERROR_OK)
3303 return ERROR_COMMAND_SYNTAX_ERROR;
3308 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
3311 COMMAND_HANDLER(handle_soft_reset_halt_command)
3313 struct target *target = get_current_target(CMD_CTX);
3315 LOG_USER("requesting target halt and executing a soft reset");
3317 target_soft_reset_halt(target);
3322 COMMAND_HANDLER(handle_reset_command)
3325 return ERROR_COMMAND_SYNTAX_ERROR;
3327 enum target_reset_mode reset_mode = RESET_RUN;
3328 if (CMD_ARGC == 1) {
3329 const struct jim_nvp *n;
3330 n = jim_nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
3331 if ((!n->name) || (n->value == RESET_UNKNOWN))
3332 return ERROR_COMMAND_SYNTAX_ERROR;
3333 reset_mode = n->value;
3336 /* reset *all* targets */
3337 return target_process_reset(CMD, reset_mode);
3341 COMMAND_HANDLER(handle_resume_command)
3345 return ERROR_COMMAND_SYNTAX_ERROR;
3347 struct target *target = get_current_target(CMD_CTX);
3349 /* with no CMD_ARGV, resume from current pc, addr = 0,
3350 * with one arguments, addr = CMD_ARGV[0],
3351 * handle breakpoints, not debugging */
3352 target_addr_t addr = 0;
3353 if (CMD_ARGC == 1) {
3354 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3358 return target_resume(target, current, addr, 1, 0);
3361 COMMAND_HANDLER(handle_step_command)
3364 return ERROR_COMMAND_SYNTAX_ERROR;
3368 /* with no CMD_ARGV, step from current pc, addr = 0,
3369 * with one argument addr = CMD_ARGV[0],
3370 * handle breakpoints, debugging */
3371 target_addr_t addr = 0;
3373 if (CMD_ARGC == 1) {
3374 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3378 struct target *target = get_current_target(CMD_CTX);
3380 return target_step(target, current_pc, addr, 1);
3383 void target_handle_md_output(struct command_invocation *cmd,
3384 struct target *target, target_addr_t address, unsigned size,
3385 unsigned count, const uint8_t *buffer)
3387 const unsigned line_bytecnt = 32;
3388 unsigned line_modulo = line_bytecnt / size;
3390 char output[line_bytecnt * 4 + 1];
3391 unsigned output_len = 0;
3393 const char *value_fmt;
3396 value_fmt = "%16.16"PRIx64" ";
3399 value_fmt = "%8.8"PRIx64" ";
3402 value_fmt = "%4.4"PRIx64" ";
3405 value_fmt = "%2.2"PRIx64" ";
3408 /* "can't happen", caller checked */
3409 LOG_ERROR("invalid memory read size: %u", size);
3413 for (unsigned i = 0; i < count; i++) {
3414 if (i % line_modulo == 0) {
3415 output_len += snprintf(output + output_len,
3416 sizeof(output) - output_len,
3417 TARGET_ADDR_FMT ": ",
3418 (address + (i * size)));
3422 const uint8_t *value_ptr = buffer + i * size;
3425 value = target_buffer_get_u64(target, value_ptr);
3428 value = target_buffer_get_u32(target, value_ptr);
3431 value = target_buffer_get_u16(target, value_ptr);
3436 output_len += snprintf(output + output_len,
3437 sizeof(output) - output_len,
3440 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
3441 command_print(cmd, "%s", output);
3447 COMMAND_HANDLER(handle_md_command)
3450 return ERROR_COMMAND_SYNTAX_ERROR;
3453 switch (CMD_NAME[2]) {
3467 return ERROR_COMMAND_SYNTAX_ERROR;
3470 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3471 int (*fn)(struct target *target,
3472 target_addr_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
3476 fn = target_read_phys_memory;
3478 fn = target_read_memory;
3479 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
3480 return ERROR_COMMAND_SYNTAX_ERROR;
3482 target_addr_t address;
3483 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3487 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3489 uint8_t *buffer = calloc(count, size);
3491 LOG_ERROR("Failed to allocate md read buffer");
3495 struct target *target = get_current_target(CMD_CTX);
3496 int retval = fn(target, address, size, count, buffer);
3497 if (retval == ERROR_OK)
3498 target_handle_md_output(CMD, target, address, size, count, buffer);
3505 typedef int (*target_write_fn)(struct target *target,
3506 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3508 static int target_fill_mem(struct target *target,
3509 target_addr_t address,
3517 /* We have to write in reasonably large chunks to be able
3518 * to fill large memory areas with any sane speed */
3519 const unsigned chunk_size = 16384;
3520 uint8_t *target_buf = malloc(chunk_size * data_size);
3522 LOG_ERROR("Out of memory");
3526 for (unsigned i = 0; i < chunk_size; i++) {
3527 switch (data_size) {
3529 target_buffer_set_u64(target, target_buf + i * data_size, b);
3532 target_buffer_set_u32(target, target_buf + i * data_size, b);
3535 target_buffer_set_u16(target, target_buf + i * data_size, b);
3538 target_buffer_set_u8(target, target_buf + i * data_size, b);
3545 int retval = ERROR_OK;
3547 for (unsigned x = 0; x < c; x += chunk_size) {
3550 if (current > chunk_size)
3551 current = chunk_size;
3552 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3553 if (retval != ERROR_OK)
3555 /* avoid GDB timeouts */
3564 COMMAND_HANDLER(handle_mw_command)
3567 return ERROR_COMMAND_SYNTAX_ERROR;
3568 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3573 fn = target_write_phys_memory;
3575 fn = target_write_memory;
3576 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3577 return ERROR_COMMAND_SYNTAX_ERROR;
3579 target_addr_t address;
3580 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3583 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[1], value);
3587 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3589 struct target *target = get_current_target(CMD_CTX);
3591 switch (CMD_NAME[2]) {
3605 return ERROR_COMMAND_SYNTAX_ERROR;
3608 return target_fill_mem(target, address, fn, wordsize, value, count);
3611 static COMMAND_HELPER(parse_load_image_command, struct image *image,
3612 target_addr_t *min_address, target_addr_t *max_address)
3614 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3615 return ERROR_COMMAND_SYNTAX_ERROR;
3617 /* a base address isn't always necessary,
3618 * default to 0x0 (i.e. don't relocate) */
3619 if (CMD_ARGC >= 2) {
3621 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3622 image->base_address = addr;
3623 image->base_address_set = true;
3625 image->base_address_set = false;
3627 image->start_address_set = false;
3630 COMMAND_PARSE_ADDRESS(CMD_ARGV[3], *min_address);
3631 if (CMD_ARGC == 5) {
3632 COMMAND_PARSE_ADDRESS(CMD_ARGV[4], *max_address);
3633 /* use size (given) to find max (required) */
3634 *max_address += *min_address;
3637 if (*min_address > *max_address)
3638 return ERROR_COMMAND_SYNTAX_ERROR;
3643 COMMAND_HANDLER(handle_load_image_command)
3647 uint32_t image_size;
3648 target_addr_t min_address = 0;
3649 target_addr_t max_address = -1;
3652 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
3653 &image, &min_address, &max_address);
3654 if (retval != ERROR_OK)
3657 struct target *target = get_current_target(CMD_CTX);
3659 struct duration bench;
3660 duration_start(&bench);
3662 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3667 for (unsigned int i = 0; i < image.num_sections; i++) {
3668 buffer = malloc(image.sections[i].size);
3671 "error allocating buffer for section (%d bytes)",
3672 (int)(image.sections[i].size));
3673 retval = ERROR_FAIL;
3677 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3678 if (retval != ERROR_OK) {
3683 uint32_t offset = 0;
3684 uint32_t length = buf_cnt;
3686 /* DANGER!!! beware of unsigned comparison here!!! */
3688 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3689 (image.sections[i].base_address < max_address)) {
3691 if (image.sections[i].base_address < min_address) {
3692 /* clip addresses below */
3693 offset += min_address-image.sections[i].base_address;
3697 if (image.sections[i].base_address + buf_cnt > max_address)
3698 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3700 retval = target_write_buffer(target,
3701 image.sections[i].base_address + offset, length, buffer + offset);
3702 if (retval != ERROR_OK) {
3706 image_size += length;
3707 command_print(CMD, "%u bytes written at address " TARGET_ADDR_FMT "",
3708 (unsigned int)length,
3709 image.sections[i].base_address + offset);
3715 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3716 command_print(CMD, "downloaded %" PRIu32 " bytes "
3717 "in %fs (%0.3f KiB/s)", image_size,
3718 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3721 image_close(&image);
3727 COMMAND_HANDLER(handle_dump_image_command)
3729 struct fileio *fileio;
3731 int retval, retvaltemp;
3732 target_addr_t address, size;
3733 struct duration bench;
3734 struct target *target = get_current_target(CMD_CTX);
3737 return ERROR_COMMAND_SYNTAX_ERROR;
3739 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], address);
3740 COMMAND_PARSE_ADDRESS(CMD_ARGV[2], size);
3742 uint32_t buf_size = (size > 4096) ? 4096 : size;
3743 buffer = malloc(buf_size);
3747 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3748 if (retval != ERROR_OK) {
3753 duration_start(&bench);
3756 size_t size_written;
3757 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3758 retval = target_read_buffer(target, address, this_run_size, buffer);
3759 if (retval != ERROR_OK)
3762 retval = fileio_write(fileio, this_run_size, buffer, &size_written);
3763 if (retval != ERROR_OK)
3766 size -= this_run_size;
3767 address += this_run_size;
3772 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3774 retval = fileio_size(fileio, &filesize);
3775 if (retval != ERROR_OK)
3778 "dumped %zu bytes in %fs (%0.3f KiB/s)", filesize,
3779 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3782 retvaltemp = fileio_close(fileio);
3783 if (retvaltemp != ERROR_OK)
3792 IMAGE_CHECKSUM_ONLY = 2
3795 static COMMAND_HELPER(handle_verify_image_command_internal, enum verify_mode verify)
3799 uint32_t image_size;
3801 uint32_t checksum = 0;
3802 uint32_t mem_checksum = 0;
3806 struct target *target = get_current_target(CMD_CTX);
3809 return ERROR_COMMAND_SYNTAX_ERROR;
3812 LOG_ERROR("no target selected");
3816 struct duration bench;
3817 duration_start(&bench);
3819 if (CMD_ARGC >= 2) {
3821 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3822 image.base_address = addr;
3823 image.base_address_set = true;
3825 image.base_address_set = false;
3826 image.base_address = 0x0;
3829 image.start_address_set = false;
3831 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3832 if (retval != ERROR_OK)
3838 for (unsigned int i = 0; i < image.num_sections; i++) {
3839 buffer = malloc(image.sections[i].size);
3842 "error allocating buffer for section (%" PRIu32 " bytes)",
3843 image.sections[i].size);
3846 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3847 if (retval != ERROR_OK) {
3852 if (verify >= IMAGE_VERIFY) {
3853 /* calculate checksum of image */
3854 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3855 if (retval != ERROR_OK) {
3860 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3861 if (retval != ERROR_OK) {
3865 if ((checksum != mem_checksum) && (verify == IMAGE_CHECKSUM_ONLY)) {
3866 LOG_ERROR("checksum mismatch");
3868 retval = ERROR_FAIL;
3871 if (checksum != mem_checksum) {
3872 /* failed crc checksum, fall back to a binary compare */
3876 LOG_ERROR("checksum mismatch - attempting binary compare");
3878 data = malloc(buf_cnt);
3880 retval = target_read_buffer(target, image.sections[i].base_address, buf_cnt, data);
3881 if (retval == ERROR_OK) {
3883 for (t = 0; t < buf_cnt; t++) {
3884 if (data[t] != buffer[t]) {
3886 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3888 (unsigned)(t + image.sections[i].base_address),
3891 if (diffs++ >= 127) {
3892 command_print(CMD, "More than 128 errors, the rest are not printed.");
3904 command_print(CMD, "address " TARGET_ADDR_FMT " length 0x%08zx",
3905 image.sections[i].base_address,
3910 image_size += buf_cnt;
3913 command_print(CMD, "No more differences found.");
3916 retval = ERROR_FAIL;
3917 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3918 command_print(CMD, "verified %" PRIu32 " bytes "
3919 "in %fs (%0.3f KiB/s)", image_size,
3920 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3923 image_close(&image);
3928 COMMAND_HANDLER(handle_verify_image_checksum_command)
3930 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_CHECKSUM_ONLY);
3933 COMMAND_HANDLER(handle_verify_image_command)
3935 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_VERIFY);
3938 COMMAND_HANDLER(handle_test_image_command)
3940 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_TEST);
3943 static int handle_bp_command_list(struct command_invocation *cmd)
3945 struct target *target = get_current_target(cmd->ctx);
3946 struct breakpoint *breakpoint = target->breakpoints;
3947 while (breakpoint) {
3948 if (breakpoint->type == BKPT_SOFT) {
3949 char *buf = buf_to_hex_str(breakpoint->orig_instr,
3950 breakpoint->length);
3951 command_print(cmd, "IVA breakpoint: " TARGET_ADDR_FMT ", 0x%x, %i, 0x%s",
3952 breakpoint->address,
3954 breakpoint->set, buf);
3957 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3958 command_print(cmd, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3960 breakpoint->length, breakpoint->set);
3961 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3962 command_print(cmd, "Hybrid breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3963 breakpoint->address,
3964 breakpoint->length, breakpoint->set);
3965 command_print(cmd, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3968 command_print(cmd, "Breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3969 breakpoint->address,
3970 breakpoint->length, breakpoint->set);
3973 breakpoint = breakpoint->next;
3978 static int handle_bp_command_set(struct command_invocation *cmd,
3979 target_addr_t addr, uint32_t asid, uint32_t length, int hw)
3981 struct target *target = get_current_target(cmd->ctx);
3985 retval = breakpoint_add(target, addr, length, hw);
3986 /* error is always logged in breakpoint_add(), do not print it again */
3987 if (retval == ERROR_OK)
3988 command_print(cmd, "breakpoint set at " TARGET_ADDR_FMT "", addr);
3990 } else if (addr == 0) {
3991 if (!target->type->add_context_breakpoint) {
3992 LOG_ERROR("Context breakpoint not available");
3993 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
3995 retval = context_breakpoint_add(target, asid, length, hw);
3996 /* error is always logged in context_breakpoint_add(), do not print it again */
3997 if (retval == ERROR_OK)
3998 command_print(cmd, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
4001 if (!target->type->add_hybrid_breakpoint) {
4002 LOG_ERROR("Hybrid breakpoint not available");
4003 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
4005 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
4006 /* error is always logged in hybrid_breakpoint_add(), do not print it again */
4007 if (retval == ERROR_OK)
4008 command_print(cmd, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
4013 COMMAND_HANDLER(handle_bp_command)
4022 return handle_bp_command_list(CMD);
4026 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4027 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4028 return handle_bp_command_set(CMD, addr, asid, length, hw);
4031 if (strcmp(CMD_ARGV[2], "hw") == 0) {
4033 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4034 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4036 return handle_bp_command_set(CMD, addr, asid, length, hw);
4037 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
4039 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
4040 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4042 return handle_bp_command_set(CMD, addr, asid, length, hw);
4047 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4048 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
4049 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
4050 return handle_bp_command_set(CMD, addr, asid, length, hw);
4053 return ERROR_COMMAND_SYNTAX_ERROR;
4057 COMMAND_HANDLER(handle_rbp_command)
4060 return ERROR_COMMAND_SYNTAX_ERROR;
4062 struct target *target = get_current_target(CMD_CTX);
4064 if (!strcmp(CMD_ARGV[0], "all")) {
4065 breakpoint_remove_all(target);
4068 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4070 breakpoint_remove(target, addr);
4076 COMMAND_HANDLER(handle_wp_command)
4078 struct target *target = get_current_target(CMD_CTX);
4080 if (CMD_ARGC == 0) {
4081 struct watchpoint *watchpoint = target->watchpoints;
4083 while (watchpoint) {
4084 command_print(CMD, "address: " TARGET_ADDR_FMT
4085 ", len: 0x%8.8" PRIx32
4086 ", r/w/a: %i, value: 0x%8.8" PRIx32
4087 ", mask: 0x%8.8" PRIx32,
4088 watchpoint->address,
4090 (int)watchpoint->rw,
4093 watchpoint = watchpoint->next;
4098 enum watchpoint_rw type = WPT_ACCESS;
4099 target_addr_t addr = 0;
4100 uint32_t length = 0;
4101 uint32_t data_value = 0x0;
4102 uint32_t data_mask = 0xffffffff;
4106 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
4109 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
4112 switch (CMD_ARGV[2][0]) {
4123 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
4124 return ERROR_COMMAND_SYNTAX_ERROR;
4128 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4129 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4133 return ERROR_COMMAND_SYNTAX_ERROR;
4136 int retval = watchpoint_add(target, addr, length, type,
4137 data_value, data_mask);
4138 if (retval != ERROR_OK)
4139 LOG_ERROR("Failure setting watchpoints");
4144 COMMAND_HANDLER(handle_rwp_command)
4147 return ERROR_COMMAND_SYNTAX_ERROR;
4150 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4152 struct target *target = get_current_target(CMD_CTX);
4153 watchpoint_remove(target, addr);
4159 * Translate a virtual address to a physical address.
4161 * The low-level target implementation must have logged a detailed error
4162 * which is forwarded to telnet/GDB session.
4164 COMMAND_HANDLER(handle_virt2phys_command)
4167 return ERROR_COMMAND_SYNTAX_ERROR;
4170 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], va);
4173 struct target *target = get_current_target(CMD_CTX);
4174 int retval = target->type->virt2phys(target, va, &pa);
4175 if (retval == ERROR_OK)
4176 command_print(CMD, "Physical address " TARGET_ADDR_FMT "", pa);
4181 static void write_data(FILE *f, const void *data, size_t len)
4183 size_t written = fwrite(data, 1, len, f);
4185 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
4188 static void write_long(FILE *f, int l, struct target *target)
4192 target_buffer_set_u32(target, val, l);
4193 write_data(f, val, 4);
4196 static void write_string(FILE *f, char *s)
4198 write_data(f, s, strlen(s));
4201 typedef unsigned char UNIT[2]; /* unit of profiling */
4203 /* Dump a gmon.out histogram file. */
4204 static void write_gmon(uint32_t *samples, uint32_t sample_num, const char *filename, bool with_range,
4205 uint32_t start_address, uint32_t end_address, struct target *target, uint32_t duration_ms)
4208 FILE *f = fopen(filename, "w");
4211 write_string(f, "gmon");
4212 write_long(f, 0x00000001, target); /* Version */
4213 write_long(f, 0, target); /* padding */
4214 write_long(f, 0, target); /* padding */
4215 write_long(f, 0, target); /* padding */
4217 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
4218 write_data(f, &zero, 1);
4220 /* figure out bucket size */
4224 min = start_address;
4229 for (i = 0; i < sample_num; i++) {
4230 if (min > samples[i])
4232 if (max < samples[i])
4236 /* max should be (largest sample + 1)
4237 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
4241 int address_space = max - min;
4242 assert(address_space >= 2);
4244 /* FIXME: What is the reasonable number of buckets?
4245 * The profiling result will be more accurate if there are enough buckets. */
4246 static const uint32_t max_buckets = 128 * 1024; /* maximum buckets. */
4247 uint32_t num_buckets = address_space / sizeof(UNIT);
4248 if (num_buckets > max_buckets)
4249 num_buckets = max_buckets;
4250 int *buckets = malloc(sizeof(int) * num_buckets);
4255 memset(buckets, 0, sizeof(int) * num_buckets);
4256 for (i = 0; i < sample_num; i++) {
4257 uint32_t address = samples[i];
4259 if ((address < min) || (max <= address))
4262 long long a = address - min;
4263 long long b = num_buckets;
4264 long long c = address_space;
4265 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
4269 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
4270 write_long(f, min, target); /* low_pc */
4271 write_long(f, max, target); /* high_pc */
4272 write_long(f, num_buckets, target); /* # of buckets */
4273 float sample_rate = sample_num / (duration_ms / 1000.0);
4274 write_long(f, sample_rate, target);
4275 write_string(f, "seconds");
4276 for (i = 0; i < (15-strlen("seconds")); i++)
4277 write_data(f, &zero, 1);
4278 write_string(f, "s");
4280 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
4282 char *data = malloc(2 * num_buckets);
4284 for (i = 0; i < num_buckets; i++) {
4289 data[i * 2] = val&0xff;
4290 data[i * 2 + 1] = (val >> 8) & 0xff;
4293 write_data(f, data, num_buckets * 2);
4301 /* profiling samples the CPU PC as quickly as OpenOCD is able,
4302 * which will be used as a random sampling of PC */
4303 COMMAND_HANDLER(handle_profile_command)
4305 struct target *target = get_current_target(CMD_CTX);
4307 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
4308 return ERROR_COMMAND_SYNTAX_ERROR;
4310 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
4312 uint32_t num_of_samples;
4313 int retval = ERROR_OK;
4314 bool halted_before_profiling = target->state == TARGET_HALTED;
4316 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
4318 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
4320 LOG_ERROR("No memory to store samples.");
4324 uint64_t timestart_ms = timeval_ms();
4326 * Some cores let us sample the PC without the
4327 * annoying halt/resume step; for example, ARMv7 PCSR.
4328 * Provide a way to use that more efficient mechanism.
4330 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
4331 &num_of_samples, offset);
4332 if (retval != ERROR_OK) {
4336 uint32_t duration_ms = timeval_ms() - timestart_ms;
4338 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
4340 retval = target_poll(target);
4341 if (retval != ERROR_OK) {
4346 if (target->state == TARGET_RUNNING && halted_before_profiling) {
4347 /* The target was halted before we started and is running now. Halt it,
4348 * for consistency. */
4349 retval = target_halt(target);
4350 if (retval != ERROR_OK) {
4354 } else if (target->state == TARGET_HALTED && !halted_before_profiling) {
4355 /* The target was running before we started and is halted now. Resume
4356 * it, for consistency. */
4357 retval = target_resume(target, 1, 0, 0, 0);
4358 if (retval != ERROR_OK) {
4364 retval = target_poll(target);
4365 if (retval != ERROR_OK) {
4370 uint32_t start_address = 0;
4371 uint32_t end_address = 0;
4372 bool with_range = false;
4373 if (CMD_ARGC == 4) {
4375 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
4376 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
4379 write_gmon(samples, num_of_samples, CMD_ARGV[1],
4380 with_range, start_address, end_address, target, duration_ms);
4381 command_print(CMD, "Wrote %s", CMD_ARGV[1]);
4387 static int new_u64_array_element(Jim_Interp *interp, const char *varname, int idx, uint64_t val)
4390 Jim_Obj *obj_name, *obj_val;
4393 namebuf = alloc_printf("%s(%d)", varname, idx);
4397 obj_name = Jim_NewStringObj(interp, namebuf, -1);
4398 jim_wide wide_val = val;
4399 obj_val = Jim_NewWideObj(interp, wide_val);
4400 if (!obj_name || !obj_val) {
4405 Jim_IncrRefCount(obj_name);
4406 Jim_IncrRefCount(obj_val);
4407 result = Jim_SetVariable(interp, obj_name, obj_val);
4408 Jim_DecrRefCount(interp, obj_name);
4409 Jim_DecrRefCount(interp, obj_val);
4411 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
4415 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4417 struct command_context *context;
4418 struct target *target;
4420 context = current_command_context(interp);
4423 target = get_current_target(context);
4425 LOG_ERROR("mem2array: no current target");
4429 return target_mem2array(interp, target, argc - 1, argv + 1);
4432 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
4436 /* argv[0] = name of array to receive the data
4437 * argv[1] = desired element width in bits
4438 * argv[2] = memory address
4439 * argv[3] = count of times to read
4440 * argv[4] = optional "phys"
4442 if (argc < 4 || argc > 5) {
4443 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4447 /* Arg 0: Name of the array variable */
4448 const char *varname = Jim_GetString(argv[0], NULL);
4450 /* Arg 1: Bit width of one element */
4452 e = Jim_GetLong(interp, argv[1], &l);
4455 const unsigned int width_bits = l;
4457 if (width_bits != 8 &&
4461 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4462 Jim_AppendStrings(interp, Jim_GetResult(interp),
4463 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4466 const unsigned int width = width_bits / 8;
4468 /* Arg 2: Memory address */
4470 e = Jim_GetWide(interp, argv[2], &wide_addr);
4473 target_addr_t addr = (target_addr_t)wide_addr;
4475 /* Arg 3: Number of elements to read */
4476 e = Jim_GetLong(interp, argv[3], &l);
4482 bool is_phys = false;
4485 const char *phys = Jim_GetString(argv[4], &str_len);
4486 if (!strncmp(phys, "phys", str_len))
4492 /* Argument checks */
4494 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4495 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
4498 if ((addr + (len * width)) < addr) {
4499 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4500 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
4504 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4505 Jim_AppendStrings(interp, Jim_GetResult(interp),
4506 "mem2array: too large read request, exceeds 64K items", NULL);
4511 ((width == 2) && ((addr & 1) == 0)) ||
4512 ((width == 4) && ((addr & 3) == 0)) ||
4513 ((width == 8) && ((addr & 7) == 0))) {
4514 /* alignment correct */
4517 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4518 sprintf(buf, "mem2array address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4521 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4530 const size_t buffersize = 4096;
4531 uint8_t *buffer = malloc(buffersize);
4538 /* Slurp... in buffer size chunks */
4539 const unsigned int max_chunk_len = buffersize / width;
4540 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4544 retval = target_read_phys_memory(target, addr, width, chunk_len, buffer);
4546 retval = target_read_memory(target, addr, width, chunk_len, buffer);
4547 if (retval != ERROR_OK) {
4549 LOG_ERROR("mem2array: Read @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4553 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4554 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
4558 for (size_t i = 0; i < chunk_len ; i++, idx++) {
4562 v = target_buffer_get_u64(target, &buffer[i*width]);
4565 v = target_buffer_get_u32(target, &buffer[i*width]);
4568 v = target_buffer_get_u16(target, &buffer[i*width]);
4571 v = buffer[i] & 0x0ff;
4574 new_u64_array_element(interp, varname, idx, v);
4577 addr += chunk_len * width;
4583 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4588 static int get_u64_array_element(Jim_Interp *interp, const char *varname, size_t idx, uint64_t *val)
4590 char *namebuf = alloc_printf("%s(%zu)", varname, idx);
4594 Jim_Obj *obj_name = Jim_NewStringObj(interp, namebuf, -1);
4600 Jim_IncrRefCount(obj_name);
4601 Jim_Obj *obj_val = Jim_GetVariable(interp, obj_name, JIM_ERRMSG);
4602 Jim_DecrRefCount(interp, obj_name);
4608 int result = Jim_GetWide(interp, obj_val, &wide_val);
4613 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4615 struct command_context *context;
4616 struct target *target;
4618 context = current_command_context(interp);
4621 target = get_current_target(context);
4623 LOG_ERROR("array2mem: no current target");
4627 return target_array2mem(interp, target, argc-1, argv + 1);
4630 static int target_array2mem(Jim_Interp *interp, struct target *target,
4631 int argc, Jim_Obj *const *argv)
4635 /* argv[0] = name of array from which to read the data
4636 * argv[1] = desired element width in bits
4637 * argv[2] = memory address
4638 * argv[3] = number of elements to write
4639 * argv[4] = optional "phys"
4641 if (argc < 4 || argc > 5) {
4642 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4646 /* Arg 0: Name of the array variable */
4647 const char *varname = Jim_GetString(argv[0], NULL);
4649 /* Arg 1: Bit width of one element */
4651 e = Jim_GetLong(interp, argv[1], &l);
4654 const unsigned int width_bits = l;
4656 if (width_bits != 8 &&
4660 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4661 Jim_AppendStrings(interp, Jim_GetResult(interp),
4662 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4665 const unsigned int width = width_bits / 8;
4667 /* Arg 2: Memory address */
4669 e = Jim_GetWide(interp, argv[2], &wide_addr);
4672 target_addr_t addr = (target_addr_t)wide_addr;
4674 /* Arg 3: Number of elements to write */
4675 e = Jim_GetLong(interp, argv[3], &l);
4681 bool is_phys = false;
4684 const char *phys = Jim_GetString(argv[4], &str_len);
4685 if (!strncmp(phys, "phys", str_len))
4691 /* Argument checks */
4693 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4694 Jim_AppendStrings(interp, Jim_GetResult(interp),
4695 "array2mem: zero width read?", NULL);
4699 if ((addr + (len * width)) < addr) {
4700 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4701 Jim_AppendStrings(interp, Jim_GetResult(interp),
4702 "array2mem: addr + len - wraps to zero?", NULL);
4707 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4708 Jim_AppendStrings(interp, Jim_GetResult(interp),
4709 "array2mem: too large memory write request, exceeds 64K items", NULL);
4714 ((width == 2) && ((addr & 1) == 0)) ||
4715 ((width == 4) && ((addr & 3) == 0)) ||
4716 ((width == 8) && ((addr & 7) == 0))) {
4717 /* alignment correct */
4720 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4721 sprintf(buf, "array2mem address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4724 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4733 const size_t buffersize = 4096;
4734 uint8_t *buffer = malloc(buffersize);
4742 /* Slurp... in buffer size chunks */
4743 const unsigned int max_chunk_len = buffersize / width;
4745 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4747 /* Fill the buffer */
4748 for (size_t i = 0; i < chunk_len; i++, idx++) {
4750 if (get_u64_array_element(interp, varname, idx, &v) != JIM_OK) {
4756 target_buffer_set_u64(target, &buffer[i * width], v);
4759 target_buffer_set_u32(target, &buffer[i * width], v);
4762 target_buffer_set_u16(target, &buffer[i * width], v);
4765 buffer[i] = v & 0x0ff;
4771 /* Write the buffer to memory */
4774 retval = target_write_phys_memory(target, addr, width, chunk_len, buffer);
4776 retval = target_write_memory(target, addr, width, chunk_len, buffer);
4777 if (retval != ERROR_OK) {
4779 LOG_ERROR("array2mem: Write @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4783 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4784 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4788 addr += chunk_len * width;
4793 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4798 /* FIX? should we propagate errors here rather than printing them
4801 void target_handle_event(struct target *target, enum target_event e)
4803 struct target_event_action *teap;
4806 for (teap = target->event_action; teap; teap = teap->next) {
4807 if (teap->event == e) {
4808 LOG_DEBUG("target(%d): %s (%s) event: %d (%s) action: %s",
4809 target->target_number,
4810 target_name(target),
4811 target_type_name(target),
4813 jim_nvp_value2name_simple(nvp_target_event, e)->name,
4814 Jim_GetString(teap->body, NULL));
4816 /* Override current target by the target an event
4817 * is issued from (lot of scripts need it).
4818 * Return back to previous override as soon
4819 * as the handler processing is done */
4820 struct command_context *cmd_ctx = current_command_context(teap->interp);
4821 struct target *saved_target_override = cmd_ctx->current_target_override;
4822 cmd_ctx->current_target_override = target;
4824 retval = Jim_EvalObj(teap->interp, teap->body);
4826 cmd_ctx->current_target_override = saved_target_override;
4828 if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
4831 if (retval == JIM_RETURN)
4832 retval = teap->interp->returnCode;
4834 if (retval != JIM_OK) {
4835 Jim_MakeErrorMessage(teap->interp);
4836 LOG_USER("Error executing event %s on target %s:\n%s",
4837 jim_nvp_value2name_simple(nvp_target_event, e)->name,
4838 target_name(target),
4839 Jim_GetString(Jim_GetResult(teap->interp), NULL));
4840 /* clean both error code and stacktrace before return */
4841 Jim_Eval(teap->interp, "error \"\" \"\"");
4848 * Returns true only if the target has a handler for the specified event.
4850 bool target_has_event_action(struct target *target, enum target_event event)
4852 struct target_event_action *teap;
4854 for (teap = target->event_action; teap; teap = teap->next) {
4855 if (teap->event == event)
4861 enum target_cfg_param {
4864 TCFG_WORK_AREA_VIRT,
4865 TCFG_WORK_AREA_PHYS,
4866 TCFG_WORK_AREA_SIZE,
4867 TCFG_WORK_AREA_BACKUP,
4870 TCFG_CHAIN_POSITION,
4875 TCFG_GDB_MAX_CONNECTIONS,
4878 static struct jim_nvp nvp_config_opts[] = {
4879 { .name = "-type", .value = TCFG_TYPE },
4880 { .name = "-event", .value = TCFG_EVENT },
4881 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4882 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4883 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4884 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4885 { .name = "-endian", .value = TCFG_ENDIAN },
4886 { .name = "-coreid", .value = TCFG_COREID },
4887 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4888 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4889 { .name = "-rtos", .value = TCFG_RTOS },
4890 { .name = "-defer-examine", .value = TCFG_DEFER_EXAMINE },
4891 { .name = "-gdb-port", .value = TCFG_GDB_PORT },
4892 { .name = "-gdb-max-connections", .value = TCFG_GDB_MAX_CONNECTIONS },
4893 { .name = NULL, .value = -1 }
4896 static int target_configure(struct jim_getopt_info *goi, struct target *target)
4903 /* parse config or cget options ... */
4904 while (goi->argc > 0) {
4905 Jim_SetEmptyResult(goi->interp);
4906 /* jim_getopt_debug(goi); */
4908 if (target->type->target_jim_configure) {
4909 /* target defines a configure function */
4910 /* target gets first dibs on parameters */
4911 e = (*(target->type->target_jim_configure))(target, goi);
4920 /* otherwise we 'continue' below */
4922 e = jim_getopt_nvp(goi, nvp_config_opts, &n);
4924 jim_getopt_nvp_unknown(goi, nvp_config_opts, 0);
4930 if (goi->isconfigure) {
4931 Jim_SetResultFormatted(goi->interp,
4932 "not settable: %s", n->name);
4936 if (goi->argc != 0) {
4937 Jim_WrongNumArgs(goi->interp,
4938 goi->argc, goi->argv,
4943 Jim_SetResultString(goi->interp,
4944 target_type_name(target), -1);
4948 if (goi->argc == 0) {
4949 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4953 e = jim_getopt_nvp(goi, nvp_target_event, &n);
4955 jim_getopt_nvp_unknown(goi, nvp_target_event, 1);
4959 if (goi->isconfigure) {
4960 if (goi->argc != 1) {
4961 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4965 if (goi->argc != 0) {
4966 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4972 struct target_event_action *teap;
4974 teap = target->event_action;
4975 /* replace existing? */
4977 if (teap->event == (enum target_event)n->value)
4982 if (goi->isconfigure) {
4983 /* START_DEPRECATED_TPIU */
4984 if (n->value == TARGET_EVENT_TRACE_CONFIG)
4985 LOG_INFO("DEPRECATED target event %s", n->name);
4986 /* END_DEPRECATED_TPIU */
4988 bool replace = true;
4991 teap = calloc(1, sizeof(*teap));
4994 teap->event = n->value;
4995 teap->interp = goi->interp;
4996 jim_getopt_obj(goi, &o);
4998 Jim_DecrRefCount(teap->interp, teap->body);
4999 teap->body = Jim_DuplicateObj(goi->interp, o);
5002 * Tcl/TK - "tk events" have a nice feature.
5003 * See the "BIND" command.
5004 * We should support that here.
5005 * You can specify %X and %Y in the event code.
5006 * The idea is: %T - target name.
5007 * The idea is: %N - target number
5008 * The idea is: %E - event name.
5010 Jim_IncrRefCount(teap->body);
5013 /* add to head of event list */
5014 teap->next = target->event_action;
5015 target->event_action = teap;
5017 Jim_SetEmptyResult(goi->interp);
5021 Jim_SetEmptyResult(goi->interp);
5023 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
5029 case TCFG_WORK_AREA_VIRT:
5030 if (goi->isconfigure) {
5031 target_free_all_working_areas(target);
5032 e = jim_getopt_wide(goi, &w);
5035 target->working_area_virt = w;
5036 target->working_area_virt_spec = true;
5041 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
5045 case TCFG_WORK_AREA_PHYS:
5046 if (goi->isconfigure) {
5047 target_free_all_working_areas(target);
5048 e = jim_getopt_wide(goi, &w);
5051 target->working_area_phys = w;
5052 target->working_area_phys_spec = true;
5057 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
5061 case TCFG_WORK_AREA_SIZE:
5062 if (goi->isconfigure) {
5063 target_free_all_working_areas(target);
5064 e = jim_getopt_wide(goi, &w);
5067 target->working_area_size = w;
5072 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
5076 case TCFG_WORK_AREA_BACKUP:
5077 if (goi->isconfigure) {
5078 target_free_all_working_areas(target);
5079 e = jim_getopt_wide(goi, &w);
5082 /* make this exactly 1 or 0 */
5083 target->backup_working_area = (!!w);
5088 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
5089 /* loop for more e*/
5094 if (goi->isconfigure) {
5095 e = jim_getopt_nvp(goi, nvp_target_endian, &n);
5097 jim_getopt_nvp_unknown(goi, nvp_target_endian, 1);
5100 target->endianness = n->value;
5105 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5107 target->endianness = TARGET_LITTLE_ENDIAN;
5108 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5110 Jim_SetResultString(goi->interp, n->name, -1);
5115 if (goi->isconfigure) {
5116 e = jim_getopt_wide(goi, &w);
5119 target->coreid = (int32_t)w;
5124 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->coreid));
5128 case TCFG_CHAIN_POSITION:
5129 if (goi->isconfigure) {
5131 struct jtag_tap *tap;
5133 if (target->has_dap) {
5134 Jim_SetResultString(goi->interp,
5135 "target requires -dap parameter instead of -chain-position!", -1);
5139 target_free_all_working_areas(target);
5140 e = jim_getopt_obj(goi, &o_t);
5143 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
5147 target->tap_configured = true;
5152 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
5153 /* loop for more e*/
5156 if (goi->isconfigure) {
5157 e = jim_getopt_wide(goi, &w);
5160 target->dbgbase = (uint32_t)w;
5161 target->dbgbase_set = true;
5166 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
5172 int result = rtos_create(goi, target);
5173 if (result != JIM_OK)
5179 case TCFG_DEFER_EXAMINE:
5181 target->defer_examine = true;
5186 if (goi->isconfigure) {
5187 struct command_context *cmd_ctx = current_command_context(goi->interp);
5188 if (cmd_ctx->mode != COMMAND_CONFIG) {
5189 Jim_SetResultString(goi->interp, "-gdb-port must be configured before 'init'", -1);
5194 e = jim_getopt_string(goi, &s, NULL);
5197 free(target->gdb_port_override);
5198 target->gdb_port_override = strdup(s);
5203 Jim_SetResultString(goi->interp, target->gdb_port_override ? target->gdb_port_override : "undefined", -1);
5207 case TCFG_GDB_MAX_CONNECTIONS:
5208 if (goi->isconfigure) {
5209 struct command_context *cmd_ctx = current_command_context(goi->interp);
5210 if (cmd_ctx->mode != COMMAND_CONFIG) {
5211 Jim_SetResultString(goi->interp, "-gdb-max-connections must be configured before 'init'", -1);
5215 e = jim_getopt_wide(goi, &w);
5218 target->gdb_max_connections = (w < 0) ? CONNECTION_LIMIT_UNLIMITED : (int)w;
5223 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->gdb_max_connections));
5226 } /* while (goi->argc) */
5229 /* done - we return */
5233 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5235 struct command *c = jim_to_command(interp);
5236 struct jim_getopt_info goi;
5238 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5239 goi.isconfigure = !strcmp(c->name, "configure");
5241 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5242 "missing: -option ...");
5245 struct command_context *cmd_ctx = current_command_context(interp);
5247 struct target *target = get_current_target(cmd_ctx);
5248 return target_configure(&goi, target);
5251 static int jim_target_mem2array(Jim_Interp *interp,
5252 int argc, Jim_Obj *const *argv)
5254 struct command_context *cmd_ctx = current_command_context(interp);
5256 struct target *target = get_current_target(cmd_ctx);
5257 return target_mem2array(interp, target, argc - 1, argv + 1);
5260 static int jim_target_array2mem(Jim_Interp *interp,
5261 int argc, Jim_Obj *const *argv)
5263 struct command_context *cmd_ctx = current_command_context(interp);
5265 struct target *target = get_current_target(cmd_ctx);
5266 return target_array2mem(interp, target, argc - 1, argv + 1);
5269 static int jim_target_tap_disabled(Jim_Interp *interp)
5271 Jim_SetResultFormatted(interp, "[TAP is disabled]");
5275 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5277 bool allow_defer = false;
5279 struct jim_getopt_info goi;
5280 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5282 const char *cmd_name = Jim_GetString(argv[0], NULL);
5283 Jim_SetResultFormatted(goi.interp,
5284 "usage: %s ['allow-defer']", cmd_name);
5288 strcmp(Jim_GetString(argv[1], NULL), "allow-defer") == 0) {
5291 int e = jim_getopt_obj(&goi, &obj);
5297 struct command_context *cmd_ctx = current_command_context(interp);
5299 struct target *target = get_current_target(cmd_ctx);
5300 if (!target->tap->enabled)
5301 return jim_target_tap_disabled(interp);
5303 if (allow_defer && target->defer_examine) {
5304 LOG_INFO("Deferring arp_examine of %s", target_name(target));
5305 LOG_INFO("Use arp_examine command to examine it manually!");
5309 int e = target->type->examine(target);
5315 static int jim_target_was_examined(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5317 struct command_context *cmd_ctx = current_command_context(interp);
5319 struct target *target = get_current_target(cmd_ctx);
5321 Jim_SetResultBool(interp, target_was_examined(target));
5325 static int jim_target_examine_deferred(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5327 struct command_context *cmd_ctx = current_command_context(interp);
5329 struct target *target = get_current_target(cmd_ctx);
5331 Jim_SetResultBool(interp, target->defer_examine);
5335 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5338 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5341 struct command_context *cmd_ctx = current_command_context(interp);
5343 struct target *target = get_current_target(cmd_ctx);
5345 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
5351 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5354 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5357 struct command_context *cmd_ctx = current_command_context(interp);
5359 struct target *target = get_current_target(cmd_ctx);
5360 if (!target->tap->enabled)
5361 return jim_target_tap_disabled(interp);
5364 if (!(target_was_examined(target)))
5365 e = ERROR_TARGET_NOT_EXAMINED;
5367 e = target->type->poll(target);
5373 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5375 struct jim_getopt_info goi;
5376 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5378 if (goi.argc != 2) {
5379 Jim_WrongNumArgs(interp, 0, argv,
5380 "([tT]|[fF]|assert|deassert) BOOL");
5385 int e = jim_getopt_nvp(&goi, nvp_assert, &n);
5387 jim_getopt_nvp_unknown(&goi, nvp_assert, 1);
5390 /* the halt or not param */
5392 e = jim_getopt_wide(&goi, &a);
5396 struct command_context *cmd_ctx = current_command_context(interp);
5398 struct target *target = get_current_target(cmd_ctx);
5399 if (!target->tap->enabled)
5400 return jim_target_tap_disabled(interp);
5402 if (!target->type->assert_reset || !target->type->deassert_reset) {
5403 Jim_SetResultFormatted(interp,
5404 "No target-specific reset for %s",
5405 target_name(target));
5409 if (target->defer_examine)
5410 target_reset_examined(target);
5412 /* determine if we should halt or not. */
5413 target->reset_halt = (a != 0);
5414 /* When this happens - all workareas are invalid. */
5415 target_free_all_working_areas_restore(target, 0);
5418 if (n->value == NVP_ASSERT)
5419 e = target->type->assert_reset(target);
5421 e = target->type->deassert_reset(target);
5422 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5425 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5428 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5431 struct command_context *cmd_ctx = current_command_context(interp);
5433 struct target *target = get_current_target(cmd_ctx);
5434 if (!target->tap->enabled)
5435 return jim_target_tap_disabled(interp);
5436 int e = target->type->halt(target);
5437 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5440 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5442 struct jim_getopt_info goi;
5443 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5445 /* params: <name> statename timeoutmsecs */
5446 if (goi.argc != 2) {
5447 const char *cmd_name = Jim_GetString(argv[0], NULL);
5448 Jim_SetResultFormatted(goi.interp,
5449 "%s <state_name> <timeout_in_msec>", cmd_name);
5454 int e = jim_getopt_nvp(&goi, nvp_target_state, &n);
5456 jim_getopt_nvp_unknown(&goi, nvp_target_state, 1);
5460 e = jim_getopt_wide(&goi, &a);
5463 struct command_context *cmd_ctx = current_command_context(interp);
5465 struct target *target = get_current_target(cmd_ctx);
5466 if (!target->tap->enabled)
5467 return jim_target_tap_disabled(interp);
5469 e = target_wait_state(target, n->value, a);
5470 if (e != ERROR_OK) {
5471 Jim_Obj *obj = Jim_NewIntObj(interp, e);
5472 Jim_SetResultFormatted(goi.interp,
5473 "target: %s wait %s fails (%#s) %s",
5474 target_name(target), n->name,
5475 obj, target_strerror_safe(e));
5480 /* List for human, Events defined for this target.
5481 * scripts/programs should use 'name cget -event NAME'
5483 COMMAND_HANDLER(handle_target_event_list)
5485 struct target *target = get_current_target(CMD_CTX);
5486 struct target_event_action *teap = target->event_action;
5488 command_print(CMD, "Event actions for target (%d) %s\n",
5489 target->target_number,
5490 target_name(target));
5491 command_print(CMD, "%-25s | Body", "Event");
5492 command_print(CMD, "------------------------- | "
5493 "----------------------------------------");
5495 struct jim_nvp *opt = jim_nvp_value2name_simple(nvp_target_event, teap->event);
5496 command_print(CMD, "%-25s | %s",
5497 opt->name, Jim_GetString(teap->body, NULL));
5500 command_print(CMD, "***END***");
5503 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5506 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5509 struct command_context *cmd_ctx = current_command_context(interp);
5511 struct target *target = get_current_target(cmd_ctx);
5512 Jim_SetResultString(interp, target_state_name(target), -1);
5515 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5517 struct jim_getopt_info goi;
5518 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5519 if (goi.argc != 1) {
5520 const char *cmd_name = Jim_GetString(argv[0], NULL);
5521 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5525 int e = jim_getopt_nvp(&goi, nvp_target_event, &n);
5527 jim_getopt_nvp_unknown(&goi, nvp_target_event, 1);
5530 struct command_context *cmd_ctx = current_command_context(interp);
5532 struct target *target = get_current_target(cmd_ctx);
5533 target_handle_event(target, n->value);
5537 static const struct command_registration target_instance_command_handlers[] = {
5539 .name = "configure",
5540 .mode = COMMAND_ANY,
5541 .jim_handler = jim_target_configure,
5542 .help = "configure a new target for use",
5543 .usage = "[target_attribute ...]",
5547 .mode = COMMAND_ANY,
5548 .jim_handler = jim_target_configure,
5549 .help = "returns the specified target attribute",
5550 .usage = "target_attribute",
5554 .handler = handle_mw_command,
5555 .mode = COMMAND_EXEC,
5556 .help = "Write 64-bit word(s) to target memory",
5557 .usage = "address data [count]",
5561 .handler = handle_mw_command,
5562 .mode = COMMAND_EXEC,
5563 .help = "Write 32-bit word(s) to target memory",
5564 .usage = "address data [count]",
5568 .handler = handle_mw_command,
5569 .mode = COMMAND_EXEC,
5570 .help = "Write 16-bit half-word(s) to target memory",
5571 .usage = "address data [count]",
5575 .handler = handle_mw_command,
5576 .mode = COMMAND_EXEC,
5577 .help = "Write byte(s) to target memory",
5578 .usage = "address data [count]",
5582 .handler = handle_md_command,
5583 .mode = COMMAND_EXEC,
5584 .help = "Display target memory as 64-bit words",
5585 .usage = "address [count]",
5589 .handler = handle_md_command,
5590 .mode = COMMAND_EXEC,
5591 .help = "Display target memory as 32-bit words",
5592 .usage = "address [count]",
5596 .handler = handle_md_command,
5597 .mode = COMMAND_EXEC,
5598 .help = "Display target memory as 16-bit half-words",
5599 .usage = "address [count]",
5603 .handler = handle_md_command,
5604 .mode = COMMAND_EXEC,
5605 .help = "Display target memory as 8-bit bytes",
5606 .usage = "address [count]",
5609 .name = "array2mem",
5610 .mode = COMMAND_EXEC,
5611 .jim_handler = jim_target_array2mem,
5612 .help = "Writes Tcl array of 8/16/32 bit numbers "
5614 .usage = "arrayname bitwidth address count",
5617 .name = "mem2array",
5618 .mode = COMMAND_EXEC,
5619 .jim_handler = jim_target_mem2array,
5620 .help = "Loads Tcl array of 8/16/32 bit numbers "
5621 "from target memory",
5622 .usage = "arrayname bitwidth address count",
5625 .name = "eventlist",
5626 .handler = handle_target_event_list,
5627 .mode = COMMAND_EXEC,
5628 .help = "displays a table of events defined for this target",
5633 .mode = COMMAND_EXEC,
5634 .jim_handler = jim_target_current_state,
5635 .help = "displays the current state of this target",
5638 .name = "arp_examine",
5639 .mode = COMMAND_EXEC,
5640 .jim_handler = jim_target_examine,
5641 .help = "used internally for reset processing",
5642 .usage = "['allow-defer']",
5645 .name = "was_examined",
5646 .mode = COMMAND_EXEC,
5647 .jim_handler = jim_target_was_examined,
5648 .help = "used internally for reset processing",
5651 .name = "examine_deferred",
5652 .mode = COMMAND_EXEC,
5653 .jim_handler = jim_target_examine_deferred,
5654 .help = "used internally for reset processing",
5657 .name = "arp_halt_gdb",
5658 .mode = COMMAND_EXEC,
5659 .jim_handler = jim_target_halt_gdb,
5660 .help = "used internally for reset processing to halt GDB",
5664 .mode = COMMAND_EXEC,
5665 .jim_handler = jim_target_poll,
5666 .help = "used internally for reset processing",
5669 .name = "arp_reset",
5670 .mode = COMMAND_EXEC,
5671 .jim_handler = jim_target_reset,
5672 .help = "used internally for reset processing",
5676 .mode = COMMAND_EXEC,
5677 .jim_handler = jim_target_halt,
5678 .help = "used internally for reset processing",
5681 .name = "arp_waitstate",
5682 .mode = COMMAND_EXEC,
5683 .jim_handler = jim_target_wait_state,
5684 .help = "used internally for reset processing",
5687 .name = "invoke-event",
5688 .mode = COMMAND_EXEC,
5689 .jim_handler = jim_target_invoke_event,
5690 .help = "invoke handler for specified event",
5691 .usage = "event_name",
5693 COMMAND_REGISTRATION_DONE
5696 static int target_create(struct jim_getopt_info *goi)
5703 struct target *target;
5704 struct command_context *cmd_ctx;
5706 cmd_ctx = current_command_context(goi->interp);
5709 if (goi->argc < 3) {
5710 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5715 jim_getopt_obj(goi, &new_cmd);
5716 /* does this command exist? */
5717 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
5719 cp = Jim_GetString(new_cmd, NULL);
5720 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5725 e = jim_getopt_string(goi, &cp, NULL);
5728 struct transport *tr = get_current_transport();
5729 if (tr->override_target) {
5730 e = tr->override_target(&cp);
5731 if (e != ERROR_OK) {
5732 LOG_ERROR("The selected transport doesn't support this target");
5735 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5737 /* now does target type exist */
5738 for (x = 0 ; target_types[x] ; x++) {
5739 if (strcmp(cp, target_types[x]->name) == 0) {
5744 if (!target_types[x]) {
5745 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5746 for (x = 0 ; target_types[x] ; x++) {
5747 if (target_types[x + 1]) {
5748 Jim_AppendStrings(goi->interp,
5749 Jim_GetResult(goi->interp),
5750 target_types[x]->name,
5753 Jim_AppendStrings(goi->interp,
5754 Jim_GetResult(goi->interp),
5756 target_types[x]->name, NULL);
5763 target = calloc(1, sizeof(struct target));
5765 LOG_ERROR("Out of memory");
5769 /* set target number */
5770 target->target_number = new_target_number();
5772 /* allocate memory for each unique target type */
5773 target->type = malloc(sizeof(struct target_type));
5774 if (!target->type) {
5775 LOG_ERROR("Out of memory");
5780 memcpy(target->type, target_types[x], sizeof(struct target_type));
5782 /* default to first core, override with -coreid */
5785 target->working_area = 0x0;
5786 target->working_area_size = 0x0;
5787 target->working_areas = NULL;
5788 target->backup_working_area = 0;
5790 target->state = TARGET_UNKNOWN;
5791 target->debug_reason = DBG_REASON_UNDEFINED;
5792 target->reg_cache = NULL;
5793 target->breakpoints = NULL;
5794 target->watchpoints = NULL;
5795 target->next = NULL;
5796 target->arch_info = NULL;
5798 target->verbose_halt_msg = true;
5800 target->halt_issued = false;
5802 /* initialize trace information */
5803 target->trace_info = calloc(1, sizeof(struct trace));
5804 if (!target->trace_info) {
5805 LOG_ERROR("Out of memory");
5811 target->dbgmsg = NULL;
5812 target->dbg_msg_enabled = 0;
5814 target->endianness = TARGET_ENDIAN_UNKNOWN;
5816 target->rtos = NULL;
5817 target->rtos_auto_detect = false;
5819 target->gdb_port_override = NULL;
5820 target->gdb_max_connections = 1;
5822 /* Do the rest as "configure" options */
5823 goi->isconfigure = 1;
5824 e = target_configure(goi, target);
5827 if (target->has_dap) {
5828 if (!target->dap_configured) {
5829 Jim_SetResultString(goi->interp, "-dap ?name? required when creating target", -1);
5833 if (!target->tap_configured) {
5834 Jim_SetResultString(goi->interp, "-chain-position ?name? required when creating target", -1);
5838 /* tap must be set after target was configured */
5844 rtos_destroy(target);
5845 free(target->gdb_port_override);
5846 free(target->trace_info);
5852 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5853 /* default endian to little if not specified */
5854 target->endianness = TARGET_LITTLE_ENDIAN;
5857 cp = Jim_GetString(new_cmd, NULL);
5858 target->cmd_name = strdup(cp);
5859 if (!target->cmd_name) {
5860 LOG_ERROR("Out of memory");
5861 rtos_destroy(target);
5862 free(target->gdb_port_override);
5863 free(target->trace_info);
5869 if (target->type->target_create) {
5870 e = (*(target->type->target_create))(target, goi->interp);
5871 if (e != ERROR_OK) {
5872 LOG_DEBUG("target_create failed");
5873 free(target->cmd_name);
5874 rtos_destroy(target);
5875 free(target->gdb_port_override);
5876 free(target->trace_info);
5883 /* create the target specific commands */
5884 if (target->type->commands) {
5885 e = register_commands(cmd_ctx, NULL, target->type->commands);
5887 LOG_ERROR("unable to register '%s' commands", cp);
5890 /* now - create the new target name command */
5891 const struct command_registration target_subcommands[] = {
5893 .chain = target_instance_command_handlers,
5896 .chain = target->type->commands,
5898 COMMAND_REGISTRATION_DONE
5900 const struct command_registration target_commands[] = {
5903 .mode = COMMAND_ANY,
5904 .help = "target command group",
5906 .chain = target_subcommands,
5908 COMMAND_REGISTRATION_DONE
5910 e = register_commands_override_target(cmd_ctx, NULL, target_commands, target);
5911 if (e != ERROR_OK) {
5912 if (target->type->deinit_target)
5913 target->type->deinit_target(target);
5914 free(target->cmd_name);
5915 rtos_destroy(target);
5916 free(target->gdb_port_override);
5917 free(target->trace_info);
5923 /* append to end of list */
5924 append_to_list_all_targets(target);
5926 cmd_ctx->current_target = target;
5930 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5933 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5936 struct command_context *cmd_ctx = current_command_context(interp);
5939 struct target *target = get_current_target_or_null(cmd_ctx);
5941 Jim_SetResultString(interp, target_name(target), -1);
5945 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5948 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5951 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5952 for (unsigned x = 0; target_types[x]; x++) {
5953 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5954 Jim_NewStringObj(interp, target_types[x]->name, -1));
5959 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5962 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5965 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5966 struct target *target = all_targets;
5968 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5969 Jim_NewStringObj(interp, target_name(target), -1));
5970 target = target->next;
5975 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5978 const char *targetname;
5980 struct target *target = (struct target *) NULL;
5981 struct target_list *head, *curr, *new;
5982 curr = (struct target_list *) NULL;
5983 head = (struct target_list *) NULL;
5986 LOG_DEBUG("%d", argc);
5987 /* argv[1] = target to associate in smp
5988 * argv[2] = target to associate in smp
5992 for (i = 1; i < argc; i++) {
5994 targetname = Jim_GetString(argv[i], &len);
5995 target = get_target(targetname);
5996 LOG_DEBUG("%s ", targetname);
5998 new = malloc(sizeof(struct target_list));
5999 new->target = target;
6000 new->next = (struct target_list *)NULL;
6001 if (head == (struct target_list *)NULL) {
6010 /* now parse the list of cpu and put the target in smp mode*/
6013 while (curr != (struct target_list *)NULL) {
6014 target = curr->target;
6016 target->head = head;
6020 if (target && target->rtos)
6021 retval = rtos_smp_init(head->target);
6027 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6029 struct jim_getopt_info goi;
6030 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
6032 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
6033 "<name> <target_type> [<target_options> ...]");
6036 return target_create(&goi);
6039 static const struct command_registration target_subcommand_handlers[] = {
6042 .mode = COMMAND_CONFIG,
6043 .handler = handle_target_init_command,
6044 .help = "initialize targets",
6049 .mode = COMMAND_CONFIG,
6050 .jim_handler = jim_target_create,
6051 .usage = "name type '-chain-position' name [options ...]",
6052 .help = "Creates and selects a new target",
6056 .mode = COMMAND_ANY,
6057 .jim_handler = jim_target_current,
6058 .help = "Returns the currently selected target",
6062 .mode = COMMAND_ANY,
6063 .jim_handler = jim_target_types,
6064 .help = "Returns the available target types as "
6065 "a list of strings",
6069 .mode = COMMAND_ANY,
6070 .jim_handler = jim_target_names,
6071 .help = "Returns the names of all targets as a list of strings",
6075 .mode = COMMAND_ANY,
6076 .jim_handler = jim_target_smp,
6077 .usage = "targetname1 targetname2 ...",
6078 .help = "gather several target in a smp list"
6081 COMMAND_REGISTRATION_DONE
6085 target_addr_t address;
6091 static int fastload_num;
6092 static struct fast_load *fastload;
6094 static void free_fastload(void)
6097 for (int i = 0; i < fastload_num; i++)
6098 free(fastload[i].data);
6104 COMMAND_HANDLER(handle_fast_load_image_command)
6108 uint32_t image_size;
6109 target_addr_t min_address = 0;
6110 target_addr_t max_address = -1;
6114 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
6115 &image, &min_address, &max_address);
6116 if (retval != ERROR_OK)
6119 struct duration bench;
6120 duration_start(&bench);
6122 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
6123 if (retval != ERROR_OK)
6128 fastload_num = image.num_sections;
6129 fastload = malloc(sizeof(struct fast_load)*image.num_sections);
6131 command_print(CMD, "out of memory");
6132 image_close(&image);
6135 memset(fastload, 0, sizeof(struct fast_load)*image.num_sections);
6136 for (unsigned int i = 0; i < image.num_sections; i++) {
6137 buffer = malloc(image.sections[i].size);
6139 command_print(CMD, "error allocating buffer for section (%d bytes)",
6140 (int)(image.sections[i].size));
6141 retval = ERROR_FAIL;
6145 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
6146 if (retval != ERROR_OK) {
6151 uint32_t offset = 0;
6152 uint32_t length = buf_cnt;
6154 /* DANGER!!! beware of unsigned comparison here!!! */
6156 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
6157 (image.sections[i].base_address < max_address)) {
6158 if (image.sections[i].base_address < min_address) {
6159 /* clip addresses below */
6160 offset += min_address-image.sections[i].base_address;
6164 if (image.sections[i].base_address + buf_cnt > max_address)
6165 length -= (image.sections[i].base_address + buf_cnt)-max_address;
6167 fastload[i].address = image.sections[i].base_address + offset;
6168 fastload[i].data = malloc(length);
6169 if (!fastload[i].data) {
6171 command_print(CMD, "error allocating buffer for section (%" PRIu32 " bytes)",
6173 retval = ERROR_FAIL;
6176 memcpy(fastload[i].data, buffer + offset, length);
6177 fastload[i].length = length;
6179 image_size += length;
6180 command_print(CMD, "%u bytes written at address 0x%8.8x",
6181 (unsigned int)length,
6182 ((unsigned int)(image.sections[i].base_address + offset)));
6188 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
6189 command_print(CMD, "Loaded %" PRIu32 " bytes "
6190 "in %fs (%0.3f KiB/s)", image_size,
6191 duration_elapsed(&bench), duration_kbps(&bench, image_size));
6194 "WARNING: image has not been loaded to target!"
6195 "You can issue a 'fast_load' to finish loading.");
6198 image_close(&image);
6200 if (retval != ERROR_OK)
6206 COMMAND_HANDLER(handle_fast_load_command)
6209 return ERROR_COMMAND_SYNTAX_ERROR;
6211 LOG_ERROR("No image in memory");
6215 int64_t ms = timeval_ms();
6217 int retval = ERROR_OK;
6218 for (i = 0; i < fastload_num; i++) {
6219 struct target *target = get_current_target(CMD_CTX);
6220 command_print(CMD, "Write to 0x%08x, length 0x%08x",
6221 (unsigned int)(fastload[i].address),
6222 (unsigned int)(fastload[i].length));
6223 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
6224 if (retval != ERROR_OK)
6226 size += fastload[i].length;
6228 if (retval == ERROR_OK) {
6229 int64_t after = timeval_ms();
6230 command_print(CMD, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
6235 static const struct command_registration target_command_handlers[] = {
6238 .handler = handle_targets_command,
6239 .mode = COMMAND_ANY,
6240 .help = "change current default target (one parameter) "
6241 "or prints table of all targets (no parameters)",
6242 .usage = "[target]",
6246 .mode = COMMAND_CONFIG,
6247 .help = "configure target",
6248 .chain = target_subcommand_handlers,
6251 COMMAND_REGISTRATION_DONE
6254 int target_register_commands(struct command_context *cmd_ctx)
6256 return register_commands(cmd_ctx, NULL, target_command_handlers);
6259 static bool target_reset_nag = true;
6261 bool get_target_reset_nag(void)
6263 return target_reset_nag;
6266 COMMAND_HANDLER(handle_target_reset_nag)
6268 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
6269 &target_reset_nag, "Nag after each reset about options to improve "
6273 COMMAND_HANDLER(handle_ps_command)
6275 struct target *target = get_current_target(CMD_CTX);
6277 if (target->state != TARGET_HALTED) {
6278 LOG_INFO("target not halted !!");
6282 if ((target->rtos) && (target->rtos->type)
6283 && (target->rtos->type->ps_command)) {
6284 display = target->rtos->type->ps_command(target);
6285 command_print(CMD, "%s", display);
6290 return ERROR_TARGET_FAILURE;
6294 static void binprint(struct command_invocation *cmd, const char *text, const uint8_t *buf, int size)
6297 command_print_sameline(cmd, "%s", text);
6298 for (int i = 0; i < size; i++)
6299 command_print_sameline(cmd, " %02x", buf[i]);
6300 command_print(cmd, " ");
6303 COMMAND_HANDLER(handle_test_mem_access_command)
6305 struct target *target = get_current_target(CMD_CTX);
6307 int retval = ERROR_OK;
6309 if (target->state != TARGET_HALTED) {
6310 LOG_INFO("target not halted !!");
6315 return ERROR_COMMAND_SYNTAX_ERROR;
6317 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
6320 size_t num_bytes = test_size + 4;
6322 struct working_area *wa = NULL;
6323 retval = target_alloc_working_area(target, num_bytes, &wa);
6324 if (retval != ERROR_OK) {
6325 LOG_ERROR("Not enough working area");
6329 uint8_t *test_pattern = malloc(num_bytes);
6331 for (size_t i = 0; i < num_bytes; i++)
6332 test_pattern[i] = rand();
6334 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6335 if (retval != ERROR_OK) {
6336 LOG_ERROR("Test pattern write failed");
6340 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6341 for (int size = 1; size <= 4; size *= 2) {
6342 for (int offset = 0; offset < 4; offset++) {
6343 uint32_t count = test_size / size;
6344 size_t host_bufsiz = (count + 2) * size + host_offset;
6345 uint8_t *read_ref = malloc(host_bufsiz);
6346 uint8_t *read_buf = malloc(host_bufsiz);
6348 for (size_t i = 0; i < host_bufsiz; i++) {
6349 read_ref[i] = rand();
6350 read_buf[i] = read_ref[i];
6352 command_print_sameline(CMD,
6353 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
6354 size, offset, host_offset ? "un" : "");
6356 struct duration bench;
6357 duration_start(&bench);
6359 retval = target_read_memory(target, wa->address + offset, size, count,
6360 read_buf + size + host_offset);
6362 duration_measure(&bench);
6364 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6365 command_print(CMD, "Unsupported alignment");
6367 } else if (retval != ERROR_OK) {
6368 command_print(CMD, "Memory read failed");
6372 /* replay on host */
6373 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
6376 int result = memcmp(read_ref, read_buf, host_bufsiz);
6378 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6379 duration_elapsed(&bench),
6380 duration_kbps(&bench, count * size));
6382 command_print(CMD, "Compare failed");
6383 binprint(CMD, "ref:", read_ref, host_bufsiz);
6384 binprint(CMD, "buf:", read_buf, host_bufsiz);
6397 target_free_working_area(target, wa);
6400 num_bytes = test_size + 4 + 4 + 4;
6402 retval = target_alloc_working_area(target, num_bytes, &wa);
6403 if (retval != ERROR_OK) {
6404 LOG_ERROR("Not enough working area");
6408 test_pattern = malloc(num_bytes);
6410 for (size_t i = 0; i < num_bytes; i++)
6411 test_pattern[i] = rand();
6413 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6414 for (int size = 1; size <= 4; size *= 2) {
6415 for (int offset = 0; offset < 4; offset++) {
6416 uint32_t count = test_size / size;
6417 size_t host_bufsiz = count * size + host_offset;
6418 uint8_t *read_ref = malloc(num_bytes);
6419 uint8_t *read_buf = malloc(num_bytes);
6420 uint8_t *write_buf = malloc(host_bufsiz);
6422 for (size_t i = 0; i < host_bufsiz; i++)
6423 write_buf[i] = rand();
6424 command_print_sameline(CMD,
6425 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
6426 size, offset, host_offset ? "un" : "");
6428 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6429 if (retval != ERROR_OK) {
6430 command_print(CMD, "Test pattern write failed");
6434 /* replay on host */
6435 memcpy(read_ref, test_pattern, num_bytes);
6436 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
6438 struct duration bench;
6439 duration_start(&bench);
6441 retval = target_write_memory(target, wa->address + size + offset, size, count,
6442 write_buf + host_offset);
6444 duration_measure(&bench);
6446 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6447 command_print(CMD, "Unsupported alignment");
6449 } else if (retval != ERROR_OK) {
6450 command_print(CMD, "Memory write failed");
6455 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
6456 if (retval != ERROR_OK) {
6457 command_print(CMD, "Test pattern write failed");
6462 int result = memcmp(read_ref, read_buf, num_bytes);
6464 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6465 duration_elapsed(&bench),
6466 duration_kbps(&bench, count * size));
6468 command_print(CMD, "Compare failed");
6469 binprint(CMD, "ref:", read_ref, num_bytes);
6470 binprint(CMD, "buf:", read_buf, num_bytes);
6482 target_free_working_area(target, wa);
6486 static const struct command_registration target_exec_command_handlers[] = {
6488 .name = "fast_load_image",
6489 .handler = handle_fast_load_image_command,
6490 .mode = COMMAND_ANY,
6491 .help = "Load image into server memory for later use by "
6492 "fast_load; primarily for profiling",
6493 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6494 "[min_address [max_length]]",
6497 .name = "fast_load",
6498 .handler = handle_fast_load_command,
6499 .mode = COMMAND_EXEC,
6500 .help = "loads active fast load image to current target "
6501 "- mainly for profiling purposes",
6506 .handler = handle_profile_command,
6507 .mode = COMMAND_EXEC,
6508 .usage = "seconds filename [start end]",
6509 .help = "profiling samples the CPU PC",
6511 /** @todo don't register virt2phys() unless target supports it */
6513 .name = "virt2phys",
6514 .handler = handle_virt2phys_command,
6515 .mode = COMMAND_ANY,
6516 .help = "translate a virtual address into a physical address",
6517 .usage = "virtual_address",
6521 .handler = handle_reg_command,
6522 .mode = COMMAND_EXEC,
6523 .help = "display (reread from target with \"force\") or set a register; "
6524 "with no arguments, displays all registers and their values",
6525 .usage = "[(register_number|register_name) [(value|'force')]]",
6529 .handler = handle_poll_command,
6530 .mode = COMMAND_EXEC,
6531 .help = "poll target state; or reconfigure background polling",
6532 .usage = "['on'|'off']",
6535 .name = "wait_halt",
6536 .handler = handle_wait_halt_command,
6537 .mode = COMMAND_EXEC,
6538 .help = "wait up to the specified number of milliseconds "
6539 "(default 5000) for a previously requested halt",
6540 .usage = "[milliseconds]",
6544 .handler = handle_halt_command,
6545 .mode = COMMAND_EXEC,
6546 .help = "request target to halt, then wait up to the specified "
6547 "number of milliseconds (default 5000) for it to complete",
6548 .usage = "[milliseconds]",
6552 .handler = handle_resume_command,
6553 .mode = COMMAND_EXEC,
6554 .help = "resume target execution from current PC or address",
6555 .usage = "[address]",
6559 .handler = handle_reset_command,
6560 .mode = COMMAND_EXEC,
6561 .usage = "[run|halt|init]",
6562 .help = "Reset all targets into the specified mode. "
6563 "Default reset mode is run, if not given.",
6566 .name = "soft_reset_halt",
6567 .handler = handle_soft_reset_halt_command,
6568 .mode = COMMAND_EXEC,
6570 .help = "halt the target and do a soft reset",
6574 .handler = handle_step_command,
6575 .mode = COMMAND_EXEC,
6576 .help = "step one instruction from current PC or address",
6577 .usage = "[address]",
6581 .handler = handle_md_command,
6582 .mode = COMMAND_EXEC,
6583 .help = "display memory double-words",
6584 .usage = "['phys'] address [count]",
6588 .handler = handle_md_command,
6589 .mode = COMMAND_EXEC,
6590 .help = "display memory words",
6591 .usage = "['phys'] address [count]",
6595 .handler = handle_md_command,
6596 .mode = COMMAND_EXEC,
6597 .help = "display memory half-words",
6598 .usage = "['phys'] address [count]",
6602 .handler = handle_md_command,
6603 .mode = COMMAND_EXEC,
6604 .help = "display memory bytes",
6605 .usage = "['phys'] address [count]",
6609 .handler = handle_mw_command,
6610 .mode = COMMAND_EXEC,
6611 .help = "write memory double-word",
6612 .usage = "['phys'] address value [count]",
6616 .handler = handle_mw_command,
6617 .mode = COMMAND_EXEC,
6618 .help = "write memory word",
6619 .usage = "['phys'] address value [count]",
6623 .handler = handle_mw_command,
6624 .mode = COMMAND_EXEC,
6625 .help = "write memory half-word",
6626 .usage = "['phys'] address value [count]",
6630 .handler = handle_mw_command,
6631 .mode = COMMAND_EXEC,
6632 .help = "write memory byte",
6633 .usage = "['phys'] address value [count]",
6637 .handler = handle_bp_command,
6638 .mode = COMMAND_EXEC,
6639 .help = "list or set hardware or software breakpoint",
6640 .usage = "[<address> [<asid>] <length> ['hw'|'hw_ctx']]",
6644 .handler = handle_rbp_command,
6645 .mode = COMMAND_EXEC,
6646 .help = "remove breakpoint",
6647 .usage = "'all' | address",
6651 .handler = handle_wp_command,
6652 .mode = COMMAND_EXEC,
6653 .help = "list (no params) or create watchpoints",
6654 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
6658 .handler = handle_rwp_command,
6659 .mode = COMMAND_EXEC,
6660 .help = "remove watchpoint",
6664 .name = "load_image",
6665 .handler = handle_load_image_command,
6666 .mode = COMMAND_EXEC,
6667 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6668 "[min_address] [max_length]",
6671 .name = "dump_image",
6672 .handler = handle_dump_image_command,
6673 .mode = COMMAND_EXEC,
6674 .usage = "filename address size",
6677 .name = "verify_image_checksum",
6678 .handler = handle_verify_image_checksum_command,
6679 .mode = COMMAND_EXEC,
6680 .usage = "filename [offset [type]]",
6683 .name = "verify_image",
6684 .handler = handle_verify_image_command,
6685 .mode = COMMAND_EXEC,
6686 .usage = "filename [offset [type]]",
6689 .name = "test_image",
6690 .handler = handle_test_image_command,
6691 .mode = COMMAND_EXEC,
6692 .usage = "filename [offset [type]]",
6695 .name = "mem2array",
6696 .mode = COMMAND_EXEC,
6697 .jim_handler = jim_mem2array,
6698 .help = "read 8/16/32 bit memory and return as a TCL array "
6699 "for script processing",
6700 .usage = "arrayname bitwidth address count",
6703 .name = "array2mem",
6704 .mode = COMMAND_EXEC,
6705 .jim_handler = jim_array2mem,
6706 .help = "convert a TCL array to memory locations "
6707 "and write the 8/16/32 bit values",
6708 .usage = "arrayname bitwidth address count",
6711 .name = "reset_nag",
6712 .handler = handle_target_reset_nag,
6713 .mode = COMMAND_ANY,
6714 .help = "Nag after each reset about options that could have been "
6715 "enabled to improve performance.",
6716 .usage = "['enable'|'disable']",
6720 .handler = handle_ps_command,
6721 .mode = COMMAND_EXEC,
6722 .help = "list all tasks",
6726 .name = "test_mem_access",
6727 .handler = handle_test_mem_access_command,
6728 .mode = COMMAND_EXEC,
6729 .help = "Test the target's memory access functions",
6733 COMMAND_REGISTRATION_DONE
6735 static int target_register_user_commands(struct command_context *cmd_ctx)
6737 int retval = ERROR_OK;
6738 retval = target_request_register_commands(cmd_ctx);
6739 if (retval != ERROR_OK)
6742 retval = trace_register_commands(cmd_ctx);
6743 if (retval != ERROR_OK)
6747 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);