1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
5 * Copyright (C) 2007-2010 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
8 * Copyright (C) 2008, Duane Ellis *
9 * openocd@duaneeellis.com *
11 * Copyright (C) 2008 by Spencer Oliver *
12 * spen@spen-soft.co.uk *
14 * Copyright (C) 2008 by Rick Altherr *
15 * kc8apf@kc8apf.net> *
17 * Copyright (C) 2011 by Broadcom Corporation *
18 * Evan Hunter - ehunter@broadcom.com *
20 * Copyright (C) ST-Ericsson SA 2011 *
21 * michel.jaouen@stericsson.com : smp minimum support *
23 * Copyright (C) 2011 Andreas Fritiofson *
24 * andreas.fritiofson@gmail.com *
26 * This program is free software; you can redistribute it and/or modify *
27 * it under the terms of the GNU General Public License as published by *
28 * the Free Software Foundation; either version 2 of the License, or *
29 * (at your option) any later version. *
31 * This program is distributed in the hope that it will be useful, *
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
34 * GNU General Public License for more details. *
36 * You should have received a copy of the GNU General Public License *
37 * along with this program. If not, see <http://www.gnu.org/licenses/>. *
38 ***************************************************************************/
44 #include <helper/time_support.h>
45 #include <jtag/jtag.h>
46 #include <flash/nor/core.h>
49 #include "target_type.h"
50 #include "target_request.h"
51 #include "breakpoints.h"
55 #include "rtos/rtos.h"
56 #include "transport/transport.h"
59 /* default halt wait timeout (ms) */
60 #define DEFAULT_HALT_TIMEOUT 5000
62 static int target_read_buffer_default(struct target *target, target_addr_t address,
63 uint32_t count, uint8_t *buffer);
64 static int target_write_buffer_default(struct target *target, target_addr_t address,
65 uint32_t count, const uint8_t *buffer);
66 static int target_array2mem(Jim_Interp *interp, struct target *target,
67 int argc, Jim_Obj * const *argv);
68 static int target_mem2array(Jim_Interp *interp, struct target *target,
69 int argc, Jim_Obj * const *argv);
70 static int target_register_user_commands(struct command_context *cmd_ctx);
71 static int target_get_gdb_fileio_info_default(struct target *target,
72 struct gdb_fileio_info *fileio_info);
73 static int target_gdb_fileio_end_default(struct target *target, int retcode,
74 int fileio_errno, bool ctrl_c);
75 static int target_profiling_default(struct target *target, uint32_t *samples,
76 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds);
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 avr_target;
98 extern struct target_type dsp563xx_target;
99 extern struct target_type dsp5680xx_target;
100 extern struct target_type testee_target;
101 extern struct target_type avr32_ap7k_target;
102 extern struct target_type hla_target;
103 extern struct target_type nds32_v2_target;
104 extern struct target_type nds32_v3_target;
105 extern struct target_type nds32_v3m_target;
106 extern struct target_type or1k_target;
107 extern struct target_type quark_x10xx_target;
108 extern struct target_type quark_d20xx_target;
109 extern struct target_type stm8_target;
110 extern struct target_type riscv_target;
111 extern struct target_type mem_ap_target;
112 extern struct target_type esirisc_target;
114 static struct target_type *target_types[] = {
154 struct target *all_targets;
155 static struct target_event_callback *target_event_callbacks;
156 static struct target_timer_callback *target_timer_callbacks;
157 LIST_HEAD(target_reset_callback_list);
158 LIST_HEAD(target_trace_callback_list);
159 static const int polling_interval = 100;
161 static const Jim_Nvp nvp_assert[] = {
162 { .name = "assert", NVP_ASSERT },
163 { .name = "deassert", NVP_DEASSERT },
164 { .name = "T", NVP_ASSERT },
165 { .name = "F", NVP_DEASSERT },
166 { .name = "t", NVP_ASSERT },
167 { .name = "f", NVP_DEASSERT },
168 { .name = NULL, .value = -1 }
171 static const Jim_Nvp nvp_error_target[] = {
172 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
173 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
174 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
175 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
176 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
177 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
178 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
179 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
180 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
181 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
182 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
183 { .value = -1, .name = NULL }
186 static const char *target_strerror_safe(int err)
190 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
197 static const Jim_Nvp nvp_target_event[] = {
199 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
200 { .value = TARGET_EVENT_HALTED, .name = "halted" },
201 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
202 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
203 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
205 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
206 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
208 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
209 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
210 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
211 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
212 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
213 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
214 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
215 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
217 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
218 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
220 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
221 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
223 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
224 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
226 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
227 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
229 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
230 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
232 { .value = TARGET_EVENT_TRACE_CONFIG, .name = "trace-config" },
234 { .name = NULL, .value = -1 }
237 static const Jim_Nvp nvp_target_state[] = {
238 { .name = "unknown", .value = TARGET_UNKNOWN },
239 { .name = "running", .value = TARGET_RUNNING },
240 { .name = "halted", .value = TARGET_HALTED },
241 { .name = "reset", .value = TARGET_RESET },
242 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
243 { .name = NULL, .value = -1 },
246 static const Jim_Nvp nvp_target_debug_reason[] = {
247 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
248 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
249 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
250 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
251 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
252 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
253 { .name = "program-exit" , .value = DBG_REASON_EXIT },
254 { .name = "exception-catch" , .value = DBG_REASON_EXC_CATCH },
255 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
256 { .name = NULL, .value = -1 },
259 static const Jim_Nvp nvp_target_endian[] = {
260 { .name = "big", .value = TARGET_BIG_ENDIAN },
261 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
262 { .name = "be", .value = TARGET_BIG_ENDIAN },
263 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
264 { .name = NULL, .value = -1 },
267 static const Jim_Nvp nvp_reset_modes[] = {
268 { .name = "unknown", .value = RESET_UNKNOWN },
269 { .name = "run" , .value = RESET_RUN },
270 { .name = "halt" , .value = RESET_HALT },
271 { .name = "init" , .value = RESET_INIT },
272 { .name = NULL , .value = -1 },
275 const char *debug_reason_name(struct target *t)
279 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
280 t->debug_reason)->name;
282 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
283 cp = "(*BUG*unknown*BUG*)";
288 const char *target_state_name(struct target *t)
291 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
293 LOG_ERROR("Invalid target state: %d", (int)(t->state));
294 cp = "(*BUG*unknown*BUG*)";
297 if (!target_was_examined(t) && t->defer_examine)
298 cp = "examine deferred";
303 const char *target_event_name(enum target_event event)
306 cp = Jim_Nvp_value2name_simple(nvp_target_event, event)->name;
308 LOG_ERROR("Invalid target event: %d", (int)(event));
309 cp = "(*BUG*unknown*BUG*)";
314 const char *target_reset_mode_name(enum target_reset_mode reset_mode)
317 cp = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name;
319 LOG_ERROR("Invalid target reset mode: %d", (int)(reset_mode));
320 cp = "(*BUG*unknown*BUG*)";
325 /* determine the number of the new target */
326 static int new_target_number(void)
331 /* number is 0 based */
335 if (x < t->target_number)
336 x = t->target_number;
342 /* read a uint64_t from a buffer in target memory endianness */
343 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
345 if (target->endianness == TARGET_LITTLE_ENDIAN)
346 return le_to_h_u64(buffer);
348 return be_to_h_u64(buffer);
351 /* read a uint32_t from a buffer in target memory endianness */
352 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
354 if (target->endianness == TARGET_LITTLE_ENDIAN)
355 return le_to_h_u32(buffer);
357 return be_to_h_u32(buffer);
360 /* read a uint24_t from a buffer in target memory endianness */
361 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
363 if (target->endianness == TARGET_LITTLE_ENDIAN)
364 return le_to_h_u24(buffer);
366 return be_to_h_u24(buffer);
369 /* read a uint16_t from a buffer in target memory endianness */
370 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
372 if (target->endianness == TARGET_LITTLE_ENDIAN)
373 return le_to_h_u16(buffer);
375 return be_to_h_u16(buffer);
378 /* write a uint64_t to a buffer in target memory endianness */
379 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
381 if (target->endianness == TARGET_LITTLE_ENDIAN)
382 h_u64_to_le(buffer, value);
384 h_u64_to_be(buffer, value);
387 /* write a uint32_t to a buffer in target memory endianness */
388 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
390 if (target->endianness == TARGET_LITTLE_ENDIAN)
391 h_u32_to_le(buffer, value);
393 h_u32_to_be(buffer, value);
396 /* write a uint24_t to a buffer in target memory endianness */
397 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
399 if (target->endianness == TARGET_LITTLE_ENDIAN)
400 h_u24_to_le(buffer, value);
402 h_u24_to_be(buffer, value);
405 /* write a uint16_t to a buffer in target memory endianness */
406 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
408 if (target->endianness == TARGET_LITTLE_ENDIAN)
409 h_u16_to_le(buffer, value);
411 h_u16_to_be(buffer, value);
414 /* write a uint8_t to a buffer in target memory endianness */
415 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
420 /* write a uint64_t array to a buffer in target memory endianness */
421 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
424 for (i = 0; i < count; i++)
425 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
428 /* write a uint32_t array to a buffer in target memory endianness */
429 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
432 for (i = 0; i < count; i++)
433 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
436 /* write a uint16_t array to a buffer in target memory endianness */
437 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
440 for (i = 0; i < count; i++)
441 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
444 /* write a uint64_t array to a buffer in target memory endianness */
445 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
448 for (i = 0; i < count; i++)
449 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
452 /* write a uint32_t array to a buffer in target memory endianness */
453 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
456 for (i = 0; i < count; i++)
457 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
460 /* write a uint16_t array to a buffer in target memory endianness */
461 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
464 for (i = 0; i < count; i++)
465 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
468 /* return a pointer to a configured target; id is name or number */
469 struct target *get_target(const char *id)
471 struct target *target;
473 /* try as tcltarget name */
474 for (target = all_targets; target; target = target->next) {
475 if (target_name(target) == NULL)
477 if (strcmp(id, target_name(target)) == 0)
481 /* It's OK to remove this fallback sometime after August 2010 or so */
483 /* no match, try as number */
485 if (parse_uint(id, &num) != ERROR_OK)
488 for (target = all_targets; target; target = target->next) {
489 if (target->target_number == (int)num) {
490 LOG_WARNING("use '%s' as target identifier, not '%u'",
491 target_name(target), num);
499 /* returns a pointer to the n-th configured target */
500 struct target *get_target_by_num(int num)
502 struct target *target = all_targets;
505 if (target->target_number == num)
507 target = target->next;
513 struct target *get_current_target(struct command_context *cmd_ctx)
515 struct target *target = get_current_target_or_null(cmd_ctx);
517 if (target == NULL) {
518 LOG_ERROR("BUG: current_target out of bounds");
525 struct target *get_current_target_or_null(struct command_context *cmd_ctx)
527 return cmd_ctx->current_target_override
528 ? cmd_ctx->current_target_override
529 : cmd_ctx->current_target;
532 int target_poll(struct target *target)
536 /* We can't poll until after examine */
537 if (!target_was_examined(target)) {
538 /* Fail silently lest we pollute the log */
542 retval = target->type->poll(target);
543 if (retval != ERROR_OK)
546 if (target->halt_issued) {
547 if (target->state == TARGET_HALTED)
548 target->halt_issued = false;
550 int64_t t = timeval_ms() - target->halt_issued_time;
551 if (t > DEFAULT_HALT_TIMEOUT) {
552 target->halt_issued = false;
553 LOG_INFO("Halt timed out, wake up GDB.");
554 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
562 int target_halt(struct target *target)
565 /* We can't poll until after examine */
566 if (!target_was_examined(target)) {
567 LOG_ERROR("Target not examined yet");
571 retval = target->type->halt(target);
572 if (retval != ERROR_OK)
575 target->halt_issued = true;
576 target->halt_issued_time = timeval_ms();
582 * Make the target (re)start executing using its saved execution
583 * context (possibly with some modifications).
585 * @param target Which target should start executing.
586 * @param current True to use the target's saved program counter instead
587 * of the address parameter
588 * @param address Optionally used as the program counter.
589 * @param handle_breakpoints True iff breakpoints at the resumption PC
590 * should be skipped. (For example, maybe execution was stopped by
591 * such a breakpoint, in which case it would be counterprodutive to
593 * @param debug_execution False if all working areas allocated by OpenOCD
594 * should be released and/or restored to their original contents.
595 * (This would for example be true to run some downloaded "helper"
596 * algorithm code, which resides in one such working buffer and uses
597 * another for data storage.)
599 * @todo Resolve the ambiguity about what the "debug_execution" flag
600 * signifies. For example, Target implementations don't agree on how
601 * it relates to invalidation of the register cache, or to whether
602 * breakpoints and watchpoints should be enabled. (It would seem wrong
603 * to enable breakpoints when running downloaded "helper" algorithms
604 * (debug_execution true), since the breakpoints would be set to match
605 * target firmware being debugged, not the helper algorithm.... and
606 * enabling them could cause such helpers to malfunction (for example,
607 * by overwriting data with a breakpoint instruction. On the other
608 * hand the infrastructure for running such helpers might use this
609 * procedure but rely on hardware breakpoint to detect termination.)
611 int target_resume(struct target *target, int current, target_addr_t address,
612 int handle_breakpoints, int debug_execution)
616 /* We can't poll until after examine */
617 if (!target_was_examined(target)) {
618 LOG_ERROR("Target not examined yet");
622 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
624 /* note that resume *must* be asynchronous. The CPU can halt before
625 * we poll. The CPU can even halt at the current PC as a result of
626 * a software breakpoint being inserted by (a bug?) the application.
628 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
629 if (retval != ERROR_OK)
632 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
637 static int target_process_reset(struct command_invocation *cmd, enum target_reset_mode reset_mode)
642 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
643 if (n->name == NULL) {
644 LOG_ERROR("invalid reset mode");
648 struct target *target;
649 for (target = all_targets; target; target = target->next)
650 target_call_reset_callbacks(target, reset_mode);
652 /* disable polling during reset to make reset event scripts
653 * more predictable, i.e. dr/irscan & pathmove in events will
654 * not have JTAG operations injected into the middle of a sequence.
656 bool save_poll = jtag_poll_get_enabled();
658 jtag_poll_set_enabled(false);
660 sprintf(buf, "ocd_process_reset %s", n->name);
661 retval = Jim_Eval(cmd->ctx->interp, buf);
663 jtag_poll_set_enabled(save_poll);
665 if (retval != JIM_OK) {
666 Jim_MakeErrorMessage(cmd->ctx->interp);
667 command_print(cmd, "%s", Jim_GetString(Jim_GetResult(cmd->ctx->interp), NULL));
671 /* We want any events to be processed before the prompt */
672 retval = target_call_timer_callbacks_now();
674 for (target = all_targets; target; target = target->next) {
675 target->type->check_reset(target);
676 target->running_alg = false;
682 static int identity_virt2phys(struct target *target,
683 target_addr_t virtual, target_addr_t *physical)
689 static int no_mmu(struct target *target, int *enabled)
695 static int default_examine(struct target *target)
697 target_set_examined(target);
701 /* no check by default */
702 static int default_check_reset(struct target *target)
707 int target_examine_one(struct target *target)
709 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
711 int retval = target->type->examine(target);
712 if (retval != ERROR_OK)
715 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
720 static int jtag_enable_callback(enum jtag_event event, void *priv)
722 struct target *target = priv;
724 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
727 jtag_unregister_event_callback(jtag_enable_callback, target);
729 return target_examine_one(target);
732 /* Targets that correctly implement init + examine, i.e.
733 * no communication with target during init:
737 int target_examine(void)
739 int retval = ERROR_OK;
740 struct target *target;
742 for (target = all_targets; target; target = target->next) {
743 /* defer examination, but don't skip it */
744 if (!target->tap->enabled) {
745 jtag_register_event_callback(jtag_enable_callback,
750 if (target->defer_examine)
753 retval = target_examine_one(target);
754 if (retval != ERROR_OK)
760 const char *target_type_name(struct target *target)
762 return target->type->name;
765 static int target_soft_reset_halt(struct target *target)
767 if (!target_was_examined(target)) {
768 LOG_ERROR("Target not examined yet");
771 if (!target->type->soft_reset_halt) {
772 LOG_ERROR("Target %s does not support soft_reset_halt",
773 target_name(target));
776 return target->type->soft_reset_halt(target);
780 * Downloads a target-specific native code algorithm to the target,
781 * and executes it. * Note that some targets may need to set up, enable,
782 * and tear down a breakpoint (hard or * soft) to detect algorithm
783 * termination, while others may support lower overhead schemes where
784 * soft breakpoints embedded in the algorithm automatically terminate the
787 * @param target used to run the algorithm
788 * @param arch_info target-specific description of the algorithm.
790 int target_run_algorithm(struct target *target,
791 int num_mem_params, struct mem_param *mem_params,
792 int num_reg_params, struct reg_param *reg_param,
793 uint32_t entry_point, uint32_t exit_point,
794 int timeout_ms, void *arch_info)
796 int retval = ERROR_FAIL;
798 if (!target_was_examined(target)) {
799 LOG_ERROR("Target not examined yet");
802 if (!target->type->run_algorithm) {
803 LOG_ERROR("Target type '%s' does not support %s",
804 target_type_name(target), __func__);
808 target->running_alg = true;
809 retval = target->type->run_algorithm(target,
810 num_mem_params, mem_params,
811 num_reg_params, reg_param,
812 entry_point, exit_point, timeout_ms, arch_info);
813 target->running_alg = false;
820 * Executes a target-specific native code algorithm and leaves it running.
822 * @param target used to run the algorithm
823 * @param arch_info target-specific description of the algorithm.
825 int target_start_algorithm(struct target *target,
826 int num_mem_params, struct mem_param *mem_params,
827 int num_reg_params, struct reg_param *reg_params,
828 uint32_t entry_point, uint32_t exit_point,
831 int retval = ERROR_FAIL;
833 if (!target_was_examined(target)) {
834 LOG_ERROR("Target not examined yet");
837 if (!target->type->start_algorithm) {
838 LOG_ERROR("Target type '%s' does not support %s",
839 target_type_name(target), __func__);
842 if (target->running_alg) {
843 LOG_ERROR("Target is already running an algorithm");
847 target->running_alg = true;
848 retval = target->type->start_algorithm(target,
849 num_mem_params, mem_params,
850 num_reg_params, reg_params,
851 entry_point, exit_point, arch_info);
858 * Waits for an algorithm started with target_start_algorithm() to complete.
860 * @param target used to run the algorithm
861 * @param arch_info target-specific description of the algorithm.
863 int target_wait_algorithm(struct target *target,
864 int num_mem_params, struct mem_param *mem_params,
865 int num_reg_params, struct reg_param *reg_params,
866 uint32_t exit_point, int timeout_ms,
869 int retval = ERROR_FAIL;
871 if (!target->type->wait_algorithm) {
872 LOG_ERROR("Target type '%s' does not support %s",
873 target_type_name(target), __func__);
876 if (!target->running_alg) {
877 LOG_ERROR("Target is not running an algorithm");
881 retval = target->type->wait_algorithm(target,
882 num_mem_params, mem_params,
883 num_reg_params, reg_params,
884 exit_point, timeout_ms, arch_info);
885 if (retval != ERROR_TARGET_TIMEOUT)
886 target->running_alg = false;
893 * Streams data to a circular buffer on target intended for consumption by code
894 * running asynchronously on target.
896 * This is intended for applications where target-specific native code runs
897 * on the target, receives data from the circular buffer, does something with
898 * it (most likely writing it to a flash memory), and advances the circular
901 * This assumes that the helper algorithm has already been loaded to the target,
902 * but has not been started yet. Given memory and register parameters are passed
905 * The buffer is defined by (buffer_start, buffer_size) arguments and has the
908 * [buffer_start + 0, buffer_start + 4):
909 * Write Pointer address (aka head). Written and updated by this
910 * routine when new data is written to the circular buffer.
911 * [buffer_start + 4, buffer_start + 8):
912 * Read Pointer address (aka tail). Updated by code running on the
913 * target after it consumes data.
914 * [buffer_start + 8, buffer_start + buffer_size):
915 * Circular buffer contents.
917 * See contrib/loaders/flash/stm32f1x.S for an example.
919 * @param target used to run the algorithm
920 * @param buffer address on the host where data to be sent is located
921 * @param count number of blocks to send
922 * @param block_size size in bytes of each block
923 * @param num_mem_params count of memory-based params to pass to algorithm
924 * @param mem_params memory-based params to pass to algorithm
925 * @param num_reg_params count of register-based params to pass to algorithm
926 * @param reg_params memory-based params to pass to algorithm
927 * @param buffer_start address on the target of the circular buffer structure
928 * @param buffer_size size of the circular buffer structure
929 * @param entry_point address on the target to execute to start the algorithm
930 * @param exit_point address at which to set a breakpoint to catch the
931 * end of the algorithm; can be 0 if target triggers a breakpoint itself
934 int target_run_flash_async_algorithm(struct target *target,
935 const uint8_t *buffer, uint32_t count, int block_size,
936 int num_mem_params, struct mem_param *mem_params,
937 int num_reg_params, struct reg_param *reg_params,
938 uint32_t buffer_start, uint32_t buffer_size,
939 uint32_t entry_point, uint32_t exit_point, void *arch_info)
944 const uint8_t *buffer_orig = buffer;
946 /* Set up working area. First word is write pointer, second word is read pointer,
947 * rest is fifo data area. */
948 uint32_t wp_addr = buffer_start;
949 uint32_t rp_addr = buffer_start + 4;
950 uint32_t fifo_start_addr = buffer_start + 8;
951 uint32_t fifo_end_addr = buffer_start + buffer_size;
953 uint32_t wp = fifo_start_addr;
954 uint32_t rp = fifo_start_addr;
956 /* validate block_size is 2^n */
957 assert(!block_size || !(block_size & (block_size - 1)));
959 retval = target_write_u32(target, wp_addr, wp);
960 if (retval != ERROR_OK)
962 retval = target_write_u32(target, rp_addr, rp);
963 if (retval != ERROR_OK)
966 /* Start up algorithm on target and let it idle while writing the first chunk */
967 retval = target_start_algorithm(target, num_mem_params, mem_params,
968 num_reg_params, reg_params,
973 if (retval != ERROR_OK) {
974 LOG_ERROR("error starting target flash write algorithm");
980 retval = target_read_u32(target, rp_addr, &rp);
981 if (retval != ERROR_OK) {
982 LOG_ERROR("failed to get read pointer");
986 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
987 (size_t) (buffer - buffer_orig), count, wp, rp);
990 LOG_ERROR("flash write algorithm aborted by target");
991 retval = ERROR_FLASH_OPERATION_FAILED;
995 if (((rp - fifo_start_addr) & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
996 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
1000 /* Count the number of bytes available in the fifo without
1001 * crossing the wrap around. Make sure to not fill it completely,
1002 * because that would make wp == rp and that's the empty condition. */
1003 uint32_t thisrun_bytes;
1005 thisrun_bytes = rp - wp - block_size;
1006 else if (rp > fifo_start_addr)
1007 thisrun_bytes = fifo_end_addr - wp;
1009 thisrun_bytes = fifo_end_addr - wp - block_size;
1011 if (thisrun_bytes == 0) {
1012 /* Throttle polling a bit if transfer is (much) faster than flash
1013 * programming. The exact delay shouldn't matter as long as it's
1014 * less than buffer size / flash speed. This is very unlikely to
1015 * run when using high latency connections such as USB. */
1018 /* to stop an infinite loop on some targets check and increment a timeout
1019 * this issue was observed on a stellaris using the new ICDI interface */
1020 if (timeout++ >= 500) {
1021 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1022 return ERROR_FLASH_OPERATION_FAILED;
1027 /* reset our timeout */
1030 /* Limit to the amount of data we actually want to write */
1031 if (thisrun_bytes > count * block_size)
1032 thisrun_bytes = count * block_size;
1034 /* Write data to fifo */
1035 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
1036 if (retval != ERROR_OK)
1039 /* Update counters and wrap write pointer */
1040 buffer += thisrun_bytes;
1041 count -= thisrun_bytes / block_size;
1042 wp += thisrun_bytes;
1043 if (wp >= fifo_end_addr)
1044 wp = fifo_start_addr;
1046 /* Store updated write pointer to target */
1047 retval = target_write_u32(target, wp_addr, wp);
1048 if (retval != ERROR_OK)
1051 /* Avoid GDB timeouts */
1055 if (retval != ERROR_OK) {
1056 /* abort flash write algorithm on target */
1057 target_write_u32(target, wp_addr, 0);
1060 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1061 num_reg_params, reg_params,
1066 if (retval2 != ERROR_OK) {
1067 LOG_ERROR("error waiting for target flash write algorithm");
1071 if (retval == ERROR_OK) {
1072 /* check if algorithm set rp = 0 after fifo writer loop finished */
1073 retval = target_read_u32(target, rp_addr, &rp);
1074 if (retval == ERROR_OK && rp == 0) {
1075 LOG_ERROR("flash write algorithm aborted by target");
1076 retval = ERROR_FLASH_OPERATION_FAILED;
1083 int target_read_memory(struct target *target,
1084 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1086 if (!target_was_examined(target)) {
1087 LOG_ERROR("Target not examined yet");
1090 if (!target->type->read_memory) {
1091 LOG_ERROR("Target %s doesn't support read_memory", target_name(target));
1094 return target->type->read_memory(target, address, size, count, buffer);
1097 int target_read_phys_memory(struct target *target,
1098 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1100 if (!target_was_examined(target)) {
1101 LOG_ERROR("Target not examined yet");
1104 if (!target->type->read_phys_memory) {
1105 LOG_ERROR("Target %s doesn't support read_phys_memory", target_name(target));
1108 return target->type->read_phys_memory(target, address, size, count, buffer);
1111 int target_write_memory(struct target *target,
1112 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1114 if (!target_was_examined(target)) {
1115 LOG_ERROR("Target not examined yet");
1118 if (!target->type->write_memory) {
1119 LOG_ERROR("Target %s doesn't support write_memory", target_name(target));
1122 return target->type->write_memory(target, address, size, count, buffer);
1125 int target_write_phys_memory(struct target *target,
1126 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1128 if (!target_was_examined(target)) {
1129 LOG_ERROR("Target not examined yet");
1132 if (!target->type->write_phys_memory) {
1133 LOG_ERROR("Target %s doesn't support write_phys_memory", target_name(target));
1136 return target->type->write_phys_memory(target, address, size, count, buffer);
1139 int target_add_breakpoint(struct target *target,
1140 struct breakpoint *breakpoint)
1142 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1143 LOG_WARNING("target %s is not halted (add breakpoint)", target_name(target));
1144 return ERROR_TARGET_NOT_HALTED;
1146 return target->type->add_breakpoint(target, breakpoint);
1149 int target_add_context_breakpoint(struct target *target,
1150 struct breakpoint *breakpoint)
1152 if (target->state != TARGET_HALTED) {
1153 LOG_WARNING("target %s is not halted (add context breakpoint)", target_name(target));
1154 return ERROR_TARGET_NOT_HALTED;
1156 return target->type->add_context_breakpoint(target, breakpoint);
1159 int target_add_hybrid_breakpoint(struct target *target,
1160 struct breakpoint *breakpoint)
1162 if (target->state != TARGET_HALTED) {
1163 LOG_WARNING("target %s is not halted (add hybrid breakpoint)", target_name(target));
1164 return ERROR_TARGET_NOT_HALTED;
1166 return target->type->add_hybrid_breakpoint(target, breakpoint);
1169 int target_remove_breakpoint(struct target *target,
1170 struct breakpoint *breakpoint)
1172 return target->type->remove_breakpoint(target, breakpoint);
1175 int target_add_watchpoint(struct target *target,
1176 struct watchpoint *watchpoint)
1178 if (target->state != TARGET_HALTED) {
1179 LOG_WARNING("target %s is not halted (add watchpoint)", target_name(target));
1180 return ERROR_TARGET_NOT_HALTED;
1182 return target->type->add_watchpoint(target, watchpoint);
1184 int target_remove_watchpoint(struct target *target,
1185 struct watchpoint *watchpoint)
1187 return target->type->remove_watchpoint(target, watchpoint);
1189 int target_hit_watchpoint(struct target *target,
1190 struct watchpoint **hit_watchpoint)
1192 if (target->state != TARGET_HALTED) {
1193 LOG_WARNING("target %s is not halted (hit watchpoint)", target->cmd_name);
1194 return ERROR_TARGET_NOT_HALTED;
1197 if (target->type->hit_watchpoint == NULL) {
1198 /* For backward compatible, if hit_watchpoint is not implemented,
1199 * return ERROR_FAIL such that gdb_server will not take the nonsense
1204 return target->type->hit_watchpoint(target, hit_watchpoint);
1207 const char *target_get_gdb_arch(struct target *target)
1209 if (target->type->get_gdb_arch == NULL)
1211 return target->type->get_gdb_arch(target);
1214 int target_get_gdb_reg_list(struct target *target,
1215 struct reg **reg_list[], int *reg_list_size,
1216 enum target_register_class reg_class)
1218 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1221 bool target_supports_gdb_connection(struct target *target)
1224 * based on current code, we can simply exclude all the targets that
1225 * don't provide get_gdb_reg_list; this could change with new targets.
1227 return !!target->type->get_gdb_reg_list;
1230 int target_step(struct target *target,
1231 int current, target_addr_t address, int handle_breakpoints)
1233 return target->type->step(target, current, address, handle_breakpoints);
1236 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1238 if (target->state != TARGET_HALTED) {
1239 LOG_WARNING("target %s is not halted (gdb fileio)", target->cmd_name);
1240 return ERROR_TARGET_NOT_HALTED;
1242 return target->type->get_gdb_fileio_info(target, fileio_info);
1245 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1247 if (target->state != TARGET_HALTED) {
1248 LOG_WARNING("target %s is not halted (gdb fileio end)", target->cmd_name);
1249 return ERROR_TARGET_NOT_HALTED;
1251 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1254 target_addr_t target_address_max(struct target *target)
1256 unsigned bits = target_address_bits(target);
1257 if (sizeof(target_addr_t) * 8 == bits)
1258 return (target_addr_t) -1;
1260 return (((target_addr_t) 1) << bits) - 1;
1263 unsigned target_address_bits(struct target *target)
1265 if (target->type->address_bits)
1266 return target->type->address_bits(target);
1270 int target_profiling(struct target *target, uint32_t *samples,
1271 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1273 if (target->state != TARGET_HALTED) {
1274 LOG_WARNING("target %s is not halted (profiling)", target->cmd_name);
1275 return ERROR_TARGET_NOT_HALTED;
1277 return target->type->profiling(target, samples, max_num_samples,
1278 num_samples, seconds);
1282 * Reset the @c examined flag for the given target.
1283 * Pure paranoia -- targets are zeroed on allocation.
1285 static void target_reset_examined(struct target *target)
1287 target->examined = false;
1290 static int handle_target(void *priv);
1292 static int target_init_one(struct command_context *cmd_ctx,
1293 struct target *target)
1295 target_reset_examined(target);
1297 struct target_type *type = target->type;
1298 if (type->examine == NULL)
1299 type->examine = default_examine;
1301 if (type->check_reset == NULL)
1302 type->check_reset = default_check_reset;
1304 assert(type->init_target != NULL);
1306 int retval = type->init_target(cmd_ctx, target);
1307 if (ERROR_OK != retval) {
1308 LOG_ERROR("target '%s' init failed", target_name(target));
1312 /* Sanity-check MMU support ... stub in what we must, to help
1313 * implement it in stages, but warn if we need to do so.
1316 if (type->virt2phys == NULL) {
1317 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1318 type->virt2phys = identity_virt2phys;
1321 /* Make sure no-MMU targets all behave the same: make no
1322 * distinction between physical and virtual addresses, and
1323 * ensure that virt2phys() is always an identity mapping.
1325 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1326 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1329 type->write_phys_memory = type->write_memory;
1330 type->read_phys_memory = type->read_memory;
1331 type->virt2phys = identity_virt2phys;
1334 if (target->type->read_buffer == NULL)
1335 target->type->read_buffer = target_read_buffer_default;
1337 if (target->type->write_buffer == NULL)
1338 target->type->write_buffer = target_write_buffer_default;
1340 if (target->type->get_gdb_fileio_info == NULL)
1341 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1343 if (target->type->gdb_fileio_end == NULL)
1344 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1346 if (target->type->profiling == NULL)
1347 target->type->profiling = target_profiling_default;
1352 static int target_init(struct command_context *cmd_ctx)
1354 struct target *target;
1357 for (target = all_targets; target; target = target->next) {
1358 retval = target_init_one(cmd_ctx, target);
1359 if (ERROR_OK != retval)
1366 retval = target_register_user_commands(cmd_ctx);
1367 if (ERROR_OK != retval)
1370 retval = target_register_timer_callback(&handle_target,
1371 polling_interval, TARGET_TIMER_TYPE_PERIODIC, cmd_ctx->interp);
1372 if (ERROR_OK != retval)
1378 COMMAND_HANDLER(handle_target_init_command)
1383 return ERROR_COMMAND_SYNTAX_ERROR;
1385 static bool target_initialized;
1386 if (target_initialized) {
1387 LOG_INFO("'target init' has already been called");
1390 target_initialized = true;
1392 retval = command_run_line(CMD_CTX, "init_targets");
1393 if (ERROR_OK != retval)
1396 retval = command_run_line(CMD_CTX, "init_target_events");
1397 if (ERROR_OK != retval)
1400 retval = command_run_line(CMD_CTX, "init_board");
1401 if (ERROR_OK != retval)
1404 LOG_DEBUG("Initializing targets...");
1405 return target_init(CMD_CTX);
1408 int target_register_event_callback(int (*callback)(struct target *target,
1409 enum target_event event, void *priv), void *priv)
1411 struct target_event_callback **callbacks_p = &target_event_callbacks;
1413 if (callback == NULL)
1414 return ERROR_COMMAND_SYNTAX_ERROR;
1417 while ((*callbacks_p)->next)
1418 callbacks_p = &((*callbacks_p)->next);
1419 callbacks_p = &((*callbacks_p)->next);
1422 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1423 (*callbacks_p)->callback = callback;
1424 (*callbacks_p)->priv = priv;
1425 (*callbacks_p)->next = NULL;
1430 int target_register_reset_callback(int (*callback)(struct target *target,
1431 enum target_reset_mode reset_mode, void *priv), void *priv)
1433 struct target_reset_callback *entry;
1435 if (callback == NULL)
1436 return ERROR_COMMAND_SYNTAX_ERROR;
1438 entry = malloc(sizeof(struct target_reset_callback));
1439 if (entry == NULL) {
1440 LOG_ERROR("error allocating buffer for reset callback entry");
1441 return ERROR_COMMAND_SYNTAX_ERROR;
1444 entry->callback = callback;
1446 list_add(&entry->list, &target_reset_callback_list);
1452 int target_register_trace_callback(int (*callback)(struct target *target,
1453 size_t len, uint8_t *data, void *priv), void *priv)
1455 struct target_trace_callback *entry;
1457 if (callback == NULL)
1458 return ERROR_COMMAND_SYNTAX_ERROR;
1460 entry = malloc(sizeof(struct target_trace_callback));
1461 if (entry == NULL) {
1462 LOG_ERROR("error allocating buffer for trace callback entry");
1463 return ERROR_COMMAND_SYNTAX_ERROR;
1466 entry->callback = callback;
1468 list_add(&entry->list, &target_trace_callback_list);
1474 int target_register_timer_callback(int (*callback)(void *priv),
1475 unsigned int time_ms, enum target_timer_type type, void *priv)
1477 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1479 if (callback == NULL)
1480 return ERROR_COMMAND_SYNTAX_ERROR;
1483 while ((*callbacks_p)->next)
1484 callbacks_p = &((*callbacks_p)->next);
1485 callbacks_p = &((*callbacks_p)->next);
1488 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1489 (*callbacks_p)->callback = callback;
1490 (*callbacks_p)->type = type;
1491 (*callbacks_p)->time_ms = time_ms;
1492 (*callbacks_p)->removed = false;
1494 gettimeofday(&(*callbacks_p)->when, NULL);
1495 timeval_add_time(&(*callbacks_p)->when, 0, time_ms * 1000);
1497 (*callbacks_p)->priv = priv;
1498 (*callbacks_p)->next = NULL;
1503 int target_unregister_event_callback(int (*callback)(struct target *target,
1504 enum target_event event, void *priv), void *priv)
1506 struct target_event_callback **p = &target_event_callbacks;
1507 struct target_event_callback *c = target_event_callbacks;
1509 if (callback == NULL)
1510 return ERROR_COMMAND_SYNTAX_ERROR;
1513 struct target_event_callback *next = c->next;
1514 if ((c->callback == callback) && (c->priv == priv)) {
1526 int target_unregister_reset_callback(int (*callback)(struct target *target,
1527 enum target_reset_mode reset_mode, void *priv), void *priv)
1529 struct target_reset_callback *entry;
1531 if (callback == NULL)
1532 return ERROR_COMMAND_SYNTAX_ERROR;
1534 list_for_each_entry(entry, &target_reset_callback_list, list) {
1535 if (entry->callback == callback && entry->priv == priv) {
1536 list_del(&entry->list);
1545 int target_unregister_trace_callback(int (*callback)(struct target *target,
1546 size_t len, uint8_t *data, void *priv), void *priv)
1548 struct target_trace_callback *entry;
1550 if (callback == NULL)
1551 return ERROR_COMMAND_SYNTAX_ERROR;
1553 list_for_each_entry(entry, &target_trace_callback_list, list) {
1554 if (entry->callback == callback && entry->priv == priv) {
1555 list_del(&entry->list);
1564 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1566 if (callback == NULL)
1567 return ERROR_COMMAND_SYNTAX_ERROR;
1569 for (struct target_timer_callback *c = target_timer_callbacks;
1571 if ((c->callback == callback) && (c->priv == priv)) {
1580 int target_call_event_callbacks(struct target *target, enum target_event event)
1582 struct target_event_callback *callback = target_event_callbacks;
1583 struct target_event_callback *next_callback;
1585 if (event == TARGET_EVENT_HALTED) {
1586 /* execute early halted first */
1587 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1590 LOG_DEBUG("target event %i (%s)", event,
1591 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1593 target_handle_event(target, event);
1596 next_callback = callback->next;
1597 callback->callback(target, event, callback->priv);
1598 callback = next_callback;
1604 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1606 struct target_reset_callback *callback;
1608 LOG_DEBUG("target reset %i (%s)", reset_mode,
1609 Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name);
1611 list_for_each_entry(callback, &target_reset_callback_list, list)
1612 callback->callback(target, reset_mode, callback->priv);
1617 int target_call_trace_callbacks(struct target *target, size_t len, uint8_t *data)
1619 struct target_trace_callback *callback;
1621 list_for_each_entry(callback, &target_trace_callback_list, list)
1622 callback->callback(target, len, data, callback->priv);
1627 static int target_timer_callback_periodic_restart(
1628 struct target_timer_callback *cb, struct timeval *now)
1631 timeval_add_time(&cb->when, 0, cb->time_ms * 1000L);
1635 static int target_call_timer_callback(struct target_timer_callback *cb,
1636 struct timeval *now)
1638 cb->callback(cb->priv);
1640 if (cb->type == TARGET_TIMER_TYPE_PERIODIC)
1641 return target_timer_callback_periodic_restart(cb, now);
1643 return target_unregister_timer_callback(cb->callback, cb->priv);
1646 static int target_call_timer_callbacks_check_time(int checktime)
1648 static bool callback_processing;
1650 /* Do not allow nesting */
1651 if (callback_processing)
1654 callback_processing = true;
1659 gettimeofday(&now, NULL);
1661 /* Store an address of the place containing a pointer to the
1662 * next item; initially, that's a standalone "root of the
1663 * list" variable. */
1664 struct target_timer_callback **callback = &target_timer_callbacks;
1666 if ((*callback)->removed) {
1667 struct target_timer_callback *p = *callback;
1668 *callback = (*callback)->next;
1673 bool call_it = (*callback)->callback &&
1674 ((!checktime && (*callback)->type == TARGET_TIMER_TYPE_PERIODIC) ||
1675 timeval_compare(&now, &(*callback)->when) >= 0);
1678 target_call_timer_callback(*callback, &now);
1680 callback = &(*callback)->next;
1683 callback_processing = false;
1687 int target_call_timer_callbacks(void)
1689 return target_call_timer_callbacks_check_time(1);
1692 /* invoke periodic callbacks immediately */
1693 int target_call_timer_callbacks_now(void)
1695 return target_call_timer_callbacks_check_time(0);
1698 /* Prints the working area layout for debug purposes */
1699 static void print_wa_layout(struct target *target)
1701 struct working_area *c = target->working_areas;
1704 LOG_DEBUG("%c%c " TARGET_ADDR_FMT "-" TARGET_ADDR_FMT " (%" PRIu32 " bytes)",
1705 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1706 c->address, c->address + c->size - 1, c->size);
1711 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1712 static void target_split_working_area(struct working_area *area, uint32_t size)
1714 assert(area->free); /* Shouldn't split an allocated area */
1715 assert(size <= area->size); /* Caller should guarantee this */
1717 /* Split only if not already the right size */
1718 if (size < area->size) {
1719 struct working_area *new_wa = malloc(sizeof(*new_wa));
1724 new_wa->next = area->next;
1725 new_wa->size = area->size - size;
1726 new_wa->address = area->address + size;
1727 new_wa->backup = NULL;
1728 new_wa->user = NULL;
1729 new_wa->free = true;
1731 area->next = new_wa;
1734 /* If backup memory was allocated to this area, it has the wrong size
1735 * now so free it and it will be reallocated if/when needed */
1738 area->backup = NULL;
1743 /* Merge all adjacent free areas into one */
1744 static void target_merge_working_areas(struct target *target)
1746 struct working_area *c = target->working_areas;
1748 while (c && c->next) {
1749 assert(c->next->address == c->address + c->size); /* This is an invariant */
1751 /* Find two adjacent free areas */
1752 if (c->free && c->next->free) {
1753 /* Merge the last into the first */
1754 c->size += c->next->size;
1756 /* Remove the last */
1757 struct working_area *to_be_freed = c->next;
1758 c->next = c->next->next;
1759 if (to_be_freed->backup)
1760 free(to_be_freed->backup);
1763 /* If backup memory was allocated to the remaining area, it's has
1764 * the wrong size now */
1775 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1777 /* Reevaluate working area address based on MMU state*/
1778 if (target->working_areas == NULL) {
1782 retval = target->type->mmu(target, &enabled);
1783 if (retval != ERROR_OK)
1787 if (target->working_area_phys_spec) {
1788 LOG_DEBUG("MMU disabled, using physical "
1789 "address for working memory " TARGET_ADDR_FMT,
1790 target->working_area_phys);
1791 target->working_area = target->working_area_phys;
1793 LOG_ERROR("No working memory available. "
1794 "Specify -work-area-phys to target.");
1795 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1798 if (target->working_area_virt_spec) {
1799 LOG_DEBUG("MMU enabled, using virtual "
1800 "address for working memory " TARGET_ADDR_FMT,
1801 target->working_area_virt);
1802 target->working_area = target->working_area_virt;
1804 LOG_ERROR("No working memory available. "
1805 "Specify -work-area-virt to target.");
1806 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1810 /* Set up initial working area on first call */
1811 struct working_area *new_wa = malloc(sizeof(*new_wa));
1813 new_wa->next = NULL;
1814 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1815 new_wa->address = target->working_area;
1816 new_wa->backup = NULL;
1817 new_wa->user = NULL;
1818 new_wa->free = true;
1821 target->working_areas = new_wa;
1824 /* only allocate multiples of 4 byte */
1826 size = (size + 3) & (~3UL);
1828 struct working_area *c = target->working_areas;
1830 /* Find the first large enough working area */
1832 if (c->free && c->size >= size)
1838 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1840 /* Split the working area into the requested size */
1841 target_split_working_area(c, size);
1843 LOG_DEBUG("allocated new working area of %" PRIu32 " bytes at address " TARGET_ADDR_FMT,
1846 if (target->backup_working_area) {
1847 if (c->backup == NULL) {
1848 c->backup = malloc(c->size);
1849 if (c->backup == NULL)
1853 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1854 if (retval != ERROR_OK)
1858 /* mark as used, and return the new (reused) area */
1865 print_wa_layout(target);
1870 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1874 retval = target_alloc_working_area_try(target, size, area);
1875 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1876 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1881 static int target_restore_working_area(struct target *target, struct working_area *area)
1883 int retval = ERROR_OK;
1885 if (target->backup_working_area && area->backup != NULL) {
1886 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1887 if (retval != ERROR_OK)
1888 LOG_ERROR("failed to restore %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
1889 area->size, area->address);
1895 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1896 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1898 int retval = ERROR_OK;
1904 retval = target_restore_working_area(target, area);
1905 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1906 if (retval != ERROR_OK)
1912 LOG_DEBUG("freed %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
1913 area->size, area->address);
1915 /* mark user pointer invalid */
1916 /* TODO: Is this really safe? It points to some previous caller's memory.
1917 * How could we know that the area pointer is still in that place and not
1918 * some other vital data? What's the purpose of this, anyway? */
1922 target_merge_working_areas(target);
1924 print_wa_layout(target);
1929 int target_free_working_area(struct target *target, struct working_area *area)
1931 return target_free_working_area_restore(target, area, 1);
1934 /* free resources and restore memory, if restoring memory fails,
1935 * free up resources anyway
1937 static void target_free_all_working_areas_restore(struct target *target, int restore)
1939 struct working_area *c = target->working_areas;
1941 LOG_DEBUG("freeing all working areas");
1943 /* Loop through all areas, restoring the allocated ones and marking them as free */
1947 target_restore_working_area(target, c);
1949 *c->user = NULL; /* Same as above */
1955 /* Run a merge pass to combine all areas into one */
1956 target_merge_working_areas(target);
1958 print_wa_layout(target);
1961 void target_free_all_working_areas(struct target *target)
1963 target_free_all_working_areas_restore(target, 1);
1965 /* Now we have none or only one working area marked as free */
1966 if (target->working_areas) {
1967 /* Free the last one to allow on-the-fly moving and resizing */
1968 free(target->working_areas->backup);
1969 free(target->working_areas);
1970 target->working_areas = NULL;
1974 /* Find the largest number of bytes that can be allocated */
1975 uint32_t target_get_working_area_avail(struct target *target)
1977 struct working_area *c = target->working_areas;
1978 uint32_t max_size = 0;
1981 return target->working_area_size;
1984 if (c->free && max_size < c->size)
1993 static void target_destroy(struct target *target)
1995 if (target->type->deinit_target)
1996 target->type->deinit_target(target);
1998 if (target->semihosting)
1999 free(target->semihosting);
2001 jtag_unregister_event_callback(jtag_enable_callback, target);
2003 struct target_event_action *teap = target->event_action;
2005 struct target_event_action *next = teap->next;
2006 Jim_DecrRefCount(teap->interp, teap->body);
2011 target_free_all_working_areas(target);
2013 /* release the targets SMP list */
2015 struct target_list *head = target->head;
2016 while (head != NULL) {
2017 struct target_list *pos = head->next;
2018 head->target->smp = 0;
2025 free(target->gdb_port_override);
2027 free(target->trace_info);
2028 free(target->fileio_info);
2029 free(target->cmd_name);
2033 void target_quit(void)
2035 struct target_event_callback *pe = target_event_callbacks;
2037 struct target_event_callback *t = pe->next;
2041 target_event_callbacks = NULL;
2043 struct target_timer_callback *pt = target_timer_callbacks;
2045 struct target_timer_callback *t = pt->next;
2049 target_timer_callbacks = NULL;
2051 for (struct target *target = all_targets; target;) {
2055 target_destroy(target);
2062 int target_arch_state(struct target *target)
2065 if (target == NULL) {
2066 LOG_WARNING("No target has been configured");
2070 if (target->state != TARGET_HALTED)
2073 retval = target->type->arch_state(target);
2077 static int target_get_gdb_fileio_info_default(struct target *target,
2078 struct gdb_fileio_info *fileio_info)
2080 /* If target does not support semi-hosting function, target
2081 has no need to provide .get_gdb_fileio_info callback.
2082 It just return ERROR_FAIL and gdb_server will return "Txx"
2083 as target halted every time. */
2087 static int target_gdb_fileio_end_default(struct target *target,
2088 int retcode, int fileio_errno, bool ctrl_c)
2093 static int target_profiling_default(struct target *target, uint32_t *samples,
2094 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
2096 struct timeval timeout, now;
2098 gettimeofday(&timeout, NULL);
2099 timeval_add_time(&timeout, seconds, 0);
2101 LOG_INFO("Starting profiling. Halting and resuming the"
2102 " target as often as we can...");
2104 uint32_t sample_count = 0;
2105 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2106 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
2108 int retval = ERROR_OK;
2110 target_poll(target);
2111 if (target->state == TARGET_HALTED) {
2112 uint32_t t = buf_get_u32(reg->value, 0, 32);
2113 samples[sample_count++] = t;
2114 /* current pc, addr = 0, do not handle breakpoints, not debugging */
2115 retval = target_resume(target, 1, 0, 0, 0);
2116 target_poll(target);
2117 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2118 } else if (target->state == TARGET_RUNNING) {
2119 /* We want to quickly sample the PC. */
2120 retval = target_halt(target);
2122 LOG_INFO("Target not halted or running");
2127 if (retval != ERROR_OK)
2130 gettimeofday(&now, NULL);
2131 if ((sample_count >= max_num_samples) || timeval_compare(&now, &timeout) >= 0) {
2132 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2137 *num_samples = sample_count;
2141 /* Single aligned words are guaranteed to use 16 or 32 bit access
2142 * mode respectively, otherwise data is handled as quickly as
2145 int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
2147 LOG_DEBUG("writing buffer of %" PRIi32 " byte at " TARGET_ADDR_FMT,
2150 if (!target_was_examined(target)) {
2151 LOG_ERROR("Target not examined yet");
2158 if ((address + size - 1) < address) {
2159 /* GDB can request this when e.g. PC is 0xfffffffc */
2160 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2166 return target->type->write_buffer(target, address, size, buffer);
2169 static int target_write_buffer_default(struct target *target,
2170 target_addr_t address, uint32_t count, const uint8_t *buffer)
2174 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2175 * will have something to do with the size we leave to it. */
2176 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2177 if (address & size) {
2178 int retval = target_write_memory(target, address, size, 1, buffer);
2179 if (retval != ERROR_OK)
2187 /* Write the data with as large access size as possible. */
2188 for (; size > 0; size /= 2) {
2189 uint32_t aligned = count - count % size;
2191 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2192 if (retval != ERROR_OK)
2203 /* Single aligned words are guaranteed to use 16 or 32 bit access
2204 * mode respectively, otherwise data is handled as quickly as
2207 int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
2209 LOG_DEBUG("reading buffer of %" PRIi32 " byte at " TARGET_ADDR_FMT,
2212 if (!target_was_examined(target)) {
2213 LOG_ERROR("Target not examined yet");
2220 if ((address + size - 1) < address) {
2221 /* GDB can request this when e.g. PC is 0xfffffffc */
2222 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2228 return target->type->read_buffer(target, address, size, buffer);
2231 static int target_read_buffer_default(struct target *target, target_addr_t address, uint32_t count, uint8_t *buffer)
2235 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2236 * will have something to do with the size we leave to it. */
2237 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2238 if (address & size) {
2239 int retval = target_read_memory(target, address, size, 1, buffer);
2240 if (retval != ERROR_OK)
2248 /* Read the data with as large access size as possible. */
2249 for (; size > 0; size /= 2) {
2250 uint32_t aligned = count - count % size;
2252 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2253 if (retval != ERROR_OK)
2264 int target_checksum_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t* crc)
2269 uint32_t checksum = 0;
2270 if (!target_was_examined(target)) {
2271 LOG_ERROR("Target not examined yet");
2275 retval = target->type->checksum_memory(target, address, size, &checksum);
2276 if (retval != ERROR_OK) {
2277 buffer = malloc(size);
2278 if (buffer == NULL) {
2279 LOG_ERROR("error allocating buffer for section (%" PRId32 " bytes)", size);
2280 return ERROR_COMMAND_SYNTAX_ERROR;
2282 retval = target_read_buffer(target, address, size, buffer);
2283 if (retval != ERROR_OK) {
2288 /* convert to target endianness */
2289 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2290 uint32_t target_data;
2291 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2292 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2295 retval = image_calculate_checksum(buffer, size, &checksum);
2304 int target_blank_check_memory(struct target *target,
2305 struct target_memory_check_block *blocks, int num_blocks,
2306 uint8_t erased_value)
2308 if (!target_was_examined(target)) {
2309 LOG_ERROR("Target not examined yet");
2313 if (target->type->blank_check_memory == NULL)
2314 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2316 return target->type->blank_check_memory(target, blocks, num_blocks, erased_value);
2319 int target_read_u64(struct target *target, target_addr_t address, uint64_t *value)
2321 uint8_t value_buf[8];
2322 if (!target_was_examined(target)) {
2323 LOG_ERROR("Target not examined yet");
2327 int retval = target_read_memory(target, address, 8, 1, value_buf);
2329 if (retval == ERROR_OK) {
2330 *value = target_buffer_get_u64(target, value_buf);
2331 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2336 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2343 int target_read_u32(struct target *target, target_addr_t address, uint32_t *value)
2345 uint8_t value_buf[4];
2346 if (!target_was_examined(target)) {
2347 LOG_ERROR("Target not examined yet");
2351 int retval = target_read_memory(target, address, 4, 1, value_buf);
2353 if (retval == ERROR_OK) {
2354 *value = target_buffer_get_u32(target, value_buf);
2355 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2360 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2367 int target_read_u16(struct target *target, target_addr_t address, uint16_t *value)
2369 uint8_t value_buf[2];
2370 if (!target_was_examined(target)) {
2371 LOG_ERROR("Target not examined yet");
2375 int retval = target_read_memory(target, address, 2, 1, value_buf);
2377 if (retval == ERROR_OK) {
2378 *value = target_buffer_get_u16(target, value_buf);
2379 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%4.4" PRIx16,
2384 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2391 int target_read_u8(struct target *target, target_addr_t address, uint8_t *value)
2393 if (!target_was_examined(target)) {
2394 LOG_ERROR("Target not examined yet");
2398 int retval = target_read_memory(target, address, 1, 1, value);
2400 if (retval == ERROR_OK) {
2401 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2406 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2413 int target_write_u64(struct target *target, target_addr_t address, uint64_t value)
2416 uint8_t value_buf[8];
2417 if (!target_was_examined(target)) {
2418 LOG_ERROR("Target not examined yet");
2422 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2426 target_buffer_set_u64(target, value_buf, value);
2427 retval = target_write_memory(target, address, 8, 1, value_buf);
2428 if (retval != ERROR_OK)
2429 LOG_DEBUG("failed: %i", retval);
2434 int target_write_u32(struct target *target, target_addr_t address, uint32_t value)
2437 uint8_t value_buf[4];
2438 if (!target_was_examined(target)) {
2439 LOG_ERROR("Target not examined yet");
2443 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2447 target_buffer_set_u32(target, value_buf, value);
2448 retval = target_write_memory(target, address, 4, 1, value_buf);
2449 if (retval != ERROR_OK)
2450 LOG_DEBUG("failed: %i", retval);
2455 int target_write_u16(struct target *target, target_addr_t address, uint16_t value)
2458 uint8_t value_buf[2];
2459 if (!target_was_examined(target)) {
2460 LOG_ERROR("Target not examined yet");
2464 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2468 target_buffer_set_u16(target, value_buf, value);
2469 retval = target_write_memory(target, address, 2, 1, value_buf);
2470 if (retval != ERROR_OK)
2471 LOG_DEBUG("failed: %i", retval);
2476 int target_write_u8(struct target *target, target_addr_t address, uint8_t value)
2479 if (!target_was_examined(target)) {
2480 LOG_ERROR("Target not examined yet");
2484 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2487 retval = target_write_memory(target, address, 1, 1, &value);
2488 if (retval != ERROR_OK)
2489 LOG_DEBUG("failed: %i", retval);
2494 int target_write_phys_u64(struct target *target, target_addr_t address, uint64_t value)
2497 uint8_t value_buf[8];
2498 if (!target_was_examined(target)) {
2499 LOG_ERROR("Target not examined yet");
2503 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2507 target_buffer_set_u64(target, value_buf, value);
2508 retval = target_write_phys_memory(target, address, 8, 1, value_buf);
2509 if (retval != ERROR_OK)
2510 LOG_DEBUG("failed: %i", retval);
2515 int target_write_phys_u32(struct target *target, target_addr_t address, uint32_t value)
2518 uint8_t value_buf[4];
2519 if (!target_was_examined(target)) {
2520 LOG_ERROR("Target not examined yet");
2524 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2528 target_buffer_set_u32(target, value_buf, value);
2529 retval = target_write_phys_memory(target, address, 4, 1, value_buf);
2530 if (retval != ERROR_OK)
2531 LOG_DEBUG("failed: %i", retval);
2536 int target_write_phys_u16(struct target *target, target_addr_t address, uint16_t value)
2539 uint8_t value_buf[2];
2540 if (!target_was_examined(target)) {
2541 LOG_ERROR("Target not examined yet");
2545 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2549 target_buffer_set_u16(target, value_buf, value);
2550 retval = target_write_phys_memory(target, address, 2, 1, value_buf);
2551 if (retval != ERROR_OK)
2552 LOG_DEBUG("failed: %i", retval);
2557 int target_write_phys_u8(struct target *target, target_addr_t address, uint8_t value)
2560 if (!target_was_examined(target)) {
2561 LOG_ERROR("Target not examined yet");
2565 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2568 retval = target_write_phys_memory(target, address, 1, 1, &value);
2569 if (retval != ERROR_OK)
2570 LOG_DEBUG("failed: %i", retval);
2575 static int find_target(struct command_invocation *cmd, const char *name)
2577 struct target *target = get_target(name);
2578 if (target == NULL) {
2579 command_print(cmd, "Target: %s is unknown, try one of:\n", name);
2582 if (!target->tap->enabled) {
2583 command_print(cmd, "Target: TAP %s is disabled, "
2584 "can't be the current target\n",
2585 target->tap->dotted_name);
2589 cmd->ctx->current_target = target;
2590 if (cmd->ctx->current_target_override)
2591 cmd->ctx->current_target_override = target;
2597 COMMAND_HANDLER(handle_targets_command)
2599 int retval = ERROR_OK;
2600 if (CMD_ARGC == 1) {
2601 retval = find_target(CMD, CMD_ARGV[0]);
2602 if (retval == ERROR_OK) {
2608 struct target *target = all_targets;
2609 command_print(CMD, " TargetName Type Endian TapName State ");
2610 command_print(CMD, "-- ------------------ ---------- ------ ------------------ ------------");
2615 if (target->tap->enabled)
2616 state = target_state_name(target);
2618 state = "tap-disabled";
2620 if (CMD_CTX->current_target == target)
2623 /* keep columns lined up to match the headers above */
2625 "%2d%c %-18s %-10s %-6s %-18s %s",
2626 target->target_number,
2628 target_name(target),
2629 target_type_name(target),
2630 Jim_Nvp_value2name_simple(nvp_target_endian,
2631 target->endianness)->name,
2632 target->tap->dotted_name,
2634 target = target->next;
2640 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2642 static int powerDropout;
2643 static int srstAsserted;
2645 static int runPowerRestore;
2646 static int runPowerDropout;
2647 static int runSrstAsserted;
2648 static int runSrstDeasserted;
2650 static int sense_handler(void)
2652 static int prevSrstAsserted;
2653 static int prevPowerdropout;
2655 int retval = jtag_power_dropout(&powerDropout);
2656 if (retval != ERROR_OK)
2660 powerRestored = prevPowerdropout && !powerDropout;
2662 runPowerRestore = 1;
2664 int64_t current = timeval_ms();
2665 static int64_t lastPower;
2666 bool waitMore = lastPower + 2000 > current;
2667 if (powerDropout && !waitMore) {
2668 runPowerDropout = 1;
2669 lastPower = current;
2672 retval = jtag_srst_asserted(&srstAsserted);
2673 if (retval != ERROR_OK)
2677 srstDeasserted = prevSrstAsserted && !srstAsserted;
2679 static int64_t lastSrst;
2680 waitMore = lastSrst + 2000 > current;
2681 if (srstDeasserted && !waitMore) {
2682 runSrstDeasserted = 1;
2686 if (!prevSrstAsserted && srstAsserted)
2687 runSrstAsserted = 1;
2689 prevSrstAsserted = srstAsserted;
2690 prevPowerdropout = powerDropout;
2692 if (srstDeasserted || powerRestored) {
2693 /* Other than logging the event we can't do anything here.
2694 * Issuing a reset is a particularly bad idea as we might
2695 * be inside a reset already.
2702 /* process target state changes */
2703 static int handle_target(void *priv)
2705 Jim_Interp *interp = (Jim_Interp *)priv;
2706 int retval = ERROR_OK;
2708 if (!is_jtag_poll_safe()) {
2709 /* polling is disabled currently */
2713 /* we do not want to recurse here... */
2714 static int recursive;
2718 /* danger! running these procedures can trigger srst assertions and power dropouts.
2719 * We need to avoid an infinite loop/recursion here and we do that by
2720 * clearing the flags after running these events.
2722 int did_something = 0;
2723 if (runSrstAsserted) {
2724 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2725 Jim_Eval(interp, "srst_asserted");
2728 if (runSrstDeasserted) {
2729 Jim_Eval(interp, "srst_deasserted");
2732 if (runPowerDropout) {
2733 LOG_INFO("Power dropout detected, running power_dropout proc.");
2734 Jim_Eval(interp, "power_dropout");
2737 if (runPowerRestore) {
2738 Jim_Eval(interp, "power_restore");
2742 if (did_something) {
2743 /* clear detect flags */
2747 /* clear action flags */
2749 runSrstAsserted = 0;
2750 runSrstDeasserted = 0;
2751 runPowerRestore = 0;
2752 runPowerDropout = 0;
2757 /* Poll targets for state changes unless that's globally disabled.
2758 * Skip targets that are currently disabled.
2760 for (struct target *target = all_targets;
2761 is_jtag_poll_safe() && target;
2762 target = target->next) {
2764 if (!target_was_examined(target))
2767 if (!target->tap->enabled)
2770 if (target->backoff.times > target->backoff.count) {
2771 /* do not poll this time as we failed previously */
2772 target->backoff.count++;
2775 target->backoff.count = 0;
2777 /* only poll target if we've got power and srst isn't asserted */
2778 if (!powerDropout && !srstAsserted) {
2779 /* polling may fail silently until the target has been examined */
2780 retval = target_poll(target);
2781 if (retval != ERROR_OK) {
2782 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2783 if (target->backoff.times * polling_interval < 5000) {
2784 target->backoff.times *= 2;
2785 target->backoff.times++;
2788 /* Tell GDB to halt the debugger. This allows the user to
2789 * run monitor commands to handle the situation.
2791 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2793 if (target->backoff.times > 0) {
2794 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
2795 target_reset_examined(target);
2796 retval = target_examine_one(target);
2797 /* Target examination could have failed due to unstable connection,
2798 * but we set the examined flag anyway to repoll it later */
2799 if (retval != ERROR_OK) {
2800 target->examined = true;
2801 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
2802 target->backoff.times * polling_interval);
2807 /* Since we succeeded, we reset backoff count */
2808 target->backoff.times = 0;
2815 COMMAND_HANDLER(handle_reg_command)
2817 struct target *target;
2818 struct reg *reg = NULL;
2824 target = get_current_target(CMD_CTX);
2826 /* list all available registers for the current target */
2827 if (CMD_ARGC == 0) {
2828 struct reg_cache *cache = target->reg_cache;
2834 command_print(CMD, "===== %s", cache->name);
2836 for (i = 0, reg = cache->reg_list;
2837 i < cache->num_regs;
2838 i++, reg++, count++) {
2839 if (reg->exist == false)
2841 /* only print cached values if they are valid */
2843 value = buf_to_str(reg->value,
2846 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2854 command_print(CMD, "(%i) %s (/%" PRIu32 ")",
2859 cache = cache->next;
2865 /* access a single register by its ordinal number */
2866 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2868 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2870 struct reg_cache *cache = target->reg_cache;
2874 for (i = 0; i < cache->num_regs; i++) {
2875 if (count++ == num) {
2876 reg = &cache->reg_list[i];
2882 cache = cache->next;
2886 command_print(CMD, "%i is out of bounds, the current target "
2887 "has only %i registers (0 - %i)", num, count, count - 1);
2891 /* access a single register by its name */
2892 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2898 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2903 /* display a register */
2904 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2905 && (CMD_ARGV[1][0] <= '9')))) {
2906 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2909 if (reg->valid == 0)
2910 reg->type->get(reg);
2911 value = buf_to_str(reg->value, reg->size, 16);
2912 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2917 /* set register value */
2918 if (CMD_ARGC == 2) {
2919 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2922 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2924 reg->type->set(reg, buf);
2926 value = buf_to_str(reg->value, reg->size, 16);
2927 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2935 return ERROR_COMMAND_SYNTAX_ERROR;
2938 command_print(CMD, "register %s not found in current target", CMD_ARGV[0]);
2942 COMMAND_HANDLER(handle_poll_command)
2944 int retval = ERROR_OK;
2945 struct target *target = get_current_target(CMD_CTX);
2947 if (CMD_ARGC == 0) {
2948 command_print(CMD, "background polling: %s",
2949 jtag_poll_get_enabled() ? "on" : "off");
2950 command_print(CMD, "TAP: %s (%s)",
2951 target->tap->dotted_name,
2952 target->tap->enabled ? "enabled" : "disabled");
2953 if (!target->tap->enabled)
2955 retval = target_poll(target);
2956 if (retval != ERROR_OK)
2958 retval = target_arch_state(target);
2959 if (retval != ERROR_OK)
2961 } else if (CMD_ARGC == 1) {
2963 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2964 jtag_poll_set_enabled(enable);
2966 return ERROR_COMMAND_SYNTAX_ERROR;
2971 COMMAND_HANDLER(handle_wait_halt_command)
2974 return ERROR_COMMAND_SYNTAX_ERROR;
2976 unsigned ms = DEFAULT_HALT_TIMEOUT;
2977 if (1 == CMD_ARGC) {
2978 int retval = parse_uint(CMD_ARGV[0], &ms);
2979 if (ERROR_OK != retval)
2980 return ERROR_COMMAND_SYNTAX_ERROR;
2983 struct target *target = get_current_target(CMD_CTX);
2984 return target_wait_state(target, TARGET_HALTED, ms);
2987 /* wait for target state to change. The trick here is to have a low
2988 * latency for short waits and not to suck up all the CPU time
2991 * After 500ms, keep_alive() is invoked
2993 int target_wait_state(struct target *target, enum target_state state, int ms)
2996 int64_t then = 0, cur;
3000 retval = target_poll(target);
3001 if (retval != ERROR_OK)
3003 if (target->state == state)
3008 then = timeval_ms();
3009 LOG_DEBUG("waiting for target %s...",
3010 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
3016 if ((cur-then) > ms) {
3017 LOG_ERROR("timed out while waiting for target %s",
3018 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
3026 COMMAND_HANDLER(handle_halt_command)
3030 struct target *target = get_current_target(CMD_CTX);
3032 target->verbose_halt_msg = true;
3034 int retval = target_halt(target);
3035 if (ERROR_OK != retval)
3038 if (CMD_ARGC == 1) {
3039 unsigned wait_local;
3040 retval = parse_uint(CMD_ARGV[0], &wait_local);
3041 if (ERROR_OK != retval)
3042 return ERROR_COMMAND_SYNTAX_ERROR;
3047 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
3050 COMMAND_HANDLER(handle_soft_reset_halt_command)
3052 struct target *target = get_current_target(CMD_CTX);
3054 LOG_USER("requesting target halt and executing a soft reset");
3056 target_soft_reset_halt(target);
3061 COMMAND_HANDLER(handle_reset_command)
3064 return ERROR_COMMAND_SYNTAX_ERROR;
3066 enum target_reset_mode reset_mode = RESET_RUN;
3067 if (CMD_ARGC == 1) {
3069 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
3070 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
3071 return ERROR_COMMAND_SYNTAX_ERROR;
3072 reset_mode = n->value;
3075 /* reset *all* targets */
3076 return target_process_reset(CMD, reset_mode);
3080 COMMAND_HANDLER(handle_resume_command)
3084 return ERROR_COMMAND_SYNTAX_ERROR;
3086 struct target *target = get_current_target(CMD_CTX);
3088 /* with no CMD_ARGV, resume from current pc, addr = 0,
3089 * with one arguments, addr = CMD_ARGV[0],
3090 * handle breakpoints, not debugging */
3091 target_addr_t addr = 0;
3092 if (CMD_ARGC == 1) {
3093 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3097 return target_resume(target, current, addr, 1, 0);
3100 COMMAND_HANDLER(handle_step_command)
3103 return ERROR_COMMAND_SYNTAX_ERROR;
3107 /* with no CMD_ARGV, step from current pc, addr = 0,
3108 * with one argument addr = CMD_ARGV[0],
3109 * handle breakpoints, debugging */
3110 target_addr_t addr = 0;
3112 if (CMD_ARGC == 1) {
3113 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3117 struct target *target = get_current_target(CMD_CTX);
3119 return target->type->step(target, current_pc, addr, 1);
3122 void target_handle_md_output(struct command_invocation *cmd,
3123 struct target *target, target_addr_t address, unsigned size,
3124 unsigned count, const uint8_t *buffer)
3126 const unsigned line_bytecnt = 32;
3127 unsigned line_modulo = line_bytecnt / size;
3129 char output[line_bytecnt * 4 + 1];
3130 unsigned output_len = 0;
3132 const char *value_fmt;
3135 value_fmt = "%16.16"PRIx64" ";
3138 value_fmt = "%8.8"PRIx64" ";
3141 value_fmt = "%4.4"PRIx64" ";
3144 value_fmt = "%2.2"PRIx64" ";
3147 /* "can't happen", caller checked */
3148 LOG_ERROR("invalid memory read size: %u", size);
3152 for (unsigned i = 0; i < count; i++) {
3153 if (i % line_modulo == 0) {
3154 output_len += snprintf(output + output_len,
3155 sizeof(output) - output_len,
3156 TARGET_ADDR_FMT ": ",
3157 (address + (i * size)));
3161 const uint8_t *value_ptr = buffer + i * size;
3164 value = target_buffer_get_u64(target, value_ptr);
3167 value = target_buffer_get_u32(target, value_ptr);
3170 value = target_buffer_get_u16(target, value_ptr);
3175 output_len += snprintf(output + output_len,
3176 sizeof(output) - output_len,
3179 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
3180 command_print(cmd, "%s", output);
3186 COMMAND_HANDLER(handle_md_command)
3189 return ERROR_COMMAND_SYNTAX_ERROR;
3192 switch (CMD_NAME[2]) {
3206 return ERROR_COMMAND_SYNTAX_ERROR;
3209 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3210 int (*fn)(struct target *target,
3211 target_addr_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
3215 fn = target_read_phys_memory;
3217 fn = target_read_memory;
3218 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
3219 return ERROR_COMMAND_SYNTAX_ERROR;
3221 target_addr_t address;
3222 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3226 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3228 uint8_t *buffer = calloc(count, size);
3229 if (buffer == NULL) {
3230 LOG_ERROR("Failed to allocate md read buffer");
3234 struct target *target = get_current_target(CMD_CTX);
3235 int retval = fn(target, address, size, count, buffer);
3236 if (ERROR_OK == retval)
3237 target_handle_md_output(CMD, target, address, size, count, buffer);
3244 typedef int (*target_write_fn)(struct target *target,
3245 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3247 static int target_fill_mem(struct target *target,
3248 target_addr_t address,
3256 /* We have to write in reasonably large chunks to be able
3257 * to fill large memory areas with any sane speed */
3258 const unsigned chunk_size = 16384;
3259 uint8_t *target_buf = malloc(chunk_size * data_size);
3260 if (target_buf == NULL) {
3261 LOG_ERROR("Out of memory");
3265 for (unsigned i = 0; i < chunk_size; i++) {
3266 switch (data_size) {
3268 target_buffer_set_u64(target, target_buf + i * data_size, b);
3271 target_buffer_set_u32(target, target_buf + i * data_size, b);
3274 target_buffer_set_u16(target, target_buf + i * data_size, b);
3277 target_buffer_set_u8(target, target_buf + i * data_size, b);
3284 int retval = ERROR_OK;
3286 for (unsigned x = 0; x < c; x += chunk_size) {
3289 if (current > chunk_size)
3290 current = chunk_size;
3291 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3292 if (retval != ERROR_OK)
3294 /* avoid GDB timeouts */
3303 COMMAND_HANDLER(handle_mw_command)
3306 return ERROR_COMMAND_SYNTAX_ERROR;
3307 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3312 fn = target_write_phys_memory;
3314 fn = target_write_memory;
3315 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3316 return ERROR_COMMAND_SYNTAX_ERROR;
3318 target_addr_t address;
3319 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3321 target_addr_t value;
3322 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], value);
3326 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3328 struct target *target = get_current_target(CMD_CTX);
3330 switch (CMD_NAME[2]) {
3344 return ERROR_COMMAND_SYNTAX_ERROR;
3347 return target_fill_mem(target, address, fn, wordsize, value, count);
3350 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
3351 target_addr_t *min_address, target_addr_t *max_address)
3353 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3354 return ERROR_COMMAND_SYNTAX_ERROR;
3356 /* a base address isn't always necessary,
3357 * default to 0x0 (i.e. don't relocate) */
3358 if (CMD_ARGC >= 2) {
3360 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3361 image->base_address = addr;
3362 image->base_address_set = 1;
3364 image->base_address_set = 0;
3366 image->start_address_set = 0;
3369 COMMAND_PARSE_ADDRESS(CMD_ARGV[3], *min_address);
3370 if (CMD_ARGC == 5) {
3371 COMMAND_PARSE_ADDRESS(CMD_ARGV[4], *max_address);
3372 /* use size (given) to find max (required) */
3373 *max_address += *min_address;
3376 if (*min_address > *max_address)
3377 return ERROR_COMMAND_SYNTAX_ERROR;
3382 COMMAND_HANDLER(handle_load_image_command)
3386 uint32_t image_size;
3387 target_addr_t min_address = 0;
3388 target_addr_t max_address = -1;
3392 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
3393 &image, &min_address, &max_address);
3394 if (ERROR_OK != retval)
3397 struct target *target = get_current_target(CMD_CTX);
3399 struct duration bench;
3400 duration_start(&bench);
3402 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3407 for (i = 0; i < image.num_sections; i++) {
3408 buffer = malloc(image.sections[i].size);
3409 if (buffer == NULL) {
3411 "error allocating buffer for section (%d bytes)",
3412 (int)(image.sections[i].size));
3413 retval = ERROR_FAIL;
3417 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3418 if (retval != ERROR_OK) {
3423 uint32_t offset = 0;
3424 uint32_t length = buf_cnt;
3426 /* DANGER!!! beware of unsigned comparision here!!! */
3428 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3429 (image.sections[i].base_address < max_address)) {
3431 if (image.sections[i].base_address < min_address) {
3432 /* clip addresses below */
3433 offset += min_address-image.sections[i].base_address;
3437 if (image.sections[i].base_address + buf_cnt > max_address)
3438 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3440 retval = target_write_buffer(target,
3441 image.sections[i].base_address + offset, length, buffer + offset);
3442 if (retval != ERROR_OK) {
3446 image_size += length;
3447 command_print(CMD, "%u bytes written at address " TARGET_ADDR_FMT "",
3448 (unsigned int)length,
3449 image.sections[i].base_address + offset);
3455 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3456 command_print(CMD, "downloaded %" PRIu32 " bytes "
3457 "in %fs (%0.3f KiB/s)", image_size,
3458 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3461 image_close(&image);
3467 COMMAND_HANDLER(handle_dump_image_command)
3469 struct fileio *fileio;
3471 int retval, retvaltemp;
3472 target_addr_t address, size;
3473 struct duration bench;
3474 struct target *target = get_current_target(CMD_CTX);
3477 return ERROR_COMMAND_SYNTAX_ERROR;
3479 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], address);
3480 COMMAND_PARSE_ADDRESS(CMD_ARGV[2], size);
3482 uint32_t buf_size = (size > 4096) ? 4096 : size;
3483 buffer = malloc(buf_size);
3487 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3488 if (retval != ERROR_OK) {
3493 duration_start(&bench);
3496 size_t size_written;
3497 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3498 retval = target_read_buffer(target, address, this_run_size, buffer);
3499 if (retval != ERROR_OK)
3502 retval = fileio_write(fileio, this_run_size, buffer, &size_written);
3503 if (retval != ERROR_OK)
3506 size -= this_run_size;
3507 address += this_run_size;
3512 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3514 retval = fileio_size(fileio, &filesize);
3515 if (retval != ERROR_OK)
3518 "dumped %zu bytes in %fs (%0.3f KiB/s)", filesize,
3519 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3522 retvaltemp = fileio_close(fileio);
3523 if (retvaltemp != ERROR_OK)
3532 IMAGE_CHECKSUM_ONLY = 2
3535 static COMMAND_HELPER(handle_verify_image_command_internal, enum verify_mode verify)
3539 uint32_t image_size;
3542 uint32_t checksum = 0;
3543 uint32_t mem_checksum = 0;
3547 struct target *target = get_current_target(CMD_CTX);
3550 return ERROR_COMMAND_SYNTAX_ERROR;
3553 LOG_ERROR("no target selected");
3557 struct duration bench;
3558 duration_start(&bench);
3560 if (CMD_ARGC >= 2) {
3562 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3563 image.base_address = addr;
3564 image.base_address_set = 1;
3566 image.base_address_set = 0;
3567 image.base_address = 0x0;
3570 image.start_address_set = 0;
3572 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3573 if (retval != ERROR_OK)
3579 for (i = 0; i < image.num_sections; i++) {
3580 buffer = malloc(image.sections[i].size);
3581 if (buffer == NULL) {
3583 "error allocating buffer for section (%d bytes)",
3584 (int)(image.sections[i].size));
3587 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3588 if (retval != ERROR_OK) {
3593 if (verify >= IMAGE_VERIFY) {
3594 /* calculate checksum of image */
3595 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3596 if (retval != ERROR_OK) {
3601 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3602 if (retval != ERROR_OK) {
3606 if ((checksum != mem_checksum) && (verify == IMAGE_CHECKSUM_ONLY)) {
3607 LOG_ERROR("checksum mismatch");
3609 retval = ERROR_FAIL;
3612 if (checksum != mem_checksum) {
3613 /* failed crc checksum, fall back to a binary compare */
3617 LOG_ERROR("checksum mismatch - attempting binary compare");
3619 data = malloc(buf_cnt);
3621 /* Can we use 32bit word accesses? */
3623 int count = buf_cnt;
3624 if ((count % 4) == 0) {
3628 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3629 if (retval == ERROR_OK) {
3631 for (t = 0; t < buf_cnt; t++) {
3632 if (data[t] != buffer[t]) {
3634 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3636 (unsigned)(t + image.sections[i].base_address),
3639 if (diffs++ >= 127) {
3640 command_print(CMD, "More than 128 errors, the rest are not printed.");
3652 command_print(CMD, "address " TARGET_ADDR_FMT " length 0x%08zx",
3653 image.sections[i].base_address,
3658 image_size += buf_cnt;
3661 command_print(CMD, "No more differences found.");
3664 retval = ERROR_FAIL;
3665 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3666 command_print(CMD, "verified %" PRIu32 " bytes "
3667 "in %fs (%0.3f KiB/s)", image_size,
3668 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3671 image_close(&image);
3676 COMMAND_HANDLER(handle_verify_image_checksum_command)
3678 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_CHECKSUM_ONLY);
3681 COMMAND_HANDLER(handle_verify_image_command)
3683 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_VERIFY);
3686 COMMAND_HANDLER(handle_test_image_command)
3688 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_TEST);
3691 static int handle_bp_command_list(struct command_invocation *cmd)
3693 struct target *target = get_current_target(cmd->ctx);
3694 struct breakpoint *breakpoint = target->breakpoints;
3695 while (breakpoint) {
3696 if (breakpoint->type == BKPT_SOFT) {
3697 char *buf = buf_to_str(breakpoint->orig_instr,
3698 breakpoint->length, 16);
3699 command_print(cmd, "IVA breakpoint: " TARGET_ADDR_FMT ", 0x%x, %i, 0x%s",
3700 breakpoint->address,
3702 breakpoint->set, buf);
3705 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3706 command_print(cmd, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3708 breakpoint->length, breakpoint->set);
3709 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3710 command_print(cmd, "Hybrid breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3711 breakpoint->address,
3712 breakpoint->length, breakpoint->set);
3713 command_print(cmd, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3716 command_print(cmd, "Breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3717 breakpoint->address,
3718 breakpoint->length, breakpoint->set);
3721 breakpoint = breakpoint->next;
3726 static int handle_bp_command_set(struct command_invocation *cmd,
3727 target_addr_t addr, uint32_t asid, uint32_t length, int hw)
3729 struct target *target = get_current_target(cmd->ctx);
3733 retval = breakpoint_add(target, addr, length, hw);
3734 /* error is always logged in breakpoint_add(), do not print it again */
3735 if (ERROR_OK == retval)
3736 command_print(cmd, "breakpoint set at " TARGET_ADDR_FMT "", addr);
3738 } else if (addr == 0) {
3739 if (target->type->add_context_breakpoint == NULL) {
3740 LOG_ERROR("Context breakpoint not available");
3741 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
3743 retval = context_breakpoint_add(target, asid, length, hw);
3744 /* error is always logged in context_breakpoint_add(), do not print it again */
3745 if (ERROR_OK == retval)
3746 command_print(cmd, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3749 if (target->type->add_hybrid_breakpoint == NULL) {
3750 LOG_ERROR("Hybrid breakpoint not available");
3751 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
3753 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3754 /* error is always logged in hybrid_breakpoint_add(), do not print it again */
3755 if (ERROR_OK == retval)
3756 command_print(cmd, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3761 COMMAND_HANDLER(handle_bp_command)
3770 return handle_bp_command_list(CMD);
3774 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3775 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3776 return handle_bp_command_set(CMD, addr, asid, length, hw);
3779 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3781 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3782 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3784 return handle_bp_command_set(CMD, addr, asid, length, hw);
3785 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3787 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3788 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3790 return handle_bp_command_set(CMD, addr, asid, length, hw);
3795 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3796 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3797 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3798 return handle_bp_command_set(CMD, addr, asid, length, hw);
3801 return ERROR_COMMAND_SYNTAX_ERROR;
3805 COMMAND_HANDLER(handle_rbp_command)
3808 return ERROR_COMMAND_SYNTAX_ERROR;
3811 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3813 struct target *target = get_current_target(CMD_CTX);
3814 breakpoint_remove(target, addr);
3819 COMMAND_HANDLER(handle_wp_command)
3821 struct target *target = get_current_target(CMD_CTX);
3823 if (CMD_ARGC == 0) {
3824 struct watchpoint *watchpoint = target->watchpoints;
3826 while (watchpoint) {
3827 command_print(CMD, "address: " TARGET_ADDR_FMT
3828 ", len: 0x%8.8" PRIx32
3829 ", r/w/a: %i, value: 0x%8.8" PRIx32
3830 ", mask: 0x%8.8" PRIx32,
3831 watchpoint->address,
3833 (int)watchpoint->rw,
3836 watchpoint = watchpoint->next;
3841 enum watchpoint_rw type = WPT_ACCESS;
3843 uint32_t length = 0;
3844 uint32_t data_value = 0x0;
3845 uint32_t data_mask = 0xffffffff;
3849 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3852 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3855 switch (CMD_ARGV[2][0]) {
3866 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3867 return ERROR_COMMAND_SYNTAX_ERROR;
3871 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3872 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3876 return ERROR_COMMAND_SYNTAX_ERROR;
3879 int retval = watchpoint_add(target, addr, length, type,
3880 data_value, data_mask);
3881 if (ERROR_OK != retval)
3882 LOG_ERROR("Failure setting watchpoints");
3887 COMMAND_HANDLER(handle_rwp_command)
3890 return ERROR_COMMAND_SYNTAX_ERROR;
3893 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3895 struct target *target = get_current_target(CMD_CTX);
3896 watchpoint_remove(target, addr);
3902 * Translate a virtual address to a physical address.
3904 * The low-level target implementation must have logged a detailed error
3905 * which is forwarded to telnet/GDB session.
3907 COMMAND_HANDLER(handle_virt2phys_command)
3910 return ERROR_COMMAND_SYNTAX_ERROR;
3913 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], va);
3916 struct target *target = get_current_target(CMD_CTX);
3917 int retval = target->type->virt2phys(target, va, &pa);
3918 if (retval == ERROR_OK)
3919 command_print(CMD, "Physical address " TARGET_ADDR_FMT "", pa);
3924 static void writeData(FILE *f, const void *data, size_t len)
3926 size_t written = fwrite(data, 1, len, f);
3928 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3931 static void writeLong(FILE *f, int l, struct target *target)
3935 target_buffer_set_u32(target, val, l);
3936 writeData(f, val, 4);
3939 static void writeString(FILE *f, char *s)
3941 writeData(f, s, strlen(s));
3944 typedef unsigned char UNIT[2]; /* unit of profiling */
3946 /* Dump a gmon.out histogram file. */
3947 static void write_gmon(uint32_t *samples, uint32_t sampleNum, const char *filename, bool with_range,
3948 uint32_t start_address, uint32_t end_address, struct target *target, uint32_t duration_ms)
3951 FILE *f = fopen(filename, "w");
3954 writeString(f, "gmon");
3955 writeLong(f, 0x00000001, target); /* Version */
3956 writeLong(f, 0, target); /* padding */
3957 writeLong(f, 0, target); /* padding */
3958 writeLong(f, 0, target); /* padding */
3960 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3961 writeData(f, &zero, 1);
3963 /* figure out bucket size */
3967 min = start_address;
3972 for (i = 0; i < sampleNum; i++) {
3973 if (min > samples[i])
3975 if (max < samples[i])
3979 /* max should be (largest sample + 1)
3980 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
3984 int addressSpace = max - min;
3985 assert(addressSpace >= 2);
3987 /* FIXME: What is the reasonable number of buckets?
3988 * The profiling result will be more accurate if there are enough buckets. */
3989 static const uint32_t maxBuckets = 128 * 1024; /* maximum buckets. */
3990 uint32_t numBuckets = addressSpace / sizeof(UNIT);
3991 if (numBuckets > maxBuckets)
3992 numBuckets = maxBuckets;
3993 int *buckets = malloc(sizeof(int) * numBuckets);
3994 if (buckets == NULL) {
3998 memset(buckets, 0, sizeof(int) * numBuckets);
3999 for (i = 0; i < sampleNum; i++) {
4000 uint32_t address = samples[i];
4002 if ((address < min) || (max <= address))
4005 long long a = address - min;
4006 long long b = numBuckets;
4007 long long c = addressSpace;
4008 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
4012 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
4013 writeLong(f, min, target); /* low_pc */
4014 writeLong(f, max, target); /* high_pc */
4015 writeLong(f, numBuckets, target); /* # of buckets */
4016 float sample_rate = sampleNum / (duration_ms / 1000.0);
4017 writeLong(f, sample_rate, target);
4018 writeString(f, "seconds");
4019 for (i = 0; i < (15-strlen("seconds")); i++)
4020 writeData(f, &zero, 1);
4021 writeString(f, "s");
4023 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
4025 char *data = malloc(2 * numBuckets);
4027 for (i = 0; i < numBuckets; i++) {
4032 data[i * 2] = val&0xff;
4033 data[i * 2 + 1] = (val >> 8) & 0xff;
4036 writeData(f, data, numBuckets * 2);
4044 /* profiling samples the CPU PC as quickly as OpenOCD is able,
4045 * which will be used as a random sampling of PC */
4046 COMMAND_HANDLER(handle_profile_command)
4048 struct target *target = get_current_target(CMD_CTX);
4050 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
4051 return ERROR_COMMAND_SYNTAX_ERROR;
4053 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
4055 uint32_t num_of_samples;
4056 int retval = ERROR_OK;
4058 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
4060 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
4061 if (samples == NULL) {
4062 LOG_ERROR("No memory to store samples.");
4066 uint64_t timestart_ms = timeval_ms();
4068 * Some cores let us sample the PC without the
4069 * annoying halt/resume step; for example, ARMv7 PCSR.
4070 * Provide a way to use that more efficient mechanism.
4072 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
4073 &num_of_samples, offset);
4074 if (retval != ERROR_OK) {
4078 uint32_t duration_ms = timeval_ms() - timestart_ms;
4080 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
4082 retval = target_poll(target);
4083 if (retval != ERROR_OK) {
4087 if (target->state == TARGET_RUNNING) {
4088 retval = target_halt(target);
4089 if (retval != ERROR_OK) {
4095 retval = target_poll(target);
4096 if (retval != ERROR_OK) {
4101 uint32_t start_address = 0;
4102 uint32_t end_address = 0;
4103 bool with_range = false;
4104 if (CMD_ARGC == 4) {
4106 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
4107 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
4110 write_gmon(samples, num_of_samples, CMD_ARGV[1],
4111 with_range, start_address, end_address, target, duration_ms);
4112 command_print(CMD, "Wrote %s", CMD_ARGV[1]);
4118 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
4121 Jim_Obj *nameObjPtr, *valObjPtr;
4124 namebuf = alloc_printf("%s(%d)", varname, idx);
4128 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
4129 valObjPtr = Jim_NewIntObj(interp, val);
4130 if (!nameObjPtr || !valObjPtr) {
4135 Jim_IncrRefCount(nameObjPtr);
4136 Jim_IncrRefCount(valObjPtr);
4137 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
4138 Jim_DecrRefCount(interp, nameObjPtr);
4139 Jim_DecrRefCount(interp, valObjPtr);
4141 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
4145 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4147 struct command_context *context;
4148 struct target *target;
4150 context = current_command_context(interp);
4151 assert(context != NULL);
4153 target = get_current_target(context);
4154 if (target == NULL) {
4155 LOG_ERROR("mem2array: no current target");
4159 return target_mem2array(interp, target, argc - 1, argv + 1);
4162 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
4170 const char *varname;
4176 /* argv[1] = name of array to receive the data
4177 * argv[2] = desired width
4178 * argv[3] = memory address
4179 * argv[4] = count of times to read
4182 if (argc < 4 || argc > 5) {
4183 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4186 varname = Jim_GetString(argv[0], &len);
4187 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
4189 e = Jim_GetLong(interp, argv[1], &l);
4194 e = Jim_GetLong(interp, argv[2], &l);
4198 e = Jim_GetLong(interp, argv[3], &l);
4204 phys = Jim_GetString(argv[4], &n);
4205 if (!strncmp(phys, "phys", n))
4221 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4222 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
4226 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4227 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
4230 if ((addr + (len * width)) < addr) {
4231 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4232 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
4235 /* absurd transfer size? */
4237 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4238 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
4243 ((width == 2) && ((addr & 1) == 0)) ||
4244 ((width == 4) && ((addr & 3) == 0))) {
4248 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4249 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
4252 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4261 size_t buffersize = 4096;
4262 uint8_t *buffer = malloc(buffersize);
4269 /* Slurp... in buffer size chunks */
4271 count = len; /* in objects.. */
4272 if (count > (buffersize / width))
4273 count = (buffersize / width);
4276 retval = target_read_phys_memory(target, addr, width, count, buffer);
4278 retval = target_read_memory(target, addr, width, count, buffer);
4279 if (retval != ERROR_OK) {
4281 LOG_ERROR("mem2array: Read @ 0x%08" PRIx32 ", w=%" PRId32 ", cnt=%" PRId32 ", failed",
4285 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4286 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
4290 v = 0; /* shut up gcc */
4291 for (i = 0; i < count ; i++, n++) {
4294 v = target_buffer_get_u32(target, &buffer[i*width]);
4297 v = target_buffer_get_u16(target, &buffer[i*width]);
4300 v = buffer[i] & 0x0ff;
4303 new_int_array_element(interp, varname, n, v);
4306 addr += count * width;
4312 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4317 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
4320 Jim_Obj *nameObjPtr, *valObjPtr;
4324 namebuf = alloc_printf("%s(%d)", varname, idx);
4328 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
4334 Jim_IncrRefCount(nameObjPtr);
4335 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
4336 Jim_DecrRefCount(interp, nameObjPtr);
4338 if (valObjPtr == NULL)
4341 result = Jim_GetLong(interp, valObjPtr, &l);
4342 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
4347 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4349 struct command_context *context;
4350 struct target *target;
4352 context = current_command_context(interp);
4353 assert(context != NULL);
4355 target = get_current_target(context);
4356 if (target == NULL) {
4357 LOG_ERROR("array2mem: no current target");
4361 return target_array2mem(interp, target, argc-1, argv + 1);
4364 static int target_array2mem(Jim_Interp *interp, struct target *target,
4365 int argc, Jim_Obj *const *argv)
4373 const char *varname;
4379 /* argv[1] = name of array to get the data
4380 * argv[2] = desired width
4381 * argv[3] = memory address
4382 * argv[4] = count to write
4384 if (argc < 4 || argc > 5) {
4385 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4388 varname = Jim_GetString(argv[0], &len);
4389 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
4391 e = Jim_GetLong(interp, argv[1], &l);
4396 e = Jim_GetLong(interp, argv[2], &l);
4400 e = Jim_GetLong(interp, argv[3], &l);
4406 phys = Jim_GetString(argv[4], &n);
4407 if (!strncmp(phys, "phys", n))
4423 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4424 Jim_AppendStrings(interp, Jim_GetResult(interp),
4425 "Invalid width param, must be 8/16/32", NULL);
4429 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4430 Jim_AppendStrings(interp, Jim_GetResult(interp),
4431 "array2mem: zero width read?", NULL);
4434 if ((addr + (len * width)) < addr) {
4435 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4436 Jim_AppendStrings(interp, Jim_GetResult(interp),
4437 "array2mem: addr + len - wraps to zero?", NULL);
4440 /* absurd transfer size? */
4442 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4443 Jim_AppendStrings(interp, Jim_GetResult(interp),
4444 "array2mem: absurd > 64K item request", NULL);
4449 ((width == 2) && ((addr & 1) == 0)) ||
4450 ((width == 4) && ((addr & 3) == 0))) {
4454 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4455 sprintf(buf, "array2mem address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
4458 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4469 size_t buffersize = 4096;
4470 uint8_t *buffer = malloc(buffersize);
4475 /* Slurp... in buffer size chunks */
4477 count = len; /* in objects.. */
4478 if (count > (buffersize / width))
4479 count = (buffersize / width);
4481 v = 0; /* shut up gcc */
4482 for (i = 0; i < count; i++, n++) {
4483 get_int_array_element(interp, varname, n, &v);
4486 target_buffer_set_u32(target, &buffer[i * width], v);
4489 target_buffer_set_u16(target, &buffer[i * width], v);
4492 buffer[i] = v & 0x0ff;
4499 retval = target_write_phys_memory(target, addr, width, count, buffer);
4501 retval = target_write_memory(target, addr, width, count, buffer);
4502 if (retval != ERROR_OK) {
4504 LOG_ERROR("array2mem: Write @ 0x%08" PRIx32 ", w=%" PRId32 ", cnt=%" PRId32 ", failed",
4508 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4509 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4513 addr += count * width;
4518 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4523 /* FIX? should we propagate errors here rather than printing them
4526 void target_handle_event(struct target *target, enum target_event e)
4528 struct target_event_action *teap;
4530 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4531 if (teap->event == e) {
4532 LOG_DEBUG("target(%d): %s (%s) event: %d (%s) action: %s",
4533 target->target_number,
4534 target_name(target),
4535 target_type_name(target),
4537 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
4538 Jim_GetString(teap->body, NULL));
4540 /* Override current target by the target an event
4541 * is issued from (lot of scripts need it).
4542 * Return back to previous override as soon
4543 * as the handler processing is done */
4544 struct command_context *cmd_ctx = current_command_context(teap->interp);
4545 struct target *saved_target_override = cmd_ctx->current_target_override;
4546 cmd_ctx->current_target_override = target;
4548 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
4549 Jim_MakeErrorMessage(teap->interp);
4550 LOG_USER("Error executing event %s on target %s:\n%s",
4551 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
4552 target_name(target),
4553 Jim_GetString(Jim_GetResult(teap->interp), NULL));
4554 /* clean both error code and stacktrace before return */
4555 Jim_Eval(teap->interp, "error \"\" \"\"");
4558 cmd_ctx->current_target_override = saved_target_override;
4564 * Returns true only if the target has a handler for the specified event.
4566 bool target_has_event_action(struct target *target, enum target_event event)
4568 struct target_event_action *teap;
4570 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4571 if (teap->event == event)
4577 enum target_cfg_param {
4580 TCFG_WORK_AREA_VIRT,
4581 TCFG_WORK_AREA_PHYS,
4582 TCFG_WORK_AREA_SIZE,
4583 TCFG_WORK_AREA_BACKUP,
4586 TCFG_CHAIN_POSITION,
4593 static Jim_Nvp nvp_config_opts[] = {
4594 { .name = "-type", .value = TCFG_TYPE },
4595 { .name = "-event", .value = TCFG_EVENT },
4596 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4597 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4598 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4599 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4600 { .name = "-endian" , .value = TCFG_ENDIAN },
4601 { .name = "-coreid", .value = TCFG_COREID },
4602 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4603 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4604 { .name = "-rtos", .value = TCFG_RTOS },
4605 { .name = "-defer-examine", .value = TCFG_DEFER_EXAMINE },
4606 { .name = "-gdb-port", .value = TCFG_GDB_PORT },
4607 { .name = NULL, .value = -1 }
4610 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
4617 /* parse config or cget options ... */
4618 while (goi->argc > 0) {
4619 Jim_SetEmptyResult(goi->interp);
4620 /* Jim_GetOpt_Debug(goi); */
4622 if (target->type->target_jim_configure) {
4623 /* target defines a configure function */
4624 /* target gets first dibs on parameters */
4625 e = (*(target->type->target_jim_configure))(target, goi);
4634 /* otherwise we 'continue' below */
4636 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
4638 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
4644 if (goi->isconfigure) {
4645 Jim_SetResultFormatted(goi->interp,
4646 "not settable: %s", n->name);
4650 if (goi->argc != 0) {
4651 Jim_WrongNumArgs(goi->interp,
4652 goi->argc, goi->argv,
4657 Jim_SetResultString(goi->interp,
4658 target_type_name(target), -1);
4662 if (goi->argc == 0) {
4663 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4667 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4669 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4673 if (goi->isconfigure) {
4674 if (goi->argc != 1) {
4675 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4679 if (goi->argc != 0) {
4680 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4686 struct target_event_action *teap;
4688 teap = target->event_action;
4689 /* replace existing? */
4691 if (teap->event == (enum target_event)n->value)
4696 if (goi->isconfigure) {
4697 bool replace = true;
4700 teap = calloc(1, sizeof(*teap));
4703 teap->event = n->value;
4704 teap->interp = goi->interp;
4705 Jim_GetOpt_Obj(goi, &o);
4707 Jim_DecrRefCount(teap->interp, teap->body);
4708 teap->body = Jim_DuplicateObj(goi->interp, o);
4711 * Tcl/TK - "tk events" have a nice feature.
4712 * See the "BIND" command.
4713 * We should support that here.
4714 * You can specify %X and %Y in the event code.
4715 * The idea is: %T - target name.
4716 * The idea is: %N - target number
4717 * The idea is: %E - event name.
4719 Jim_IncrRefCount(teap->body);
4722 /* add to head of event list */
4723 teap->next = target->event_action;
4724 target->event_action = teap;
4726 Jim_SetEmptyResult(goi->interp);
4730 Jim_SetEmptyResult(goi->interp);
4732 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4738 case TCFG_WORK_AREA_VIRT:
4739 if (goi->isconfigure) {
4740 target_free_all_working_areas(target);
4741 e = Jim_GetOpt_Wide(goi, &w);
4744 target->working_area_virt = w;
4745 target->working_area_virt_spec = true;
4750 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4754 case TCFG_WORK_AREA_PHYS:
4755 if (goi->isconfigure) {
4756 target_free_all_working_areas(target);
4757 e = Jim_GetOpt_Wide(goi, &w);
4760 target->working_area_phys = w;
4761 target->working_area_phys_spec = true;
4766 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4770 case TCFG_WORK_AREA_SIZE:
4771 if (goi->isconfigure) {
4772 target_free_all_working_areas(target);
4773 e = Jim_GetOpt_Wide(goi, &w);
4776 target->working_area_size = w;
4781 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4785 case TCFG_WORK_AREA_BACKUP:
4786 if (goi->isconfigure) {
4787 target_free_all_working_areas(target);
4788 e = Jim_GetOpt_Wide(goi, &w);
4791 /* make this exactly 1 or 0 */
4792 target->backup_working_area = (!!w);
4797 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4798 /* loop for more e*/
4803 if (goi->isconfigure) {
4804 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4806 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4809 target->endianness = n->value;
4814 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4815 if (n->name == NULL) {
4816 target->endianness = TARGET_LITTLE_ENDIAN;
4817 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4819 Jim_SetResultString(goi->interp, n->name, -1);
4824 if (goi->isconfigure) {
4825 e = Jim_GetOpt_Wide(goi, &w);
4828 target->coreid = (int32_t)w;
4833 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->coreid));
4837 case TCFG_CHAIN_POSITION:
4838 if (goi->isconfigure) {
4840 struct jtag_tap *tap;
4842 if (target->has_dap) {
4843 Jim_SetResultString(goi->interp,
4844 "target requires -dap parameter instead of -chain-position!", -1);
4848 target_free_all_working_areas(target);
4849 e = Jim_GetOpt_Obj(goi, &o_t);
4852 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4856 target->tap_configured = true;
4861 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4862 /* loop for more e*/
4865 if (goi->isconfigure) {
4866 e = Jim_GetOpt_Wide(goi, &w);
4869 target->dbgbase = (uint32_t)w;
4870 target->dbgbase_set = true;
4875 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4881 int result = rtos_create(goi, target);
4882 if (result != JIM_OK)
4888 case TCFG_DEFER_EXAMINE:
4890 target->defer_examine = true;
4895 if (goi->isconfigure) {
4897 e = Jim_GetOpt_String(goi, &s, NULL);
4900 target->gdb_port_override = strdup(s);
4905 Jim_SetResultString(goi->interp, target->gdb_port_override ? : "undefined", -1);
4909 } /* while (goi->argc) */
4912 /* done - we return */
4916 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4920 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4921 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4923 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4924 "missing: -option ...");
4927 struct target *target = Jim_CmdPrivData(goi.interp);
4928 return target_configure(&goi, target);
4931 static int jim_target_mem2array(Jim_Interp *interp,
4932 int argc, Jim_Obj *const *argv)
4934 struct target *target = Jim_CmdPrivData(interp);
4935 return target_mem2array(interp, target, argc - 1, argv + 1);
4938 static int jim_target_array2mem(Jim_Interp *interp,
4939 int argc, Jim_Obj *const *argv)
4941 struct target *target = Jim_CmdPrivData(interp);
4942 return target_array2mem(interp, target, argc - 1, argv + 1);
4945 static int jim_target_tap_disabled(Jim_Interp *interp)
4947 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4951 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4953 bool allow_defer = false;
4956 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4958 const char *cmd_name = Jim_GetString(argv[0], NULL);
4959 Jim_SetResultFormatted(goi.interp,
4960 "usage: %s ['allow-defer']", cmd_name);
4964 strcmp(Jim_GetString(argv[1], NULL), "allow-defer") == 0) {
4966 struct Jim_Obj *obj;
4967 int e = Jim_GetOpt_Obj(&goi, &obj);
4973 struct target *target = Jim_CmdPrivData(interp);
4974 if (!target->tap->enabled)
4975 return jim_target_tap_disabled(interp);
4977 if (allow_defer && target->defer_examine) {
4978 LOG_INFO("Deferring arp_examine of %s", target_name(target));
4979 LOG_INFO("Use arp_examine command to examine it manually!");
4983 int e = target->type->examine(target);
4989 static int jim_target_was_examined(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4991 struct target *target = Jim_CmdPrivData(interp);
4993 Jim_SetResultBool(interp, target_was_examined(target));
4997 static int jim_target_examine_deferred(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4999 struct target *target = Jim_CmdPrivData(interp);
5001 Jim_SetResultBool(interp, target->defer_examine);
5005 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5008 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5011 struct target *target = Jim_CmdPrivData(interp);
5013 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
5019 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5022 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5025 struct target *target = Jim_CmdPrivData(interp);
5026 if (!target->tap->enabled)
5027 return jim_target_tap_disabled(interp);
5030 if (!(target_was_examined(target)))
5031 e = ERROR_TARGET_NOT_EXAMINED;
5033 e = target->type->poll(target);
5039 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5042 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5044 if (goi.argc != 2) {
5045 Jim_WrongNumArgs(interp, 0, argv,
5046 "([tT]|[fF]|assert|deassert) BOOL");
5051 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
5053 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
5056 /* the halt or not param */
5058 e = Jim_GetOpt_Wide(&goi, &a);
5062 struct target *target = Jim_CmdPrivData(goi.interp);
5063 if (!target->tap->enabled)
5064 return jim_target_tap_disabled(interp);
5066 if (!target->type->assert_reset || !target->type->deassert_reset) {
5067 Jim_SetResultFormatted(interp,
5068 "No target-specific reset for %s",
5069 target_name(target));
5073 if (target->defer_examine)
5074 target_reset_examined(target);
5076 /* determine if we should halt or not. */
5077 target->reset_halt = !!a;
5078 /* When this happens - all workareas are invalid. */
5079 target_free_all_working_areas_restore(target, 0);
5082 if (n->value == NVP_ASSERT)
5083 e = target->type->assert_reset(target);
5085 e = target->type->deassert_reset(target);
5086 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5089 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5092 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5095 struct target *target = Jim_CmdPrivData(interp);
5096 if (!target->tap->enabled)
5097 return jim_target_tap_disabled(interp);
5098 int e = target->type->halt(target);
5099 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5102 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5105 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5107 /* params: <name> statename timeoutmsecs */
5108 if (goi.argc != 2) {
5109 const char *cmd_name = Jim_GetString(argv[0], NULL);
5110 Jim_SetResultFormatted(goi.interp,
5111 "%s <state_name> <timeout_in_msec>", cmd_name);
5116 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
5118 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
5122 e = Jim_GetOpt_Wide(&goi, &a);
5125 struct target *target = Jim_CmdPrivData(interp);
5126 if (!target->tap->enabled)
5127 return jim_target_tap_disabled(interp);
5129 e = target_wait_state(target, n->value, a);
5130 if (e != ERROR_OK) {
5131 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
5132 Jim_SetResultFormatted(goi.interp,
5133 "target: %s wait %s fails (%#s) %s",
5134 target_name(target), n->name,
5135 eObj, target_strerror_safe(e));
5136 Jim_FreeNewObj(interp, eObj);
5141 /* List for human, Events defined for this target.
5142 * scripts/programs should use 'name cget -event NAME'
5144 COMMAND_HANDLER(handle_target_event_list)
5146 struct target *target = get_current_target(CMD_CTX);
5147 struct target_event_action *teap = target->event_action;
5149 command_print(CMD, "Event actions for target (%d) %s\n",
5150 target->target_number,
5151 target_name(target));
5152 command_print(CMD, "%-25s | Body", "Event");
5153 command_print(CMD, "------------------------- | "
5154 "----------------------------------------");
5156 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
5157 command_print(CMD, "%-25s | %s",
5158 opt->name, Jim_GetString(teap->body, NULL));
5161 command_print(CMD, "***END***");
5164 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5167 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5170 struct target *target = Jim_CmdPrivData(interp);
5171 Jim_SetResultString(interp, target_state_name(target), -1);
5174 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5177 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5178 if (goi.argc != 1) {
5179 const char *cmd_name = Jim_GetString(argv[0], NULL);
5180 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5184 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
5186 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
5189 struct target *target = Jim_CmdPrivData(interp);
5190 target_handle_event(target, n->value);
5194 static const struct command_registration target_instance_command_handlers[] = {
5196 .name = "configure",
5197 .mode = COMMAND_CONFIG,
5198 .jim_handler = jim_target_configure,
5199 .help = "configure a new target for use",
5200 .usage = "[target_attribute ...]",
5204 .mode = COMMAND_ANY,
5205 .jim_handler = jim_target_configure,
5206 .help = "returns the specified target attribute",
5207 .usage = "target_attribute",
5211 .handler = handle_mw_command,
5212 .mode = COMMAND_EXEC,
5213 .help = "Write 64-bit word(s) to target memory",
5214 .usage = "address data [count]",
5218 .handler = handle_mw_command,
5219 .mode = COMMAND_EXEC,
5220 .help = "Write 32-bit word(s) to target memory",
5221 .usage = "address data [count]",
5225 .handler = handle_mw_command,
5226 .mode = COMMAND_EXEC,
5227 .help = "Write 16-bit half-word(s) to target memory",
5228 .usage = "address data [count]",
5232 .handler = handle_mw_command,
5233 .mode = COMMAND_EXEC,
5234 .help = "Write byte(s) to target memory",
5235 .usage = "address data [count]",
5239 .handler = handle_md_command,
5240 .mode = COMMAND_EXEC,
5241 .help = "Display target memory as 64-bit words",
5242 .usage = "address [count]",
5246 .handler = handle_md_command,
5247 .mode = COMMAND_EXEC,
5248 .help = "Display target memory as 32-bit words",
5249 .usage = "address [count]",
5253 .handler = handle_md_command,
5254 .mode = COMMAND_EXEC,
5255 .help = "Display target memory as 16-bit half-words",
5256 .usage = "address [count]",
5260 .handler = handle_md_command,
5261 .mode = COMMAND_EXEC,
5262 .help = "Display target memory as 8-bit bytes",
5263 .usage = "address [count]",
5266 .name = "array2mem",
5267 .mode = COMMAND_EXEC,
5268 .jim_handler = jim_target_array2mem,
5269 .help = "Writes Tcl array of 8/16/32 bit numbers "
5271 .usage = "arrayname bitwidth address count",
5274 .name = "mem2array",
5275 .mode = COMMAND_EXEC,
5276 .jim_handler = jim_target_mem2array,
5277 .help = "Loads Tcl array of 8/16/32 bit numbers "
5278 "from target memory",
5279 .usage = "arrayname bitwidth address count",
5282 .name = "eventlist",
5283 .handler = handle_target_event_list,
5284 .mode = COMMAND_EXEC,
5285 .help = "displays a table of events defined for this target",
5290 .mode = COMMAND_EXEC,
5291 .jim_handler = jim_target_current_state,
5292 .help = "displays the current state of this target",
5295 .name = "arp_examine",
5296 .mode = COMMAND_EXEC,
5297 .jim_handler = jim_target_examine,
5298 .help = "used internally for reset processing",
5299 .usage = "['allow-defer']",
5302 .name = "was_examined",
5303 .mode = COMMAND_EXEC,
5304 .jim_handler = jim_target_was_examined,
5305 .help = "used internally for reset processing",
5308 .name = "examine_deferred",
5309 .mode = COMMAND_EXEC,
5310 .jim_handler = jim_target_examine_deferred,
5311 .help = "used internally for reset processing",
5314 .name = "arp_halt_gdb",
5315 .mode = COMMAND_EXEC,
5316 .jim_handler = jim_target_halt_gdb,
5317 .help = "used internally for reset processing to halt GDB",
5321 .mode = COMMAND_EXEC,
5322 .jim_handler = jim_target_poll,
5323 .help = "used internally for reset processing",
5326 .name = "arp_reset",
5327 .mode = COMMAND_EXEC,
5328 .jim_handler = jim_target_reset,
5329 .help = "used internally for reset processing",
5333 .mode = COMMAND_EXEC,
5334 .jim_handler = jim_target_halt,
5335 .help = "used internally for reset processing",
5338 .name = "arp_waitstate",
5339 .mode = COMMAND_EXEC,
5340 .jim_handler = jim_target_wait_state,
5341 .help = "used internally for reset processing",
5344 .name = "invoke-event",
5345 .mode = COMMAND_EXEC,
5346 .jim_handler = jim_target_invoke_event,
5347 .help = "invoke handler for specified event",
5348 .usage = "event_name",
5350 COMMAND_REGISTRATION_DONE
5353 static int target_create(Jim_GetOptInfo *goi)
5360 struct target *target;
5361 struct command_context *cmd_ctx;
5363 cmd_ctx = current_command_context(goi->interp);
5364 assert(cmd_ctx != NULL);
5366 if (goi->argc < 3) {
5367 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5372 Jim_GetOpt_Obj(goi, &new_cmd);
5373 /* does this command exist? */
5374 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
5376 cp = Jim_GetString(new_cmd, NULL);
5377 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5382 e = Jim_GetOpt_String(goi, &cp, NULL);
5385 struct transport *tr = get_current_transport();
5386 if (tr->override_target) {
5387 e = tr->override_target(&cp);
5388 if (e != ERROR_OK) {
5389 LOG_ERROR("The selected transport doesn't support this target");
5392 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5394 /* now does target type exist */
5395 for (x = 0 ; target_types[x] ; x++) {
5396 if (0 == strcmp(cp, target_types[x]->name)) {
5401 /* check for deprecated name */
5402 if (target_types[x]->deprecated_name) {
5403 if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
5405 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
5410 if (target_types[x] == NULL) {
5411 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5412 for (x = 0 ; target_types[x] ; x++) {
5413 if (target_types[x + 1]) {
5414 Jim_AppendStrings(goi->interp,
5415 Jim_GetResult(goi->interp),
5416 target_types[x]->name,
5419 Jim_AppendStrings(goi->interp,
5420 Jim_GetResult(goi->interp),
5422 target_types[x]->name, NULL);
5429 target = calloc(1, sizeof(struct target));
5430 /* set target number */
5431 target->target_number = new_target_number();
5432 cmd_ctx->current_target = target;
5434 /* allocate memory for each unique target type */
5435 target->type = calloc(1, sizeof(struct target_type));
5437 memcpy(target->type, target_types[x], sizeof(struct target_type));
5439 /* will be set by "-endian" */
5440 target->endianness = TARGET_ENDIAN_UNKNOWN;
5442 /* default to first core, override with -coreid */
5445 target->working_area = 0x0;
5446 target->working_area_size = 0x0;
5447 target->working_areas = NULL;
5448 target->backup_working_area = 0;
5450 target->state = TARGET_UNKNOWN;
5451 target->debug_reason = DBG_REASON_UNDEFINED;
5452 target->reg_cache = NULL;
5453 target->breakpoints = NULL;
5454 target->watchpoints = NULL;
5455 target->next = NULL;
5456 target->arch_info = NULL;
5458 target->verbose_halt_msg = true;
5460 target->halt_issued = false;
5462 /* initialize trace information */
5463 target->trace_info = calloc(1, sizeof(struct trace));
5465 target->dbgmsg = NULL;
5466 target->dbg_msg_enabled = 0;
5468 target->endianness = TARGET_ENDIAN_UNKNOWN;
5470 target->rtos = NULL;
5471 target->rtos_auto_detect = false;
5473 target->gdb_port_override = NULL;
5475 /* Do the rest as "configure" options */
5476 goi->isconfigure = 1;
5477 e = target_configure(goi, target);
5480 if (target->has_dap) {
5481 if (!target->dap_configured) {
5482 Jim_SetResultString(goi->interp, "-dap ?name? required when creating target", -1);
5486 if (!target->tap_configured) {
5487 Jim_SetResultString(goi->interp, "-chain-position ?name? required when creating target", -1);
5491 /* tap must be set after target was configured */
5492 if (target->tap == NULL)
5497 free(target->gdb_port_override);
5503 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5504 /* default endian to little if not specified */
5505 target->endianness = TARGET_LITTLE_ENDIAN;
5508 cp = Jim_GetString(new_cmd, NULL);
5509 target->cmd_name = strdup(cp);
5511 if (target->type->target_create) {
5512 e = (*(target->type->target_create))(target, goi->interp);
5513 if (e != ERROR_OK) {
5514 LOG_DEBUG("target_create failed");
5515 free(target->gdb_port_override);
5517 free(target->cmd_name);
5523 /* create the target specific commands */
5524 if (target->type->commands) {
5525 e = register_commands(cmd_ctx, NULL, target->type->commands);
5527 LOG_ERROR("unable to register '%s' commands", cp);
5530 /* append to end of list */
5532 struct target **tpp;
5533 tpp = &(all_targets);
5535 tpp = &((*tpp)->next);
5539 /* now - create the new target name command */
5540 const struct command_registration target_subcommands[] = {
5542 .chain = target_instance_command_handlers,
5545 .chain = target->type->commands,
5547 COMMAND_REGISTRATION_DONE
5549 const struct command_registration target_commands[] = {
5552 .mode = COMMAND_ANY,
5553 .help = "target command group",
5555 .chain = target_subcommands,
5557 COMMAND_REGISTRATION_DONE
5559 e = register_commands(cmd_ctx, NULL, target_commands);
5563 struct command *c = command_find_in_context(cmd_ctx, cp);
5565 command_set_handler_data(c, target);
5567 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5570 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5573 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5576 struct command_context *cmd_ctx = current_command_context(interp);
5577 assert(cmd_ctx != NULL);
5579 Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5583 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5586 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5589 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5590 for (unsigned x = 0; NULL != target_types[x]; x++) {
5591 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5592 Jim_NewStringObj(interp, target_types[x]->name, -1));
5597 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5600 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5603 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5604 struct target *target = all_targets;
5606 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5607 Jim_NewStringObj(interp, target_name(target), -1));
5608 target = target->next;
5613 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5616 const char *targetname;
5618 struct target *target = (struct target *) NULL;
5619 struct target_list *head, *curr, *new;
5620 curr = (struct target_list *) NULL;
5621 head = (struct target_list *) NULL;
5624 LOG_DEBUG("%d", argc);
5625 /* argv[1] = target to associate in smp
5626 * argv[2] = target to assoicate in smp
5630 for (i = 1; i < argc; i++) {
5632 targetname = Jim_GetString(argv[i], &len);
5633 target = get_target(targetname);
5634 LOG_DEBUG("%s ", targetname);
5636 new = malloc(sizeof(struct target_list));
5637 new->target = target;
5638 new->next = (struct target_list *)NULL;
5639 if (head == (struct target_list *)NULL) {
5648 /* now parse the list of cpu and put the target in smp mode*/
5651 while (curr != (struct target_list *)NULL) {
5652 target = curr->target;
5654 target->head = head;
5658 if (target && target->rtos)
5659 retval = rtos_smp_init(head->target);
5665 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5668 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5670 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5671 "<name> <target_type> [<target_options> ...]");
5674 return target_create(&goi);
5677 static const struct command_registration target_subcommand_handlers[] = {
5680 .mode = COMMAND_CONFIG,
5681 .handler = handle_target_init_command,
5682 .help = "initialize targets",
5687 .mode = COMMAND_CONFIG,
5688 .jim_handler = jim_target_create,
5689 .usage = "name type '-chain-position' name [options ...]",
5690 .help = "Creates and selects a new target",
5694 .mode = COMMAND_ANY,
5695 .jim_handler = jim_target_current,
5696 .help = "Returns the currently selected target",
5700 .mode = COMMAND_ANY,
5701 .jim_handler = jim_target_types,
5702 .help = "Returns the available target types as "
5703 "a list of strings",
5707 .mode = COMMAND_ANY,
5708 .jim_handler = jim_target_names,
5709 .help = "Returns the names of all targets as a list of strings",
5713 .mode = COMMAND_ANY,
5714 .jim_handler = jim_target_smp,
5715 .usage = "targetname1 targetname2 ...",
5716 .help = "gather several target in a smp list"
5719 COMMAND_REGISTRATION_DONE
5723 target_addr_t address;
5729 static int fastload_num;
5730 static struct FastLoad *fastload;
5732 static void free_fastload(void)
5734 if (fastload != NULL) {
5736 for (i = 0; i < fastload_num; i++) {
5737 if (fastload[i].data)
5738 free(fastload[i].data);
5745 COMMAND_HANDLER(handle_fast_load_image_command)
5749 uint32_t image_size;
5750 target_addr_t min_address = 0;
5751 target_addr_t max_address = -1;
5756 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5757 &image, &min_address, &max_address);
5758 if (ERROR_OK != retval)
5761 struct duration bench;
5762 duration_start(&bench);
5764 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5765 if (retval != ERROR_OK)
5770 fastload_num = image.num_sections;
5771 fastload = malloc(sizeof(struct FastLoad)*image.num_sections);
5772 if (fastload == NULL) {
5773 command_print(CMD, "out of memory");
5774 image_close(&image);
5777 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5778 for (i = 0; i < image.num_sections; i++) {
5779 buffer = malloc(image.sections[i].size);
5780 if (buffer == NULL) {
5781 command_print(CMD, "error allocating buffer for section (%d bytes)",
5782 (int)(image.sections[i].size));
5783 retval = ERROR_FAIL;
5787 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5788 if (retval != ERROR_OK) {
5793 uint32_t offset = 0;
5794 uint32_t length = buf_cnt;
5796 /* DANGER!!! beware of unsigned comparision here!!! */
5798 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5799 (image.sections[i].base_address < max_address)) {
5800 if (image.sections[i].base_address < min_address) {
5801 /* clip addresses below */
5802 offset += min_address-image.sections[i].base_address;
5806 if (image.sections[i].base_address + buf_cnt > max_address)
5807 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5809 fastload[i].address = image.sections[i].base_address + offset;
5810 fastload[i].data = malloc(length);
5811 if (fastload[i].data == NULL) {
5813 command_print(CMD, "error allocating buffer for section (%" PRIu32 " bytes)",
5815 retval = ERROR_FAIL;
5818 memcpy(fastload[i].data, buffer + offset, length);
5819 fastload[i].length = length;
5821 image_size += length;
5822 command_print(CMD, "%u bytes written at address 0x%8.8x",
5823 (unsigned int)length,
5824 ((unsigned int)(image.sections[i].base_address + offset)));
5830 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5831 command_print(CMD, "Loaded %" PRIu32 " bytes "
5832 "in %fs (%0.3f KiB/s)", image_size,
5833 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5836 "WARNING: image has not been loaded to target!"
5837 "You can issue a 'fast_load' to finish loading.");
5840 image_close(&image);
5842 if (retval != ERROR_OK)
5848 COMMAND_HANDLER(handle_fast_load_command)
5851 return ERROR_COMMAND_SYNTAX_ERROR;
5852 if (fastload == NULL) {
5853 LOG_ERROR("No image in memory");
5857 int64_t ms = timeval_ms();
5859 int retval = ERROR_OK;
5860 for (i = 0; i < fastload_num; i++) {
5861 struct target *target = get_current_target(CMD_CTX);
5862 command_print(CMD, "Write to 0x%08x, length 0x%08x",
5863 (unsigned int)(fastload[i].address),
5864 (unsigned int)(fastload[i].length));
5865 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5866 if (retval != ERROR_OK)
5868 size += fastload[i].length;
5870 if (retval == ERROR_OK) {
5871 int64_t after = timeval_ms();
5872 command_print(CMD, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5877 static const struct command_registration target_command_handlers[] = {
5880 .handler = handle_targets_command,
5881 .mode = COMMAND_ANY,
5882 .help = "change current default target (one parameter) "
5883 "or prints table of all targets (no parameters)",
5884 .usage = "[target]",
5888 .mode = COMMAND_CONFIG,
5889 .help = "configure target",
5890 .chain = target_subcommand_handlers,
5893 COMMAND_REGISTRATION_DONE
5896 int target_register_commands(struct command_context *cmd_ctx)
5898 return register_commands(cmd_ctx, NULL, target_command_handlers);
5901 static bool target_reset_nag = true;
5903 bool get_target_reset_nag(void)
5905 return target_reset_nag;
5908 COMMAND_HANDLER(handle_target_reset_nag)
5910 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5911 &target_reset_nag, "Nag after each reset about options to improve "
5915 COMMAND_HANDLER(handle_ps_command)
5917 struct target *target = get_current_target(CMD_CTX);
5919 if (target->state != TARGET_HALTED) {
5920 LOG_INFO("target not halted !!");
5924 if ((target->rtos) && (target->rtos->type)
5925 && (target->rtos->type->ps_command)) {
5926 display = target->rtos->type->ps_command(target);
5927 command_print(CMD, "%s", display);
5932 return ERROR_TARGET_FAILURE;
5936 static void binprint(struct command_invocation *cmd, const char *text, const uint8_t *buf, int size)
5939 command_print_sameline(cmd, "%s", text);
5940 for (int i = 0; i < size; i++)
5941 command_print_sameline(cmd, " %02x", buf[i]);
5942 command_print(cmd, " ");
5945 COMMAND_HANDLER(handle_test_mem_access_command)
5947 struct target *target = get_current_target(CMD_CTX);
5949 int retval = ERROR_OK;
5951 if (target->state != TARGET_HALTED) {
5952 LOG_INFO("target not halted !!");
5957 return ERROR_COMMAND_SYNTAX_ERROR;
5959 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
5962 size_t num_bytes = test_size + 4;
5964 struct working_area *wa = NULL;
5965 retval = target_alloc_working_area(target, num_bytes, &wa);
5966 if (retval != ERROR_OK) {
5967 LOG_ERROR("Not enough working area");
5971 uint8_t *test_pattern = malloc(num_bytes);
5973 for (size_t i = 0; i < num_bytes; i++)
5974 test_pattern[i] = rand();
5976 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
5977 if (retval != ERROR_OK) {
5978 LOG_ERROR("Test pattern write failed");
5982 for (int host_offset = 0; host_offset <= 1; host_offset++) {
5983 for (int size = 1; size <= 4; size *= 2) {
5984 for (int offset = 0; offset < 4; offset++) {
5985 uint32_t count = test_size / size;
5986 size_t host_bufsiz = (count + 2) * size + host_offset;
5987 uint8_t *read_ref = malloc(host_bufsiz);
5988 uint8_t *read_buf = malloc(host_bufsiz);
5990 for (size_t i = 0; i < host_bufsiz; i++) {
5991 read_ref[i] = rand();
5992 read_buf[i] = read_ref[i];
5994 command_print_sameline(CMD,
5995 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
5996 size, offset, host_offset ? "un" : "");
5998 struct duration bench;
5999 duration_start(&bench);
6001 retval = target_read_memory(target, wa->address + offset, size, count,
6002 read_buf + size + host_offset);
6004 duration_measure(&bench);
6006 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6007 command_print(CMD, "Unsupported alignment");
6009 } else if (retval != ERROR_OK) {
6010 command_print(CMD, "Memory read failed");
6014 /* replay on host */
6015 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
6018 int result = memcmp(read_ref, read_buf, host_bufsiz);
6020 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6021 duration_elapsed(&bench),
6022 duration_kbps(&bench, count * size));
6024 command_print(CMD, "Compare failed");
6025 binprint(CMD, "ref:", read_ref, host_bufsiz);
6026 binprint(CMD, "buf:", read_buf, host_bufsiz);
6039 target_free_working_area(target, wa);
6042 num_bytes = test_size + 4 + 4 + 4;
6044 retval = target_alloc_working_area(target, num_bytes, &wa);
6045 if (retval != ERROR_OK) {
6046 LOG_ERROR("Not enough working area");
6050 test_pattern = malloc(num_bytes);
6052 for (size_t i = 0; i < num_bytes; i++)
6053 test_pattern[i] = rand();
6055 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6056 for (int size = 1; size <= 4; size *= 2) {
6057 for (int offset = 0; offset < 4; offset++) {
6058 uint32_t count = test_size / size;
6059 size_t host_bufsiz = count * size + host_offset;
6060 uint8_t *read_ref = malloc(num_bytes);
6061 uint8_t *read_buf = malloc(num_bytes);
6062 uint8_t *write_buf = malloc(host_bufsiz);
6064 for (size_t i = 0; i < host_bufsiz; i++)
6065 write_buf[i] = rand();
6066 command_print_sameline(CMD,
6067 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
6068 size, offset, host_offset ? "un" : "");
6070 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6071 if (retval != ERROR_OK) {
6072 command_print(CMD, "Test pattern write failed");
6076 /* replay on host */
6077 memcpy(read_ref, test_pattern, num_bytes);
6078 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
6080 struct duration bench;
6081 duration_start(&bench);
6083 retval = target_write_memory(target, wa->address + size + offset, size, count,
6084 write_buf + host_offset);
6086 duration_measure(&bench);
6088 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6089 command_print(CMD, "Unsupported alignment");
6091 } else if (retval != ERROR_OK) {
6092 command_print(CMD, "Memory write failed");
6097 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
6098 if (retval != ERROR_OK) {
6099 command_print(CMD, "Test pattern write failed");
6104 int result = memcmp(read_ref, read_buf, num_bytes);
6106 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6107 duration_elapsed(&bench),
6108 duration_kbps(&bench, count * size));
6110 command_print(CMD, "Compare failed");
6111 binprint(CMD, "ref:", read_ref, num_bytes);
6112 binprint(CMD, "buf:", read_buf, num_bytes);
6124 target_free_working_area(target, wa);
6128 static const struct command_registration target_exec_command_handlers[] = {
6130 .name = "fast_load_image",
6131 .handler = handle_fast_load_image_command,
6132 .mode = COMMAND_ANY,
6133 .help = "Load image into server memory for later use by "
6134 "fast_load; primarily for profiling",
6135 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6136 "[min_address [max_length]]",
6139 .name = "fast_load",
6140 .handler = handle_fast_load_command,
6141 .mode = COMMAND_EXEC,
6142 .help = "loads active fast load image to current target "
6143 "- mainly for profiling purposes",
6148 .handler = handle_profile_command,
6149 .mode = COMMAND_EXEC,
6150 .usage = "seconds filename [start end]",
6151 .help = "profiling samples the CPU PC",
6153 /** @todo don't register virt2phys() unless target supports it */
6155 .name = "virt2phys",
6156 .handler = handle_virt2phys_command,
6157 .mode = COMMAND_ANY,
6158 .help = "translate a virtual address into a physical address",
6159 .usage = "virtual_address",
6163 .handler = handle_reg_command,
6164 .mode = COMMAND_EXEC,
6165 .help = "display (reread from target with \"force\") or set a register; "
6166 "with no arguments, displays all registers and their values",
6167 .usage = "[(register_number|register_name) [(value|'force')]]",
6171 .handler = handle_poll_command,
6172 .mode = COMMAND_EXEC,
6173 .help = "poll target state; or reconfigure background polling",
6174 .usage = "['on'|'off']",
6177 .name = "wait_halt",
6178 .handler = handle_wait_halt_command,
6179 .mode = COMMAND_EXEC,
6180 .help = "wait up to the specified number of milliseconds "
6181 "(default 5000) for a previously requested halt",
6182 .usage = "[milliseconds]",
6186 .handler = handle_halt_command,
6187 .mode = COMMAND_EXEC,
6188 .help = "request target to halt, then wait up to the specified"
6189 "number of milliseconds (default 5000) for it to complete",
6190 .usage = "[milliseconds]",
6194 .handler = handle_resume_command,
6195 .mode = COMMAND_EXEC,
6196 .help = "resume target execution from current PC or address",
6197 .usage = "[address]",
6201 .handler = handle_reset_command,
6202 .mode = COMMAND_EXEC,
6203 .usage = "[run|halt|init]",
6204 .help = "Reset all targets into the specified mode."
6205 "Default reset mode is run, if not given.",
6208 .name = "soft_reset_halt",
6209 .handler = handle_soft_reset_halt_command,
6210 .mode = COMMAND_EXEC,
6212 .help = "halt the target and do a soft reset",
6216 .handler = handle_step_command,
6217 .mode = COMMAND_EXEC,
6218 .help = "step one instruction from current PC or address",
6219 .usage = "[address]",
6223 .handler = handle_md_command,
6224 .mode = COMMAND_EXEC,
6225 .help = "display memory double-words",
6226 .usage = "['phys'] address [count]",
6230 .handler = handle_md_command,
6231 .mode = COMMAND_EXEC,
6232 .help = "display memory words",
6233 .usage = "['phys'] address [count]",
6237 .handler = handle_md_command,
6238 .mode = COMMAND_EXEC,
6239 .help = "display memory half-words",
6240 .usage = "['phys'] address [count]",
6244 .handler = handle_md_command,
6245 .mode = COMMAND_EXEC,
6246 .help = "display memory bytes",
6247 .usage = "['phys'] address [count]",
6251 .handler = handle_mw_command,
6252 .mode = COMMAND_EXEC,
6253 .help = "write memory double-word",
6254 .usage = "['phys'] address value [count]",
6258 .handler = handle_mw_command,
6259 .mode = COMMAND_EXEC,
6260 .help = "write memory word",
6261 .usage = "['phys'] address value [count]",
6265 .handler = handle_mw_command,
6266 .mode = COMMAND_EXEC,
6267 .help = "write memory half-word",
6268 .usage = "['phys'] address value [count]",
6272 .handler = handle_mw_command,
6273 .mode = COMMAND_EXEC,
6274 .help = "write memory byte",
6275 .usage = "['phys'] address value [count]",
6279 .handler = handle_bp_command,
6280 .mode = COMMAND_EXEC,
6281 .help = "list or set hardware or software breakpoint",
6282 .usage = "[<address> [<asid>] <length> ['hw'|'hw_ctx']]",
6286 .handler = handle_rbp_command,
6287 .mode = COMMAND_EXEC,
6288 .help = "remove breakpoint",
6293 .handler = handle_wp_command,
6294 .mode = COMMAND_EXEC,
6295 .help = "list (no params) or create watchpoints",
6296 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
6300 .handler = handle_rwp_command,
6301 .mode = COMMAND_EXEC,
6302 .help = "remove watchpoint",
6306 .name = "load_image",
6307 .handler = handle_load_image_command,
6308 .mode = COMMAND_EXEC,
6309 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6310 "[min_address] [max_length]",
6313 .name = "dump_image",
6314 .handler = handle_dump_image_command,
6315 .mode = COMMAND_EXEC,
6316 .usage = "filename address size",
6319 .name = "verify_image_checksum",
6320 .handler = handle_verify_image_checksum_command,
6321 .mode = COMMAND_EXEC,
6322 .usage = "filename [offset [type]]",
6325 .name = "verify_image",
6326 .handler = handle_verify_image_command,
6327 .mode = COMMAND_EXEC,
6328 .usage = "filename [offset [type]]",
6331 .name = "test_image",
6332 .handler = handle_test_image_command,
6333 .mode = COMMAND_EXEC,
6334 .usage = "filename [offset [type]]",
6337 .name = "mem2array",
6338 .mode = COMMAND_EXEC,
6339 .jim_handler = jim_mem2array,
6340 .help = "read 8/16/32 bit memory and return as a TCL array "
6341 "for script processing",
6342 .usage = "arrayname bitwidth address count",
6345 .name = "array2mem",
6346 .mode = COMMAND_EXEC,
6347 .jim_handler = jim_array2mem,
6348 .help = "convert a TCL array to memory locations "
6349 "and write the 8/16/32 bit values",
6350 .usage = "arrayname bitwidth address count",
6353 .name = "reset_nag",
6354 .handler = handle_target_reset_nag,
6355 .mode = COMMAND_ANY,
6356 .help = "Nag after each reset about options that could have been "
6357 "enabled to improve performance. ",
6358 .usage = "['enable'|'disable']",
6362 .handler = handle_ps_command,
6363 .mode = COMMAND_EXEC,
6364 .help = "list all tasks ",
6368 .name = "test_mem_access",
6369 .handler = handle_test_mem_access_command,
6370 .mode = COMMAND_EXEC,
6371 .help = "Test the target's memory access functions",
6375 COMMAND_REGISTRATION_DONE
6377 static int target_register_user_commands(struct command_context *cmd_ctx)
6379 int retval = ERROR_OK;
6380 retval = target_request_register_commands(cmd_ctx);
6381 if (retval != ERROR_OK)
6384 retval = trace_register_commands(cmd_ctx);
6385 if (retval != ERROR_OK)
6389 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);