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, write to the *
38 * Free Software Foundation, Inc., *
39 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
40 ***************************************************************************/
46 #include <helper/time_support.h>
47 #include <jtag/jtag.h>
48 #include <flash/nor/core.h>
51 #include "target_type.h"
52 #include "target_request.h"
53 #include "breakpoints.h"
57 #include "rtos/rtos.h"
58 #include "transport/transport.h"
60 /* default halt wait timeout (ms) */
61 #define DEFAULT_HALT_TIMEOUT 5000
63 static int target_read_buffer_default(struct target *target, uint32_t address,
64 uint32_t count, uint8_t *buffer);
65 static int target_write_buffer_default(struct target *target, uint32_t address,
66 uint32_t count, const uint8_t *buffer);
67 static int target_array2mem(Jim_Interp *interp, struct target *target,
68 int argc, Jim_Obj * const *argv);
69 static int target_mem2array(Jim_Interp *interp, struct target *target,
70 int argc, Jim_Obj * const *argv);
71 static int target_register_user_commands(struct command_context *cmd_ctx);
72 static int target_get_gdb_fileio_info_default(struct target *target,
73 struct gdb_fileio_info *fileio_info);
74 static int target_gdb_fileio_end_default(struct target *target, int retcode,
75 int fileio_errno, bool ctrl_c);
76 static int target_profiling_default(struct target *target, uint32_t *samples,
77 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds);
80 extern struct target_type arm7tdmi_target;
81 extern struct target_type arm720t_target;
82 extern struct target_type arm9tdmi_target;
83 extern struct target_type arm920t_target;
84 extern struct target_type arm966e_target;
85 extern struct target_type arm946e_target;
86 extern struct target_type arm926ejs_target;
87 extern struct target_type fa526_target;
88 extern struct target_type feroceon_target;
89 extern struct target_type dragonite_target;
90 extern struct target_type xscale_target;
91 extern struct target_type cortexm_target;
92 extern struct target_type cortexa_target;
93 extern struct target_type cortexr4_target;
94 extern struct target_type arm11_target;
95 extern struct target_type mips_m4k_target;
96 extern struct target_type avr_target;
97 extern struct target_type dsp563xx_target;
98 extern struct target_type dsp5680xx_target;
99 extern struct target_type testee_target;
100 extern struct target_type avr32_ap7k_target;
101 extern struct target_type hla_target;
102 extern struct target_type nds32_v2_target;
103 extern struct target_type nds32_v3_target;
104 extern struct target_type nds32_v3m_target;
105 extern struct target_type or1k_target;
106 extern struct target_type quark_x10xx_target;
108 static struct target_type *target_types[] = {
139 struct target *all_targets;
140 static struct target_event_callback *target_event_callbacks;
141 static struct target_timer_callback *target_timer_callbacks;
142 LIST_HEAD(target_reset_callback_list);
143 static const int polling_interval = 100;
145 static const Jim_Nvp nvp_assert[] = {
146 { .name = "assert", NVP_ASSERT },
147 { .name = "deassert", NVP_DEASSERT },
148 { .name = "T", NVP_ASSERT },
149 { .name = "F", NVP_DEASSERT },
150 { .name = "t", NVP_ASSERT },
151 { .name = "f", NVP_DEASSERT },
152 { .name = NULL, .value = -1 }
155 static const Jim_Nvp nvp_error_target[] = {
156 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
157 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
158 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
159 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
160 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
161 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
162 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
163 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
164 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
165 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
166 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
167 { .value = -1, .name = NULL }
170 static const char *target_strerror_safe(int err)
174 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
181 static const Jim_Nvp nvp_target_event[] = {
183 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
184 { .value = TARGET_EVENT_HALTED, .name = "halted" },
185 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
186 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
187 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
189 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
190 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
192 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
193 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
194 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
195 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
196 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
197 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
198 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
199 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
200 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
201 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
202 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
203 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
205 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
206 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
208 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
209 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
211 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
212 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
214 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
215 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
217 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
218 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
220 { .name = NULL, .value = -1 }
223 static const Jim_Nvp nvp_target_state[] = {
224 { .name = "unknown", .value = TARGET_UNKNOWN },
225 { .name = "running", .value = TARGET_RUNNING },
226 { .name = "halted", .value = TARGET_HALTED },
227 { .name = "reset", .value = TARGET_RESET },
228 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
229 { .name = NULL, .value = -1 },
232 static const Jim_Nvp nvp_target_debug_reason[] = {
233 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
234 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
235 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
236 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
237 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
238 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
239 { .name = "program-exit" , .value = DBG_REASON_EXIT },
240 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
241 { .name = NULL, .value = -1 },
244 static const Jim_Nvp nvp_target_endian[] = {
245 { .name = "big", .value = TARGET_BIG_ENDIAN },
246 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
247 { .name = "be", .value = TARGET_BIG_ENDIAN },
248 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
249 { .name = NULL, .value = -1 },
252 static const Jim_Nvp nvp_reset_modes[] = {
253 { .name = "unknown", .value = RESET_UNKNOWN },
254 { .name = "run" , .value = RESET_RUN },
255 { .name = "halt" , .value = RESET_HALT },
256 { .name = "init" , .value = RESET_INIT },
257 { .name = NULL , .value = -1 },
260 const char *debug_reason_name(struct target *t)
264 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
265 t->debug_reason)->name;
267 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
268 cp = "(*BUG*unknown*BUG*)";
273 const char *target_state_name(struct target *t)
276 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
278 LOG_ERROR("Invalid target state: %d", (int)(t->state));
279 cp = "(*BUG*unknown*BUG*)";
284 const char *target_event_name(enum target_event event)
287 cp = Jim_Nvp_value2name_simple(nvp_target_event, event)->name;
289 LOG_ERROR("Invalid target event: %d", (int)(event));
290 cp = "(*BUG*unknown*BUG*)";
295 const char *target_reset_mode_name(enum target_reset_mode reset_mode)
298 cp = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name;
300 LOG_ERROR("Invalid target reset mode: %d", (int)(reset_mode));
301 cp = "(*BUG*unknown*BUG*)";
306 /* determine the number of the new target */
307 static int new_target_number(void)
312 /* number is 0 based */
316 if (x < t->target_number)
317 x = t->target_number;
323 /* read a uint64_t from a buffer in target memory endianness */
324 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
326 if (target->endianness == TARGET_LITTLE_ENDIAN)
327 return le_to_h_u64(buffer);
329 return be_to_h_u64(buffer);
332 /* read a uint32_t from a buffer in target memory endianness */
333 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
335 if (target->endianness == TARGET_LITTLE_ENDIAN)
336 return le_to_h_u32(buffer);
338 return be_to_h_u32(buffer);
341 /* read a uint24_t from a buffer in target memory endianness */
342 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
344 if (target->endianness == TARGET_LITTLE_ENDIAN)
345 return le_to_h_u24(buffer);
347 return be_to_h_u24(buffer);
350 /* read a uint16_t from a buffer in target memory endianness */
351 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
353 if (target->endianness == TARGET_LITTLE_ENDIAN)
354 return le_to_h_u16(buffer);
356 return be_to_h_u16(buffer);
359 /* read a uint8_t from a buffer in target memory endianness */
360 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
362 return *buffer & 0x0ff;
365 /* write a uint64_t to a buffer in target memory endianness */
366 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
368 if (target->endianness == TARGET_LITTLE_ENDIAN)
369 h_u64_to_le(buffer, value);
371 h_u64_to_be(buffer, value);
374 /* write a uint32_t to a buffer in target memory endianness */
375 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
377 if (target->endianness == TARGET_LITTLE_ENDIAN)
378 h_u32_to_le(buffer, value);
380 h_u32_to_be(buffer, value);
383 /* write a uint24_t to a buffer in target memory endianness */
384 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
386 if (target->endianness == TARGET_LITTLE_ENDIAN)
387 h_u24_to_le(buffer, value);
389 h_u24_to_be(buffer, value);
392 /* write a uint16_t to a buffer in target memory endianness */
393 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
395 if (target->endianness == TARGET_LITTLE_ENDIAN)
396 h_u16_to_le(buffer, value);
398 h_u16_to_be(buffer, value);
401 /* write a uint8_t to a buffer in target memory endianness */
402 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
407 /* write a uint64_t array to a buffer in target memory endianness */
408 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
411 for (i = 0; i < count; i++)
412 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
415 /* write a uint32_t array to a buffer in target memory endianness */
416 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
419 for (i = 0; i < count; i++)
420 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
423 /* write a uint16_t array to a buffer in target memory endianness */
424 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
427 for (i = 0; i < count; i++)
428 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
431 /* write a uint64_t array to a buffer in target memory endianness */
432 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
435 for (i = 0; i < count; i++)
436 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
439 /* write a uint32_t array to a buffer in target memory endianness */
440 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
443 for (i = 0; i < count; i++)
444 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
447 /* write a uint16_t array to a buffer in target memory endianness */
448 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
451 for (i = 0; i < count; i++)
452 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
455 /* return a pointer to a configured target; id is name or number */
456 struct target *get_target(const char *id)
458 struct target *target;
460 /* try as tcltarget name */
461 for (target = all_targets; target; target = target->next) {
462 if (target_name(target) == NULL)
464 if (strcmp(id, target_name(target)) == 0)
468 /* It's OK to remove this fallback sometime after August 2010 or so */
470 /* no match, try as number */
472 if (parse_uint(id, &num) != ERROR_OK)
475 for (target = all_targets; target; target = target->next) {
476 if (target->target_number == (int)num) {
477 LOG_WARNING("use '%s' as target identifier, not '%u'",
478 target_name(target), num);
486 /* returns a pointer to the n-th configured target */
487 static struct target *get_target_by_num(int num)
489 struct target *target = all_targets;
492 if (target->target_number == num)
494 target = target->next;
500 struct target *get_current_target(struct command_context *cmd_ctx)
502 struct target *target = get_target_by_num(cmd_ctx->current_target);
504 if (target == NULL) {
505 LOG_ERROR("BUG: current_target out of bounds");
512 int target_poll(struct target *target)
516 /* We can't poll until after examine */
517 if (!target_was_examined(target)) {
518 /* Fail silently lest we pollute the log */
522 retval = target->type->poll(target);
523 if (retval != ERROR_OK)
526 if (target->halt_issued) {
527 if (target->state == TARGET_HALTED)
528 target->halt_issued = false;
530 long long t = timeval_ms() - target->halt_issued_time;
531 if (t > DEFAULT_HALT_TIMEOUT) {
532 target->halt_issued = false;
533 LOG_INFO("Halt timed out, wake up GDB.");
534 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
542 int target_halt(struct target *target)
545 /* We can't poll until after examine */
546 if (!target_was_examined(target)) {
547 LOG_ERROR("Target not examined yet");
551 retval = target->type->halt(target);
552 if (retval != ERROR_OK)
555 target->halt_issued = true;
556 target->halt_issued_time = timeval_ms();
562 * Make the target (re)start executing using its saved execution
563 * context (possibly with some modifications).
565 * @param target Which target should start executing.
566 * @param current True to use the target's saved program counter instead
567 * of the address parameter
568 * @param address Optionally used as the program counter.
569 * @param handle_breakpoints True iff breakpoints at the resumption PC
570 * should be skipped. (For example, maybe execution was stopped by
571 * such a breakpoint, in which case it would be counterprodutive to
573 * @param debug_execution False if all working areas allocated by OpenOCD
574 * should be released and/or restored to their original contents.
575 * (This would for example be true to run some downloaded "helper"
576 * algorithm code, which resides in one such working buffer and uses
577 * another for data storage.)
579 * @todo Resolve the ambiguity about what the "debug_execution" flag
580 * signifies. For example, Target implementations don't agree on how
581 * it relates to invalidation of the register cache, or to whether
582 * breakpoints and watchpoints should be enabled. (It would seem wrong
583 * to enable breakpoints when running downloaded "helper" algorithms
584 * (debug_execution true), since the breakpoints would be set to match
585 * target firmware being debugged, not the helper algorithm.... and
586 * enabling them could cause such helpers to malfunction (for example,
587 * by overwriting data with a breakpoint instruction. On the other
588 * hand the infrastructure for running such helpers might use this
589 * procedure but rely on hardware breakpoint to detect termination.)
591 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
595 /* We can't poll until after examine */
596 if (!target_was_examined(target)) {
597 LOG_ERROR("Target not examined yet");
601 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
603 /* note that resume *must* be asynchronous. The CPU can halt before
604 * we poll. The CPU can even halt at the current PC as a result of
605 * a software breakpoint being inserted by (a bug?) the application.
607 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
608 if (retval != ERROR_OK)
611 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
616 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
621 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
622 if (n->name == NULL) {
623 LOG_ERROR("invalid reset mode");
627 struct target *target;
628 for (target = all_targets; target; target = target->next)
629 target_call_reset_callbacks(target, reset_mode);
631 /* disable polling during reset to make reset event scripts
632 * more predictable, i.e. dr/irscan & pathmove in events will
633 * not have JTAG operations injected into the middle of a sequence.
635 bool save_poll = jtag_poll_get_enabled();
637 jtag_poll_set_enabled(false);
639 sprintf(buf, "ocd_process_reset %s", n->name);
640 retval = Jim_Eval(cmd_ctx->interp, buf);
642 jtag_poll_set_enabled(save_poll);
644 if (retval != JIM_OK) {
645 Jim_MakeErrorMessage(cmd_ctx->interp);
646 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
650 /* We want any events to be processed before the prompt */
651 retval = target_call_timer_callbacks_now();
653 for (target = all_targets; target; target = target->next) {
654 target->type->check_reset(target);
655 target->running_alg = false;
661 static int identity_virt2phys(struct target *target,
662 uint32_t virtual, uint32_t *physical)
668 static int no_mmu(struct target *target, int *enabled)
674 static int default_examine(struct target *target)
676 target_set_examined(target);
680 /* no check by default */
681 static int default_check_reset(struct target *target)
686 int target_examine_one(struct target *target)
688 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
690 int retval = target->type->examine(target);
691 if (retval != ERROR_OK)
694 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
699 static int jtag_enable_callback(enum jtag_event event, void *priv)
701 struct target *target = priv;
703 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
706 jtag_unregister_event_callback(jtag_enable_callback, target);
708 return target_examine_one(target);
711 /* Targets that correctly implement init + examine, i.e.
712 * no communication with target during init:
716 int target_examine(void)
718 int retval = ERROR_OK;
719 struct target *target;
721 for (target = all_targets; target; target = target->next) {
722 /* defer examination, but don't skip it */
723 if (!target->tap->enabled) {
724 jtag_register_event_callback(jtag_enable_callback,
729 retval = target_examine_one(target);
730 if (retval != ERROR_OK)
736 const char *target_type_name(struct target *target)
738 return target->type->name;
741 static int target_soft_reset_halt(struct target *target)
743 if (!target_was_examined(target)) {
744 LOG_ERROR("Target not examined yet");
747 if (!target->type->soft_reset_halt) {
748 LOG_ERROR("Target %s does not support soft_reset_halt",
749 target_name(target));
752 return target->type->soft_reset_halt(target);
756 * Downloads a target-specific native code algorithm to the target,
757 * and executes it. * Note that some targets may need to set up, enable,
758 * and tear down a breakpoint (hard or * soft) to detect algorithm
759 * termination, while others may support lower overhead schemes where
760 * soft breakpoints embedded in the algorithm automatically terminate the
763 * @param target used to run the algorithm
764 * @param arch_info target-specific description of the algorithm.
766 int target_run_algorithm(struct target *target,
767 int num_mem_params, struct mem_param *mem_params,
768 int num_reg_params, struct reg_param *reg_param,
769 uint32_t entry_point, uint32_t exit_point,
770 int timeout_ms, void *arch_info)
772 int retval = ERROR_FAIL;
774 if (!target_was_examined(target)) {
775 LOG_ERROR("Target not examined yet");
778 if (!target->type->run_algorithm) {
779 LOG_ERROR("Target type '%s' does not support %s",
780 target_type_name(target), __func__);
784 target->running_alg = true;
785 retval = target->type->run_algorithm(target,
786 num_mem_params, mem_params,
787 num_reg_params, reg_param,
788 entry_point, exit_point, timeout_ms, arch_info);
789 target->running_alg = false;
796 * Downloads a target-specific native code algorithm to the target,
797 * executes and leaves it running.
799 * @param target used to run the algorithm
800 * @param arch_info target-specific description of the algorithm.
802 int target_start_algorithm(struct target *target,
803 int num_mem_params, struct mem_param *mem_params,
804 int num_reg_params, struct reg_param *reg_params,
805 uint32_t entry_point, uint32_t exit_point,
808 int retval = ERROR_FAIL;
810 if (!target_was_examined(target)) {
811 LOG_ERROR("Target not examined yet");
814 if (!target->type->start_algorithm) {
815 LOG_ERROR("Target type '%s' does not support %s",
816 target_type_name(target), __func__);
819 if (target->running_alg) {
820 LOG_ERROR("Target is already running an algorithm");
824 target->running_alg = true;
825 retval = target->type->start_algorithm(target,
826 num_mem_params, mem_params,
827 num_reg_params, reg_params,
828 entry_point, exit_point, arch_info);
835 * Waits for an algorithm started with target_start_algorithm() to complete.
837 * @param target used to run the algorithm
838 * @param arch_info target-specific description of the algorithm.
840 int target_wait_algorithm(struct target *target,
841 int num_mem_params, struct mem_param *mem_params,
842 int num_reg_params, struct reg_param *reg_params,
843 uint32_t exit_point, int timeout_ms,
846 int retval = ERROR_FAIL;
848 if (!target->type->wait_algorithm) {
849 LOG_ERROR("Target type '%s' does not support %s",
850 target_type_name(target), __func__);
853 if (!target->running_alg) {
854 LOG_ERROR("Target is not running an algorithm");
858 retval = target->type->wait_algorithm(target,
859 num_mem_params, mem_params,
860 num_reg_params, reg_params,
861 exit_point, timeout_ms, arch_info);
862 if (retval != ERROR_TARGET_TIMEOUT)
863 target->running_alg = false;
870 * Executes a target-specific native code algorithm in the target.
871 * It differs from target_run_algorithm in that the algorithm is asynchronous.
872 * Because of this it requires an compliant algorithm:
873 * see contrib/loaders/flash/stm32f1x.S for example.
875 * @param target used to run the algorithm
878 int target_run_flash_async_algorithm(struct target *target,
879 const uint8_t *buffer, uint32_t count, int block_size,
880 int num_mem_params, struct mem_param *mem_params,
881 int num_reg_params, struct reg_param *reg_params,
882 uint32_t buffer_start, uint32_t buffer_size,
883 uint32_t entry_point, uint32_t exit_point, void *arch_info)
888 const uint8_t *buffer_orig = buffer;
890 /* Set up working area. First word is write pointer, second word is read pointer,
891 * rest is fifo data area. */
892 uint32_t wp_addr = buffer_start;
893 uint32_t rp_addr = buffer_start + 4;
894 uint32_t fifo_start_addr = buffer_start + 8;
895 uint32_t fifo_end_addr = buffer_start + buffer_size;
897 uint32_t wp = fifo_start_addr;
898 uint32_t rp = fifo_start_addr;
900 /* validate block_size is 2^n */
901 assert(!block_size || !(block_size & (block_size - 1)));
903 retval = target_write_u32(target, wp_addr, wp);
904 if (retval != ERROR_OK)
906 retval = target_write_u32(target, rp_addr, rp);
907 if (retval != ERROR_OK)
910 /* Start up algorithm on target and let it idle while writing the first chunk */
911 retval = target_start_algorithm(target, num_mem_params, mem_params,
912 num_reg_params, reg_params,
917 if (retval != ERROR_OK) {
918 LOG_ERROR("error starting target flash write algorithm");
924 retval = target_read_u32(target, rp_addr, &rp);
925 if (retval != ERROR_OK) {
926 LOG_ERROR("failed to get read pointer");
930 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
931 (size_t) (buffer - buffer_orig), count, wp, rp);
934 LOG_ERROR("flash write algorithm aborted by target");
935 retval = ERROR_FLASH_OPERATION_FAILED;
939 if ((rp & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
940 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
944 /* Count the number of bytes available in the fifo without
945 * crossing the wrap around. Make sure to not fill it completely,
946 * because that would make wp == rp and that's the empty condition. */
947 uint32_t thisrun_bytes;
949 thisrun_bytes = rp - wp - block_size;
950 else if (rp > fifo_start_addr)
951 thisrun_bytes = fifo_end_addr - wp;
953 thisrun_bytes = fifo_end_addr - wp - block_size;
955 if (thisrun_bytes == 0) {
956 /* Throttle polling a bit if transfer is (much) faster than flash
957 * programming. The exact delay shouldn't matter as long as it's
958 * less than buffer size / flash speed. This is very unlikely to
959 * run when using high latency connections such as USB. */
962 /* to stop an infinite loop on some targets check and increment a timeout
963 * this issue was observed on a stellaris using the new ICDI interface */
964 if (timeout++ >= 500) {
965 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
966 return ERROR_FLASH_OPERATION_FAILED;
971 /* reset our timeout */
974 /* Limit to the amount of data we actually want to write */
975 if (thisrun_bytes > count * block_size)
976 thisrun_bytes = count * block_size;
978 /* Write data to fifo */
979 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
980 if (retval != ERROR_OK)
983 /* Update counters and wrap write pointer */
984 buffer += thisrun_bytes;
985 count -= thisrun_bytes / block_size;
987 if (wp >= fifo_end_addr)
988 wp = fifo_start_addr;
990 /* Store updated write pointer to target */
991 retval = target_write_u32(target, wp_addr, wp);
992 if (retval != ERROR_OK)
996 if (retval != ERROR_OK) {
997 /* abort flash write algorithm on target */
998 target_write_u32(target, wp_addr, 0);
1001 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1002 num_reg_params, reg_params,
1007 if (retval2 != ERROR_OK) {
1008 LOG_ERROR("error waiting for target flash write algorithm");
1015 int target_read_memory(struct target *target,
1016 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1018 if (!target_was_examined(target)) {
1019 LOG_ERROR("Target not examined yet");
1022 return target->type->read_memory(target, address, size, count, buffer);
1025 int target_read_phys_memory(struct target *target,
1026 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1028 if (!target_was_examined(target)) {
1029 LOG_ERROR("Target not examined yet");
1032 return target->type->read_phys_memory(target, address, size, count, buffer);
1035 int target_write_memory(struct target *target,
1036 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1038 if (!target_was_examined(target)) {
1039 LOG_ERROR("Target not examined yet");
1042 return target->type->write_memory(target, address, size, count, buffer);
1045 int target_write_phys_memory(struct target *target,
1046 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1048 if (!target_was_examined(target)) {
1049 LOG_ERROR("Target not examined yet");
1052 return target->type->write_phys_memory(target, address, size, count, buffer);
1055 int target_add_breakpoint(struct target *target,
1056 struct breakpoint *breakpoint)
1058 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1059 LOG_WARNING("target %s is not halted", target_name(target));
1060 return ERROR_TARGET_NOT_HALTED;
1062 return target->type->add_breakpoint(target, breakpoint);
1065 int target_add_context_breakpoint(struct target *target,
1066 struct breakpoint *breakpoint)
1068 if (target->state != TARGET_HALTED) {
1069 LOG_WARNING("target %s is not halted", target_name(target));
1070 return ERROR_TARGET_NOT_HALTED;
1072 return target->type->add_context_breakpoint(target, breakpoint);
1075 int target_add_hybrid_breakpoint(struct target *target,
1076 struct breakpoint *breakpoint)
1078 if (target->state != TARGET_HALTED) {
1079 LOG_WARNING("target %s is not halted", target_name(target));
1080 return ERROR_TARGET_NOT_HALTED;
1082 return target->type->add_hybrid_breakpoint(target, breakpoint);
1085 int target_remove_breakpoint(struct target *target,
1086 struct breakpoint *breakpoint)
1088 return target->type->remove_breakpoint(target, breakpoint);
1091 int target_add_watchpoint(struct target *target,
1092 struct watchpoint *watchpoint)
1094 if (target->state != TARGET_HALTED) {
1095 LOG_WARNING("target %s is not halted", target_name(target));
1096 return ERROR_TARGET_NOT_HALTED;
1098 return target->type->add_watchpoint(target, watchpoint);
1100 int target_remove_watchpoint(struct target *target,
1101 struct watchpoint *watchpoint)
1103 return target->type->remove_watchpoint(target, watchpoint);
1105 int target_hit_watchpoint(struct target *target,
1106 struct watchpoint **hit_watchpoint)
1108 if (target->state != TARGET_HALTED) {
1109 LOG_WARNING("target %s is not halted", target->cmd_name);
1110 return ERROR_TARGET_NOT_HALTED;
1113 if (target->type->hit_watchpoint == NULL) {
1114 /* For backward compatible, if hit_watchpoint is not implemented,
1115 * return ERROR_FAIL such that gdb_server will not take the nonsense
1120 return target->type->hit_watchpoint(target, hit_watchpoint);
1123 int target_get_gdb_reg_list(struct target *target,
1124 struct reg **reg_list[], int *reg_list_size,
1125 enum target_register_class reg_class)
1127 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1129 int target_step(struct target *target,
1130 int current, uint32_t address, int handle_breakpoints)
1132 return target->type->step(target, current, address, handle_breakpoints);
1135 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1137 if (target->state != TARGET_HALTED) {
1138 LOG_WARNING("target %s is not halted", target->cmd_name);
1139 return ERROR_TARGET_NOT_HALTED;
1141 return target->type->get_gdb_fileio_info(target, fileio_info);
1144 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1146 if (target->state != TARGET_HALTED) {
1147 LOG_WARNING("target %s is not halted", target->cmd_name);
1148 return ERROR_TARGET_NOT_HALTED;
1150 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1153 int target_profiling(struct target *target, uint32_t *samples,
1154 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1156 if (target->state != TARGET_HALTED) {
1157 LOG_WARNING("target %s is not halted", target->cmd_name);
1158 return ERROR_TARGET_NOT_HALTED;
1160 return target->type->profiling(target, samples, max_num_samples,
1161 num_samples, seconds);
1165 * Reset the @c examined flag for the given target.
1166 * Pure paranoia -- targets are zeroed on allocation.
1168 static void target_reset_examined(struct target *target)
1170 target->examined = false;
1173 static int err_read_phys_memory(struct target *target, uint32_t address,
1174 uint32_t size, uint32_t count, uint8_t *buffer)
1176 LOG_ERROR("Not implemented: %s", __func__);
1180 static int err_write_phys_memory(struct target *target, uint32_t address,
1181 uint32_t size, uint32_t count, const uint8_t *buffer)
1183 LOG_ERROR("Not implemented: %s", __func__);
1187 static int handle_target(void *priv);
1189 static int target_init_one(struct command_context *cmd_ctx,
1190 struct target *target)
1192 target_reset_examined(target);
1194 struct target_type *type = target->type;
1195 if (type->examine == NULL)
1196 type->examine = default_examine;
1198 if (type->check_reset == NULL)
1199 type->check_reset = default_check_reset;
1201 assert(type->init_target != NULL);
1203 int retval = type->init_target(cmd_ctx, target);
1204 if (ERROR_OK != retval) {
1205 LOG_ERROR("target '%s' init failed", target_name(target));
1209 /* Sanity-check MMU support ... stub in what we must, to help
1210 * implement it in stages, but warn if we need to do so.
1213 if (type->write_phys_memory == NULL) {
1214 LOG_ERROR("type '%s' is missing write_phys_memory",
1216 type->write_phys_memory = err_write_phys_memory;
1218 if (type->read_phys_memory == NULL) {
1219 LOG_ERROR("type '%s' is missing read_phys_memory",
1221 type->read_phys_memory = err_read_phys_memory;
1223 if (type->virt2phys == NULL) {
1224 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1225 type->virt2phys = identity_virt2phys;
1228 /* Make sure no-MMU targets all behave the same: make no
1229 * distinction between physical and virtual addresses, and
1230 * ensure that virt2phys() is always an identity mapping.
1232 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1233 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1236 type->write_phys_memory = type->write_memory;
1237 type->read_phys_memory = type->read_memory;
1238 type->virt2phys = identity_virt2phys;
1241 if (target->type->read_buffer == NULL)
1242 target->type->read_buffer = target_read_buffer_default;
1244 if (target->type->write_buffer == NULL)
1245 target->type->write_buffer = target_write_buffer_default;
1247 if (target->type->get_gdb_fileio_info == NULL)
1248 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1250 if (target->type->gdb_fileio_end == NULL)
1251 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1253 if (target->type->profiling == NULL)
1254 target->type->profiling = target_profiling_default;
1259 static int target_init(struct command_context *cmd_ctx)
1261 struct target *target;
1264 for (target = all_targets; target; target = target->next) {
1265 retval = target_init_one(cmd_ctx, target);
1266 if (ERROR_OK != retval)
1273 retval = target_register_user_commands(cmd_ctx);
1274 if (ERROR_OK != retval)
1277 retval = target_register_timer_callback(&handle_target,
1278 polling_interval, 1, cmd_ctx->interp);
1279 if (ERROR_OK != retval)
1285 COMMAND_HANDLER(handle_target_init_command)
1290 return ERROR_COMMAND_SYNTAX_ERROR;
1292 static bool target_initialized;
1293 if (target_initialized) {
1294 LOG_INFO("'target init' has already been called");
1297 target_initialized = true;
1299 retval = command_run_line(CMD_CTX, "init_targets");
1300 if (ERROR_OK != retval)
1303 retval = command_run_line(CMD_CTX, "init_target_events");
1304 if (ERROR_OK != retval)
1307 retval = command_run_line(CMD_CTX, "init_board");
1308 if (ERROR_OK != retval)
1311 LOG_DEBUG("Initializing targets...");
1312 return target_init(CMD_CTX);
1315 int target_register_event_callback(int (*callback)(struct target *target,
1316 enum target_event event, void *priv), void *priv)
1318 struct target_event_callback **callbacks_p = &target_event_callbacks;
1320 if (callback == NULL)
1321 return ERROR_COMMAND_SYNTAX_ERROR;
1324 while ((*callbacks_p)->next)
1325 callbacks_p = &((*callbacks_p)->next);
1326 callbacks_p = &((*callbacks_p)->next);
1329 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1330 (*callbacks_p)->callback = callback;
1331 (*callbacks_p)->priv = priv;
1332 (*callbacks_p)->next = NULL;
1337 int target_register_reset_callback(int (*callback)(struct target *target,
1338 enum target_reset_mode reset_mode, void *priv), void *priv)
1340 struct target_reset_callback *entry;
1342 if (callback == NULL)
1343 return ERROR_COMMAND_SYNTAX_ERROR;
1345 entry = malloc(sizeof(struct target_reset_callback));
1346 if (entry == NULL) {
1347 LOG_ERROR("error allocating buffer for reset callback entry");
1348 return ERROR_COMMAND_SYNTAX_ERROR;
1351 entry->callback = callback;
1353 list_add(&entry->list, &target_reset_callback_list);
1359 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1361 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1364 if (callback == NULL)
1365 return ERROR_COMMAND_SYNTAX_ERROR;
1368 while ((*callbacks_p)->next)
1369 callbacks_p = &((*callbacks_p)->next);
1370 callbacks_p = &((*callbacks_p)->next);
1373 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1374 (*callbacks_p)->callback = callback;
1375 (*callbacks_p)->periodic = periodic;
1376 (*callbacks_p)->time_ms = time_ms;
1377 (*callbacks_p)->removed = false;
1379 gettimeofday(&now, NULL);
1380 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
1381 time_ms -= (time_ms % 1000);
1382 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
1383 if ((*callbacks_p)->when.tv_usec > 1000000) {
1384 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
1385 (*callbacks_p)->when.tv_sec += 1;
1388 (*callbacks_p)->priv = priv;
1389 (*callbacks_p)->next = NULL;
1394 int target_unregister_event_callback(int (*callback)(struct target *target,
1395 enum target_event event, void *priv), void *priv)
1397 struct target_event_callback **p = &target_event_callbacks;
1398 struct target_event_callback *c = target_event_callbacks;
1400 if (callback == NULL)
1401 return ERROR_COMMAND_SYNTAX_ERROR;
1404 struct target_event_callback *next = c->next;
1405 if ((c->callback == callback) && (c->priv == priv)) {
1417 int target_unregister_reset_callback(int (*callback)(struct target *target,
1418 enum target_reset_mode reset_mode, void *priv), void *priv)
1420 struct target_reset_callback *entry;
1422 if (callback == NULL)
1423 return ERROR_COMMAND_SYNTAX_ERROR;
1425 list_for_each_entry(entry, &target_reset_callback_list, list) {
1426 if (entry->callback == callback && entry->priv == priv) {
1427 list_del(&entry->list);
1436 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1438 if (callback == NULL)
1439 return ERROR_COMMAND_SYNTAX_ERROR;
1441 for (struct target_timer_callback *c = target_timer_callbacks;
1443 if ((c->callback == callback) && (c->priv == priv)) {
1452 int target_call_event_callbacks(struct target *target, enum target_event event)
1454 struct target_event_callback *callback = target_event_callbacks;
1455 struct target_event_callback *next_callback;
1457 if (event == TARGET_EVENT_HALTED) {
1458 /* execute early halted first */
1459 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1462 LOG_DEBUG("target event %i (%s)", event,
1463 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1465 target_handle_event(target, event);
1468 next_callback = callback->next;
1469 callback->callback(target, event, callback->priv);
1470 callback = next_callback;
1476 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1478 struct target_reset_callback *callback;
1480 LOG_DEBUG("target reset %i (%s)", reset_mode,
1481 Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name);
1483 list_for_each_entry(callback, &target_reset_callback_list, list)
1484 callback->callback(target, reset_mode, callback->priv);
1489 static int target_timer_callback_periodic_restart(
1490 struct target_timer_callback *cb, struct timeval *now)
1492 int time_ms = cb->time_ms;
1493 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1494 time_ms -= (time_ms % 1000);
1495 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1496 if (cb->when.tv_usec > 1000000) {
1497 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1498 cb->when.tv_sec += 1;
1503 static int target_call_timer_callback(struct target_timer_callback *cb,
1504 struct timeval *now)
1506 cb->callback(cb->priv);
1509 return target_timer_callback_periodic_restart(cb, now);
1511 return target_unregister_timer_callback(cb->callback, cb->priv);
1514 static int target_call_timer_callbacks_check_time(int checktime)
1516 static bool callback_processing;
1518 /* Do not allow nesting */
1519 if (callback_processing)
1522 callback_processing = true;
1527 gettimeofday(&now, NULL);
1529 /* Store an address of the place containing a pointer to the
1530 * next item; initially, that's a standalone "root of the
1531 * list" variable. */
1532 struct target_timer_callback **callback = &target_timer_callbacks;
1534 if ((*callback)->removed) {
1535 struct target_timer_callback *p = *callback;
1536 *callback = (*callback)->next;
1541 bool call_it = (*callback)->callback &&
1542 ((!checktime && (*callback)->periodic) ||
1543 now.tv_sec > (*callback)->when.tv_sec ||
1544 (now.tv_sec == (*callback)->when.tv_sec &&
1545 now.tv_usec >= (*callback)->when.tv_usec));
1548 target_call_timer_callback(*callback, &now);
1550 callback = &(*callback)->next;
1553 callback_processing = false;
1557 int target_call_timer_callbacks(void)
1559 return target_call_timer_callbacks_check_time(1);
1562 /* invoke periodic callbacks immediately */
1563 int target_call_timer_callbacks_now(void)
1565 return target_call_timer_callbacks_check_time(0);
1568 /* Prints the working area layout for debug purposes */
1569 static void print_wa_layout(struct target *target)
1571 struct working_area *c = target->working_areas;
1574 LOG_DEBUG("%c%c 0x%08"PRIx32"-0x%08"PRIx32" (%"PRIu32" bytes)",
1575 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1576 c->address, c->address + c->size - 1, c->size);
1581 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1582 static void target_split_working_area(struct working_area *area, uint32_t size)
1584 assert(area->free); /* Shouldn't split an allocated area */
1585 assert(size <= area->size); /* Caller should guarantee this */
1587 /* Split only if not already the right size */
1588 if (size < area->size) {
1589 struct working_area *new_wa = malloc(sizeof(*new_wa));
1594 new_wa->next = area->next;
1595 new_wa->size = area->size - size;
1596 new_wa->address = area->address + size;
1597 new_wa->backup = NULL;
1598 new_wa->user = NULL;
1599 new_wa->free = true;
1601 area->next = new_wa;
1604 /* If backup memory was allocated to this area, it has the wrong size
1605 * now so free it and it will be reallocated if/when needed */
1608 area->backup = NULL;
1613 /* Merge all adjacent free areas into one */
1614 static void target_merge_working_areas(struct target *target)
1616 struct working_area *c = target->working_areas;
1618 while (c && c->next) {
1619 assert(c->next->address == c->address + c->size); /* This is an invariant */
1621 /* Find two adjacent free areas */
1622 if (c->free && c->next->free) {
1623 /* Merge the last into the first */
1624 c->size += c->next->size;
1626 /* Remove the last */
1627 struct working_area *to_be_freed = c->next;
1628 c->next = c->next->next;
1629 if (to_be_freed->backup)
1630 free(to_be_freed->backup);
1633 /* If backup memory was allocated to the remaining area, it's has
1634 * the wrong size now */
1645 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1647 /* Reevaluate working area address based on MMU state*/
1648 if (target->working_areas == NULL) {
1652 retval = target->type->mmu(target, &enabled);
1653 if (retval != ERROR_OK)
1657 if (target->working_area_phys_spec) {
1658 LOG_DEBUG("MMU disabled, using physical "
1659 "address for working memory 0x%08"PRIx32,
1660 target->working_area_phys);
1661 target->working_area = target->working_area_phys;
1663 LOG_ERROR("No working memory available. "
1664 "Specify -work-area-phys to target.");
1665 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1668 if (target->working_area_virt_spec) {
1669 LOG_DEBUG("MMU enabled, using virtual "
1670 "address for working memory 0x%08"PRIx32,
1671 target->working_area_virt);
1672 target->working_area = target->working_area_virt;
1674 LOG_ERROR("No working memory available. "
1675 "Specify -work-area-virt to target.");
1676 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1680 /* Set up initial working area on first call */
1681 struct working_area *new_wa = malloc(sizeof(*new_wa));
1683 new_wa->next = NULL;
1684 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1685 new_wa->address = target->working_area;
1686 new_wa->backup = NULL;
1687 new_wa->user = NULL;
1688 new_wa->free = true;
1691 target->working_areas = new_wa;
1694 /* only allocate multiples of 4 byte */
1696 size = (size + 3) & (~3UL);
1698 struct working_area *c = target->working_areas;
1700 /* Find the first large enough working area */
1702 if (c->free && c->size >= size)
1708 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1710 /* Split the working area into the requested size */
1711 target_split_working_area(c, size);
1713 LOG_DEBUG("allocated new working area of %"PRIu32" bytes at address 0x%08"PRIx32, size, c->address);
1715 if (target->backup_working_area) {
1716 if (c->backup == NULL) {
1717 c->backup = malloc(c->size);
1718 if (c->backup == NULL)
1722 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1723 if (retval != ERROR_OK)
1727 /* mark as used, and return the new (reused) area */
1734 print_wa_layout(target);
1739 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1743 retval = target_alloc_working_area_try(target, size, area);
1744 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1745 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1750 static int target_restore_working_area(struct target *target, struct working_area *area)
1752 int retval = ERROR_OK;
1754 if (target->backup_working_area && area->backup != NULL) {
1755 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1756 if (retval != ERROR_OK)
1757 LOG_ERROR("failed to restore %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1758 area->size, area->address);
1764 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1765 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1767 int retval = ERROR_OK;
1773 retval = target_restore_working_area(target, area);
1774 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1775 if (retval != ERROR_OK)
1781 LOG_DEBUG("freed %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1782 area->size, area->address);
1784 /* mark user pointer invalid */
1785 /* TODO: Is this really safe? It points to some previous caller's memory.
1786 * How could we know that the area pointer is still in that place and not
1787 * some other vital data? What's the purpose of this, anyway? */
1791 target_merge_working_areas(target);
1793 print_wa_layout(target);
1798 int target_free_working_area(struct target *target, struct working_area *area)
1800 return target_free_working_area_restore(target, area, 1);
1803 /* free resources and restore memory, if restoring memory fails,
1804 * free up resources anyway
1806 static void target_free_all_working_areas_restore(struct target *target, int restore)
1808 struct working_area *c = target->working_areas;
1810 LOG_DEBUG("freeing all working areas");
1812 /* Loop through all areas, restoring the allocated ones and marking them as free */
1816 target_restore_working_area(target, c);
1818 *c->user = NULL; /* Same as above */
1824 /* Run a merge pass to combine all areas into one */
1825 target_merge_working_areas(target);
1827 print_wa_layout(target);
1830 void target_free_all_working_areas(struct target *target)
1832 target_free_all_working_areas_restore(target, 1);
1835 /* Find the largest number of bytes that can be allocated */
1836 uint32_t target_get_working_area_avail(struct target *target)
1838 struct working_area *c = target->working_areas;
1839 uint32_t max_size = 0;
1842 return target->working_area_size;
1845 if (c->free && max_size < c->size)
1854 int target_arch_state(struct target *target)
1857 if (target == NULL) {
1858 LOG_USER("No target has been configured");
1862 LOG_USER("target state: %s", target_state_name(target));
1864 if (target->state != TARGET_HALTED)
1867 retval = target->type->arch_state(target);
1871 static int target_get_gdb_fileio_info_default(struct target *target,
1872 struct gdb_fileio_info *fileio_info)
1874 /* If target does not support semi-hosting function, target
1875 has no need to provide .get_gdb_fileio_info callback.
1876 It just return ERROR_FAIL and gdb_server will return "Txx"
1877 as target halted every time. */
1881 static int target_gdb_fileio_end_default(struct target *target,
1882 int retcode, int fileio_errno, bool ctrl_c)
1887 static int target_profiling_default(struct target *target, uint32_t *samples,
1888 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1890 struct timeval timeout, now;
1892 gettimeofday(&timeout, NULL);
1893 timeval_add_time(&timeout, seconds, 0);
1895 LOG_INFO("Starting profiling. Halting and resuming the"
1896 " target as often as we can...");
1898 uint32_t sample_count = 0;
1899 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
1900 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
1902 int retval = ERROR_OK;
1904 target_poll(target);
1905 if (target->state == TARGET_HALTED) {
1906 uint32_t t = buf_get_u32(reg->value, 0, 32);
1907 samples[sample_count++] = t;
1908 /* current pc, addr = 0, do not handle breakpoints, not debugging */
1909 retval = target_resume(target, 1, 0, 0, 0);
1910 target_poll(target);
1911 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
1912 } else if (target->state == TARGET_RUNNING) {
1913 /* We want to quickly sample the PC. */
1914 retval = target_halt(target);
1916 LOG_INFO("Target not halted or running");
1921 if (retval != ERROR_OK)
1924 gettimeofday(&now, NULL);
1925 if ((sample_count >= max_num_samples) ||
1926 ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec))) {
1927 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
1932 *num_samples = sample_count;
1936 /* Single aligned words are guaranteed to use 16 or 32 bit access
1937 * mode respectively, otherwise data is handled as quickly as
1940 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1942 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1943 (int)size, (unsigned)address);
1945 if (!target_was_examined(target)) {
1946 LOG_ERROR("Target not examined yet");
1953 if ((address + size - 1) < address) {
1954 /* GDB can request this when e.g. PC is 0xfffffffc*/
1955 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1961 return target->type->write_buffer(target, address, size, buffer);
1964 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t count, const uint8_t *buffer)
1968 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
1969 * will have something to do with the size we leave to it. */
1970 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
1971 if (address & size) {
1972 int retval = target_write_memory(target, address, size, 1, buffer);
1973 if (retval != ERROR_OK)
1981 /* Write the data with as large access size as possible. */
1982 for (; size > 0; size /= 2) {
1983 uint32_t aligned = count - count % size;
1985 int retval = target_write_memory(target, address, size, aligned / size, buffer);
1986 if (retval != ERROR_OK)
1997 /* Single aligned words are guaranteed to use 16 or 32 bit access
1998 * mode respectively, otherwise data is handled as quickly as
2001 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
2003 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
2004 (int)size, (unsigned)address);
2006 if (!target_was_examined(target)) {
2007 LOG_ERROR("Target not examined yet");
2014 if ((address + size - 1) < address) {
2015 /* GDB can request this when e.g. PC is 0xfffffffc*/
2016 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
2022 return target->type->read_buffer(target, address, size, buffer);
2025 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t count, uint8_t *buffer)
2029 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2030 * will have something to do with the size we leave to it. */
2031 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2032 if (address & size) {
2033 int retval = target_read_memory(target, address, size, 1, buffer);
2034 if (retval != ERROR_OK)
2042 /* Read the data with as large access size as possible. */
2043 for (; size > 0; size /= 2) {
2044 uint32_t aligned = count - count % size;
2046 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2047 if (retval != ERROR_OK)
2058 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
2063 uint32_t checksum = 0;
2064 if (!target_was_examined(target)) {
2065 LOG_ERROR("Target not examined yet");
2069 retval = target->type->checksum_memory(target, address, size, &checksum);
2070 if (retval != ERROR_OK) {
2071 buffer = malloc(size);
2072 if (buffer == NULL) {
2073 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
2074 return ERROR_COMMAND_SYNTAX_ERROR;
2076 retval = target_read_buffer(target, address, size, buffer);
2077 if (retval != ERROR_OK) {
2082 /* convert to target endianness */
2083 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2084 uint32_t target_data;
2085 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2086 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2089 retval = image_calculate_checksum(buffer, size, &checksum);
2098 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
2101 if (!target_was_examined(target)) {
2102 LOG_ERROR("Target not examined yet");
2106 if (target->type->blank_check_memory == 0)
2107 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2109 retval = target->type->blank_check_memory(target, address, size, blank);
2114 int target_read_u64(struct target *target, uint64_t address, uint64_t *value)
2116 uint8_t value_buf[8];
2117 if (!target_was_examined(target)) {
2118 LOG_ERROR("Target not examined yet");
2122 int retval = target_read_memory(target, address, 8, 1, value_buf);
2124 if (retval == ERROR_OK) {
2125 *value = target_buffer_get_u64(target, value_buf);
2126 LOG_DEBUG("address: 0x%" PRIx64 ", value: 0x%16.16" PRIx64 "",
2131 LOG_DEBUG("address: 0x%" PRIx64 " failed",
2138 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
2140 uint8_t value_buf[4];
2141 if (!target_was_examined(target)) {
2142 LOG_ERROR("Target not examined yet");
2146 int retval = target_read_memory(target, address, 4, 1, value_buf);
2148 if (retval == ERROR_OK) {
2149 *value = target_buffer_get_u32(target, value_buf);
2150 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2155 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2162 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
2164 uint8_t value_buf[2];
2165 if (!target_was_examined(target)) {
2166 LOG_ERROR("Target not examined yet");
2170 int retval = target_read_memory(target, address, 2, 1, value_buf);
2172 if (retval == ERROR_OK) {
2173 *value = target_buffer_get_u16(target, value_buf);
2174 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
2179 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2186 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
2188 if (!target_was_examined(target)) {
2189 LOG_ERROR("Target not examined yet");
2193 int retval = target_read_memory(target, address, 1, 1, value);
2195 if (retval == ERROR_OK) {
2196 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2201 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2208 int target_write_u64(struct target *target, uint64_t address, uint64_t value)
2211 uint8_t value_buf[8];
2212 if (!target_was_examined(target)) {
2213 LOG_ERROR("Target not examined yet");
2217 LOG_DEBUG("address: 0x%" PRIx64 ", value: 0x%16.16" PRIx64 "",
2221 target_buffer_set_u64(target, value_buf, value);
2222 retval = target_write_memory(target, address, 8, 1, value_buf);
2223 if (retval != ERROR_OK)
2224 LOG_DEBUG("failed: %i", retval);
2229 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
2232 uint8_t value_buf[4];
2233 if (!target_was_examined(target)) {
2234 LOG_ERROR("Target not examined yet");
2238 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2242 target_buffer_set_u32(target, value_buf, value);
2243 retval = target_write_memory(target, address, 4, 1, value_buf);
2244 if (retval != ERROR_OK)
2245 LOG_DEBUG("failed: %i", retval);
2250 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
2253 uint8_t value_buf[2];
2254 if (!target_was_examined(target)) {
2255 LOG_ERROR("Target not examined yet");
2259 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
2263 target_buffer_set_u16(target, value_buf, value);
2264 retval = target_write_memory(target, address, 2, 1, value_buf);
2265 if (retval != ERROR_OK)
2266 LOG_DEBUG("failed: %i", retval);
2271 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
2274 if (!target_was_examined(target)) {
2275 LOG_ERROR("Target not examined yet");
2279 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2282 retval = target_write_memory(target, address, 1, 1, &value);
2283 if (retval != ERROR_OK)
2284 LOG_DEBUG("failed: %i", retval);
2289 static int find_target(struct command_context *cmd_ctx, const char *name)
2291 struct target *target = get_target(name);
2292 if (target == NULL) {
2293 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2296 if (!target->tap->enabled) {
2297 LOG_USER("Target: TAP %s is disabled, "
2298 "can't be the current target\n",
2299 target->tap->dotted_name);
2303 cmd_ctx->current_target = target->target_number;
2308 COMMAND_HANDLER(handle_targets_command)
2310 int retval = ERROR_OK;
2311 if (CMD_ARGC == 1) {
2312 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2313 if (retval == ERROR_OK) {
2319 struct target *target = all_targets;
2320 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2321 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2326 if (target->tap->enabled)
2327 state = target_state_name(target);
2329 state = "tap-disabled";
2331 if (CMD_CTX->current_target == target->target_number)
2334 /* keep columns lined up to match the headers above */
2335 command_print(CMD_CTX,
2336 "%2d%c %-18s %-10s %-6s %-18s %s",
2337 target->target_number,
2339 target_name(target),
2340 target_type_name(target),
2341 Jim_Nvp_value2name_simple(nvp_target_endian,
2342 target->endianness)->name,
2343 target->tap->dotted_name,
2345 target = target->next;
2351 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2353 static int powerDropout;
2354 static int srstAsserted;
2356 static int runPowerRestore;
2357 static int runPowerDropout;
2358 static int runSrstAsserted;
2359 static int runSrstDeasserted;
2361 static int sense_handler(void)
2363 static int prevSrstAsserted;
2364 static int prevPowerdropout;
2366 int retval = jtag_power_dropout(&powerDropout);
2367 if (retval != ERROR_OK)
2371 powerRestored = prevPowerdropout && !powerDropout;
2373 runPowerRestore = 1;
2375 long long current = timeval_ms();
2376 static long long lastPower;
2377 int waitMore = lastPower + 2000 > current;
2378 if (powerDropout && !waitMore) {
2379 runPowerDropout = 1;
2380 lastPower = current;
2383 retval = jtag_srst_asserted(&srstAsserted);
2384 if (retval != ERROR_OK)
2388 srstDeasserted = prevSrstAsserted && !srstAsserted;
2390 static long long lastSrst;
2391 waitMore = lastSrst + 2000 > current;
2392 if (srstDeasserted && !waitMore) {
2393 runSrstDeasserted = 1;
2397 if (!prevSrstAsserted && srstAsserted)
2398 runSrstAsserted = 1;
2400 prevSrstAsserted = srstAsserted;
2401 prevPowerdropout = powerDropout;
2403 if (srstDeasserted || powerRestored) {
2404 /* Other than logging the event we can't do anything here.
2405 * Issuing a reset is a particularly bad idea as we might
2406 * be inside a reset already.
2413 /* process target state changes */
2414 static int handle_target(void *priv)
2416 Jim_Interp *interp = (Jim_Interp *)priv;
2417 int retval = ERROR_OK;
2419 if (!is_jtag_poll_safe()) {
2420 /* polling is disabled currently */
2424 /* we do not want to recurse here... */
2425 static int recursive;
2429 /* danger! running these procedures can trigger srst assertions and power dropouts.
2430 * We need to avoid an infinite loop/recursion here and we do that by
2431 * clearing the flags after running these events.
2433 int did_something = 0;
2434 if (runSrstAsserted) {
2435 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2436 Jim_Eval(interp, "srst_asserted");
2439 if (runSrstDeasserted) {
2440 Jim_Eval(interp, "srst_deasserted");
2443 if (runPowerDropout) {
2444 LOG_INFO("Power dropout detected, running power_dropout proc.");
2445 Jim_Eval(interp, "power_dropout");
2448 if (runPowerRestore) {
2449 Jim_Eval(interp, "power_restore");
2453 if (did_something) {
2454 /* clear detect flags */
2458 /* clear action flags */
2460 runSrstAsserted = 0;
2461 runSrstDeasserted = 0;
2462 runPowerRestore = 0;
2463 runPowerDropout = 0;
2468 /* Poll targets for state changes unless that's globally disabled.
2469 * Skip targets that are currently disabled.
2471 for (struct target *target = all_targets;
2472 is_jtag_poll_safe() && target;
2473 target = target->next) {
2475 if (!target_was_examined(target))
2478 if (!target->tap->enabled)
2481 if (target->backoff.times > target->backoff.count) {
2482 /* do not poll this time as we failed previously */
2483 target->backoff.count++;
2486 target->backoff.count = 0;
2488 /* only poll target if we've got power and srst isn't asserted */
2489 if (!powerDropout && !srstAsserted) {
2490 /* polling may fail silently until the target has been examined */
2491 retval = target_poll(target);
2492 if (retval != ERROR_OK) {
2493 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2494 if (target->backoff.times * polling_interval < 5000) {
2495 target->backoff.times *= 2;
2496 target->backoff.times++;
2498 LOG_USER("Polling target %s failed, GDB will be halted. Polling again in %dms",
2499 target_name(target),
2500 target->backoff.times * polling_interval);
2502 /* Tell GDB to halt the debugger. This allows the user to
2503 * run monitor commands to handle the situation.
2505 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2508 /* Since we succeeded, we reset backoff count */
2509 if (target->backoff.times > 0) {
2510 LOG_USER("Polling target %s succeeded again, trying to reexamine", target_name(target));
2511 target_reset_examined(target);
2512 retval = target_examine_one(target);
2513 /* Target examination could have failed due to unstable connection,
2514 * but we set the examined flag anyway to repoll it later */
2515 if (retval != ERROR_OK) {
2516 target->examined = true;
2521 target->backoff.times = 0;
2528 COMMAND_HANDLER(handle_reg_command)
2530 struct target *target;
2531 struct reg *reg = NULL;
2537 target = get_current_target(CMD_CTX);
2539 /* list all available registers for the current target */
2540 if (CMD_ARGC == 0) {
2541 struct reg_cache *cache = target->reg_cache;
2547 command_print(CMD_CTX, "===== %s", cache->name);
2549 for (i = 0, reg = cache->reg_list;
2550 i < cache->num_regs;
2551 i++, reg++, count++) {
2552 /* only print cached values if they are valid */
2554 value = buf_to_str(reg->value,
2556 command_print(CMD_CTX,
2557 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2565 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2570 cache = cache->next;
2576 /* access a single register by its ordinal number */
2577 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2579 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2581 struct reg_cache *cache = target->reg_cache;
2585 for (i = 0; i < cache->num_regs; i++) {
2586 if (count++ == num) {
2587 reg = &cache->reg_list[i];
2593 cache = cache->next;
2597 command_print(CMD_CTX, "%i is out of bounds, the current target "
2598 "has only %i registers (0 - %i)", num, count, count - 1);
2602 /* access a single register by its name */
2603 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2606 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2611 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2613 /* display a register */
2614 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2615 && (CMD_ARGV[1][0] <= '9')))) {
2616 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2619 if (reg->valid == 0)
2620 reg->type->get(reg);
2621 value = buf_to_str(reg->value, reg->size, 16);
2622 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2627 /* set register value */
2628 if (CMD_ARGC == 2) {
2629 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2632 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2634 reg->type->set(reg, buf);
2636 value = buf_to_str(reg->value, reg->size, 16);
2637 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2645 return ERROR_COMMAND_SYNTAX_ERROR;
2648 COMMAND_HANDLER(handle_poll_command)
2650 int retval = ERROR_OK;
2651 struct target *target = get_current_target(CMD_CTX);
2653 if (CMD_ARGC == 0) {
2654 command_print(CMD_CTX, "background polling: %s",
2655 jtag_poll_get_enabled() ? "on" : "off");
2656 command_print(CMD_CTX, "TAP: %s (%s)",
2657 target->tap->dotted_name,
2658 target->tap->enabled ? "enabled" : "disabled");
2659 if (!target->tap->enabled)
2661 retval = target_poll(target);
2662 if (retval != ERROR_OK)
2664 retval = target_arch_state(target);
2665 if (retval != ERROR_OK)
2667 } else if (CMD_ARGC == 1) {
2669 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2670 jtag_poll_set_enabled(enable);
2672 return ERROR_COMMAND_SYNTAX_ERROR;
2677 COMMAND_HANDLER(handle_wait_halt_command)
2680 return ERROR_COMMAND_SYNTAX_ERROR;
2682 unsigned ms = DEFAULT_HALT_TIMEOUT;
2683 if (1 == CMD_ARGC) {
2684 int retval = parse_uint(CMD_ARGV[0], &ms);
2685 if (ERROR_OK != retval)
2686 return ERROR_COMMAND_SYNTAX_ERROR;
2689 struct target *target = get_current_target(CMD_CTX);
2690 return target_wait_state(target, TARGET_HALTED, ms);
2693 /* wait for target state to change. The trick here is to have a low
2694 * latency for short waits and not to suck up all the CPU time
2697 * After 500ms, keep_alive() is invoked
2699 int target_wait_state(struct target *target, enum target_state state, int ms)
2702 long long then = 0, cur;
2706 retval = target_poll(target);
2707 if (retval != ERROR_OK)
2709 if (target->state == state)
2714 then = timeval_ms();
2715 LOG_DEBUG("waiting for target %s...",
2716 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2722 if ((cur-then) > ms) {
2723 LOG_ERROR("timed out while waiting for target %s",
2724 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2732 COMMAND_HANDLER(handle_halt_command)
2736 struct target *target = get_current_target(CMD_CTX);
2737 int retval = target_halt(target);
2738 if (ERROR_OK != retval)
2741 if (CMD_ARGC == 1) {
2742 unsigned wait_local;
2743 retval = parse_uint(CMD_ARGV[0], &wait_local);
2744 if (ERROR_OK != retval)
2745 return ERROR_COMMAND_SYNTAX_ERROR;
2750 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2753 COMMAND_HANDLER(handle_soft_reset_halt_command)
2755 struct target *target = get_current_target(CMD_CTX);
2757 LOG_USER("requesting target halt and executing a soft reset");
2759 target_soft_reset_halt(target);
2764 COMMAND_HANDLER(handle_reset_command)
2767 return ERROR_COMMAND_SYNTAX_ERROR;
2769 enum target_reset_mode reset_mode = RESET_RUN;
2770 if (CMD_ARGC == 1) {
2772 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2773 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2774 return ERROR_COMMAND_SYNTAX_ERROR;
2775 reset_mode = n->value;
2778 /* reset *all* targets */
2779 return target_process_reset(CMD_CTX, reset_mode);
2783 COMMAND_HANDLER(handle_resume_command)
2787 return ERROR_COMMAND_SYNTAX_ERROR;
2789 struct target *target = get_current_target(CMD_CTX);
2791 /* with no CMD_ARGV, resume from current pc, addr = 0,
2792 * with one arguments, addr = CMD_ARGV[0],
2793 * handle breakpoints, not debugging */
2795 if (CMD_ARGC == 1) {
2796 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2800 return target_resume(target, current, addr, 1, 0);
2803 COMMAND_HANDLER(handle_step_command)
2806 return ERROR_COMMAND_SYNTAX_ERROR;
2810 /* with no CMD_ARGV, step from current pc, addr = 0,
2811 * with one argument addr = CMD_ARGV[0],
2812 * handle breakpoints, debugging */
2815 if (CMD_ARGC == 1) {
2816 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2820 struct target *target = get_current_target(CMD_CTX);
2822 return target->type->step(target, current_pc, addr, 1);
2825 static void handle_md_output(struct command_context *cmd_ctx,
2826 struct target *target, uint32_t address, unsigned size,
2827 unsigned count, const uint8_t *buffer)
2829 const unsigned line_bytecnt = 32;
2830 unsigned line_modulo = line_bytecnt / size;
2832 char output[line_bytecnt * 4 + 1];
2833 unsigned output_len = 0;
2835 const char *value_fmt;
2838 value_fmt = "%8.8x ";
2841 value_fmt = "%4.4x ";
2844 value_fmt = "%2.2x ";
2847 /* "can't happen", caller checked */
2848 LOG_ERROR("invalid memory read size: %u", size);
2852 for (unsigned i = 0; i < count; i++) {
2853 if (i % line_modulo == 0) {
2854 output_len += snprintf(output + output_len,
2855 sizeof(output) - output_len,
2857 (unsigned)(address + (i*size)));
2861 const uint8_t *value_ptr = buffer + i * size;
2864 value = target_buffer_get_u32(target, value_ptr);
2867 value = target_buffer_get_u16(target, value_ptr);
2872 output_len += snprintf(output + output_len,
2873 sizeof(output) - output_len,
2876 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2877 command_print(cmd_ctx, "%s", output);
2883 COMMAND_HANDLER(handle_md_command)
2886 return ERROR_COMMAND_SYNTAX_ERROR;
2889 switch (CMD_NAME[2]) {
2900 return ERROR_COMMAND_SYNTAX_ERROR;
2903 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2904 int (*fn)(struct target *target,
2905 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2909 fn = target_read_phys_memory;
2911 fn = target_read_memory;
2912 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2913 return ERROR_COMMAND_SYNTAX_ERROR;
2916 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2920 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2922 uint8_t *buffer = calloc(count, size);
2924 struct target *target = get_current_target(CMD_CTX);
2925 int retval = fn(target, address, size, count, buffer);
2926 if (ERROR_OK == retval)
2927 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2934 typedef int (*target_write_fn)(struct target *target,
2935 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2937 static int target_fill_mem(struct target *target,
2946 /* We have to write in reasonably large chunks to be able
2947 * to fill large memory areas with any sane speed */
2948 const unsigned chunk_size = 16384;
2949 uint8_t *target_buf = malloc(chunk_size * data_size);
2950 if (target_buf == NULL) {
2951 LOG_ERROR("Out of memory");
2955 for (unsigned i = 0; i < chunk_size; i++) {
2956 switch (data_size) {
2958 target_buffer_set_u32(target, target_buf + i * data_size, b);
2961 target_buffer_set_u16(target, target_buf + i * data_size, b);
2964 target_buffer_set_u8(target, target_buf + i * data_size, b);
2971 int retval = ERROR_OK;
2973 for (unsigned x = 0; x < c; x += chunk_size) {
2976 if (current > chunk_size)
2977 current = chunk_size;
2978 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2979 if (retval != ERROR_OK)
2981 /* avoid GDB timeouts */
2990 COMMAND_HANDLER(handle_mw_command)
2993 return ERROR_COMMAND_SYNTAX_ERROR;
2994 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2999 fn = target_write_phys_memory;
3001 fn = target_write_memory;
3002 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3003 return ERROR_COMMAND_SYNTAX_ERROR;
3006 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
3009 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
3013 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3015 struct target *target = get_current_target(CMD_CTX);
3017 switch (CMD_NAME[2]) {
3028 return ERROR_COMMAND_SYNTAX_ERROR;
3031 return target_fill_mem(target, address, fn, wordsize, value, count);
3034 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
3035 uint32_t *min_address, uint32_t *max_address)
3037 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3038 return ERROR_COMMAND_SYNTAX_ERROR;
3040 /* a base address isn't always necessary,
3041 * default to 0x0 (i.e. don't relocate) */
3042 if (CMD_ARGC >= 2) {
3044 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3045 image->base_address = addr;
3046 image->base_address_set = 1;
3048 image->base_address_set = 0;
3050 image->start_address_set = 0;
3053 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
3054 if (CMD_ARGC == 5) {
3055 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
3056 /* use size (given) to find max (required) */
3057 *max_address += *min_address;
3060 if (*min_address > *max_address)
3061 return ERROR_COMMAND_SYNTAX_ERROR;
3066 COMMAND_HANDLER(handle_load_image_command)
3070 uint32_t image_size;
3071 uint32_t min_address = 0;
3072 uint32_t max_address = 0xffffffff;
3076 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
3077 &image, &min_address, &max_address);
3078 if (ERROR_OK != retval)
3081 struct target *target = get_current_target(CMD_CTX);
3083 struct duration bench;
3084 duration_start(&bench);
3086 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3091 for (i = 0; i < image.num_sections; i++) {
3092 buffer = malloc(image.sections[i].size);
3093 if (buffer == NULL) {
3094 command_print(CMD_CTX,
3095 "error allocating buffer for section (%d bytes)",
3096 (int)(image.sections[i].size));
3100 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3101 if (retval != ERROR_OK) {
3106 uint32_t offset = 0;
3107 uint32_t length = buf_cnt;
3109 /* DANGER!!! beware of unsigned comparision here!!! */
3111 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3112 (image.sections[i].base_address < max_address)) {
3114 if (image.sections[i].base_address < min_address) {
3115 /* clip addresses below */
3116 offset += min_address-image.sections[i].base_address;
3120 if (image.sections[i].base_address + buf_cnt > max_address)
3121 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3123 retval = target_write_buffer(target,
3124 image.sections[i].base_address + offset, length, buffer + offset);
3125 if (retval != ERROR_OK) {
3129 image_size += length;
3130 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
3131 (unsigned int)length,
3132 image.sections[i].base_address + offset);
3138 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3139 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
3140 "in %fs (%0.3f KiB/s)", image_size,
3141 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3144 image_close(&image);
3150 COMMAND_HANDLER(handle_dump_image_command)
3152 struct fileio fileio;
3154 int retval, retvaltemp;
3155 uint32_t address, size;
3156 struct duration bench;
3157 struct target *target = get_current_target(CMD_CTX);
3160 return ERROR_COMMAND_SYNTAX_ERROR;
3162 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
3163 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
3165 uint32_t buf_size = (size > 4096) ? 4096 : size;
3166 buffer = malloc(buf_size);
3170 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3171 if (retval != ERROR_OK) {
3176 duration_start(&bench);
3179 size_t size_written;
3180 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3181 retval = target_read_buffer(target, address, this_run_size, buffer);
3182 if (retval != ERROR_OK)
3185 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
3186 if (retval != ERROR_OK)
3189 size -= this_run_size;
3190 address += this_run_size;
3195 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3197 retval = fileio_size(&fileio, &filesize);
3198 if (retval != ERROR_OK)
3200 command_print(CMD_CTX,
3201 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
3202 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3205 retvaltemp = fileio_close(&fileio);
3206 if (retvaltemp != ERROR_OK)
3212 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
3216 uint32_t image_size;
3219 uint32_t checksum = 0;
3220 uint32_t mem_checksum = 0;
3224 struct target *target = get_current_target(CMD_CTX);
3227 return ERROR_COMMAND_SYNTAX_ERROR;
3230 LOG_ERROR("no target selected");
3234 struct duration bench;
3235 duration_start(&bench);
3237 if (CMD_ARGC >= 2) {
3239 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3240 image.base_address = addr;
3241 image.base_address_set = 1;
3243 image.base_address_set = 0;
3244 image.base_address = 0x0;
3247 image.start_address_set = 0;
3249 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3250 if (retval != ERROR_OK)
3256 for (i = 0; i < image.num_sections; i++) {
3257 buffer = malloc(image.sections[i].size);
3258 if (buffer == NULL) {
3259 command_print(CMD_CTX,
3260 "error allocating buffer for section (%d bytes)",
3261 (int)(image.sections[i].size));
3264 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3265 if (retval != ERROR_OK) {
3271 /* calculate checksum of image */
3272 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3273 if (retval != ERROR_OK) {
3278 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3279 if (retval != ERROR_OK) {
3284 if (checksum != mem_checksum) {
3285 /* failed crc checksum, fall back to a binary compare */
3289 LOG_ERROR("checksum mismatch - attempting binary compare");
3291 data = malloc(buf_cnt);
3293 /* Can we use 32bit word accesses? */
3295 int count = buf_cnt;
3296 if ((count % 4) == 0) {
3300 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3301 if (retval == ERROR_OK) {
3303 for (t = 0; t < buf_cnt; t++) {
3304 if (data[t] != buffer[t]) {
3305 command_print(CMD_CTX,
3306 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3308 (unsigned)(t + image.sections[i].base_address),
3311 if (diffs++ >= 127) {
3312 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3324 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3325 image.sections[i].base_address,
3330 image_size += buf_cnt;
3333 command_print(CMD_CTX, "No more differences found.");
3336 retval = ERROR_FAIL;
3337 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3338 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3339 "in %fs (%0.3f KiB/s)", image_size,
3340 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3343 image_close(&image);
3348 COMMAND_HANDLER(handle_verify_image_command)
3350 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3353 COMMAND_HANDLER(handle_test_image_command)
3355 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3358 static int handle_bp_command_list(struct command_context *cmd_ctx)
3360 struct target *target = get_current_target(cmd_ctx);
3361 struct breakpoint *breakpoint = target->breakpoints;
3362 while (breakpoint) {
3363 if (breakpoint->type == BKPT_SOFT) {
3364 char *buf = buf_to_str(breakpoint->orig_instr,
3365 breakpoint->length, 16);
3366 command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3367 breakpoint->address,
3369 breakpoint->set, buf);
3372 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3373 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3375 breakpoint->length, breakpoint->set);
3376 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3377 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3378 breakpoint->address,
3379 breakpoint->length, breakpoint->set);
3380 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3383 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3384 breakpoint->address,
3385 breakpoint->length, breakpoint->set);
3388 breakpoint = breakpoint->next;
3393 static int handle_bp_command_set(struct command_context *cmd_ctx,
3394 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3396 struct target *target = get_current_target(cmd_ctx);
3400 retval = breakpoint_add(target, addr, length, hw);
3401 if (ERROR_OK == retval)
3402 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3404 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3407 } else if (addr == 0) {
3408 if (target->type->add_context_breakpoint == NULL) {
3409 LOG_WARNING("Context breakpoint not available");
3412 retval = context_breakpoint_add(target, asid, length, hw);
3413 if (ERROR_OK == retval)
3414 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3416 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3420 if (target->type->add_hybrid_breakpoint == NULL) {
3421 LOG_WARNING("Hybrid breakpoint not available");
3424 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3425 if (ERROR_OK == retval)
3426 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3428 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3435 COMMAND_HANDLER(handle_bp_command)
3444 return handle_bp_command_list(CMD_CTX);
3448 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3449 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3450 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3453 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3455 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3457 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3460 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3461 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3463 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3464 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3466 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3471 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3472 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3473 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3474 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3477 return ERROR_COMMAND_SYNTAX_ERROR;
3481 COMMAND_HANDLER(handle_rbp_command)
3484 return ERROR_COMMAND_SYNTAX_ERROR;
3487 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3489 struct target *target = get_current_target(CMD_CTX);
3490 breakpoint_remove(target, addr);
3495 COMMAND_HANDLER(handle_wp_command)
3497 struct target *target = get_current_target(CMD_CTX);
3499 if (CMD_ARGC == 0) {
3500 struct watchpoint *watchpoint = target->watchpoints;
3502 while (watchpoint) {
3503 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3504 ", len: 0x%8.8" PRIx32
3505 ", r/w/a: %i, value: 0x%8.8" PRIx32
3506 ", mask: 0x%8.8" PRIx32,
3507 watchpoint->address,
3509 (int)watchpoint->rw,
3512 watchpoint = watchpoint->next;
3517 enum watchpoint_rw type = WPT_ACCESS;
3519 uint32_t length = 0;
3520 uint32_t data_value = 0x0;
3521 uint32_t data_mask = 0xffffffff;
3525 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3528 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3531 switch (CMD_ARGV[2][0]) {
3542 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3543 return ERROR_COMMAND_SYNTAX_ERROR;
3547 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3548 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3552 return ERROR_COMMAND_SYNTAX_ERROR;
3555 int retval = watchpoint_add(target, addr, length, type,
3556 data_value, data_mask);
3557 if (ERROR_OK != retval)
3558 LOG_ERROR("Failure setting watchpoints");
3563 COMMAND_HANDLER(handle_rwp_command)
3566 return ERROR_COMMAND_SYNTAX_ERROR;
3569 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3571 struct target *target = get_current_target(CMD_CTX);
3572 watchpoint_remove(target, addr);
3578 * Translate a virtual address to a physical address.
3580 * The low-level target implementation must have logged a detailed error
3581 * which is forwarded to telnet/GDB session.
3583 COMMAND_HANDLER(handle_virt2phys_command)
3586 return ERROR_COMMAND_SYNTAX_ERROR;
3589 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3592 struct target *target = get_current_target(CMD_CTX);
3593 int retval = target->type->virt2phys(target, va, &pa);
3594 if (retval == ERROR_OK)
3595 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3600 static void writeData(FILE *f, const void *data, size_t len)
3602 size_t written = fwrite(data, 1, len, f);
3604 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3607 static void writeLong(FILE *f, int l, struct target *target)
3611 target_buffer_set_u32(target, val, l);
3612 writeData(f, val, 4);
3615 static void writeString(FILE *f, char *s)
3617 writeData(f, s, strlen(s));
3620 typedef unsigned char UNIT[2]; /* unit of profiling */
3622 /* Dump a gmon.out histogram file. */
3623 static void write_gmon(uint32_t *samples, uint32_t sampleNum, const char *filename, bool with_range,
3624 uint32_t start_address, uint32_t end_address, struct target *target)
3627 FILE *f = fopen(filename, "w");
3630 writeString(f, "gmon");
3631 writeLong(f, 0x00000001, target); /* Version */
3632 writeLong(f, 0, target); /* padding */
3633 writeLong(f, 0, target); /* padding */
3634 writeLong(f, 0, target); /* padding */
3636 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3637 writeData(f, &zero, 1);
3639 /* figure out bucket size */
3643 min = start_address;
3648 for (i = 0; i < sampleNum; i++) {
3649 if (min > samples[i])
3651 if (max < samples[i])
3655 /* max should be (largest sample + 1)
3656 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
3660 int addressSpace = max - min;
3661 assert(addressSpace >= 2);
3663 /* FIXME: What is the reasonable number of buckets?
3664 * The profiling result will be more accurate if there are enough buckets. */
3665 static const uint32_t maxBuckets = 128 * 1024; /* maximum buckets. */
3666 uint32_t numBuckets = addressSpace / sizeof(UNIT);
3667 if (numBuckets > maxBuckets)
3668 numBuckets = maxBuckets;
3669 int *buckets = malloc(sizeof(int) * numBuckets);
3670 if (buckets == NULL) {
3674 memset(buckets, 0, sizeof(int) * numBuckets);
3675 for (i = 0; i < sampleNum; i++) {
3676 uint32_t address = samples[i];
3678 if ((address < min) || (max <= address))
3681 long long a = address - min;
3682 long long b = numBuckets;
3683 long long c = addressSpace;
3684 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3688 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3689 writeLong(f, min, target); /* low_pc */
3690 writeLong(f, max, target); /* high_pc */
3691 writeLong(f, numBuckets, target); /* # of buckets */
3692 writeLong(f, 100, target); /* KLUDGE! We lie, ca. 100Hz best case. */
3693 writeString(f, "seconds");
3694 for (i = 0; i < (15-strlen("seconds")); i++)
3695 writeData(f, &zero, 1);
3696 writeString(f, "s");
3698 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3700 char *data = malloc(2 * numBuckets);
3702 for (i = 0; i < numBuckets; i++) {
3707 data[i * 2] = val&0xff;
3708 data[i * 2 + 1] = (val >> 8) & 0xff;
3711 writeData(f, data, numBuckets * 2);
3719 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3720 * which will be used as a random sampling of PC */
3721 COMMAND_HANDLER(handle_profile_command)
3723 struct target *target = get_current_target(CMD_CTX);
3725 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
3726 return ERROR_COMMAND_SYNTAX_ERROR;
3728 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
3730 uint32_t num_of_samples;
3731 int retval = ERROR_OK;
3733 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
3735 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
3736 if (samples == NULL) {
3737 LOG_ERROR("No memory to store samples.");
3742 * Some cores let us sample the PC without the
3743 * annoying halt/resume step; for example, ARMv7 PCSR.
3744 * Provide a way to use that more efficient mechanism.
3746 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
3747 &num_of_samples, offset);
3748 if (retval != ERROR_OK) {
3753 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
3755 retval = target_poll(target);
3756 if (retval != ERROR_OK) {
3760 if (target->state == TARGET_RUNNING) {
3761 retval = target_halt(target);
3762 if (retval != ERROR_OK) {
3768 retval = target_poll(target);
3769 if (retval != ERROR_OK) {
3774 uint32_t start_address = 0;
3775 uint32_t end_address = 0;
3776 bool with_range = false;
3777 if (CMD_ARGC == 4) {
3779 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
3780 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
3783 write_gmon(samples, num_of_samples, CMD_ARGV[1],
3784 with_range, start_address, end_address, target);
3785 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3791 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3794 Jim_Obj *nameObjPtr, *valObjPtr;
3797 namebuf = alloc_printf("%s(%d)", varname, idx);
3801 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3802 valObjPtr = Jim_NewIntObj(interp, val);
3803 if (!nameObjPtr || !valObjPtr) {
3808 Jim_IncrRefCount(nameObjPtr);
3809 Jim_IncrRefCount(valObjPtr);
3810 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3811 Jim_DecrRefCount(interp, nameObjPtr);
3812 Jim_DecrRefCount(interp, valObjPtr);
3814 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3818 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3820 struct command_context *context;
3821 struct target *target;
3823 context = current_command_context(interp);
3824 assert(context != NULL);
3826 target = get_current_target(context);
3827 if (target == NULL) {
3828 LOG_ERROR("mem2array: no current target");
3832 return target_mem2array(interp, target, argc - 1, argv + 1);
3835 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3843 const char *varname;
3847 /* argv[1] = name of array to receive the data
3848 * argv[2] = desired width
3849 * argv[3] = memory address
3850 * argv[4] = count of times to read
3853 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3856 varname = Jim_GetString(argv[0], &len);
3857 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3859 e = Jim_GetLong(interp, argv[1], &l);
3864 e = Jim_GetLong(interp, argv[2], &l);
3868 e = Jim_GetLong(interp, argv[3], &l);
3883 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3884 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3888 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3889 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3892 if ((addr + (len * width)) < addr) {
3893 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3894 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3897 /* absurd transfer size? */
3899 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3900 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3905 ((width == 2) && ((addr & 1) == 0)) ||
3906 ((width == 4) && ((addr & 3) == 0))) {
3910 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3911 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3914 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3923 size_t buffersize = 4096;
3924 uint8_t *buffer = malloc(buffersize);
3931 /* Slurp... in buffer size chunks */
3933 count = len; /* in objects.. */
3934 if (count > (buffersize / width))
3935 count = (buffersize / width);
3937 retval = target_read_memory(target, addr, width, count, buffer);
3938 if (retval != ERROR_OK) {
3940 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3944 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3945 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3949 v = 0; /* shut up gcc */
3950 for (i = 0; i < count ; i++, n++) {
3953 v = target_buffer_get_u32(target, &buffer[i*width]);
3956 v = target_buffer_get_u16(target, &buffer[i*width]);
3959 v = buffer[i] & 0x0ff;
3962 new_int_array_element(interp, varname, n, v);
3965 addr += count * width;
3971 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3976 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
3979 Jim_Obj *nameObjPtr, *valObjPtr;
3983 namebuf = alloc_printf("%s(%d)", varname, idx);
3987 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3993 Jim_IncrRefCount(nameObjPtr);
3994 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3995 Jim_DecrRefCount(interp, nameObjPtr);
3997 if (valObjPtr == NULL)
4000 result = Jim_GetLong(interp, valObjPtr, &l);
4001 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
4006 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4008 struct command_context *context;
4009 struct target *target;
4011 context = current_command_context(interp);
4012 assert(context != NULL);
4014 target = get_current_target(context);
4015 if (target == NULL) {
4016 LOG_ERROR("array2mem: no current target");
4020 return target_array2mem(interp, target, argc-1, argv + 1);
4023 static int target_array2mem(Jim_Interp *interp, struct target *target,
4024 int argc, Jim_Obj *const *argv)
4032 const char *varname;
4036 /* argv[1] = name of array to get the data
4037 * argv[2] = desired width
4038 * argv[3] = memory address
4039 * argv[4] = count to write
4042 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
4045 varname = Jim_GetString(argv[0], &len);
4046 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
4048 e = Jim_GetLong(interp, argv[1], &l);
4053 e = Jim_GetLong(interp, argv[2], &l);
4057 e = Jim_GetLong(interp, argv[3], &l);
4072 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4073 Jim_AppendStrings(interp, Jim_GetResult(interp),
4074 "Invalid width param, must be 8/16/32", NULL);
4078 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4079 Jim_AppendStrings(interp, Jim_GetResult(interp),
4080 "array2mem: zero width read?", NULL);
4083 if ((addr + (len * width)) < addr) {
4084 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4085 Jim_AppendStrings(interp, Jim_GetResult(interp),
4086 "array2mem: addr + len - wraps to zero?", NULL);
4089 /* absurd transfer size? */
4091 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4092 Jim_AppendStrings(interp, Jim_GetResult(interp),
4093 "array2mem: absurd > 64K item request", NULL);
4098 ((width == 2) && ((addr & 1) == 0)) ||
4099 ((width == 4) && ((addr & 3) == 0))) {
4103 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4104 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
4107 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
4118 size_t buffersize = 4096;
4119 uint8_t *buffer = malloc(buffersize);
4124 /* Slurp... in buffer size chunks */
4126 count = len; /* in objects.. */
4127 if (count > (buffersize / width))
4128 count = (buffersize / width);
4130 v = 0; /* shut up gcc */
4131 for (i = 0; i < count; i++, n++) {
4132 get_int_array_element(interp, varname, n, &v);
4135 target_buffer_set_u32(target, &buffer[i * width], v);
4138 target_buffer_set_u16(target, &buffer[i * width], v);
4141 buffer[i] = v & 0x0ff;
4147 retval = target_write_memory(target, addr, width, count, buffer);
4148 if (retval != ERROR_OK) {
4150 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
4154 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4155 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4159 addr += count * width;
4164 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4169 /* FIX? should we propagate errors here rather than printing them
4172 void target_handle_event(struct target *target, enum target_event e)
4174 struct target_event_action *teap;
4176 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4177 if (teap->event == e) {
4178 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
4179 target->target_number,
4180 target_name(target),
4181 target_type_name(target),
4183 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
4184 Jim_GetString(teap->body, NULL));
4185 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
4186 Jim_MakeErrorMessage(teap->interp);
4187 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
4194 * Returns true only if the target has a handler for the specified event.
4196 bool target_has_event_action(struct target *target, enum target_event event)
4198 struct target_event_action *teap;
4200 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4201 if (teap->event == event)
4207 enum target_cfg_param {
4210 TCFG_WORK_AREA_VIRT,
4211 TCFG_WORK_AREA_PHYS,
4212 TCFG_WORK_AREA_SIZE,
4213 TCFG_WORK_AREA_BACKUP,
4216 TCFG_CHAIN_POSITION,
4221 static Jim_Nvp nvp_config_opts[] = {
4222 { .name = "-type", .value = TCFG_TYPE },
4223 { .name = "-event", .value = TCFG_EVENT },
4224 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4225 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4226 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4227 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4228 { .name = "-endian" , .value = TCFG_ENDIAN },
4229 { .name = "-coreid", .value = TCFG_COREID },
4230 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4231 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4232 { .name = "-rtos", .value = TCFG_RTOS },
4233 { .name = NULL, .value = -1 }
4236 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
4243 /* parse config or cget options ... */
4244 while (goi->argc > 0) {
4245 Jim_SetEmptyResult(goi->interp);
4246 /* Jim_GetOpt_Debug(goi); */
4248 if (target->type->target_jim_configure) {
4249 /* target defines a configure function */
4250 /* target gets first dibs on parameters */
4251 e = (*(target->type->target_jim_configure))(target, goi);
4260 /* otherwise we 'continue' below */
4262 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
4264 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
4270 if (goi->isconfigure) {
4271 Jim_SetResultFormatted(goi->interp,
4272 "not settable: %s", n->name);
4276 if (goi->argc != 0) {
4277 Jim_WrongNumArgs(goi->interp,
4278 goi->argc, goi->argv,
4283 Jim_SetResultString(goi->interp,
4284 target_type_name(target), -1);
4288 if (goi->argc == 0) {
4289 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4293 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4295 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4299 if (goi->isconfigure) {
4300 if (goi->argc != 1) {
4301 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4305 if (goi->argc != 0) {
4306 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4312 struct target_event_action *teap;
4314 teap = target->event_action;
4315 /* replace existing? */
4317 if (teap->event == (enum target_event)n->value)
4322 if (goi->isconfigure) {
4323 bool replace = true;
4326 teap = calloc(1, sizeof(*teap));
4329 teap->event = n->value;
4330 teap->interp = goi->interp;
4331 Jim_GetOpt_Obj(goi, &o);
4333 Jim_DecrRefCount(teap->interp, teap->body);
4334 teap->body = Jim_DuplicateObj(goi->interp, o);
4337 * Tcl/TK - "tk events" have a nice feature.
4338 * See the "BIND" command.
4339 * We should support that here.
4340 * You can specify %X and %Y in the event code.
4341 * The idea is: %T - target name.
4342 * The idea is: %N - target number
4343 * The idea is: %E - event name.
4345 Jim_IncrRefCount(teap->body);
4348 /* add to head of event list */
4349 teap->next = target->event_action;
4350 target->event_action = teap;
4352 Jim_SetEmptyResult(goi->interp);
4356 Jim_SetEmptyResult(goi->interp);
4358 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4364 case TCFG_WORK_AREA_VIRT:
4365 if (goi->isconfigure) {
4366 target_free_all_working_areas(target);
4367 e = Jim_GetOpt_Wide(goi, &w);
4370 target->working_area_virt = w;
4371 target->working_area_virt_spec = true;
4376 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4380 case TCFG_WORK_AREA_PHYS:
4381 if (goi->isconfigure) {
4382 target_free_all_working_areas(target);
4383 e = Jim_GetOpt_Wide(goi, &w);
4386 target->working_area_phys = w;
4387 target->working_area_phys_spec = true;
4392 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4396 case TCFG_WORK_AREA_SIZE:
4397 if (goi->isconfigure) {
4398 target_free_all_working_areas(target);
4399 e = Jim_GetOpt_Wide(goi, &w);
4402 target->working_area_size = w;
4407 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4411 case TCFG_WORK_AREA_BACKUP:
4412 if (goi->isconfigure) {
4413 target_free_all_working_areas(target);
4414 e = Jim_GetOpt_Wide(goi, &w);
4417 /* make this exactly 1 or 0 */
4418 target->backup_working_area = (!!w);
4423 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4424 /* loop for more e*/
4429 if (goi->isconfigure) {
4430 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4432 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4435 target->endianness = n->value;
4440 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4441 if (n->name == NULL) {
4442 target->endianness = TARGET_LITTLE_ENDIAN;
4443 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4445 Jim_SetResultString(goi->interp, n->name, -1);
4450 if (goi->isconfigure) {
4451 e = Jim_GetOpt_Wide(goi, &w);
4454 target->coreid = (int32_t)w;
4459 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4463 case TCFG_CHAIN_POSITION:
4464 if (goi->isconfigure) {
4466 struct jtag_tap *tap;
4467 target_free_all_working_areas(target);
4468 e = Jim_GetOpt_Obj(goi, &o_t);
4471 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4474 /* make this exactly 1 or 0 */
4480 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4481 /* loop for more e*/
4484 if (goi->isconfigure) {
4485 e = Jim_GetOpt_Wide(goi, &w);
4488 target->dbgbase = (uint32_t)w;
4489 target->dbgbase_set = true;
4494 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4501 int result = rtos_create(goi, target);
4502 if (result != JIM_OK)
4508 } /* while (goi->argc) */
4511 /* done - we return */
4515 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4519 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4520 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4521 int need_args = 1 + goi.isconfigure;
4522 if (goi.argc < need_args) {
4523 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4525 ? "missing: -option VALUE ..."
4526 : "missing: -option ...");
4529 struct target *target = Jim_CmdPrivData(goi.interp);
4530 return target_configure(&goi, target);
4533 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4535 const char *cmd_name = Jim_GetString(argv[0], NULL);
4538 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4540 if (goi.argc < 2 || goi.argc > 4) {
4541 Jim_SetResultFormatted(goi.interp,
4542 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4547 fn = target_write_memory;
4550 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4552 struct Jim_Obj *obj;
4553 e = Jim_GetOpt_Obj(&goi, &obj);
4557 fn = target_write_phys_memory;
4561 e = Jim_GetOpt_Wide(&goi, &a);
4566 e = Jim_GetOpt_Wide(&goi, &b);
4571 if (goi.argc == 1) {
4572 e = Jim_GetOpt_Wide(&goi, &c);
4577 /* all args must be consumed */
4581 struct target *target = Jim_CmdPrivData(goi.interp);
4583 if (strcasecmp(cmd_name, "mww") == 0)
4585 else if (strcasecmp(cmd_name, "mwh") == 0)
4587 else if (strcasecmp(cmd_name, "mwb") == 0)
4590 LOG_ERROR("command '%s' unknown: ", cmd_name);
4594 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4598 * @brief Reads an array of words/halfwords/bytes from target memory starting at specified address.
4600 * Usage: mdw [phys] <address> [<count>] - for 32 bit reads
4601 * mdh [phys] <address> [<count>] - for 16 bit reads
4602 * mdb [phys] <address> [<count>] - for 8 bit reads
4604 * Count defaults to 1.
4606 * Calls target_read_memory or target_read_phys_memory depending on
4607 * the presence of the "phys" argument
4608 * Reads the target memory in blocks of max. 32 bytes, and returns an array of ints formatted
4609 * to int representation in base16.
4610 * Also outputs read data in a human readable form using command_print
4612 * @param phys if present target_read_phys_memory will be used instead of target_read_memory
4613 * @param address address where to start the read. May be specified in decimal or hex using the standard "0x" prefix
4614 * @param count optional count parameter to read an array of values. If not specified, defaults to 1.
4615 * @returns: JIM_ERR on error or JIM_OK on success and sets the result string to an array of ascii formatted numbers
4616 * on success, with [<count>] number of elements.
4618 * In case of little endian target:
4619 * Example1: "mdw 0x00000000" returns "10123456"
4620 * Exmaple2: "mdh 0x00000000 1" returns "3456"
4621 * Example3: "mdb 0x00000000" returns "56"
4622 * Example4: "mdh 0x00000000 2" returns "3456 1012"
4623 * Example5: "mdb 0x00000000 3" returns "56 34 12"
4625 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4627 const char *cmd_name = Jim_GetString(argv[0], NULL);
4630 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4632 if ((goi.argc < 1) || (goi.argc > 3)) {
4633 Jim_SetResultFormatted(goi.interp,
4634 "usage: %s [phys] <address> [<count>]", cmd_name);
4638 int (*fn)(struct target *target,
4639 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4640 fn = target_read_memory;
4643 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4645 struct Jim_Obj *obj;
4646 e = Jim_GetOpt_Obj(&goi, &obj);
4650 fn = target_read_phys_memory;
4653 /* Read address parameter */
4655 e = Jim_GetOpt_Wide(&goi, &addr);
4659 /* If next parameter exists, read it out as the count parameter, if not, set it to 1 (default) */
4661 if (goi.argc == 1) {
4662 e = Jim_GetOpt_Wide(&goi, &count);
4668 /* all args must be consumed */
4672 jim_wide dwidth = 1; /* shut up gcc */
4673 if (strcasecmp(cmd_name, "mdw") == 0)
4675 else if (strcasecmp(cmd_name, "mdh") == 0)
4677 else if (strcasecmp(cmd_name, "mdb") == 0)
4680 LOG_ERROR("command '%s' unknown: ", cmd_name);
4684 /* convert count to "bytes" */
4685 int bytes = count * dwidth;
4687 struct target *target = Jim_CmdPrivData(goi.interp);
4688 uint8_t target_buf[32];
4691 y = (bytes < 16) ? bytes : 16; /* y = min(bytes, 16); */
4693 /* Try to read out next block */
4694 e = fn(target, addr, dwidth, y / dwidth, target_buf);
4696 if (e != ERROR_OK) {
4697 Jim_SetResultFormatted(interp, "error reading target @ 0x%08lx", (long)addr);
4701 command_print_sameline(NULL, "0x%08x ", (int)(addr));
4704 for (x = 0; x < 16 && x < y; x += 4) {
4705 z = target_buffer_get_u32(target, &(target_buf[x]));
4706 command_print_sameline(NULL, "%08x ", (int)(z));
4708 for (; (x < 16) ; x += 4)
4709 command_print_sameline(NULL, " ");
4712 for (x = 0; x < 16 && x < y; x += 2) {
4713 z = target_buffer_get_u16(target, &(target_buf[x]));
4714 command_print_sameline(NULL, "%04x ", (int)(z));
4716 for (; (x < 16) ; x += 2)
4717 command_print_sameline(NULL, " ");
4721 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4722 z = target_buffer_get_u8(target, &(target_buf[x]));
4723 command_print_sameline(NULL, "%02x ", (int)(z));
4725 for (; (x < 16) ; x += 1)
4726 command_print_sameline(NULL, " ");
4729 /* ascii-ify the bytes */
4730 for (x = 0 ; x < y ; x++) {
4731 if ((target_buf[x] >= 0x20) &&
4732 (target_buf[x] <= 0x7e)) {
4736 target_buf[x] = '.';
4741 target_buf[x] = ' ';
4746 /* print - with a newline */
4747 command_print_sameline(NULL, "%s\n", target_buf);
4755 static int jim_target_mem2array(Jim_Interp *interp,
4756 int argc, Jim_Obj *const *argv)
4758 struct target *target = Jim_CmdPrivData(interp);
4759 return target_mem2array(interp, target, argc - 1, argv + 1);
4762 static int jim_target_array2mem(Jim_Interp *interp,
4763 int argc, Jim_Obj *const *argv)
4765 struct target *target = Jim_CmdPrivData(interp);
4766 return target_array2mem(interp, target, argc - 1, argv + 1);
4769 static int jim_target_tap_disabled(Jim_Interp *interp)
4771 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4775 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4778 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4781 struct target *target = Jim_CmdPrivData(interp);
4782 if (!target->tap->enabled)
4783 return jim_target_tap_disabled(interp);
4785 int e = target->type->examine(target);
4791 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4794 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4797 struct target *target = Jim_CmdPrivData(interp);
4799 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4805 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4808 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4811 struct target *target = Jim_CmdPrivData(interp);
4812 if (!target->tap->enabled)
4813 return jim_target_tap_disabled(interp);
4816 if (!(target_was_examined(target)))
4817 e = ERROR_TARGET_NOT_EXAMINED;
4819 e = target->type->poll(target);
4825 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4828 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4830 if (goi.argc != 2) {
4831 Jim_WrongNumArgs(interp, 0, argv,
4832 "([tT]|[fF]|assert|deassert) BOOL");
4837 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4839 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4842 /* the halt or not param */
4844 e = Jim_GetOpt_Wide(&goi, &a);
4848 struct target *target = Jim_CmdPrivData(goi.interp);
4849 if (!target->tap->enabled)
4850 return jim_target_tap_disabled(interp);
4851 if (!(target_was_examined(target))) {
4852 LOG_ERROR("Target not examined yet");
4853 return ERROR_TARGET_NOT_EXAMINED;
4855 if (!target->type->assert_reset || !target->type->deassert_reset) {
4856 Jim_SetResultFormatted(interp,
4857 "No target-specific reset for %s",
4858 target_name(target));
4861 /* determine if we should halt or not. */
4862 target->reset_halt = !!a;
4863 /* When this happens - all workareas are invalid. */
4864 target_free_all_working_areas_restore(target, 0);
4867 if (n->value == NVP_ASSERT)
4868 e = target->type->assert_reset(target);
4870 e = target->type->deassert_reset(target);
4871 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4874 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4877 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4880 struct target *target = Jim_CmdPrivData(interp);
4881 if (!target->tap->enabled)
4882 return jim_target_tap_disabled(interp);
4883 int e = target->type->halt(target);
4884 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4887 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4890 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4892 /* params: <name> statename timeoutmsecs */
4893 if (goi.argc != 2) {
4894 const char *cmd_name = Jim_GetString(argv[0], NULL);
4895 Jim_SetResultFormatted(goi.interp,
4896 "%s <state_name> <timeout_in_msec>", cmd_name);
4901 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4903 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
4907 e = Jim_GetOpt_Wide(&goi, &a);
4910 struct target *target = Jim_CmdPrivData(interp);
4911 if (!target->tap->enabled)
4912 return jim_target_tap_disabled(interp);
4914 e = target_wait_state(target, n->value, a);
4915 if (e != ERROR_OK) {
4916 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4917 Jim_SetResultFormatted(goi.interp,
4918 "target: %s wait %s fails (%#s) %s",
4919 target_name(target), n->name,
4920 eObj, target_strerror_safe(e));
4921 Jim_FreeNewObj(interp, eObj);
4926 /* List for human, Events defined for this target.
4927 * scripts/programs should use 'name cget -event NAME'
4929 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4931 struct command_context *cmd_ctx = current_command_context(interp);
4932 assert(cmd_ctx != NULL);
4934 struct target *target = Jim_CmdPrivData(interp);
4935 struct target_event_action *teap = target->event_action;
4936 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4937 target->target_number,
4938 target_name(target));
4939 command_print(cmd_ctx, "%-25s | Body", "Event");
4940 command_print(cmd_ctx, "------------------------- | "
4941 "----------------------------------------");
4943 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4944 command_print(cmd_ctx, "%-25s | %s",
4945 opt->name, Jim_GetString(teap->body, NULL));
4948 command_print(cmd_ctx, "***END***");
4951 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4954 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4957 struct target *target = Jim_CmdPrivData(interp);
4958 Jim_SetResultString(interp, target_state_name(target), -1);
4961 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4964 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4965 if (goi.argc != 1) {
4966 const char *cmd_name = Jim_GetString(argv[0], NULL);
4967 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4971 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4973 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4976 struct target *target = Jim_CmdPrivData(interp);
4977 target_handle_event(target, n->value);
4981 static const struct command_registration target_instance_command_handlers[] = {
4983 .name = "configure",
4984 .mode = COMMAND_CONFIG,
4985 .jim_handler = jim_target_configure,
4986 .help = "configure a new target for use",
4987 .usage = "[target_attribute ...]",
4991 .mode = COMMAND_ANY,
4992 .jim_handler = jim_target_configure,
4993 .help = "returns the specified target attribute",
4994 .usage = "target_attribute",
4998 .mode = COMMAND_EXEC,
4999 .jim_handler = jim_target_mw,
5000 .help = "Write 32-bit word(s) to target memory",
5001 .usage = "address data [count]",
5005 .mode = COMMAND_EXEC,
5006 .jim_handler = jim_target_mw,
5007 .help = "Write 16-bit half-word(s) to target memory",
5008 .usage = "address data [count]",
5012 .mode = COMMAND_EXEC,
5013 .jim_handler = jim_target_mw,
5014 .help = "Write byte(s) to target memory",
5015 .usage = "address data [count]",
5019 .mode = COMMAND_EXEC,
5020 .jim_handler = jim_target_md,
5021 .help = "Display target memory as 32-bit words",
5022 .usage = "address [count]",
5026 .mode = COMMAND_EXEC,
5027 .jim_handler = jim_target_md,
5028 .help = "Display target memory as 16-bit half-words",
5029 .usage = "address [count]",
5033 .mode = COMMAND_EXEC,
5034 .jim_handler = jim_target_md,
5035 .help = "Display target memory as 8-bit bytes",
5036 .usage = "address [count]",
5039 .name = "array2mem",
5040 .mode = COMMAND_EXEC,
5041 .jim_handler = jim_target_array2mem,
5042 .help = "Writes Tcl array of 8/16/32 bit numbers "
5044 .usage = "arrayname bitwidth address count",
5047 .name = "mem2array",
5048 .mode = COMMAND_EXEC,
5049 .jim_handler = jim_target_mem2array,
5050 .help = "Loads Tcl array of 8/16/32 bit numbers "
5051 "from target memory",
5052 .usage = "arrayname bitwidth address count",
5055 .name = "eventlist",
5056 .mode = COMMAND_EXEC,
5057 .jim_handler = jim_target_event_list,
5058 .help = "displays a table of events defined for this target",
5062 .mode = COMMAND_EXEC,
5063 .jim_handler = jim_target_current_state,
5064 .help = "displays the current state of this target",
5067 .name = "arp_examine",
5068 .mode = COMMAND_EXEC,
5069 .jim_handler = jim_target_examine,
5070 .help = "used internally for reset processing",
5073 .name = "arp_halt_gdb",
5074 .mode = COMMAND_EXEC,
5075 .jim_handler = jim_target_halt_gdb,
5076 .help = "used internally for reset processing to halt GDB",
5080 .mode = COMMAND_EXEC,
5081 .jim_handler = jim_target_poll,
5082 .help = "used internally for reset processing",
5085 .name = "arp_reset",
5086 .mode = COMMAND_EXEC,
5087 .jim_handler = jim_target_reset,
5088 .help = "used internally for reset processing",
5092 .mode = COMMAND_EXEC,
5093 .jim_handler = jim_target_halt,
5094 .help = "used internally for reset processing",
5097 .name = "arp_waitstate",
5098 .mode = COMMAND_EXEC,
5099 .jim_handler = jim_target_wait_state,
5100 .help = "used internally for reset processing",
5103 .name = "invoke-event",
5104 .mode = COMMAND_EXEC,
5105 .jim_handler = jim_target_invoke_event,
5106 .help = "invoke handler for specified event",
5107 .usage = "event_name",
5109 COMMAND_REGISTRATION_DONE
5112 static int target_create(Jim_GetOptInfo *goi)
5120 struct target *target;
5121 struct command_context *cmd_ctx;
5123 cmd_ctx = current_command_context(goi->interp);
5124 assert(cmd_ctx != NULL);
5126 if (goi->argc < 3) {
5127 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5132 Jim_GetOpt_Obj(goi, &new_cmd);
5133 /* does this command exist? */
5134 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
5136 cp = Jim_GetString(new_cmd, NULL);
5137 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5142 e = Jim_GetOpt_String(goi, &cp2, NULL);
5146 struct transport *tr = get_current_transport();
5147 if (tr->override_target) {
5148 e = tr->override_target(&cp);
5149 if (e != ERROR_OK) {
5150 LOG_ERROR("The selected transport doesn't support this target");
5153 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5155 /* now does target type exist */
5156 for (x = 0 ; target_types[x] ; x++) {
5157 if (0 == strcmp(cp, target_types[x]->name)) {
5162 /* check for deprecated name */
5163 if (target_types[x]->deprecated_name) {
5164 if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
5166 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
5171 if (target_types[x] == NULL) {
5172 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5173 for (x = 0 ; target_types[x] ; x++) {
5174 if (target_types[x + 1]) {
5175 Jim_AppendStrings(goi->interp,
5176 Jim_GetResult(goi->interp),
5177 target_types[x]->name,
5180 Jim_AppendStrings(goi->interp,
5181 Jim_GetResult(goi->interp),
5183 target_types[x]->name, NULL);
5190 target = calloc(1, sizeof(struct target));
5191 /* set target number */
5192 target->target_number = new_target_number();
5193 cmd_ctx->current_target = target->target_number;
5195 /* allocate memory for each unique target type */
5196 target->type = calloc(1, sizeof(struct target_type));
5198 memcpy(target->type, target_types[x], sizeof(struct target_type));
5200 /* will be set by "-endian" */
5201 target->endianness = TARGET_ENDIAN_UNKNOWN;
5203 /* default to first core, override with -coreid */
5206 target->working_area = 0x0;
5207 target->working_area_size = 0x0;
5208 target->working_areas = NULL;
5209 target->backup_working_area = 0;
5211 target->state = TARGET_UNKNOWN;
5212 target->debug_reason = DBG_REASON_UNDEFINED;
5213 target->reg_cache = NULL;
5214 target->breakpoints = NULL;
5215 target->watchpoints = NULL;
5216 target->next = NULL;
5217 target->arch_info = NULL;
5219 target->display = 1;
5221 target->halt_issued = false;
5223 /* initialize trace information */
5224 target->trace_info = malloc(sizeof(struct trace));
5225 target->trace_info->num_trace_points = 0;
5226 target->trace_info->trace_points_size = 0;
5227 target->trace_info->trace_points = NULL;
5228 target->trace_info->trace_history_size = 0;
5229 target->trace_info->trace_history = NULL;
5230 target->trace_info->trace_history_pos = 0;
5231 target->trace_info->trace_history_overflowed = 0;
5233 target->dbgmsg = NULL;
5234 target->dbg_msg_enabled = 0;
5236 target->endianness = TARGET_ENDIAN_UNKNOWN;
5238 target->rtos = NULL;
5239 target->rtos_auto_detect = false;
5241 /* Do the rest as "configure" options */
5242 goi->isconfigure = 1;
5243 e = target_configure(goi, target);
5245 if (target->tap == NULL) {
5246 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
5256 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5257 /* default endian to little if not specified */
5258 target->endianness = TARGET_LITTLE_ENDIAN;
5261 cp = Jim_GetString(new_cmd, NULL);
5262 target->cmd_name = strdup(cp);
5264 /* create the target specific commands */
5265 if (target->type->commands) {
5266 e = register_commands(cmd_ctx, NULL, target->type->commands);
5268 LOG_ERROR("unable to register '%s' commands", cp);
5270 if (target->type->target_create)
5271 (*(target->type->target_create))(target, goi->interp);
5273 /* append to end of list */
5275 struct target **tpp;
5276 tpp = &(all_targets);
5278 tpp = &((*tpp)->next);
5282 /* now - create the new target name command */
5283 const struct command_registration target_subcommands[] = {
5285 .chain = target_instance_command_handlers,
5288 .chain = target->type->commands,
5290 COMMAND_REGISTRATION_DONE
5292 const struct command_registration target_commands[] = {
5295 .mode = COMMAND_ANY,
5296 .help = "target command group",
5298 .chain = target_subcommands,
5300 COMMAND_REGISTRATION_DONE
5302 e = register_commands(cmd_ctx, NULL, target_commands);
5306 struct command *c = command_find_in_context(cmd_ctx, cp);
5308 command_set_handler_data(c, target);
5310 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5313 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5316 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5319 struct command_context *cmd_ctx = current_command_context(interp);
5320 assert(cmd_ctx != NULL);
5322 Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5326 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5329 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5332 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5333 for (unsigned x = 0; NULL != target_types[x]; x++) {
5334 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5335 Jim_NewStringObj(interp, target_types[x]->name, -1));
5340 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5343 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5346 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5347 struct target *target = all_targets;
5349 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5350 Jim_NewStringObj(interp, target_name(target), -1));
5351 target = target->next;
5356 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5359 const char *targetname;
5361 struct target *target = (struct target *) NULL;
5362 struct target_list *head, *curr, *new;
5363 curr = (struct target_list *) NULL;
5364 head = (struct target_list *) NULL;
5367 LOG_DEBUG("%d", argc);
5368 /* argv[1] = target to associate in smp
5369 * argv[2] = target to assoicate in smp
5373 for (i = 1; i < argc; i++) {
5375 targetname = Jim_GetString(argv[i], &len);
5376 target = get_target(targetname);
5377 LOG_DEBUG("%s ", targetname);
5379 new = malloc(sizeof(struct target_list));
5380 new->target = target;
5381 new->next = (struct target_list *)NULL;
5382 if (head == (struct target_list *)NULL) {
5391 /* now parse the list of cpu and put the target in smp mode*/
5394 while (curr != (struct target_list *)NULL) {
5395 target = curr->target;
5397 target->head = head;
5401 if (target && target->rtos)
5402 retval = rtos_smp_init(head->target);
5408 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5411 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5413 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5414 "<name> <target_type> [<target_options> ...]");
5417 return target_create(&goi);
5420 static const struct command_registration target_subcommand_handlers[] = {
5423 .mode = COMMAND_CONFIG,
5424 .handler = handle_target_init_command,
5425 .help = "initialize targets",
5429 /* REVISIT this should be COMMAND_CONFIG ... */
5430 .mode = COMMAND_ANY,
5431 .jim_handler = jim_target_create,
5432 .usage = "name type '-chain-position' name [options ...]",
5433 .help = "Creates and selects a new target",
5437 .mode = COMMAND_ANY,
5438 .jim_handler = jim_target_current,
5439 .help = "Returns the currently selected target",
5443 .mode = COMMAND_ANY,
5444 .jim_handler = jim_target_types,
5445 .help = "Returns the available target types as "
5446 "a list of strings",
5450 .mode = COMMAND_ANY,
5451 .jim_handler = jim_target_names,
5452 .help = "Returns the names of all targets as a list of strings",
5456 .mode = COMMAND_ANY,
5457 .jim_handler = jim_target_smp,
5458 .usage = "targetname1 targetname2 ...",
5459 .help = "gather several target in a smp list"
5462 COMMAND_REGISTRATION_DONE
5472 static int fastload_num;
5473 static struct FastLoad *fastload;
5475 static void free_fastload(void)
5477 if (fastload != NULL) {
5479 for (i = 0; i < fastload_num; i++) {
5480 if (fastload[i].data)
5481 free(fastload[i].data);
5488 COMMAND_HANDLER(handle_fast_load_image_command)
5492 uint32_t image_size;
5493 uint32_t min_address = 0;
5494 uint32_t max_address = 0xffffffff;
5499 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5500 &image, &min_address, &max_address);
5501 if (ERROR_OK != retval)
5504 struct duration bench;
5505 duration_start(&bench);
5507 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5508 if (retval != ERROR_OK)
5513 fastload_num = image.num_sections;
5514 fastload = malloc(sizeof(struct FastLoad)*image.num_sections);
5515 if (fastload == NULL) {
5516 command_print(CMD_CTX, "out of memory");
5517 image_close(&image);
5520 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5521 for (i = 0; i < image.num_sections; i++) {
5522 buffer = malloc(image.sections[i].size);
5523 if (buffer == NULL) {
5524 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5525 (int)(image.sections[i].size));
5526 retval = ERROR_FAIL;
5530 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5531 if (retval != ERROR_OK) {
5536 uint32_t offset = 0;
5537 uint32_t length = buf_cnt;
5539 /* DANGER!!! beware of unsigned comparision here!!! */
5541 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5542 (image.sections[i].base_address < max_address)) {
5543 if (image.sections[i].base_address < min_address) {
5544 /* clip addresses below */
5545 offset += min_address-image.sections[i].base_address;
5549 if (image.sections[i].base_address + buf_cnt > max_address)
5550 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5552 fastload[i].address = image.sections[i].base_address + offset;
5553 fastload[i].data = malloc(length);
5554 if (fastload[i].data == NULL) {
5556 command_print(CMD_CTX, "error allocating buffer for section (%" PRIu32 " bytes)",
5558 retval = ERROR_FAIL;
5561 memcpy(fastload[i].data, buffer + offset, length);
5562 fastload[i].length = length;
5564 image_size += length;
5565 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5566 (unsigned int)length,
5567 ((unsigned int)(image.sections[i].base_address + offset)));
5573 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5574 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5575 "in %fs (%0.3f KiB/s)", image_size,
5576 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5578 command_print(CMD_CTX,
5579 "WARNING: image has not been loaded to target!"
5580 "You can issue a 'fast_load' to finish loading.");
5583 image_close(&image);
5585 if (retval != ERROR_OK)
5591 COMMAND_HANDLER(handle_fast_load_command)
5594 return ERROR_COMMAND_SYNTAX_ERROR;
5595 if (fastload == NULL) {
5596 LOG_ERROR("No image in memory");
5600 int ms = timeval_ms();
5602 int retval = ERROR_OK;
5603 for (i = 0; i < fastload_num; i++) {
5604 struct target *target = get_current_target(CMD_CTX);
5605 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5606 (unsigned int)(fastload[i].address),
5607 (unsigned int)(fastload[i].length));
5608 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5609 if (retval != ERROR_OK)
5611 size += fastload[i].length;
5613 if (retval == ERROR_OK) {
5614 int after = timeval_ms();
5615 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5620 static const struct command_registration target_command_handlers[] = {
5623 .handler = handle_targets_command,
5624 .mode = COMMAND_ANY,
5625 .help = "change current default target (one parameter) "
5626 "or prints table of all targets (no parameters)",
5627 .usage = "[target]",
5631 .mode = COMMAND_CONFIG,
5632 .help = "configure target",
5634 .chain = target_subcommand_handlers,
5636 COMMAND_REGISTRATION_DONE
5639 int target_register_commands(struct command_context *cmd_ctx)
5641 return register_commands(cmd_ctx, NULL, target_command_handlers);
5644 static bool target_reset_nag = true;
5646 bool get_target_reset_nag(void)
5648 return target_reset_nag;
5651 COMMAND_HANDLER(handle_target_reset_nag)
5653 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5654 &target_reset_nag, "Nag after each reset about options to improve "
5658 COMMAND_HANDLER(handle_ps_command)
5660 struct target *target = get_current_target(CMD_CTX);
5662 if (target->state != TARGET_HALTED) {
5663 LOG_INFO("target not halted !!");
5667 if ((target->rtos) && (target->rtos->type)
5668 && (target->rtos->type->ps_command)) {
5669 display = target->rtos->type->ps_command(target);
5670 command_print(CMD_CTX, "%s", display);
5675 return ERROR_TARGET_FAILURE;
5679 static void binprint(struct command_context *cmd_ctx, const char *text, const uint8_t *buf, int size)
5682 command_print_sameline(cmd_ctx, "%s", text);
5683 for (int i = 0; i < size; i++)
5684 command_print_sameline(cmd_ctx, " %02x", buf[i]);
5685 command_print(cmd_ctx, " ");
5688 COMMAND_HANDLER(handle_test_mem_access_command)
5690 struct target *target = get_current_target(CMD_CTX);
5692 int retval = ERROR_OK;
5694 if (target->state != TARGET_HALTED) {
5695 LOG_INFO("target not halted !!");
5700 return ERROR_COMMAND_SYNTAX_ERROR;
5702 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
5705 size_t num_bytes = test_size + 4;
5707 struct working_area *wa = NULL;
5708 retval = target_alloc_working_area(target, num_bytes, &wa);
5709 if (retval != ERROR_OK) {
5710 LOG_ERROR("Not enough working area");
5714 uint8_t *test_pattern = malloc(num_bytes);
5716 for (size_t i = 0; i < num_bytes; i++)
5717 test_pattern[i] = rand();
5719 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
5720 if (retval != ERROR_OK) {
5721 LOG_ERROR("Test pattern write failed");
5725 for (int host_offset = 0; host_offset <= 1; host_offset++) {
5726 for (int size = 1; size <= 4; size *= 2) {
5727 for (int offset = 0; offset < 4; offset++) {
5728 uint32_t count = test_size / size;
5729 size_t host_bufsiz = (count + 2) * size + host_offset;
5730 uint8_t *read_ref = malloc(host_bufsiz);
5731 uint8_t *read_buf = malloc(host_bufsiz);
5733 for (size_t i = 0; i < host_bufsiz; i++) {
5734 read_ref[i] = rand();
5735 read_buf[i] = read_ref[i];
5737 command_print_sameline(CMD_CTX,
5738 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
5739 size, offset, host_offset ? "un" : "");
5741 struct duration bench;
5742 duration_start(&bench);
5744 retval = target_read_memory(target, wa->address + offset, size, count,
5745 read_buf + size + host_offset);
5747 duration_measure(&bench);
5749 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
5750 command_print(CMD_CTX, "Unsupported alignment");
5752 } else if (retval != ERROR_OK) {
5753 command_print(CMD_CTX, "Memory read failed");
5757 /* replay on host */
5758 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
5761 int result = memcmp(read_ref, read_buf, host_bufsiz);
5763 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
5764 duration_elapsed(&bench),
5765 duration_kbps(&bench, count * size));
5767 command_print(CMD_CTX, "Compare failed");
5768 binprint(CMD_CTX, "ref:", read_ref, host_bufsiz);
5769 binprint(CMD_CTX, "buf:", read_buf, host_bufsiz);
5782 target_free_working_area(target, wa);
5785 num_bytes = test_size + 4 + 4 + 4;
5787 retval = target_alloc_working_area(target, num_bytes, &wa);
5788 if (retval != ERROR_OK) {
5789 LOG_ERROR("Not enough working area");
5793 test_pattern = malloc(num_bytes);
5795 for (size_t i = 0; i < num_bytes; i++)
5796 test_pattern[i] = rand();
5798 for (int host_offset = 0; host_offset <= 1; host_offset++) {
5799 for (int size = 1; size <= 4; size *= 2) {
5800 for (int offset = 0; offset < 4; offset++) {
5801 uint32_t count = test_size / size;
5802 size_t host_bufsiz = count * size + host_offset;
5803 uint8_t *read_ref = malloc(num_bytes);
5804 uint8_t *read_buf = malloc(num_bytes);
5805 uint8_t *write_buf = malloc(host_bufsiz);
5807 for (size_t i = 0; i < host_bufsiz; i++)
5808 write_buf[i] = rand();
5809 command_print_sameline(CMD_CTX,
5810 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
5811 size, offset, host_offset ? "un" : "");
5813 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
5814 if (retval != ERROR_OK) {
5815 command_print(CMD_CTX, "Test pattern write failed");
5819 /* replay on host */
5820 memcpy(read_ref, test_pattern, num_bytes);
5821 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
5823 struct duration bench;
5824 duration_start(&bench);
5826 retval = target_write_memory(target, wa->address + size + offset, size, count,
5827 write_buf + host_offset);
5829 duration_measure(&bench);
5831 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
5832 command_print(CMD_CTX, "Unsupported alignment");
5834 } else if (retval != ERROR_OK) {
5835 command_print(CMD_CTX, "Memory write failed");
5840 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
5841 if (retval != ERROR_OK) {
5842 command_print(CMD_CTX, "Test pattern write failed");
5847 int result = memcmp(read_ref, read_buf, num_bytes);
5849 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
5850 duration_elapsed(&bench),
5851 duration_kbps(&bench, count * size));
5853 command_print(CMD_CTX, "Compare failed");
5854 binprint(CMD_CTX, "ref:", read_ref, num_bytes);
5855 binprint(CMD_CTX, "buf:", read_buf, num_bytes);
5867 target_free_working_area(target, wa);
5871 static const struct command_registration target_exec_command_handlers[] = {
5873 .name = "fast_load_image",
5874 .handler = handle_fast_load_image_command,
5875 .mode = COMMAND_ANY,
5876 .help = "Load image into server memory for later use by "
5877 "fast_load; primarily for profiling",
5878 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5879 "[min_address [max_length]]",
5882 .name = "fast_load",
5883 .handler = handle_fast_load_command,
5884 .mode = COMMAND_EXEC,
5885 .help = "loads active fast load image to current target "
5886 "- mainly for profiling purposes",
5891 .handler = handle_profile_command,
5892 .mode = COMMAND_EXEC,
5893 .usage = "seconds filename [start end]",
5894 .help = "profiling samples the CPU PC",
5896 /** @todo don't register virt2phys() unless target supports it */
5898 .name = "virt2phys",
5899 .handler = handle_virt2phys_command,
5900 .mode = COMMAND_ANY,
5901 .help = "translate a virtual address into a physical address",
5902 .usage = "virtual_address",
5906 .handler = handle_reg_command,
5907 .mode = COMMAND_EXEC,
5908 .help = "display (reread from target with \"force\") or set a register; "
5909 "with no arguments, displays all registers and their values",
5910 .usage = "[(register_number|register_name) [(value|'force')]]",
5914 .handler = handle_poll_command,
5915 .mode = COMMAND_EXEC,
5916 .help = "poll target state; or reconfigure background polling",
5917 .usage = "['on'|'off']",
5920 .name = "wait_halt",
5921 .handler = handle_wait_halt_command,
5922 .mode = COMMAND_EXEC,
5923 .help = "wait up to the specified number of milliseconds "
5924 "(default 5000) for a previously requested halt",
5925 .usage = "[milliseconds]",
5929 .handler = handle_halt_command,
5930 .mode = COMMAND_EXEC,
5931 .help = "request target to halt, then wait up to the specified"
5932 "number of milliseconds (default 5000) for it to complete",
5933 .usage = "[milliseconds]",
5937 .handler = handle_resume_command,
5938 .mode = COMMAND_EXEC,
5939 .help = "resume target execution from current PC or address",
5940 .usage = "[address]",
5944 .handler = handle_reset_command,
5945 .mode = COMMAND_EXEC,
5946 .usage = "[run|halt|init]",
5947 .help = "Reset all targets into the specified mode."
5948 "Default reset mode is run, if not given.",
5951 .name = "soft_reset_halt",
5952 .handler = handle_soft_reset_halt_command,
5953 .mode = COMMAND_EXEC,
5955 .help = "halt the target and do a soft reset",
5959 .handler = handle_step_command,
5960 .mode = COMMAND_EXEC,
5961 .help = "step one instruction from current PC or address",
5962 .usage = "[address]",
5966 .handler = handle_md_command,
5967 .mode = COMMAND_EXEC,
5968 .help = "display memory words",
5969 .usage = "['phys'] address [count]",
5973 .handler = handle_md_command,
5974 .mode = COMMAND_EXEC,
5975 .help = "display memory half-words",
5976 .usage = "['phys'] address [count]",
5980 .handler = handle_md_command,
5981 .mode = COMMAND_EXEC,
5982 .help = "display memory bytes",
5983 .usage = "['phys'] address [count]",
5987 .handler = handle_mw_command,
5988 .mode = COMMAND_EXEC,
5989 .help = "write memory word",
5990 .usage = "['phys'] address value [count]",
5994 .handler = handle_mw_command,
5995 .mode = COMMAND_EXEC,
5996 .help = "write memory half-word",
5997 .usage = "['phys'] address value [count]",
6001 .handler = handle_mw_command,
6002 .mode = COMMAND_EXEC,
6003 .help = "write memory byte",
6004 .usage = "['phys'] address value [count]",
6008 .handler = handle_bp_command,
6009 .mode = COMMAND_EXEC,
6010 .help = "list or set hardware or software breakpoint",
6011 .usage = "<address> [<asid>]<length> ['hw'|'hw_ctx']",
6015 .handler = handle_rbp_command,
6016 .mode = COMMAND_EXEC,
6017 .help = "remove breakpoint",
6022 .handler = handle_wp_command,
6023 .mode = COMMAND_EXEC,
6024 .help = "list (no params) or create watchpoints",
6025 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
6029 .handler = handle_rwp_command,
6030 .mode = COMMAND_EXEC,
6031 .help = "remove watchpoint",
6035 .name = "load_image",
6036 .handler = handle_load_image_command,
6037 .mode = COMMAND_EXEC,
6038 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6039 "[min_address] [max_length]",
6042 .name = "dump_image",
6043 .handler = handle_dump_image_command,
6044 .mode = COMMAND_EXEC,
6045 .usage = "filename address size",
6048 .name = "verify_image",
6049 .handler = handle_verify_image_command,
6050 .mode = COMMAND_EXEC,
6051 .usage = "filename [offset [type]]",
6054 .name = "test_image",
6055 .handler = handle_test_image_command,
6056 .mode = COMMAND_EXEC,
6057 .usage = "filename [offset [type]]",
6060 .name = "mem2array",
6061 .mode = COMMAND_EXEC,
6062 .jim_handler = jim_mem2array,
6063 .help = "read 8/16/32 bit memory and return as a TCL array "
6064 "for script processing",
6065 .usage = "arrayname bitwidth address count",
6068 .name = "array2mem",
6069 .mode = COMMAND_EXEC,
6070 .jim_handler = jim_array2mem,
6071 .help = "convert a TCL array to memory locations "
6072 "and write the 8/16/32 bit values",
6073 .usage = "arrayname bitwidth address count",
6076 .name = "reset_nag",
6077 .handler = handle_target_reset_nag,
6078 .mode = COMMAND_ANY,
6079 .help = "Nag after each reset about options that could have been "
6080 "enabled to improve performance. ",
6081 .usage = "['enable'|'disable']",
6085 .handler = handle_ps_command,
6086 .mode = COMMAND_EXEC,
6087 .help = "list all tasks ",
6091 .name = "test_mem_access",
6092 .handler = handle_test_mem_access_command,
6093 .mode = COMMAND_EXEC,
6094 .help = "Test the target's memory access functions",
6098 COMMAND_REGISTRATION_DONE
6100 static int target_register_user_commands(struct command_context *cmd_ctx)
6102 int retval = ERROR_OK;
6103 retval = target_request_register_commands(cmd_ctx);
6104 if (retval != ERROR_OK)
6107 retval = trace_register_commands(cmd_ctx);
6108 if (retval != ERROR_OK)
6112 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);