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 void target_quit(void)
1805 struct target_event_callback *pe = target_event_callbacks;
1807 struct target_event_callback *t = pe->next;
1811 target_event_callbacks = NULL;
1813 struct target_timer_callback *pt = target_timer_callbacks;
1815 struct target_timer_callback *t = pt->next;
1819 target_timer_callbacks = NULL;
1821 for (struct target *target = all_targets;
1822 target; target = target->next) {
1823 if (target->type->deinit_target)
1824 target->type->deinit_target(target);
1828 /* free resources and restore memory, if restoring memory fails,
1829 * free up resources anyway
1831 static void target_free_all_working_areas_restore(struct target *target, int restore)
1833 struct working_area *c = target->working_areas;
1835 LOG_DEBUG("freeing all working areas");
1837 /* Loop through all areas, restoring the allocated ones and marking them as free */
1841 target_restore_working_area(target, c);
1843 *c->user = NULL; /* Same as above */
1849 /* Run a merge pass to combine all areas into one */
1850 target_merge_working_areas(target);
1852 print_wa_layout(target);
1855 void target_free_all_working_areas(struct target *target)
1857 target_free_all_working_areas_restore(target, 1);
1860 /* Find the largest number of bytes that can be allocated */
1861 uint32_t target_get_working_area_avail(struct target *target)
1863 struct working_area *c = target->working_areas;
1864 uint32_t max_size = 0;
1867 return target->working_area_size;
1870 if (c->free && max_size < c->size)
1879 int target_arch_state(struct target *target)
1882 if (target == NULL) {
1883 LOG_USER("No target has been configured");
1887 LOG_USER("target state: %s", target_state_name(target));
1889 if (target->state != TARGET_HALTED)
1892 retval = target->type->arch_state(target);
1896 static int target_get_gdb_fileio_info_default(struct target *target,
1897 struct gdb_fileio_info *fileio_info)
1899 /* If target does not support semi-hosting function, target
1900 has no need to provide .get_gdb_fileio_info callback.
1901 It just return ERROR_FAIL and gdb_server will return "Txx"
1902 as target halted every time. */
1906 static int target_gdb_fileio_end_default(struct target *target,
1907 int retcode, int fileio_errno, bool ctrl_c)
1912 static int target_profiling_default(struct target *target, uint32_t *samples,
1913 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1915 struct timeval timeout, now;
1917 gettimeofday(&timeout, NULL);
1918 timeval_add_time(&timeout, seconds, 0);
1920 LOG_INFO("Starting profiling. Halting and resuming the"
1921 " target as often as we can...");
1923 uint32_t sample_count = 0;
1924 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
1925 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
1927 int retval = ERROR_OK;
1929 target_poll(target);
1930 if (target->state == TARGET_HALTED) {
1931 uint32_t t = buf_get_u32(reg->value, 0, 32);
1932 samples[sample_count++] = t;
1933 /* current pc, addr = 0, do not handle breakpoints, not debugging */
1934 retval = target_resume(target, 1, 0, 0, 0);
1935 target_poll(target);
1936 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
1937 } else if (target->state == TARGET_RUNNING) {
1938 /* We want to quickly sample the PC. */
1939 retval = target_halt(target);
1941 LOG_INFO("Target not halted or running");
1946 if (retval != ERROR_OK)
1949 gettimeofday(&now, NULL);
1950 if ((sample_count >= max_num_samples) ||
1951 ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec))) {
1952 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
1957 *num_samples = sample_count;
1961 /* Single aligned words are guaranteed to use 16 or 32 bit access
1962 * mode respectively, otherwise data is handled as quickly as
1965 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1967 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1968 (int)size, (unsigned)address);
1970 if (!target_was_examined(target)) {
1971 LOG_ERROR("Target not examined yet");
1978 if ((address + size - 1) < address) {
1979 /* GDB can request this when e.g. PC is 0xfffffffc*/
1980 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1986 return target->type->write_buffer(target, address, size, buffer);
1989 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t count, const uint8_t *buffer)
1993 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
1994 * will have something to do with the size we leave to it. */
1995 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
1996 if (address & size) {
1997 int retval = target_write_memory(target, address, size, 1, buffer);
1998 if (retval != ERROR_OK)
2006 /* Write the data with as large access size as possible. */
2007 for (; size > 0; size /= 2) {
2008 uint32_t aligned = count - count % size;
2010 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2011 if (retval != ERROR_OK)
2022 /* Single aligned words are guaranteed to use 16 or 32 bit access
2023 * mode respectively, otherwise data is handled as quickly as
2026 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
2028 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
2029 (int)size, (unsigned)address);
2031 if (!target_was_examined(target)) {
2032 LOG_ERROR("Target not examined yet");
2039 if ((address + size - 1) < address) {
2040 /* GDB can request this when e.g. PC is 0xfffffffc*/
2041 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
2047 return target->type->read_buffer(target, address, size, buffer);
2050 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t count, uint8_t *buffer)
2054 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2055 * will have something to do with the size we leave to it. */
2056 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2057 if (address & size) {
2058 int retval = target_read_memory(target, address, size, 1, buffer);
2059 if (retval != ERROR_OK)
2067 /* Read the data with as large access size as possible. */
2068 for (; size > 0; size /= 2) {
2069 uint32_t aligned = count - count % size;
2071 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2072 if (retval != ERROR_OK)
2083 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
2088 uint32_t checksum = 0;
2089 if (!target_was_examined(target)) {
2090 LOG_ERROR("Target not examined yet");
2094 retval = target->type->checksum_memory(target, address, size, &checksum);
2095 if (retval != ERROR_OK) {
2096 buffer = malloc(size);
2097 if (buffer == NULL) {
2098 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
2099 return ERROR_COMMAND_SYNTAX_ERROR;
2101 retval = target_read_buffer(target, address, size, buffer);
2102 if (retval != ERROR_OK) {
2107 /* convert to target endianness */
2108 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2109 uint32_t target_data;
2110 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2111 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2114 retval = image_calculate_checksum(buffer, size, &checksum);
2123 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
2126 if (!target_was_examined(target)) {
2127 LOG_ERROR("Target not examined yet");
2131 if (target->type->blank_check_memory == 0)
2132 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2134 retval = target->type->blank_check_memory(target, address, size, blank);
2139 int target_read_u64(struct target *target, uint64_t address, uint64_t *value)
2141 uint8_t value_buf[8];
2142 if (!target_was_examined(target)) {
2143 LOG_ERROR("Target not examined yet");
2147 int retval = target_read_memory(target, address, 8, 1, value_buf);
2149 if (retval == ERROR_OK) {
2150 *value = target_buffer_get_u64(target, value_buf);
2151 LOG_DEBUG("address: 0x%" PRIx64 ", value: 0x%16.16" PRIx64 "",
2156 LOG_DEBUG("address: 0x%" PRIx64 " failed",
2163 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
2165 uint8_t value_buf[4];
2166 if (!target_was_examined(target)) {
2167 LOG_ERROR("Target not examined yet");
2171 int retval = target_read_memory(target, address, 4, 1, value_buf);
2173 if (retval == ERROR_OK) {
2174 *value = target_buffer_get_u32(target, value_buf);
2175 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2180 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2187 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
2189 uint8_t value_buf[2];
2190 if (!target_was_examined(target)) {
2191 LOG_ERROR("Target not examined yet");
2195 int retval = target_read_memory(target, address, 2, 1, value_buf);
2197 if (retval == ERROR_OK) {
2198 *value = target_buffer_get_u16(target, value_buf);
2199 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
2204 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2211 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
2213 if (!target_was_examined(target)) {
2214 LOG_ERROR("Target not examined yet");
2218 int retval = target_read_memory(target, address, 1, 1, value);
2220 if (retval == ERROR_OK) {
2221 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2226 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2233 int target_write_u64(struct target *target, uint64_t address, uint64_t value)
2236 uint8_t value_buf[8];
2237 if (!target_was_examined(target)) {
2238 LOG_ERROR("Target not examined yet");
2242 LOG_DEBUG("address: 0x%" PRIx64 ", value: 0x%16.16" PRIx64 "",
2246 target_buffer_set_u64(target, value_buf, value);
2247 retval = target_write_memory(target, address, 8, 1, value_buf);
2248 if (retval != ERROR_OK)
2249 LOG_DEBUG("failed: %i", retval);
2254 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
2257 uint8_t value_buf[4];
2258 if (!target_was_examined(target)) {
2259 LOG_ERROR("Target not examined yet");
2263 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2267 target_buffer_set_u32(target, value_buf, value);
2268 retval = target_write_memory(target, address, 4, 1, value_buf);
2269 if (retval != ERROR_OK)
2270 LOG_DEBUG("failed: %i", retval);
2275 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
2278 uint8_t value_buf[2];
2279 if (!target_was_examined(target)) {
2280 LOG_ERROR("Target not examined yet");
2284 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
2288 target_buffer_set_u16(target, value_buf, value);
2289 retval = target_write_memory(target, address, 2, 1, value_buf);
2290 if (retval != ERROR_OK)
2291 LOG_DEBUG("failed: %i", retval);
2296 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
2299 if (!target_was_examined(target)) {
2300 LOG_ERROR("Target not examined yet");
2304 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2307 retval = target_write_memory(target, address, 1, 1, &value);
2308 if (retval != ERROR_OK)
2309 LOG_DEBUG("failed: %i", retval);
2314 static int find_target(struct command_context *cmd_ctx, const char *name)
2316 struct target *target = get_target(name);
2317 if (target == NULL) {
2318 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2321 if (!target->tap->enabled) {
2322 LOG_USER("Target: TAP %s is disabled, "
2323 "can't be the current target\n",
2324 target->tap->dotted_name);
2328 cmd_ctx->current_target = target->target_number;
2333 COMMAND_HANDLER(handle_targets_command)
2335 int retval = ERROR_OK;
2336 if (CMD_ARGC == 1) {
2337 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2338 if (retval == ERROR_OK) {
2344 struct target *target = all_targets;
2345 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2346 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2351 if (target->tap->enabled)
2352 state = target_state_name(target);
2354 state = "tap-disabled";
2356 if (CMD_CTX->current_target == target->target_number)
2359 /* keep columns lined up to match the headers above */
2360 command_print(CMD_CTX,
2361 "%2d%c %-18s %-10s %-6s %-18s %s",
2362 target->target_number,
2364 target_name(target),
2365 target_type_name(target),
2366 Jim_Nvp_value2name_simple(nvp_target_endian,
2367 target->endianness)->name,
2368 target->tap->dotted_name,
2370 target = target->next;
2376 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2378 static int powerDropout;
2379 static int srstAsserted;
2381 static int runPowerRestore;
2382 static int runPowerDropout;
2383 static int runSrstAsserted;
2384 static int runSrstDeasserted;
2386 static int sense_handler(void)
2388 static int prevSrstAsserted;
2389 static int prevPowerdropout;
2391 int retval = jtag_power_dropout(&powerDropout);
2392 if (retval != ERROR_OK)
2396 powerRestored = prevPowerdropout && !powerDropout;
2398 runPowerRestore = 1;
2400 long long current = timeval_ms();
2401 static long long lastPower;
2402 int waitMore = lastPower + 2000 > current;
2403 if (powerDropout && !waitMore) {
2404 runPowerDropout = 1;
2405 lastPower = current;
2408 retval = jtag_srst_asserted(&srstAsserted);
2409 if (retval != ERROR_OK)
2413 srstDeasserted = prevSrstAsserted && !srstAsserted;
2415 static long long lastSrst;
2416 waitMore = lastSrst + 2000 > current;
2417 if (srstDeasserted && !waitMore) {
2418 runSrstDeasserted = 1;
2422 if (!prevSrstAsserted && srstAsserted)
2423 runSrstAsserted = 1;
2425 prevSrstAsserted = srstAsserted;
2426 prevPowerdropout = powerDropout;
2428 if (srstDeasserted || powerRestored) {
2429 /* Other than logging the event we can't do anything here.
2430 * Issuing a reset is a particularly bad idea as we might
2431 * be inside a reset already.
2438 /* process target state changes */
2439 static int handle_target(void *priv)
2441 Jim_Interp *interp = (Jim_Interp *)priv;
2442 int retval = ERROR_OK;
2444 if (!is_jtag_poll_safe()) {
2445 /* polling is disabled currently */
2449 /* we do not want to recurse here... */
2450 static int recursive;
2454 /* danger! running these procedures can trigger srst assertions and power dropouts.
2455 * We need to avoid an infinite loop/recursion here and we do that by
2456 * clearing the flags after running these events.
2458 int did_something = 0;
2459 if (runSrstAsserted) {
2460 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2461 Jim_Eval(interp, "srst_asserted");
2464 if (runSrstDeasserted) {
2465 Jim_Eval(interp, "srst_deasserted");
2468 if (runPowerDropout) {
2469 LOG_INFO("Power dropout detected, running power_dropout proc.");
2470 Jim_Eval(interp, "power_dropout");
2473 if (runPowerRestore) {
2474 Jim_Eval(interp, "power_restore");
2478 if (did_something) {
2479 /* clear detect flags */
2483 /* clear action flags */
2485 runSrstAsserted = 0;
2486 runSrstDeasserted = 0;
2487 runPowerRestore = 0;
2488 runPowerDropout = 0;
2493 /* Poll targets for state changes unless that's globally disabled.
2494 * Skip targets that are currently disabled.
2496 for (struct target *target = all_targets;
2497 is_jtag_poll_safe() && target;
2498 target = target->next) {
2500 if (!target_was_examined(target))
2503 if (!target->tap->enabled)
2506 if (target->backoff.times > target->backoff.count) {
2507 /* do not poll this time as we failed previously */
2508 target->backoff.count++;
2511 target->backoff.count = 0;
2513 /* only poll target if we've got power and srst isn't asserted */
2514 if (!powerDropout && !srstAsserted) {
2515 /* polling may fail silently until the target has been examined */
2516 retval = target_poll(target);
2517 if (retval != ERROR_OK) {
2518 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2519 if (target->backoff.times * polling_interval < 5000) {
2520 target->backoff.times *= 2;
2521 target->backoff.times++;
2523 LOG_USER("Polling target %s failed, GDB will be halted. Polling again in %dms",
2524 target_name(target),
2525 target->backoff.times * polling_interval);
2527 /* Tell GDB to halt the debugger. This allows the user to
2528 * run monitor commands to handle the situation.
2530 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2533 /* Since we succeeded, we reset backoff count */
2534 if (target->backoff.times > 0) {
2535 LOG_USER("Polling target %s succeeded again, trying to reexamine", target_name(target));
2536 target_reset_examined(target);
2537 retval = target_examine_one(target);
2538 /* Target examination could have failed due to unstable connection,
2539 * but we set the examined flag anyway to repoll it later */
2540 if (retval != ERROR_OK) {
2541 target->examined = true;
2546 target->backoff.times = 0;
2553 COMMAND_HANDLER(handle_reg_command)
2555 struct target *target;
2556 struct reg *reg = NULL;
2562 target = get_current_target(CMD_CTX);
2564 /* list all available registers for the current target */
2565 if (CMD_ARGC == 0) {
2566 struct reg_cache *cache = target->reg_cache;
2572 command_print(CMD_CTX, "===== %s", cache->name);
2574 for (i = 0, reg = cache->reg_list;
2575 i < cache->num_regs;
2576 i++, reg++, count++) {
2577 /* only print cached values if they are valid */
2579 value = buf_to_str(reg->value,
2581 command_print(CMD_CTX,
2582 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2590 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2595 cache = cache->next;
2601 /* access a single register by its ordinal number */
2602 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2604 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2606 struct reg_cache *cache = target->reg_cache;
2610 for (i = 0; i < cache->num_regs; i++) {
2611 if (count++ == num) {
2612 reg = &cache->reg_list[i];
2618 cache = cache->next;
2622 command_print(CMD_CTX, "%i is out of bounds, the current target "
2623 "has only %i registers (0 - %i)", num, count, count - 1);
2627 /* access a single register by its name */
2628 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2631 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2636 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2638 /* display a register */
2639 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2640 && (CMD_ARGV[1][0] <= '9')))) {
2641 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2644 if (reg->valid == 0)
2645 reg->type->get(reg);
2646 value = buf_to_str(reg->value, reg->size, 16);
2647 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2652 /* set register value */
2653 if (CMD_ARGC == 2) {
2654 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2657 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2659 reg->type->set(reg, buf);
2661 value = buf_to_str(reg->value, reg->size, 16);
2662 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2670 return ERROR_COMMAND_SYNTAX_ERROR;
2673 COMMAND_HANDLER(handle_poll_command)
2675 int retval = ERROR_OK;
2676 struct target *target = get_current_target(CMD_CTX);
2678 if (CMD_ARGC == 0) {
2679 command_print(CMD_CTX, "background polling: %s",
2680 jtag_poll_get_enabled() ? "on" : "off");
2681 command_print(CMD_CTX, "TAP: %s (%s)",
2682 target->tap->dotted_name,
2683 target->tap->enabled ? "enabled" : "disabled");
2684 if (!target->tap->enabled)
2686 retval = target_poll(target);
2687 if (retval != ERROR_OK)
2689 retval = target_arch_state(target);
2690 if (retval != ERROR_OK)
2692 } else if (CMD_ARGC == 1) {
2694 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2695 jtag_poll_set_enabled(enable);
2697 return ERROR_COMMAND_SYNTAX_ERROR;
2702 COMMAND_HANDLER(handle_wait_halt_command)
2705 return ERROR_COMMAND_SYNTAX_ERROR;
2707 unsigned ms = DEFAULT_HALT_TIMEOUT;
2708 if (1 == CMD_ARGC) {
2709 int retval = parse_uint(CMD_ARGV[0], &ms);
2710 if (ERROR_OK != retval)
2711 return ERROR_COMMAND_SYNTAX_ERROR;
2714 struct target *target = get_current_target(CMD_CTX);
2715 return target_wait_state(target, TARGET_HALTED, ms);
2718 /* wait for target state to change. The trick here is to have a low
2719 * latency for short waits and not to suck up all the CPU time
2722 * After 500ms, keep_alive() is invoked
2724 int target_wait_state(struct target *target, enum target_state state, int ms)
2727 long long then = 0, cur;
2731 retval = target_poll(target);
2732 if (retval != ERROR_OK)
2734 if (target->state == state)
2739 then = timeval_ms();
2740 LOG_DEBUG("waiting for target %s...",
2741 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2747 if ((cur-then) > ms) {
2748 LOG_ERROR("timed out while waiting for target %s",
2749 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2757 COMMAND_HANDLER(handle_halt_command)
2761 struct target *target = get_current_target(CMD_CTX);
2762 int retval = target_halt(target);
2763 if (ERROR_OK != retval)
2766 if (CMD_ARGC == 1) {
2767 unsigned wait_local;
2768 retval = parse_uint(CMD_ARGV[0], &wait_local);
2769 if (ERROR_OK != retval)
2770 return ERROR_COMMAND_SYNTAX_ERROR;
2775 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2778 COMMAND_HANDLER(handle_soft_reset_halt_command)
2780 struct target *target = get_current_target(CMD_CTX);
2782 LOG_USER("requesting target halt and executing a soft reset");
2784 target_soft_reset_halt(target);
2789 COMMAND_HANDLER(handle_reset_command)
2792 return ERROR_COMMAND_SYNTAX_ERROR;
2794 enum target_reset_mode reset_mode = RESET_RUN;
2795 if (CMD_ARGC == 1) {
2797 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2798 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2799 return ERROR_COMMAND_SYNTAX_ERROR;
2800 reset_mode = n->value;
2803 /* reset *all* targets */
2804 return target_process_reset(CMD_CTX, reset_mode);
2808 COMMAND_HANDLER(handle_resume_command)
2812 return ERROR_COMMAND_SYNTAX_ERROR;
2814 struct target *target = get_current_target(CMD_CTX);
2816 /* with no CMD_ARGV, resume from current pc, addr = 0,
2817 * with one arguments, addr = CMD_ARGV[0],
2818 * handle breakpoints, not debugging */
2820 if (CMD_ARGC == 1) {
2821 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2825 return target_resume(target, current, addr, 1, 0);
2828 COMMAND_HANDLER(handle_step_command)
2831 return ERROR_COMMAND_SYNTAX_ERROR;
2835 /* with no CMD_ARGV, step from current pc, addr = 0,
2836 * with one argument addr = CMD_ARGV[0],
2837 * handle breakpoints, debugging */
2840 if (CMD_ARGC == 1) {
2841 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2845 struct target *target = get_current_target(CMD_CTX);
2847 return target->type->step(target, current_pc, addr, 1);
2850 static void handle_md_output(struct command_context *cmd_ctx,
2851 struct target *target, uint32_t address, unsigned size,
2852 unsigned count, const uint8_t *buffer)
2854 const unsigned line_bytecnt = 32;
2855 unsigned line_modulo = line_bytecnt / size;
2857 char output[line_bytecnt * 4 + 1];
2858 unsigned output_len = 0;
2860 const char *value_fmt;
2863 value_fmt = "%8.8x ";
2866 value_fmt = "%4.4x ";
2869 value_fmt = "%2.2x ";
2872 /* "can't happen", caller checked */
2873 LOG_ERROR("invalid memory read size: %u", size);
2877 for (unsigned i = 0; i < count; i++) {
2878 if (i % line_modulo == 0) {
2879 output_len += snprintf(output + output_len,
2880 sizeof(output) - output_len,
2882 (unsigned)(address + (i*size)));
2886 const uint8_t *value_ptr = buffer + i * size;
2889 value = target_buffer_get_u32(target, value_ptr);
2892 value = target_buffer_get_u16(target, value_ptr);
2897 output_len += snprintf(output + output_len,
2898 sizeof(output) - output_len,
2901 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2902 command_print(cmd_ctx, "%s", output);
2908 COMMAND_HANDLER(handle_md_command)
2911 return ERROR_COMMAND_SYNTAX_ERROR;
2914 switch (CMD_NAME[2]) {
2925 return ERROR_COMMAND_SYNTAX_ERROR;
2928 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2929 int (*fn)(struct target *target,
2930 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2934 fn = target_read_phys_memory;
2936 fn = target_read_memory;
2937 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2938 return ERROR_COMMAND_SYNTAX_ERROR;
2941 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2945 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2947 uint8_t *buffer = calloc(count, size);
2949 struct target *target = get_current_target(CMD_CTX);
2950 int retval = fn(target, address, size, count, buffer);
2951 if (ERROR_OK == retval)
2952 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2959 typedef int (*target_write_fn)(struct target *target,
2960 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2962 static int target_fill_mem(struct target *target,
2971 /* We have to write in reasonably large chunks to be able
2972 * to fill large memory areas with any sane speed */
2973 const unsigned chunk_size = 16384;
2974 uint8_t *target_buf = malloc(chunk_size * data_size);
2975 if (target_buf == NULL) {
2976 LOG_ERROR("Out of memory");
2980 for (unsigned i = 0; i < chunk_size; i++) {
2981 switch (data_size) {
2983 target_buffer_set_u32(target, target_buf + i * data_size, b);
2986 target_buffer_set_u16(target, target_buf + i * data_size, b);
2989 target_buffer_set_u8(target, target_buf + i * data_size, b);
2996 int retval = ERROR_OK;
2998 for (unsigned x = 0; x < c; x += chunk_size) {
3001 if (current > chunk_size)
3002 current = chunk_size;
3003 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3004 if (retval != ERROR_OK)
3006 /* avoid GDB timeouts */
3015 COMMAND_HANDLER(handle_mw_command)
3018 return ERROR_COMMAND_SYNTAX_ERROR;
3019 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3024 fn = target_write_phys_memory;
3026 fn = target_write_memory;
3027 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3028 return ERROR_COMMAND_SYNTAX_ERROR;
3031 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
3034 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
3038 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3040 struct target *target = get_current_target(CMD_CTX);
3042 switch (CMD_NAME[2]) {
3053 return ERROR_COMMAND_SYNTAX_ERROR;
3056 return target_fill_mem(target, address, fn, wordsize, value, count);
3059 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
3060 uint32_t *min_address, uint32_t *max_address)
3062 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3063 return ERROR_COMMAND_SYNTAX_ERROR;
3065 /* a base address isn't always necessary,
3066 * default to 0x0 (i.e. don't relocate) */
3067 if (CMD_ARGC >= 2) {
3069 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3070 image->base_address = addr;
3071 image->base_address_set = 1;
3073 image->base_address_set = 0;
3075 image->start_address_set = 0;
3078 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
3079 if (CMD_ARGC == 5) {
3080 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
3081 /* use size (given) to find max (required) */
3082 *max_address += *min_address;
3085 if (*min_address > *max_address)
3086 return ERROR_COMMAND_SYNTAX_ERROR;
3091 COMMAND_HANDLER(handle_load_image_command)
3095 uint32_t image_size;
3096 uint32_t min_address = 0;
3097 uint32_t max_address = 0xffffffff;
3101 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
3102 &image, &min_address, &max_address);
3103 if (ERROR_OK != retval)
3106 struct target *target = get_current_target(CMD_CTX);
3108 struct duration bench;
3109 duration_start(&bench);
3111 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3116 for (i = 0; i < image.num_sections; i++) {
3117 buffer = malloc(image.sections[i].size);
3118 if (buffer == NULL) {
3119 command_print(CMD_CTX,
3120 "error allocating buffer for section (%d bytes)",
3121 (int)(image.sections[i].size));
3125 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3126 if (retval != ERROR_OK) {
3131 uint32_t offset = 0;
3132 uint32_t length = buf_cnt;
3134 /* DANGER!!! beware of unsigned comparision here!!! */
3136 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3137 (image.sections[i].base_address < max_address)) {
3139 if (image.sections[i].base_address < min_address) {
3140 /* clip addresses below */
3141 offset += min_address-image.sections[i].base_address;
3145 if (image.sections[i].base_address + buf_cnt > max_address)
3146 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3148 retval = target_write_buffer(target,
3149 image.sections[i].base_address + offset, length, buffer + offset);
3150 if (retval != ERROR_OK) {
3154 image_size += length;
3155 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
3156 (unsigned int)length,
3157 image.sections[i].base_address + offset);
3163 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3164 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
3165 "in %fs (%0.3f KiB/s)", image_size,
3166 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3169 image_close(&image);
3175 COMMAND_HANDLER(handle_dump_image_command)
3177 struct fileio fileio;
3179 int retval, retvaltemp;
3180 uint32_t address, size;
3181 struct duration bench;
3182 struct target *target = get_current_target(CMD_CTX);
3185 return ERROR_COMMAND_SYNTAX_ERROR;
3187 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
3188 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
3190 uint32_t buf_size = (size > 4096) ? 4096 : size;
3191 buffer = malloc(buf_size);
3195 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3196 if (retval != ERROR_OK) {
3201 duration_start(&bench);
3204 size_t size_written;
3205 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3206 retval = target_read_buffer(target, address, this_run_size, buffer);
3207 if (retval != ERROR_OK)
3210 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
3211 if (retval != ERROR_OK)
3214 size -= this_run_size;
3215 address += this_run_size;
3220 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3222 retval = fileio_size(&fileio, &filesize);
3223 if (retval != ERROR_OK)
3225 command_print(CMD_CTX,
3226 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
3227 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3230 retvaltemp = fileio_close(&fileio);
3231 if (retvaltemp != ERROR_OK)
3237 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
3241 uint32_t image_size;
3244 uint32_t checksum = 0;
3245 uint32_t mem_checksum = 0;
3249 struct target *target = get_current_target(CMD_CTX);
3252 return ERROR_COMMAND_SYNTAX_ERROR;
3255 LOG_ERROR("no target selected");
3259 struct duration bench;
3260 duration_start(&bench);
3262 if (CMD_ARGC >= 2) {
3264 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3265 image.base_address = addr;
3266 image.base_address_set = 1;
3268 image.base_address_set = 0;
3269 image.base_address = 0x0;
3272 image.start_address_set = 0;
3274 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3275 if (retval != ERROR_OK)
3281 for (i = 0; i < image.num_sections; i++) {
3282 buffer = malloc(image.sections[i].size);
3283 if (buffer == NULL) {
3284 command_print(CMD_CTX,
3285 "error allocating buffer for section (%d bytes)",
3286 (int)(image.sections[i].size));
3289 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3290 if (retval != ERROR_OK) {
3296 /* calculate checksum of image */
3297 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3298 if (retval != ERROR_OK) {
3303 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3304 if (retval != ERROR_OK) {
3309 if (checksum != mem_checksum) {
3310 /* failed crc checksum, fall back to a binary compare */
3314 LOG_ERROR("checksum mismatch - attempting binary compare");
3316 data = malloc(buf_cnt);
3318 /* Can we use 32bit word accesses? */
3320 int count = buf_cnt;
3321 if ((count % 4) == 0) {
3325 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3326 if (retval == ERROR_OK) {
3328 for (t = 0; t < buf_cnt; t++) {
3329 if (data[t] != buffer[t]) {
3330 command_print(CMD_CTX,
3331 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3333 (unsigned)(t + image.sections[i].base_address),
3336 if (diffs++ >= 127) {
3337 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3349 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3350 image.sections[i].base_address,
3355 image_size += buf_cnt;
3358 command_print(CMD_CTX, "No more differences found.");
3361 retval = ERROR_FAIL;
3362 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3363 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3364 "in %fs (%0.3f KiB/s)", image_size,
3365 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3368 image_close(&image);
3373 COMMAND_HANDLER(handle_verify_image_command)
3375 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3378 COMMAND_HANDLER(handle_test_image_command)
3380 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3383 static int handle_bp_command_list(struct command_context *cmd_ctx)
3385 struct target *target = get_current_target(cmd_ctx);
3386 struct breakpoint *breakpoint = target->breakpoints;
3387 while (breakpoint) {
3388 if (breakpoint->type == BKPT_SOFT) {
3389 char *buf = buf_to_str(breakpoint->orig_instr,
3390 breakpoint->length, 16);
3391 command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3392 breakpoint->address,
3394 breakpoint->set, buf);
3397 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3398 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3400 breakpoint->length, breakpoint->set);
3401 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3402 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3403 breakpoint->address,
3404 breakpoint->length, breakpoint->set);
3405 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3408 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3409 breakpoint->address,
3410 breakpoint->length, breakpoint->set);
3413 breakpoint = breakpoint->next;
3418 static int handle_bp_command_set(struct command_context *cmd_ctx,
3419 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3421 struct target *target = get_current_target(cmd_ctx);
3425 retval = breakpoint_add(target, addr, length, hw);
3426 if (ERROR_OK == retval)
3427 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3429 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3432 } else if (addr == 0) {
3433 if (target->type->add_context_breakpoint == NULL) {
3434 LOG_WARNING("Context breakpoint not available");
3437 retval = context_breakpoint_add(target, asid, length, hw);
3438 if (ERROR_OK == retval)
3439 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3441 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3445 if (target->type->add_hybrid_breakpoint == NULL) {
3446 LOG_WARNING("Hybrid breakpoint not available");
3449 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3450 if (ERROR_OK == retval)
3451 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3453 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3460 COMMAND_HANDLER(handle_bp_command)
3469 return handle_bp_command_list(CMD_CTX);
3473 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3474 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3475 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3478 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3480 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3482 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3485 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3486 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3488 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3489 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3491 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3496 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3497 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3498 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3499 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3502 return ERROR_COMMAND_SYNTAX_ERROR;
3506 COMMAND_HANDLER(handle_rbp_command)
3509 return ERROR_COMMAND_SYNTAX_ERROR;
3512 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3514 struct target *target = get_current_target(CMD_CTX);
3515 breakpoint_remove(target, addr);
3520 COMMAND_HANDLER(handle_wp_command)
3522 struct target *target = get_current_target(CMD_CTX);
3524 if (CMD_ARGC == 0) {
3525 struct watchpoint *watchpoint = target->watchpoints;
3527 while (watchpoint) {
3528 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3529 ", len: 0x%8.8" PRIx32
3530 ", r/w/a: %i, value: 0x%8.8" PRIx32
3531 ", mask: 0x%8.8" PRIx32,
3532 watchpoint->address,
3534 (int)watchpoint->rw,
3537 watchpoint = watchpoint->next;
3542 enum watchpoint_rw type = WPT_ACCESS;
3544 uint32_t length = 0;
3545 uint32_t data_value = 0x0;
3546 uint32_t data_mask = 0xffffffff;
3550 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3553 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3556 switch (CMD_ARGV[2][0]) {
3567 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3568 return ERROR_COMMAND_SYNTAX_ERROR;
3572 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3573 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3577 return ERROR_COMMAND_SYNTAX_ERROR;
3580 int retval = watchpoint_add(target, addr, length, type,
3581 data_value, data_mask);
3582 if (ERROR_OK != retval)
3583 LOG_ERROR("Failure setting watchpoints");
3588 COMMAND_HANDLER(handle_rwp_command)
3591 return ERROR_COMMAND_SYNTAX_ERROR;
3594 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3596 struct target *target = get_current_target(CMD_CTX);
3597 watchpoint_remove(target, addr);
3603 * Translate a virtual address to a physical address.
3605 * The low-level target implementation must have logged a detailed error
3606 * which is forwarded to telnet/GDB session.
3608 COMMAND_HANDLER(handle_virt2phys_command)
3611 return ERROR_COMMAND_SYNTAX_ERROR;
3614 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3617 struct target *target = get_current_target(CMD_CTX);
3618 int retval = target->type->virt2phys(target, va, &pa);
3619 if (retval == ERROR_OK)
3620 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3625 static void writeData(FILE *f, const void *data, size_t len)
3627 size_t written = fwrite(data, 1, len, f);
3629 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3632 static void writeLong(FILE *f, int l, struct target *target)
3636 target_buffer_set_u32(target, val, l);
3637 writeData(f, val, 4);
3640 static void writeString(FILE *f, char *s)
3642 writeData(f, s, strlen(s));
3645 typedef unsigned char UNIT[2]; /* unit of profiling */
3647 /* Dump a gmon.out histogram file. */
3648 static void write_gmon(uint32_t *samples, uint32_t sampleNum, const char *filename, bool with_range,
3649 uint32_t start_address, uint32_t end_address, struct target *target)
3652 FILE *f = fopen(filename, "w");
3655 writeString(f, "gmon");
3656 writeLong(f, 0x00000001, target); /* Version */
3657 writeLong(f, 0, target); /* padding */
3658 writeLong(f, 0, target); /* padding */
3659 writeLong(f, 0, target); /* padding */
3661 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3662 writeData(f, &zero, 1);
3664 /* figure out bucket size */
3668 min = start_address;
3673 for (i = 0; i < sampleNum; i++) {
3674 if (min > samples[i])
3676 if (max < samples[i])
3680 /* max should be (largest sample + 1)
3681 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
3685 int addressSpace = max - min;
3686 assert(addressSpace >= 2);
3688 /* FIXME: What is the reasonable number of buckets?
3689 * The profiling result will be more accurate if there are enough buckets. */
3690 static const uint32_t maxBuckets = 128 * 1024; /* maximum buckets. */
3691 uint32_t numBuckets = addressSpace / sizeof(UNIT);
3692 if (numBuckets > maxBuckets)
3693 numBuckets = maxBuckets;
3694 int *buckets = malloc(sizeof(int) * numBuckets);
3695 if (buckets == NULL) {
3699 memset(buckets, 0, sizeof(int) * numBuckets);
3700 for (i = 0; i < sampleNum; i++) {
3701 uint32_t address = samples[i];
3703 if ((address < min) || (max <= address))
3706 long long a = address - min;
3707 long long b = numBuckets;
3708 long long c = addressSpace;
3709 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3713 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3714 writeLong(f, min, target); /* low_pc */
3715 writeLong(f, max, target); /* high_pc */
3716 writeLong(f, numBuckets, target); /* # of buckets */
3717 writeLong(f, 100, target); /* KLUDGE! We lie, ca. 100Hz best case. */
3718 writeString(f, "seconds");
3719 for (i = 0; i < (15-strlen("seconds")); i++)
3720 writeData(f, &zero, 1);
3721 writeString(f, "s");
3723 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3725 char *data = malloc(2 * numBuckets);
3727 for (i = 0; i < numBuckets; i++) {
3732 data[i * 2] = val&0xff;
3733 data[i * 2 + 1] = (val >> 8) & 0xff;
3736 writeData(f, data, numBuckets * 2);
3744 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3745 * which will be used as a random sampling of PC */
3746 COMMAND_HANDLER(handle_profile_command)
3748 struct target *target = get_current_target(CMD_CTX);
3750 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
3751 return ERROR_COMMAND_SYNTAX_ERROR;
3753 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
3755 uint32_t num_of_samples;
3756 int retval = ERROR_OK;
3758 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
3760 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
3761 if (samples == NULL) {
3762 LOG_ERROR("No memory to store samples.");
3767 * Some cores let us sample the PC without the
3768 * annoying halt/resume step; for example, ARMv7 PCSR.
3769 * Provide a way to use that more efficient mechanism.
3771 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
3772 &num_of_samples, offset);
3773 if (retval != ERROR_OK) {
3778 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
3780 retval = target_poll(target);
3781 if (retval != ERROR_OK) {
3785 if (target->state == TARGET_RUNNING) {
3786 retval = target_halt(target);
3787 if (retval != ERROR_OK) {
3793 retval = target_poll(target);
3794 if (retval != ERROR_OK) {
3799 uint32_t start_address = 0;
3800 uint32_t end_address = 0;
3801 bool with_range = false;
3802 if (CMD_ARGC == 4) {
3804 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
3805 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
3808 write_gmon(samples, num_of_samples, CMD_ARGV[1],
3809 with_range, start_address, end_address, target);
3810 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3816 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3819 Jim_Obj *nameObjPtr, *valObjPtr;
3822 namebuf = alloc_printf("%s(%d)", varname, idx);
3826 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3827 valObjPtr = Jim_NewIntObj(interp, val);
3828 if (!nameObjPtr || !valObjPtr) {
3833 Jim_IncrRefCount(nameObjPtr);
3834 Jim_IncrRefCount(valObjPtr);
3835 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3836 Jim_DecrRefCount(interp, nameObjPtr);
3837 Jim_DecrRefCount(interp, valObjPtr);
3839 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3843 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3845 struct command_context *context;
3846 struct target *target;
3848 context = current_command_context(interp);
3849 assert(context != NULL);
3851 target = get_current_target(context);
3852 if (target == NULL) {
3853 LOG_ERROR("mem2array: no current target");
3857 return target_mem2array(interp, target, argc - 1, argv + 1);
3860 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3868 const char *varname;
3872 /* argv[1] = name of array to receive the data
3873 * argv[2] = desired width
3874 * argv[3] = memory address
3875 * argv[4] = count of times to read
3878 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3881 varname = Jim_GetString(argv[0], &len);
3882 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3884 e = Jim_GetLong(interp, argv[1], &l);
3889 e = Jim_GetLong(interp, argv[2], &l);
3893 e = Jim_GetLong(interp, argv[3], &l);
3908 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3909 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3913 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3914 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3917 if ((addr + (len * width)) < addr) {
3918 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3919 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3922 /* absurd transfer size? */
3924 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3925 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3930 ((width == 2) && ((addr & 1) == 0)) ||
3931 ((width == 4) && ((addr & 3) == 0))) {
3935 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3936 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3939 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3948 size_t buffersize = 4096;
3949 uint8_t *buffer = malloc(buffersize);
3956 /* Slurp... in buffer size chunks */
3958 count = len; /* in objects.. */
3959 if (count > (buffersize / width))
3960 count = (buffersize / width);
3962 retval = target_read_memory(target, addr, width, count, buffer);
3963 if (retval != ERROR_OK) {
3965 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3969 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3970 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3974 v = 0; /* shut up gcc */
3975 for (i = 0; i < count ; i++, n++) {
3978 v = target_buffer_get_u32(target, &buffer[i*width]);
3981 v = target_buffer_get_u16(target, &buffer[i*width]);
3984 v = buffer[i] & 0x0ff;
3987 new_int_array_element(interp, varname, n, v);
3990 addr += count * width;
3996 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4001 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
4004 Jim_Obj *nameObjPtr, *valObjPtr;
4008 namebuf = alloc_printf("%s(%d)", varname, idx);
4012 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
4018 Jim_IncrRefCount(nameObjPtr);
4019 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
4020 Jim_DecrRefCount(interp, nameObjPtr);
4022 if (valObjPtr == NULL)
4025 result = Jim_GetLong(interp, valObjPtr, &l);
4026 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
4031 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4033 struct command_context *context;
4034 struct target *target;
4036 context = current_command_context(interp);
4037 assert(context != NULL);
4039 target = get_current_target(context);
4040 if (target == NULL) {
4041 LOG_ERROR("array2mem: no current target");
4045 return target_array2mem(interp, target, argc-1, argv + 1);
4048 static int target_array2mem(Jim_Interp *interp, struct target *target,
4049 int argc, Jim_Obj *const *argv)
4057 const char *varname;
4061 /* argv[1] = name of array to get the data
4062 * argv[2] = desired width
4063 * argv[3] = memory address
4064 * argv[4] = count to write
4067 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
4070 varname = Jim_GetString(argv[0], &len);
4071 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
4073 e = Jim_GetLong(interp, argv[1], &l);
4078 e = Jim_GetLong(interp, argv[2], &l);
4082 e = Jim_GetLong(interp, argv[3], &l);
4097 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4098 Jim_AppendStrings(interp, Jim_GetResult(interp),
4099 "Invalid width param, must be 8/16/32", NULL);
4103 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4104 Jim_AppendStrings(interp, Jim_GetResult(interp),
4105 "array2mem: zero width read?", NULL);
4108 if ((addr + (len * width)) < addr) {
4109 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4110 Jim_AppendStrings(interp, Jim_GetResult(interp),
4111 "array2mem: addr + len - wraps to zero?", NULL);
4114 /* absurd transfer size? */
4116 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4117 Jim_AppendStrings(interp, Jim_GetResult(interp),
4118 "array2mem: absurd > 64K item request", NULL);
4123 ((width == 2) && ((addr & 1) == 0)) ||
4124 ((width == 4) && ((addr & 3) == 0))) {
4128 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4129 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
4132 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
4143 size_t buffersize = 4096;
4144 uint8_t *buffer = malloc(buffersize);
4149 /* Slurp... in buffer size chunks */
4151 count = len; /* in objects.. */
4152 if (count > (buffersize / width))
4153 count = (buffersize / width);
4155 v = 0; /* shut up gcc */
4156 for (i = 0; i < count; i++, n++) {
4157 get_int_array_element(interp, varname, n, &v);
4160 target_buffer_set_u32(target, &buffer[i * width], v);
4163 target_buffer_set_u16(target, &buffer[i * width], v);
4166 buffer[i] = v & 0x0ff;
4172 retval = target_write_memory(target, addr, width, count, buffer);
4173 if (retval != ERROR_OK) {
4175 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
4179 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4180 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4184 addr += count * width;
4189 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4194 /* FIX? should we propagate errors here rather than printing them
4197 void target_handle_event(struct target *target, enum target_event e)
4199 struct target_event_action *teap;
4201 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4202 if (teap->event == e) {
4203 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
4204 target->target_number,
4205 target_name(target),
4206 target_type_name(target),
4208 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
4209 Jim_GetString(teap->body, NULL));
4210 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
4211 Jim_MakeErrorMessage(teap->interp);
4212 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
4219 * Returns true only if the target has a handler for the specified event.
4221 bool target_has_event_action(struct target *target, enum target_event event)
4223 struct target_event_action *teap;
4225 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4226 if (teap->event == event)
4232 enum target_cfg_param {
4235 TCFG_WORK_AREA_VIRT,
4236 TCFG_WORK_AREA_PHYS,
4237 TCFG_WORK_AREA_SIZE,
4238 TCFG_WORK_AREA_BACKUP,
4241 TCFG_CHAIN_POSITION,
4246 static Jim_Nvp nvp_config_opts[] = {
4247 { .name = "-type", .value = TCFG_TYPE },
4248 { .name = "-event", .value = TCFG_EVENT },
4249 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4250 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4251 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4252 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4253 { .name = "-endian" , .value = TCFG_ENDIAN },
4254 { .name = "-coreid", .value = TCFG_COREID },
4255 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4256 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4257 { .name = "-rtos", .value = TCFG_RTOS },
4258 { .name = NULL, .value = -1 }
4261 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
4268 /* parse config or cget options ... */
4269 while (goi->argc > 0) {
4270 Jim_SetEmptyResult(goi->interp);
4271 /* Jim_GetOpt_Debug(goi); */
4273 if (target->type->target_jim_configure) {
4274 /* target defines a configure function */
4275 /* target gets first dibs on parameters */
4276 e = (*(target->type->target_jim_configure))(target, goi);
4285 /* otherwise we 'continue' below */
4287 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
4289 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
4295 if (goi->isconfigure) {
4296 Jim_SetResultFormatted(goi->interp,
4297 "not settable: %s", n->name);
4301 if (goi->argc != 0) {
4302 Jim_WrongNumArgs(goi->interp,
4303 goi->argc, goi->argv,
4308 Jim_SetResultString(goi->interp,
4309 target_type_name(target), -1);
4313 if (goi->argc == 0) {
4314 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4318 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4320 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4324 if (goi->isconfigure) {
4325 if (goi->argc != 1) {
4326 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4330 if (goi->argc != 0) {
4331 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4337 struct target_event_action *teap;
4339 teap = target->event_action;
4340 /* replace existing? */
4342 if (teap->event == (enum target_event)n->value)
4347 if (goi->isconfigure) {
4348 bool replace = true;
4351 teap = calloc(1, sizeof(*teap));
4354 teap->event = n->value;
4355 teap->interp = goi->interp;
4356 Jim_GetOpt_Obj(goi, &o);
4358 Jim_DecrRefCount(teap->interp, teap->body);
4359 teap->body = Jim_DuplicateObj(goi->interp, o);
4362 * Tcl/TK - "tk events" have a nice feature.
4363 * See the "BIND" command.
4364 * We should support that here.
4365 * You can specify %X and %Y in the event code.
4366 * The idea is: %T - target name.
4367 * The idea is: %N - target number
4368 * The idea is: %E - event name.
4370 Jim_IncrRefCount(teap->body);
4373 /* add to head of event list */
4374 teap->next = target->event_action;
4375 target->event_action = teap;
4377 Jim_SetEmptyResult(goi->interp);
4381 Jim_SetEmptyResult(goi->interp);
4383 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4389 case TCFG_WORK_AREA_VIRT:
4390 if (goi->isconfigure) {
4391 target_free_all_working_areas(target);
4392 e = Jim_GetOpt_Wide(goi, &w);
4395 target->working_area_virt = w;
4396 target->working_area_virt_spec = true;
4401 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4405 case TCFG_WORK_AREA_PHYS:
4406 if (goi->isconfigure) {
4407 target_free_all_working_areas(target);
4408 e = Jim_GetOpt_Wide(goi, &w);
4411 target->working_area_phys = w;
4412 target->working_area_phys_spec = true;
4417 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4421 case TCFG_WORK_AREA_SIZE:
4422 if (goi->isconfigure) {
4423 target_free_all_working_areas(target);
4424 e = Jim_GetOpt_Wide(goi, &w);
4427 target->working_area_size = w;
4432 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4436 case TCFG_WORK_AREA_BACKUP:
4437 if (goi->isconfigure) {
4438 target_free_all_working_areas(target);
4439 e = Jim_GetOpt_Wide(goi, &w);
4442 /* make this exactly 1 or 0 */
4443 target->backup_working_area = (!!w);
4448 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4449 /* loop for more e*/
4454 if (goi->isconfigure) {
4455 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4457 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4460 target->endianness = n->value;
4465 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4466 if (n->name == NULL) {
4467 target->endianness = TARGET_LITTLE_ENDIAN;
4468 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4470 Jim_SetResultString(goi->interp, n->name, -1);
4475 if (goi->isconfigure) {
4476 e = Jim_GetOpt_Wide(goi, &w);
4479 target->coreid = (int32_t)w;
4484 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4488 case TCFG_CHAIN_POSITION:
4489 if (goi->isconfigure) {
4491 struct jtag_tap *tap;
4492 target_free_all_working_areas(target);
4493 e = Jim_GetOpt_Obj(goi, &o_t);
4496 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4499 /* make this exactly 1 or 0 */
4505 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4506 /* loop for more e*/
4509 if (goi->isconfigure) {
4510 e = Jim_GetOpt_Wide(goi, &w);
4513 target->dbgbase = (uint32_t)w;
4514 target->dbgbase_set = true;
4519 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4526 int result = rtos_create(goi, target);
4527 if (result != JIM_OK)
4533 } /* while (goi->argc) */
4536 /* done - we return */
4540 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4544 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4545 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4546 int need_args = 1 + goi.isconfigure;
4547 if (goi.argc < need_args) {
4548 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4550 ? "missing: -option VALUE ..."
4551 : "missing: -option ...");
4554 struct target *target = Jim_CmdPrivData(goi.interp);
4555 return target_configure(&goi, target);
4558 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4560 const char *cmd_name = Jim_GetString(argv[0], NULL);
4563 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4565 if (goi.argc < 2 || goi.argc > 4) {
4566 Jim_SetResultFormatted(goi.interp,
4567 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4572 fn = target_write_memory;
4575 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4577 struct Jim_Obj *obj;
4578 e = Jim_GetOpt_Obj(&goi, &obj);
4582 fn = target_write_phys_memory;
4586 e = Jim_GetOpt_Wide(&goi, &a);
4591 e = Jim_GetOpt_Wide(&goi, &b);
4596 if (goi.argc == 1) {
4597 e = Jim_GetOpt_Wide(&goi, &c);
4602 /* all args must be consumed */
4606 struct target *target = Jim_CmdPrivData(goi.interp);
4608 if (strcasecmp(cmd_name, "mww") == 0)
4610 else if (strcasecmp(cmd_name, "mwh") == 0)
4612 else if (strcasecmp(cmd_name, "mwb") == 0)
4615 LOG_ERROR("command '%s' unknown: ", cmd_name);
4619 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4623 * @brief Reads an array of words/halfwords/bytes from target memory starting at specified address.
4625 * Usage: mdw [phys] <address> [<count>] - for 32 bit reads
4626 * mdh [phys] <address> [<count>] - for 16 bit reads
4627 * mdb [phys] <address> [<count>] - for 8 bit reads
4629 * Count defaults to 1.
4631 * Calls target_read_memory or target_read_phys_memory depending on
4632 * the presence of the "phys" argument
4633 * Reads the target memory in blocks of max. 32 bytes, and returns an array of ints formatted
4634 * to int representation in base16.
4635 * Also outputs read data in a human readable form using command_print
4637 * @param phys if present target_read_phys_memory will be used instead of target_read_memory
4638 * @param address address where to start the read. May be specified in decimal or hex using the standard "0x" prefix
4639 * @param count optional count parameter to read an array of values. If not specified, defaults to 1.
4640 * @returns: JIM_ERR on error or JIM_OK on success and sets the result string to an array of ascii formatted numbers
4641 * on success, with [<count>] number of elements.
4643 * In case of little endian target:
4644 * Example1: "mdw 0x00000000" returns "10123456"
4645 * Exmaple2: "mdh 0x00000000 1" returns "3456"
4646 * Example3: "mdb 0x00000000" returns "56"
4647 * Example4: "mdh 0x00000000 2" returns "3456 1012"
4648 * Example5: "mdb 0x00000000 3" returns "56 34 12"
4650 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4652 const char *cmd_name = Jim_GetString(argv[0], NULL);
4655 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4657 if ((goi.argc < 1) || (goi.argc > 3)) {
4658 Jim_SetResultFormatted(goi.interp,
4659 "usage: %s [phys] <address> [<count>]", cmd_name);
4663 int (*fn)(struct target *target,
4664 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4665 fn = target_read_memory;
4668 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4670 struct Jim_Obj *obj;
4671 e = Jim_GetOpt_Obj(&goi, &obj);
4675 fn = target_read_phys_memory;
4678 /* Read address parameter */
4680 e = Jim_GetOpt_Wide(&goi, &addr);
4684 /* If next parameter exists, read it out as the count parameter, if not, set it to 1 (default) */
4686 if (goi.argc == 1) {
4687 e = Jim_GetOpt_Wide(&goi, &count);
4693 /* all args must be consumed */
4697 jim_wide dwidth = 1; /* shut up gcc */
4698 if (strcasecmp(cmd_name, "mdw") == 0)
4700 else if (strcasecmp(cmd_name, "mdh") == 0)
4702 else if (strcasecmp(cmd_name, "mdb") == 0)
4705 LOG_ERROR("command '%s' unknown: ", cmd_name);
4709 /* convert count to "bytes" */
4710 int bytes = count * dwidth;
4712 struct target *target = Jim_CmdPrivData(goi.interp);
4713 uint8_t target_buf[32];
4716 y = (bytes < 16) ? bytes : 16; /* y = min(bytes, 16); */
4718 /* Try to read out next block */
4719 e = fn(target, addr, dwidth, y / dwidth, target_buf);
4721 if (e != ERROR_OK) {
4722 Jim_SetResultFormatted(interp, "error reading target @ 0x%08lx", (long)addr);
4726 command_print_sameline(NULL, "0x%08x ", (int)(addr));
4729 for (x = 0; x < 16 && x < y; x += 4) {
4730 z = target_buffer_get_u32(target, &(target_buf[x]));
4731 command_print_sameline(NULL, "%08x ", (int)(z));
4733 for (; (x < 16) ; x += 4)
4734 command_print_sameline(NULL, " ");
4737 for (x = 0; x < 16 && x < y; x += 2) {
4738 z = target_buffer_get_u16(target, &(target_buf[x]));
4739 command_print_sameline(NULL, "%04x ", (int)(z));
4741 for (; (x < 16) ; x += 2)
4742 command_print_sameline(NULL, " ");
4746 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4747 z = target_buffer_get_u8(target, &(target_buf[x]));
4748 command_print_sameline(NULL, "%02x ", (int)(z));
4750 for (; (x < 16) ; x += 1)
4751 command_print_sameline(NULL, " ");
4754 /* ascii-ify the bytes */
4755 for (x = 0 ; x < y ; x++) {
4756 if ((target_buf[x] >= 0x20) &&
4757 (target_buf[x] <= 0x7e)) {
4761 target_buf[x] = '.';
4766 target_buf[x] = ' ';
4771 /* print - with a newline */
4772 command_print_sameline(NULL, "%s\n", target_buf);
4780 static int jim_target_mem2array(Jim_Interp *interp,
4781 int argc, Jim_Obj *const *argv)
4783 struct target *target = Jim_CmdPrivData(interp);
4784 return target_mem2array(interp, target, argc - 1, argv + 1);
4787 static int jim_target_array2mem(Jim_Interp *interp,
4788 int argc, Jim_Obj *const *argv)
4790 struct target *target = Jim_CmdPrivData(interp);
4791 return target_array2mem(interp, target, argc - 1, argv + 1);
4794 static int jim_target_tap_disabled(Jim_Interp *interp)
4796 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4800 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4803 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4806 struct target *target = Jim_CmdPrivData(interp);
4807 if (!target->tap->enabled)
4808 return jim_target_tap_disabled(interp);
4810 int e = target->type->examine(target);
4816 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4819 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4822 struct target *target = Jim_CmdPrivData(interp);
4824 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4830 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4833 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4836 struct target *target = Jim_CmdPrivData(interp);
4837 if (!target->tap->enabled)
4838 return jim_target_tap_disabled(interp);
4841 if (!(target_was_examined(target)))
4842 e = ERROR_TARGET_NOT_EXAMINED;
4844 e = target->type->poll(target);
4850 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4853 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4855 if (goi.argc != 2) {
4856 Jim_WrongNumArgs(interp, 0, argv,
4857 "([tT]|[fF]|assert|deassert) BOOL");
4862 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4864 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4867 /* the halt or not param */
4869 e = Jim_GetOpt_Wide(&goi, &a);
4873 struct target *target = Jim_CmdPrivData(goi.interp);
4874 if (!target->tap->enabled)
4875 return jim_target_tap_disabled(interp);
4876 if (!(target_was_examined(target))) {
4877 LOG_ERROR("Target not examined yet");
4878 return ERROR_TARGET_NOT_EXAMINED;
4880 if (!target->type->assert_reset || !target->type->deassert_reset) {
4881 Jim_SetResultFormatted(interp,
4882 "No target-specific reset for %s",
4883 target_name(target));
4886 /* determine if we should halt or not. */
4887 target->reset_halt = !!a;
4888 /* When this happens - all workareas are invalid. */
4889 target_free_all_working_areas_restore(target, 0);
4892 if (n->value == NVP_ASSERT)
4893 e = target->type->assert_reset(target);
4895 e = target->type->deassert_reset(target);
4896 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4899 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4902 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4905 struct target *target = Jim_CmdPrivData(interp);
4906 if (!target->tap->enabled)
4907 return jim_target_tap_disabled(interp);
4908 int e = target->type->halt(target);
4909 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4912 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4915 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4917 /* params: <name> statename timeoutmsecs */
4918 if (goi.argc != 2) {
4919 const char *cmd_name = Jim_GetString(argv[0], NULL);
4920 Jim_SetResultFormatted(goi.interp,
4921 "%s <state_name> <timeout_in_msec>", cmd_name);
4926 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4928 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
4932 e = Jim_GetOpt_Wide(&goi, &a);
4935 struct target *target = Jim_CmdPrivData(interp);
4936 if (!target->tap->enabled)
4937 return jim_target_tap_disabled(interp);
4939 e = target_wait_state(target, n->value, a);
4940 if (e != ERROR_OK) {
4941 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4942 Jim_SetResultFormatted(goi.interp,
4943 "target: %s wait %s fails (%#s) %s",
4944 target_name(target), n->name,
4945 eObj, target_strerror_safe(e));
4946 Jim_FreeNewObj(interp, eObj);
4951 /* List for human, Events defined for this target.
4952 * scripts/programs should use 'name cget -event NAME'
4954 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4956 struct command_context *cmd_ctx = current_command_context(interp);
4957 assert(cmd_ctx != NULL);
4959 struct target *target = Jim_CmdPrivData(interp);
4960 struct target_event_action *teap = target->event_action;
4961 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4962 target->target_number,
4963 target_name(target));
4964 command_print(cmd_ctx, "%-25s | Body", "Event");
4965 command_print(cmd_ctx, "------------------------- | "
4966 "----------------------------------------");
4968 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4969 command_print(cmd_ctx, "%-25s | %s",
4970 opt->name, Jim_GetString(teap->body, NULL));
4973 command_print(cmd_ctx, "***END***");
4976 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4979 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4982 struct target *target = Jim_CmdPrivData(interp);
4983 Jim_SetResultString(interp, target_state_name(target), -1);
4986 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4989 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4990 if (goi.argc != 1) {
4991 const char *cmd_name = Jim_GetString(argv[0], NULL);
4992 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4996 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4998 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
5001 struct target *target = Jim_CmdPrivData(interp);
5002 target_handle_event(target, n->value);
5006 static const struct command_registration target_instance_command_handlers[] = {
5008 .name = "configure",
5009 .mode = COMMAND_CONFIG,
5010 .jim_handler = jim_target_configure,
5011 .help = "configure a new target for use",
5012 .usage = "[target_attribute ...]",
5016 .mode = COMMAND_ANY,
5017 .jim_handler = jim_target_configure,
5018 .help = "returns the specified target attribute",
5019 .usage = "target_attribute",
5023 .mode = COMMAND_EXEC,
5024 .jim_handler = jim_target_mw,
5025 .help = "Write 32-bit word(s) to target memory",
5026 .usage = "address data [count]",
5030 .mode = COMMAND_EXEC,
5031 .jim_handler = jim_target_mw,
5032 .help = "Write 16-bit half-word(s) to target memory",
5033 .usage = "address data [count]",
5037 .mode = COMMAND_EXEC,
5038 .jim_handler = jim_target_mw,
5039 .help = "Write byte(s) to target memory",
5040 .usage = "address data [count]",
5044 .mode = COMMAND_EXEC,
5045 .jim_handler = jim_target_md,
5046 .help = "Display target memory as 32-bit words",
5047 .usage = "address [count]",
5051 .mode = COMMAND_EXEC,
5052 .jim_handler = jim_target_md,
5053 .help = "Display target memory as 16-bit half-words",
5054 .usage = "address [count]",
5058 .mode = COMMAND_EXEC,
5059 .jim_handler = jim_target_md,
5060 .help = "Display target memory as 8-bit bytes",
5061 .usage = "address [count]",
5064 .name = "array2mem",
5065 .mode = COMMAND_EXEC,
5066 .jim_handler = jim_target_array2mem,
5067 .help = "Writes Tcl array of 8/16/32 bit numbers "
5069 .usage = "arrayname bitwidth address count",
5072 .name = "mem2array",
5073 .mode = COMMAND_EXEC,
5074 .jim_handler = jim_target_mem2array,
5075 .help = "Loads Tcl array of 8/16/32 bit numbers "
5076 "from target memory",
5077 .usage = "arrayname bitwidth address count",
5080 .name = "eventlist",
5081 .mode = COMMAND_EXEC,
5082 .jim_handler = jim_target_event_list,
5083 .help = "displays a table of events defined for this target",
5087 .mode = COMMAND_EXEC,
5088 .jim_handler = jim_target_current_state,
5089 .help = "displays the current state of this target",
5092 .name = "arp_examine",
5093 .mode = COMMAND_EXEC,
5094 .jim_handler = jim_target_examine,
5095 .help = "used internally for reset processing",
5098 .name = "arp_halt_gdb",
5099 .mode = COMMAND_EXEC,
5100 .jim_handler = jim_target_halt_gdb,
5101 .help = "used internally for reset processing to halt GDB",
5105 .mode = COMMAND_EXEC,
5106 .jim_handler = jim_target_poll,
5107 .help = "used internally for reset processing",
5110 .name = "arp_reset",
5111 .mode = COMMAND_EXEC,
5112 .jim_handler = jim_target_reset,
5113 .help = "used internally for reset processing",
5117 .mode = COMMAND_EXEC,
5118 .jim_handler = jim_target_halt,
5119 .help = "used internally for reset processing",
5122 .name = "arp_waitstate",
5123 .mode = COMMAND_EXEC,
5124 .jim_handler = jim_target_wait_state,
5125 .help = "used internally for reset processing",
5128 .name = "invoke-event",
5129 .mode = COMMAND_EXEC,
5130 .jim_handler = jim_target_invoke_event,
5131 .help = "invoke handler for specified event",
5132 .usage = "event_name",
5134 COMMAND_REGISTRATION_DONE
5137 static int target_create(Jim_GetOptInfo *goi)
5145 struct target *target;
5146 struct command_context *cmd_ctx;
5148 cmd_ctx = current_command_context(goi->interp);
5149 assert(cmd_ctx != NULL);
5151 if (goi->argc < 3) {
5152 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5157 Jim_GetOpt_Obj(goi, &new_cmd);
5158 /* does this command exist? */
5159 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
5161 cp = Jim_GetString(new_cmd, NULL);
5162 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5167 e = Jim_GetOpt_String(goi, &cp2, NULL);
5171 struct transport *tr = get_current_transport();
5172 if (tr->override_target) {
5173 e = tr->override_target(&cp);
5174 if (e != ERROR_OK) {
5175 LOG_ERROR("The selected transport doesn't support this target");
5178 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5180 /* now does target type exist */
5181 for (x = 0 ; target_types[x] ; x++) {
5182 if (0 == strcmp(cp, target_types[x]->name)) {
5187 /* check for deprecated name */
5188 if (target_types[x]->deprecated_name) {
5189 if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
5191 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
5196 if (target_types[x] == NULL) {
5197 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5198 for (x = 0 ; target_types[x] ; x++) {
5199 if (target_types[x + 1]) {
5200 Jim_AppendStrings(goi->interp,
5201 Jim_GetResult(goi->interp),
5202 target_types[x]->name,
5205 Jim_AppendStrings(goi->interp,
5206 Jim_GetResult(goi->interp),
5208 target_types[x]->name, NULL);
5215 target = calloc(1, sizeof(struct target));
5216 /* set target number */
5217 target->target_number = new_target_number();
5218 cmd_ctx->current_target = target->target_number;
5220 /* allocate memory for each unique target type */
5221 target->type = calloc(1, sizeof(struct target_type));
5223 memcpy(target->type, target_types[x], sizeof(struct target_type));
5225 /* will be set by "-endian" */
5226 target->endianness = TARGET_ENDIAN_UNKNOWN;
5228 /* default to first core, override with -coreid */
5231 target->working_area = 0x0;
5232 target->working_area_size = 0x0;
5233 target->working_areas = NULL;
5234 target->backup_working_area = 0;
5236 target->state = TARGET_UNKNOWN;
5237 target->debug_reason = DBG_REASON_UNDEFINED;
5238 target->reg_cache = NULL;
5239 target->breakpoints = NULL;
5240 target->watchpoints = NULL;
5241 target->next = NULL;
5242 target->arch_info = NULL;
5244 target->display = 1;
5246 target->halt_issued = false;
5248 /* initialize trace information */
5249 target->trace_info = malloc(sizeof(struct trace));
5250 target->trace_info->num_trace_points = 0;
5251 target->trace_info->trace_points_size = 0;
5252 target->trace_info->trace_points = NULL;
5253 target->trace_info->trace_history_size = 0;
5254 target->trace_info->trace_history = NULL;
5255 target->trace_info->trace_history_pos = 0;
5256 target->trace_info->trace_history_overflowed = 0;
5258 target->dbgmsg = NULL;
5259 target->dbg_msg_enabled = 0;
5261 target->endianness = TARGET_ENDIAN_UNKNOWN;
5263 target->rtos = NULL;
5264 target->rtos_auto_detect = false;
5266 /* Do the rest as "configure" options */
5267 goi->isconfigure = 1;
5268 e = target_configure(goi, target);
5270 if (target->tap == NULL) {
5271 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
5281 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5282 /* default endian to little if not specified */
5283 target->endianness = TARGET_LITTLE_ENDIAN;
5286 cp = Jim_GetString(new_cmd, NULL);
5287 target->cmd_name = strdup(cp);
5289 /* create the target specific commands */
5290 if (target->type->commands) {
5291 e = register_commands(cmd_ctx, NULL, target->type->commands);
5293 LOG_ERROR("unable to register '%s' commands", cp);
5295 if (target->type->target_create)
5296 (*(target->type->target_create))(target, goi->interp);
5298 /* append to end of list */
5300 struct target **tpp;
5301 tpp = &(all_targets);
5303 tpp = &((*tpp)->next);
5307 /* now - create the new target name command */
5308 const struct command_registration target_subcommands[] = {
5310 .chain = target_instance_command_handlers,
5313 .chain = target->type->commands,
5315 COMMAND_REGISTRATION_DONE
5317 const struct command_registration target_commands[] = {
5320 .mode = COMMAND_ANY,
5321 .help = "target command group",
5323 .chain = target_subcommands,
5325 COMMAND_REGISTRATION_DONE
5327 e = register_commands(cmd_ctx, NULL, target_commands);
5331 struct command *c = command_find_in_context(cmd_ctx, cp);
5333 command_set_handler_data(c, target);
5335 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5338 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5341 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5344 struct command_context *cmd_ctx = current_command_context(interp);
5345 assert(cmd_ctx != NULL);
5347 Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5351 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5354 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5357 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5358 for (unsigned x = 0; NULL != target_types[x]; x++) {
5359 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5360 Jim_NewStringObj(interp, target_types[x]->name, -1));
5365 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5368 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5371 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5372 struct target *target = all_targets;
5374 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5375 Jim_NewStringObj(interp, target_name(target), -1));
5376 target = target->next;
5381 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5384 const char *targetname;
5386 struct target *target = (struct target *) NULL;
5387 struct target_list *head, *curr, *new;
5388 curr = (struct target_list *) NULL;
5389 head = (struct target_list *) NULL;
5392 LOG_DEBUG("%d", argc);
5393 /* argv[1] = target to associate in smp
5394 * argv[2] = target to assoicate in smp
5398 for (i = 1; i < argc; i++) {
5400 targetname = Jim_GetString(argv[i], &len);
5401 target = get_target(targetname);
5402 LOG_DEBUG("%s ", targetname);
5404 new = malloc(sizeof(struct target_list));
5405 new->target = target;
5406 new->next = (struct target_list *)NULL;
5407 if (head == (struct target_list *)NULL) {
5416 /* now parse the list of cpu and put the target in smp mode*/
5419 while (curr != (struct target_list *)NULL) {
5420 target = curr->target;
5422 target->head = head;
5426 if (target && target->rtos)
5427 retval = rtos_smp_init(head->target);
5433 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5436 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5438 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5439 "<name> <target_type> [<target_options> ...]");
5442 return target_create(&goi);
5445 static const struct command_registration target_subcommand_handlers[] = {
5448 .mode = COMMAND_CONFIG,
5449 .handler = handle_target_init_command,
5450 .help = "initialize targets",
5454 /* REVISIT this should be COMMAND_CONFIG ... */
5455 .mode = COMMAND_ANY,
5456 .jim_handler = jim_target_create,
5457 .usage = "name type '-chain-position' name [options ...]",
5458 .help = "Creates and selects a new target",
5462 .mode = COMMAND_ANY,
5463 .jim_handler = jim_target_current,
5464 .help = "Returns the currently selected target",
5468 .mode = COMMAND_ANY,
5469 .jim_handler = jim_target_types,
5470 .help = "Returns the available target types as "
5471 "a list of strings",
5475 .mode = COMMAND_ANY,
5476 .jim_handler = jim_target_names,
5477 .help = "Returns the names of all targets as a list of strings",
5481 .mode = COMMAND_ANY,
5482 .jim_handler = jim_target_smp,
5483 .usage = "targetname1 targetname2 ...",
5484 .help = "gather several target in a smp list"
5487 COMMAND_REGISTRATION_DONE
5497 static int fastload_num;
5498 static struct FastLoad *fastload;
5500 static void free_fastload(void)
5502 if (fastload != NULL) {
5504 for (i = 0; i < fastload_num; i++) {
5505 if (fastload[i].data)
5506 free(fastload[i].data);
5513 COMMAND_HANDLER(handle_fast_load_image_command)
5517 uint32_t image_size;
5518 uint32_t min_address = 0;
5519 uint32_t max_address = 0xffffffff;
5524 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5525 &image, &min_address, &max_address);
5526 if (ERROR_OK != retval)
5529 struct duration bench;
5530 duration_start(&bench);
5532 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5533 if (retval != ERROR_OK)
5538 fastload_num = image.num_sections;
5539 fastload = malloc(sizeof(struct FastLoad)*image.num_sections);
5540 if (fastload == NULL) {
5541 command_print(CMD_CTX, "out of memory");
5542 image_close(&image);
5545 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5546 for (i = 0; i < image.num_sections; i++) {
5547 buffer = malloc(image.sections[i].size);
5548 if (buffer == NULL) {
5549 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5550 (int)(image.sections[i].size));
5551 retval = ERROR_FAIL;
5555 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5556 if (retval != ERROR_OK) {
5561 uint32_t offset = 0;
5562 uint32_t length = buf_cnt;
5564 /* DANGER!!! beware of unsigned comparision here!!! */
5566 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5567 (image.sections[i].base_address < max_address)) {
5568 if (image.sections[i].base_address < min_address) {
5569 /* clip addresses below */
5570 offset += min_address-image.sections[i].base_address;
5574 if (image.sections[i].base_address + buf_cnt > max_address)
5575 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5577 fastload[i].address = image.sections[i].base_address + offset;
5578 fastload[i].data = malloc(length);
5579 if (fastload[i].data == NULL) {
5581 command_print(CMD_CTX, "error allocating buffer for section (%" PRIu32 " bytes)",
5583 retval = ERROR_FAIL;
5586 memcpy(fastload[i].data, buffer + offset, length);
5587 fastload[i].length = length;
5589 image_size += length;
5590 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5591 (unsigned int)length,
5592 ((unsigned int)(image.sections[i].base_address + offset)));
5598 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5599 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5600 "in %fs (%0.3f KiB/s)", image_size,
5601 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5603 command_print(CMD_CTX,
5604 "WARNING: image has not been loaded to target!"
5605 "You can issue a 'fast_load' to finish loading.");
5608 image_close(&image);
5610 if (retval != ERROR_OK)
5616 COMMAND_HANDLER(handle_fast_load_command)
5619 return ERROR_COMMAND_SYNTAX_ERROR;
5620 if (fastload == NULL) {
5621 LOG_ERROR("No image in memory");
5625 int ms = timeval_ms();
5627 int retval = ERROR_OK;
5628 for (i = 0; i < fastload_num; i++) {
5629 struct target *target = get_current_target(CMD_CTX);
5630 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5631 (unsigned int)(fastload[i].address),
5632 (unsigned int)(fastload[i].length));
5633 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5634 if (retval != ERROR_OK)
5636 size += fastload[i].length;
5638 if (retval == ERROR_OK) {
5639 int after = timeval_ms();
5640 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5645 static const struct command_registration target_command_handlers[] = {
5648 .handler = handle_targets_command,
5649 .mode = COMMAND_ANY,
5650 .help = "change current default target (one parameter) "
5651 "or prints table of all targets (no parameters)",
5652 .usage = "[target]",
5656 .mode = COMMAND_CONFIG,
5657 .help = "configure target",
5659 .chain = target_subcommand_handlers,
5661 COMMAND_REGISTRATION_DONE
5664 int target_register_commands(struct command_context *cmd_ctx)
5666 return register_commands(cmd_ctx, NULL, target_command_handlers);
5669 static bool target_reset_nag = true;
5671 bool get_target_reset_nag(void)
5673 return target_reset_nag;
5676 COMMAND_HANDLER(handle_target_reset_nag)
5678 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5679 &target_reset_nag, "Nag after each reset about options to improve "
5683 COMMAND_HANDLER(handle_ps_command)
5685 struct target *target = get_current_target(CMD_CTX);
5687 if (target->state != TARGET_HALTED) {
5688 LOG_INFO("target not halted !!");
5692 if ((target->rtos) && (target->rtos->type)
5693 && (target->rtos->type->ps_command)) {
5694 display = target->rtos->type->ps_command(target);
5695 command_print(CMD_CTX, "%s", display);
5700 return ERROR_TARGET_FAILURE;
5704 static void binprint(struct command_context *cmd_ctx, const char *text, const uint8_t *buf, int size)
5707 command_print_sameline(cmd_ctx, "%s", text);
5708 for (int i = 0; i < size; i++)
5709 command_print_sameline(cmd_ctx, " %02x", buf[i]);
5710 command_print(cmd_ctx, " ");
5713 COMMAND_HANDLER(handle_test_mem_access_command)
5715 struct target *target = get_current_target(CMD_CTX);
5717 int retval = ERROR_OK;
5719 if (target->state != TARGET_HALTED) {
5720 LOG_INFO("target not halted !!");
5725 return ERROR_COMMAND_SYNTAX_ERROR;
5727 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
5730 size_t num_bytes = test_size + 4;
5732 struct working_area *wa = NULL;
5733 retval = target_alloc_working_area(target, num_bytes, &wa);
5734 if (retval != ERROR_OK) {
5735 LOG_ERROR("Not enough working area");
5739 uint8_t *test_pattern = malloc(num_bytes);
5741 for (size_t i = 0; i < num_bytes; i++)
5742 test_pattern[i] = rand();
5744 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
5745 if (retval != ERROR_OK) {
5746 LOG_ERROR("Test pattern write failed");
5750 for (int host_offset = 0; host_offset <= 1; host_offset++) {
5751 for (int size = 1; size <= 4; size *= 2) {
5752 for (int offset = 0; offset < 4; offset++) {
5753 uint32_t count = test_size / size;
5754 size_t host_bufsiz = (count + 2) * size + host_offset;
5755 uint8_t *read_ref = malloc(host_bufsiz);
5756 uint8_t *read_buf = malloc(host_bufsiz);
5758 for (size_t i = 0; i < host_bufsiz; i++) {
5759 read_ref[i] = rand();
5760 read_buf[i] = read_ref[i];
5762 command_print_sameline(CMD_CTX,
5763 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
5764 size, offset, host_offset ? "un" : "");
5766 struct duration bench;
5767 duration_start(&bench);
5769 retval = target_read_memory(target, wa->address + offset, size, count,
5770 read_buf + size + host_offset);
5772 duration_measure(&bench);
5774 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
5775 command_print(CMD_CTX, "Unsupported alignment");
5777 } else if (retval != ERROR_OK) {
5778 command_print(CMD_CTX, "Memory read failed");
5782 /* replay on host */
5783 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
5786 int result = memcmp(read_ref, read_buf, host_bufsiz);
5788 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
5789 duration_elapsed(&bench),
5790 duration_kbps(&bench, count * size));
5792 command_print(CMD_CTX, "Compare failed");
5793 binprint(CMD_CTX, "ref:", read_ref, host_bufsiz);
5794 binprint(CMD_CTX, "buf:", read_buf, host_bufsiz);
5807 target_free_working_area(target, wa);
5810 num_bytes = test_size + 4 + 4 + 4;
5812 retval = target_alloc_working_area(target, num_bytes, &wa);
5813 if (retval != ERROR_OK) {
5814 LOG_ERROR("Not enough working area");
5818 test_pattern = malloc(num_bytes);
5820 for (size_t i = 0; i < num_bytes; i++)
5821 test_pattern[i] = rand();
5823 for (int host_offset = 0; host_offset <= 1; host_offset++) {
5824 for (int size = 1; size <= 4; size *= 2) {
5825 for (int offset = 0; offset < 4; offset++) {
5826 uint32_t count = test_size / size;
5827 size_t host_bufsiz = count * size + host_offset;
5828 uint8_t *read_ref = malloc(num_bytes);
5829 uint8_t *read_buf = malloc(num_bytes);
5830 uint8_t *write_buf = malloc(host_bufsiz);
5832 for (size_t i = 0; i < host_bufsiz; i++)
5833 write_buf[i] = rand();
5834 command_print_sameline(CMD_CTX,
5835 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
5836 size, offset, host_offset ? "un" : "");
5838 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
5839 if (retval != ERROR_OK) {
5840 command_print(CMD_CTX, "Test pattern write failed");
5844 /* replay on host */
5845 memcpy(read_ref, test_pattern, num_bytes);
5846 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
5848 struct duration bench;
5849 duration_start(&bench);
5851 retval = target_write_memory(target, wa->address + size + offset, size, count,
5852 write_buf + host_offset);
5854 duration_measure(&bench);
5856 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
5857 command_print(CMD_CTX, "Unsupported alignment");
5859 } else if (retval != ERROR_OK) {
5860 command_print(CMD_CTX, "Memory write failed");
5865 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
5866 if (retval != ERROR_OK) {
5867 command_print(CMD_CTX, "Test pattern write failed");
5872 int result = memcmp(read_ref, read_buf, num_bytes);
5874 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
5875 duration_elapsed(&bench),
5876 duration_kbps(&bench, count * size));
5878 command_print(CMD_CTX, "Compare failed");
5879 binprint(CMD_CTX, "ref:", read_ref, num_bytes);
5880 binprint(CMD_CTX, "buf:", read_buf, num_bytes);
5892 target_free_working_area(target, wa);
5896 static const struct command_registration target_exec_command_handlers[] = {
5898 .name = "fast_load_image",
5899 .handler = handle_fast_load_image_command,
5900 .mode = COMMAND_ANY,
5901 .help = "Load image into server memory for later use by "
5902 "fast_load; primarily for profiling",
5903 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5904 "[min_address [max_length]]",
5907 .name = "fast_load",
5908 .handler = handle_fast_load_command,
5909 .mode = COMMAND_EXEC,
5910 .help = "loads active fast load image to current target "
5911 "- mainly for profiling purposes",
5916 .handler = handle_profile_command,
5917 .mode = COMMAND_EXEC,
5918 .usage = "seconds filename [start end]",
5919 .help = "profiling samples the CPU PC",
5921 /** @todo don't register virt2phys() unless target supports it */
5923 .name = "virt2phys",
5924 .handler = handle_virt2phys_command,
5925 .mode = COMMAND_ANY,
5926 .help = "translate a virtual address into a physical address",
5927 .usage = "virtual_address",
5931 .handler = handle_reg_command,
5932 .mode = COMMAND_EXEC,
5933 .help = "display (reread from target with \"force\") or set a register; "
5934 "with no arguments, displays all registers and their values",
5935 .usage = "[(register_number|register_name) [(value|'force')]]",
5939 .handler = handle_poll_command,
5940 .mode = COMMAND_EXEC,
5941 .help = "poll target state; or reconfigure background polling",
5942 .usage = "['on'|'off']",
5945 .name = "wait_halt",
5946 .handler = handle_wait_halt_command,
5947 .mode = COMMAND_EXEC,
5948 .help = "wait up to the specified number of milliseconds "
5949 "(default 5000) for a previously requested halt",
5950 .usage = "[milliseconds]",
5954 .handler = handle_halt_command,
5955 .mode = COMMAND_EXEC,
5956 .help = "request target to halt, then wait up to the specified"
5957 "number of milliseconds (default 5000) for it to complete",
5958 .usage = "[milliseconds]",
5962 .handler = handle_resume_command,
5963 .mode = COMMAND_EXEC,
5964 .help = "resume target execution from current PC or address",
5965 .usage = "[address]",
5969 .handler = handle_reset_command,
5970 .mode = COMMAND_EXEC,
5971 .usage = "[run|halt|init]",
5972 .help = "Reset all targets into the specified mode."
5973 "Default reset mode is run, if not given.",
5976 .name = "soft_reset_halt",
5977 .handler = handle_soft_reset_halt_command,
5978 .mode = COMMAND_EXEC,
5980 .help = "halt the target and do a soft reset",
5984 .handler = handle_step_command,
5985 .mode = COMMAND_EXEC,
5986 .help = "step one instruction from current PC or address",
5987 .usage = "[address]",
5991 .handler = handle_md_command,
5992 .mode = COMMAND_EXEC,
5993 .help = "display memory words",
5994 .usage = "['phys'] address [count]",
5998 .handler = handle_md_command,
5999 .mode = COMMAND_EXEC,
6000 .help = "display memory half-words",
6001 .usage = "['phys'] address [count]",
6005 .handler = handle_md_command,
6006 .mode = COMMAND_EXEC,
6007 .help = "display memory bytes",
6008 .usage = "['phys'] address [count]",
6012 .handler = handle_mw_command,
6013 .mode = COMMAND_EXEC,
6014 .help = "write memory word",
6015 .usage = "['phys'] address value [count]",
6019 .handler = handle_mw_command,
6020 .mode = COMMAND_EXEC,
6021 .help = "write memory half-word",
6022 .usage = "['phys'] address value [count]",
6026 .handler = handle_mw_command,
6027 .mode = COMMAND_EXEC,
6028 .help = "write memory byte",
6029 .usage = "['phys'] address value [count]",
6033 .handler = handle_bp_command,
6034 .mode = COMMAND_EXEC,
6035 .help = "list or set hardware or software breakpoint",
6036 .usage = "<address> [<asid>]<length> ['hw'|'hw_ctx']",
6040 .handler = handle_rbp_command,
6041 .mode = COMMAND_EXEC,
6042 .help = "remove breakpoint",
6047 .handler = handle_wp_command,
6048 .mode = COMMAND_EXEC,
6049 .help = "list (no params) or create watchpoints",
6050 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
6054 .handler = handle_rwp_command,
6055 .mode = COMMAND_EXEC,
6056 .help = "remove watchpoint",
6060 .name = "load_image",
6061 .handler = handle_load_image_command,
6062 .mode = COMMAND_EXEC,
6063 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6064 "[min_address] [max_length]",
6067 .name = "dump_image",
6068 .handler = handle_dump_image_command,
6069 .mode = COMMAND_EXEC,
6070 .usage = "filename address size",
6073 .name = "verify_image",
6074 .handler = handle_verify_image_command,
6075 .mode = COMMAND_EXEC,
6076 .usage = "filename [offset [type]]",
6079 .name = "test_image",
6080 .handler = handle_test_image_command,
6081 .mode = COMMAND_EXEC,
6082 .usage = "filename [offset [type]]",
6085 .name = "mem2array",
6086 .mode = COMMAND_EXEC,
6087 .jim_handler = jim_mem2array,
6088 .help = "read 8/16/32 bit memory and return as a TCL array "
6089 "for script processing",
6090 .usage = "arrayname bitwidth address count",
6093 .name = "array2mem",
6094 .mode = COMMAND_EXEC,
6095 .jim_handler = jim_array2mem,
6096 .help = "convert a TCL array to memory locations "
6097 "and write the 8/16/32 bit values",
6098 .usage = "arrayname bitwidth address count",
6101 .name = "reset_nag",
6102 .handler = handle_target_reset_nag,
6103 .mode = COMMAND_ANY,
6104 .help = "Nag after each reset about options that could have been "
6105 "enabled to improve performance. ",
6106 .usage = "['enable'|'disable']",
6110 .handler = handle_ps_command,
6111 .mode = COMMAND_EXEC,
6112 .help = "list all tasks ",
6116 .name = "test_mem_access",
6117 .handler = handle_test_mem_access_command,
6118 .mode = COMMAND_EXEC,
6119 .help = "Test the target's memory access functions",
6123 COMMAND_REGISTRATION_DONE
6125 static int target_register_user_commands(struct command_context *cmd_ctx)
6127 int retval = ERROR_OK;
6128 retval = target_request_register_commands(cmd_ctx);
6129 if (retval != ERROR_OK)
6132 retval = trace_register_commands(cmd_ctx);
6133 if (retval != ERROR_OK)
6137 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);