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"
61 /* default halt wait timeout (ms) */
62 #define DEFAULT_HALT_TIMEOUT 5000
64 static int target_read_buffer_default(struct target *target, target_addr_t address,
65 uint32_t count, uint8_t *buffer);
66 static int target_write_buffer_default(struct target *target, target_addr_t address,
67 uint32_t count, const uint8_t *buffer);
68 static int target_array2mem(Jim_Interp *interp, struct target *target,
69 int argc, Jim_Obj * const *argv);
70 static int target_mem2array(Jim_Interp *interp, struct target *target,
71 int argc, Jim_Obj * const *argv);
72 static int target_register_user_commands(struct command_context *cmd_ctx);
73 static int target_get_gdb_fileio_info_default(struct target *target,
74 struct gdb_fileio_info *fileio_info);
75 static int target_gdb_fileio_end_default(struct target *target, int retcode,
76 int fileio_errno, bool ctrl_c);
79 extern struct target_type arm7tdmi_target;
80 extern struct target_type arm720t_target;
81 extern struct target_type arm9tdmi_target;
82 extern struct target_type arm920t_target;
83 extern struct target_type arm966e_target;
84 extern struct target_type arm946e_target;
85 extern struct target_type arm926ejs_target;
86 extern struct target_type fa526_target;
87 extern struct target_type feroceon_target;
88 extern struct target_type dragonite_target;
89 extern struct target_type xscale_target;
90 extern struct target_type cortexm_target;
91 extern struct target_type cortexa_target;
92 extern struct target_type aarch64_target;
93 extern struct target_type cortexr4_target;
94 extern struct target_type arm11_target;
95 extern struct target_type ls1_sap_target;
96 extern struct target_type mips_m4k_target;
97 extern struct target_type mips_mips64_target;
98 extern struct target_type avr_target;
99 extern struct target_type dsp563xx_target;
100 extern struct target_type dsp5680xx_target;
101 extern struct target_type testee_target;
102 extern struct target_type avr32_ap7k_target;
103 extern struct target_type hla_target;
104 extern struct target_type nds32_v2_target;
105 extern struct target_type nds32_v3_target;
106 extern struct target_type nds32_v3m_target;
107 extern struct target_type or1k_target;
108 extern struct target_type quark_x10xx_target;
109 extern struct target_type quark_d20xx_target;
110 extern struct target_type stm8_target;
111 extern struct target_type riscv_target;
112 extern struct target_type mem_ap_target;
113 extern struct target_type esirisc_target;
114 extern struct target_type arcv2_target;
116 static struct target_type *target_types[] = {
156 struct target *all_targets;
157 static struct target_event_callback *target_event_callbacks;
158 static struct target_timer_callback *target_timer_callbacks;
159 static int64_t target_timer_next_event_value;
160 static LIST_HEAD(target_reset_callback_list);
161 static LIST_HEAD(target_trace_callback_list);
162 static const int polling_interval = TARGET_DEFAULT_POLLING_INTERVAL;
163 static LIST_HEAD(empty_smp_targets);
165 static const struct jim_nvp nvp_assert[] = {
166 { .name = "assert", NVP_ASSERT },
167 { .name = "deassert", NVP_DEASSERT },
168 { .name = "T", NVP_ASSERT },
169 { .name = "F", NVP_DEASSERT },
170 { .name = "t", NVP_ASSERT },
171 { .name = "f", NVP_DEASSERT },
172 { .name = NULL, .value = -1 }
175 static const struct jim_nvp nvp_error_target[] = {
176 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
177 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
178 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
179 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
180 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
181 { .value = ERROR_TARGET_UNALIGNED_ACCESS, .name = "err-unaligned-access" },
182 { .value = ERROR_TARGET_DATA_ABORT, .name = "err-data-abort" },
183 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE, .name = "err-resource-not-available" },
184 { .value = ERROR_TARGET_TRANSLATION_FAULT, .name = "err-translation-fault" },
185 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
186 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
187 { .value = -1, .name = NULL }
190 static const char *target_strerror_safe(int err)
192 const struct jim_nvp *n;
194 n = jim_nvp_value2name_simple(nvp_error_target, err);
201 static const struct jim_nvp nvp_target_event[] = {
203 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
204 { .value = TARGET_EVENT_HALTED, .name = "halted" },
205 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
206 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
207 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
208 { .value = TARGET_EVENT_STEP_START, .name = "step-start" },
209 { .value = TARGET_EVENT_STEP_END, .name = "step-end" },
211 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
212 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
214 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
215 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
216 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
217 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
218 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
219 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
220 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
221 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
223 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
224 { .value = TARGET_EVENT_EXAMINE_FAIL, .name = "examine-fail" },
225 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
227 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
228 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
230 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
231 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
233 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
234 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END, .name = "gdb-flash-write-end" },
236 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
237 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END, .name = "gdb-flash-erase-end" },
239 { .value = TARGET_EVENT_TRACE_CONFIG, .name = "trace-config" },
241 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x100, .name = "semihosting-user-cmd-0x100" },
242 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x101, .name = "semihosting-user-cmd-0x101" },
243 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x102, .name = "semihosting-user-cmd-0x102" },
244 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x103, .name = "semihosting-user-cmd-0x103" },
245 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x104, .name = "semihosting-user-cmd-0x104" },
246 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x105, .name = "semihosting-user-cmd-0x105" },
247 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x106, .name = "semihosting-user-cmd-0x106" },
248 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0x107, .name = "semihosting-user-cmd-0x107" },
250 { .name = NULL, .value = -1 }
253 static const struct jim_nvp nvp_target_state[] = {
254 { .name = "unknown", .value = TARGET_UNKNOWN },
255 { .name = "running", .value = TARGET_RUNNING },
256 { .name = "halted", .value = TARGET_HALTED },
257 { .name = "reset", .value = TARGET_RESET },
258 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
259 { .name = NULL, .value = -1 },
262 static const struct jim_nvp nvp_target_debug_reason[] = {
263 { .name = "debug-request", .value = DBG_REASON_DBGRQ },
264 { .name = "breakpoint", .value = DBG_REASON_BREAKPOINT },
265 { .name = "watchpoint", .value = DBG_REASON_WATCHPOINT },
266 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
267 { .name = "single-step", .value = DBG_REASON_SINGLESTEP },
268 { .name = "target-not-halted", .value = DBG_REASON_NOTHALTED },
269 { .name = "program-exit", .value = DBG_REASON_EXIT },
270 { .name = "exception-catch", .value = DBG_REASON_EXC_CATCH },
271 { .name = "undefined", .value = DBG_REASON_UNDEFINED },
272 { .name = NULL, .value = -1 },
275 static const struct jim_nvp nvp_target_endian[] = {
276 { .name = "big", .value = TARGET_BIG_ENDIAN },
277 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
278 { .name = "be", .value = TARGET_BIG_ENDIAN },
279 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
280 { .name = NULL, .value = -1 },
283 static const struct jim_nvp nvp_reset_modes[] = {
284 { .name = "unknown", .value = RESET_UNKNOWN },
285 { .name = "run", .value = RESET_RUN },
286 { .name = "halt", .value = RESET_HALT },
287 { .name = "init", .value = RESET_INIT },
288 { .name = NULL, .value = -1 },
291 const char *debug_reason_name(struct target *t)
295 cp = jim_nvp_value2name_simple(nvp_target_debug_reason,
296 t->debug_reason)->name;
298 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
299 cp = "(*BUG*unknown*BUG*)";
304 const char *target_state_name(struct target *t)
307 cp = jim_nvp_value2name_simple(nvp_target_state, t->state)->name;
309 LOG_ERROR("Invalid target state: %d", (int)(t->state));
310 cp = "(*BUG*unknown*BUG*)";
313 if (!target_was_examined(t) && t->defer_examine)
314 cp = "examine deferred";
319 const char *target_event_name(enum target_event event)
322 cp = jim_nvp_value2name_simple(nvp_target_event, event)->name;
324 LOG_ERROR("Invalid target event: %d", (int)(event));
325 cp = "(*BUG*unknown*BUG*)";
330 const char *target_reset_mode_name(enum target_reset_mode reset_mode)
333 cp = jim_nvp_value2name_simple(nvp_reset_modes, reset_mode)->name;
335 LOG_ERROR("Invalid target reset mode: %d", (int)(reset_mode));
336 cp = "(*BUG*unknown*BUG*)";
341 /* determine the number of the new target */
342 static int new_target_number(void)
347 /* number is 0 based */
351 if (x < t->target_number)
352 x = t->target_number;
358 static void append_to_list_all_targets(struct target *target)
360 struct target **t = &all_targets;
367 /* read a uint64_t from a buffer in target memory endianness */
368 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
370 if (target->endianness == TARGET_LITTLE_ENDIAN)
371 return le_to_h_u64(buffer);
373 return be_to_h_u64(buffer);
376 /* read a uint32_t from a buffer in target memory endianness */
377 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
379 if (target->endianness == TARGET_LITTLE_ENDIAN)
380 return le_to_h_u32(buffer);
382 return be_to_h_u32(buffer);
385 /* read a uint24_t from a buffer in target memory endianness */
386 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
388 if (target->endianness == TARGET_LITTLE_ENDIAN)
389 return le_to_h_u24(buffer);
391 return be_to_h_u24(buffer);
394 /* read a uint16_t from a buffer in target memory endianness */
395 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
397 if (target->endianness == TARGET_LITTLE_ENDIAN)
398 return le_to_h_u16(buffer);
400 return be_to_h_u16(buffer);
403 /* write a uint64_t to a buffer in target memory endianness */
404 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
406 if (target->endianness == TARGET_LITTLE_ENDIAN)
407 h_u64_to_le(buffer, value);
409 h_u64_to_be(buffer, value);
412 /* write a uint32_t to a buffer in target memory endianness */
413 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
415 if (target->endianness == TARGET_LITTLE_ENDIAN)
416 h_u32_to_le(buffer, value);
418 h_u32_to_be(buffer, value);
421 /* write a uint24_t to a buffer in target memory endianness */
422 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
424 if (target->endianness == TARGET_LITTLE_ENDIAN)
425 h_u24_to_le(buffer, value);
427 h_u24_to_be(buffer, value);
430 /* write a uint16_t to a buffer in target memory endianness */
431 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
433 if (target->endianness == TARGET_LITTLE_ENDIAN)
434 h_u16_to_le(buffer, value);
436 h_u16_to_be(buffer, value);
439 /* write a uint8_t to a buffer in target memory endianness */
440 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
445 /* write a uint64_t array to a buffer in target memory endianness */
446 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
449 for (i = 0; i < count; i++)
450 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
453 /* write a uint32_t array to a buffer in target memory endianness */
454 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
457 for (i = 0; i < count; i++)
458 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
461 /* write a uint16_t array to a buffer in target memory endianness */
462 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
465 for (i = 0; i < count; i++)
466 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
469 /* write a uint64_t array to a buffer in target memory endianness */
470 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
473 for (i = 0; i < count; i++)
474 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
477 /* write a uint32_t array to a buffer in target memory endianness */
478 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
481 for (i = 0; i < count; i++)
482 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
485 /* write a uint16_t array to a buffer in target memory endianness */
486 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
489 for (i = 0; i < count; i++)
490 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
493 /* return a pointer to a configured target; id is name or number */
494 struct target *get_target(const char *id)
496 struct target *target;
498 /* try as tcltarget name */
499 for (target = all_targets; target; target = target->next) {
500 if (!target_name(target))
502 if (strcmp(id, target_name(target)) == 0)
506 /* It's OK to remove this fallback sometime after August 2010 or so */
508 /* no match, try as number */
510 if (parse_uint(id, &num) != ERROR_OK)
513 for (target = all_targets; target; target = target->next) {
514 if (target->target_number == (int)num) {
515 LOG_WARNING("use '%s' as target identifier, not '%u'",
516 target_name(target), num);
524 /* returns a pointer to the n-th configured target */
525 struct target *get_target_by_num(int num)
527 struct target *target = all_targets;
530 if (target->target_number == num)
532 target = target->next;
538 struct target *get_current_target(struct command_context *cmd_ctx)
540 struct target *target = get_current_target_or_null(cmd_ctx);
543 LOG_ERROR("BUG: current_target out of bounds");
550 struct target *get_current_target_or_null(struct command_context *cmd_ctx)
552 return cmd_ctx->current_target_override
553 ? cmd_ctx->current_target_override
554 : cmd_ctx->current_target;
557 int target_poll(struct target *target)
561 /* We can't poll until after examine */
562 if (!target_was_examined(target)) {
563 /* Fail silently lest we pollute the log */
567 retval = target->type->poll(target);
568 if (retval != ERROR_OK)
571 if (target->halt_issued) {
572 if (target->state == TARGET_HALTED)
573 target->halt_issued = false;
575 int64_t t = timeval_ms() - target->halt_issued_time;
576 if (t > DEFAULT_HALT_TIMEOUT) {
577 target->halt_issued = false;
578 LOG_INFO("Halt timed out, wake up GDB.");
579 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
587 int target_halt(struct target *target)
590 /* We can't poll until after examine */
591 if (!target_was_examined(target)) {
592 LOG_ERROR("Target not examined yet");
596 retval = target->type->halt(target);
597 if (retval != ERROR_OK)
600 target->halt_issued = true;
601 target->halt_issued_time = timeval_ms();
607 * Make the target (re)start executing using its saved execution
608 * context (possibly with some modifications).
610 * @param target Which target should start executing.
611 * @param current True to use the target's saved program counter instead
612 * of the address parameter
613 * @param address Optionally used as the program counter.
614 * @param handle_breakpoints True iff breakpoints at the resumption PC
615 * should be skipped. (For example, maybe execution was stopped by
616 * such a breakpoint, in which case it would be counterproductive to
618 * @param debug_execution False if all working areas allocated by OpenOCD
619 * should be released and/or restored to their original contents.
620 * (This would for example be true to run some downloaded "helper"
621 * algorithm code, which resides in one such working buffer and uses
622 * another for data storage.)
624 * @todo Resolve the ambiguity about what the "debug_execution" flag
625 * signifies. For example, Target implementations don't agree on how
626 * it relates to invalidation of the register cache, or to whether
627 * breakpoints and watchpoints should be enabled. (It would seem wrong
628 * to enable breakpoints when running downloaded "helper" algorithms
629 * (debug_execution true), since the breakpoints would be set to match
630 * target firmware being debugged, not the helper algorithm.... and
631 * enabling them could cause such helpers to malfunction (for example,
632 * by overwriting data with a breakpoint instruction. On the other
633 * hand the infrastructure for running such helpers might use this
634 * procedure but rely on hardware breakpoint to detect termination.)
636 int target_resume(struct target *target, int current, target_addr_t address,
637 int handle_breakpoints, int debug_execution)
641 /* We can't poll until after examine */
642 if (!target_was_examined(target)) {
643 LOG_ERROR("Target not examined yet");
647 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
649 /* note that resume *must* be asynchronous. The CPU can halt before
650 * we poll. The CPU can even halt at the current PC as a result of
651 * a software breakpoint being inserted by (a bug?) the application.
654 * resume() triggers the event 'resumed'. The execution of TCL commands
655 * in the event handler causes the polling of targets. If the target has
656 * already halted for a breakpoint, polling will run the 'halted' event
657 * handler before the pending 'resumed' handler.
658 * Disable polling during resume() to guarantee the execution of handlers
659 * in the correct order.
661 bool save_poll = jtag_poll_get_enabled();
662 jtag_poll_set_enabled(false);
663 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
664 jtag_poll_set_enabled(save_poll);
665 if (retval != ERROR_OK)
668 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
673 static int target_process_reset(struct command_invocation *cmd, enum target_reset_mode reset_mode)
678 n = jim_nvp_value2name_simple(nvp_reset_modes, reset_mode);
680 LOG_ERROR("invalid reset mode");
684 struct target *target;
685 for (target = all_targets; target; target = target->next)
686 target_call_reset_callbacks(target, reset_mode);
688 /* disable polling during reset to make reset event scripts
689 * more predictable, i.e. dr/irscan & pathmove in events will
690 * not have JTAG operations injected into the middle of a sequence.
692 bool save_poll = jtag_poll_get_enabled();
694 jtag_poll_set_enabled(false);
696 sprintf(buf, "ocd_process_reset %s", n->name);
697 retval = Jim_Eval(cmd->ctx->interp, buf);
699 jtag_poll_set_enabled(save_poll);
701 if (retval != JIM_OK) {
702 Jim_MakeErrorMessage(cmd->ctx->interp);
703 command_print(cmd, "%s", Jim_GetString(Jim_GetResult(cmd->ctx->interp), NULL));
707 /* We want any events to be processed before the prompt */
708 retval = target_call_timer_callbacks_now();
710 for (target = all_targets; target; target = target->next) {
711 target->type->check_reset(target);
712 target->running_alg = false;
718 static int identity_virt2phys(struct target *target,
719 target_addr_t virtual, target_addr_t *physical)
725 static int no_mmu(struct target *target, int *enabled)
732 * Reset the @c examined flag for the given target.
733 * Pure paranoia -- targets are zeroed on allocation.
735 static inline void target_reset_examined(struct target *target)
737 target->examined = false;
740 static int default_examine(struct target *target)
742 target_set_examined(target);
746 /* no check by default */
747 static int default_check_reset(struct target *target)
752 /* Equivalent Tcl code arp_examine_one is in src/target/startup.tcl
754 int target_examine_one(struct target *target)
756 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
758 int retval = target->type->examine(target);
759 if (retval != ERROR_OK) {
760 target_reset_examined(target);
761 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_FAIL);
765 target_set_examined(target);
766 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
771 static int jtag_enable_callback(enum jtag_event event, void *priv)
773 struct target *target = priv;
775 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
778 jtag_unregister_event_callback(jtag_enable_callback, target);
780 return target_examine_one(target);
783 /* Targets that correctly implement init + examine, i.e.
784 * no communication with target during init:
788 int target_examine(void)
790 int retval = ERROR_OK;
791 struct target *target;
793 for (target = all_targets; target; target = target->next) {
794 /* defer examination, but don't skip it */
795 if (!target->tap->enabled) {
796 jtag_register_event_callback(jtag_enable_callback,
801 if (target->defer_examine)
804 int retval2 = target_examine_one(target);
805 if (retval2 != ERROR_OK) {
806 LOG_WARNING("target %s examination failed", target_name(target));
813 const char *target_type_name(struct target *target)
815 return target->type->name;
818 static int target_soft_reset_halt(struct target *target)
820 if (!target_was_examined(target)) {
821 LOG_ERROR("Target not examined yet");
824 if (!target->type->soft_reset_halt) {
825 LOG_ERROR("Target %s does not support soft_reset_halt",
826 target_name(target));
829 return target->type->soft_reset_halt(target);
833 * Downloads a target-specific native code algorithm to the target,
834 * and executes it. * Note that some targets may need to set up, enable,
835 * and tear down a breakpoint (hard or * soft) to detect algorithm
836 * termination, while others may support lower overhead schemes where
837 * soft breakpoints embedded in the algorithm automatically terminate the
840 * @param target used to run the algorithm
841 * @param num_mem_params
843 * @param num_reg_params
848 * @param arch_info target-specific description of the algorithm.
850 int target_run_algorithm(struct target *target,
851 int num_mem_params, struct mem_param *mem_params,
852 int num_reg_params, struct reg_param *reg_param,
853 target_addr_t entry_point, target_addr_t exit_point,
854 int timeout_ms, void *arch_info)
856 int retval = ERROR_FAIL;
858 if (!target_was_examined(target)) {
859 LOG_ERROR("Target not examined yet");
862 if (!target->type->run_algorithm) {
863 LOG_ERROR("Target type '%s' does not support %s",
864 target_type_name(target), __func__);
868 target->running_alg = true;
869 retval = target->type->run_algorithm(target,
870 num_mem_params, mem_params,
871 num_reg_params, reg_param,
872 entry_point, exit_point, timeout_ms, arch_info);
873 target->running_alg = false;
880 * Executes a target-specific native code algorithm and leaves it running.
882 * @param target used to run the algorithm
883 * @param num_mem_params
885 * @param num_reg_params
889 * @param arch_info target-specific description of the algorithm.
891 int target_start_algorithm(struct target *target,
892 int num_mem_params, struct mem_param *mem_params,
893 int num_reg_params, struct reg_param *reg_params,
894 target_addr_t entry_point, target_addr_t exit_point,
897 int retval = ERROR_FAIL;
899 if (!target_was_examined(target)) {
900 LOG_ERROR("Target not examined yet");
903 if (!target->type->start_algorithm) {
904 LOG_ERROR("Target type '%s' does not support %s",
905 target_type_name(target), __func__);
908 if (target->running_alg) {
909 LOG_ERROR("Target is already running an algorithm");
913 target->running_alg = true;
914 retval = target->type->start_algorithm(target,
915 num_mem_params, mem_params,
916 num_reg_params, reg_params,
917 entry_point, exit_point, arch_info);
924 * Waits for an algorithm started with target_start_algorithm() to complete.
926 * @param target used to run the algorithm
927 * @param num_mem_params
929 * @param num_reg_params
933 * @param arch_info target-specific description of the algorithm.
935 int target_wait_algorithm(struct target *target,
936 int num_mem_params, struct mem_param *mem_params,
937 int num_reg_params, struct reg_param *reg_params,
938 target_addr_t exit_point, int timeout_ms,
941 int retval = ERROR_FAIL;
943 if (!target->type->wait_algorithm) {
944 LOG_ERROR("Target type '%s' does not support %s",
945 target_type_name(target), __func__);
948 if (!target->running_alg) {
949 LOG_ERROR("Target is not running an algorithm");
953 retval = target->type->wait_algorithm(target,
954 num_mem_params, mem_params,
955 num_reg_params, reg_params,
956 exit_point, timeout_ms, arch_info);
957 if (retval != ERROR_TARGET_TIMEOUT)
958 target->running_alg = false;
965 * Streams data to a circular buffer on target intended for consumption by code
966 * running asynchronously on target.
968 * This is intended for applications where target-specific native code runs
969 * on the target, receives data from the circular buffer, does something with
970 * it (most likely writing it to a flash memory), and advances the circular
973 * This assumes that the helper algorithm has already been loaded to the target,
974 * but has not been started yet. Given memory and register parameters are passed
977 * The buffer is defined by (buffer_start, buffer_size) arguments and has the
980 * [buffer_start + 0, buffer_start + 4):
981 * Write Pointer address (aka head). Written and updated by this
982 * routine when new data is written to the circular buffer.
983 * [buffer_start + 4, buffer_start + 8):
984 * Read Pointer address (aka tail). Updated by code running on the
985 * target after it consumes data.
986 * [buffer_start + 8, buffer_start + buffer_size):
987 * Circular buffer contents.
989 * See contrib/loaders/flash/stm32f1x.S for an example.
991 * @param target used to run the algorithm
992 * @param buffer address on the host where data to be sent is located
993 * @param count number of blocks to send
994 * @param block_size size in bytes of each block
995 * @param num_mem_params count of memory-based params to pass to algorithm
996 * @param mem_params memory-based params to pass to algorithm
997 * @param num_reg_params count of register-based params to pass to algorithm
998 * @param reg_params memory-based params to pass to algorithm
999 * @param buffer_start address on the target of the circular buffer structure
1000 * @param buffer_size size of the circular buffer structure
1001 * @param entry_point address on the target to execute to start the algorithm
1002 * @param exit_point address at which to set a breakpoint to catch the
1003 * end of the algorithm; can be 0 if target triggers a breakpoint itself
1007 int target_run_flash_async_algorithm(struct target *target,
1008 const uint8_t *buffer, uint32_t count, int block_size,
1009 int num_mem_params, struct mem_param *mem_params,
1010 int num_reg_params, struct reg_param *reg_params,
1011 uint32_t buffer_start, uint32_t buffer_size,
1012 uint32_t entry_point, uint32_t exit_point, void *arch_info)
1017 const uint8_t *buffer_orig = buffer;
1019 /* Set up working area. First word is write pointer, second word is read pointer,
1020 * rest is fifo data area. */
1021 uint32_t wp_addr = buffer_start;
1022 uint32_t rp_addr = buffer_start + 4;
1023 uint32_t fifo_start_addr = buffer_start + 8;
1024 uint32_t fifo_end_addr = buffer_start + buffer_size;
1026 uint32_t wp = fifo_start_addr;
1027 uint32_t rp = fifo_start_addr;
1029 /* validate block_size is 2^n */
1030 assert(IS_PWR_OF_2(block_size));
1032 retval = target_write_u32(target, wp_addr, wp);
1033 if (retval != ERROR_OK)
1035 retval = target_write_u32(target, rp_addr, rp);
1036 if (retval != ERROR_OK)
1039 /* Start up algorithm on target and let it idle while writing the first chunk */
1040 retval = target_start_algorithm(target, num_mem_params, mem_params,
1041 num_reg_params, reg_params,
1046 if (retval != ERROR_OK) {
1047 LOG_ERROR("error starting target flash write algorithm");
1053 retval = target_read_u32(target, rp_addr, &rp);
1054 if (retval != ERROR_OK) {
1055 LOG_ERROR("failed to get read pointer");
1059 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1060 (size_t) (buffer - buffer_orig), count, wp, rp);
1063 LOG_ERROR("flash write algorithm aborted by target");
1064 retval = ERROR_FLASH_OPERATION_FAILED;
1068 if (!IS_ALIGNED(rp - fifo_start_addr, block_size) || rp < fifo_start_addr || rp >= fifo_end_addr) {
1069 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
1073 /* Count the number of bytes available in the fifo without
1074 * crossing the wrap around. Make sure to not fill it completely,
1075 * because that would make wp == rp and that's the empty condition. */
1076 uint32_t thisrun_bytes;
1078 thisrun_bytes = rp - wp - block_size;
1079 else if (rp > fifo_start_addr)
1080 thisrun_bytes = fifo_end_addr - wp;
1082 thisrun_bytes = fifo_end_addr - wp - block_size;
1084 if (thisrun_bytes == 0) {
1085 /* Throttle polling a bit if transfer is (much) faster than flash
1086 * programming. The exact delay shouldn't matter as long as it's
1087 * less than buffer size / flash speed. This is very unlikely to
1088 * run when using high latency connections such as USB. */
1091 /* to stop an infinite loop on some targets check and increment a timeout
1092 * this issue was observed on a stellaris using the new ICDI interface */
1093 if (timeout++ >= 2500) {
1094 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1095 return ERROR_FLASH_OPERATION_FAILED;
1100 /* reset our timeout */
1103 /* Limit to the amount of data we actually want to write */
1104 if (thisrun_bytes > count * block_size)
1105 thisrun_bytes = count * block_size;
1107 /* Force end of large blocks to be word aligned */
1108 if (thisrun_bytes >= 16)
1109 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1111 /* Write data to fifo */
1112 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
1113 if (retval != ERROR_OK)
1116 /* Update counters and wrap write pointer */
1117 buffer += thisrun_bytes;
1118 count -= thisrun_bytes / block_size;
1119 wp += thisrun_bytes;
1120 if (wp >= fifo_end_addr)
1121 wp = fifo_start_addr;
1123 /* Store updated write pointer to target */
1124 retval = target_write_u32(target, wp_addr, wp);
1125 if (retval != ERROR_OK)
1128 /* Avoid GDB timeouts */
1132 if (retval != ERROR_OK) {
1133 /* abort flash write algorithm on target */
1134 target_write_u32(target, wp_addr, 0);
1137 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1138 num_reg_params, reg_params,
1143 if (retval2 != ERROR_OK) {
1144 LOG_ERROR("error waiting for target flash write algorithm");
1148 if (retval == ERROR_OK) {
1149 /* check if algorithm set rp = 0 after fifo writer loop finished */
1150 retval = target_read_u32(target, rp_addr, &rp);
1151 if (retval == ERROR_OK && rp == 0) {
1152 LOG_ERROR("flash write algorithm aborted by target");
1153 retval = ERROR_FLASH_OPERATION_FAILED;
1160 int target_run_read_async_algorithm(struct target *target,
1161 uint8_t *buffer, uint32_t count, int block_size,
1162 int num_mem_params, struct mem_param *mem_params,
1163 int num_reg_params, struct reg_param *reg_params,
1164 uint32_t buffer_start, uint32_t buffer_size,
1165 uint32_t entry_point, uint32_t exit_point, void *arch_info)
1170 const uint8_t *buffer_orig = buffer;
1172 /* Set up working area. First word is write pointer, second word is read pointer,
1173 * rest is fifo data area. */
1174 uint32_t wp_addr = buffer_start;
1175 uint32_t rp_addr = buffer_start + 4;
1176 uint32_t fifo_start_addr = buffer_start + 8;
1177 uint32_t fifo_end_addr = buffer_start + buffer_size;
1179 uint32_t wp = fifo_start_addr;
1180 uint32_t rp = fifo_start_addr;
1182 /* validate block_size is 2^n */
1183 assert(IS_PWR_OF_2(block_size));
1185 retval = target_write_u32(target, wp_addr, wp);
1186 if (retval != ERROR_OK)
1188 retval = target_write_u32(target, rp_addr, rp);
1189 if (retval != ERROR_OK)
1192 /* Start up algorithm on target */
1193 retval = target_start_algorithm(target, num_mem_params, mem_params,
1194 num_reg_params, reg_params,
1199 if (retval != ERROR_OK) {
1200 LOG_ERROR("error starting target flash read algorithm");
1205 retval = target_read_u32(target, wp_addr, &wp);
1206 if (retval != ERROR_OK) {
1207 LOG_ERROR("failed to get write pointer");
1211 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1212 (size_t)(buffer - buffer_orig), count, wp, rp);
1215 LOG_ERROR("flash read algorithm aborted by target");
1216 retval = ERROR_FLASH_OPERATION_FAILED;
1220 if (!IS_ALIGNED(wp - fifo_start_addr, block_size) || wp < fifo_start_addr || wp >= fifo_end_addr) {
1221 LOG_ERROR("corrupted fifo write pointer 0x%" PRIx32, wp);
1225 /* Count the number of bytes available in the fifo without
1226 * crossing the wrap around. */
1227 uint32_t thisrun_bytes;
1229 thisrun_bytes = wp - rp;
1231 thisrun_bytes = fifo_end_addr - rp;
1233 if (thisrun_bytes == 0) {
1234 /* Throttle polling a bit if transfer is (much) faster than flash
1235 * reading. The exact delay shouldn't matter as long as it's
1236 * less than buffer size / flash speed. This is very unlikely to
1237 * run when using high latency connections such as USB. */
1240 /* to stop an infinite loop on some targets check and increment a timeout
1241 * this issue was observed on a stellaris using the new ICDI interface */
1242 if (timeout++ >= 2500) {
1243 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1244 return ERROR_FLASH_OPERATION_FAILED;
1249 /* Reset our timeout */
1252 /* Limit to the amount of data we actually want to read */
1253 if (thisrun_bytes > count * block_size)
1254 thisrun_bytes = count * block_size;
1256 /* Force end of large blocks to be word aligned */
1257 if (thisrun_bytes >= 16)
1258 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1260 /* Read data from fifo */
1261 retval = target_read_buffer(target, rp, thisrun_bytes, buffer);
1262 if (retval != ERROR_OK)
1265 /* Update counters and wrap write pointer */
1266 buffer += thisrun_bytes;
1267 count -= thisrun_bytes / block_size;
1268 rp += thisrun_bytes;
1269 if (rp >= fifo_end_addr)
1270 rp = fifo_start_addr;
1272 /* Store updated write pointer to target */
1273 retval = target_write_u32(target, rp_addr, rp);
1274 if (retval != ERROR_OK)
1277 /* Avoid GDB timeouts */
1282 if (retval != ERROR_OK) {
1283 /* abort flash write algorithm on target */
1284 target_write_u32(target, rp_addr, 0);
1287 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1288 num_reg_params, reg_params,
1293 if (retval2 != ERROR_OK) {
1294 LOG_ERROR("error waiting for target flash write algorithm");
1298 if (retval == ERROR_OK) {
1299 /* check if algorithm set wp = 0 after fifo writer loop finished */
1300 retval = target_read_u32(target, wp_addr, &wp);
1301 if (retval == ERROR_OK && wp == 0) {
1302 LOG_ERROR("flash read algorithm aborted by target");
1303 retval = ERROR_FLASH_OPERATION_FAILED;
1310 int target_read_memory(struct target *target,
1311 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1313 if (!target_was_examined(target)) {
1314 LOG_ERROR("Target not examined yet");
1317 if (!target->type->read_memory) {
1318 LOG_ERROR("Target %s doesn't support read_memory", target_name(target));
1321 return target->type->read_memory(target, address, size, count, buffer);
1324 int target_read_phys_memory(struct target *target,
1325 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1327 if (!target_was_examined(target)) {
1328 LOG_ERROR("Target not examined yet");
1331 if (!target->type->read_phys_memory) {
1332 LOG_ERROR("Target %s doesn't support read_phys_memory", target_name(target));
1335 return target->type->read_phys_memory(target, address, size, count, buffer);
1338 int target_write_memory(struct target *target,
1339 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1341 if (!target_was_examined(target)) {
1342 LOG_ERROR("Target not examined yet");
1345 if (!target->type->write_memory) {
1346 LOG_ERROR("Target %s doesn't support write_memory", target_name(target));
1349 return target->type->write_memory(target, address, size, count, buffer);
1352 int target_write_phys_memory(struct target *target,
1353 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1355 if (!target_was_examined(target)) {
1356 LOG_ERROR("Target not examined yet");
1359 if (!target->type->write_phys_memory) {
1360 LOG_ERROR("Target %s doesn't support write_phys_memory", target_name(target));
1363 return target->type->write_phys_memory(target, address, size, count, buffer);
1366 int target_add_breakpoint(struct target *target,
1367 struct breakpoint *breakpoint)
1369 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1370 LOG_WARNING("target %s is not halted (add breakpoint)", target_name(target));
1371 return ERROR_TARGET_NOT_HALTED;
1373 return target->type->add_breakpoint(target, breakpoint);
1376 int target_add_context_breakpoint(struct target *target,
1377 struct breakpoint *breakpoint)
1379 if (target->state != TARGET_HALTED) {
1380 LOG_WARNING("target %s is not halted (add context breakpoint)", target_name(target));
1381 return ERROR_TARGET_NOT_HALTED;
1383 return target->type->add_context_breakpoint(target, breakpoint);
1386 int target_add_hybrid_breakpoint(struct target *target,
1387 struct breakpoint *breakpoint)
1389 if (target->state != TARGET_HALTED) {
1390 LOG_WARNING("target %s is not halted (add hybrid breakpoint)", target_name(target));
1391 return ERROR_TARGET_NOT_HALTED;
1393 return target->type->add_hybrid_breakpoint(target, breakpoint);
1396 int target_remove_breakpoint(struct target *target,
1397 struct breakpoint *breakpoint)
1399 return target->type->remove_breakpoint(target, breakpoint);
1402 int target_add_watchpoint(struct target *target,
1403 struct watchpoint *watchpoint)
1405 if (target->state != TARGET_HALTED) {
1406 LOG_WARNING("target %s is not halted (add watchpoint)", target_name(target));
1407 return ERROR_TARGET_NOT_HALTED;
1409 return target->type->add_watchpoint(target, watchpoint);
1411 int target_remove_watchpoint(struct target *target,
1412 struct watchpoint *watchpoint)
1414 return target->type->remove_watchpoint(target, watchpoint);
1416 int target_hit_watchpoint(struct target *target,
1417 struct watchpoint **hit_watchpoint)
1419 if (target->state != TARGET_HALTED) {
1420 LOG_WARNING("target %s is not halted (hit watchpoint)", target->cmd_name);
1421 return ERROR_TARGET_NOT_HALTED;
1424 if (!target->type->hit_watchpoint) {
1425 /* For backward compatible, if hit_watchpoint is not implemented,
1426 * return ERROR_FAIL such that gdb_server will not take the nonsense
1431 return target->type->hit_watchpoint(target, hit_watchpoint);
1434 const char *target_get_gdb_arch(struct target *target)
1436 if (!target->type->get_gdb_arch)
1438 return target->type->get_gdb_arch(target);
1441 int target_get_gdb_reg_list(struct target *target,
1442 struct reg **reg_list[], int *reg_list_size,
1443 enum target_register_class reg_class)
1445 int result = ERROR_FAIL;
1447 if (!target_was_examined(target)) {
1448 LOG_ERROR("Target not examined yet");
1452 result = target->type->get_gdb_reg_list(target, reg_list,
1453 reg_list_size, reg_class);
1456 if (result != ERROR_OK) {
1463 int target_get_gdb_reg_list_noread(struct target *target,
1464 struct reg **reg_list[], int *reg_list_size,
1465 enum target_register_class reg_class)
1467 if (target->type->get_gdb_reg_list_noread &&
1468 target->type->get_gdb_reg_list_noread(target, reg_list,
1469 reg_list_size, reg_class) == ERROR_OK)
1471 return target_get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1474 bool target_supports_gdb_connection(struct target *target)
1477 * exclude all the targets that don't provide get_gdb_reg_list
1478 * or that have explicit gdb_max_connection == 0
1480 return !!target->type->get_gdb_reg_list && !!target->gdb_max_connections;
1483 int target_step(struct target *target,
1484 int current, target_addr_t address, int handle_breakpoints)
1488 target_call_event_callbacks(target, TARGET_EVENT_STEP_START);
1490 retval = target->type->step(target, current, address, handle_breakpoints);
1491 if (retval != ERROR_OK)
1494 target_call_event_callbacks(target, TARGET_EVENT_STEP_END);
1499 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1501 if (target->state != TARGET_HALTED) {
1502 LOG_WARNING("target %s is not halted (gdb fileio)", target->cmd_name);
1503 return ERROR_TARGET_NOT_HALTED;
1505 return target->type->get_gdb_fileio_info(target, fileio_info);
1508 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1510 if (target->state != TARGET_HALTED) {
1511 LOG_WARNING("target %s is not halted (gdb fileio end)", target->cmd_name);
1512 return ERROR_TARGET_NOT_HALTED;
1514 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1517 target_addr_t target_address_max(struct target *target)
1519 unsigned bits = target_address_bits(target);
1520 if (sizeof(target_addr_t) * 8 == bits)
1521 return (target_addr_t) -1;
1523 return (((target_addr_t) 1) << bits) - 1;
1526 unsigned target_address_bits(struct target *target)
1528 if (target->type->address_bits)
1529 return target->type->address_bits(target);
1533 unsigned int target_data_bits(struct target *target)
1535 if (target->type->data_bits)
1536 return target->type->data_bits(target);
1540 static int target_profiling(struct target *target, uint32_t *samples,
1541 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1543 return target->type->profiling(target, samples, max_num_samples,
1544 num_samples, seconds);
1547 static int handle_target(void *priv);
1549 static int target_init_one(struct command_context *cmd_ctx,
1550 struct target *target)
1552 target_reset_examined(target);
1554 struct target_type *type = target->type;
1556 type->examine = default_examine;
1558 if (!type->check_reset)
1559 type->check_reset = default_check_reset;
1561 assert(type->init_target);
1563 int retval = type->init_target(cmd_ctx, target);
1564 if (retval != ERROR_OK) {
1565 LOG_ERROR("target '%s' init failed", target_name(target));
1569 /* Sanity-check MMU support ... stub in what we must, to help
1570 * implement it in stages, but warn if we need to do so.
1573 if (!type->virt2phys) {
1574 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1575 type->virt2phys = identity_virt2phys;
1578 /* Make sure no-MMU targets all behave the same: make no
1579 * distinction between physical and virtual addresses, and
1580 * ensure that virt2phys() is always an identity mapping.
1582 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1583 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1586 type->write_phys_memory = type->write_memory;
1587 type->read_phys_memory = type->read_memory;
1588 type->virt2phys = identity_virt2phys;
1591 if (!target->type->read_buffer)
1592 target->type->read_buffer = target_read_buffer_default;
1594 if (!target->type->write_buffer)
1595 target->type->write_buffer = target_write_buffer_default;
1597 if (!target->type->get_gdb_fileio_info)
1598 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1600 if (!target->type->gdb_fileio_end)
1601 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1603 if (!target->type->profiling)
1604 target->type->profiling = target_profiling_default;
1609 static int target_init(struct command_context *cmd_ctx)
1611 struct target *target;
1614 for (target = all_targets; target; target = target->next) {
1615 retval = target_init_one(cmd_ctx, target);
1616 if (retval != ERROR_OK)
1623 retval = target_register_user_commands(cmd_ctx);
1624 if (retval != ERROR_OK)
1627 retval = target_register_timer_callback(&handle_target,
1628 polling_interval, TARGET_TIMER_TYPE_PERIODIC, cmd_ctx->interp);
1629 if (retval != ERROR_OK)
1635 COMMAND_HANDLER(handle_target_init_command)
1640 return ERROR_COMMAND_SYNTAX_ERROR;
1642 static bool target_initialized;
1643 if (target_initialized) {
1644 LOG_INFO("'target init' has already been called");
1647 target_initialized = true;
1649 retval = command_run_line(CMD_CTX, "init_targets");
1650 if (retval != ERROR_OK)
1653 retval = command_run_line(CMD_CTX, "init_target_events");
1654 if (retval != ERROR_OK)
1657 retval = command_run_line(CMD_CTX, "init_board");
1658 if (retval != ERROR_OK)
1661 LOG_DEBUG("Initializing targets...");
1662 return target_init(CMD_CTX);
1665 int target_register_event_callback(int (*callback)(struct target *target,
1666 enum target_event event, void *priv), void *priv)
1668 struct target_event_callback **callbacks_p = &target_event_callbacks;
1671 return ERROR_COMMAND_SYNTAX_ERROR;
1674 while ((*callbacks_p)->next)
1675 callbacks_p = &((*callbacks_p)->next);
1676 callbacks_p = &((*callbacks_p)->next);
1679 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1680 (*callbacks_p)->callback = callback;
1681 (*callbacks_p)->priv = priv;
1682 (*callbacks_p)->next = NULL;
1687 int target_register_reset_callback(int (*callback)(struct target *target,
1688 enum target_reset_mode reset_mode, void *priv), void *priv)
1690 struct target_reset_callback *entry;
1693 return ERROR_COMMAND_SYNTAX_ERROR;
1695 entry = malloc(sizeof(struct target_reset_callback));
1697 LOG_ERROR("error allocating buffer for reset callback entry");
1698 return ERROR_COMMAND_SYNTAX_ERROR;
1701 entry->callback = callback;
1703 list_add(&entry->list, &target_reset_callback_list);
1709 int target_register_trace_callback(int (*callback)(struct target *target,
1710 size_t len, uint8_t *data, void *priv), void *priv)
1712 struct target_trace_callback *entry;
1715 return ERROR_COMMAND_SYNTAX_ERROR;
1717 entry = malloc(sizeof(struct target_trace_callback));
1719 LOG_ERROR("error allocating buffer for trace callback entry");
1720 return ERROR_COMMAND_SYNTAX_ERROR;
1723 entry->callback = callback;
1725 list_add(&entry->list, &target_trace_callback_list);
1731 int target_register_timer_callback(int (*callback)(void *priv),
1732 unsigned int time_ms, enum target_timer_type type, void *priv)
1734 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1737 return ERROR_COMMAND_SYNTAX_ERROR;
1740 while ((*callbacks_p)->next)
1741 callbacks_p = &((*callbacks_p)->next);
1742 callbacks_p = &((*callbacks_p)->next);
1745 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1746 (*callbacks_p)->callback = callback;
1747 (*callbacks_p)->type = type;
1748 (*callbacks_p)->time_ms = time_ms;
1749 (*callbacks_p)->removed = false;
1751 (*callbacks_p)->when = timeval_ms() + time_ms;
1752 target_timer_next_event_value = MIN(target_timer_next_event_value, (*callbacks_p)->when);
1754 (*callbacks_p)->priv = priv;
1755 (*callbacks_p)->next = NULL;
1760 int target_unregister_event_callback(int (*callback)(struct target *target,
1761 enum target_event event, void *priv), void *priv)
1763 struct target_event_callback **p = &target_event_callbacks;
1764 struct target_event_callback *c = target_event_callbacks;
1767 return ERROR_COMMAND_SYNTAX_ERROR;
1770 struct target_event_callback *next = c->next;
1771 if ((c->callback == callback) && (c->priv == priv)) {
1783 int target_unregister_reset_callback(int (*callback)(struct target *target,
1784 enum target_reset_mode reset_mode, void *priv), void *priv)
1786 struct target_reset_callback *entry;
1789 return ERROR_COMMAND_SYNTAX_ERROR;
1791 list_for_each_entry(entry, &target_reset_callback_list, list) {
1792 if (entry->callback == callback && entry->priv == priv) {
1793 list_del(&entry->list);
1802 int target_unregister_trace_callback(int (*callback)(struct target *target,
1803 size_t len, uint8_t *data, void *priv), void *priv)
1805 struct target_trace_callback *entry;
1808 return ERROR_COMMAND_SYNTAX_ERROR;
1810 list_for_each_entry(entry, &target_trace_callback_list, list) {
1811 if (entry->callback == callback && entry->priv == priv) {
1812 list_del(&entry->list);
1821 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1824 return ERROR_COMMAND_SYNTAX_ERROR;
1826 for (struct target_timer_callback *c = target_timer_callbacks;
1828 if ((c->callback == callback) && (c->priv == priv)) {
1837 int target_call_event_callbacks(struct target *target, enum target_event event)
1839 struct target_event_callback *callback = target_event_callbacks;
1840 struct target_event_callback *next_callback;
1842 if (event == TARGET_EVENT_HALTED) {
1843 /* execute early halted first */
1844 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1847 LOG_DEBUG("target event %i (%s) for core %s", event,
1848 target_event_name(event),
1849 target_name(target));
1851 target_handle_event(target, event);
1854 next_callback = callback->next;
1855 callback->callback(target, event, callback->priv);
1856 callback = next_callback;
1862 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1864 struct target_reset_callback *callback;
1866 LOG_DEBUG("target reset %i (%s)", reset_mode,
1867 jim_nvp_value2name_simple(nvp_reset_modes, reset_mode)->name);
1869 list_for_each_entry(callback, &target_reset_callback_list, list)
1870 callback->callback(target, reset_mode, callback->priv);
1875 int target_call_trace_callbacks(struct target *target, size_t len, uint8_t *data)
1877 struct target_trace_callback *callback;
1879 list_for_each_entry(callback, &target_trace_callback_list, list)
1880 callback->callback(target, len, data, callback->priv);
1885 static int target_timer_callback_periodic_restart(
1886 struct target_timer_callback *cb, int64_t *now)
1888 cb->when = *now + cb->time_ms;
1892 static int target_call_timer_callback(struct target_timer_callback *cb,
1895 cb->callback(cb->priv);
1897 if (cb->type == TARGET_TIMER_TYPE_PERIODIC)
1898 return target_timer_callback_periodic_restart(cb, now);
1900 return target_unregister_timer_callback(cb->callback, cb->priv);
1903 static int target_call_timer_callbacks_check_time(int checktime)
1905 static bool callback_processing;
1907 /* Do not allow nesting */
1908 if (callback_processing)
1911 callback_processing = true;
1915 int64_t now = timeval_ms();
1917 /* Initialize to a default value that's a ways into the future.
1918 * The loop below will make it closer to now if there are
1919 * callbacks that want to be called sooner. */
1920 target_timer_next_event_value = now + 1000;
1922 /* Store an address of the place containing a pointer to the
1923 * next item; initially, that's a standalone "root of the
1924 * list" variable. */
1925 struct target_timer_callback **callback = &target_timer_callbacks;
1926 while (callback && *callback) {
1927 if ((*callback)->removed) {
1928 struct target_timer_callback *p = *callback;
1929 *callback = (*callback)->next;
1934 bool call_it = (*callback)->callback &&
1935 ((!checktime && (*callback)->type == TARGET_TIMER_TYPE_PERIODIC) ||
1936 now >= (*callback)->when);
1939 target_call_timer_callback(*callback, &now);
1941 if (!(*callback)->removed && (*callback)->when < target_timer_next_event_value)
1942 target_timer_next_event_value = (*callback)->when;
1944 callback = &(*callback)->next;
1947 callback_processing = false;
1951 int target_call_timer_callbacks()
1953 return target_call_timer_callbacks_check_time(1);
1956 /* invoke periodic callbacks immediately */
1957 int target_call_timer_callbacks_now()
1959 return target_call_timer_callbacks_check_time(0);
1962 int64_t target_timer_next_event(void)
1964 return target_timer_next_event_value;
1967 /* Prints the working area layout for debug purposes */
1968 static void print_wa_layout(struct target *target)
1970 struct working_area *c = target->working_areas;
1973 LOG_DEBUG("%c%c " TARGET_ADDR_FMT "-" TARGET_ADDR_FMT " (%" PRIu32 " bytes)",
1974 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1975 c->address, c->address + c->size - 1, c->size);
1980 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1981 static void target_split_working_area(struct working_area *area, uint32_t size)
1983 assert(area->free); /* Shouldn't split an allocated area */
1984 assert(size <= area->size); /* Caller should guarantee this */
1986 /* Split only if not already the right size */
1987 if (size < area->size) {
1988 struct working_area *new_wa = malloc(sizeof(*new_wa));
1993 new_wa->next = area->next;
1994 new_wa->size = area->size - size;
1995 new_wa->address = area->address + size;
1996 new_wa->backup = NULL;
1997 new_wa->user = NULL;
1998 new_wa->free = true;
2000 area->next = new_wa;
2003 /* If backup memory was allocated to this area, it has the wrong size
2004 * now so free it and it will be reallocated if/when needed */
2006 area->backup = NULL;
2010 /* Merge all adjacent free areas into one */
2011 static void target_merge_working_areas(struct target *target)
2013 struct working_area *c = target->working_areas;
2015 while (c && c->next) {
2016 assert(c->next->address == c->address + c->size); /* This is an invariant */
2018 /* Find two adjacent free areas */
2019 if (c->free && c->next->free) {
2020 /* Merge the last into the first */
2021 c->size += c->next->size;
2023 /* Remove the last */
2024 struct working_area *to_be_freed = c->next;
2025 c->next = c->next->next;
2026 free(to_be_freed->backup);
2029 /* If backup memory was allocated to the remaining area, it's has
2030 * the wrong size now */
2039 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
2041 /* Reevaluate working area address based on MMU state*/
2042 if (!target->working_areas) {
2046 retval = target->type->mmu(target, &enabled);
2047 if (retval != ERROR_OK)
2051 if (target->working_area_phys_spec) {
2052 LOG_DEBUG("MMU disabled, using physical "
2053 "address for working memory " TARGET_ADDR_FMT,
2054 target->working_area_phys);
2055 target->working_area = target->working_area_phys;
2057 LOG_ERROR("No working memory available. "
2058 "Specify -work-area-phys to target.");
2059 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2062 if (target->working_area_virt_spec) {
2063 LOG_DEBUG("MMU enabled, using virtual "
2064 "address for working memory " TARGET_ADDR_FMT,
2065 target->working_area_virt);
2066 target->working_area = target->working_area_virt;
2068 LOG_ERROR("No working memory available. "
2069 "Specify -work-area-virt to target.");
2070 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2074 /* Set up initial working area on first call */
2075 struct working_area *new_wa = malloc(sizeof(*new_wa));
2077 new_wa->next = NULL;
2078 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
2079 new_wa->address = target->working_area;
2080 new_wa->backup = NULL;
2081 new_wa->user = NULL;
2082 new_wa->free = true;
2085 target->working_areas = new_wa;
2088 /* only allocate multiples of 4 byte */
2090 size = (size + 3) & (~3UL);
2092 struct working_area *c = target->working_areas;
2094 /* Find the first large enough working area */
2096 if (c->free && c->size >= size)
2102 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2104 /* Split the working area into the requested size */
2105 target_split_working_area(c, size);
2107 LOG_DEBUG("allocated new working area of %" PRIu32 " bytes at address " TARGET_ADDR_FMT,
2110 if (target->backup_working_area) {
2112 c->backup = malloc(c->size);
2117 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
2118 if (retval != ERROR_OK)
2122 /* mark as used, and return the new (reused) area */
2129 print_wa_layout(target);
2134 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
2138 retval = target_alloc_working_area_try(target, size, area);
2139 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
2140 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
2145 static int target_restore_working_area(struct target *target, struct working_area *area)
2147 int retval = ERROR_OK;
2149 if (target->backup_working_area && area->backup) {
2150 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
2151 if (retval != ERROR_OK)
2152 LOG_ERROR("failed to restore %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2153 area->size, area->address);
2159 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
2160 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
2162 if (!area || area->free)
2165 int retval = ERROR_OK;
2167 retval = target_restore_working_area(target, area);
2168 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
2169 if (retval != ERROR_OK)
2175 LOG_DEBUG("freed %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2176 area->size, area->address);
2178 /* mark user pointer invalid */
2179 /* TODO: Is this really safe? It points to some previous caller's memory.
2180 * How could we know that the area pointer is still in that place and not
2181 * some other vital data? What's the purpose of this, anyway? */
2185 target_merge_working_areas(target);
2187 print_wa_layout(target);
2192 int target_free_working_area(struct target *target, struct working_area *area)
2194 return target_free_working_area_restore(target, area, 1);
2197 /* free resources and restore memory, if restoring memory fails,
2198 * free up resources anyway
2200 static void target_free_all_working_areas_restore(struct target *target, int restore)
2202 struct working_area *c = target->working_areas;
2204 LOG_DEBUG("freeing all working areas");
2206 /* Loop through all areas, restoring the allocated ones and marking them as free */
2210 target_restore_working_area(target, c);
2212 *c->user = NULL; /* Same as above */
2218 /* Run a merge pass to combine all areas into one */
2219 target_merge_working_areas(target);
2221 print_wa_layout(target);
2224 void target_free_all_working_areas(struct target *target)
2226 target_free_all_working_areas_restore(target, 1);
2228 /* Now we have none or only one working area marked as free */
2229 if (target->working_areas) {
2230 /* Free the last one to allow on-the-fly moving and resizing */
2231 free(target->working_areas->backup);
2232 free(target->working_areas);
2233 target->working_areas = NULL;
2237 /* Find the largest number of bytes that can be allocated */
2238 uint32_t target_get_working_area_avail(struct target *target)
2240 struct working_area *c = target->working_areas;
2241 uint32_t max_size = 0;
2244 return target->working_area_size;
2247 if (c->free && max_size < c->size)
2256 static void target_destroy(struct target *target)
2258 if (target->type->deinit_target)
2259 target->type->deinit_target(target);
2261 free(target->semihosting);
2263 jtag_unregister_event_callback(jtag_enable_callback, target);
2265 struct target_event_action *teap = target->event_action;
2267 struct target_event_action *next = teap->next;
2268 Jim_DecrRefCount(teap->interp, teap->body);
2273 target_free_all_working_areas(target);
2275 /* release the targets SMP list */
2277 struct target_list *head, *tmp;
2279 list_for_each_entry_safe(head, tmp, target->smp_targets, lh) {
2280 list_del(&head->lh);
2281 head->target->smp = 0;
2284 if (target->smp_targets != &empty_smp_targets)
2285 free(target->smp_targets);
2289 rtos_destroy(target);
2291 free(target->gdb_port_override);
2293 free(target->trace_info);
2294 free(target->fileio_info);
2295 free(target->cmd_name);
2299 void target_quit(void)
2301 struct target_event_callback *pe = target_event_callbacks;
2303 struct target_event_callback *t = pe->next;
2307 target_event_callbacks = NULL;
2309 struct target_timer_callback *pt = target_timer_callbacks;
2311 struct target_timer_callback *t = pt->next;
2315 target_timer_callbacks = NULL;
2317 for (struct target *target = all_targets; target;) {
2321 target_destroy(target);
2328 int target_arch_state(struct target *target)
2332 LOG_WARNING("No target has been configured");
2336 if (target->state != TARGET_HALTED)
2339 retval = target->type->arch_state(target);
2343 static int target_get_gdb_fileio_info_default(struct target *target,
2344 struct gdb_fileio_info *fileio_info)
2346 /* If target does not support semi-hosting function, target
2347 has no need to provide .get_gdb_fileio_info callback.
2348 It just return ERROR_FAIL and gdb_server will return "Txx"
2349 as target halted every time. */
2353 static int target_gdb_fileio_end_default(struct target *target,
2354 int retcode, int fileio_errno, bool ctrl_c)
2359 int target_profiling_default(struct target *target, uint32_t *samples,
2360 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
2362 struct timeval timeout, now;
2364 gettimeofday(&timeout, NULL);
2365 timeval_add_time(&timeout, seconds, 0);
2367 LOG_INFO("Starting profiling. Halting and resuming the"
2368 " target as often as we can...");
2370 uint32_t sample_count = 0;
2371 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2372 struct reg *reg = register_get_by_name(target->reg_cache, "pc", true);
2374 int retval = ERROR_OK;
2376 target_poll(target);
2377 if (target->state == TARGET_HALTED) {
2378 uint32_t t = buf_get_u32(reg->value, 0, 32);
2379 samples[sample_count++] = t;
2380 /* current pc, addr = 0, do not handle breakpoints, not debugging */
2381 retval = target_resume(target, 1, 0, 0, 0);
2382 target_poll(target);
2383 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2384 } else if (target->state == TARGET_RUNNING) {
2385 /* We want to quickly sample the PC. */
2386 retval = target_halt(target);
2388 LOG_INFO("Target not halted or running");
2393 if (retval != ERROR_OK)
2396 gettimeofday(&now, NULL);
2397 if ((sample_count >= max_num_samples) || timeval_compare(&now, &timeout) >= 0) {
2398 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2403 *num_samples = sample_count;
2407 /* Single aligned words are guaranteed to use 16 or 32 bit access
2408 * mode respectively, otherwise data is handled as quickly as
2411 int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
2413 LOG_DEBUG("writing buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2416 if (!target_was_examined(target)) {
2417 LOG_ERROR("Target not examined yet");
2424 if ((address + size - 1) < address) {
2425 /* GDB can request this when e.g. PC is 0xfffffffc */
2426 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2432 return target->type->write_buffer(target, address, size, buffer);
2435 static int target_write_buffer_default(struct target *target,
2436 target_addr_t address, uint32_t count, const uint8_t *buffer)
2439 unsigned int data_bytes = target_data_bits(target) / 8;
2441 /* Align up to maximum bytes. The loop condition makes sure the next pass
2442 * will have something to do with the size we leave to it. */
2444 size < data_bytes && count >= size * 2 + (address & size);
2446 if (address & size) {
2447 int retval = target_write_memory(target, address, size, 1, buffer);
2448 if (retval != ERROR_OK)
2456 /* Write the data with as large access size as possible. */
2457 for (; size > 0; size /= 2) {
2458 uint32_t aligned = count - count % size;
2460 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2461 if (retval != ERROR_OK)
2472 /* Single aligned words are guaranteed to use 16 or 32 bit access
2473 * mode respectively, otherwise data is handled as quickly as
2476 int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
2478 LOG_DEBUG("reading buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2481 if (!target_was_examined(target)) {
2482 LOG_ERROR("Target not examined yet");
2489 if ((address + size - 1) < address) {
2490 /* GDB can request this when e.g. PC is 0xfffffffc */
2491 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2497 return target->type->read_buffer(target, address, size, buffer);
2500 static int target_read_buffer_default(struct target *target, target_addr_t address, uint32_t count, uint8_t *buffer)
2503 unsigned int data_bytes = target_data_bits(target) / 8;
2505 /* Align up to maximum bytes. The loop condition makes sure the next pass
2506 * will have something to do with the size we leave to it. */
2508 size < data_bytes && count >= size * 2 + (address & size);
2510 if (address & size) {
2511 int retval = target_read_memory(target, address, size, 1, buffer);
2512 if (retval != ERROR_OK)
2520 /* Read the data with as large access size as possible. */
2521 for (; size > 0; size /= 2) {
2522 uint32_t aligned = count - count % size;
2524 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2525 if (retval != ERROR_OK)
2536 int target_checksum_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t *crc)
2541 uint32_t checksum = 0;
2542 if (!target_was_examined(target)) {
2543 LOG_ERROR("Target not examined yet");
2546 if (!target->type->checksum_memory) {
2547 LOG_ERROR("Target %s doesn't support checksum_memory", target_name(target));
2551 retval = target->type->checksum_memory(target, address, size, &checksum);
2552 if (retval != ERROR_OK) {
2553 buffer = malloc(size);
2555 LOG_ERROR("error allocating buffer for section (%" PRIu32 " bytes)", size);
2556 return ERROR_COMMAND_SYNTAX_ERROR;
2558 retval = target_read_buffer(target, address, size, buffer);
2559 if (retval != ERROR_OK) {
2564 /* convert to target endianness */
2565 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2566 uint32_t target_data;
2567 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2568 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2571 retval = image_calculate_checksum(buffer, size, &checksum);
2580 int target_blank_check_memory(struct target *target,
2581 struct target_memory_check_block *blocks, int num_blocks,
2582 uint8_t erased_value)
2584 if (!target_was_examined(target)) {
2585 LOG_ERROR("Target not examined yet");
2589 if (!target->type->blank_check_memory)
2590 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2592 return target->type->blank_check_memory(target, blocks, num_blocks, erased_value);
2595 int target_read_u64(struct target *target, target_addr_t address, uint64_t *value)
2597 uint8_t value_buf[8];
2598 if (!target_was_examined(target)) {
2599 LOG_ERROR("Target not examined yet");
2603 int retval = target_read_memory(target, address, 8, 1, value_buf);
2605 if (retval == ERROR_OK) {
2606 *value = target_buffer_get_u64(target, value_buf);
2607 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2612 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2619 int target_read_u32(struct target *target, target_addr_t address, uint32_t *value)
2621 uint8_t value_buf[4];
2622 if (!target_was_examined(target)) {
2623 LOG_ERROR("Target not examined yet");
2627 int retval = target_read_memory(target, address, 4, 1, value_buf);
2629 if (retval == ERROR_OK) {
2630 *value = target_buffer_get_u32(target, value_buf);
2631 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2636 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2643 int target_read_u16(struct target *target, target_addr_t address, uint16_t *value)
2645 uint8_t value_buf[2];
2646 if (!target_was_examined(target)) {
2647 LOG_ERROR("Target not examined yet");
2651 int retval = target_read_memory(target, address, 2, 1, value_buf);
2653 if (retval == ERROR_OK) {
2654 *value = target_buffer_get_u16(target, value_buf);
2655 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%4.4" PRIx16,
2660 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2667 int target_read_u8(struct target *target, target_addr_t address, uint8_t *value)
2669 if (!target_was_examined(target)) {
2670 LOG_ERROR("Target not examined yet");
2674 int retval = target_read_memory(target, address, 1, 1, value);
2676 if (retval == ERROR_OK) {
2677 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2682 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2689 int target_write_u64(struct target *target, target_addr_t address, uint64_t value)
2692 uint8_t value_buf[8];
2693 if (!target_was_examined(target)) {
2694 LOG_ERROR("Target not examined yet");
2698 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2702 target_buffer_set_u64(target, value_buf, value);
2703 retval = target_write_memory(target, address, 8, 1, value_buf);
2704 if (retval != ERROR_OK)
2705 LOG_DEBUG("failed: %i", retval);
2710 int target_write_u32(struct target *target, target_addr_t address, uint32_t value)
2713 uint8_t value_buf[4];
2714 if (!target_was_examined(target)) {
2715 LOG_ERROR("Target not examined yet");
2719 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2723 target_buffer_set_u32(target, value_buf, value);
2724 retval = target_write_memory(target, address, 4, 1, value_buf);
2725 if (retval != ERROR_OK)
2726 LOG_DEBUG("failed: %i", retval);
2731 int target_write_u16(struct target *target, target_addr_t address, uint16_t value)
2734 uint8_t value_buf[2];
2735 if (!target_was_examined(target)) {
2736 LOG_ERROR("Target not examined yet");
2740 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2744 target_buffer_set_u16(target, value_buf, value);
2745 retval = target_write_memory(target, address, 2, 1, value_buf);
2746 if (retval != ERROR_OK)
2747 LOG_DEBUG("failed: %i", retval);
2752 int target_write_u8(struct target *target, target_addr_t address, uint8_t value)
2755 if (!target_was_examined(target)) {
2756 LOG_ERROR("Target not examined yet");
2760 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2763 retval = target_write_memory(target, address, 1, 1, &value);
2764 if (retval != ERROR_OK)
2765 LOG_DEBUG("failed: %i", retval);
2770 int target_write_phys_u64(struct target *target, target_addr_t address, uint64_t value)
2773 uint8_t value_buf[8];
2774 if (!target_was_examined(target)) {
2775 LOG_ERROR("Target not examined yet");
2779 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2783 target_buffer_set_u64(target, value_buf, value);
2784 retval = target_write_phys_memory(target, address, 8, 1, value_buf);
2785 if (retval != ERROR_OK)
2786 LOG_DEBUG("failed: %i", retval);
2791 int target_write_phys_u32(struct target *target, target_addr_t address, uint32_t value)
2794 uint8_t value_buf[4];
2795 if (!target_was_examined(target)) {
2796 LOG_ERROR("Target not examined yet");
2800 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2804 target_buffer_set_u32(target, value_buf, value);
2805 retval = target_write_phys_memory(target, address, 4, 1, value_buf);
2806 if (retval != ERROR_OK)
2807 LOG_DEBUG("failed: %i", retval);
2812 int target_write_phys_u16(struct target *target, target_addr_t address, uint16_t value)
2815 uint8_t value_buf[2];
2816 if (!target_was_examined(target)) {
2817 LOG_ERROR("Target not examined yet");
2821 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2825 target_buffer_set_u16(target, value_buf, value);
2826 retval = target_write_phys_memory(target, address, 2, 1, value_buf);
2827 if (retval != ERROR_OK)
2828 LOG_DEBUG("failed: %i", retval);
2833 int target_write_phys_u8(struct target *target, target_addr_t address, uint8_t value)
2836 if (!target_was_examined(target)) {
2837 LOG_ERROR("Target not examined yet");
2841 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2844 retval = target_write_phys_memory(target, address, 1, 1, &value);
2845 if (retval != ERROR_OK)
2846 LOG_DEBUG("failed: %i", retval);
2851 static int find_target(struct command_invocation *cmd, const char *name)
2853 struct target *target = get_target(name);
2855 command_print(cmd, "Target: %s is unknown, try one of:\n", name);
2858 if (!target->tap->enabled) {
2859 command_print(cmd, "Target: TAP %s is disabled, "
2860 "can't be the current target\n",
2861 target->tap->dotted_name);
2865 cmd->ctx->current_target = target;
2866 if (cmd->ctx->current_target_override)
2867 cmd->ctx->current_target_override = target;
2873 COMMAND_HANDLER(handle_targets_command)
2875 int retval = ERROR_OK;
2876 if (CMD_ARGC == 1) {
2877 retval = find_target(CMD, CMD_ARGV[0]);
2878 if (retval == ERROR_OK) {
2884 struct target *target = all_targets;
2885 command_print(CMD, " TargetName Type Endian TapName State ");
2886 command_print(CMD, "-- ------------------ ---------- ------ ------------------ ------------");
2891 if (target->tap->enabled)
2892 state = target_state_name(target);
2894 state = "tap-disabled";
2896 if (CMD_CTX->current_target == target)
2899 /* keep columns lined up to match the headers above */
2901 "%2d%c %-18s %-10s %-6s %-18s %s",
2902 target->target_number,
2904 target_name(target),
2905 target_type_name(target),
2906 jim_nvp_value2name_simple(nvp_target_endian,
2907 target->endianness)->name,
2908 target->tap->dotted_name,
2910 target = target->next;
2916 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2918 static int power_dropout;
2919 static int srst_asserted;
2921 static int run_power_restore;
2922 static int run_power_dropout;
2923 static int run_srst_asserted;
2924 static int run_srst_deasserted;
2926 static int sense_handler(void)
2928 static int prev_srst_asserted;
2929 static int prev_power_dropout;
2931 int retval = jtag_power_dropout(&power_dropout);
2932 if (retval != ERROR_OK)
2936 power_restored = prev_power_dropout && !power_dropout;
2938 run_power_restore = 1;
2940 int64_t current = timeval_ms();
2941 static int64_t last_power;
2942 bool wait_more = last_power + 2000 > current;
2943 if (power_dropout && !wait_more) {
2944 run_power_dropout = 1;
2945 last_power = current;
2948 retval = jtag_srst_asserted(&srst_asserted);
2949 if (retval != ERROR_OK)
2952 int srst_deasserted;
2953 srst_deasserted = prev_srst_asserted && !srst_asserted;
2955 static int64_t last_srst;
2956 wait_more = last_srst + 2000 > current;
2957 if (srst_deasserted && !wait_more) {
2958 run_srst_deasserted = 1;
2959 last_srst = current;
2962 if (!prev_srst_asserted && srst_asserted)
2963 run_srst_asserted = 1;
2965 prev_srst_asserted = srst_asserted;
2966 prev_power_dropout = power_dropout;
2968 if (srst_deasserted || power_restored) {
2969 /* Other than logging the event we can't do anything here.
2970 * Issuing a reset is a particularly bad idea as we might
2971 * be inside a reset already.
2978 /* process target state changes */
2979 static int handle_target(void *priv)
2981 Jim_Interp *interp = (Jim_Interp *)priv;
2982 int retval = ERROR_OK;
2984 if (!is_jtag_poll_safe()) {
2985 /* polling is disabled currently */
2989 /* we do not want to recurse here... */
2990 static int recursive;
2994 /* danger! running these procedures can trigger srst assertions and power dropouts.
2995 * We need to avoid an infinite loop/recursion here and we do that by
2996 * clearing the flags after running these events.
2998 int did_something = 0;
2999 if (run_srst_asserted) {
3000 LOG_INFO("srst asserted detected, running srst_asserted proc.");
3001 Jim_Eval(interp, "srst_asserted");
3004 if (run_srst_deasserted) {
3005 Jim_Eval(interp, "srst_deasserted");
3008 if (run_power_dropout) {
3009 LOG_INFO("Power dropout detected, running power_dropout proc.");
3010 Jim_Eval(interp, "power_dropout");
3013 if (run_power_restore) {
3014 Jim_Eval(interp, "power_restore");
3018 if (did_something) {
3019 /* clear detect flags */
3023 /* clear action flags */
3025 run_srst_asserted = 0;
3026 run_srst_deasserted = 0;
3027 run_power_restore = 0;
3028 run_power_dropout = 0;
3033 /* Poll targets for state changes unless that's globally disabled.
3034 * Skip targets that are currently disabled.
3036 for (struct target *target = all_targets;
3037 is_jtag_poll_safe() && target;
3038 target = target->next) {
3040 if (!target_was_examined(target))
3043 if (!target->tap->enabled)
3046 if (target->backoff.times > target->backoff.count) {
3047 /* do not poll this time as we failed previously */
3048 target->backoff.count++;
3051 target->backoff.count = 0;
3053 /* only poll target if we've got power and srst isn't asserted */
3054 if (!power_dropout && !srst_asserted) {
3055 /* polling may fail silently until the target has been examined */
3056 retval = target_poll(target);
3057 if (retval != ERROR_OK) {
3058 /* 100ms polling interval. Increase interval between polling up to 5000ms */
3059 if (target->backoff.times * polling_interval < 5000) {
3060 target->backoff.times *= 2;
3061 target->backoff.times++;
3064 /* Tell GDB to halt the debugger. This allows the user to
3065 * run monitor commands to handle the situation.
3067 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3069 if (target->backoff.times > 0) {
3070 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
3071 target_reset_examined(target);
3072 retval = target_examine_one(target);
3073 /* Target examination could have failed due to unstable connection,
3074 * but we set the examined flag anyway to repoll it later */
3075 if (retval != ERROR_OK) {
3076 target_set_examined(target);
3077 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
3078 target->backoff.times * polling_interval);
3083 /* Since we succeeded, we reset backoff count */
3084 target->backoff.times = 0;
3091 COMMAND_HANDLER(handle_reg_command)
3095 struct target *target = get_current_target(CMD_CTX);
3096 struct reg *reg = NULL;
3098 /* list all available registers for the current target */
3099 if (CMD_ARGC == 0) {
3100 struct reg_cache *cache = target->reg_cache;
3102 unsigned int count = 0;
3106 command_print(CMD, "===== %s", cache->name);
3108 for (i = 0, reg = cache->reg_list;
3109 i < cache->num_regs;
3110 i++, reg++, count++) {
3111 if (reg->exist == false || reg->hidden)
3113 /* only print cached values if they are valid */
3115 char *value = buf_to_hex_str(reg->value,
3118 "(%i) %s (/%" PRIu32 "): 0x%s%s",
3126 command_print(CMD, "(%i) %s (/%" PRIu32 ")",
3131 cache = cache->next;
3137 /* access a single register by its ordinal number */
3138 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
3140 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
3142 struct reg_cache *cache = target->reg_cache;
3143 unsigned int count = 0;
3146 for (i = 0; i < cache->num_regs; i++) {
3147 if (count++ == num) {
3148 reg = &cache->reg_list[i];
3154 cache = cache->next;
3158 command_print(CMD, "%i is out of bounds, the current target "
3159 "has only %i registers (0 - %i)", num, count, count - 1);
3163 /* access a single register by its name */
3164 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], true);
3170 assert(reg); /* give clang a hint that we *know* reg is != NULL here */
3175 /* display a register */
3176 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
3177 && (CMD_ARGV[1][0] <= '9')))) {
3178 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
3181 if (reg->valid == 0) {
3182 int retval = reg->type->get(reg);
3183 if (retval != ERROR_OK) {
3184 LOG_ERROR("Could not read register '%s'", reg->name);
3188 char *value = buf_to_hex_str(reg->value, reg->size);
3189 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3194 /* set register value */
3195 if (CMD_ARGC == 2) {
3196 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
3199 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
3201 int retval = reg->type->set(reg, buf);
3202 if (retval != ERROR_OK) {
3203 LOG_ERROR("Could not write to register '%s'", reg->name);
3205 char *value = buf_to_hex_str(reg->value, reg->size);
3206 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3215 return ERROR_COMMAND_SYNTAX_ERROR;
3218 command_print(CMD, "register %s not found in current target", CMD_ARGV[0]);
3222 COMMAND_HANDLER(handle_poll_command)
3224 int retval = ERROR_OK;
3225 struct target *target = get_current_target(CMD_CTX);
3227 if (CMD_ARGC == 0) {
3228 command_print(CMD, "background polling: %s",
3229 jtag_poll_get_enabled() ? "on" : "off");
3230 command_print(CMD, "TAP: %s (%s)",
3231 target->tap->dotted_name,
3232 target->tap->enabled ? "enabled" : "disabled");
3233 if (!target->tap->enabled)
3235 retval = target_poll(target);
3236 if (retval != ERROR_OK)
3238 retval = target_arch_state(target);
3239 if (retval != ERROR_OK)
3241 } else if (CMD_ARGC == 1) {
3243 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
3244 jtag_poll_set_enabled(enable);
3246 return ERROR_COMMAND_SYNTAX_ERROR;
3251 COMMAND_HANDLER(handle_wait_halt_command)
3254 return ERROR_COMMAND_SYNTAX_ERROR;
3256 unsigned ms = DEFAULT_HALT_TIMEOUT;
3257 if (1 == CMD_ARGC) {
3258 int retval = parse_uint(CMD_ARGV[0], &ms);
3259 if (retval != ERROR_OK)
3260 return ERROR_COMMAND_SYNTAX_ERROR;
3263 struct target *target = get_current_target(CMD_CTX);
3264 return target_wait_state(target, TARGET_HALTED, ms);
3267 /* wait for target state to change. The trick here is to have a low
3268 * latency for short waits and not to suck up all the CPU time
3271 * After 500ms, keep_alive() is invoked
3273 int target_wait_state(struct target *target, enum target_state state, int ms)
3276 int64_t then = 0, cur;
3280 retval = target_poll(target);
3281 if (retval != ERROR_OK)
3283 if (target->state == state)
3288 then = timeval_ms();
3289 LOG_DEBUG("waiting for target %s...",
3290 jim_nvp_value2name_simple(nvp_target_state, state)->name);
3296 if ((cur-then) > ms) {
3297 LOG_ERROR("timed out while waiting for target %s",
3298 jim_nvp_value2name_simple(nvp_target_state, state)->name);
3306 COMMAND_HANDLER(handle_halt_command)
3310 struct target *target = get_current_target(CMD_CTX);
3312 target->verbose_halt_msg = true;
3314 int retval = target_halt(target);
3315 if (retval != ERROR_OK)
3318 if (CMD_ARGC == 1) {
3319 unsigned wait_local;
3320 retval = parse_uint(CMD_ARGV[0], &wait_local);
3321 if (retval != ERROR_OK)
3322 return ERROR_COMMAND_SYNTAX_ERROR;
3327 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
3330 COMMAND_HANDLER(handle_soft_reset_halt_command)
3332 struct target *target = get_current_target(CMD_CTX);
3334 LOG_USER("requesting target halt and executing a soft reset");
3336 target_soft_reset_halt(target);
3341 COMMAND_HANDLER(handle_reset_command)
3344 return ERROR_COMMAND_SYNTAX_ERROR;
3346 enum target_reset_mode reset_mode = RESET_RUN;
3347 if (CMD_ARGC == 1) {
3348 const struct jim_nvp *n;
3349 n = jim_nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
3350 if ((!n->name) || (n->value == RESET_UNKNOWN))
3351 return ERROR_COMMAND_SYNTAX_ERROR;
3352 reset_mode = n->value;
3355 /* reset *all* targets */
3356 return target_process_reset(CMD, reset_mode);
3360 COMMAND_HANDLER(handle_resume_command)
3364 return ERROR_COMMAND_SYNTAX_ERROR;
3366 struct target *target = get_current_target(CMD_CTX);
3368 /* with no CMD_ARGV, resume from current pc, addr = 0,
3369 * with one arguments, addr = CMD_ARGV[0],
3370 * handle breakpoints, not debugging */
3371 target_addr_t addr = 0;
3372 if (CMD_ARGC == 1) {
3373 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3377 return target_resume(target, current, addr, 1, 0);
3380 COMMAND_HANDLER(handle_step_command)
3383 return ERROR_COMMAND_SYNTAX_ERROR;
3387 /* with no CMD_ARGV, step from current pc, addr = 0,
3388 * with one argument addr = CMD_ARGV[0],
3389 * handle breakpoints, debugging */
3390 target_addr_t addr = 0;
3392 if (CMD_ARGC == 1) {
3393 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3397 struct target *target = get_current_target(CMD_CTX);
3399 return target_step(target, current_pc, addr, 1);
3402 void target_handle_md_output(struct command_invocation *cmd,
3403 struct target *target, target_addr_t address, unsigned size,
3404 unsigned count, const uint8_t *buffer)
3406 const unsigned line_bytecnt = 32;
3407 unsigned line_modulo = line_bytecnt / size;
3409 char output[line_bytecnt * 4 + 1];
3410 unsigned output_len = 0;
3412 const char *value_fmt;
3415 value_fmt = "%16.16"PRIx64" ";
3418 value_fmt = "%8.8"PRIx64" ";
3421 value_fmt = "%4.4"PRIx64" ";
3424 value_fmt = "%2.2"PRIx64" ";
3427 /* "can't happen", caller checked */
3428 LOG_ERROR("invalid memory read size: %u", size);
3432 for (unsigned i = 0; i < count; i++) {
3433 if (i % line_modulo == 0) {
3434 output_len += snprintf(output + output_len,
3435 sizeof(output) - output_len,
3436 TARGET_ADDR_FMT ": ",
3437 (address + (i * size)));
3441 const uint8_t *value_ptr = buffer + i * size;
3444 value = target_buffer_get_u64(target, value_ptr);
3447 value = target_buffer_get_u32(target, value_ptr);
3450 value = target_buffer_get_u16(target, value_ptr);
3455 output_len += snprintf(output + output_len,
3456 sizeof(output) - output_len,
3459 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
3460 command_print(cmd, "%s", output);
3466 COMMAND_HANDLER(handle_md_command)
3469 return ERROR_COMMAND_SYNTAX_ERROR;
3472 switch (CMD_NAME[2]) {
3486 return ERROR_COMMAND_SYNTAX_ERROR;
3489 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3490 int (*fn)(struct target *target,
3491 target_addr_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
3495 fn = target_read_phys_memory;
3497 fn = target_read_memory;
3498 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
3499 return ERROR_COMMAND_SYNTAX_ERROR;
3501 target_addr_t address;
3502 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3506 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3508 uint8_t *buffer = calloc(count, size);
3510 LOG_ERROR("Failed to allocate md read buffer");
3514 struct target *target = get_current_target(CMD_CTX);
3515 int retval = fn(target, address, size, count, buffer);
3516 if (retval == ERROR_OK)
3517 target_handle_md_output(CMD, target, address, size, count, buffer);
3524 typedef int (*target_write_fn)(struct target *target,
3525 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3527 static int target_fill_mem(struct target *target,
3528 target_addr_t address,
3536 /* We have to write in reasonably large chunks to be able
3537 * to fill large memory areas with any sane speed */
3538 const unsigned chunk_size = 16384;
3539 uint8_t *target_buf = malloc(chunk_size * data_size);
3541 LOG_ERROR("Out of memory");
3545 for (unsigned i = 0; i < chunk_size; i++) {
3546 switch (data_size) {
3548 target_buffer_set_u64(target, target_buf + i * data_size, b);
3551 target_buffer_set_u32(target, target_buf + i * data_size, b);
3554 target_buffer_set_u16(target, target_buf + i * data_size, b);
3557 target_buffer_set_u8(target, target_buf + i * data_size, b);
3564 int retval = ERROR_OK;
3566 for (unsigned x = 0; x < c; x += chunk_size) {
3569 if (current > chunk_size)
3570 current = chunk_size;
3571 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3572 if (retval != ERROR_OK)
3574 /* avoid GDB timeouts */
3583 COMMAND_HANDLER(handle_mw_command)
3586 return ERROR_COMMAND_SYNTAX_ERROR;
3587 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3592 fn = target_write_phys_memory;
3594 fn = target_write_memory;
3595 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3596 return ERROR_COMMAND_SYNTAX_ERROR;
3598 target_addr_t address;
3599 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3602 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[1], value);
3606 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3608 struct target *target = get_current_target(CMD_CTX);
3610 switch (CMD_NAME[2]) {
3624 return ERROR_COMMAND_SYNTAX_ERROR;
3627 return target_fill_mem(target, address, fn, wordsize, value, count);
3630 static COMMAND_HELPER(parse_load_image_command, struct image *image,
3631 target_addr_t *min_address, target_addr_t *max_address)
3633 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3634 return ERROR_COMMAND_SYNTAX_ERROR;
3636 /* a base address isn't always necessary,
3637 * default to 0x0 (i.e. don't relocate) */
3638 if (CMD_ARGC >= 2) {
3640 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3641 image->base_address = addr;
3642 image->base_address_set = true;
3644 image->base_address_set = false;
3646 image->start_address_set = false;
3649 COMMAND_PARSE_ADDRESS(CMD_ARGV[3], *min_address);
3650 if (CMD_ARGC == 5) {
3651 COMMAND_PARSE_ADDRESS(CMD_ARGV[4], *max_address);
3652 /* use size (given) to find max (required) */
3653 *max_address += *min_address;
3656 if (*min_address > *max_address)
3657 return ERROR_COMMAND_SYNTAX_ERROR;
3662 COMMAND_HANDLER(handle_load_image_command)
3666 uint32_t image_size;
3667 target_addr_t min_address = 0;
3668 target_addr_t max_address = -1;
3671 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
3672 &image, &min_address, &max_address);
3673 if (retval != ERROR_OK)
3676 struct target *target = get_current_target(CMD_CTX);
3678 struct duration bench;
3679 duration_start(&bench);
3681 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3686 for (unsigned int i = 0; i < image.num_sections; i++) {
3687 buffer = malloc(image.sections[i].size);
3690 "error allocating buffer for section (%d bytes)",
3691 (int)(image.sections[i].size));
3692 retval = ERROR_FAIL;
3696 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3697 if (retval != ERROR_OK) {
3702 uint32_t offset = 0;
3703 uint32_t length = buf_cnt;
3705 /* DANGER!!! beware of unsigned comparison here!!! */
3707 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3708 (image.sections[i].base_address < max_address)) {
3710 if (image.sections[i].base_address < min_address) {
3711 /* clip addresses below */
3712 offset += min_address-image.sections[i].base_address;
3716 if (image.sections[i].base_address + buf_cnt > max_address)
3717 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3719 retval = target_write_buffer(target,
3720 image.sections[i].base_address + offset, length, buffer + offset);
3721 if (retval != ERROR_OK) {
3725 image_size += length;
3726 command_print(CMD, "%u bytes written at address " TARGET_ADDR_FMT "",
3727 (unsigned int)length,
3728 image.sections[i].base_address + offset);
3734 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3735 command_print(CMD, "downloaded %" PRIu32 " bytes "
3736 "in %fs (%0.3f KiB/s)", image_size,
3737 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3740 image_close(&image);
3746 COMMAND_HANDLER(handle_dump_image_command)
3748 struct fileio *fileio;
3750 int retval, retvaltemp;
3751 target_addr_t address, size;
3752 struct duration bench;
3753 struct target *target = get_current_target(CMD_CTX);
3756 return ERROR_COMMAND_SYNTAX_ERROR;
3758 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], address);
3759 COMMAND_PARSE_ADDRESS(CMD_ARGV[2], size);
3761 uint32_t buf_size = (size > 4096) ? 4096 : size;
3762 buffer = malloc(buf_size);
3766 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3767 if (retval != ERROR_OK) {
3772 duration_start(&bench);
3775 size_t size_written;
3776 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3777 retval = target_read_buffer(target, address, this_run_size, buffer);
3778 if (retval != ERROR_OK)
3781 retval = fileio_write(fileio, this_run_size, buffer, &size_written);
3782 if (retval != ERROR_OK)
3785 size -= this_run_size;
3786 address += this_run_size;
3791 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3793 retval = fileio_size(fileio, &filesize);
3794 if (retval != ERROR_OK)
3797 "dumped %zu bytes in %fs (%0.3f KiB/s)", filesize,
3798 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3801 retvaltemp = fileio_close(fileio);
3802 if (retvaltemp != ERROR_OK)
3811 IMAGE_CHECKSUM_ONLY = 2
3814 static COMMAND_HELPER(handle_verify_image_command_internal, enum verify_mode verify)
3818 uint32_t image_size;
3820 uint32_t checksum = 0;
3821 uint32_t mem_checksum = 0;
3825 struct target *target = get_current_target(CMD_CTX);
3828 return ERROR_COMMAND_SYNTAX_ERROR;
3831 LOG_ERROR("no target selected");
3835 struct duration bench;
3836 duration_start(&bench);
3838 if (CMD_ARGC >= 2) {
3840 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3841 image.base_address = addr;
3842 image.base_address_set = true;
3844 image.base_address_set = false;
3845 image.base_address = 0x0;
3848 image.start_address_set = false;
3850 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3851 if (retval != ERROR_OK)
3857 for (unsigned int i = 0; i < image.num_sections; i++) {
3858 buffer = malloc(image.sections[i].size);
3861 "error allocating buffer for section (%" PRIu32 " bytes)",
3862 image.sections[i].size);
3865 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3866 if (retval != ERROR_OK) {
3871 if (verify >= IMAGE_VERIFY) {
3872 /* calculate checksum of image */
3873 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3874 if (retval != ERROR_OK) {
3879 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3880 if (retval != ERROR_OK) {
3884 if ((checksum != mem_checksum) && (verify == IMAGE_CHECKSUM_ONLY)) {
3885 LOG_ERROR("checksum mismatch");
3887 retval = ERROR_FAIL;
3890 if (checksum != mem_checksum) {
3891 /* failed crc checksum, fall back to a binary compare */
3895 LOG_ERROR("checksum mismatch - attempting binary compare");
3897 data = malloc(buf_cnt);
3899 retval = target_read_buffer(target, image.sections[i].base_address, buf_cnt, data);
3900 if (retval == ERROR_OK) {
3902 for (t = 0; t < buf_cnt; t++) {
3903 if (data[t] != buffer[t]) {
3905 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3907 (unsigned)(t + image.sections[i].base_address),
3910 if (diffs++ >= 127) {
3911 command_print(CMD, "More than 128 errors, the rest are not printed.");
3923 command_print(CMD, "address " TARGET_ADDR_FMT " length 0x%08zx",
3924 image.sections[i].base_address,
3929 image_size += buf_cnt;
3932 command_print(CMD, "No more differences found.");
3935 retval = ERROR_FAIL;
3936 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3937 command_print(CMD, "verified %" PRIu32 " bytes "
3938 "in %fs (%0.3f KiB/s)", image_size,
3939 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3942 image_close(&image);
3947 COMMAND_HANDLER(handle_verify_image_checksum_command)
3949 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_CHECKSUM_ONLY);
3952 COMMAND_HANDLER(handle_verify_image_command)
3954 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_VERIFY);
3957 COMMAND_HANDLER(handle_test_image_command)
3959 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_TEST);
3962 static int handle_bp_command_list(struct command_invocation *cmd)
3964 struct target *target = get_current_target(cmd->ctx);
3965 struct breakpoint *breakpoint = target->breakpoints;
3966 while (breakpoint) {
3967 if (breakpoint->type == BKPT_SOFT) {
3968 char *buf = buf_to_hex_str(breakpoint->orig_instr,
3969 breakpoint->length);
3970 command_print(cmd, "IVA breakpoint: " TARGET_ADDR_FMT ", 0x%x, %i, 0x%s",
3971 breakpoint->address,
3973 breakpoint->set, buf);
3976 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3977 command_print(cmd, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3979 breakpoint->length, breakpoint->set);
3980 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3981 command_print(cmd, "Hybrid breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3982 breakpoint->address,
3983 breakpoint->length, breakpoint->set);
3984 command_print(cmd, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3987 command_print(cmd, "Breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3988 breakpoint->address,
3989 breakpoint->length, breakpoint->set);
3992 breakpoint = breakpoint->next;
3997 static int handle_bp_command_set(struct command_invocation *cmd,
3998 target_addr_t addr, uint32_t asid, uint32_t length, int hw)
4000 struct target *target = get_current_target(cmd->ctx);
4004 retval = breakpoint_add(target, addr, length, hw);
4005 /* error is always logged in breakpoint_add(), do not print it again */
4006 if (retval == ERROR_OK)
4007 command_print(cmd, "breakpoint set at " TARGET_ADDR_FMT "", addr);
4009 } else if (addr == 0) {
4010 if (!target->type->add_context_breakpoint) {
4011 LOG_ERROR("Context breakpoint not available");
4012 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
4014 retval = context_breakpoint_add(target, asid, length, hw);
4015 /* error is always logged in context_breakpoint_add(), do not print it again */
4016 if (retval == ERROR_OK)
4017 command_print(cmd, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
4020 if (!target->type->add_hybrid_breakpoint) {
4021 LOG_ERROR("Hybrid breakpoint not available");
4022 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
4024 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
4025 /* error is always logged in hybrid_breakpoint_add(), do not print it again */
4026 if (retval == ERROR_OK)
4027 command_print(cmd, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
4032 COMMAND_HANDLER(handle_bp_command)
4041 return handle_bp_command_list(CMD);
4045 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4046 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4047 return handle_bp_command_set(CMD, addr, asid, length, hw);
4050 if (strcmp(CMD_ARGV[2], "hw") == 0) {
4052 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4053 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4055 return handle_bp_command_set(CMD, addr, asid, length, hw);
4056 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
4058 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
4059 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4061 return handle_bp_command_set(CMD, addr, asid, length, hw);
4066 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4067 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
4068 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
4069 return handle_bp_command_set(CMD, addr, asid, length, hw);
4072 return ERROR_COMMAND_SYNTAX_ERROR;
4076 COMMAND_HANDLER(handle_rbp_command)
4079 return ERROR_COMMAND_SYNTAX_ERROR;
4081 struct target *target = get_current_target(CMD_CTX);
4083 if (!strcmp(CMD_ARGV[0], "all")) {
4084 breakpoint_remove_all(target);
4087 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4089 breakpoint_remove(target, addr);
4095 COMMAND_HANDLER(handle_wp_command)
4097 struct target *target = get_current_target(CMD_CTX);
4099 if (CMD_ARGC == 0) {
4100 struct watchpoint *watchpoint = target->watchpoints;
4102 while (watchpoint) {
4103 command_print(CMD, "address: " TARGET_ADDR_FMT
4104 ", len: 0x%8.8" PRIx32
4105 ", r/w/a: %i, value: 0x%8.8" PRIx32
4106 ", mask: 0x%8.8" PRIx32,
4107 watchpoint->address,
4109 (int)watchpoint->rw,
4112 watchpoint = watchpoint->next;
4117 enum watchpoint_rw type = WPT_ACCESS;
4118 target_addr_t addr = 0;
4119 uint32_t length = 0;
4120 uint32_t data_value = 0x0;
4121 uint32_t data_mask = 0xffffffff;
4125 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
4128 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
4131 switch (CMD_ARGV[2][0]) {
4142 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
4143 return ERROR_COMMAND_SYNTAX_ERROR;
4147 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4148 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4152 return ERROR_COMMAND_SYNTAX_ERROR;
4155 int retval = watchpoint_add(target, addr, length, type,
4156 data_value, data_mask);
4157 if (retval != ERROR_OK)
4158 LOG_ERROR("Failure setting watchpoints");
4163 COMMAND_HANDLER(handle_rwp_command)
4166 return ERROR_COMMAND_SYNTAX_ERROR;
4169 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4171 struct target *target = get_current_target(CMD_CTX);
4172 watchpoint_remove(target, addr);
4178 * Translate a virtual address to a physical address.
4180 * The low-level target implementation must have logged a detailed error
4181 * which is forwarded to telnet/GDB session.
4183 COMMAND_HANDLER(handle_virt2phys_command)
4186 return ERROR_COMMAND_SYNTAX_ERROR;
4189 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], va);
4192 struct target *target = get_current_target(CMD_CTX);
4193 int retval = target->type->virt2phys(target, va, &pa);
4194 if (retval == ERROR_OK)
4195 command_print(CMD, "Physical address " TARGET_ADDR_FMT "", pa);
4200 static void write_data(FILE *f, const void *data, size_t len)
4202 size_t written = fwrite(data, 1, len, f);
4204 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
4207 static void write_long(FILE *f, int l, struct target *target)
4211 target_buffer_set_u32(target, val, l);
4212 write_data(f, val, 4);
4215 static void write_string(FILE *f, char *s)
4217 write_data(f, s, strlen(s));
4220 typedef unsigned char UNIT[2]; /* unit of profiling */
4222 /* Dump a gmon.out histogram file. */
4223 static void write_gmon(uint32_t *samples, uint32_t sample_num, const char *filename, bool with_range,
4224 uint32_t start_address, uint32_t end_address, struct target *target, uint32_t duration_ms)
4227 FILE *f = fopen(filename, "w");
4230 write_string(f, "gmon");
4231 write_long(f, 0x00000001, target); /* Version */
4232 write_long(f, 0, target); /* padding */
4233 write_long(f, 0, target); /* padding */
4234 write_long(f, 0, target); /* padding */
4236 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
4237 write_data(f, &zero, 1);
4239 /* figure out bucket size */
4243 min = start_address;
4248 for (i = 0; i < sample_num; i++) {
4249 if (min > samples[i])
4251 if (max < samples[i])
4255 /* max should be (largest sample + 1)
4256 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
4260 int address_space = max - min;
4261 assert(address_space >= 2);
4263 /* FIXME: What is the reasonable number of buckets?
4264 * The profiling result will be more accurate if there are enough buckets. */
4265 static const uint32_t max_buckets = 128 * 1024; /* maximum buckets. */
4266 uint32_t num_buckets = address_space / sizeof(UNIT);
4267 if (num_buckets > max_buckets)
4268 num_buckets = max_buckets;
4269 int *buckets = malloc(sizeof(int) * num_buckets);
4274 memset(buckets, 0, sizeof(int) * num_buckets);
4275 for (i = 0; i < sample_num; i++) {
4276 uint32_t address = samples[i];
4278 if ((address < min) || (max <= address))
4281 long long a = address - min;
4282 long long b = num_buckets;
4283 long long c = address_space;
4284 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
4288 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
4289 write_long(f, min, target); /* low_pc */
4290 write_long(f, max, target); /* high_pc */
4291 write_long(f, num_buckets, target); /* # of buckets */
4292 float sample_rate = sample_num / (duration_ms / 1000.0);
4293 write_long(f, sample_rate, target);
4294 write_string(f, "seconds");
4295 for (i = 0; i < (15-strlen("seconds")); i++)
4296 write_data(f, &zero, 1);
4297 write_string(f, "s");
4299 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
4301 char *data = malloc(2 * num_buckets);
4303 for (i = 0; i < num_buckets; i++) {
4308 data[i * 2] = val&0xff;
4309 data[i * 2 + 1] = (val >> 8) & 0xff;
4312 write_data(f, data, num_buckets * 2);
4320 /* profiling samples the CPU PC as quickly as OpenOCD is able,
4321 * which will be used as a random sampling of PC */
4322 COMMAND_HANDLER(handle_profile_command)
4324 struct target *target = get_current_target(CMD_CTX);
4326 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
4327 return ERROR_COMMAND_SYNTAX_ERROR;
4329 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
4331 uint32_t num_of_samples;
4332 int retval = ERROR_OK;
4333 bool halted_before_profiling = target->state == TARGET_HALTED;
4335 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
4337 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
4339 LOG_ERROR("No memory to store samples.");
4343 uint64_t timestart_ms = timeval_ms();
4345 * Some cores let us sample the PC without the
4346 * annoying halt/resume step; for example, ARMv7 PCSR.
4347 * Provide a way to use that more efficient mechanism.
4349 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
4350 &num_of_samples, offset);
4351 if (retval != ERROR_OK) {
4355 uint32_t duration_ms = timeval_ms() - timestart_ms;
4357 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
4359 retval = target_poll(target);
4360 if (retval != ERROR_OK) {
4365 if (target->state == TARGET_RUNNING && halted_before_profiling) {
4366 /* The target was halted before we started and is running now. Halt it,
4367 * for consistency. */
4368 retval = target_halt(target);
4369 if (retval != ERROR_OK) {
4373 } else if (target->state == TARGET_HALTED && !halted_before_profiling) {
4374 /* The target was running before we started and is halted now. Resume
4375 * it, for consistency. */
4376 retval = target_resume(target, 1, 0, 0, 0);
4377 if (retval != ERROR_OK) {
4383 retval = target_poll(target);
4384 if (retval != ERROR_OK) {
4389 uint32_t start_address = 0;
4390 uint32_t end_address = 0;
4391 bool with_range = false;
4392 if (CMD_ARGC == 4) {
4394 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
4395 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
4398 write_gmon(samples, num_of_samples, CMD_ARGV[1],
4399 with_range, start_address, end_address, target, duration_ms);
4400 command_print(CMD, "Wrote %s", CMD_ARGV[1]);
4406 static int new_u64_array_element(Jim_Interp *interp, const char *varname, int idx, uint64_t val)
4409 Jim_Obj *obj_name, *obj_val;
4412 namebuf = alloc_printf("%s(%d)", varname, idx);
4416 obj_name = Jim_NewStringObj(interp, namebuf, -1);
4417 jim_wide wide_val = val;
4418 obj_val = Jim_NewWideObj(interp, wide_val);
4419 if (!obj_name || !obj_val) {
4424 Jim_IncrRefCount(obj_name);
4425 Jim_IncrRefCount(obj_val);
4426 result = Jim_SetVariable(interp, obj_name, obj_val);
4427 Jim_DecrRefCount(interp, obj_name);
4428 Jim_DecrRefCount(interp, obj_val);
4430 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
4434 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
4438 LOG_WARNING("DEPRECATED! use 'read_memory' not 'mem2array'");
4440 /* argv[0] = name of array to receive the data
4441 * argv[1] = desired element width in bits
4442 * argv[2] = memory address
4443 * argv[3] = count of times to read
4444 * argv[4] = optional "phys"
4446 if (argc < 4 || argc > 5) {
4447 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4451 /* Arg 0: Name of the array variable */
4452 const char *varname = Jim_GetString(argv[0], NULL);
4454 /* Arg 1: Bit width of one element */
4456 e = Jim_GetLong(interp, argv[1], &l);
4459 const unsigned int width_bits = l;
4461 if (width_bits != 8 &&
4465 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4466 Jim_AppendStrings(interp, Jim_GetResult(interp),
4467 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4470 const unsigned int width = width_bits / 8;
4472 /* Arg 2: Memory address */
4474 e = Jim_GetWide(interp, argv[2], &wide_addr);
4477 target_addr_t addr = (target_addr_t)wide_addr;
4479 /* Arg 3: Number of elements to read */
4480 e = Jim_GetLong(interp, argv[3], &l);
4486 bool is_phys = false;
4489 const char *phys = Jim_GetString(argv[4], &str_len);
4490 if (!strncmp(phys, "phys", str_len))
4496 /* Argument checks */
4498 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4499 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
4502 if ((addr + (len * width)) < addr) {
4503 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4504 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
4508 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4509 Jim_AppendStrings(interp, Jim_GetResult(interp),
4510 "mem2array: too large read request, exceeds 64K items", NULL);
4515 ((width == 2) && ((addr & 1) == 0)) ||
4516 ((width == 4) && ((addr & 3) == 0)) ||
4517 ((width == 8) && ((addr & 7) == 0))) {
4518 /* alignment correct */
4521 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4522 sprintf(buf, "mem2array address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4525 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4534 const size_t buffersize = 4096;
4535 uint8_t *buffer = malloc(buffersize);
4542 /* Slurp... in buffer size chunks */
4543 const unsigned int max_chunk_len = buffersize / width;
4544 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4548 retval = target_read_phys_memory(target, addr, width, chunk_len, buffer);
4550 retval = target_read_memory(target, addr, width, chunk_len, buffer);
4551 if (retval != ERROR_OK) {
4553 LOG_ERROR("mem2array: Read @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4557 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4558 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
4562 for (size_t i = 0; i < chunk_len ; i++, idx++) {
4566 v = target_buffer_get_u64(target, &buffer[i*width]);
4569 v = target_buffer_get_u32(target, &buffer[i*width]);
4572 v = target_buffer_get_u16(target, &buffer[i*width]);
4575 v = buffer[i] & 0x0ff;
4578 new_u64_array_element(interp, varname, idx, v);
4581 addr += chunk_len * width;
4587 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4592 static int target_jim_read_memory(Jim_Interp *interp, int argc,
4593 Jim_Obj * const *argv)
4596 * argv[1] = memory address
4597 * argv[2] = desired element width in bits
4598 * argv[3] = number of elements to read
4599 * argv[4] = optional "phys"
4602 if (argc < 4 || argc > 5) {
4603 Jim_WrongNumArgs(interp, 1, argv, "address width count ['phys']");
4607 /* Arg 1: Memory address. */
4610 e = Jim_GetWide(interp, argv[1], &wide_addr);
4615 target_addr_t addr = (target_addr_t)wide_addr;
4617 /* Arg 2: Bit width of one element. */
4619 e = Jim_GetLong(interp, argv[2], &l);
4624 const unsigned int width_bits = l;
4626 /* Arg 3: Number of elements to read. */
4627 e = Jim_GetLong(interp, argv[3], &l);
4634 /* Arg 4: Optional 'phys'. */
4635 bool is_phys = false;
4638 const char *phys = Jim_GetString(argv[4], NULL);
4640 if (strcmp(phys, "phys")) {
4641 Jim_SetResultFormatted(interp, "invalid argument '%s', must be 'phys'", phys);
4648 switch (width_bits) {
4655 Jim_SetResultString(interp, "invalid width, must be 8, 16, 32 or 64", -1);
4659 const unsigned int width = width_bits / 8;
4661 if ((addr + (count * width)) < addr) {
4662 Jim_SetResultString(interp, "read_memory: addr + count wraps to zero", -1);
4666 if (count > 65536) {
4667 Jim_SetResultString(interp, "read_memory: too large read request, exeeds 64K elements", -1);
4671 struct command_context *cmd_ctx = current_command_context(interp);
4672 assert(cmd_ctx != NULL);
4673 struct target *target = get_current_target(cmd_ctx);
4675 const size_t buffersize = 4096;
4676 uint8_t *buffer = malloc(buffersize);
4679 LOG_ERROR("Failed to allocate memory");
4683 Jim_Obj *result_list = Jim_NewListObj(interp, NULL, 0);
4684 Jim_IncrRefCount(result_list);
4687 const unsigned int max_chunk_len = buffersize / width;
4688 const size_t chunk_len = MIN(count, max_chunk_len);
4693 retval = target_read_phys_memory(target, addr, width, chunk_len, buffer);
4695 retval = target_read_memory(target, addr, width, chunk_len, buffer);
4697 if (retval != ERROR_OK) {
4698 LOG_ERROR("read_memory: read at " TARGET_ADDR_FMT " with width=%u and count=%zu failed",
4699 addr, width_bits, chunk_len);
4700 Jim_SetResultString(interp, "read_memory: failed to read memory", -1);
4705 for (size_t i = 0; i < chunk_len ; i++) {
4710 v = target_buffer_get_u64(target, &buffer[i * width]);
4713 v = target_buffer_get_u32(target, &buffer[i * width]);
4716 v = target_buffer_get_u16(target, &buffer[i * width]);
4724 snprintf(value_buf, sizeof(value_buf), "0x%" PRIx64, v);
4726 Jim_ListAppendElement(interp, result_list,
4727 Jim_NewStringObj(interp, value_buf, -1));
4731 addr += chunk_len * width;
4737 Jim_DecrRefCount(interp, result_list);
4741 Jim_SetResult(interp, result_list);
4742 Jim_DecrRefCount(interp, result_list);
4747 static int get_u64_array_element(Jim_Interp *interp, const char *varname, size_t idx, uint64_t *val)
4749 char *namebuf = alloc_printf("%s(%zu)", varname, idx);
4753 Jim_Obj *obj_name = Jim_NewStringObj(interp, namebuf, -1);
4759 Jim_IncrRefCount(obj_name);
4760 Jim_Obj *obj_val = Jim_GetVariable(interp, obj_name, JIM_ERRMSG);
4761 Jim_DecrRefCount(interp, obj_name);
4767 int result = Jim_GetWide(interp, obj_val, &wide_val);
4772 static int target_array2mem(Jim_Interp *interp, struct target *target,
4773 int argc, Jim_Obj *const *argv)
4777 LOG_WARNING("DEPRECATED! use 'write_memory' not 'array2mem'");
4779 /* argv[0] = name of array from which to read the data
4780 * argv[1] = desired element width in bits
4781 * argv[2] = memory address
4782 * argv[3] = number of elements to write
4783 * argv[4] = optional "phys"
4785 if (argc < 4 || argc > 5) {
4786 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4790 /* Arg 0: Name of the array variable */
4791 const char *varname = Jim_GetString(argv[0], NULL);
4793 /* Arg 1: Bit width of one element */
4795 e = Jim_GetLong(interp, argv[1], &l);
4798 const unsigned int width_bits = l;
4800 if (width_bits != 8 &&
4804 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4805 Jim_AppendStrings(interp, Jim_GetResult(interp),
4806 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4809 const unsigned int width = width_bits / 8;
4811 /* Arg 2: Memory address */
4813 e = Jim_GetWide(interp, argv[2], &wide_addr);
4816 target_addr_t addr = (target_addr_t)wide_addr;
4818 /* Arg 3: Number of elements to write */
4819 e = Jim_GetLong(interp, argv[3], &l);
4825 bool is_phys = false;
4828 const char *phys = Jim_GetString(argv[4], &str_len);
4829 if (!strncmp(phys, "phys", str_len))
4835 /* Argument checks */
4837 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4838 Jim_AppendStrings(interp, Jim_GetResult(interp),
4839 "array2mem: zero width read?", NULL);
4843 if ((addr + (len * width)) < addr) {
4844 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4845 Jim_AppendStrings(interp, Jim_GetResult(interp),
4846 "array2mem: addr + len - wraps to zero?", NULL);
4851 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4852 Jim_AppendStrings(interp, Jim_GetResult(interp),
4853 "array2mem: too large memory write request, exceeds 64K items", NULL);
4858 ((width == 2) && ((addr & 1) == 0)) ||
4859 ((width == 4) && ((addr & 3) == 0)) ||
4860 ((width == 8) && ((addr & 7) == 0))) {
4861 /* alignment correct */
4864 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4865 sprintf(buf, "array2mem address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4868 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4877 const size_t buffersize = 4096;
4878 uint8_t *buffer = malloc(buffersize);
4886 /* Slurp... in buffer size chunks */
4887 const unsigned int max_chunk_len = buffersize / width;
4889 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4891 /* Fill the buffer */
4892 for (size_t i = 0; i < chunk_len; i++, idx++) {
4894 if (get_u64_array_element(interp, varname, idx, &v) != JIM_OK) {
4900 target_buffer_set_u64(target, &buffer[i * width], v);
4903 target_buffer_set_u32(target, &buffer[i * width], v);
4906 target_buffer_set_u16(target, &buffer[i * width], v);
4909 buffer[i] = v & 0x0ff;
4915 /* Write the buffer to memory */
4918 retval = target_write_phys_memory(target, addr, width, chunk_len, buffer);
4920 retval = target_write_memory(target, addr, width, chunk_len, buffer);
4921 if (retval != ERROR_OK) {
4923 LOG_ERROR("array2mem: Write @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4927 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4928 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4932 addr += chunk_len * width;
4937 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4942 static int target_jim_write_memory(Jim_Interp *interp, int argc,
4943 Jim_Obj * const *argv)
4946 * argv[1] = memory address
4947 * argv[2] = desired element width in bits
4948 * argv[3] = list of data to write
4949 * argv[4] = optional "phys"
4952 if (argc < 4 || argc > 5) {
4953 Jim_WrongNumArgs(interp, 1, argv, "address width data ['phys']");
4957 /* Arg 1: Memory address. */
4960 e = Jim_GetWide(interp, argv[1], &wide_addr);
4965 target_addr_t addr = (target_addr_t)wide_addr;
4967 /* Arg 2: Bit width of one element. */
4969 e = Jim_GetLong(interp, argv[2], &l);
4974 const unsigned int width_bits = l;
4975 size_t count = Jim_ListLength(interp, argv[3]);
4977 /* Arg 4: Optional 'phys'. */
4978 bool is_phys = false;
4981 const char *phys = Jim_GetString(argv[4], NULL);
4983 if (strcmp(phys, "phys")) {
4984 Jim_SetResultFormatted(interp, "invalid argument '%s', must be 'phys'", phys);
4991 switch (width_bits) {
4998 Jim_SetResultString(interp, "invalid width, must be 8, 16, 32 or 64", -1);
5002 const unsigned int width = width_bits / 8;
5004 if ((addr + (count * width)) < addr) {
5005 Jim_SetResultString(interp, "write_memory: addr + len wraps to zero", -1);
5009 if (count > 65536) {
5010 Jim_SetResultString(interp, "write_memory: too large memory write request, exceeds 64K elements", -1);
5014 struct command_context *cmd_ctx = current_command_context(interp);
5015 assert(cmd_ctx != NULL);
5016 struct target *target = get_current_target(cmd_ctx);
5018 const size_t buffersize = 4096;
5019 uint8_t *buffer = malloc(buffersize);
5022 LOG_ERROR("Failed to allocate memory");
5029 const unsigned int max_chunk_len = buffersize / width;
5030 const size_t chunk_len = MIN(count, max_chunk_len);
5032 for (size_t i = 0; i < chunk_len; i++, j++) {
5033 Jim_Obj *tmp = Jim_ListGetIndex(interp, argv[3], j);
5034 jim_wide element_wide;
5035 Jim_GetWide(interp, tmp, &element_wide);
5037 const uint64_t v = element_wide;
5041 target_buffer_set_u64(target, &buffer[i * width], v);
5044 target_buffer_set_u32(target, &buffer[i * width], v);
5047 target_buffer_set_u16(target, &buffer[i * width], v);
5050 buffer[i] = v & 0x0ff;
5060 retval = target_write_phys_memory(target, addr, width, chunk_len, buffer);
5062 retval = target_write_memory(target, addr, width, chunk_len, buffer);
5064 if (retval != ERROR_OK) {
5065 LOG_ERROR("write_memory: write at " TARGET_ADDR_FMT " with width=%u and count=%zu failed",
5066 addr, width_bits, chunk_len);
5067 Jim_SetResultString(interp, "write_memory: failed to write memory", -1);
5072 addr += chunk_len * width;
5080 /* FIX? should we propagate errors here rather than printing them
5083 void target_handle_event(struct target *target, enum target_event e)
5085 struct target_event_action *teap;
5088 for (teap = target->event_action; teap; teap = teap->next) {
5089 if (teap->event == e) {
5090 LOG_DEBUG("target(%d): %s (%s) event: %d (%s) action: %s",
5091 target->target_number,
5092 target_name(target),
5093 target_type_name(target),
5095 target_event_name(e),
5096 Jim_GetString(teap->body, NULL));
5098 /* Override current target by the target an event
5099 * is issued from (lot of scripts need it).
5100 * Return back to previous override as soon
5101 * as the handler processing is done */
5102 struct command_context *cmd_ctx = current_command_context(teap->interp);
5103 struct target *saved_target_override = cmd_ctx->current_target_override;
5104 cmd_ctx->current_target_override = target;
5106 retval = Jim_EvalObj(teap->interp, teap->body);
5108 cmd_ctx->current_target_override = saved_target_override;
5110 if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
5113 if (retval == JIM_RETURN)
5114 retval = teap->interp->returnCode;
5116 if (retval != JIM_OK) {
5117 Jim_MakeErrorMessage(teap->interp);
5118 LOG_USER("Error executing event %s on target %s:\n%s",
5119 target_event_name(e),
5120 target_name(target),
5121 Jim_GetString(Jim_GetResult(teap->interp), NULL));
5122 /* clean both error code and stacktrace before return */
5123 Jim_Eval(teap->interp, "error \"\" \"\"");
5129 static int target_jim_get_reg(Jim_Interp *interp, int argc,
5130 Jim_Obj * const *argv)
5135 const char *option = Jim_GetString(argv[1], NULL);
5137 if (!strcmp(option, "-force")) {
5142 Jim_SetResultFormatted(interp, "invalid option '%s'", option);
5148 Jim_WrongNumArgs(interp, 1, argv, "[-force] list");
5152 const int length = Jim_ListLength(interp, argv[1]);
5154 Jim_Obj *result_dict = Jim_NewDictObj(interp, NULL, 0);
5159 struct command_context *cmd_ctx = current_command_context(interp);
5160 assert(cmd_ctx != NULL);
5161 const struct target *target = get_current_target(cmd_ctx);
5163 for (int i = 0; i < length; i++) {
5164 Jim_Obj *elem = Jim_ListGetIndex(interp, argv[1], i);
5169 const char *reg_name = Jim_String(elem);
5171 struct reg *reg = register_get_by_name(target->reg_cache, reg_name,
5174 if (!reg || !reg->exist) {
5175 Jim_SetResultFormatted(interp, "unknown register '%s'", reg_name);
5180 int retval = reg->type->get(reg);
5182 if (retval != ERROR_OK) {
5183 Jim_SetResultFormatted(interp, "failed to read register '%s'",
5189 char *reg_value = buf_to_hex_str(reg->value, reg->size);
5192 LOG_ERROR("Failed to allocate memory");
5196 char *tmp = alloc_printf("0x%s", reg_value);
5201 LOG_ERROR("Failed to allocate memory");
5205 Jim_DictAddElement(interp, result_dict, elem,
5206 Jim_NewStringObj(interp, tmp, -1));
5211 Jim_SetResult(interp, result_dict);
5216 static int target_jim_set_reg(Jim_Interp *interp, int argc,
5217 Jim_Obj * const *argv)
5220 Jim_WrongNumArgs(interp, 1, argv, "dict");
5225 Jim_Obj **dict = Jim_DictPairs(interp, argv[1], &tmp);
5230 const unsigned int length = tmp;
5231 struct command_context *cmd_ctx = current_command_context(interp);
5233 const struct target *target = get_current_target(cmd_ctx);
5235 for (unsigned int i = 0; i < length; i += 2) {
5236 const char *reg_name = Jim_String(dict[i]);
5237 const char *reg_value = Jim_String(dict[i + 1]);
5238 struct reg *reg = register_get_by_name(target->reg_cache, reg_name,
5241 if (!reg || !reg->exist) {
5242 Jim_SetResultFormatted(interp, "unknown register '%s'", reg_name);
5246 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
5249 LOG_ERROR("Failed to allocate memory");
5253 str_to_buf(reg_value, strlen(reg_value), buf, reg->size, 0);
5254 int retval = reg->type->set(reg, buf);
5257 if (retval != ERROR_OK) {
5258 Jim_SetResultFormatted(interp, "failed to set '%s' to register '%s'",
5259 reg_value, reg_name);
5268 * Returns true only if the target has a handler for the specified event.
5270 bool target_has_event_action(struct target *target, enum target_event event)
5272 struct target_event_action *teap;
5274 for (teap = target->event_action; teap; teap = teap->next) {
5275 if (teap->event == event)
5281 enum target_cfg_param {
5284 TCFG_WORK_AREA_VIRT,
5285 TCFG_WORK_AREA_PHYS,
5286 TCFG_WORK_AREA_SIZE,
5287 TCFG_WORK_AREA_BACKUP,
5290 TCFG_CHAIN_POSITION,
5295 TCFG_GDB_MAX_CONNECTIONS,
5298 static struct jim_nvp nvp_config_opts[] = {
5299 { .name = "-type", .value = TCFG_TYPE },
5300 { .name = "-event", .value = TCFG_EVENT },
5301 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
5302 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
5303 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
5304 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
5305 { .name = "-endian", .value = TCFG_ENDIAN },
5306 { .name = "-coreid", .value = TCFG_COREID },
5307 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
5308 { .name = "-dbgbase", .value = TCFG_DBGBASE },
5309 { .name = "-rtos", .value = TCFG_RTOS },
5310 { .name = "-defer-examine", .value = TCFG_DEFER_EXAMINE },
5311 { .name = "-gdb-port", .value = TCFG_GDB_PORT },
5312 { .name = "-gdb-max-connections", .value = TCFG_GDB_MAX_CONNECTIONS },
5313 { .name = NULL, .value = -1 }
5316 static int target_configure(struct jim_getopt_info *goi, struct target *target)
5323 /* parse config or cget options ... */
5324 while (goi->argc > 0) {
5325 Jim_SetEmptyResult(goi->interp);
5326 /* jim_getopt_debug(goi); */
5328 if (target->type->target_jim_configure) {
5329 /* target defines a configure function */
5330 /* target gets first dibs on parameters */
5331 e = (*(target->type->target_jim_configure))(target, goi);
5340 /* otherwise we 'continue' below */
5342 e = jim_getopt_nvp(goi, nvp_config_opts, &n);
5344 jim_getopt_nvp_unknown(goi, nvp_config_opts, 0);
5350 if (goi->isconfigure) {
5351 Jim_SetResultFormatted(goi->interp,
5352 "not settable: %s", n->name);
5356 if (goi->argc != 0) {
5357 Jim_WrongNumArgs(goi->interp,
5358 goi->argc, goi->argv,
5363 Jim_SetResultString(goi->interp,
5364 target_type_name(target), -1);
5368 if (goi->argc == 0) {
5369 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
5373 e = jim_getopt_nvp(goi, nvp_target_event, &n);
5375 jim_getopt_nvp_unknown(goi, nvp_target_event, 1);
5379 if (goi->isconfigure) {
5380 if (goi->argc != 1) {
5381 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
5385 if (goi->argc != 0) {
5386 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
5392 struct target_event_action *teap;
5394 teap = target->event_action;
5395 /* replace existing? */
5397 if (teap->event == (enum target_event)n->value)
5402 if (goi->isconfigure) {
5403 /* START_DEPRECATED_TPIU */
5404 if (n->value == TARGET_EVENT_TRACE_CONFIG)
5405 LOG_INFO("DEPRECATED target event %s; use TPIU events {pre,post}-{enable,disable}", n->name);
5406 /* END_DEPRECATED_TPIU */
5408 bool replace = true;
5411 teap = calloc(1, sizeof(*teap));
5414 teap->event = n->value;
5415 teap->interp = goi->interp;
5416 jim_getopt_obj(goi, &o);
5418 Jim_DecrRefCount(teap->interp, teap->body);
5419 teap->body = Jim_DuplicateObj(goi->interp, o);
5422 * Tcl/TK - "tk events" have a nice feature.
5423 * See the "BIND" command.
5424 * We should support that here.
5425 * You can specify %X and %Y in the event code.
5426 * The idea is: %T - target name.
5427 * The idea is: %N - target number
5428 * The idea is: %E - event name.
5430 Jim_IncrRefCount(teap->body);
5433 /* add to head of event list */
5434 teap->next = target->event_action;
5435 target->event_action = teap;
5437 Jim_SetEmptyResult(goi->interp);
5441 Jim_SetEmptyResult(goi->interp);
5443 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
5449 case TCFG_WORK_AREA_VIRT:
5450 if (goi->isconfigure) {
5451 target_free_all_working_areas(target);
5452 e = jim_getopt_wide(goi, &w);
5455 target->working_area_virt = w;
5456 target->working_area_virt_spec = true;
5461 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
5465 case TCFG_WORK_AREA_PHYS:
5466 if (goi->isconfigure) {
5467 target_free_all_working_areas(target);
5468 e = jim_getopt_wide(goi, &w);
5471 target->working_area_phys = w;
5472 target->working_area_phys_spec = true;
5477 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
5481 case TCFG_WORK_AREA_SIZE:
5482 if (goi->isconfigure) {
5483 target_free_all_working_areas(target);
5484 e = jim_getopt_wide(goi, &w);
5487 target->working_area_size = w;
5492 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
5496 case TCFG_WORK_AREA_BACKUP:
5497 if (goi->isconfigure) {
5498 target_free_all_working_areas(target);
5499 e = jim_getopt_wide(goi, &w);
5502 /* make this exactly 1 or 0 */
5503 target->backup_working_area = (!!w);
5508 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
5509 /* loop for more e*/
5514 if (goi->isconfigure) {
5515 e = jim_getopt_nvp(goi, nvp_target_endian, &n);
5517 jim_getopt_nvp_unknown(goi, nvp_target_endian, 1);
5520 target->endianness = n->value;
5525 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5527 target->endianness = TARGET_LITTLE_ENDIAN;
5528 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5530 Jim_SetResultString(goi->interp, n->name, -1);
5535 if (goi->isconfigure) {
5536 e = jim_getopt_wide(goi, &w);
5539 target->coreid = (int32_t)w;
5544 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->coreid));
5548 case TCFG_CHAIN_POSITION:
5549 if (goi->isconfigure) {
5551 struct jtag_tap *tap;
5553 if (target->has_dap) {
5554 Jim_SetResultString(goi->interp,
5555 "target requires -dap parameter instead of -chain-position!", -1);
5559 target_free_all_working_areas(target);
5560 e = jim_getopt_obj(goi, &o_t);
5563 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
5567 target->tap_configured = true;
5572 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
5573 /* loop for more e*/
5576 if (goi->isconfigure) {
5577 e = jim_getopt_wide(goi, &w);
5580 target->dbgbase = (uint32_t)w;
5581 target->dbgbase_set = true;
5586 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
5592 int result = rtos_create(goi, target);
5593 if (result != JIM_OK)
5599 case TCFG_DEFER_EXAMINE:
5601 target->defer_examine = true;
5606 if (goi->isconfigure) {
5607 struct command_context *cmd_ctx = current_command_context(goi->interp);
5608 if (cmd_ctx->mode != COMMAND_CONFIG) {
5609 Jim_SetResultString(goi->interp, "-gdb-port must be configured before 'init'", -1);
5614 e = jim_getopt_string(goi, &s, NULL);
5617 free(target->gdb_port_override);
5618 target->gdb_port_override = strdup(s);
5623 Jim_SetResultString(goi->interp, target->gdb_port_override ? target->gdb_port_override : "undefined", -1);
5627 case TCFG_GDB_MAX_CONNECTIONS:
5628 if (goi->isconfigure) {
5629 struct command_context *cmd_ctx = current_command_context(goi->interp);
5630 if (cmd_ctx->mode != COMMAND_CONFIG) {
5631 Jim_SetResultString(goi->interp, "-gdb-max-connections must be configured before 'init'", -1);
5635 e = jim_getopt_wide(goi, &w);
5638 target->gdb_max_connections = (w < 0) ? CONNECTION_LIMIT_UNLIMITED : (int)w;
5643 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->gdb_max_connections));
5646 } /* while (goi->argc) */
5649 /* done - we return */
5653 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5655 struct command *c = jim_to_command(interp);
5656 struct jim_getopt_info goi;
5658 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5659 goi.isconfigure = !strcmp(c->name, "configure");
5661 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5662 "missing: -option ...");
5665 struct command_context *cmd_ctx = current_command_context(interp);
5667 struct target *target = get_current_target(cmd_ctx);
5668 return target_configure(&goi, target);
5671 static int jim_target_mem2array(Jim_Interp *interp,
5672 int argc, Jim_Obj *const *argv)
5674 struct command_context *cmd_ctx = current_command_context(interp);
5676 struct target *target = get_current_target(cmd_ctx);
5677 return target_mem2array(interp, target, argc - 1, argv + 1);
5680 static int jim_target_array2mem(Jim_Interp *interp,
5681 int argc, Jim_Obj *const *argv)
5683 struct command_context *cmd_ctx = current_command_context(interp);
5685 struct target *target = get_current_target(cmd_ctx);
5686 return target_array2mem(interp, target, argc - 1, argv + 1);
5689 static int jim_target_tap_disabled(Jim_Interp *interp)
5691 Jim_SetResultFormatted(interp, "[TAP is disabled]");
5695 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5697 bool allow_defer = false;
5699 struct jim_getopt_info goi;
5700 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5702 const char *cmd_name = Jim_GetString(argv[0], NULL);
5703 Jim_SetResultFormatted(goi.interp,
5704 "usage: %s ['allow-defer']", cmd_name);
5708 strcmp(Jim_GetString(argv[1], NULL), "allow-defer") == 0) {
5711 int e = jim_getopt_obj(&goi, &obj);
5717 struct command_context *cmd_ctx = current_command_context(interp);
5719 struct target *target = get_current_target(cmd_ctx);
5720 if (!target->tap->enabled)
5721 return jim_target_tap_disabled(interp);
5723 if (allow_defer && target->defer_examine) {
5724 LOG_INFO("Deferring arp_examine of %s", target_name(target));
5725 LOG_INFO("Use arp_examine command to examine it manually!");
5729 int e = target->type->examine(target);
5730 if (e != ERROR_OK) {
5731 target_reset_examined(target);
5735 target_set_examined(target);
5740 static int jim_target_was_examined(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5742 struct command_context *cmd_ctx = current_command_context(interp);
5744 struct target *target = get_current_target(cmd_ctx);
5746 Jim_SetResultBool(interp, target_was_examined(target));
5750 static int jim_target_examine_deferred(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5752 struct command_context *cmd_ctx = current_command_context(interp);
5754 struct target *target = get_current_target(cmd_ctx);
5756 Jim_SetResultBool(interp, target->defer_examine);
5760 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5763 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5766 struct command_context *cmd_ctx = current_command_context(interp);
5768 struct target *target = get_current_target(cmd_ctx);
5770 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
5776 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5779 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5782 struct command_context *cmd_ctx = current_command_context(interp);
5784 struct target *target = get_current_target(cmd_ctx);
5785 if (!target->tap->enabled)
5786 return jim_target_tap_disabled(interp);
5789 if (!(target_was_examined(target)))
5790 e = ERROR_TARGET_NOT_EXAMINED;
5792 e = target->type->poll(target);
5798 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5800 struct jim_getopt_info goi;
5801 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5803 if (goi.argc != 2) {
5804 Jim_WrongNumArgs(interp, 0, argv,
5805 "([tT]|[fF]|assert|deassert) BOOL");
5810 int e = jim_getopt_nvp(&goi, nvp_assert, &n);
5812 jim_getopt_nvp_unknown(&goi, nvp_assert, 1);
5815 /* the halt or not param */
5817 e = jim_getopt_wide(&goi, &a);
5821 struct command_context *cmd_ctx = current_command_context(interp);
5823 struct target *target = get_current_target(cmd_ctx);
5824 if (!target->tap->enabled)
5825 return jim_target_tap_disabled(interp);
5827 if (!target->type->assert_reset || !target->type->deassert_reset) {
5828 Jim_SetResultFormatted(interp,
5829 "No target-specific reset for %s",
5830 target_name(target));
5834 if (target->defer_examine)
5835 target_reset_examined(target);
5837 /* determine if we should halt or not. */
5838 target->reset_halt = (a != 0);
5839 /* When this happens - all workareas are invalid. */
5840 target_free_all_working_areas_restore(target, 0);
5843 if (n->value == NVP_ASSERT)
5844 e = target->type->assert_reset(target);
5846 e = target->type->deassert_reset(target);
5847 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5850 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5853 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5856 struct command_context *cmd_ctx = current_command_context(interp);
5858 struct target *target = get_current_target(cmd_ctx);
5859 if (!target->tap->enabled)
5860 return jim_target_tap_disabled(interp);
5861 int e = target->type->halt(target);
5862 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5865 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5867 struct jim_getopt_info goi;
5868 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5870 /* params: <name> statename timeoutmsecs */
5871 if (goi.argc != 2) {
5872 const char *cmd_name = Jim_GetString(argv[0], NULL);
5873 Jim_SetResultFormatted(goi.interp,
5874 "%s <state_name> <timeout_in_msec>", cmd_name);
5879 int e = jim_getopt_nvp(&goi, nvp_target_state, &n);
5881 jim_getopt_nvp_unknown(&goi, nvp_target_state, 1);
5885 e = jim_getopt_wide(&goi, &a);
5888 struct command_context *cmd_ctx = current_command_context(interp);
5890 struct target *target = get_current_target(cmd_ctx);
5891 if (!target->tap->enabled)
5892 return jim_target_tap_disabled(interp);
5894 e = target_wait_state(target, n->value, a);
5895 if (e != ERROR_OK) {
5896 Jim_Obj *obj = Jim_NewIntObj(interp, e);
5897 Jim_SetResultFormatted(goi.interp,
5898 "target: %s wait %s fails (%#s) %s",
5899 target_name(target), n->name,
5900 obj, target_strerror_safe(e));
5905 /* List for human, Events defined for this target.
5906 * scripts/programs should use 'name cget -event NAME'
5908 COMMAND_HANDLER(handle_target_event_list)
5910 struct target *target = get_current_target(CMD_CTX);
5911 struct target_event_action *teap = target->event_action;
5913 command_print(CMD, "Event actions for target (%d) %s\n",
5914 target->target_number,
5915 target_name(target));
5916 command_print(CMD, "%-25s | Body", "Event");
5917 command_print(CMD, "------------------------- | "
5918 "----------------------------------------");
5920 command_print(CMD, "%-25s | %s",
5921 target_event_name(teap->event),
5922 Jim_GetString(teap->body, NULL));
5925 command_print(CMD, "***END***");
5928 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5931 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5934 struct command_context *cmd_ctx = current_command_context(interp);
5936 struct target *target = get_current_target(cmd_ctx);
5937 Jim_SetResultString(interp, target_state_name(target), -1);
5940 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5942 struct jim_getopt_info goi;
5943 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5944 if (goi.argc != 1) {
5945 const char *cmd_name = Jim_GetString(argv[0], NULL);
5946 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5950 int e = jim_getopt_nvp(&goi, nvp_target_event, &n);
5952 jim_getopt_nvp_unknown(&goi, nvp_target_event, 1);
5955 struct command_context *cmd_ctx = current_command_context(interp);
5957 struct target *target = get_current_target(cmd_ctx);
5958 target_handle_event(target, n->value);
5962 static const struct command_registration target_instance_command_handlers[] = {
5964 .name = "configure",
5965 .mode = COMMAND_ANY,
5966 .jim_handler = jim_target_configure,
5967 .help = "configure a new target for use",
5968 .usage = "[target_attribute ...]",
5972 .mode = COMMAND_ANY,
5973 .jim_handler = jim_target_configure,
5974 .help = "returns the specified target attribute",
5975 .usage = "target_attribute",
5979 .handler = handle_mw_command,
5980 .mode = COMMAND_EXEC,
5981 .help = "Write 64-bit word(s) to target memory",
5982 .usage = "address data [count]",
5986 .handler = handle_mw_command,
5987 .mode = COMMAND_EXEC,
5988 .help = "Write 32-bit word(s) to target memory",
5989 .usage = "address data [count]",
5993 .handler = handle_mw_command,
5994 .mode = COMMAND_EXEC,
5995 .help = "Write 16-bit half-word(s) to target memory",
5996 .usage = "address data [count]",
6000 .handler = handle_mw_command,
6001 .mode = COMMAND_EXEC,
6002 .help = "Write byte(s) to target memory",
6003 .usage = "address data [count]",
6007 .handler = handle_md_command,
6008 .mode = COMMAND_EXEC,
6009 .help = "Display target memory as 64-bit words",
6010 .usage = "address [count]",
6014 .handler = handle_md_command,
6015 .mode = COMMAND_EXEC,
6016 .help = "Display target memory as 32-bit words",
6017 .usage = "address [count]",
6021 .handler = handle_md_command,
6022 .mode = COMMAND_EXEC,
6023 .help = "Display target memory as 16-bit half-words",
6024 .usage = "address [count]",
6028 .handler = handle_md_command,
6029 .mode = COMMAND_EXEC,
6030 .help = "Display target memory as 8-bit bytes",
6031 .usage = "address [count]",
6034 .name = "array2mem",
6035 .mode = COMMAND_EXEC,
6036 .jim_handler = jim_target_array2mem,
6037 .help = "Writes Tcl array of 8/16/32 bit numbers "
6039 .usage = "arrayname bitwidth address count",
6042 .name = "mem2array",
6043 .mode = COMMAND_EXEC,
6044 .jim_handler = jim_target_mem2array,
6045 .help = "Loads Tcl array of 8/16/32 bit numbers "
6046 "from target memory",
6047 .usage = "arrayname bitwidth address count",
6051 .mode = COMMAND_EXEC,
6052 .jim_handler = target_jim_get_reg,
6053 .help = "Get register values from the target",
6058 .mode = COMMAND_EXEC,
6059 .jim_handler = target_jim_set_reg,
6060 .help = "Set target register values",
6064 .name = "read_memory",
6065 .mode = COMMAND_EXEC,
6066 .jim_handler = target_jim_read_memory,
6067 .help = "Read Tcl list of 8/16/32/64 bit numbers from target memory",
6068 .usage = "address width count ['phys']",
6071 .name = "write_memory",
6072 .mode = COMMAND_EXEC,
6073 .jim_handler = target_jim_write_memory,
6074 .help = "Write Tcl list of 8/16/32/64 bit numbers to target memory",
6075 .usage = "address width data ['phys']",
6078 .name = "eventlist",
6079 .handler = handle_target_event_list,
6080 .mode = COMMAND_EXEC,
6081 .help = "displays a table of events defined for this target",
6086 .mode = COMMAND_EXEC,
6087 .jim_handler = jim_target_current_state,
6088 .help = "displays the current state of this target",
6091 .name = "arp_examine",
6092 .mode = COMMAND_EXEC,
6093 .jim_handler = jim_target_examine,
6094 .help = "used internally for reset processing",
6095 .usage = "['allow-defer']",
6098 .name = "was_examined",
6099 .mode = COMMAND_EXEC,
6100 .jim_handler = jim_target_was_examined,
6101 .help = "used internally for reset processing",
6104 .name = "examine_deferred",
6105 .mode = COMMAND_EXEC,
6106 .jim_handler = jim_target_examine_deferred,
6107 .help = "used internally for reset processing",
6110 .name = "arp_halt_gdb",
6111 .mode = COMMAND_EXEC,
6112 .jim_handler = jim_target_halt_gdb,
6113 .help = "used internally for reset processing to halt GDB",
6117 .mode = COMMAND_EXEC,
6118 .jim_handler = jim_target_poll,
6119 .help = "used internally for reset processing",
6122 .name = "arp_reset",
6123 .mode = COMMAND_EXEC,
6124 .jim_handler = jim_target_reset,
6125 .help = "used internally for reset processing",
6129 .mode = COMMAND_EXEC,
6130 .jim_handler = jim_target_halt,
6131 .help = "used internally for reset processing",
6134 .name = "arp_waitstate",
6135 .mode = COMMAND_EXEC,
6136 .jim_handler = jim_target_wait_state,
6137 .help = "used internally for reset processing",
6140 .name = "invoke-event",
6141 .mode = COMMAND_EXEC,
6142 .jim_handler = jim_target_invoke_event,
6143 .help = "invoke handler for specified event",
6144 .usage = "event_name",
6146 COMMAND_REGISTRATION_DONE
6149 static int target_create(struct jim_getopt_info *goi)
6156 struct target *target;
6157 struct command_context *cmd_ctx;
6159 cmd_ctx = current_command_context(goi->interp);
6162 if (goi->argc < 3) {
6163 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
6168 jim_getopt_obj(goi, &new_cmd);
6169 /* does this command exist? */
6170 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_NONE);
6172 cp = Jim_GetString(new_cmd, NULL);
6173 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
6178 e = jim_getopt_string(goi, &cp, NULL);
6181 struct transport *tr = get_current_transport();
6182 if (tr->override_target) {
6183 e = tr->override_target(&cp);
6184 if (e != ERROR_OK) {
6185 LOG_ERROR("The selected transport doesn't support this target");
6188 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
6190 /* now does target type exist */
6191 for (x = 0 ; target_types[x] ; x++) {
6192 if (strcmp(cp, target_types[x]->name) == 0) {
6197 if (!target_types[x]) {
6198 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
6199 for (x = 0 ; target_types[x] ; x++) {
6200 if (target_types[x + 1]) {
6201 Jim_AppendStrings(goi->interp,
6202 Jim_GetResult(goi->interp),
6203 target_types[x]->name,
6206 Jim_AppendStrings(goi->interp,
6207 Jim_GetResult(goi->interp),
6209 target_types[x]->name, NULL);
6216 target = calloc(1, sizeof(struct target));
6218 LOG_ERROR("Out of memory");
6222 /* set empty smp cluster */
6223 target->smp_targets = &empty_smp_targets;
6225 /* set target number */
6226 target->target_number = new_target_number();
6228 /* allocate memory for each unique target type */
6229 target->type = malloc(sizeof(struct target_type));
6230 if (!target->type) {
6231 LOG_ERROR("Out of memory");
6236 memcpy(target->type, target_types[x], sizeof(struct target_type));
6238 /* default to first core, override with -coreid */
6241 target->working_area = 0x0;
6242 target->working_area_size = 0x0;
6243 target->working_areas = NULL;
6244 target->backup_working_area = 0;
6246 target->state = TARGET_UNKNOWN;
6247 target->debug_reason = DBG_REASON_UNDEFINED;
6248 target->reg_cache = NULL;
6249 target->breakpoints = NULL;
6250 target->watchpoints = NULL;
6251 target->next = NULL;
6252 target->arch_info = NULL;
6254 target->verbose_halt_msg = true;
6256 target->halt_issued = false;
6258 /* initialize trace information */
6259 target->trace_info = calloc(1, sizeof(struct trace));
6260 if (!target->trace_info) {
6261 LOG_ERROR("Out of memory");
6267 target->dbgmsg = NULL;
6268 target->dbg_msg_enabled = 0;
6270 target->endianness = TARGET_ENDIAN_UNKNOWN;
6272 target->rtos = NULL;
6273 target->rtos_auto_detect = false;
6275 target->gdb_port_override = NULL;
6276 target->gdb_max_connections = 1;
6278 /* Do the rest as "configure" options */
6279 goi->isconfigure = 1;
6280 e = target_configure(goi, target);
6283 if (target->has_dap) {
6284 if (!target->dap_configured) {
6285 Jim_SetResultString(goi->interp, "-dap ?name? required when creating target", -1);
6289 if (!target->tap_configured) {
6290 Jim_SetResultString(goi->interp, "-chain-position ?name? required when creating target", -1);
6294 /* tap must be set after target was configured */
6300 rtos_destroy(target);
6301 free(target->gdb_port_override);
6302 free(target->trace_info);
6308 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
6309 /* default endian to little if not specified */
6310 target->endianness = TARGET_LITTLE_ENDIAN;
6313 cp = Jim_GetString(new_cmd, NULL);
6314 target->cmd_name = strdup(cp);
6315 if (!target->cmd_name) {
6316 LOG_ERROR("Out of memory");
6317 rtos_destroy(target);
6318 free(target->gdb_port_override);
6319 free(target->trace_info);
6325 if (target->type->target_create) {
6326 e = (*(target->type->target_create))(target, goi->interp);
6327 if (e != ERROR_OK) {
6328 LOG_DEBUG("target_create failed");
6329 free(target->cmd_name);
6330 rtos_destroy(target);
6331 free(target->gdb_port_override);
6332 free(target->trace_info);
6339 /* create the target specific commands */
6340 if (target->type->commands) {
6341 e = register_commands(cmd_ctx, NULL, target->type->commands);
6343 LOG_ERROR("unable to register '%s' commands", cp);
6346 /* now - create the new target name command */
6347 const struct command_registration target_subcommands[] = {
6349 .chain = target_instance_command_handlers,
6352 .chain = target->type->commands,
6354 COMMAND_REGISTRATION_DONE
6356 const struct command_registration target_commands[] = {
6359 .mode = COMMAND_ANY,
6360 .help = "target command group",
6362 .chain = target_subcommands,
6364 COMMAND_REGISTRATION_DONE
6366 e = register_commands_override_target(cmd_ctx, NULL, target_commands, target);
6367 if (e != ERROR_OK) {
6368 if (target->type->deinit_target)
6369 target->type->deinit_target(target);
6370 free(target->cmd_name);
6371 rtos_destroy(target);
6372 free(target->gdb_port_override);
6373 free(target->trace_info);
6379 /* append to end of list */
6380 append_to_list_all_targets(target);
6382 cmd_ctx->current_target = target;
6386 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6389 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
6392 struct command_context *cmd_ctx = current_command_context(interp);
6395 struct target *target = get_current_target_or_null(cmd_ctx);
6397 Jim_SetResultString(interp, target_name(target), -1);
6401 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6404 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
6407 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
6408 for (unsigned x = 0; target_types[x]; x++) {
6409 Jim_ListAppendElement(interp, Jim_GetResult(interp),
6410 Jim_NewStringObj(interp, target_types[x]->name, -1));
6415 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6418 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
6421 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
6422 struct target *target = all_targets;
6424 Jim_ListAppendElement(interp, Jim_GetResult(interp),
6425 Jim_NewStringObj(interp, target_name(target), -1));
6426 target = target->next;
6431 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6434 const char *targetname;
6436 struct target *target = NULL;
6437 struct target_list *head, *new;
6440 LOG_DEBUG("%d", argc);
6441 /* argv[1] = target to associate in smp
6442 * argv[2] = target to associate in smp
6446 struct list_head *lh = malloc(sizeof(*lh));
6448 LOG_ERROR("Out of memory");
6453 for (i = 1; i < argc; i++) {
6455 targetname = Jim_GetString(argv[i], &len);
6456 target = get_target(targetname);
6457 LOG_DEBUG("%s ", targetname);
6459 new = malloc(sizeof(struct target_list));
6460 new->target = target;
6461 list_add_tail(&new->lh, lh);
6464 /* now parse the list of cpu and put the target in smp mode*/
6465 foreach_smp_target(head, lh) {
6466 target = head->target;
6468 target->smp_targets = lh;
6471 if (target && target->rtos)
6472 retval = rtos_smp_init(head->target);
6478 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6480 struct jim_getopt_info goi;
6481 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
6483 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
6484 "<name> <target_type> [<target_options> ...]");
6487 return target_create(&goi);
6490 static const struct command_registration target_subcommand_handlers[] = {
6493 .mode = COMMAND_CONFIG,
6494 .handler = handle_target_init_command,
6495 .help = "initialize targets",
6500 .mode = COMMAND_CONFIG,
6501 .jim_handler = jim_target_create,
6502 .usage = "name type '-chain-position' name [options ...]",
6503 .help = "Creates and selects a new target",
6507 .mode = COMMAND_ANY,
6508 .jim_handler = jim_target_current,
6509 .help = "Returns the currently selected target",
6513 .mode = COMMAND_ANY,
6514 .jim_handler = jim_target_types,
6515 .help = "Returns the available target types as "
6516 "a list of strings",
6520 .mode = COMMAND_ANY,
6521 .jim_handler = jim_target_names,
6522 .help = "Returns the names of all targets as a list of strings",
6526 .mode = COMMAND_ANY,
6527 .jim_handler = jim_target_smp,
6528 .usage = "targetname1 targetname2 ...",
6529 .help = "gather several target in a smp list"
6532 COMMAND_REGISTRATION_DONE
6536 target_addr_t address;
6542 static int fastload_num;
6543 static struct fast_load *fastload;
6545 static void free_fastload(void)
6548 for (int i = 0; i < fastload_num; i++)
6549 free(fastload[i].data);
6555 COMMAND_HANDLER(handle_fast_load_image_command)
6559 uint32_t image_size;
6560 target_addr_t min_address = 0;
6561 target_addr_t max_address = -1;
6565 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
6566 &image, &min_address, &max_address);
6567 if (retval != ERROR_OK)
6570 struct duration bench;
6571 duration_start(&bench);
6573 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
6574 if (retval != ERROR_OK)
6579 fastload_num = image.num_sections;
6580 fastload = malloc(sizeof(struct fast_load)*image.num_sections);
6582 command_print(CMD, "out of memory");
6583 image_close(&image);
6586 memset(fastload, 0, sizeof(struct fast_load)*image.num_sections);
6587 for (unsigned int i = 0; i < image.num_sections; i++) {
6588 buffer = malloc(image.sections[i].size);
6590 command_print(CMD, "error allocating buffer for section (%d bytes)",
6591 (int)(image.sections[i].size));
6592 retval = ERROR_FAIL;
6596 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
6597 if (retval != ERROR_OK) {
6602 uint32_t offset = 0;
6603 uint32_t length = buf_cnt;
6605 /* DANGER!!! beware of unsigned comparison here!!! */
6607 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
6608 (image.sections[i].base_address < max_address)) {
6609 if (image.sections[i].base_address < min_address) {
6610 /* clip addresses below */
6611 offset += min_address-image.sections[i].base_address;
6615 if (image.sections[i].base_address + buf_cnt > max_address)
6616 length -= (image.sections[i].base_address + buf_cnt)-max_address;
6618 fastload[i].address = image.sections[i].base_address + offset;
6619 fastload[i].data = malloc(length);
6620 if (!fastload[i].data) {
6622 command_print(CMD, "error allocating buffer for section (%" PRIu32 " bytes)",
6624 retval = ERROR_FAIL;
6627 memcpy(fastload[i].data, buffer + offset, length);
6628 fastload[i].length = length;
6630 image_size += length;
6631 command_print(CMD, "%u bytes written at address 0x%8.8x",
6632 (unsigned int)length,
6633 ((unsigned int)(image.sections[i].base_address + offset)));
6639 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
6640 command_print(CMD, "Loaded %" PRIu32 " bytes "
6641 "in %fs (%0.3f KiB/s)", image_size,
6642 duration_elapsed(&bench), duration_kbps(&bench, image_size));
6645 "WARNING: image has not been loaded to target!"
6646 "You can issue a 'fast_load' to finish loading.");
6649 image_close(&image);
6651 if (retval != ERROR_OK)
6657 COMMAND_HANDLER(handle_fast_load_command)
6660 return ERROR_COMMAND_SYNTAX_ERROR;
6662 LOG_ERROR("No image in memory");
6666 int64_t ms = timeval_ms();
6668 int retval = ERROR_OK;
6669 for (i = 0; i < fastload_num; i++) {
6670 struct target *target = get_current_target(CMD_CTX);
6671 command_print(CMD, "Write to 0x%08x, length 0x%08x",
6672 (unsigned int)(fastload[i].address),
6673 (unsigned int)(fastload[i].length));
6674 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
6675 if (retval != ERROR_OK)
6677 size += fastload[i].length;
6679 if (retval == ERROR_OK) {
6680 int64_t after = timeval_ms();
6681 command_print(CMD, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
6686 static const struct command_registration target_command_handlers[] = {
6689 .handler = handle_targets_command,
6690 .mode = COMMAND_ANY,
6691 .help = "change current default target (one parameter) "
6692 "or prints table of all targets (no parameters)",
6693 .usage = "[target]",
6697 .mode = COMMAND_CONFIG,
6698 .help = "configure target",
6699 .chain = target_subcommand_handlers,
6702 COMMAND_REGISTRATION_DONE
6705 int target_register_commands(struct command_context *cmd_ctx)
6707 return register_commands(cmd_ctx, NULL, target_command_handlers);
6710 static bool target_reset_nag = true;
6712 bool get_target_reset_nag(void)
6714 return target_reset_nag;
6717 COMMAND_HANDLER(handle_target_reset_nag)
6719 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
6720 &target_reset_nag, "Nag after each reset about options to improve "
6724 COMMAND_HANDLER(handle_ps_command)
6726 struct target *target = get_current_target(CMD_CTX);
6728 if (target->state != TARGET_HALTED) {
6729 LOG_INFO("target not halted !!");
6733 if ((target->rtos) && (target->rtos->type)
6734 && (target->rtos->type->ps_command)) {
6735 display = target->rtos->type->ps_command(target);
6736 command_print(CMD, "%s", display);
6741 return ERROR_TARGET_FAILURE;
6745 static void binprint(struct command_invocation *cmd, const char *text, const uint8_t *buf, int size)
6748 command_print_sameline(cmd, "%s", text);
6749 for (int i = 0; i < size; i++)
6750 command_print_sameline(cmd, " %02x", buf[i]);
6751 command_print(cmd, " ");
6754 COMMAND_HANDLER(handle_test_mem_access_command)
6756 struct target *target = get_current_target(CMD_CTX);
6758 int retval = ERROR_OK;
6760 if (target->state != TARGET_HALTED) {
6761 LOG_INFO("target not halted !!");
6766 return ERROR_COMMAND_SYNTAX_ERROR;
6768 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
6771 size_t num_bytes = test_size + 4;
6773 struct working_area *wa = NULL;
6774 retval = target_alloc_working_area(target, num_bytes, &wa);
6775 if (retval != ERROR_OK) {
6776 LOG_ERROR("Not enough working area");
6780 uint8_t *test_pattern = malloc(num_bytes);
6782 for (size_t i = 0; i < num_bytes; i++)
6783 test_pattern[i] = rand();
6785 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6786 if (retval != ERROR_OK) {
6787 LOG_ERROR("Test pattern write failed");
6791 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6792 for (int size = 1; size <= 4; size *= 2) {
6793 for (int offset = 0; offset < 4; offset++) {
6794 uint32_t count = test_size / size;
6795 size_t host_bufsiz = (count + 2) * size + host_offset;
6796 uint8_t *read_ref = malloc(host_bufsiz);
6797 uint8_t *read_buf = malloc(host_bufsiz);
6799 for (size_t i = 0; i < host_bufsiz; i++) {
6800 read_ref[i] = rand();
6801 read_buf[i] = read_ref[i];
6803 command_print_sameline(CMD,
6804 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
6805 size, offset, host_offset ? "un" : "");
6807 struct duration bench;
6808 duration_start(&bench);
6810 retval = target_read_memory(target, wa->address + offset, size, count,
6811 read_buf + size + host_offset);
6813 duration_measure(&bench);
6815 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6816 command_print(CMD, "Unsupported alignment");
6818 } else if (retval != ERROR_OK) {
6819 command_print(CMD, "Memory read failed");
6823 /* replay on host */
6824 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
6827 int result = memcmp(read_ref, read_buf, host_bufsiz);
6829 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6830 duration_elapsed(&bench),
6831 duration_kbps(&bench, count * size));
6833 command_print(CMD, "Compare failed");
6834 binprint(CMD, "ref:", read_ref, host_bufsiz);
6835 binprint(CMD, "buf:", read_buf, host_bufsiz);
6847 target_free_working_area(target, wa);
6850 num_bytes = test_size + 4 + 4 + 4;
6852 retval = target_alloc_working_area(target, num_bytes, &wa);
6853 if (retval != ERROR_OK) {
6854 LOG_ERROR("Not enough working area");
6858 test_pattern = malloc(num_bytes);
6860 for (size_t i = 0; i < num_bytes; i++)
6861 test_pattern[i] = rand();
6863 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6864 for (int size = 1; size <= 4; size *= 2) {
6865 for (int offset = 0; offset < 4; offset++) {
6866 uint32_t count = test_size / size;
6867 size_t host_bufsiz = count * size + host_offset;
6868 uint8_t *read_ref = malloc(num_bytes);
6869 uint8_t *read_buf = malloc(num_bytes);
6870 uint8_t *write_buf = malloc(host_bufsiz);
6872 for (size_t i = 0; i < host_bufsiz; i++)
6873 write_buf[i] = rand();
6874 command_print_sameline(CMD,
6875 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
6876 size, offset, host_offset ? "un" : "");
6878 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6879 if (retval != ERROR_OK) {
6880 command_print(CMD, "Test pattern write failed");
6884 /* replay on host */
6885 memcpy(read_ref, test_pattern, num_bytes);
6886 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
6888 struct duration bench;
6889 duration_start(&bench);
6891 retval = target_write_memory(target, wa->address + size + offset, size, count,
6892 write_buf + host_offset);
6894 duration_measure(&bench);
6896 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6897 command_print(CMD, "Unsupported alignment");
6899 } else if (retval != ERROR_OK) {
6900 command_print(CMD, "Memory write failed");
6905 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
6906 if (retval != ERROR_OK) {
6907 command_print(CMD, "Test pattern write failed");
6912 int result = memcmp(read_ref, read_buf, num_bytes);
6914 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6915 duration_elapsed(&bench),
6916 duration_kbps(&bench, count * size));
6918 command_print(CMD, "Compare failed");
6919 binprint(CMD, "ref:", read_ref, num_bytes);
6920 binprint(CMD, "buf:", read_buf, num_bytes);
6931 target_free_working_area(target, wa);
6935 static const struct command_registration target_exec_command_handlers[] = {
6937 .name = "fast_load_image",
6938 .handler = handle_fast_load_image_command,
6939 .mode = COMMAND_ANY,
6940 .help = "Load image into server memory for later use by "
6941 "fast_load; primarily for profiling",
6942 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6943 "[min_address [max_length]]",
6946 .name = "fast_load",
6947 .handler = handle_fast_load_command,
6948 .mode = COMMAND_EXEC,
6949 .help = "loads active fast load image to current target "
6950 "- mainly for profiling purposes",
6955 .handler = handle_profile_command,
6956 .mode = COMMAND_EXEC,
6957 .usage = "seconds filename [start end]",
6958 .help = "profiling samples the CPU PC",
6960 /** @todo don't register virt2phys() unless target supports it */
6962 .name = "virt2phys",
6963 .handler = handle_virt2phys_command,
6964 .mode = COMMAND_ANY,
6965 .help = "translate a virtual address into a physical address",
6966 .usage = "virtual_address",
6970 .handler = handle_reg_command,
6971 .mode = COMMAND_EXEC,
6972 .help = "display (reread from target with \"force\") or set a register; "
6973 "with no arguments, displays all registers and their values",
6974 .usage = "[(register_number|register_name) [(value|'force')]]",
6978 .handler = handle_poll_command,
6979 .mode = COMMAND_EXEC,
6980 .help = "poll target state; or reconfigure background polling",
6981 .usage = "['on'|'off']",
6984 .name = "wait_halt",
6985 .handler = handle_wait_halt_command,
6986 .mode = COMMAND_EXEC,
6987 .help = "wait up to the specified number of milliseconds "
6988 "(default 5000) for a previously requested halt",
6989 .usage = "[milliseconds]",
6993 .handler = handle_halt_command,
6994 .mode = COMMAND_EXEC,
6995 .help = "request target to halt, then wait up to the specified "
6996 "number of milliseconds (default 5000) for it to complete",
6997 .usage = "[milliseconds]",
7001 .handler = handle_resume_command,
7002 .mode = COMMAND_EXEC,
7003 .help = "resume target execution from current PC or address",
7004 .usage = "[address]",
7008 .handler = handle_reset_command,
7009 .mode = COMMAND_EXEC,
7010 .usage = "[run|halt|init]",
7011 .help = "Reset all targets into the specified mode. "
7012 "Default reset mode is run, if not given.",
7015 .name = "soft_reset_halt",
7016 .handler = handle_soft_reset_halt_command,
7017 .mode = COMMAND_EXEC,
7019 .help = "halt the target and do a soft reset",
7023 .handler = handle_step_command,
7024 .mode = COMMAND_EXEC,
7025 .help = "step one instruction from current PC or address",
7026 .usage = "[address]",
7030 .handler = handle_md_command,
7031 .mode = COMMAND_EXEC,
7032 .help = "display memory double-words",
7033 .usage = "['phys'] address [count]",
7037 .handler = handle_md_command,
7038 .mode = COMMAND_EXEC,
7039 .help = "display memory words",
7040 .usage = "['phys'] address [count]",
7044 .handler = handle_md_command,
7045 .mode = COMMAND_EXEC,
7046 .help = "display memory half-words",
7047 .usage = "['phys'] address [count]",
7051 .handler = handle_md_command,
7052 .mode = COMMAND_EXEC,
7053 .help = "display memory bytes",
7054 .usage = "['phys'] address [count]",
7058 .handler = handle_mw_command,
7059 .mode = COMMAND_EXEC,
7060 .help = "write memory double-word",
7061 .usage = "['phys'] address value [count]",
7065 .handler = handle_mw_command,
7066 .mode = COMMAND_EXEC,
7067 .help = "write memory word",
7068 .usage = "['phys'] address value [count]",
7072 .handler = handle_mw_command,
7073 .mode = COMMAND_EXEC,
7074 .help = "write memory half-word",
7075 .usage = "['phys'] address value [count]",
7079 .handler = handle_mw_command,
7080 .mode = COMMAND_EXEC,
7081 .help = "write memory byte",
7082 .usage = "['phys'] address value [count]",
7086 .handler = handle_bp_command,
7087 .mode = COMMAND_EXEC,
7088 .help = "list or set hardware or software breakpoint",
7089 .usage = "[<address> [<asid>] <length> ['hw'|'hw_ctx']]",
7093 .handler = handle_rbp_command,
7094 .mode = COMMAND_EXEC,
7095 .help = "remove breakpoint",
7096 .usage = "'all' | address",
7100 .handler = handle_wp_command,
7101 .mode = COMMAND_EXEC,
7102 .help = "list (no params) or create watchpoints",
7103 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
7107 .handler = handle_rwp_command,
7108 .mode = COMMAND_EXEC,
7109 .help = "remove watchpoint",
7113 .name = "load_image",
7114 .handler = handle_load_image_command,
7115 .mode = COMMAND_EXEC,
7116 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
7117 "[min_address] [max_length]",
7120 .name = "dump_image",
7121 .handler = handle_dump_image_command,
7122 .mode = COMMAND_EXEC,
7123 .usage = "filename address size",
7126 .name = "verify_image_checksum",
7127 .handler = handle_verify_image_checksum_command,
7128 .mode = COMMAND_EXEC,
7129 .usage = "filename [offset [type]]",
7132 .name = "verify_image",
7133 .handler = handle_verify_image_command,
7134 .mode = COMMAND_EXEC,
7135 .usage = "filename [offset [type]]",
7138 .name = "test_image",
7139 .handler = handle_test_image_command,
7140 .mode = COMMAND_EXEC,
7141 .usage = "filename [offset [type]]",
7145 .mode = COMMAND_EXEC,
7146 .jim_handler = target_jim_get_reg,
7147 .help = "Get register values from the target",
7152 .mode = COMMAND_EXEC,
7153 .jim_handler = target_jim_set_reg,
7154 .help = "Set target register values",
7158 .name = "read_memory",
7159 .mode = COMMAND_EXEC,
7160 .jim_handler = target_jim_read_memory,
7161 .help = "Read Tcl list of 8/16/32/64 bit numbers from target memory",
7162 .usage = "address width count ['phys']",
7165 .name = "write_memory",
7166 .mode = COMMAND_EXEC,
7167 .jim_handler = target_jim_write_memory,
7168 .help = "Write Tcl list of 8/16/32/64 bit numbers to target memory",
7169 .usage = "address width data ['phys']",
7172 .name = "reset_nag",
7173 .handler = handle_target_reset_nag,
7174 .mode = COMMAND_ANY,
7175 .help = "Nag after each reset about options that could have been "
7176 "enabled to improve performance.",
7177 .usage = "['enable'|'disable']",
7181 .handler = handle_ps_command,
7182 .mode = COMMAND_EXEC,
7183 .help = "list all tasks",
7187 .name = "test_mem_access",
7188 .handler = handle_test_mem_access_command,
7189 .mode = COMMAND_EXEC,
7190 .help = "Test the target's memory access functions",
7194 COMMAND_REGISTRATION_DONE
7196 static int target_register_user_commands(struct command_context *cmd_ctx)
7198 int retval = ERROR_OK;
7199 retval = target_request_register_commands(cmd_ctx);
7200 if (retval != ERROR_OK)
7203 retval = trace_register_commands(cmd_ctx);
7204 if (retval != ERROR_OK)
7208 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);