1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
5 * Copyright (C) 2007-2010 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
8 * Copyright (C) 2008, Duane Ellis *
9 * openocd@duaneeellis.com *
11 * Copyright (C) 2008 by Spencer Oliver *
12 * spen@spen-soft.co.uk *
14 * Copyright (C) 2008 by Rick Altherr *
15 * kc8apf@kc8apf.net> *
17 * Copyright (C) 2011 by Broadcom Corporation *
18 * Evan Hunter - ehunter@broadcom.com *
20 * Copyright (C) ST-Ericsson SA 2011 *
21 * michel.jaouen@stericsson.com : smp minimum support *
23 * Copyright (C) 2011 Andreas Fritiofson *
24 * andreas.fritiofson@gmail.com *
26 * This program is free software; you can redistribute it and/or modify *
27 * it under the terms of the GNU General Public License as published by *
28 * the Free Software Foundation; either version 2 of the License, or *
29 * (at your option) any later version. *
31 * This program is distributed in the hope that it will be useful, *
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
34 * GNU General Public License for more details. *
36 * You should have received a copy of the GNU General Public License *
37 * along with this program. If not, see <http://www.gnu.org/licenses/>. *
38 ***************************************************************************/
44 #include <helper/align.h>
45 #include <helper/time_support.h>
46 #include <jtag/jtag.h>
47 #include <flash/nor/core.h>
50 #include "target_type.h"
51 #include "target_request.h"
52 #include "breakpoints.h"
56 #include "rtos/rtos.h"
57 #include "transport/transport.h"
60 #include "semihosting_common.h"
62 /* default halt wait timeout (ms) */
63 #define DEFAULT_HALT_TIMEOUT 5000
65 static int target_read_buffer_default(struct target *target, target_addr_t address,
66 uint32_t count, uint8_t *buffer);
67 static int target_write_buffer_default(struct target *target, target_addr_t address,
68 uint32_t count, const uint8_t *buffer);
69 static int target_array2mem(Jim_Interp *interp, struct target *target,
70 int argc, Jim_Obj * const *argv);
71 static int target_mem2array(Jim_Interp *interp, struct target *target,
72 int argc, Jim_Obj * const *argv);
73 static int target_register_user_commands(struct command_context *cmd_ctx);
74 static int target_get_gdb_fileio_info_default(struct target *target,
75 struct gdb_fileio_info *fileio_info);
76 static int target_gdb_fileio_end_default(struct target *target, int retcode,
77 int fileio_errno, bool ctrl_c);
80 extern struct target_type arm7tdmi_target;
81 extern struct target_type arm720t_target;
82 extern struct target_type arm9tdmi_target;
83 extern struct target_type arm920t_target;
84 extern struct target_type arm966e_target;
85 extern struct target_type arm946e_target;
86 extern struct target_type arm926ejs_target;
87 extern struct target_type fa526_target;
88 extern struct target_type feroceon_target;
89 extern struct target_type dragonite_target;
90 extern struct target_type xscale_target;
91 extern struct target_type cortexm_target;
92 extern struct target_type cortexa_target;
93 extern struct target_type aarch64_target;
94 extern struct target_type cortexr4_target;
95 extern struct target_type arm11_target;
96 extern struct target_type ls1_sap_target;
97 extern struct target_type mips_m4k_target;
98 extern struct target_type mips_mips64_target;
99 extern struct target_type avr_target;
100 extern struct target_type dsp563xx_target;
101 extern struct target_type dsp5680xx_target;
102 extern struct target_type testee_target;
103 extern struct target_type avr32_ap7k_target;
104 extern struct target_type hla_target;
105 extern struct target_type nds32_v2_target;
106 extern struct target_type nds32_v3_target;
107 extern struct target_type nds32_v3m_target;
108 extern struct target_type or1k_target;
109 extern struct target_type quark_x10xx_target;
110 extern struct target_type quark_d20xx_target;
111 extern struct target_type stm8_target;
112 extern struct target_type riscv_target;
113 extern struct target_type mem_ap_target;
114 extern struct target_type esirisc_target;
115 extern struct target_type arcv2_target;
117 static struct target_type *target_types[] = {
157 struct target *all_targets;
158 static struct target_event_callback *target_event_callbacks;
159 static struct target_timer_callback *target_timer_callbacks;
160 static int64_t target_timer_next_event_value;
161 static LIST_HEAD(target_reset_callback_list);
162 static LIST_HEAD(target_trace_callback_list);
163 static const int polling_interval = TARGET_DEFAULT_POLLING_INTERVAL;
164 static LIST_HEAD(empty_smp_targets);
166 static const struct jim_nvp nvp_assert[] = {
167 { .name = "assert", NVP_ASSERT },
168 { .name = "deassert", NVP_DEASSERT },
169 { .name = "T", NVP_ASSERT },
170 { .name = "F", NVP_DEASSERT },
171 { .name = "t", NVP_ASSERT },
172 { .name = "f", NVP_DEASSERT },
173 { .name = NULL, .value = -1 }
176 static const struct jim_nvp nvp_error_target[] = {
177 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
178 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
179 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
180 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
181 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
182 { .value = ERROR_TARGET_UNALIGNED_ACCESS, .name = "err-unaligned-access" },
183 { .value = ERROR_TARGET_DATA_ABORT, .name = "err-data-abort" },
184 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE, .name = "err-resource-not-available" },
185 { .value = ERROR_TARGET_TRANSLATION_FAULT, .name = "err-translation-fault" },
186 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
187 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
188 { .value = -1, .name = NULL }
191 static const char *target_strerror_safe(int err)
193 const struct jim_nvp *n;
195 n = jim_nvp_value2name_simple(nvp_error_target, err);
202 static const struct jim_nvp nvp_target_event[] = {
204 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
205 { .value = TARGET_EVENT_HALTED, .name = "halted" },
206 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
207 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
208 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
209 { .value = TARGET_EVENT_STEP_START, .name = "step-start" },
210 { .value = TARGET_EVENT_STEP_END, .name = "step-end" },
212 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
213 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
215 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
216 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
217 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
218 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
219 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
220 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
221 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
222 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
224 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
225 { .value = TARGET_EVENT_EXAMINE_FAIL, .name = "examine-fail" },
226 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
228 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
229 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
231 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
232 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
234 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
235 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END, .name = "gdb-flash-write-end" },
237 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
238 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END, .name = "gdb-flash-erase-end" },
240 { .value = TARGET_EVENT_TRACE_CONFIG, .name = "trace-config" },
242 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x100, .name = "semihosting-user-cmd-0x100" },
243 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x101, .name = "semihosting-user-cmd-0x101" },
244 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x102, .name = "semihosting-user-cmd-0x102" },
245 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x103, .name = "semihosting-user-cmd-0x103" },
246 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x104, .name = "semihosting-user-cmd-0x104" },
247 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x105, .name = "semihosting-user-cmd-0x105" },
248 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x106, .name = "semihosting-user-cmd-0x106" },
249 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x107, .name = "semihosting-user-cmd-0x107" },
251 { .name = NULL, .value = -1 }
254 static const struct jim_nvp nvp_target_state[] = {
255 { .name = "unknown", .value = TARGET_UNKNOWN },
256 { .name = "running", .value = TARGET_RUNNING },
257 { .name = "halted", .value = TARGET_HALTED },
258 { .name = "reset", .value = TARGET_RESET },
259 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
260 { .name = NULL, .value = -1 },
263 static const struct jim_nvp nvp_target_debug_reason[] = {
264 { .name = "debug-request", .value = DBG_REASON_DBGRQ },
265 { .name = "breakpoint", .value = DBG_REASON_BREAKPOINT },
266 { .name = "watchpoint", .value = DBG_REASON_WATCHPOINT },
267 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
268 { .name = "single-step", .value = DBG_REASON_SINGLESTEP },
269 { .name = "target-not-halted", .value = DBG_REASON_NOTHALTED },
270 { .name = "program-exit", .value = DBG_REASON_EXIT },
271 { .name = "exception-catch", .value = DBG_REASON_EXC_CATCH },
272 { .name = "undefined", .value = DBG_REASON_UNDEFINED },
273 { .name = NULL, .value = -1 },
276 static const struct jim_nvp nvp_target_endian[] = {
277 { .name = "big", .value = TARGET_BIG_ENDIAN },
278 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
279 { .name = "be", .value = TARGET_BIG_ENDIAN },
280 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
281 { .name = NULL, .value = -1 },
284 static const struct jim_nvp nvp_reset_modes[] = {
285 { .name = "unknown", .value = RESET_UNKNOWN },
286 { .name = "run", .value = RESET_RUN },
287 { .name = "halt", .value = RESET_HALT },
288 { .name = "init", .value = RESET_INIT },
289 { .name = NULL, .value = -1 },
292 const char *debug_reason_name(struct target *t)
296 cp = jim_nvp_value2name_simple(nvp_target_debug_reason,
297 t->debug_reason)->name;
299 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
300 cp = "(*BUG*unknown*BUG*)";
305 const char *target_state_name(struct target *t)
308 cp = jim_nvp_value2name_simple(nvp_target_state, t->state)->name;
310 LOG_ERROR("Invalid target state: %d", (int)(t->state));
311 cp = "(*BUG*unknown*BUG*)";
314 if (!target_was_examined(t) && t->defer_examine)
315 cp = "examine deferred";
320 const char *target_event_name(enum target_event event)
323 cp = jim_nvp_value2name_simple(nvp_target_event, event)->name;
325 LOG_ERROR("Invalid target event: %d", (int)(event));
326 cp = "(*BUG*unknown*BUG*)";
331 const char *target_reset_mode_name(enum target_reset_mode reset_mode)
334 cp = jim_nvp_value2name_simple(nvp_reset_modes, reset_mode)->name;
336 LOG_ERROR("Invalid target reset mode: %d", (int)(reset_mode));
337 cp = "(*BUG*unknown*BUG*)";
342 /* determine the number of the new target */
343 static int new_target_number(void)
348 /* number is 0 based */
352 if (x < t->target_number)
353 x = t->target_number;
359 static void append_to_list_all_targets(struct target *target)
361 struct target **t = &all_targets;
368 /* read a uint64_t from a buffer in target memory endianness */
369 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
371 if (target->endianness == TARGET_LITTLE_ENDIAN)
372 return le_to_h_u64(buffer);
374 return be_to_h_u64(buffer);
377 /* read a uint32_t from a buffer in target memory endianness */
378 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
380 if (target->endianness == TARGET_LITTLE_ENDIAN)
381 return le_to_h_u32(buffer);
383 return be_to_h_u32(buffer);
386 /* read a uint24_t from a buffer in target memory endianness */
387 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
389 if (target->endianness == TARGET_LITTLE_ENDIAN)
390 return le_to_h_u24(buffer);
392 return be_to_h_u24(buffer);
395 /* read a uint16_t from a buffer in target memory endianness */
396 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
398 if (target->endianness == TARGET_LITTLE_ENDIAN)
399 return le_to_h_u16(buffer);
401 return be_to_h_u16(buffer);
404 /* write a uint64_t to a buffer in target memory endianness */
405 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
407 if (target->endianness == TARGET_LITTLE_ENDIAN)
408 h_u64_to_le(buffer, value);
410 h_u64_to_be(buffer, value);
413 /* write a uint32_t to a buffer in target memory endianness */
414 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
416 if (target->endianness == TARGET_LITTLE_ENDIAN)
417 h_u32_to_le(buffer, value);
419 h_u32_to_be(buffer, value);
422 /* write a uint24_t to a buffer in target memory endianness */
423 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
425 if (target->endianness == TARGET_LITTLE_ENDIAN)
426 h_u24_to_le(buffer, value);
428 h_u24_to_be(buffer, value);
431 /* write a uint16_t to a buffer in target memory endianness */
432 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
434 if (target->endianness == TARGET_LITTLE_ENDIAN)
435 h_u16_to_le(buffer, value);
437 h_u16_to_be(buffer, value);
440 /* write a uint8_t to a buffer in target memory endianness */
441 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
446 /* write a uint64_t array to a buffer in target memory endianness */
447 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
450 for (i = 0; i < count; i++)
451 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
454 /* write a uint32_t array to a buffer in target memory endianness */
455 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
458 for (i = 0; i < count; i++)
459 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
462 /* write a uint16_t array to a buffer in target memory endianness */
463 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
466 for (i = 0; i < count; i++)
467 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
470 /* write a uint64_t array to a buffer in target memory endianness */
471 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
474 for (i = 0; i < count; i++)
475 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
478 /* write a uint32_t array to a buffer in target memory endianness */
479 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
482 for (i = 0; i < count; i++)
483 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
486 /* write a uint16_t array to a buffer in target memory endianness */
487 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
490 for (i = 0; i < count; i++)
491 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
494 /* return a pointer to a configured target; id is name or number */
495 struct target *get_target(const char *id)
497 struct target *target;
499 /* try as tcltarget name */
500 for (target = all_targets; target; target = target->next) {
501 if (!target_name(target))
503 if (strcmp(id, target_name(target)) == 0)
507 /* It's OK to remove this fallback sometime after August 2010 or so */
509 /* no match, try as number */
511 if (parse_uint(id, &num) != ERROR_OK)
514 for (target = all_targets; target; target = target->next) {
515 if (target->target_number == (int)num) {
516 LOG_WARNING("use '%s' as target identifier, not '%u'",
517 target_name(target), num);
525 /* returns a pointer to the n-th configured target */
526 struct target *get_target_by_num(int num)
528 struct target *target = all_targets;
531 if (target->target_number == num)
533 target = target->next;
539 struct target *get_current_target(struct command_context *cmd_ctx)
541 struct target *target = get_current_target_or_null(cmd_ctx);
544 LOG_ERROR("BUG: current_target out of bounds");
551 struct target *get_current_target_or_null(struct command_context *cmd_ctx)
553 return cmd_ctx->current_target_override
554 ? cmd_ctx->current_target_override
555 : cmd_ctx->current_target;
558 int target_poll(struct target *target)
562 /* We can't poll until after examine */
563 if (!target_was_examined(target)) {
564 /* Fail silently lest we pollute the log */
568 retval = target->type->poll(target);
569 if (retval != ERROR_OK)
572 if (target->halt_issued) {
573 if (target->state == TARGET_HALTED)
574 target->halt_issued = false;
576 int64_t t = timeval_ms() - target->halt_issued_time;
577 if (t > DEFAULT_HALT_TIMEOUT) {
578 target->halt_issued = false;
579 LOG_INFO("Halt timed out, wake up GDB.");
580 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
588 int target_halt(struct target *target)
591 /* We can't poll until after examine */
592 if (!target_was_examined(target)) {
593 LOG_ERROR("Target not examined yet");
597 retval = target->type->halt(target);
598 if (retval != ERROR_OK)
601 target->halt_issued = true;
602 target->halt_issued_time = timeval_ms();
608 * Make the target (re)start executing using its saved execution
609 * context (possibly with some modifications).
611 * @param target Which target should start executing.
612 * @param current True to use the target's saved program counter instead
613 * of the address parameter
614 * @param address Optionally used as the program counter.
615 * @param handle_breakpoints True iff breakpoints at the resumption PC
616 * should be skipped. (For example, maybe execution was stopped by
617 * such a breakpoint, in which case it would be counterproductive to
619 * @param debug_execution False if all working areas allocated by OpenOCD
620 * should be released and/or restored to their original contents.
621 * (This would for example be true to run some downloaded "helper"
622 * algorithm code, which resides in one such working buffer and uses
623 * another for data storage.)
625 * @todo Resolve the ambiguity about what the "debug_execution" flag
626 * signifies. For example, Target implementations don't agree on how
627 * it relates to invalidation of the register cache, or to whether
628 * breakpoints and watchpoints should be enabled. (It would seem wrong
629 * to enable breakpoints when running downloaded "helper" algorithms
630 * (debug_execution true), since the breakpoints would be set to match
631 * target firmware being debugged, not the helper algorithm.... and
632 * enabling them could cause such helpers to malfunction (for example,
633 * by overwriting data with a breakpoint instruction. On the other
634 * hand the infrastructure for running such helpers might use this
635 * procedure but rely on hardware breakpoint to detect termination.)
637 int target_resume(struct target *target, int current, target_addr_t address,
638 int handle_breakpoints, int debug_execution)
642 /* We can't poll until after examine */
643 if (!target_was_examined(target)) {
644 LOG_ERROR("Target not examined yet");
648 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
650 /* note that resume *must* be asynchronous. The CPU can halt before
651 * we poll. The CPU can even halt at the current PC as a result of
652 * a software breakpoint being inserted by (a bug?) the application.
655 * resume() triggers the event 'resumed'. The execution of TCL commands
656 * in the event handler causes the polling of targets. If the target has
657 * already halted for a breakpoint, polling will run the 'halted' event
658 * handler before the pending 'resumed' handler.
659 * Disable polling during resume() to guarantee the execution of handlers
660 * in the correct order.
662 bool save_poll = jtag_poll_get_enabled();
663 jtag_poll_set_enabled(false);
664 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
665 jtag_poll_set_enabled(save_poll);
666 if (retval != ERROR_OK)
669 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
674 static int target_process_reset(struct command_invocation *cmd, enum target_reset_mode reset_mode)
679 n = jim_nvp_value2name_simple(nvp_reset_modes, reset_mode);
681 LOG_ERROR("invalid reset mode");
685 struct target *target;
686 for (target = all_targets; target; target = target->next)
687 target_call_reset_callbacks(target, reset_mode);
689 /* disable polling during reset to make reset event scripts
690 * more predictable, i.e. dr/irscan & pathmove in events will
691 * not have JTAG operations injected into the middle of a sequence.
693 bool save_poll = jtag_poll_get_enabled();
695 jtag_poll_set_enabled(false);
697 sprintf(buf, "ocd_process_reset %s", n->name);
698 retval = Jim_Eval(cmd->ctx->interp, buf);
700 jtag_poll_set_enabled(save_poll);
702 if (retval != JIM_OK) {
703 Jim_MakeErrorMessage(cmd->ctx->interp);
704 command_print(cmd, "%s", Jim_GetString(Jim_GetResult(cmd->ctx->interp), NULL));
708 /* We want any events to be processed before the prompt */
709 retval = target_call_timer_callbacks_now();
711 for (target = all_targets; target; target = target->next) {
712 target->type->check_reset(target);
713 target->running_alg = false;
719 static int identity_virt2phys(struct target *target,
720 target_addr_t virtual, target_addr_t *physical)
726 static int no_mmu(struct target *target, int *enabled)
733 * Reset the @c examined flag for the given target.
734 * Pure paranoia -- targets are zeroed on allocation.
736 static inline void target_reset_examined(struct target *target)
738 target->examined = false;
741 static int default_examine(struct target *target)
743 target_set_examined(target);
747 /* no check by default */
748 static int default_check_reset(struct target *target)
753 /* Equivalent Tcl code arp_examine_one is in src/target/startup.tcl
755 int target_examine_one(struct target *target)
757 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
759 int retval = target->type->examine(target);
760 if (retval != ERROR_OK) {
761 target_reset_examined(target);
762 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_FAIL);
766 target_set_examined(target);
767 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
772 static int jtag_enable_callback(enum jtag_event event, void *priv)
774 struct target *target = priv;
776 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
779 jtag_unregister_event_callback(jtag_enable_callback, target);
781 return target_examine_one(target);
784 /* Targets that correctly implement init + examine, i.e.
785 * no communication with target during init:
789 int target_examine(void)
791 int retval = ERROR_OK;
792 struct target *target;
794 for (target = all_targets; target; target = target->next) {
795 /* defer examination, but don't skip it */
796 if (!target->tap->enabled) {
797 jtag_register_event_callback(jtag_enable_callback,
802 if (target->defer_examine)
805 int retval2 = target_examine_one(target);
806 if (retval2 != ERROR_OK) {
807 LOG_WARNING("target %s examination failed", target_name(target));
814 const char *target_type_name(struct target *target)
816 return target->type->name;
819 static int target_soft_reset_halt(struct target *target)
821 if (!target_was_examined(target)) {
822 LOG_ERROR("Target not examined yet");
825 if (!target->type->soft_reset_halt) {
826 LOG_ERROR("Target %s does not support soft_reset_halt",
827 target_name(target));
830 return target->type->soft_reset_halt(target);
834 * Downloads a target-specific native code algorithm to the target,
835 * and executes it. * Note that some targets may need to set up, enable,
836 * and tear down a breakpoint (hard or * soft) to detect algorithm
837 * termination, while others may support lower overhead schemes where
838 * soft breakpoints embedded in the algorithm automatically terminate the
841 * @param target used to run the algorithm
842 * @param num_mem_params
844 * @param num_reg_params
849 * @param arch_info target-specific description of the algorithm.
851 int target_run_algorithm(struct target *target,
852 int num_mem_params, struct mem_param *mem_params,
853 int num_reg_params, struct reg_param *reg_param,
854 target_addr_t entry_point, target_addr_t exit_point,
855 int timeout_ms, void *arch_info)
857 int retval = ERROR_FAIL;
859 if (!target_was_examined(target)) {
860 LOG_ERROR("Target not examined yet");
863 if (!target->type->run_algorithm) {
864 LOG_ERROR("Target type '%s' does not support %s",
865 target_type_name(target), __func__);
869 target->running_alg = true;
870 retval = target->type->run_algorithm(target,
871 num_mem_params, mem_params,
872 num_reg_params, reg_param,
873 entry_point, exit_point, timeout_ms, arch_info);
874 target->running_alg = false;
881 * Executes a target-specific native code algorithm and leaves it running.
883 * @param target used to run the algorithm
884 * @param num_mem_params
886 * @param num_reg_params
890 * @param arch_info target-specific description of the algorithm.
892 int target_start_algorithm(struct target *target,
893 int num_mem_params, struct mem_param *mem_params,
894 int num_reg_params, struct reg_param *reg_params,
895 target_addr_t entry_point, target_addr_t exit_point,
898 int retval = ERROR_FAIL;
900 if (!target_was_examined(target)) {
901 LOG_ERROR("Target not examined yet");
904 if (!target->type->start_algorithm) {
905 LOG_ERROR("Target type '%s' does not support %s",
906 target_type_name(target), __func__);
909 if (target->running_alg) {
910 LOG_ERROR("Target is already running an algorithm");
914 target->running_alg = true;
915 retval = target->type->start_algorithm(target,
916 num_mem_params, mem_params,
917 num_reg_params, reg_params,
918 entry_point, exit_point, arch_info);
925 * Waits for an algorithm started with target_start_algorithm() to complete.
927 * @param target used to run the algorithm
928 * @param num_mem_params
930 * @param num_reg_params
934 * @param arch_info target-specific description of the algorithm.
936 int target_wait_algorithm(struct target *target,
937 int num_mem_params, struct mem_param *mem_params,
938 int num_reg_params, struct reg_param *reg_params,
939 target_addr_t exit_point, int timeout_ms,
942 int retval = ERROR_FAIL;
944 if (!target->type->wait_algorithm) {
945 LOG_ERROR("Target type '%s' does not support %s",
946 target_type_name(target), __func__);
949 if (!target->running_alg) {
950 LOG_ERROR("Target is not running an algorithm");
954 retval = target->type->wait_algorithm(target,
955 num_mem_params, mem_params,
956 num_reg_params, reg_params,
957 exit_point, timeout_ms, arch_info);
958 if (retval != ERROR_TARGET_TIMEOUT)
959 target->running_alg = false;
966 * Streams data to a circular buffer on target intended for consumption by code
967 * running asynchronously on target.
969 * This is intended for applications where target-specific native code runs
970 * on the target, receives data from the circular buffer, does something with
971 * it (most likely writing it to a flash memory), and advances the circular
974 * This assumes that the helper algorithm has already been loaded to the target,
975 * but has not been started yet. Given memory and register parameters are passed
978 * The buffer is defined by (buffer_start, buffer_size) arguments and has the
981 * [buffer_start + 0, buffer_start + 4):
982 * Write Pointer address (aka head). Written and updated by this
983 * routine when new data is written to the circular buffer.
984 * [buffer_start + 4, buffer_start + 8):
985 * Read Pointer address (aka tail). Updated by code running on the
986 * target after it consumes data.
987 * [buffer_start + 8, buffer_start + buffer_size):
988 * Circular buffer contents.
990 * See contrib/loaders/flash/stm32f1x.S for an example.
992 * @param target used to run the algorithm
993 * @param buffer address on the host where data to be sent is located
994 * @param count number of blocks to send
995 * @param block_size size in bytes of each block
996 * @param num_mem_params count of memory-based params to pass to algorithm
997 * @param mem_params memory-based params to pass to algorithm
998 * @param num_reg_params count of register-based params to pass to algorithm
999 * @param reg_params memory-based params to pass to algorithm
1000 * @param buffer_start address on the target of the circular buffer structure
1001 * @param buffer_size size of the circular buffer structure
1002 * @param entry_point address on the target to execute to start the algorithm
1003 * @param exit_point address at which to set a breakpoint to catch the
1004 * end of the algorithm; can be 0 if target triggers a breakpoint itself
1008 int target_run_flash_async_algorithm(struct target *target,
1009 const uint8_t *buffer, uint32_t count, int block_size,
1010 int num_mem_params, struct mem_param *mem_params,
1011 int num_reg_params, struct reg_param *reg_params,
1012 uint32_t buffer_start, uint32_t buffer_size,
1013 uint32_t entry_point, uint32_t exit_point, void *arch_info)
1018 const uint8_t *buffer_orig = buffer;
1020 /* Set up working area. First word is write pointer, second word is read pointer,
1021 * rest is fifo data area. */
1022 uint32_t wp_addr = buffer_start;
1023 uint32_t rp_addr = buffer_start + 4;
1024 uint32_t fifo_start_addr = buffer_start + 8;
1025 uint32_t fifo_end_addr = buffer_start + buffer_size;
1027 uint32_t wp = fifo_start_addr;
1028 uint32_t rp = fifo_start_addr;
1030 /* validate block_size is 2^n */
1031 assert(IS_PWR_OF_2(block_size));
1033 retval = target_write_u32(target, wp_addr, wp);
1034 if (retval != ERROR_OK)
1036 retval = target_write_u32(target, rp_addr, rp);
1037 if (retval != ERROR_OK)
1040 /* Start up algorithm on target and let it idle while writing the first chunk */
1041 retval = target_start_algorithm(target, num_mem_params, mem_params,
1042 num_reg_params, reg_params,
1047 if (retval != ERROR_OK) {
1048 LOG_ERROR("error starting target flash write algorithm");
1054 retval = target_read_u32(target, rp_addr, &rp);
1055 if (retval != ERROR_OK) {
1056 LOG_ERROR("failed to get read pointer");
1060 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1061 (size_t) (buffer - buffer_orig), count, wp, rp);
1064 LOG_ERROR("flash write algorithm aborted by target");
1065 retval = ERROR_FLASH_OPERATION_FAILED;
1069 if (!IS_ALIGNED(rp - fifo_start_addr, block_size) || rp < fifo_start_addr || rp >= fifo_end_addr) {
1070 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
1074 /* Count the number of bytes available in the fifo without
1075 * crossing the wrap around. Make sure to not fill it completely,
1076 * because that would make wp == rp and that's the empty condition. */
1077 uint32_t thisrun_bytes;
1079 thisrun_bytes = rp - wp - block_size;
1080 else if (rp > fifo_start_addr)
1081 thisrun_bytes = fifo_end_addr - wp;
1083 thisrun_bytes = fifo_end_addr - wp - block_size;
1085 if (thisrun_bytes == 0) {
1086 /* Throttle polling a bit if transfer is (much) faster than flash
1087 * programming. The exact delay shouldn't matter as long as it's
1088 * less than buffer size / flash speed. This is very unlikely to
1089 * run when using high latency connections such as USB. */
1092 /* to stop an infinite loop on some targets check and increment a timeout
1093 * this issue was observed on a stellaris using the new ICDI interface */
1094 if (timeout++ >= 2500) {
1095 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1096 return ERROR_FLASH_OPERATION_FAILED;
1101 /* reset our timeout */
1104 /* Limit to the amount of data we actually want to write */
1105 if (thisrun_bytes > count * block_size)
1106 thisrun_bytes = count * block_size;
1108 /* Force end of large blocks to be word aligned */
1109 if (thisrun_bytes >= 16)
1110 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1112 /* Write data to fifo */
1113 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
1114 if (retval != ERROR_OK)
1117 /* Update counters and wrap write pointer */
1118 buffer += thisrun_bytes;
1119 count -= thisrun_bytes / block_size;
1120 wp += thisrun_bytes;
1121 if (wp >= fifo_end_addr)
1122 wp = fifo_start_addr;
1124 /* Store updated write pointer to target */
1125 retval = target_write_u32(target, wp_addr, wp);
1126 if (retval != ERROR_OK)
1129 /* Avoid GDB timeouts */
1133 if (retval != ERROR_OK) {
1134 /* abort flash write algorithm on target */
1135 target_write_u32(target, wp_addr, 0);
1138 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1139 num_reg_params, reg_params,
1144 if (retval2 != ERROR_OK) {
1145 LOG_ERROR("error waiting for target flash write algorithm");
1149 if (retval == ERROR_OK) {
1150 /* check if algorithm set rp = 0 after fifo writer loop finished */
1151 retval = target_read_u32(target, rp_addr, &rp);
1152 if (retval == ERROR_OK && rp == 0) {
1153 LOG_ERROR("flash write algorithm aborted by target");
1154 retval = ERROR_FLASH_OPERATION_FAILED;
1161 int target_run_read_async_algorithm(struct target *target,
1162 uint8_t *buffer, uint32_t count, int block_size,
1163 int num_mem_params, struct mem_param *mem_params,
1164 int num_reg_params, struct reg_param *reg_params,
1165 uint32_t buffer_start, uint32_t buffer_size,
1166 uint32_t entry_point, uint32_t exit_point, void *arch_info)
1171 const uint8_t *buffer_orig = buffer;
1173 /* Set up working area. First word is write pointer, second word is read pointer,
1174 * rest is fifo data area. */
1175 uint32_t wp_addr = buffer_start;
1176 uint32_t rp_addr = buffer_start + 4;
1177 uint32_t fifo_start_addr = buffer_start + 8;
1178 uint32_t fifo_end_addr = buffer_start + buffer_size;
1180 uint32_t wp = fifo_start_addr;
1181 uint32_t rp = fifo_start_addr;
1183 /* validate block_size is 2^n */
1184 assert(IS_PWR_OF_2(block_size));
1186 retval = target_write_u32(target, wp_addr, wp);
1187 if (retval != ERROR_OK)
1189 retval = target_write_u32(target, rp_addr, rp);
1190 if (retval != ERROR_OK)
1193 /* Start up algorithm on target */
1194 retval = target_start_algorithm(target, num_mem_params, mem_params,
1195 num_reg_params, reg_params,
1200 if (retval != ERROR_OK) {
1201 LOG_ERROR("error starting target flash read algorithm");
1206 retval = target_read_u32(target, wp_addr, &wp);
1207 if (retval != ERROR_OK) {
1208 LOG_ERROR("failed to get write pointer");
1212 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1213 (size_t)(buffer - buffer_orig), count, wp, rp);
1216 LOG_ERROR("flash read algorithm aborted by target");
1217 retval = ERROR_FLASH_OPERATION_FAILED;
1221 if (!IS_ALIGNED(wp - fifo_start_addr, block_size) || wp < fifo_start_addr || wp >= fifo_end_addr) {
1222 LOG_ERROR("corrupted fifo write pointer 0x%" PRIx32, wp);
1226 /* Count the number of bytes available in the fifo without
1227 * crossing the wrap around. */
1228 uint32_t thisrun_bytes;
1230 thisrun_bytes = wp - rp;
1232 thisrun_bytes = fifo_end_addr - rp;
1234 if (thisrun_bytes == 0) {
1235 /* Throttle polling a bit if transfer is (much) faster than flash
1236 * reading. The exact delay shouldn't matter as long as it's
1237 * less than buffer size / flash speed. This is very unlikely to
1238 * run when using high latency connections such as USB. */
1241 /* to stop an infinite loop on some targets check and increment a timeout
1242 * this issue was observed on a stellaris using the new ICDI interface */
1243 if (timeout++ >= 2500) {
1244 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1245 return ERROR_FLASH_OPERATION_FAILED;
1250 /* Reset our timeout */
1253 /* Limit to the amount of data we actually want to read */
1254 if (thisrun_bytes > count * block_size)
1255 thisrun_bytes = count * block_size;
1257 /* Force end of large blocks to be word aligned */
1258 if (thisrun_bytes >= 16)
1259 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1261 /* Read data from fifo */
1262 retval = target_read_buffer(target, rp, thisrun_bytes, buffer);
1263 if (retval != ERROR_OK)
1266 /* Update counters and wrap write pointer */
1267 buffer += thisrun_bytes;
1268 count -= thisrun_bytes / block_size;
1269 rp += thisrun_bytes;
1270 if (rp >= fifo_end_addr)
1271 rp = fifo_start_addr;
1273 /* Store updated write pointer to target */
1274 retval = target_write_u32(target, rp_addr, rp);
1275 if (retval != ERROR_OK)
1278 /* Avoid GDB timeouts */
1283 if (retval != ERROR_OK) {
1284 /* abort flash write algorithm on target */
1285 target_write_u32(target, rp_addr, 0);
1288 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1289 num_reg_params, reg_params,
1294 if (retval2 != ERROR_OK) {
1295 LOG_ERROR("error waiting for target flash write algorithm");
1299 if (retval == ERROR_OK) {
1300 /* check if algorithm set wp = 0 after fifo writer loop finished */
1301 retval = target_read_u32(target, wp_addr, &wp);
1302 if (retval == ERROR_OK && wp == 0) {
1303 LOG_ERROR("flash read algorithm aborted by target");
1304 retval = ERROR_FLASH_OPERATION_FAILED;
1311 int target_read_memory(struct target *target,
1312 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1314 if (!target_was_examined(target)) {
1315 LOG_ERROR("Target not examined yet");
1318 if (!target->type->read_memory) {
1319 LOG_ERROR("Target %s doesn't support read_memory", target_name(target));
1322 return target->type->read_memory(target, address, size, count, buffer);
1325 int target_read_phys_memory(struct target *target,
1326 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1328 if (!target_was_examined(target)) {
1329 LOG_ERROR("Target not examined yet");
1332 if (!target->type->read_phys_memory) {
1333 LOG_ERROR("Target %s doesn't support read_phys_memory", target_name(target));
1336 return target->type->read_phys_memory(target, address, size, count, buffer);
1339 int target_write_memory(struct target *target,
1340 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1342 if (!target_was_examined(target)) {
1343 LOG_ERROR("Target not examined yet");
1346 if (!target->type->write_memory) {
1347 LOG_ERROR("Target %s doesn't support write_memory", target_name(target));
1350 return target->type->write_memory(target, address, size, count, buffer);
1353 int target_write_phys_memory(struct target *target,
1354 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1356 if (!target_was_examined(target)) {
1357 LOG_ERROR("Target not examined yet");
1360 if (!target->type->write_phys_memory) {
1361 LOG_ERROR("Target %s doesn't support write_phys_memory", target_name(target));
1364 return target->type->write_phys_memory(target, address, size, count, buffer);
1367 int target_add_breakpoint(struct target *target,
1368 struct breakpoint *breakpoint)
1370 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1371 LOG_WARNING("target %s is not halted (add breakpoint)", target_name(target));
1372 return ERROR_TARGET_NOT_HALTED;
1374 return target->type->add_breakpoint(target, breakpoint);
1377 int target_add_context_breakpoint(struct target *target,
1378 struct breakpoint *breakpoint)
1380 if (target->state != TARGET_HALTED) {
1381 LOG_WARNING("target %s is not halted (add context breakpoint)", target_name(target));
1382 return ERROR_TARGET_NOT_HALTED;
1384 return target->type->add_context_breakpoint(target, breakpoint);
1387 int target_add_hybrid_breakpoint(struct target *target,
1388 struct breakpoint *breakpoint)
1390 if (target->state != TARGET_HALTED) {
1391 LOG_WARNING("target %s is not halted (add hybrid breakpoint)", target_name(target));
1392 return ERROR_TARGET_NOT_HALTED;
1394 return target->type->add_hybrid_breakpoint(target, breakpoint);
1397 int target_remove_breakpoint(struct target *target,
1398 struct breakpoint *breakpoint)
1400 return target->type->remove_breakpoint(target, breakpoint);
1403 int target_add_watchpoint(struct target *target,
1404 struct watchpoint *watchpoint)
1406 if (target->state != TARGET_HALTED) {
1407 LOG_WARNING("target %s is not halted (add watchpoint)", target_name(target));
1408 return ERROR_TARGET_NOT_HALTED;
1410 return target->type->add_watchpoint(target, watchpoint);
1412 int target_remove_watchpoint(struct target *target,
1413 struct watchpoint *watchpoint)
1415 return target->type->remove_watchpoint(target, watchpoint);
1417 int target_hit_watchpoint(struct target *target,
1418 struct watchpoint **hit_watchpoint)
1420 if (target->state != TARGET_HALTED) {
1421 LOG_WARNING("target %s is not halted (hit watchpoint)", target->cmd_name);
1422 return ERROR_TARGET_NOT_HALTED;
1425 if (!target->type->hit_watchpoint) {
1426 /* For backward compatible, if hit_watchpoint is not implemented,
1427 * return ERROR_FAIL such that gdb_server will not take the nonsense
1432 return target->type->hit_watchpoint(target, hit_watchpoint);
1435 const char *target_get_gdb_arch(struct target *target)
1437 if (!target->type->get_gdb_arch)
1439 return target->type->get_gdb_arch(target);
1442 int target_get_gdb_reg_list(struct target *target,
1443 struct reg **reg_list[], int *reg_list_size,
1444 enum target_register_class reg_class)
1446 int result = ERROR_FAIL;
1448 if (!target_was_examined(target)) {
1449 LOG_ERROR("Target not examined yet");
1453 result = target->type->get_gdb_reg_list(target, reg_list,
1454 reg_list_size, reg_class);
1457 if (result != ERROR_OK) {
1464 int target_get_gdb_reg_list_noread(struct target *target,
1465 struct reg **reg_list[], int *reg_list_size,
1466 enum target_register_class reg_class)
1468 if (target->type->get_gdb_reg_list_noread &&
1469 target->type->get_gdb_reg_list_noread(target, reg_list,
1470 reg_list_size, reg_class) == ERROR_OK)
1472 return target_get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1475 bool target_supports_gdb_connection(struct target *target)
1478 * exclude all the targets that don't provide get_gdb_reg_list
1479 * or that have explicit gdb_max_connection == 0
1481 return !!target->type->get_gdb_reg_list && !!target->gdb_max_connections;
1484 int target_step(struct target *target,
1485 int current, target_addr_t address, int handle_breakpoints)
1489 target_call_event_callbacks(target, TARGET_EVENT_STEP_START);
1491 retval = target->type->step(target, current, address, handle_breakpoints);
1492 if (retval != ERROR_OK)
1495 target_call_event_callbacks(target, TARGET_EVENT_STEP_END);
1500 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1502 if (target->state != TARGET_HALTED) {
1503 LOG_WARNING("target %s is not halted (gdb fileio)", target->cmd_name);
1504 return ERROR_TARGET_NOT_HALTED;
1506 return target->type->get_gdb_fileio_info(target, fileio_info);
1509 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1511 if (target->state != TARGET_HALTED) {
1512 LOG_WARNING("target %s is not halted (gdb fileio end)", target->cmd_name);
1513 return ERROR_TARGET_NOT_HALTED;
1515 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1518 target_addr_t target_address_max(struct target *target)
1520 unsigned bits = target_address_bits(target);
1521 if (sizeof(target_addr_t) * 8 == bits)
1522 return (target_addr_t) -1;
1524 return (((target_addr_t) 1) << bits) - 1;
1527 unsigned target_address_bits(struct target *target)
1529 if (target->type->address_bits)
1530 return target->type->address_bits(target);
1534 unsigned int target_data_bits(struct target *target)
1536 if (target->type->data_bits)
1537 return target->type->data_bits(target);
1541 static int target_profiling(struct target *target, uint32_t *samples,
1542 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1544 return target->type->profiling(target, samples, max_num_samples,
1545 num_samples, seconds);
1548 static int handle_target(void *priv);
1550 static int target_init_one(struct command_context *cmd_ctx,
1551 struct target *target)
1553 target_reset_examined(target);
1555 struct target_type *type = target->type;
1557 type->examine = default_examine;
1559 if (!type->check_reset)
1560 type->check_reset = default_check_reset;
1562 assert(type->init_target);
1564 int retval = type->init_target(cmd_ctx, target);
1565 if (retval != ERROR_OK) {
1566 LOG_ERROR("target '%s' init failed", target_name(target));
1570 /* Sanity-check MMU support ... stub in what we must, to help
1571 * implement it in stages, but warn if we need to do so.
1574 if (!type->virt2phys) {
1575 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1576 type->virt2phys = identity_virt2phys;
1579 /* Make sure no-MMU targets all behave the same: make no
1580 * distinction between physical and virtual addresses, and
1581 * ensure that virt2phys() is always an identity mapping.
1583 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1584 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1587 type->write_phys_memory = type->write_memory;
1588 type->read_phys_memory = type->read_memory;
1589 type->virt2phys = identity_virt2phys;
1592 if (!target->type->read_buffer)
1593 target->type->read_buffer = target_read_buffer_default;
1595 if (!target->type->write_buffer)
1596 target->type->write_buffer = target_write_buffer_default;
1598 if (!target->type->get_gdb_fileio_info)
1599 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1601 if (!target->type->gdb_fileio_end)
1602 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1604 if (!target->type->profiling)
1605 target->type->profiling = target_profiling_default;
1610 static int target_init(struct command_context *cmd_ctx)
1612 struct target *target;
1615 for (target = all_targets; target; target = target->next) {
1616 retval = target_init_one(cmd_ctx, target);
1617 if (retval != ERROR_OK)
1624 retval = target_register_user_commands(cmd_ctx);
1625 if (retval != ERROR_OK)
1628 retval = target_register_timer_callback(&handle_target,
1629 polling_interval, TARGET_TIMER_TYPE_PERIODIC, cmd_ctx->interp);
1630 if (retval != ERROR_OK)
1636 COMMAND_HANDLER(handle_target_init_command)
1641 return ERROR_COMMAND_SYNTAX_ERROR;
1643 static bool target_initialized;
1644 if (target_initialized) {
1645 LOG_INFO("'target init' has already been called");
1648 target_initialized = true;
1650 retval = command_run_line(CMD_CTX, "init_targets");
1651 if (retval != ERROR_OK)
1654 retval = command_run_line(CMD_CTX, "init_target_events");
1655 if (retval != ERROR_OK)
1658 retval = command_run_line(CMD_CTX, "init_board");
1659 if (retval != ERROR_OK)
1662 LOG_DEBUG("Initializing targets...");
1663 return target_init(CMD_CTX);
1666 int target_register_event_callback(int (*callback)(struct target *target,
1667 enum target_event event, void *priv), void *priv)
1669 struct target_event_callback **callbacks_p = &target_event_callbacks;
1672 return ERROR_COMMAND_SYNTAX_ERROR;
1675 while ((*callbacks_p)->next)
1676 callbacks_p = &((*callbacks_p)->next);
1677 callbacks_p = &((*callbacks_p)->next);
1680 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1681 (*callbacks_p)->callback = callback;
1682 (*callbacks_p)->priv = priv;
1683 (*callbacks_p)->next = NULL;
1688 int target_register_reset_callback(int (*callback)(struct target *target,
1689 enum target_reset_mode reset_mode, void *priv), void *priv)
1691 struct target_reset_callback *entry;
1694 return ERROR_COMMAND_SYNTAX_ERROR;
1696 entry = malloc(sizeof(struct target_reset_callback));
1698 LOG_ERROR("error allocating buffer for reset callback entry");
1699 return ERROR_COMMAND_SYNTAX_ERROR;
1702 entry->callback = callback;
1704 list_add(&entry->list, &target_reset_callback_list);
1710 int target_register_trace_callback(int (*callback)(struct target *target,
1711 size_t len, uint8_t *data, void *priv), void *priv)
1713 struct target_trace_callback *entry;
1716 return ERROR_COMMAND_SYNTAX_ERROR;
1718 entry = malloc(sizeof(struct target_trace_callback));
1720 LOG_ERROR("error allocating buffer for trace callback entry");
1721 return ERROR_COMMAND_SYNTAX_ERROR;
1724 entry->callback = callback;
1726 list_add(&entry->list, &target_trace_callback_list);
1732 int target_register_timer_callback(int (*callback)(void *priv),
1733 unsigned int time_ms, enum target_timer_type type, void *priv)
1735 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1738 return ERROR_COMMAND_SYNTAX_ERROR;
1741 while ((*callbacks_p)->next)
1742 callbacks_p = &((*callbacks_p)->next);
1743 callbacks_p = &((*callbacks_p)->next);
1746 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1747 (*callbacks_p)->callback = callback;
1748 (*callbacks_p)->type = type;
1749 (*callbacks_p)->time_ms = time_ms;
1750 (*callbacks_p)->removed = false;
1752 (*callbacks_p)->when = timeval_ms() + time_ms;
1753 target_timer_next_event_value = MIN(target_timer_next_event_value, (*callbacks_p)->when);
1755 (*callbacks_p)->priv = priv;
1756 (*callbacks_p)->next = NULL;
1761 int target_unregister_event_callback(int (*callback)(struct target *target,
1762 enum target_event event, void *priv), void *priv)
1764 struct target_event_callback **p = &target_event_callbacks;
1765 struct target_event_callback *c = target_event_callbacks;
1768 return ERROR_COMMAND_SYNTAX_ERROR;
1771 struct target_event_callback *next = c->next;
1772 if ((c->callback == callback) && (c->priv == priv)) {
1784 int target_unregister_reset_callback(int (*callback)(struct target *target,
1785 enum target_reset_mode reset_mode, void *priv), void *priv)
1787 struct target_reset_callback *entry;
1790 return ERROR_COMMAND_SYNTAX_ERROR;
1792 list_for_each_entry(entry, &target_reset_callback_list, list) {
1793 if (entry->callback == callback && entry->priv == priv) {
1794 list_del(&entry->list);
1803 int target_unregister_trace_callback(int (*callback)(struct target *target,
1804 size_t len, uint8_t *data, void *priv), void *priv)
1806 struct target_trace_callback *entry;
1809 return ERROR_COMMAND_SYNTAX_ERROR;
1811 list_for_each_entry(entry, &target_trace_callback_list, list) {
1812 if (entry->callback == callback && entry->priv == priv) {
1813 list_del(&entry->list);
1822 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1825 return ERROR_COMMAND_SYNTAX_ERROR;
1827 for (struct target_timer_callback *c = target_timer_callbacks;
1829 if ((c->callback == callback) && (c->priv == priv)) {
1838 int target_call_event_callbacks(struct target *target, enum target_event event)
1840 struct target_event_callback *callback = target_event_callbacks;
1841 struct target_event_callback *next_callback;
1843 if (event == TARGET_EVENT_HALTED) {
1844 /* execute early halted first */
1845 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1848 LOG_DEBUG("target event %i (%s) for core %s", event,
1849 target_event_name(event),
1850 target_name(target));
1852 target_handle_event(target, event);
1855 next_callback = callback->next;
1856 callback->callback(target, event, callback->priv);
1857 callback = next_callback;
1863 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1865 struct target_reset_callback *callback;
1867 LOG_DEBUG("target reset %i (%s)", reset_mode,
1868 jim_nvp_value2name_simple(nvp_reset_modes, reset_mode)->name);
1870 list_for_each_entry(callback, &target_reset_callback_list, list)
1871 callback->callback(target, reset_mode, callback->priv);
1876 int target_call_trace_callbacks(struct target *target, size_t len, uint8_t *data)
1878 struct target_trace_callback *callback;
1880 list_for_each_entry(callback, &target_trace_callback_list, list)
1881 callback->callback(target, len, data, callback->priv);
1886 static int target_timer_callback_periodic_restart(
1887 struct target_timer_callback *cb, int64_t *now)
1889 cb->when = *now + cb->time_ms;
1893 static int target_call_timer_callback(struct target_timer_callback *cb,
1896 cb->callback(cb->priv);
1898 if (cb->type == TARGET_TIMER_TYPE_PERIODIC)
1899 return target_timer_callback_periodic_restart(cb, now);
1901 return target_unregister_timer_callback(cb->callback, cb->priv);
1904 static int target_call_timer_callbacks_check_time(int checktime)
1906 static bool callback_processing;
1908 /* Do not allow nesting */
1909 if (callback_processing)
1912 callback_processing = true;
1916 int64_t now = timeval_ms();
1918 /* Initialize to a default value that's a ways into the future.
1919 * The loop below will make it closer to now if there are
1920 * callbacks that want to be called sooner. */
1921 target_timer_next_event_value = now + 1000;
1923 /* Store an address of the place containing a pointer to the
1924 * next item; initially, that's a standalone "root of the
1925 * list" variable. */
1926 struct target_timer_callback **callback = &target_timer_callbacks;
1927 while (callback && *callback) {
1928 if ((*callback)->removed) {
1929 struct target_timer_callback *p = *callback;
1930 *callback = (*callback)->next;
1935 bool call_it = (*callback)->callback &&
1936 ((!checktime && (*callback)->type == TARGET_TIMER_TYPE_PERIODIC) ||
1937 now >= (*callback)->when);
1940 target_call_timer_callback(*callback, &now);
1942 if (!(*callback)->removed && (*callback)->when < target_timer_next_event_value)
1943 target_timer_next_event_value = (*callback)->when;
1945 callback = &(*callback)->next;
1948 callback_processing = false;
1952 int target_call_timer_callbacks()
1954 return target_call_timer_callbacks_check_time(1);
1957 /* invoke periodic callbacks immediately */
1958 int target_call_timer_callbacks_now()
1960 return target_call_timer_callbacks_check_time(0);
1963 int64_t target_timer_next_event(void)
1965 return target_timer_next_event_value;
1968 /* Prints the working area layout for debug purposes */
1969 static void print_wa_layout(struct target *target)
1971 struct working_area *c = target->working_areas;
1974 LOG_DEBUG("%c%c " TARGET_ADDR_FMT "-" TARGET_ADDR_FMT " (%" PRIu32 " bytes)",
1975 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1976 c->address, c->address + c->size - 1, c->size);
1981 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1982 static void target_split_working_area(struct working_area *area, uint32_t size)
1984 assert(area->free); /* Shouldn't split an allocated area */
1985 assert(size <= area->size); /* Caller should guarantee this */
1987 /* Split only if not already the right size */
1988 if (size < area->size) {
1989 struct working_area *new_wa = malloc(sizeof(*new_wa));
1994 new_wa->next = area->next;
1995 new_wa->size = area->size - size;
1996 new_wa->address = area->address + size;
1997 new_wa->backup = NULL;
1998 new_wa->user = NULL;
1999 new_wa->free = true;
2001 area->next = new_wa;
2004 /* If backup memory was allocated to this area, it has the wrong size
2005 * now so free it and it will be reallocated if/when needed */
2007 area->backup = NULL;
2011 /* Merge all adjacent free areas into one */
2012 static void target_merge_working_areas(struct target *target)
2014 struct working_area *c = target->working_areas;
2016 while (c && c->next) {
2017 assert(c->next->address == c->address + c->size); /* This is an invariant */
2019 /* Find two adjacent free areas */
2020 if (c->free && c->next->free) {
2021 /* Merge the last into the first */
2022 c->size += c->next->size;
2024 /* Remove the last */
2025 struct working_area *to_be_freed = c->next;
2026 c->next = c->next->next;
2027 free(to_be_freed->backup);
2030 /* If backup memory was allocated to the remaining area, it's has
2031 * the wrong size now */
2040 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
2042 /* Reevaluate working area address based on MMU state*/
2043 if (!target->working_areas) {
2047 retval = target->type->mmu(target, &enabled);
2048 if (retval != ERROR_OK)
2052 if (target->working_area_phys_spec) {
2053 LOG_DEBUG("MMU disabled, using physical "
2054 "address for working memory " TARGET_ADDR_FMT,
2055 target->working_area_phys);
2056 target->working_area = target->working_area_phys;
2058 LOG_ERROR("No working memory available. "
2059 "Specify -work-area-phys to target.");
2060 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2063 if (target->working_area_virt_spec) {
2064 LOG_DEBUG("MMU enabled, using virtual "
2065 "address for working memory " TARGET_ADDR_FMT,
2066 target->working_area_virt);
2067 target->working_area = target->working_area_virt;
2069 LOG_ERROR("No working memory available. "
2070 "Specify -work-area-virt to target.");
2071 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2075 /* Set up initial working area on first call */
2076 struct working_area *new_wa = malloc(sizeof(*new_wa));
2078 new_wa->next = NULL;
2079 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
2080 new_wa->address = target->working_area;
2081 new_wa->backup = NULL;
2082 new_wa->user = NULL;
2083 new_wa->free = true;
2086 target->working_areas = new_wa;
2089 /* only allocate multiples of 4 byte */
2091 size = (size + 3) & (~3UL);
2093 struct working_area *c = target->working_areas;
2095 /* Find the first large enough working area */
2097 if (c->free && c->size >= size)
2103 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2105 /* Split the working area into the requested size */
2106 target_split_working_area(c, size);
2108 LOG_DEBUG("allocated new working area of %" PRIu32 " bytes at address " TARGET_ADDR_FMT,
2111 if (target->backup_working_area) {
2113 c->backup = malloc(c->size);
2118 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
2119 if (retval != ERROR_OK)
2123 /* mark as used, and return the new (reused) area */
2130 print_wa_layout(target);
2135 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
2139 retval = target_alloc_working_area_try(target, size, area);
2140 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
2141 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
2146 static int target_restore_working_area(struct target *target, struct working_area *area)
2148 int retval = ERROR_OK;
2150 if (target->backup_working_area && area->backup) {
2151 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
2152 if (retval != ERROR_OK)
2153 LOG_ERROR("failed to restore %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2154 area->size, area->address);
2160 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
2161 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
2163 if (!area || area->free)
2166 int retval = ERROR_OK;
2168 retval = target_restore_working_area(target, area);
2169 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
2170 if (retval != ERROR_OK)
2176 LOG_DEBUG("freed %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2177 area->size, area->address);
2179 /* mark user pointer invalid */
2180 /* TODO: Is this really safe? It points to some previous caller's memory.
2181 * How could we know that the area pointer is still in that place and not
2182 * some other vital data? What's the purpose of this, anyway? */
2186 target_merge_working_areas(target);
2188 print_wa_layout(target);
2193 int target_free_working_area(struct target *target, struct working_area *area)
2195 return target_free_working_area_restore(target, area, 1);
2198 /* free resources and restore memory, if restoring memory fails,
2199 * free up resources anyway
2201 static void target_free_all_working_areas_restore(struct target *target, int restore)
2203 struct working_area *c = target->working_areas;
2205 LOG_DEBUG("freeing all working areas");
2207 /* Loop through all areas, restoring the allocated ones and marking them as free */
2211 target_restore_working_area(target, c);
2213 *c->user = NULL; /* Same as above */
2219 /* Run a merge pass to combine all areas into one */
2220 target_merge_working_areas(target);
2222 print_wa_layout(target);
2225 void target_free_all_working_areas(struct target *target)
2227 target_free_all_working_areas_restore(target, 1);
2229 /* Now we have none or only one working area marked as free */
2230 if (target->working_areas) {
2231 /* Free the last one to allow on-the-fly moving and resizing */
2232 free(target->working_areas->backup);
2233 free(target->working_areas);
2234 target->working_areas = NULL;
2238 /* Find the largest number of bytes that can be allocated */
2239 uint32_t target_get_working_area_avail(struct target *target)
2241 struct working_area *c = target->working_areas;
2242 uint32_t max_size = 0;
2245 return target->working_area_size;
2248 if (c->free && max_size < c->size)
2257 static void target_destroy(struct target *target)
2259 if (target->type->deinit_target)
2260 target->type->deinit_target(target);
2262 if (target->semihosting)
2263 free(target->semihosting->basedir);
2264 free(target->semihosting);
2266 jtag_unregister_event_callback(jtag_enable_callback, target);
2268 struct target_event_action *teap = target->event_action;
2270 struct target_event_action *next = teap->next;
2271 Jim_DecrRefCount(teap->interp, teap->body);
2276 target_free_all_working_areas(target);
2278 /* release the targets SMP list */
2280 struct target_list *head, *tmp;
2282 list_for_each_entry_safe(head, tmp, target->smp_targets, lh) {
2283 list_del(&head->lh);
2284 head->target->smp = 0;
2287 if (target->smp_targets != &empty_smp_targets)
2288 free(target->smp_targets);
2292 rtos_destroy(target);
2294 free(target->gdb_port_override);
2296 free(target->trace_info);
2297 free(target->fileio_info);
2298 free(target->cmd_name);
2302 void target_quit(void)
2304 struct target_event_callback *pe = target_event_callbacks;
2306 struct target_event_callback *t = pe->next;
2310 target_event_callbacks = NULL;
2312 struct target_timer_callback *pt = target_timer_callbacks;
2314 struct target_timer_callback *t = pt->next;
2318 target_timer_callbacks = NULL;
2320 for (struct target *target = all_targets; target;) {
2324 target_destroy(target);
2331 int target_arch_state(struct target *target)
2335 LOG_WARNING("No target has been configured");
2339 if (target->state != TARGET_HALTED)
2342 retval = target->type->arch_state(target);
2346 static int target_get_gdb_fileio_info_default(struct target *target,
2347 struct gdb_fileio_info *fileio_info)
2349 /* If target does not support semi-hosting function, target
2350 has no need to provide .get_gdb_fileio_info callback.
2351 It just return ERROR_FAIL and gdb_server will return "Txx"
2352 as target halted every time. */
2356 static int target_gdb_fileio_end_default(struct target *target,
2357 int retcode, int fileio_errno, bool ctrl_c)
2362 int target_profiling_default(struct target *target, uint32_t *samples,
2363 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
2365 struct timeval timeout, now;
2367 gettimeofday(&timeout, NULL);
2368 timeval_add_time(&timeout, seconds, 0);
2370 LOG_INFO("Starting profiling. Halting and resuming the"
2371 " target as often as we can...");
2373 uint32_t sample_count = 0;
2374 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2375 struct reg *reg = register_get_by_name(target->reg_cache, "pc", true);
2377 int retval = ERROR_OK;
2379 target_poll(target);
2380 if (target->state == TARGET_HALTED) {
2381 uint32_t t = buf_get_u32(reg->value, 0, 32);
2382 samples[sample_count++] = t;
2383 /* current pc, addr = 0, do not handle breakpoints, not debugging */
2384 retval = target_resume(target, 1, 0, 0, 0);
2385 target_poll(target);
2386 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2387 } else if (target->state == TARGET_RUNNING) {
2388 /* We want to quickly sample the PC. */
2389 retval = target_halt(target);
2391 LOG_INFO("Target not halted or running");
2396 if (retval != ERROR_OK)
2399 gettimeofday(&now, NULL);
2400 if ((sample_count >= max_num_samples) || timeval_compare(&now, &timeout) >= 0) {
2401 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2406 *num_samples = sample_count;
2410 /* Single aligned words are guaranteed to use 16 or 32 bit access
2411 * mode respectively, otherwise data is handled as quickly as
2414 int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
2416 LOG_DEBUG("writing buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2419 if (!target_was_examined(target)) {
2420 LOG_ERROR("Target not examined yet");
2427 if ((address + size - 1) < address) {
2428 /* GDB can request this when e.g. PC is 0xfffffffc */
2429 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2435 return target->type->write_buffer(target, address, size, buffer);
2438 static int target_write_buffer_default(struct target *target,
2439 target_addr_t address, uint32_t count, const uint8_t *buffer)
2442 unsigned int data_bytes = target_data_bits(target) / 8;
2444 /* Align up to maximum bytes. The loop condition makes sure the next pass
2445 * will have something to do with the size we leave to it. */
2447 size < data_bytes && count >= size * 2 + (address & size);
2449 if (address & size) {
2450 int retval = target_write_memory(target, address, size, 1, buffer);
2451 if (retval != ERROR_OK)
2459 /* Write the data with as large access size as possible. */
2460 for (; size > 0; size /= 2) {
2461 uint32_t aligned = count - count % size;
2463 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2464 if (retval != ERROR_OK)
2475 /* Single aligned words are guaranteed to use 16 or 32 bit access
2476 * mode respectively, otherwise data is handled as quickly as
2479 int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
2481 LOG_DEBUG("reading buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2484 if (!target_was_examined(target)) {
2485 LOG_ERROR("Target not examined yet");
2492 if ((address + size - 1) < address) {
2493 /* GDB can request this when e.g. PC is 0xfffffffc */
2494 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2500 return target->type->read_buffer(target, address, size, buffer);
2503 static int target_read_buffer_default(struct target *target, target_addr_t address, uint32_t count, uint8_t *buffer)
2506 unsigned int data_bytes = target_data_bits(target) / 8;
2508 /* Align up to maximum bytes. The loop condition makes sure the next pass
2509 * will have something to do with the size we leave to it. */
2511 size < data_bytes && count >= size * 2 + (address & size);
2513 if (address & size) {
2514 int retval = target_read_memory(target, address, size, 1, buffer);
2515 if (retval != ERROR_OK)
2523 /* Read the data with as large access size as possible. */
2524 for (; size > 0; size /= 2) {
2525 uint32_t aligned = count - count % size;
2527 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2528 if (retval != ERROR_OK)
2539 int target_checksum_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t *crc)
2544 uint32_t checksum = 0;
2545 if (!target_was_examined(target)) {
2546 LOG_ERROR("Target not examined yet");
2549 if (!target->type->checksum_memory) {
2550 LOG_ERROR("Target %s doesn't support checksum_memory", target_name(target));
2554 retval = target->type->checksum_memory(target, address, size, &checksum);
2555 if (retval != ERROR_OK) {
2556 buffer = malloc(size);
2558 LOG_ERROR("error allocating buffer for section (%" PRIu32 " bytes)", size);
2559 return ERROR_COMMAND_SYNTAX_ERROR;
2561 retval = target_read_buffer(target, address, size, buffer);
2562 if (retval != ERROR_OK) {
2567 /* convert to target endianness */
2568 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2569 uint32_t target_data;
2570 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2571 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2574 retval = image_calculate_checksum(buffer, size, &checksum);
2583 int target_blank_check_memory(struct target *target,
2584 struct target_memory_check_block *blocks, int num_blocks,
2585 uint8_t erased_value)
2587 if (!target_was_examined(target)) {
2588 LOG_ERROR("Target not examined yet");
2592 if (!target->type->blank_check_memory)
2593 return ERROR_NOT_IMPLEMENTED;
2595 return target->type->blank_check_memory(target, blocks, num_blocks, erased_value);
2598 int target_read_u64(struct target *target, target_addr_t address, uint64_t *value)
2600 uint8_t value_buf[8];
2601 if (!target_was_examined(target)) {
2602 LOG_ERROR("Target not examined yet");
2606 int retval = target_read_memory(target, address, 8, 1, value_buf);
2608 if (retval == ERROR_OK) {
2609 *value = target_buffer_get_u64(target, value_buf);
2610 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2615 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2622 int target_read_u32(struct target *target, target_addr_t address, uint32_t *value)
2624 uint8_t value_buf[4];
2625 if (!target_was_examined(target)) {
2626 LOG_ERROR("Target not examined yet");
2630 int retval = target_read_memory(target, address, 4, 1, value_buf);
2632 if (retval == ERROR_OK) {
2633 *value = target_buffer_get_u32(target, value_buf);
2634 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2639 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2646 int target_read_u16(struct target *target, target_addr_t address, uint16_t *value)
2648 uint8_t value_buf[2];
2649 if (!target_was_examined(target)) {
2650 LOG_ERROR("Target not examined yet");
2654 int retval = target_read_memory(target, address, 2, 1, value_buf);
2656 if (retval == ERROR_OK) {
2657 *value = target_buffer_get_u16(target, value_buf);
2658 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%4.4" PRIx16,
2663 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2670 int target_read_u8(struct target *target, target_addr_t address, uint8_t *value)
2672 if (!target_was_examined(target)) {
2673 LOG_ERROR("Target not examined yet");
2677 int retval = target_read_memory(target, address, 1, 1, value);
2679 if (retval == ERROR_OK) {
2680 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2685 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2692 int target_write_u64(struct target *target, target_addr_t address, uint64_t value)
2695 uint8_t value_buf[8];
2696 if (!target_was_examined(target)) {
2697 LOG_ERROR("Target not examined yet");
2701 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2705 target_buffer_set_u64(target, value_buf, value);
2706 retval = target_write_memory(target, address, 8, 1, value_buf);
2707 if (retval != ERROR_OK)
2708 LOG_DEBUG("failed: %i", retval);
2713 int target_write_u32(struct target *target, target_addr_t address, uint32_t value)
2716 uint8_t value_buf[4];
2717 if (!target_was_examined(target)) {
2718 LOG_ERROR("Target not examined yet");
2722 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2726 target_buffer_set_u32(target, value_buf, value);
2727 retval = target_write_memory(target, address, 4, 1, value_buf);
2728 if (retval != ERROR_OK)
2729 LOG_DEBUG("failed: %i", retval);
2734 int target_write_u16(struct target *target, target_addr_t address, uint16_t value)
2737 uint8_t value_buf[2];
2738 if (!target_was_examined(target)) {
2739 LOG_ERROR("Target not examined yet");
2743 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2747 target_buffer_set_u16(target, value_buf, value);
2748 retval = target_write_memory(target, address, 2, 1, value_buf);
2749 if (retval != ERROR_OK)
2750 LOG_DEBUG("failed: %i", retval);
2755 int target_write_u8(struct target *target, target_addr_t address, uint8_t value)
2758 if (!target_was_examined(target)) {
2759 LOG_ERROR("Target not examined yet");
2763 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2766 retval = target_write_memory(target, address, 1, 1, &value);
2767 if (retval != ERROR_OK)
2768 LOG_DEBUG("failed: %i", retval);
2773 int target_write_phys_u64(struct target *target, target_addr_t address, uint64_t value)
2776 uint8_t value_buf[8];
2777 if (!target_was_examined(target)) {
2778 LOG_ERROR("Target not examined yet");
2782 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2786 target_buffer_set_u64(target, value_buf, value);
2787 retval = target_write_phys_memory(target, address, 8, 1, value_buf);
2788 if (retval != ERROR_OK)
2789 LOG_DEBUG("failed: %i", retval);
2794 int target_write_phys_u32(struct target *target, target_addr_t address, uint32_t value)
2797 uint8_t value_buf[4];
2798 if (!target_was_examined(target)) {
2799 LOG_ERROR("Target not examined yet");
2803 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2807 target_buffer_set_u32(target, value_buf, value);
2808 retval = target_write_phys_memory(target, address, 4, 1, value_buf);
2809 if (retval != ERROR_OK)
2810 LOG_DEBUG("failed: %i", retval);
2815 int target_write_phys_u16(struct target *target, target_addr_t address, uint16_t value)
2818 uint8_t value_buf[2];
2819 if (!target_was_examined(target)) {
2820 LOG_ERROR("Target not examined yet");
2824 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2828 target_buffer_set_u16(target, value_buf, value);
2829 retval = target_write_phys_memory(target, address, 2, 1, value_buf);
2830 if (retval != ERROR_OK)
2831 LOG_DEBUG("failed: %i", retval);
2836 int target_write_phys_u8(struct target *target, target_addr_t address, uint8_t value)
2839 if (!target_was_examined(target)) {
2840 LOG_ERROR("Target not examined yet");
2844 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2847 retval = target_write_phys_memory(target, address, 1, 1, &value);
2848 if (retval != ERROR_OK)
2849 LOG_DEBUG("failed: %i", retval);
2854 static int find_target(struct command_invocation *cmd, const char *name)
2856 struct target *target = get_target(name);
2858 command_print(cmd, "Target: %s is unknown, try one of:\n", name);
2861 if (!target->tap->enabled) {
2862 command_print(cmd, "Target: TAP %s is disabled, "
2863 "can't be the current target\n",
2864 target->tap->dotted_name);
2868 cmd->ctx->current_target = target;
2869 if (cmd->ctx->current_target_override)
2870 cmd->ctx->current_target_override = target;
2876 COMMAND_HANDLER(handle_targets_command)
2878 int retval = ERROR_OK;
2879 if (CMD_ARGC == 1) {
2880 retval = find_target(CMD, CMD_ARGV[0]);
2881 if (retval == ERROR_OK) {
2887 struct target *target = all_targets;
2888 command_print(CMD, " TargetName Type Endian TapName State ");
2889 command_print(CMD, "-- ------------------ ---------- ------ ------------------ ------------");
2894 if (target->tap->enabled)
2895 state = target_state_name(target);
2897 state = "tap-disabled";
2899 if (CMD_CTX->current_target == target)
2902 /* keep columns lined up to match the headers above */
2904 "%2d%c %-18s %-10s %-6s %-18s %s",
2905 target->target_number,
2907 target_name(target),
2908 target_type_name(target),
2909 jim_nvp_value2name_simple(nvp_target_endian,
2910 target->endianness)->name,
2911 target->tap->dotted_name,
2913 target = target->next;
2919 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2921 static int power_dropout;
2922 static int srst_asserted;
2924 static int run_power_restore;
2925 static int run_power_dropout;
2926 static int run_srst_asserted;
2927 static int run_srst_deasserted;
2929 static int sense_handler(void)
2931 static int prev_srst_asserted;
2932 static int prev_power_dropout;
2934 int retval = jtag_power_dropout(&power_dropout);
2935 if (retval != ERROR_OK)
2939 power_restored = prev_power_dropout && !power_dropout;
2941 run_power_restore = 1;
2943 int64_t current = timeval_ms();
2944 static int64_t last_power;
2945 bool wait_more = last_power + 2000 > current;
2946 if (power_dropout && !wait_more) {
2947 run_power_dropout = 1;
2948 last_power = current;
2951 retval = jtag_srst_asserted(&srst_asserted);
2952 if (retval != ERROR_OK)
2955 int srst_deasserted;
2956 srst_deasserted = prev_srst_asserted && !srst_asserted;
2958 static int64_t last_srst;
2959 wait_more = last_srst + 2000 > current;
2960 if (srst_deasserted && !wait_more) {
2961 run_srst_deasserted = 1;
2962 last_srst = current;
2965 if (!prev_srst_asserted && srst_asserted)
2966 run_srst_asserted = 1;
2968 prev_srst_asserted = srst_asserted;
2969 prev_power_dropout = power_dropout;
2971 if (srst_deasserted || power_restored) {
2972 /* Other than logging the event we can't do anything here.
2973 * Issuing a reset is a particularly bad idea as we might
2974 * be inside a reset already.
2981 /* process target state changes */
2982 static int handle_target(void *priv)
2984 Jim_Interp *interp = (Jim_Interp *)priv;
2985 int retval = ERROR_OK;
2987 if (!is_jtag_poll_safe()) {
2988 /* polling is disabled currently */
2992 /* we do not want to recurse here... */
2993 static int recursive;
2997 /* danger! running these procedures can trigger srst assertions and power dropouts.
2998 * We need to avoid an infinite loop/recursion here and we do that by
2999 * clearing the flags after running these events.
3001 int did_something = 0;
3002 if (run_srst_asserted) {
3003 LOG_INFO("srst asserted detected, running srst_asserted proc.");
3004 Jim_Eval(interp, "srst_asserted");
3007 if (run_srst_deasserted) {
3008 Jim_Eval(interp, "srst_deasserted");
3011 if (run_power_dropout) {
3012 LOG_INFO("Power dropout detected, running power_dropout proc.");
3013 Jim_Eval(interp, "power_dropout");
3016 if (run_power_restore) {
3017 Jim_Eval(interp, "power_restore");
3021 if (did_something) {
3022 /* clear detect flags */
3026 /* clear action flags */
3028 run_srst_asserted = 0;
3029 run_srst_deasserted = 0;
3030 run_power_restore = 0;
3031 run_power_dropout = 0;
3036 /* Poll targets for state changes unless that's globally disabled.
3037 * Skip targets that are currently disabled.
3039 for (struct target *target = all_targets;
3040 is_jtag_poll_safe() && target;
3041 target = target->next) {
3043 if (!target_was_examined(target))
3046 if (!target->tap->enabled)
3049 if (target->backoff.times > target->backoff.count) {
3050 /* do not poll this time as we failed previously */
3051 target->backoff.count++;
3054 target->backoff.count = 0;
3056 /* only poll target if we've got power and srst isn't asserted */
3057 if (!power_dropout && !srst_asserted) {
3058 /* polling may fail silently until the target has been examined */
3059 retval = target_poll(target);
3060 if (retval != ERROR_OK) {
3061 /* 100ms polling interval. Increase interval between polling up to 5000ms */
3062 if (target->backoff.times * polling_interval < 5000) {
3063 target->backoff.times *= 2;
3064 target->backoff.times++;
3067 /* Tell GDB to halt the debugger. This allows the user to
3068 * run monitor commands to handle the situation.
3070 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3072 if (target->backoff.times > 0) {
3073 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
3074 target_reset_examined(target);
3075 retval = target_examine_one(target);
3076 /* Target examination could have failed due to unstable connection,
3077 * but we set the examined flag anyway to repoll it later */
3078 if (retval != ERROR_OK) {
3079 target_set_examined(target);
3080 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
3081 target->backoff.times * polling_interval);
3086 /* Since we succeeded, we reset backoff count */
3087 target->backoff.times = 0;
3094 COMMAND_HANDLER(handle_reg_command)
3098 struct target *target = get_current_target(CMD_CTX);
3099 struct reg *reg = NULL;
3101 /* list all available registers for the current target */
3102 if (CMD_ARGC == 0) {
3103 struct reg_cache *cache = target->reg_cache;
3105 unsigned int count = 0;
3109 command_print(CMD, "===== %s", cache->name);
3111 for (i = 0, reg = cache->reg_list;
3112 i < cache->num_regs;
3113 i++, reg++, count++) {
3114 if (reg->exist == false || reg->hidden)
3116 /* only print cached values if they are valid */
3118 char *value = buf_to_hex_str(reg->value,
3121 "(%i) %s (/%" PRIu32 "): 0x%s%s",
3129 command_print(CMD, "(%i) %s (/%" PRIu32 ")",
3134 cache = cache->next;
3140 /* access a single register by its ordinal number */
3141 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
3143 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
3145 struct reg_cache *cache = target->reg_cache;
3146 unsigned int count = 0;
3149 for (i = 0; i < cache->num_regs; i++) {
3150 if (count++ == num) {
3151 reg = &cache->reg_list[i];
3157 cache = cache->next;
3161 command_print(CMD, "%i is out of bounds, the current target "
3162 "has only %i registers (0 - %i)", num, count, count - 1);
3166 /* access a single register by its name */
3167 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], true);
3173 assert(reg); /* give clang a hint that we *know* reg is != NULL here */
3178 /* display a register */
3179 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
3180 && (CMD_ARGV[1][0] <= '9')))) {
3181 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
3184 if (reg->valid == 0) {
3185 int retval = reg->type->get(reg);
3186 if (retval != ERROR_OK) {
3187 LOG_ERROR("Could not read register '%s'", reg->name);
3191 char *value = buf_to_hex_str(reg->value, reg->size);
3192 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3197 /* set register value */
3198 if (CMD_ARGC == 2) {
3199 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
3202 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
3204 int retval = reg->type->set(reg, buf);
3205 if (retval != ERROR_OK) {
3206 LOG_ERROR("Could not write to register '%s'", reg->name);
3208 char *value = buf_to_hex_str(reg->value, reg->size);
3209 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3218 return ERROR_COMMAND_SYNTAX_ERROR;
3221 command_print(CMD, "register %s not found in current target", CMD_ARGV[0]);
3225 COMMAND_HANDLER(handle_poll_command)
3227 int retval = ERROR_OK;
3228 struct target *target = get_current_target(CMD_CTX);
3230 if (CMD_ARGC == 0) {
3231 command_print(CMD, "background polling: %s",
3232 jtag_poll_get_enabled() ? "on" : "off");
3233 command_print(CMD, "TAP: %s (%s)",
3234 target->tap->dotted_name,
3235 target->tap->enabled ? "enabled" : "disabled");
3236 if (!target->tap->enabled)
3238 retval = target_poll(target);
3239 if (retval != ERROR_OK)
3241 retval = target_arch_state(target);
3242 if (retval != ERROR_OK)
3244 } else if (CMD_ARGC == 1) {
3246 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
3247 jtag_poll_set_enabled(enable);
3249 return ERROR_COMMAND_SYNTAX_ERROR;
3254 COMMAND_HANDLER(handle_wait_halt_command)
3257 return ERROR_COMMAND_SYNTAX_ERROR;
3259 unsigned ms = DEFAULT_HALT_TIMEOUT;
3260 if (1 == CMD_ARGC) {
3261 int retval = parse_uint(CMD_ARGV[0], &ms);
3262 if (retval != ERROR_OK)
3263 return ERROR_COMMAND_SYNTAX_ERROR;
3266 struct target *target = get_current_target(CMD_CTX);
3267 return target_wait_state(target, TARGET_HALTED, ms);
3270 /* wait for target state to change. The trick here is to have a low
3271 * latency for short waits and not to suck up all the CPU time
3274 * After 500ms, keep_alive() is invoked
3276 int target_wait_state(struct target *target, enum target_state state, int ms)
3279 int64_t then = 0, cur;
3283 retval = target_poll(target);
3284 if (retval != ERROR_OK)
3286 if (target->state == state)
3291 then = timeval_ms();
3292 LOG_DEBUG("waiting for target %s...",
3293 jim_nvp_value2name_simple(nvp_target_state, state)->name);
3299 if ((cur-then) > ms) {
3300 LOG_ERROR("timed out while waiting for target %s",
3301 jim_nvp_value2name_simple(nvp_target_state, state)->name);
3309 COMMAND_HANDLER(handle_halt_command)
3313 struct target *target = get_current_target(CMD_CTX);
3315 target->verbose_halt_msg = true;
3317 int retval = target_halt(target);
3318 if (retval != ERROR_OK)
3321 if (CMD_ARGC == 1) {
3322 unsigned wait_local;
3323 retval = parse_uint(CMD_ARGV[0], &wait_local);
3324 if (retval != ERROR_OK)
3325 return ERROR_COMMAND_SYNTAX_ERROR;
3330 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
3333 COMMAND_HANDLER(handle_soft_reset_halt_command)
3335 struct target *target = get_current_target(CMD_CTX);
3337 LOG_USER("requesting target halt and executing a soft reset");
3339 target_soft_reset_halt(target);
3344 COMMAND_HANDLER(handle_reset_command)
3347 return ERROR_COMMAND_SYNTAX_ERROR;
3349 enum target_reset_mode reset_mode = RESET_RUN;
3350 if (CMD_ARGC == 1) {
3351 const struct jim_nvp *n;
3352 n = jim_nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
3353 if ((!n->name) || (n->value == RESET_UNKNOWN))
3354 return ERROR_COMMAND_SYNTAX_ERROR;
3355 reset_mode = n->value;
3358 /* reset *all* targets */
3359 return target_process_reset(CMD, reset_mode);
3363 COMMAND_HANDLER(handle_resume_command)
3367 return ERROR_COMMAND_SYNTAX_ERROR;
3369 struct target *target = get_current_target(CMD_CTX);
3371 /* with no CMD_ARGV, resume from current pc, addr = 0,
3372 * with one arguments, addr = CMD_ARGV[0],
3373 * handle breakpoints, not debugging */
3374 target_addr_t addr = 0;
3375 if (CMD_ARGC == 1) {
3376 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3380 return target_resume(target, current, addr, 1, 0);
3383 COMMAND_HANDLER(handle_step_command)
3386 return ERROR_COMMAND_SYNTAX_ERROR;
3390 /* with no CMD_ARGV, step from current pc, addr = 0,
3391 * with one argument addr = CMD_ARGV[0],
3392 * handle breakpoints, debugging */
3393 target_addr_t addr = 0;
3395 if (CMD_ARGC == 1) {
3396 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3400 struct target *target = get_current_target(CMD_CTX);
3402 return target_step(target, current_pc, addr, 1);
3405 void target_handle_md_output(struct command_invocation *cmd,
3406 struct target *target, target_addr_t address, unsigned size,
3407 unsigned count, const uint8_t *buffer)
3409 const unsigned line_bytecnt = 32;
3410 unsigned line_modulo = line_bytecnt / size;
3412 char output[line_bytecnt * 4 + 1];
3413 unsigned output_len = 0;
3415 const char *value_fmt;
3418 value_fmt = "%16.16"PRIx64" ";
3421 value_fmt = "%8.8"PRIx64" ";
3424 value_fmt = "%4.4"PRIx64" ";
3427 value_fmt = "%2.2"PRIx64" ";
3430 /* "can't happen", caller checked */
3431 LOG_ERROR("invalid memory read size: %u", size);
3435 for (unsigned i = 0; i < count; i++) {
3436 if (i % line_modulo == 0) {
3437 output_len += snprintf(output + output_len,
3438 sizeof(output) - output_len,
3439 TARGET_ADDR_FMT ": ",
3440 (address + (i * size)));
3444 const uint8_t *value_ptr = buffer + i * size;
3447 value = target_buffer_get_u64(target, value_ptr);
3450 value = target_buffer_get_u32(target, value_ptr);
3453 value = target_buffer_get_u16(target, value_ptr);
3458 output_len += snprintf(output + output_len,
3459 sizeof(output) - output_len,
3462 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
3463 command_print(cmd, "%s", output);
3469 COMMAND_HANDLER(handle_md_command)
3472 return ERROR_COMMAND_SYNTAX_ERROR;
3475 switch (CMD_NAME[2]) {
3489 return ERROR_COMMAND_SYNTAX_ERROR;
3492 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3493 int (*fn)(struct target *target,
3494 target_addr_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
3498 fn = target_read_phys_memory;
3500 fn = target_read_memory;
3501 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
3502 return ERROR_COMMAND_SYNTAX_ERROR;
3504 target_addr_t address;
3505 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3509 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3511 uint8_t *buffer = calloc(count, size);
3513 LOG_ERROR("Failed to allocate md read buffer");
3517 struct target *target = get_current_target(CMD_CTX);
3518 int retval = fn(target, address, size, count, buffer);
3519 if (retval == ERROR_OK)
3520 target_handle_md_output(CMD, target, address, size, count, buffer);
3527 typedef int (*target_write_fn)(struct target *target,
3528 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3530 static int target_fill_mem(struct target *target,
3531 target_addr_t address,
3539 /* We have to write in reasonably large chunks to be able
3540 * to fill large memory areas with any sane speed */
3541 const unsigned chunk_size = 16384;
3542 uint8_t *target_buf = malloc(chunk_size * data_size);
3544 LOG_ERROR("Out of memory");
3548 for (unsigned i = 0; i < chunk_size; i++) {
3549 switch (data_size) {
3551 target_buffer_set_u64(target, target_buf + i * data_size, b);
3554 target_buffer_set_u32(target, target_buf + i * data_size, b);
3557 target_buffer_set_u16(target, target_buf + i * data_size, b);
3560 target_buffer_set_u8(target, target_buf + i * data_size, b);
3567 int retval = ERROR_OK;
3569 for (unsigned x = 0; x < c; x += chunk_size) {
3572 if (current > chunk_size)
3573 current = chunk_size;
3574 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3575 if (retval != ERROR_OK)
3577 /* avoid GDB timeouts */
3586 COMMAND_HANDLER(handle_mw_command)
3589 return ERROR_COMMAND_SYNTAX_ERROR;
3590 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3595 fn = target_write_phys_memory;
3597 fn = target_write_memory;
3598 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3599 return ERROR_COMMAND_SYNTAX_ERROR;
3601 target_addr_t address;
3602 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3605 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[1], value);
3609 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3611 struct target *target = get_current_target(CMD_CTX);
3613 switch (CMD_NAME[2]) {
3627 return ERROR_COMMAND_SYNTAX_ERROR;
3630 return target_fill_mem(target, address, fn, wordsize, value, count);
3633 static COMMAND_HELPER(parse_load_image_command, struct image *image,
3634 target_addr_t *min_address, target_addr_t *max_address)
3636 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3637 return ERROR_COMMAND_SYNTAX_ERROR;
3639 /* a base address isn't always necessary,
3640 * default to 0x0 (i.e. don't relocate) */
3641 if (CMD_ARGC >= 2) {
3643 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3644 image->base_address = addr;
3645 image->base_address_set = true;
3647 image->base_address_set = false;
3649 image->start_address_set = false;
3652 COMMAND_PARSE_ADDRESS(CMD_ARGV[3], *min_address);
3653 if (CMD_ARGC == 5) {
3654 COMMAND_PARSE_ADDRESS(CMD_ARGV[4], *max_address);
3655 /* use size (given) to find max (required) */
3656 *max_address += *min_address;
3659 if (*min_address > *max_address)
3660 return ERROR_COMMAND_SYNTAX_ERROR;
3665 COMMAND_HANDLER(handle_load_image_command)
3669 uint32_t image_size;
3670 target_addr_t min_address = 0;
3671 target_addr_t max_address = -1;
3674 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
3675 &image, &min_address, &max_address);
3676 if (retval != ERROR_OK)
3679 struct target *target = get_current_target(CMD_CTX);
3681 struct duration bench;
3682 duration_start(&bench);
3684 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3689 for (unsigned int i = 0; i < image.num_sections; i++) {
3690 buffer = malloc(image.sections[i].size);
3693 "error allocating buffer for section (%d bytes)",
3694 (int)(image.sections[i].size));
3695 retval = ERROR_FAIL;
3699 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3700 if (retval != ERROR_OK) {
3705 uint32_t offset = 0;
3706 uint32_t length = buf_cnt;
3708 /* DANGER!!! beware of unsigned comparison here!!! */
3710 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3711 (image.sections[i].base_address < max_address)) {
3713 if (image.sections[i].base_address < min_address) {
3714 /* clip addresses below */
3715 offset += min_address-image.sections[i].base_address;
3719 if (image.sections[i].base_address + buf_cnt > max_address)
3720 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3722 retval = target_write_buffer(target,
3723 image.sections[i].base_address + offset, length, buffer + offset);
3724 if (retval != ERROR_OK) {
3728 image_size += length;
3729 command_print(CMD, "%u bytes written at address " TARGET_ADDR_FMT "",
3730 (unsigned int)length,
3731 image.sections[i].base_address + offset);
3737 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3738 command_print(CMD, "downloaded %" PRIu32 " bytes "
3739 "in %fs (%0.3f KiB/s)", image_size,
3740 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3743 image_close(&image);
3749 COMMAND_HANDLER(handle_dump_image_command)
3751 struct fileio *fileio;
3753 int retval, retvaltemp;
3754 target_addr_t address, size;
3755 struct duration bench;
3756 struct target *target = get_current_target(CMD_CTX);
3759 return ERROR_COMMAND_SYNTAX_ERROR;
3761 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], address);
3762 COMMAND_PARSE_ADDRESS(CMD_ARGV[2], size);
3764 uint32_t buf_size = (size > 4096) ? 4096 : size;
3765 buffer = malloc(buf_size);
3769 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3770 if (retval != ERROR_OK) {
3775 duration_start(&bench);
3778 size_t size_written;
3779 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3780 retval = target_read_buffer(target, address, this_run_size, buffer);
3781 if (retval != ERROR_OK)
3784 retval = fileio_write(fileio, this_run_size, buffer, &size_written);
3785 if (retval != ERROR_OK)
3788 size -= this_run_size;
3789 address += this_run_size;
3794 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3796 retval = fileio_size(fileio, &filesize);
3797 if (retval != ERROR_OK)
3800 "dumped %zu bytes in %fs (%0.3f KiB/s)", filesize,
3801 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3804 retvaltemp = fileio_close(fileio);
3805 if (retvaltemp != ERROR_OK)
3814 IMAGE_CHECKSUM_ONLY = 2
3817 static COMMAND_HELPER(handle_verify_image_command_internal, enum verify_mode verify)
3821 uint32_t image_size;
3823 uint32_t checksum = 0;
3824 uint32_t mem_checksum = 0;
3828 struct target *target = get_current_target(CMD_CTX);
3831 return ERROR_COMMAND_SYNTAX_ERROR;
3834 LOG_ERROR("no target selected");
3838 struct duration bench;
3839 duration_start(&bench);
3841 if (CMD_ARGC >= 2) {
3843 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3844 image.base_address = addr;
3845 image.base_address_set = true;
3847 image.base_address_set = false;
3848 image.base_address = 0x0;
3851 image.start_address_set = false;
3853 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3854 if (retval != ERROR_OK)
3860 for (unsigned int i = 0; i < image.num_sections; i++) {
3861 buffer = malloc(image.sections[i].size);
3864 "error allocating buffer for section (%" PRIu32 " bytes)",
3865 image.sections[i].size);
3868 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3869 if (retval != ERROR_OK) {
3874 if (verify >= IMAGE_VERIFY) {
3875 /* calculate checksum of image */
3876 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3877 if (retval != ERROR_OK) {
3882 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3883 if (retval != ERROR_OK) {
3887 if ((checksum != mem_checksum) && (verify == IMAGE_CHECKSUM_ONLY)) {
3888 LOG_ERROR("checksum mismatch");
3890 retval = ERROR_FAIL;
3893 if (checksum != mem_checksum) {
3894 /* failed crc checksum, fall back to a binary compare */
3898 LOG_ERROR("checksum mismatch - attempting binary compare");
3900 data = malloc(buf_cnt);
3902 retval = target_read_buffer(target, image.sections[i].base_address, buf_cnt, data);
3903 if (retval == ERROR_OK) {
3905 for (t = 0; t < buf_cnt; t++) {
3906 if (data[t] != buffer[t]) {
3908 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3910 (unsigned)(t + image.sections[i].base_address),
3913 if (diffs++ >= 127) {
3914 command_print(CMD, "More than 128 errors, the rest are not printed.");
3926 command_print(CMD, "address " TARGET_ADDR_FMT " length 0x%08zx",
3927 image.sections[i].base_address,
3932 image_size += buf_cnt;
3935 command_print(CMD, "No more differences found.");
3938 retval = ERROR_FAIL;
3939 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3940 command_print(CMD, "verified %" PRIu32 " bytes "
3941 "in %fs (%0.3f KiB/s)", image_size,
3942 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3945 image_close(&image);
3950 COMMAND_HANDLER(handle_verify_image_checksum_command)
3952 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_CHECKSUM_ONLY);
3955 COMMAND_HANDLER(handle_verify_image_command)
3957 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_VERIFY);
3960 COMMAND_HANDLER(handle_test_image_command)
3962 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_TEST);
3965 static int handle_bp_command_list(struct command_invocation *cmd)
3967 struct target *target = get_current_target(cmd->ctx);
3968 struct breakpoint *breakpoint = target->breakpoints;
3969 while (breakpoint) {
3970 if (breakpoint->type == BKPT_SOFT) {
3971 char *buf = buf_to_hex_str(breakpoint->orig_instr,
3972 breakpoint->length);
3973 command_print(cmd, "IVA breakpoint: " TARGET_ADDR_FMT ", 0x%x, 0x%s",
3974 breakpoint->address,
3979 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3980 command_print(cmd, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %u",
3982 breakpoint->length, breakpoint->number);
3983 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3984 command_print(cmd, "Hybrid breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %u",
3985 breakpoint->address,
3986 breakpoint->length, breakpoint->number);
3987 command_print(cmd, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3990 command_print(cmd, "Breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %u",
3991 breakpoint->address,
3992 breakpoint->length, breakpoint->number);
3995 breakpoint = breakpoint->next;
4000 static int handle_bp_command_set(struct command_invocation *cmd,
4001 target_addr_t addr, uint32_t asid, uint32_t length, int hw)
4003 struct target *target = get_current_target(cmd->ctx);
4007 retval = breakpoint_add(target, addr, length, hw);
4008 /* error is always logged in breakpoint_add(), do not print it again */
4009 if (retval == ERROR_OK)
4010 command_print(cmd, "breakpoint set at " TARGET_ADDR_FMT "", addr);
4012 } else if (addr == 0) {
4013 if (!target->type->add_context_breakpoint) {
4014 LOG_ERROR("Context breakpoint not available");
4015 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
4017 retval = context_breakpoint_add(target, asid, length, hw);
4018 /* error is always logged in context_breakpoint_add(), do not print it again */
4019 if (retval == ERROR_OK)
4020 command_print(cmd, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
4023 if (!target->type->add_hybrid_breakpoint) {
4024 LOG_ERROR("Hybrid breakpoint not available");
4025 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
4027 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
4028 /* error is always logged in hybrid_breakpoint_add(), do not print it again */
4029 if (retval == ERROR_OK)
4030 command_print(cmd, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
4035 COMMAND_HANDLER(handle_bp_command)
4044 return handle_bp_command_list(CMD);
4048 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4049 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4050 return handle_bp_command_set(CMD, addr, asid, length, hw);
4053 if (strcmp(CMD_ARGV[2], "hw") == 0) {
4055 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4056 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4058 return handle_bp_command_set(CMD, addr, asid, length, hw);
4059 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
4061 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
4062 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4064 return handle_bp_command_set(CMD, addr, asid, length, hw);
4069 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4070 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
4071 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
4072 return handle_bp_command_set(CMD, addr, asid, length, hw);
4075 return ERROR_COMMAND_SYNTAX_ERROR;
4079 COMMAND_HANDLER(handle_rbp_command)
4082 return ERROR_COMMAND_SYNTAX_ERROR;
4084 struct target *target = get_current_target(CMD_CTX);
4086 if (!strcmp(CMD_ARGV[0], "all")) {
4087 breakpoint_remove_all(target);
4090 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4092 breakpoint_remove(target, addr);
4098 COMMAND_HANDLER(handle_wp_command)
4100 struct target *target = get_current_target(CMD_CTX);
4102 if (CMD_ARGC == 0) {
4103 struct watchpoint *watchpoint = target->watchpoints;
4105 while (watchpoint) {
4106 command_print(CMD, "address: " TARGET_ADDR_FMT
4107 ", len: 0x%8.8" PRIx32
4108 ", r/w/a: %i, value: 0x%8.8" PRIx32
4109 ", mask: 0x%8.8" PRIx32,
4110 watchpoint->address,
4112 (int)watchpoint->rw,
4115 watchpoint = watchpoint->next;
4120 enum watchpoint_rw type = WPT_ACCESS;
4121 target_addr_t addr = 0;
4122 uint32_t length = 0;
4123 uint32_t data_value = 0x0;
4124 uint32_t data_mask = 0xffffffff;
4128 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
4131 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
4134 switch (CMD_ARGV[2][0]) {
4145 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
4146 return ERROR_COMMAND_SYNTAX_ERROR;
4150 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4151 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4155 return ERROR_COMMAND_SYNTAX_ERROR;
4158 int retval = watchpoint_add(target, addr, length, type,
4159 data_value, data_mask);
4160 if (retval != ERROR_OK)
4161 LOG_ERROR("Failure setting watchpoints");
4166 COMMAND_HANDLER(handle_rwp_command)
4169 return ERROR_COMMAND_SYNTAX_ERROR;
4172 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4174 struct target *target = get_current_target(CMD_CTX);
4175 watchpoint_remove(target, addr);
4181 * Translate a virtual address to a physical address.
4183 * The low-level target implementation must have logged a detailed error
4184 * which is forwarded to telnet/GDB session.
4186 COMMAND_HANDLER(handle_virt2phys_command)
4189 return ERROR_COMMAND_SYNTAX_ERROR;
4192 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], va);
4195 struct target *target = get_current_target(CMD_CTX);
4196 int retval = target->type->virt2phys(target, va, &pa);
4197 if (retval == ERROR_OK)
4198 command_print(CMD, "Physical address " TARGET_ADDR_FMT "", pa);
4203 static void write_data(FILE *f, const void *data, size_t len)
4205 size_t written = fwrite(data, 1, len, f);
4207 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
4210 static void write_long(FILE *f, int l, struct target *target)
4214 target_buffer_set_u32(target, val, l);
4215 write_data(f, val, 4);
4218 static void write_string(FILE *f, char *s)
4220 write_data(f, s, strlen(s));
4223 typedef unsigned char UNIT[2]; /* unit of profiling */
4225 /* Dump a gmon.out histogram file. */
4226 static void write_gmon(uint32_t *samples, uint32_t sample_num, const char *filename, bool with_range,
4227 uint32_t start_address, uint32_t end_address, struct target *target, uint32_t duration_ms)
4230 FILE *f = fopen(filename, "w");
4233 write_string(f, "gmon");
4234 write_long(f, 0x00000001, target); /* Version */
4235 write_long(f, 0, target); /* padding */
4236 write_long(f, 0, target); /* padding */
4237 write_long(f, 0, target); /* padding */
4239 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
4240 write_data(f, &zero, 1);
4242 /* figure out bucket size */
4246 min = start_address;
4251 for (i = 0; i < sample_num; i++) {
4252 if (min > samples[i])
4254 if (max < samples[i])
4258 /* max should be (largest sample + 1)
4259 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
4263 int address_space = max - min;
4264 assert(address_space >= 2);
4266 /* FIXME: What is the reasonable number of buckets?
4267 * The profiling result will be more accurate if there are enough buckets. */
4268 static const uint32_t max_buckets = 128 * 1024; /* maximum buckets. */
4269 uint32_t num_buckets = address_space / sizeof(UNIT);
4270 if (num_buckets > max_buckets)
4271 num_buckets = max_buckets;
4272 int *buckets = malloc(sizeof(int) * num_buckets);
4277 memset(buckets, 0, sizeof(int) * num_buckets);
4278 for (i = 0; i < sample_num; i++) {
4279 uint32_t address = samples[i];
4281 if ((address < min) || (max <= address))
4284 long long a = address - min;
4285 long long b = num_buckets;
4286 long long c = address_space;
4287 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
4291 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
4292 write_long(f, min, target); /* low_pc */
4293 write_long(f, max, target); /* high_pc */
4294 write_long(f, num_buckets, target); /* # of buckets */
4295 float sample_rate = sample_num / (duration_ms / 1000.0);
4296 write_long(f, sample_rate, target);
4297 write_string(f, "seconds");
4298 for (i = 0; i < (15-strlen("seconds")); i++)
4299 write_data(f, &zero, 1);
4300 write_string(f, "s");
4302 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
4304 char *data = malloc(2 * num_buckets);
4306 for (i = 0; i < num_buckets; i++) {
4311 data[i * 2] = val&0xff;
4312 data[i * 2 + 1] = (val >> 8) & 0xff;
4315 write_data(f, data, num_buckets * 2);
4323 /* profiling samples the CPU PC as quickly as OpenOCD is able,
4324 * which will be used as a random sampling of PC */
4325 COMMAND_HANDLER(handle_profile_command)
4327 struct target *target = get_current_target(CMD_CTX);
4329 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
4330 return ERROR_COMMAND_SYNTAX_ERROR;
4332 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
4334 uint32_t num_of_samples;
4335 int retval = ERROR_OK;
4336 bool halted_before_profiling = target->state == TARGET_HALTED;
4338 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
4340 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
4342 LOG_ERROR("No memory to store samples.");
4346 uint64_t timestart_ms = timeval_ms();
4348 * Some cores let us sample the PC without the
4349 * annoying halt/resume step; for example, ARMv7 PCSR.
4350 * Provide a way to use that more efficient mechanism.
4352 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
4353 &num_of_samples, offset);
4354 if (retval != ERROR_OK) {
4358 uint32_t duration_ms = timeval_ms() - timestart_ms;
4360 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
4362 retval = target_poll(target);
4363 if (retval != ERROR_OK) {
4368 if (target->state == TARGET_RUNNING && halted_before_profiling) {
4369 /* The target was halted before we started and is running now. Halt it,
4370 * for consistency. */
4371 retval = target_halt(target);
4372 if (retval != ERROR_OK) {
4376 } else if (target->state == TARGET_HALTED && !halted_before_profiling) {
4377 /* The target was running before we started and is halted now. Resume
4378 * it, for consistency. */
4379 retval = target_resume(target, 1, 0, 0, 0);
4380 if (retval != ERROR_OK) {
4386 retval = target_poll(target);
4387 if (retval != ERROR_OK) {
4392 uint32_t start_address = 0;
4393 uint32_t end_address = 0;
4394 bool with_range = false;
4395 if (CMD_ARGC == 4) {
4397 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
4398 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
4401 write_gmon(samples, num_of_samples, CMD_ARGV[1],
4402 with_range, start_address, end_address, target, duration_ms);
4403 command_print(CMD, "Wrote %s", CMD_ARGV[1]);
4409 static int new_u64_array_element(Jim_Interp *interp, const char *varname, int idx, uint64_t val)
4412 Jim_Obj *obj_name, *obj_val;
4415 namebuf = alloc_printf("%s(%d)", varname, idx);
4419 obj_name = Jim_NewStringObj(interp, namebuf, -1);
4420 jim_wide wide_val = val;
4421 obj_val = Jim_NewWideObj(interp, wide_val);
4422 if (!obj_name || !obj_val) {
4427 Jim_IncrRefCount(obj_name);
4428 Jim_IncrRefCount(obj_val);
4429 result = Jim_SetVariable(interp, obj_name, obj_val);
4430 Jim_DecrRefCount(interp, obj_name);
4431 Jim_DecrRefCount(interp, obj_val);
4433 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
4437 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
4441 LOG_WARNING("DEPRECATED! use 'read_memory' not 'mem2array'");
4443 /* argv[0] = name of array to receive the data
4444 * argv[1] = desired element width in bits
4445 * argv[2] = memory address
4446 * argv[3] = count of times to read
4447 * argv[4] = optional "phys"
4449 if (argc < 4 || argc > 5) {
4450 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4454 /* Arg 0: Name of the array variable */
4455 const char *varname = Jim_GetString(argv[0], NULL);
4457 /* Arg 1: Bit width of one element */
4459 e = Jim_GetLong(interp, argv[1], &l);
4462 const unsigned int width_bits = l;
4464 if (width_bits != 8 &&
4468 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4469 Jim_AppendStrings(interp, Jim_GetResult(interp),
4470 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4473 const unsigned int width = width_bits / 8;
4475 /* Arg 2: Memory address */
4477 e = Jim_GetWide(interp, argv[2], &wide_addr);
4480 target_addr_t addr = (target_addr_t)wide_addr;
4482 /* Arg 3: Number of elements to read */
4483 e = Jim_GetLong(interp, argv[3], &l);
4489 bool is_phys = false;
4492 const char *phys = Jim_GetString(argv[4], &str_len);
4493 if (!strncmp(phys, "phys", str_len))
4499 /* Argument checks */
4501 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4502 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
4505 if ((addr + (len * width)) < addr) {
4506 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4507 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
4511 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4512 Jim_AppendStrings(interp, Jim_GetResult(interp),
4513 "mem2array: too large read request, exceeds 64K items", NULL);
4518 ((width == 2) && ((addr & 1) == 0)) ||
4519 ((width == 4) && ((addr & 3) == 0)) ||
4520 ((width == 8) && ((addr & 7) == 0))) {
4521 /* alignment correct */
4524 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4525 sprintf(buf, "mem2array address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4528 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4537 const size_t buffersize = 4096;
4538 uint8_t *buffer = malloc(buffersize);
4545 /* Slurp... in buffer size chunks */
4546 const unsigned int max_chunk_len = buffersize / width;
4547 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4551 retval = target_read_phys_memory(target, addr, width, chunk_len, buffer);
4553 retval = target_read_memory(target, addr, width, chunk_len, buffer);
4554 if (retval != ERROR_OK) {
4556 LOG_ERROR("mem2array: Read @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4560 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4561 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
4565 for (size_t i = 0; i < chunk_len ; i++, idx++) {
4569 v = target_buffer_get_u64(target, &buffer[i*width]);
4572 v = target_buffer_get_u32(target, &buffer[i*width]);
4575 v = target_buffer_get_u16(target, &buffer[i*width]);
4578 v = buffer[i] & 0x0ff;
4581 new_u64_array_element(interp, varname, idx, v);
4584 addr += chunk_len * width;
4590 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4595 static int target_jim_read_memory(Jim_Interp *interp, int argc,
4596 Jim_Obj * const *argv)
4599 * argv[1] = memory address
4600 * argv[2] = desired element width in bits
4601 * argv[3] = number of elements to read
4602 * argv[4] = optional "phys"
4605 if (argc < 4 || argc > 5) {
4606 Jim_WrongNumArgs(interp, 1, argv, "address width count ['phys']");
4610 /* Arg 1: Memory address. */
4613 e = Jim_GetWide(interp, argv[1], &wide_addr);
4618 target_addr_t addr = (target_addr_t)wide_addr;
4620 /* Arg 2: Bit width of one element. */
4622 e = Jim_GetLong(interp, argv[2], &l);
4627 const unsigned int width_bits = l;
4629 /* Arg 3: Number of elements to read. */
4630 e = Jim_GetLong(interp, argv[3], &l);
4637 /* Arg 4: Optional 'phys'. */
4638 bool is_phys = false;
4641 const char *phys = Jim_GetString(argv[4], NULL);
4643 if (strcmp(phys, "phys")) {
4644 Jim_SetResultFormatted(interp, "invalid argument '%s', must be 'phys'", phys);
4651 switch (width_bits) {
4658 Jim_SetResultString(interp, "invalid width, must be 8, 16, 32 or 64", -1);
4662 const unsigned int width = width_bits / 8;
4664 if ((addr + (count * width)) < addr) {
4665 Jim_SetResultString(interp, "read_memory: addr + count wraps to zero", -1);
4669 if (count > 65536) {
4670 Jim_SetResultString(interp, "read_memory: too large read request, exeeds 64K elements", -1);
4674 struct command_context *cmd_ctx = current_command_context(interp);
4675 assert(cmd_ctx != NULL);
4676 struct target *target = get_current_target(cmd_ctx);
4678 const size_t buffersize = 4096;
4679 uint8_t *buffer = malloc(buffersize);
4682 LOG_ERROR("Failed to allocate memory");
4686 Jim_Obj *result_list = Jim_NewListObj(interp, NULL, 0);
4687 Jim_IncrRefCount(result_list);
4690 const unsigned int max_chunk_len = buffersize / width;
4691 const size_t chunk_len = MIN(count, max_chunk_len);
4696 retval = target_read_phys_memory(target, addr, width, chunk_len, buffer);
4698 retval = target_read_memory(target, addr, width, chunk_len, buffer);
4700 if (retval != ERROR_OK) {
4701 LOG_ERROR("read_memory: read at " TARGET_ADDR_FMT " with width=%u and count=%zu failed",
4702 addr, width_bits, chunk_len);
4703 Jim_SetResultString(interp, "read_memory: failed to read memory", -1);
4708 for (size_t i = 0; i < chunk_len ; i++) {
4713 v = target_buffer_get_u64(target, &buffer[i * width]);
4716 v = target_buffer_get_u32(target, &buffer[i * width]);
4719 v = target_buffer_get_u16(target, &buffer[i * width]);
4727 snprintf(value_buf, sizeof(value_buf), "0x%" PRIx64, v);
4729 Jim_ListAppendElement(interp, result_list,
4730 Jim_NewStringObj(interp, value_buf, -1));
4734 addr += chunk_len * width;
4740 Jim_DecrRefCount(interp, result_list);
4744 Jim_SetResult(interp, result_list);
4745 Jim_DecrRefCount(interp, result_list);
4750 static int get_u64_array_element(Jim_Interp *interp, const char *varname, size_t idx, uint64_t *val)
4752 char *namebuf = alloc_printf("%s(%zu)", varname, idx);
4756 Jim_Obj *obj_name = Jim_NewStringObj(interp, namebuf, -1);
4762 Jim_IncrRefCount(obj_name);
4763 Jim_Obj *obj_val = Jim_GetVariable(interp, obj_name, JIM_ERRMSG);
4764 Jim_DecrRefCount(interp, obj_name);
4770 int result = Jim_GetWide(interp, obj_val, &wide_val);
4775 static int target_array2mem(Jim_Interp *interp, struct target *target,
4776 int argc, Jim_Obj *const *argv)
4780 LOG_WARNING("DEPRECATED! use 'write_memory' not 'array2mem'");
4782 /* argv[0] = name of array from which to read the data
4783 * argv[1] = desired element width in bits
4784 * argv[2] = memory address
4785 * argv[3] = number of elements to write
4786 * argv[4] = optional "phys"
4788 if (argc < 4 || argc > 5) {
4789 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4793 /* Arg 0: Name of the array variable */
4794 const char *varname = Jim_GetString(argv[0], NULL);
4796 /* Arg 1: Bit width of one element */
4798 e = Jim_GetLong(interp, argv[1], &l);
4801 const unsigned int width_bits = l;
4803 if (width_bits != 8 &&
4807 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4808 Jim_AppendStrings(interp, Jim_GetResult(interp),
4809 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4812 const unsigned int width = width_bits / 8;
4814 /* Arg 2: Memory address */
4816 e = Jim_GetWide(interp, argv[2], &wide_addr);
4819 target_addr_t addr = (target_addr_t)wide_addr;
4821 /* Arg 3: Number of elements to write */
4822 e = Jim_GetLong(interp, argv[3], &l);
4828 bool is_phys = false;
4831 const char *phys = Jim_GetString(argv[4], &str_len);
4832 if (!strncmp(phys, "phys", str_len))
4838 /* Argument checks */
4840 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4841 Jim_AppendStrings(interp, Jim_GetResult(interp),
4842 "array2mem: zero width read?", NULL);
4846 if ((addr + (len * width)) < addr) {
4847 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4848 Jim_AppendStrings(interp, Jim_GetResult(interp),
4849 "array2mem: addr + len - wraps to zero?", NULL);
4854 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4855 Jim_AppendStrings(interp, Jim_GetResult(interp),
4856 "array2mem: too large memory write request, exceeds 64K items", NULL);
4861 ((width == 2) && ((addr & 1) == 0)) ||
4862 ((width == 4) && ((addr & 3) == 0)) ||
4863 ((width == 8) && ((addr & 7) == 0))) {
4864 /* alignment correct */
4867 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4868 sprintf(buf, "array2mem address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4871 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4880 const size_t buffersize = 4096;
4881 uint8_t *buffer = malloc(buffersize);
4889 /* Slurp... in buffer size chunks */
4890 const unsigned int max_chunk_len = buffersize / width;
4892 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4894 /* Fill the buffer */
4895 for (size_t i = 0; i < chunk_len; i++, idx++) {
4897 if (get_u64_array_element(interp, varname, idx, &v) != JIM_OK) {
4903 target_buffer_set_u64(target, &buffer[i * width], v);
4906 target_buffer_set_u32(target, &buffer[i * width], v);
4909 target_buffer_set_u16(target, &buffer[i * width], v);
4912 buffer[i] = v & 0x0ff;
4918 /* Write the buffer to memory */
4921 retval = target_write_phys_memory(target, addr, width, chunk_len, buffer);
4923 retval = target_write_memory(target, addr, width, chunk_len, buffer);
4924 if (retval != ERROR_OK) {
4926 LOG_ERROR("array2mem: Write @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4930 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4931 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4935 addr += chunk_len * width;
4940 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4945 static int target_jim_write_memory(Jim_Interp *interp, int argc,
4946 Jim_Obj * const *argv)
4949 * argv[1] = memory address
4950 * argv[2] = desired element width in bits
4951 * argv[3] = list of data to write
4952 * argv[4] = optional "phys"
4955 if (argc < 4 || argc > 5) {
4956 Jim_WrongNumArgs(interp, 1, argv, "address width data ['phys']");
4960 /* Arg 1: Memory address. */
4963 e = Jim_GetWide(interp, argv[1], &wide_addr);
4968 target_addr_t addr = (target_addr_t)wide_addr;
4970 /* Arg 2: Bit width of one element. */
4972 e = Jim_GetLong(interp, argv[2], &l);
4977 const unsigned int width_bits = l;
4978 size_t count = Jim_ListLength(interp, argv[3]);
4980 /* Arg 4: Optional 'phys'. */
4981 bool is_phys = false;
4984 const char *phys = Jim_GetString(argv[4], NULL);
4986 if (strcmp(phys, "phys")) {
4987 Jim_SetResultFormatted(interp, "invalid argument '%s', must be 'phys'", phys);
4994 switch (width_bits) {
5001 Jim_SetResultString(interp, "invalid width, must be 8, 16, 32 or 64", -1);
5005 const unsigned int width = width_bits / 8;
5007 if ((addr + (count * width)) < addr) {
5008 Jim_SetResultString(interp, "write_memory: addr + len wraps to zero", -1);
5012 if (count > 65536) {
5013 Jim_SetResultString(interp, "write_memory: too large memory write request, exceeds 64K elements", -1);
5017 struct command_context *cmd_ctx = current_command_context(interp);
5018 assert(cmd_ctx != NULL);
5019 struct target *target = get_current_target(cmd_ctx);
5021 const size_t buffersize = 4096;
5022 uint8_t *buffer = malloc(buffersize);
5025 LOG_ERROR("Failed to allocate memory");
5032 const unsigned int max_chunk_len = buffersize / width;
5033 const size_t chunk_len = MIN(count, max_chunk_len);
5035 for (size_t i = 0; i < chunk_len; i++, j++) {
5036 Jim_Obj *tmp = Jim_ListGetIndex(interp, argv[3], j);
5037 jim_wide element_wide;
5038 Jim_GetWide(interp, tmp, &element_wide);
5040 const uint64_t v = element_wide;
5044 target_buffer_set_u64(target, &buffer[i * width], v);
5047 target_buffer_set_u32(target, &buffer[i * width], v);
5050 target_buffer_set_u16(target, &buffer[i * width], v);
5053 buffer[i] = v & 0x0ff;
5063 retval = target_write_phys_memory(target, addr, width, chunk_len, buffer);
5065 retval = target_write_memory(target, addr, width, chunk_len, buffer);
5067 if (retval != ERROR_OK) {
5068 LOG_ERROR("write_memory: write at " TARGET_ADDR_FMT " with width=%u and count=%zu failed",
5069 addr, width_bits, chunk_len);
5070 Jim_SetResultString(interp, "write_memory: failed to write memory", -1);
5075 addr += chunk_len * width;
5083 /* FIX? should we propagate errors here rather than printing them
5086 void target_handle_event(struct target *target, enum target_event e)
5088 struct target_event_action *teap;
5091 for (teap = target->event_action; teap; teap = teap->next) {
5092 if (teap->event == e) {
5093 LOG_DEBUG("target(%d): %s (%s) event: %d (%s) action: %s",
5094 target->target_number,
5095 target_name(target),
5096 target_type_name(target),
5098 target_event_name(e),
5099 Jim_GetString(teap->body, NULL));
5101 /* Override current target by the target an event
5102 * is issued from (lot of scripts need it).
5103 * Return back to previous override as soon
5104 * as the handler processing is done */
5105 struct command_context *cmd_ctx = current_command_context(teap->interp);
5106 struct target *saved_target_override = cmd_ctx->current_target_override;
5107 cmd_ctx->current_target_override = target;
5109 retval = Jim_EvalObj(teap->interp, teap->body);
5111 cmd_ctx->current_target_override = saved_target_override;
5113 if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
5116 if (retval == JIM_RETURN)
5117 retval = teap->interp->returnCode;
5119 if (retval != JIM_OK) {
5120 Jim_MakeErrorMessage(teap->interp);
5121 LOG_USER("Error executing event %s on target %s:\n%s",
5122 target_event_name(e),
5123 target_name(target),
5124 Jim_GetString(Jim_GetResult(teap->interp), NULL));
5125 /* clean both error code and stacktrace before return */
5126 Jim_Eval(teap->interp, "error \"\" \"\"");
5132 static int target_jim_get_reg(Jim_Interp *interp, int argc,
5133 Jim_Obj * const *argv)
5138 const char *option = Jim_GetString(argv[1], NULL);
5140 if (!strcmp(option, "-force")) {
5145 Jim_SetResultFormatted(interp, "invalid option '%s'", option);
5151 Jim_WrongNumArgs(interp, 1, argv, "[-force] list");
5155 const int length = Jim_ListLength(interp, argv[1]);
5157 Jim_Obj *result_dict = Jim_NewDictObj(interp, NULL, 0);
5162 struct command_context *cmd_ctx = current_command_context(interp);
5163 assert(cmd_ctx != NULL);
5164 const struct target *target = get_current_target(cmd_ctx);
5166 for (int i = 0; i < length; i++) {
5167 Jim_Obj *elem = Jim_ListGetIndex(interp, argv[1], i);
5172 const char *reg_name = Jim_String(elem);
5174 struct reg *reg = register_get_by_name(target->reg_cache, reg_name,
5177 if (!reg || !reg->exist) {
5178 Jim_SetResultFormatted(interp, "unknown register '%s'", reg_name);
5183 int retval = reg->type->get(reg);
5185 if (retval != ERROR_OK) {
5186 Jim_SetResultFormatted(interp, "failed to read register '%s'",
5192 char *reg_value = buf_to_hex_str(reg->value, reg->size);
5195 LOG_ERROR("Failed to allocate memory");
5199 char *tmp = alloc_printf("0x%s", reg_value);
5204 LOG_ERROR("Failed to allocate memory");
5208 Jim_DictAddElement(interp, result_dict, elem,
5209 Jim_NewStringObj(interp, tmp, -1));
5214 Jim_SetResult(interp, result_dict);
5219 static int target_jim_set_reg(Jim_Interp *interp, int argc,
5220 Jim_Obj * const *argv)
5223 Jim_WrongNumArgs(interp, 1, argv, "dict");
5228 #if JIM_VERSION >= 80
5229 Jim_Obj **dict = Jim_DictPairs(interp, argv[1], &tmp);
5235 int ret = Jim_DictPairs(interp, argv[1], &dict, &tmp);
5241 const unsigned int length = tmp;
5242 struct command_context *cmd_ctx = current_command_context(interp);
5244 const struct target *target = get_current_target(cmd_ctx);
5246 for (unsigned int i = 0; i < length; i += 2) {
5247 const char *reg_name = Jim_String(dict[i]);
5248 const char *reg_value = Jim_String(dict[i + 1]);
5249 struct reg *reg = register_get_by_name(target->reg_cache, reg_name,
5252 if (!reg || !reg->exist) {
5253 Jim_SetResultFormatted(interp, "unknown register '%s'", reg_name);
5257 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
5260 LOG_ERROR("Failed to allocate memory");
5264 str_to_buf(reg_value, strlen(reg_value), buf, reg->size, 0);
5265 int retval = reg->type->set(reg, buf);
5268 if (retval != ERROR_OK) {
5269 Jim_SetResultFormatted(interp, "failed to set '%s' to register '%s'",
5270 reg_value, reg_name);
5279 * Returns true only if the target has a handler for the specified event.
5281 bool target_has_event_action(struct target *target, enum target_event event)
5283 struct target_event_action *teap;
5285 for (teap = target->event_action; teap; teap = teap->next) {
5286 if (teap->event == event)
5292 enum target_cfg_param {
5295 TCFG_WORK_AREA_VIRT,
5296 TCFG_WORK_AREA_PHYS,
5297 TCFG_WORK_AREA_SIZE,
5298 TCFG_WORK_AREA_BACKUP,
5301 TCFG_CHAIN_POSITION,
5306 TCFG_GDB_MAX_CONNECTIONS,
5309 static struct jim_nvp nvp_config_opts[] = {
5310 { .name = "-type", .value = TCFG_TYPE },
5311 { .name = "-event", .value = TCFG_EVENT },
5312 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
5313 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
5314 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
5315 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
5316 { .name = "-endian", .value = TCFG_ENDIAN },
5317 { .name = "-coreid", .value = TCFG_COREID },
5318 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
5319 { .name = "-dbgbase", .value = TCFG_DBGBASE },
5320 { .name = "-rtos", .value = TCFG_RTOS },
5321 { .name = "-defer-examine", .value = TCFG_DEFER_EXAMINE },
5322 { .name = "-gdb-port", .value = TCFG_GDB_PORT },
5323 { .name = "-gdb-max-connections", .value = TCFG_GDB_MAX_CONNECTIONS },
5324 { .name = NULL, .value = -1 }
5327 static int target_configure(struct jim_getopt_info *goi, struct target *target)
5334 /* parse config or cget options ... */
5335 while (goi->argc > 0) {
5336 Jim_SetEmptyResult(goi->interp);
5337 /* jim_getopt_debug(goi); */
5339 if (target->type->target_jim_configure) {
5340 /* target defines a configure function */
5341 /* target gets first dibs on parameters */
5342 e = (*(target->type->target_jim_configure))(target, goi);
5351 /* otherwise we 'continue' below */
5353 e = jim_getopt_nvp(goi, nvp_config_opts, &n);
5355 jim_getopt_nvp_unknown(goi, nvp_config_opts, 0);
5361 if (goi->isconfigure) {
5362 Jim_SetResultFormatted(goi->interp,
5363 "not settable: %s", n->name);
5367 if (goi->argc != 0) {
5368 Jim_WrongNumArgs(goi->interp,
5369 goi->argc, goi->argv,
5374 Jim_SetResultString(goi->interp,
5375 target_type_name(target), -1);
5379 if (goi->argc == 0) {
5380 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
5384 e = jim_getopt_nvp(goi, nvp_target_event, &n);
5386 jim_getopt_nvp_unknown(goi, nvp_target_event, 1);
5390 if (goi->isconfigure) {
5391 if (goi->argc != 1) {
5392 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
5396 if (goi->argc != 0) {
5397 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
5403 struct target_event_action *teap;
5405 teap = target->event_action;
5406 /* replace existing? */
5408 if (teap->event == (enum target_event)n->value)
5413 if (goi->isconfigure) {
5414 /* START_DEPRECATED_TPIU */
5415 if (n->value == TARGET_EVENT_TRACE_CONFIG)
5416 LOG_INFO("DEPRECATED target event %s; use TPIU events {pre,post}-{enable,disable}", n->name);
5417 /* END_DEPRECATED_TPIU */
5419 bool replace = true;
5422 teap = calloc(1, sizeof(*teap));
5425 teap->event = n->value;
5426 teap->interp = goi->interp;
5427 jim_getopt_obj(goi, &o);
5429 Jim_DecrRefCount(teap->interp, teap->body);
5430 teap->body = Jim_DuplicateObj(goi->interp, o);
5433 * Tcl/TK - "tk events" have a nice feature.
5434 * See the "BIND" command.
5435 * We should support that here.
5436 * You can specify %X and %Y in the event code.
5437 * The idea is: %T - target name.
5438 * The idea is: %N - target number
5439 * The idea is: %E - event name.
5441 Jim_IncrRefCount(teap->body);
5444 /* add to head of event list */
5445 teap->next = target->event_action;
5446 target->event_action = teap;
5448 Jim_SetEmptyResult(goi->interp);
5452 Jim_SetEmptyResult(goi->interp);
5454 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
5460 case TCFG_WORK_AREA_VIRT:
5461 if (goi->isconfigure) {
5462 target_free_all_working_areas(target);
5463 e = jim_getopt_wide(goi, &w);
5466 target->working_area_virt = w;
5467 target->working_area_virt_spec = true;
5472 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
5476 case TCFG_WORK_AREA_PHYS:
5477 if (goi->isconfigure) {
5478 target_free_all_working_areas(target);
5479 e = jim_getopt_wide(goi, &w);
5482 target->working_area_phys = w;
5483 target->working_area_phys_spec = true;
5488 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
5492 case TCFG_WORK_AREA_SIZE:
5493 if (goi->isconfigure) {
5494 target_free_all_working_areas(target);
5495 e = jim_getopt_wide(goi, &w);
5498 target->working_area_size = w;
5503 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
5507 case TCFG_WORK_AREA_BACKUP:
5508 if (goi->isconfigure) {
5509 target_free_all_working_areas(target);
5510 e = jim_getopt_wide(goi, &w);
5513 /* make this exactly 1 or 0 */
5514 target->backup_working_area = (!!w);
5519 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
5520 /* loop for more e*/
5525 if (goi->isconfigure) {
5526 e = jim_getopt_nvp(goi, nvp_target_endian, &n);
5528 jim_getopt_nvp_unknown(goi, nvp_target_endian, 1);
5531 target->endianness = n->value;
5536 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5538 target->endianness = TARGET_LITTLE_ENDIAN;
5539 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5541 Jim_SetResultString(goi->interp, n->name, -1);
5546 if (goi->isconfigure) {
5547 e = jim_getopt_wide(goi, &w);
5550 target->coreid = (int32_t)w;
5555 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->coreid));
5559 case TCFG_CHAIN_POSITION:
5560 if (goi->isconfigure) {
5562 struct jtag_tap *tap;
5564 if (target->has_dap) {
5565 Jim_SetResultString(goi->interp,
5566 "target requires -dap parameter instead of -chain-position!", -1);
5570 target_free_all_working_areas(target);
5571 e = jim_getopt_obj(goi, &o_t);
5574 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
5578 target->tap_configured = true;
5583 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
5584 /* loop for more e*/
5587 if (goi->isconfigure) {
5588 e = jim_getopt_wide(goi, &w);
5591 target->dbgbase = (uint32_t)w;
5592 target->dbgbase_set = true;
5597 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
5603 int result = rtos_create(goi, target);
5604 if (result != JIM_OK)
5610 case TCFG_DEFER_EXAMINE:
5612 target->defer_examine = true;
5617 if (goi->isconfigure) {
5618 struct command_context *cmd_ctx = current_command_context(goi->interp);
5619 if (cmd_ctx->mode != COMMAND_CONFIG) {
5620 Jim_SetResultString(goi->interp, "-gdb-port must be configured before 'init'", -1);
5625 e = jim_getopt_string(goi, &s, NULL);
5628 free(target->gdb_port_override);
5629 target->gdb_port_override = strdup(s);
5634 Jim_SetResultString(goi->interp, target->gdb_port_override ? target->gdb_port_override : "undefined", -1);
5638 case TCFG_GDB_MAX_CONNECTIONS:
5639 if (goi->isconfigure) {
5640 struct command_context *cmd_ctx = current_command_context(goi->interp);
5641 if (cmd_ctx->mode != COMMAND_CONFIG) {
5642 Jim_SetResultString(goi->interp, "-gdb-max-connections must be configured before 'init'", -1);
5646 e = jim_getopt_wide(goi, &w);
5649 target->gdb_max_connections = (w < 0) ? CONNECTION_LIMIT_UNLIMITED : (int)w;
5654 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->gdb_max_connections));
5657 } /* while (goi->argc) */
5660 /* done - we return */
5664 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5666 struct command *c = jim_to_command(interp);
5667 struct jim_getopt_info goi;
5669 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5670 goi.isconfigure = !strcmp(c->name, "configure");
5672 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5673 "missing: -option ...");
5676 struct command_context *cmd_ctx = current_command_context(interp);
5678 struct target *target = get_current_target(cmd_ctx);
5679 return target_configure(&goi, target);
5682 static int jim_target_mem2array(Jim_Interp *interp,
5683 int argc, Jim_Obj *const *argv)
5685 struct command_context *cmd_ctx = current_command_context(interp);
5687 struct target *target = get_current_target(cmd_ctx);
5688 return target_mem2array(interp, target, argc - 1, argv + 1);
5691 static int jim_target_array2mem(Jim_Interp *interp,
5692 int argc, Jim_Obj *const *argv)
5694 struct command_context *cmd_ctx = current_command_context(interp);
5696 struct target *target = get_current_target(cmd_ctx);
5697 return target_array2mem(interp, target, argc - 1, argv + 1);
5700 static int jim_target_tap_disabled(Jim_Interp *interp)
5702 Jim_SetResultFormatted(interp, "[TAP is disabled]");
5706 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5708 bool allow_defer = false;
5710 struct jim_getopt_info goi;
5711 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5713 const char *cmd_name = Jim_GetString(argv[0], NULL);
5714 Jim_SetResultFormatted(goi.interp,
5715 "usage: %s ['allow-defer']", cmd_name);
5719 strcmp(Jim_GetString(argv[1], NULL), "allow-defer") == 0) {
5722 int e = jim_getopt_obj(&goi, &obj);
5728 struct command_context *cmd_ctx = current_command_context(interp);
5730 struct target *target = get_current_target(cmd_ctx);
5731 if (!target->tap->enabled)
5732 return jim_target_tap_disabled(interp);
5734 if (allow_defer && target->defer_examine) {
5735 LOG_INFO("Deferring arp_examine of %s", target_name(target));
5736 LOG_INFO("Use arp_examine command to examine it manually!");
5740 int e = target->type->examine(target);
5741 if (e != ERROR_OK) {
5742 target_reset_examined(target);
5746 target_set_examined(target);
5751 static int jim_target_was_examined(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5753 struct command_context *cmd_ctx = current_command_context(interp);
5755 struct target *target = get_current_target(cmd_ctx);
5757 Jim_SetResultBool(interp, target_was_examined(target));
5761 static int jim_target_examine_deferred(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5763 struct command_context *cmd_ctx = current_command_context(interp);
5765 struct target *target = get_current_target(cmd_ctx);
5767 Jim_SetResultBool(interp, target->defer_examine);
5771 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5774 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5777 struct command_context *cmd_ctx = current_command_context(interp);
5779 struct target *target = get_current_target(cmd_ctx);
5781 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
5787 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5790 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5793 struct command_context *cmd_ctx = current_command_context(interp);
5795 struct target *target = get_current_target(cmd_ctx);
5796 if (!target->tap->enabled)
5797 return jim_target_tap_disabled(interp);
5800 if (!(target_was_examined(target)))
5801 e = ERROR_TARGET_NOT_EXAMINED;
5803 e = target->type->poll(target);
5809 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5811 struct jim_getopt_info goi;
5812 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5814 if (goi.argc != 2) {
5815 Jim_WrongNumArgs(interp, 0, argv,
5816 "([tT]|[fF]|assert|deassert) BOOL");
5821 int e = jim_getopt_nvp(&goi, nvp_assert, &n);
5823 jim_getopt_nvp_unknown(&goi, nvp_assert, 1);
5826 /* the halt or not param */
5828 e = jim_getopt_wide(&goi, &a);
5832 struct command_context *cmd_ctx = current_command_context(interp);
5834 struct target *target = get_current_target(cmd_ctx);
5835 if (!target->tap->enabled)
5836 return jim_target_tap_disabled(interp);
5838 if (!target->type->assert_reset || !target->type->deassert_reset) {
5839 Jim_SetResultFormatted(interp,
5840 "No target-specific reset for %s",
5841 target_name(target));
5845 if (target->defer_examine)
5846 target_reset_examined(target);
5848 /* determine if we should halt or not. */
5849 target->reset_halt = (a != 0);
5850 /* When this happens - all workareas are invalid. */
5851 target_free_all_working_areas_restore(target, 0);
5854 if (n->value == NVP_ASSERT)
5855 e = target->type->assert_reset(target);
5857 e = target->type->deassert_reset(target);
5858 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5861 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5864 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5867 struct command_context *cmd_ctx = current_command_context(interp);
5869 struct target *target = get_current_target(cmd_ctx);
5870 if (!target->tap->enabled)
5871 return jim_target_tap_disabled(interp);
5872 int e = target->type->halt(target);
5873 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5876 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5878 struct jim_getopt_info goi;
5879 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5881 /* params: <name> statename timeoutmsecs */
5882 if (goi.argc != 2) {
5883 const char *cmd_name = Jim_GetString(argv[0], NULL);
5884 Jim_SetResultFormatted(goi.interp,
5885 "%s <state_name> <timeout_in_msec>", cmd_name);
5890 int e = jim_getopt_nvp(&goi, nvp_target_state, &n);
5892 jim_getopt_nvp_unknown(&goi, nvp_target_state, 1);
5896 e = jim_getopt_wide(&goi, &a);
5899 struct command_context *cmd_ctx = current_command_context(interp);
5901 struct target *target = get_current_target(cmd_ctx);
5902 if (!target->tap->enabled)
5903 return jim_target_tap_disabled(interp);
5905 e = target_wait_state(target, n->value, a);
5906 if (e != ERROR_OK) {
5907 Jim_Obj *obj = Jim_NewIntObj(interp, e);
5908 Jim_SetResultFormatted(goi.interp,
5909 "target: %s wait %s fails (%#s) %s",
5910 target_name(target), n->name,
5911 obj, target_strerror_safe(e));
5916 /* List for human, Events defined for this target.
5917 * scripts/programs should use 'name cget -event NAME'
5919 COMMAND_HANDLER(handle_target_event_list)
5921 struct target *target = get_current_target(CMD_CTX);
5922 struct target_event_action *teap = target->event_action;
5924 command_print(CMD, "Event actions for target (%d) %s\n",
5925 target->target_number,
5926 target_name(target));
5927 command_print(CMD, "%-25s | Body", "Event");
5928 command_print(CMD, "------------------------- | "
5929 "----------------------------------------");
5931 command_print(CMD, "%-25s | %s",
5932 target_event_name(teap->event),
5933 Jim_GetString(teap->body, NULL));
5936 command_print(CMD, "***END***");
5939 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5942 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5945 struct command_context *cmd_ctx = current_command_context(interp);
5947 struct target *target = get_current_target(cmd_ctx);
5948 Jim_SetResultString(interp, target_state_name(target), -1);
5951 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5953 struct jim_getopt_info goi;
5954 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5955 if (goi.argc != 1) {
5956 const char *cmd_name = Jim_GetString(argv[0], NULL);
5957 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5961 int e = jim_getopt_nvp(&goi, nvp_target_event, &n);
5963 jim_getopt_nvp_unknown(&goi, nvp_target_event, 1);
5966 struct command_context *cmd_ctx = current_command_context(interp);
5968 struct target *target = get_current_target(cmd_ctx);
5969 target_handle_event(target, n->value);
5973 static const struct command_registration target_instance_command_handlers[] = {
5975 .name = "configure",
5976 .mode = COMMAND_ANY,
5977 .jim_handler = jim_target_configure,
5978 .help = "configure a new target for use",
5979 .usage = "[target_attribute ...]",
5983 .mode = COMMAND_ANY,
5984 .jim_handler = jim_target_configure,
5985 .help = "returns the specified target attribute",
5986 .usage = "target_attribute",
5990 .handler = handle_mw_command,
5991 .mode = COMMAND_EXEC,
5992 .help = "Write 64-bit word(s) to target memory",
5993 .usage = "address data [count]",
5997 .handler = handle_mw_command,
5998 .mode = COMMAND_EXEC,
5999 .help = "Write 32-bit word(s) to target memory",
6000 .usage = "address data [count]",
6004 .handler = handle_mw_command,
6005 .mode = COMMAND_EXEC,
6006 .help = "Write 16-bit half-word(s) to target memory",
6007 .usage = "address data [count]",
6011 .handler = handle_mw_command,
6012 .mode = COMMAND_EXEC,
6013 .help = "Write byte(s) to target memory",
6014 .usage = "address data [count]",
6018 .handler = handle_md_command,
6019 .mode = COMMAND_EXEC,
6020 .help = "Display target memory as 64-bit words",
6021 .usage = "address [count]",
6025 .handler = handle_md_command,
6026 .mode = COMMAND_EXEC,
6027 .help = "Display target memory as 32-bit words",
6028 .usage = "address [count]",
6032 .handler = handle_md_command,
6033 .mode = COMMAND_EXEC,
6034 .help = "Display target memory as 16-bit half-words",
6035 .usage = "address [count]",
6039 .handler = handle_md_command,
6040 .mode = COMMAND_EXEC,
6041 .help = "Display target memory as 8-bit bytes",
6042 .usage = "address [count]",
6045 .name = "array2mem",
6046 .mode = COMMAND_EXEC,
6047 .jim_handler = jim_target_array2mem,
6048 .help = "Writes Tcl array of 8/16/32 bit numbers "
6050 .usage = "arrayname bitwidth address count",
6053 .name = "mem2array",
6054 .mode = COMMAND_EXEC,
6055 .jim_handler = jim_target_mem2array,
6056 .help = "Loads Tcl array of 8/16/32 bit numbers "
6057 "from target memory",
6058 .usage = "arrayname bitwidth address count",
6062 .mode = COMMAND_EXEC,
6063 .jim_handler = target_jim_get_reg,
6064 .help = "Get register values from the target",
6069 .mode = COMMAND_EXEC,
6070 .jim_handler = target_jim_set_reg,
6071 .help = "Set target register values",
6075 .name = "read_memory",
6076 .mode = COMMAND_EXEC,
6077 .jim_handler = target_jim_read_memory,
6078 .help = "Read Tcl list of 8/16/32/64 bit numbers from target memory",
6079 .usage = "address width count ['phys']",
6082 .name = "write_memory",
6083 .mode = COMMAND_EXEC,
6084 .jim_handler = target_jim_write_memory,
6085 .help = "Write Tcl list of 8/16/32/64 bit numbers to target memory",
6086 .usage = "address width data ['phys']",
6089 .name = "eventlist",
6090 .handler = handle_target_event_list,
6091 .mode = COMMAND_EXEC,
6092 .help = "displays a table of events defined for this target",
6097 .mode = COMMAND_EXEC,
6098 .jim_handler = jim_target_current_state,
6099 .help = "displays the current state of this target",
6102 .name = "arp_examine",
6103 .mode = COMMAND_EXEC,
6104 .jim_handler = jim_target_examine,
6105 .help = "used internally for reset processing",
6106 .usage = "['allow-defer']",
6109 .name = "was_examined",
6110 .mode = COMMAND_EXEC,
6111 .jim_handler = jim_target_was_examined,
6112 .help = "used internally for reset processing",
6115 .name = "examine_deferred",
6116 .mode = COMMAND_EXEC,
6117 .jim_handler = jim_target_examine_deferred,
6118 .help = "used internally for reset processing",
6121 .name = "arp_halt_gdb",
6122 .mode = COMMAND_EXEC,
6123 .jim_handler = jim_target_halt_gdb,
6124 .help = "used internally for reset processing to halt GDB",
6128 .mode = COMMAND_EXEC,
6129 .jim_handler = jim_target_poll,
6130 .help = "used internally for reset processing",
6133 .name = "arp_reset",
6134 .mode = COMMAND_EXEC,
6135 .jim_handler = jim_target_reset,
6136 .help = "used internally for reset processing",
6140 .mode = COMMAND_EXEC,
6141 .jim_handler = jim_target_halt,
6142 .help = "used internally for reset processing",
6145 .name = "arp_waitstate",
6146 .mode = COMMAND_EXEC,
6147 .jim_handler = jim_target_wait_state,
6148 .help = "used internally for reset processing",
6151 .name = "invoke-event",
6152 .mode = COMMAND_EXEC,
6153 .jim_handler = jim_target_invoke_event,
6154 .help = "invoke handler for specified event",
6155 .usage = "event_name",
6157 COMMAND_REGISTRATION_DONE
6160 static int target_create(struct jim_getopt_info *goi)
6167 struct target *target;
6168 struct command_context *cmd_ctx;
6170 cmd_ctx = current_command_context(goi->interp);
6173 if (goi->argc < 3) {
6174 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
6179 jim_getopt_obj(goi, &new_cmd);
6180 /* does this command exist? */
6181 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_NONE);
6183 cp = Jim_GetString(new_cmd, NULL);
6184 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
6189 e = jim_getopt_string(goi, &cp, NULL);
6192 struct transport *tr = get_current_transport();
6193 if (tr->override_target) {
6194 e = tr->override_target(&cp);
6195 if (e != ERROR_OK) {
6196 LOG_ERROR("The selected transport doesn't support this target");
6199 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
6201 /* now does target type exist */
6202 for (x = 0 ; target_types[x] ; x++) {
6203 if (strcmp(cp, target_types[x]->name) == 0) {
6208 if (!target_types[x]) {
6209 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
6210 for (x = 0 ; target_types[x] ; x++) {
6211 if (target_types[x + 1]) {
6212 Jim_AppendStrings(goi->interp,
6213 Jim_GetResult(goi->interp),
6214 target_types[x]->name,
6217 Jim_AppendStrings(goi->interp,
6218 Jim_GetResult(goi->interp),
6220 target_types[x]->name, NULL);
6227 target = calloc(1, sizeof(struct target));
6229 LOG_ERROR("Out of memory");
6233 /* set empty smp cluster */
6234 target->smp_targets = &empty_smp_targets;
6236 /* set target number */
6237 target->target_number = new_target_number();
6239 /* allocate memory for each unique target type */
6240 target->type = malloc(sizeof(struct target_type));
6241 if (!target->type) {
6242 LOG_ERROR("Out of memory");
6247 memcpy(target->type, target_types[x], sizeof(struct target_type));
6249 /* default to first core, override with -coreid */
6252 target->working_area = 0x0;
6253 target->working_area_size = 0x0;
6254 target->working_areas = NULL;
6255 target->backup_working_area = 0;
6257 target->state = TARGET_UNKNOWN;
6258 target->debug_reason = DBG_REASON_UNDEFINED;
6259 target->reg_cache = NULL;
6260 target->breakpoints = NULL;
6261 target->watchpoints = NULL;
6262 target->next = NULL;
6263 target->arch_info = NULL;
6265 target->verbose_halt_msg = true;
6267 target->halt_issued = false;
6269 /* initialize trace information */
6270 target->trace_info = calloc(1, sizeof(struct trace));
6271 if (!target->trace_info) {
6272 LOG_ERROR("Out of memory");
6278 target->dbgmsg = NULL;
6279 target->dbg_msg_enabled = 0;
6281 target->endianness = TARGET_ENDIAN_UNKNOWN;
6283 target->rtos = NULL;
6284 target->rtos_auto_detect = false;
6286 target->gdb_port_override = NULL;
6287 target->gdb_max_connections = 1;
6289 /* Do the rest as "configure" options */
6290 goi->isconfigure = 1;
6291 e = target_configure(goi, target);
6294 if (target->has_dap) {
6295 if (!target->dap_configured) {
6296 Jim_SetResultString(goi->interp, "-dap ?name? required when creating target", -1);
6300 if (!target->tap_configured) {
6301 Jim_SetResultString(goi->interp, "-chain-position ?name? required when creating target", -1);
6305 /* tap must be set after target was configured */
6311 rtos_destroy(target);
6312 free(target->gdb_port_override);
6313 free(target->trace_info);
6319 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
6320 /* default endian to little if not specified */
6321 target->endianness = TARGET_LITTLE_ENDIAN;
6324 cp = Jim_GetString(new_cmd, NULL);
6325 target->cmd_name = strdup(cp);
6326 if (!target->cmd_name) {
6327 LOG_ERROR("Out of memory");
6328 rtos_destroy(target);
6329 free(target->gdb_port_override);
6330 free(target->trace_info);
6336 if (target->type->target_create) {
6337 e = (*(target->type->target_create))(target, goi->interp);
6338 if (e != ERROR_OK) {
6339 LOG_DEBUG("target_create failed");
6340 free(target->cmd_name);
6341 rtos_destroy(target);
6342 free(target->gdb_port_override);
6343 free(target->trace_info);
6350 /* create the target specific commands */
6351 if (target->type->commands) {
6352 e = register_commands(cmd_ctx, NULL, target->type->commands);
6354 LOG_ERROR("unable to register '%s' commands", cp);
6357 /* now - create the new target name command */
6358 const struct command_registration target_subcommands[] = {
6360 .chain = target_instance_command_handlers,
6363 .chain = target->type->commands,
6365 COMMAND_REGISTRATION_DONE
6367 const struct command_registration target_commands[] = {
6370 .mode = COMMAND_ANY,
6371 .help = "target command group",
6373 .chain = target_subcommands,
6375 COMMAND_REGISTRATION_DONE
6377 e = register_commands_override_target(cmd_ctx, NULL, target_commands, target);
6378 if (e != ERROR_OK) {
6379 if (target->type->deinit_target)
6380 target->type->deinit_target(target);
6381 free(target->cmd_name);
6382 rtos_destroy(target);
6383 free(target->gdb_port_override);
6384 free(target->trace_info);
6390 /* append to end of list */
6391 append_to_list_all_targets(target);
6393 cmd_ctx->current_target = target;
6397 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6400 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
6403 struct command_context *cmd_ctx = current_command_context(interp);
6406 struct target *target = get_current_target_or_null(cmd_ctx);
6408 Jim_SetResultString(interp, target_name(target), -1);
6412 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6415 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
6418 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
6419 for (unsigned x = 0; target_types[x]; x++) {
6420 Jim_ListAppendElement(interp, Jim_GetResult(interp),
6421 Jim_NewStringObj(interp, target_types[x]->name, -1));
6426 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6429 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
6432 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
6433 struct target *target = all_targets;
6435 Jim_ListAppendElement(interp, Jim_GetResult(interp),
6436 Jim_NewStringObj(interp, target_name(target), -1));
6437 target = target->next;
6442 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6445 const char *targetname;
6447 static int smp_group = 1;
6448 struct target *target = NULL;
6449 struct target_list *head, *new;
6452 LOG_DEBUG("%d", argc);
6453 /* argv[1] = target to associate in smp
6454 * argv[2] = target to associate in smp
6458 struct list_head *lh = malloc(sizeof(*lh));
6460 LOG_ERROR("Out of memory");
6465 for (i = 1; i < argc; i++) {
6467 targetname = Jim_GetString(argv[i], &len);
6468 target = get_target(targetname);
6469 LOG_DEBUG("%s ", targetname);
6471 new = malloc(sizeof(struct target_list));
6472 new->target = target;
6473 list_add_tail(&new->lh, lh);
6476 /* now parse the list of cpu and put the target in smp mode*/
6477 foreach_smp_target(head, lh) {
6478 target = head->target;
6479 target->smp = smp_group;
6480 target->smp_targets = lh;
6484 if (target && target->rtos)
6485 retval = rtos_smp_init(target);
6491 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6493 struct jim_getopt_info goi;
6494 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
6496 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
6497 "<name> <target_type> [<target_options> ...]");
6500 return target_create(&goi);
6503 static const struct command_registration target_subcommand_handlers[] = {
6506 .mode = COMMAND_CONFIG,
6507 .handler = handle_target_init_command,
6508 .help = "initialize targets",
6513 .mode = COMMAND_CONFIG,
6514 .jim_handler = jim_target_create,
6515 .usage = "name type '-chain-position' name [options ...]",
6516 .help = "Creates and selects a new target",
6520 .mode = COMMAND_ANY,
6521 .jim_handler = jim_target_current,
6522 .help = "Returns the currently selected target",
6526 .mode = COMMAND_ANY,
6527 .jim_handler = jim_target_types,
6528 .help = "Returns the available target types as "
6529 "a list of strings",
6533 .mode = COMMAND_ANY,
6534 .jim_handler = jim_target_names,
6535 .help = "Returns the names of all targets as a list of strings",
6539 .mode = COMMAND_ANY,
6540 .jim_handler = jim_target_smp,
6541 .usage = "targetname1 targetname2 ...",
6542 .help = "gather several target in a smp list"
6545 COMMAND_REGISTRATION_DONE
6549 target_addr_t address;
6555 static int fastload_num;
6556 static struct fast_load *fastload;
6558 static void free_fastload(void)
6561 for (int i = 0; i < fastload_num; i++)
6562 free(fastload[i].data);
6568 COMMAND_HANDLER(handle_fast_load_image_command)
6572 uint32_t image_size;
6573 target_addr_t min_address = 0;
6574 target_addr_t max_address = -1;
6578 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
6579 &image, &min_address, &max_address);
6580 if (retval != ERROR_OK)
6583 struct duration bench;
6584 duration_start(&bench);
6586 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
6587 if (retval != ERROR_OK)
6592 fastload_num = image.num_sections;
6593 fastload = malloc(sizeof(struct fast_load)*image.num_sections);
6595 command_print(CMD, "out of memory");
6596 image_close(&image);
6599 memset(fastload, 0, sizeof(struct fast_load)*image.num_sections);
6600 for (unsigned int i = 0; i < image.num_sections; i++) {
6601 buffer = malloc(image.sections[i].size);
6603 command_print(CMD, "error allocating buffer for section (%d bytes)",
6604 (int)(image.sections[i].size));
6605 retval = ERROR_FAIL;
6609 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
6610 if (retval != ERROR_OK) {
6615 uint32_t offset = 0;
6616 uint32_t length = buf_cnt;
6618 /* DANGER!!! beware of unsigned comparison here!!! */
6620 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
6621 (image.sections[i].base_address < max_address)) {
6622 if (image.sections[i].base_address < min_address) {
6623 /* clip addresses below */
6624 offset += min_address-image.sections[i].base_address;
6628 if (image.sections[i].base_address + buf_cnt > max_address)
6629 length -= (image.sections[i].base_address + buf_cnt)-max_address;
6631 fastload[i].address = image.sections[i].base_address + offset;
6632 fastload[i].data = malloc(length);
6633 if (!fastload[i].data) {
6635 command_print(CMD, "error allocating buffer for section (%" PRIu32 " bytes)",
6637 retval = ERROR_FAIL;
6640 memcpy(fastload[i].data, buffer + offset, length);
6641 fastload[i].length = length;
6643 image_size += length;
6644 command_print(CMD, "%u bytes written at address 0x%8.8x",
6645 (unsigned int)length,
6646 ((unsigned int)(image.sections[i].base_address + offset)));
6652 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
6653 command_print(CMD, "Loaded %" PRIu32 " bytes "
6654 "in %fs (%0.3f KiB/s)", image_size,
6655 duration_elapsed(&bench), duration_kbps(&bench, image_size));
6658 "WARNING: image has not been loaded to target!"
6659 "You can issue a 'fast_load' to finish loading.");
6662 image_close(&image);
6664 if (retval != ERROR_OK)
6670 COMMAND_HANDLER(handle_fast_load_command)
6673 return ERROR_COMMAND_SYNTAX_ERROR;
6675 LOG_ERROR("No image in memory");
6679 int64_t ms = timeval_ms();
6681 int retval = ERROR_OK;
6682 for (i = 0; i < fastload_num; i++) {
6683 struct target *target = get_current_target(CMD_CTX);
6684 command_print(CMD, "Write to 0x%08x, length 0x%08x",
6685 (unsigned int)(fastload[i].address),
6686 (unsigned int)(fastload[i].length));
6687 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
6688 if (retval != ERROR_OK)
6690 size += fastload[i].length;
6692 if (retval == ERROR_OK) {
6693 int64_t after = timeval_ms();
6694 command_print(CMD, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
6699 static const struct command_registration target_command_handlers[] = {
6702 .handler = handle_targets_command,
6703 .mode = COMMAND_ANY,
6704 .help = "change current default target (one parameter) "
6705 "or prints table of all targets (no parameters)",
6706 .usage = "[target]",
6710 .mode = COMMAND_CONFIG,
6711 .help = "configure target",
6712 .chain = target_subcommand_handlers,
6715 COMMAND_REGISTRATION_DONE
6718 int target_register_commands(struct command_context *cmd_ctx)
6720 return register_commands(cmd_ctx, NULL, target_command_handlers);
6723 static bool target_reset_nag = true;
6725 bool get_target_reset_nag(void)
6727 return target_reset_nag;
6730 COMMAND_HANDLER(handle_target_reset_nag)
6732 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
6733 &target_reset_nag, "Nag after each reset about options to improve "
6737 COMMAND_HANDLER(handle_ps_command)
6739 struct target *target = get_current_target(CMD_CTX);
6741 if (target->state != TARGET_HALTED) {
6742 LOG_INFO("target not halted !!");
6746 if ((target->rtos) && (target->rtos->type)
6747 && (target->rtos->type->ps_command)) {
6748 display = target->rtos->type->ps_command(target);
6749 command_print(CMD, "%s", display);
6754 return ERROR_TARGET_FAILURE;
6758 static void binprint(struct command_invocation *cmd, const char *text, const uint8_t *buf, int size)
6761 command_print_sameline(cmd, "%s", text);
6762 for (int i = 0; i < size; i++)
6763 command_print_sameline(cmd, " %02x", buf[i]);
6764 command_print(cmd, " ");
6767 COMMAND_HANDLER(handle_test_mem_access_command)
6769 struct target *target = get_current_target(CMD_CTX);
6771 int retval = ERROR_OK;
6773 if (target->state != TARGET_HALTED) {
6774 LOG_INFO("target not halted !!");
6779 return ERROR_COMMAND_SYNTAX_ERROR;
6781 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
6784 size_t num_bytes = test_size + 4;
6786 struct working_area *wa = NULL;
6787 retval = target_alloc_working_area(target, num_bytes, &wa);
6788 if (retval != ERROR_OK) {
6789 LOG_ERROR("Not enough working area");
6793 uint8_t *test_pattern = malloc(num_bytes);
6795 for (size_t i = 0; i < num_bytes; i++)
6796 test_pattern[i] = rand();
6798 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6799 if (retval != ERROR_OK) {
6800 LOG_ERROR("Test pattern write failed");
6804 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6805 for (int size = 1; size <= 4; size *= 2) {
6806 for (int offset = 0; offset < 4; offset++) {
6807 uint32_t count = test_size / size;
6808 size_t host_bufsiz = (count + 2) * size + host_offset;
6809 uint8_t *read_ref = malloc(host_bufsiz);
6810 uint8_t *read_buf = malloc(host_bufsiz);
6812 for (size_t i = 0; i < host_bufsiz; i++) {
6813 read_ref[i] = rand();
6814 read_buf[i] = read_ref[i];
6816 command_print_sameline(CMD,
6817 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
6818 size, offset, host_offset ? "un" : "");
6820 struct duration bench;
6821 duration_start(&bench);
6823 retval = target_read_memory(target, wa->address + offset, size, count,
6824 read_buf + size + host_offset);
6826 duration_measure(&bench);
6828 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6829 command_print(CMD, "Unsupported alignment");
6831 } else if (retval != ERROR_OK) {
6832 command_print(CMD, "Memory read failed");
6836 /* replay on host */
6837 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
6840 int result = memcmp(read_ref, read_buf, host_bufsiz);
6842 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6843 duration_elapsed(&bench),
6844 duration_kbps(&bench, count * size));
6846 command_print(CMD, "Compare failed");
6847 binprint(CMD, "ref:", read_ref, host_bufsiz);
6848 binprint(CMD, "buf:", read_buf, host_bufsiz);
6860 target_free_working_area(target, wa);
6863 num_bytes = test_size + 4 + 4 + 4;
6865 retval = target_alloc_working_area(target, num_bytes, &wa);
6866 if (retval != ERROR_OK) {
6867 LOG_ERROR("Not enough working area");
6871 test_pattern = malloc(num_bytes);
6873 for (size_t i = 0; i < num_bytes; i++)
6874 test_pattern[i] = rand();
6876 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6877 for (int size = 1; size <= 4; size *= 2) {
6878 for (int offset = 0; offset < 4; offset++) {
6879 uint32_t count = test_size / size;
6880 size_t host_bufsiz = count * size + host_offset;
6881 uint8_t *read_ref = malloc(num_bytes);
6882 uint8_t *read_buf = malloc(num_bytes);
6883 uint8_t *write_buf = malloc(host_bufsiz);
6885 for (size_t i = 0; i < host_bufsiz; i++)
6886 write_buf[i] = rand();
6887 command_print_sameline(CMD,
6888 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
6889 size, offset, host_offset ? "un" : "");
6891 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6892 if (retval != ERROR_OK) {
6893 command_print(CMD, "Test pattern write failed");
6897 /* replay on host */
6898 memcpy(read_ref, test_pattern, num_bytes);
6899 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
6901 struct duration bench;
6902 duration_start(&bench);
6904 retval = target_write_memory(target, wa->address + size + offset, size, count,
6905 write_buf + host_offset);
6907 duration_measure(&bench);
6909 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6910 command_print(CMD, "Unsupported alignment");
6912 } else if (retval != ERROR_OK) {
6913 command_print(CMD, "Memory write failed");
6918 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
6919 if (retval != ERROR_OK) {
6920 command_print(CMD, "Test pattern write failed");
6925 int result = memcmp(read_ref, read_buf, num_bytes);
6927 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6928 duration_elapsed(&bench),
6929 duration_kbps(&bench, count * size));
6931 command_print(CMD, "Compare failed");
6932 binprint(CMD, "ref:", read_ref, num_bytes);
6933 binprint(CMD, "buf:", read_buf, num_bytes);
6944 target_free_working_area(target, wa);
6948 static const struct command_registration target_exec_command_handlers[] = {
6950 .name = "fast_load_image",
6951 .handler = handle_fast_load_image_command,
6952 .mode = COMMAND_ANY,
6953 .help = "Load image into server memory for later use by "
6954 "fast_load; primarily for profiling",
6955 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6956 "[min_address [max_length]]",
6959 .name = "fast_load",
6960 .handler = handle_fast_load_command,
6961 .mode = COMMAND_EXEC,
6962 .help = "loads active fast load image to current target "
6963 "- mainly for profiling purposes",
6968 .handler = handle_profile_command,
6969 .mode = COMMAND_EXEC,
6970 .usage = "seconds filename [start end]",
6971 .help = "profiling samples the CPU PC",
6973 /** @todo don't register virt2phys() unless target supports it */
6975 .name = "virt2phys",
6976 .handler = handle_virt2phys_command,
6977 .mode = COMMAND_ANY,
6978 .help = "translate a virtual address into a physical address",
6979 .usage = "virtual_address",
6983 .handler = handle_reg_command,
6984 .mode = COMMAND_EXEC,
6985 .help = "display (reread from target with \"force\") or set a register; "
6986 "with no arguments, displays all registers and their values",
6987 .usage = "[(register_number|register_name) [(value|'force')]]",
6991 .handler = handle_poll_command,
6992 .mode = COMMAND_EXEC,
6993 .help = "poll target state; or reconfigure background polling",
6994 .usage = "['on'|'off']",
6997 .name = "wait_halt",
6998 .handler = handle_wait_halt_command,
6999 .mode = COMMAND_EXEC,
7000 .help = "wait up to the specified number of milliseconds "
7001 "(default 5000) for a previously requested halt",
7002 .usage = "[milliseconds]",
7006 .handler = handle_halt_command,
7007 .mode = COMMAND_EXEC,
7008 .help = "request target to halt, then wait up to the specified "
7009 "number of milliseconds (default 5000) for it to complete",
7010 .usage = "[milliseconds]",
7014 .handler = handle_resume_command,
7015 .mode = COMMAND_EXEC,
7016 .help = "resume target execution from current PC or address",
7017 .usage = "[address]",
7021 .handler = handle_reset_command,
7022 .mode = COMMAND_EXEC,
7023 .usage = "[run|halt|init]",
7024 .help = "Reset all targets into the specified mode. "
7025 "Default reset mode is run, if not given.",
7028 .name = "soft_reset_halt",
7029 .handler = handle_soft_reset_halt_command,
7030 .mode = COMMAND_EXEC,
7032 .help = "halt the target and do a soft reset",
7036 .handler = handle_step_command,
7037 .mode = COMMAND_EXEC,
7038 .help = "step one instruction from current PC or address",
7039 .usage = "[address]",
7043 .handler = handle_md_command,
7044 .mode = COMMAND_EXEC,
7045 .help = "display memory double-words",
7046 .usage = "['phys'] address [count]",
7050 .handler = handle_md_command,
7051 .mode = COMMAND_EXEC,
7052 .help = "display memory words",
7053 .usage = "['phys'] address [count]",
7057 .handler = handle_md_command,
7058 .mode = COMMAND_EXEC,
7059 .help = "display memory half-words",
7060 .usage = "['phys'] address [count]",
7064 .handler = handle_md_command,
7065 .mode = COMMAND_EXEC,
7066 .help = "display memory bytes",
7067 .usage = "['phys'] address [count]",
7071 .handler = handle_mw_command,
7072 .mode = COMMAND_EXEC,
7073 .help = "write memory double-word",
7074 .usage = "['phys'] address value [count]",
7078 .handler = handle_mw_command,
7079 .mode = COMMAND_EXEC,
7080 .help = "write memory word",
7081 .usage = "['phys'] address value [count]",
7085 .handler = handle_mw_command,
7086 .mode = COMMAND_EXEC,
7087 .help = "write memory half-word",
7088 .usage = "['phys'] address value [count]",
7092 .handler = handle_mw_command,
7093 .mode = COMMAND_EXEC,
7094 .help = "write memory byte",
7095 .usage = "['phys'] address value [count]",
7099 .handler = handle_bp_command,
7100 .mode = COMMAND_EXEC,
7101 .help = "list or set hardware or software breakpoint",
7102 .usage = "[<address> [<asid>] <length> ['hw'|'hw_ctx']]",
7106 .handler = handle_rbp_command,
7107 .mode = COMMAND_EXEC,
7108 .help = "remove breakpoint",
7109 .usage = "'all' | address",
7113 .handler = handle_wp_command,
7114 .mode = COMMAND_EXEC,
7115 .help = "list (no params) or create watchpoints",
7116 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
7120 .handler = handle_rwp_command,
7121 .mode = COMMAND_EXEC,
7122 .help = "remove watchpoint",
7126 .name = "load_image",
7127 .handler = handle_load_image_command,
7128 .mode = COMMAND_EXEC,
7129 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
7130 "[min_address] [max_length]",
7133 .name = "dump_image",
7134 .handler = handle_dump_image_command,
7135 .mode = COMMAND_EXEC,
7136 .usage = "filename address size",
7139 .name = "verify_image_checksum",
7140 .handler = handle_verify_image_checksum_command,
7141 .mode = COMMAND_EXEC,
7142 .usage = "filename [offset [type]]",
7145 .name = "verify_image",
7146 .handler = handle_verify_image_command,
7147 .mode = COMMAND_EXEC,
7148 .usage = "filename [offset [type]]",
7151 .name = "test_image",
7152 .handler = handle_test_image_command,
7153 .mode = COMMAND_EXEC,
7154 .usage = "filename [offset [type]]",
7158 .mode = COMMAND_EXEC,
7159 .jim_handler = target_jim_get_reg,
7160 .help = "Get register values from the target",
7165 .mode = COMMAND_EXEC,
7166 .jim_handler = target_jim_set_reg,
7167 .help = "Set target register values",
7171 .name = "read_memory",
7172 .mode = COMMAND_EXEC,
7173 .jim_handler = target_jim_read_memory,
7174 .help = "Read Tcl list of 8/16/32/64 bit numbers from target memory",
7175 .usage = "address width count ['phys']",
7178 .name = "write_memory",
7179 .mode = COMMAND_EXEC,
7180 .jim_handler = target_jim_write_memory,
7181 .help = "Write Tcl list of 8/16/32/64 bit numbers to target memory",
7182 .usage = "address width data ['phys']",
7185 .name = "reset_nag",
7186 .handler = handle_target_reset_nag,
7187 .mode = COMMAND_ANY,
7188 .help = "Nag after each reset about options that could have been "
7189 "enabled to improve performance.",
7190 .usage = "['enable'|'disable']",
7194 .handler = handle_ps_command,
7195 .mode = COMMAND_EXEC,
7196 .help = "list all tasks",
7200 .name = "test_mem_access",
7201 .handler = handle_test_mem_access_command,
7202 .mode = COMMAND_EXEC,
7203 .help = "Test the target's memory access functions",
7207 COMMAND_REGISTRATION_DONE
7209 static int target_register_user_commands(struct command_context *cmd_ctx)
7211 int retval = ERROR_OK;
7212 retval = target_request_register_commands(cmd_ctx);
7213 if (retval != ERROR_OK)
7216 retval = trace_register_commands(cmd_ctx);
7217 if (retval != ERROR_OK)
7221 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);