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 return target->type->examine(target);
691 static int jtag_enable_callback(enum jtag_event event, void *priv)
693 struct target *target = priv;
695 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
698 jtag_unregister_event_callback(jtag_enable_callback, target);
700 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
702 int retval = target_examine_one(target);
703 if (retval != ERROR_OK)
706 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
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 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
731 retval = target_examine_one(target);
732 if (retval != ERROR_OK)
735 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
740 const char *target_type_name(struct target *target)
742 return target->type->name;
745 static int target_soft_reset_halt(struct target *target)
747 if (!target_was_examined(target)) {
748 LOG_ERROR("Target not examined yet");
751 if (!target->type->soft_reset_halt) {
752 LOG_ERROR("Target %s does not support soft_reset_halt",
753 target_name(target));
756 return target->type->soft_reset_halt(target);
760 * Downloads a target-specific native code algorithm to the target,
761 * and executes it. * Note that some targets may need to set up, enable,
762 * and tear down a breakpoint (hard or * soft) to detect algorithm
763 * termination, while others may support lower overhead schemes where
764 * soft breakpoints embedded in the algorithm automatically terminate the
767 * @param target used to run the algorithm
768 * @param arch_info target-specific description of the algorithm.
770 int target_run_algorithm(struct target *target,
771 int num_mem_params, struct mem_param *mem_params,
772 int num_reg_params, struct reg_param *reg_param,
773 uint32_t entry_point, uint32_t exit_point,
774 int timeout_ms, void *arch_info)
776 int retval = ERROR_FAIL;
778 if (!target_was_examined(target)) {
779 LOG_ERROR("Target not examined yet");
782 if (!target->type->run_algorithm) {
783 LOG_ERROR("Target type '%s' does not support %s",
784 target_type_name(target), __func__);
788 target->running_alg = true;
789 retval = target->type->run_algorithm(target,
790 num_mem_params, mem_params,
791 num_reg_params, reg_param,
792 entry_point, exit_point, timeout_ms, arch_info);
793 target->running_alg = false;
800 * Downloads a target-specific native code algorithm to the target,
801 * executes and leaves it running.
803 * @param target used to run the algorithm
804 * @param arch_info target-specific description of the algorithm.
806 int target_start_algorithm(struct target *target,
807 int num_mem_params, struct mem_param *mem_params,
808 int num_reg_params, struct reg_param *reg_params,
809 uint32_t entry_point, uint32_t exit_point,
812 int retval = ERROR_FAIL;
814 if (!target_was_examined(target)) {
815 LOG_ERROR("Target not examined yet");
818 if (!target->type->start_algorithm) {
819 LOG_ERROR("Target type '%s' does not support %s",
820 target_type_name(target), __func__);
823 if (target->running_alg) {
824 LOG_ERROR("Target is already running an algorithm");
828 target->running_alg = true;
829 retval = target->type->start_algorithm(target,
830 num_mem_params, mem_params,
831 num_reg_params, reg_params,
832 entry_point, exit_point, arch_info);
839 * Waits for an algorithm started with target_start_algorithm() to complete.
841 * @param target used to run the algorithm
842 * @param arch_info target-specific description of the algorithm.
844 int target_wait_algorithm(struct target *target,
845 int num_mem_params, struct mem_param *mem_params,
846 int num_reg_params, struct reg_param *reg_params,
847 uint32_t exit_point, int timeout_ms,
850 int retval = ERROR_FAIL;
852 if (!target->type->wait_algorithm) {
853 LOG_ERROR("Target type '%s' does not support %s",
854 target_type_name(target), __func__);
857 if (!target->running_alg) {
858 LOG_ERROR("Target is not running an algorithm");
862 retval = target->type->wait_algorithm(target,
863 num_mem_params, mem_params,
864 num_reg_params, reg_params,
865 exit_point, timeout_ms, arch_info);
866 if (retval != ERROR_TARGET_TIMEOUT)
867 target->running_alg = false;
874 * Executes a target-specific native code algorithm in the target.
875 * It differs from target_run_algorithm in that the algorithm is asynchronous.
876 * Because of this it requires an compliant algorithm:
877 * see contrib/loaders/flash/stm32f1x.S for example.
879 * @param target used to run the algorithm
882 int target_run_flash_async_algorithm(struct target *target,
883 const uint8_t *buffer, uint32_t count, int block_size,
884 int num_mem_params, struct mem_param *mem_params,
885 int num_reg_params, struct reg_param *reg_params,
886 uint32_t buffer_start, uint32_t buffer_size,
887 uint32_t entry_point, uint32_t exit_point, void *arch_info)
892 const uint8_t *buffer_orig = buffer;
894 /* Set up working area. First word is write pointer, second word is read pointer,
895 * rest is fifo data area. */
896 uint32_t wp_addr = buffer_start;
897 uint32_t rp_addr = buffer_start + 4;
898 uint32_t fifo_start_addr = buffer_start + 8;
899 uint32_t fifo_end_addr = buffer_start + buffer_size;
901 uint32_t wp = fifo_start_addr;
902 uint32_t rp = fifo_start_addr;
904 /* validate block_size is 2^n */
905 assert(!block_size || !(block_size & (block_size - 1)));
907 retval = target_write_u32(target, wp_addr, wp);
908 if (retval != ERROR_OK)
910 retval = target_write_u32(target, rp_addr, rp);
911 if (retval != ERROR_OK)
914 /* Start up algorithm on target and let it idle while writing the first chunk */
915 retval = target_start_algorithm(target, num_mem_params, mem_params,
916 num_reg_params, reg_params,
921 if (retval != ERROR_OK) {
922 LOG_ERROR("error starting target flash write algorithm");
928 retval = target_read_u32(target, rp_addr, &rp);
929 if (retval != ERROR_OK) {
930 LOG_ERROR("failed to get read pointer");
934 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
935 (size_t) (buffer - buffer_orig), count, wp, rp);
938 LOG_ERROR("flash write algorithm aborted by target");
939 retval = ERROR_FLASH_OPERATION_FAILED;
943 if ((rp & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
944 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
948 /* Count the number of bytes available in the fifo without
949 * crossing the wrap around. Make sure to not fill it completely,
950 * because that would make wp == rp and that's the empty condition. */
951 uint32_t thisrun_bytes;
953 thisrun_bytes = rp - wp - block_size;
954 else if (rp > fifo_start_addr)
955 thisrun_bytes = fifo_end_addr - wp;
957 thisrun_bytes = fifo_end_addr - wp - block_size;
959 if (thisrun_bytes == 0) {
960 /* Throttle polling a bit if transfer is (much) faster than flash
961 * programming. The exact delay shouldn't matter as long as it's
962 * less than buffer size / flash speed. This is very unlikely to
963 * run when using high latency connections such as USB. */
966 /* to stop an infinite loop on some targets check and increment a timeout
967 * this issue was observed on a stellaris using the new ICDI interface */
968 if (timeout++ >= 500) {
969 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
970 return ERROR_FLASH_OPERATION_FAILED;
975 /* reset our timeout */
978 /* Limit to the amount of data we actually want to write */
979 if (thisrun_bytes > count * block_size)
980 thisrun_bytes = count * block_size;
982 /* Write data to fifo */
983 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
984 if (retval != ERROR_OK)
987 /* Update counters and wrap write pointer */
988 buffer += thisrun_bytes;
989 count -= thisrun_bytes / block_size;
991 if (wp >= fifo_end_addr)
992 wp = fifo_start_addr;
994 /* Store updated write pointer to target */
995 retval = target_write_u32(target, wp_addr, wp);
996 if (retval != ERROR_OK)
1000 if (retval != ERROR_OK) {
1001 /* abort flash write algorithm on target */
1002 target_write_u32(target, wp_addr, 0);
1005 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1006 num_reg_params, reg_params,
1011 if (retval2 != ERROR_OK) {
1012 LOG_ERROR("error waiting for target flash write algorithm");
1019 int target_read_memory(struct target *target,
1020 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1022 if (!target_was_examined(target)) {
1023 LOG_ERROR("Target not examined yet");
1026 return target->type->read_memory(target, address, size, count, buffer);
1029 int target_read_phys_memory(struct target *target,
1030 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1032 if (!target_was_examined(target)) {
1033 LOG_ERROR("Target not examined yet");
1036 return target->type->read_phys_memory(target, address, size, count, buffer);
1039 int target_write_memory(struct target *target,
1040 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1042 if (!target_was_examined(target)) {
1043 LOG_ERROR("Target not examined yet");
1046 return target->type->write_memory(target, address, size, count, buffer);
1049 int target_write_phys_memory(struct target *target,
1050 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1052 if (!target_was_examined(target)) {
1053 LOG_ERROR("Target not examined yet");
1056 return target->type->write_phys_memory(target, address, size, count, buffer);
1059 int target_add_breakpoint(struct target *target,
1060 struct breakpoint *breakpoint)
1062 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1063 LOG_WARNING("target %s is not halted", target_name(target));
1064 return ERROR_TARGET_NOT_HALTED;
1066 return target->type->add_breakpoint(target, breakpoint);
1069 int target_add_context_breakpoint(struct target *target,
1070 struct breakpoint *breakpoint)
1072 if (target->state != TARGET_HALTED) {
1073 LOG_WARNING("target %s is not halted", target_name(target));
1074 return ERROR_TARGET_NOT_HALTED;
1076 return target->type->add_context_breakpoint(target, breakpoint);
1079 int target_add_hybrid_breakpoint(struct target *target,
1080 struct breakpoint *breakpoint)
1082 if (target->state != TARGET_HALTED) {
1083 LOG_WARNING("target %s is not halted", target_name(target));
1084 return ERROR_TARGET_NOT_HALTED;
1086 return target->type->add_hybrid_breakpoint(target, breakpoint);
1089 int target_remove_breakpoint(struct target *target,
1090 struct breakpoint *breakpoint)
1092 return target->type->remove_breakpoint(target, breakpoint);
1095 int target_add_watchpoint(struct target *target,
1096 struct watchpoint *watchpoint)
1098 if (target->state != TARGET_HALTED) {
1099 LOG_WARNING("target %s is not halted", target_name(target));
1100 return ERROR_TARGET_NOT_HALTED;
1102 return target->type->add_watchpoint(target, watchpoint);
1104 int target_remove_watchpoint(struct target *target,
1105 struct watchpoint *watchpoint)
1107 return target->type->remove_watchpoint(target, watchpoint);
1109 int target_hit_watchpoint(struct target *target,
1110 struct watchpoint **hit_watchpoint)
1112 if (target->state != TARGET_HALTED) {
1113 LOG_WARNING("target %s is not halted", target->cmd_name);
1114 return ERROR_TARGET_NOT_HALTED;
1117 if (target->type->hit_watchpoint == NULL) {
1118 /* For backward compatible, if hit_watchpoint is not implemented,
1119 * return ERROR_FAIL such that gdb_server will not take the nonsense
1124 return target->type->hit_watchpoint(target, hit_watchpoint);
1127 int target_get_gdb_reg_list(struct target *target,
1128 struct reg **reg_list[], int *reg_list_size,
1129 enum target_register_class reg_class)
1131 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1133 int target_step(struct target *target,
1134 int current, uint32_t address, int handle_breakpoints)
1136 return target->type->step(target, current, address, handle_breakpoints);
1139 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1141 if (target->state != TARGET_HALTED) {
1142 LOG_WARNING("target %s is not halted", target->cmd_name);
1143 return ERROR_TARGET_NOT_HALTED;
1145 return target->type->get_gdb_fileio_info(target, fileio_info);
1148 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1150 if (target->state != TARGET_HALTED) {
1151 LOG_WARNING("target %s is not halted", target->cmd_name);
1152 return ERROR_TARGET_NOT_HALTED;
1154 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1157 int target_profiling(struct target *target, uint32_t *samples,
1158 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1160 if (target->state != TARGET_HALTED) {
1161 LOG_WARNING("target %s is not halted", target->cmd_name);
1162 return ERROR_TARGET_NOT_HALTED;
1164 return target->type->profiling(target, samples, max_num_samples,
1165 num_samples, seconds);
1169 * Reset the @c examined flag for the given target.
1170 * Pure paranoia -- targets are zeroed on allocation.
1172 static void target_reset_examined(struct target *target)
1174 target->examined = false;
1177 static int err_read_phys_memory(struct target *target, uint32_t address,
1178 uint32_t size, uint32_t count, uint8_t *buffer)
1180 LOG_ERROR("Not implemented: %s", __func__);
1184 static int err_write_phys_memory(struct target *target, uint32_t address,
1185 uint32_t size, uint32_t count, const uint8_t *buffer)
1187 LOG_ERROR("Not implemented: %s", __func__);
1191 static int handle_target(void *priv);
1193 static int target_init_one(struct command_context *cmd_ctx,
1194 struct target *target)
1196 target_reset_examined(target);
1198 struct target_type *type = target->type;
1199 if (type->examine == NULL)
1200 type->examine = default_examine;
1202 if (type->check_reset == NULL)
1203 type->check_reset = default_check_reset;
1205 assert(type->init_target != NULL);
1207 int retval = type->init_target(cmd_ctx, target);
1208 if (ERROR_OK != retval) {
1209 LOG_ERROR("target '%s' init failed", target_name(target));
1213 /* Sanity-check MMU support ... stub in what we must, to help
1214 * implement it in stages, but warn if we need to do so.
1217 if (type->write_phys_memory == NULL) {
1218 LOG_ERROR("type '%s' is missing write_phys_memory",
1220 type->write_phys_memory = err_write_phys_memory;
1222 if (type->read_phys_memory == NULL) {
1223 LOG_ERROR("type '%s' is missing read_phys_memory",
1225 type->read_phys_memory = err_read_phys_memory;
1227 if (type->virt2phys == NULL) {
1228 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1229 type->virt2phys = identity_virt2phys;
1232 /* Make sure no-MMU targets all behave the same: make no
1233 * distinction between physical and virtual addresses, and
1234 * ensure that virt2phys() is always an identity mapping.
1236 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1237 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1240 type->write_phys_memory = type->write_memory;
1241 type->read_phys_memory = type->read_memory;
1242 type->virt2phys = identity_virt2phys;
1245 if (target->type->read_buffer == NULL)
1246 target->type->read_buffer = target_read_buffer_default;
1248 if (target->type->write_buffer == NULL)
1249 target->type->write_buffer = target_write_buffer_default;
1251 if (target->type->get_gdb_fileio_info == NULL)
1252 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1254 if (target->type->gdb_fileio_end == NULL)
1255 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1257 if (target->type->profiling == NULL)
1258 target->type->profiling = target_profiling_default;
1263 static int target_init(struct command_context *cmd_ctx)
1265 struct target *target;
1268 for (target = all_targets; target; target = target->next) {
1269 retval = target_init_one(cmd_ctx, target);
1270 if (ERROR_OK != retval)
1277 retval = target_register_user_commands(cmd_ctx);
1278 if (ERROR_OK != retval)
1281 retval = target_register_timer_callback(&handle_target,
1282 polling_interval, 1, cmd_ctx->interp);
1283 if (ERROR_OK != retval)
1289 COMMAND_HANDLER(handle_target_init_command)
1294 return ERROR_COMMAND_SYNTAX_ERROR;
1296 static bool target_initialized;
1297 if (target_initialized) {
1298 LOG_INFO("'target init' has already been called");
1301 target_initialized = true;
1303 retval = command_run_line(CMD_CTX, "init_targets");
1304 if (ERROR_OK != retval)
1307 retval = command_run_line(CMD_CTX, "init_target_events");
1308 if (ERROR_OK != retval)
1311 retval = command_run_line(CMD_CTX, "init_board");
1312 if (ERROR_OK != retval)
1315 LOG_DEBUG("Initializing targets...");
1316 return target_init(CMD_CTX);
1319 int target_register_event_callback(int (*callback)(struct target *target,
1320 enum target_event event, void *priv), void *priv)
1322 struct target_event_callback **callbacks_p = &target_event_callbacks;
1324 if (callback == NULL)
1325 return ERROR_COMMAND_SYNTAX_ERROR;
1328 while ((*callbacks_p)->next)
1329 callbacks_p = &((*callbacks_p)->next);
1330 callbacks_p = &((*callbacks_p)->next);
1333 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1334 (*callbacks_p)->callback = callback;
1335 (*callbacks_p)->priv = priv;
1336 (*callbacks_p)->next = NULL;
1341 int target_register_reset_callback(int (*callback)(struct target *target,
1342 enum target_reset_mode reset_mode, void *priv), void *priv)
1344 struct target_reset_callback *entry;
1346 if (callback == NULL)
1347 return ERROR_COMMAND_SYNTAX_ERROR;
1349 entry = malloc(sizeof(struct target_reset_callback));
1350 if (entry == NULL) {
1351 LOG_ERROR("error allocating buffer for reset callback entry");
1352 return ERROR_COMMAND_SYNTAX_ERROR;
1355 entry->callback = callback;
1357 list_add(&entry->list, &target_reset_callback_list);
1363 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1365 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1368 if (callback == NULL)
1369 return ERROR_COMMAND_SYNTAX_ERROR;
1372 while ((*callbacks_p)->next)
1373 callbacks_p = &((*callbacks_p)->next);
1374 callbacks_p = &((*callbacks_p)->next);
1377 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1378 (*callbacks_p)->callback = callback;
1379 (*callbacks_p)->periodic = periodic;
1380 (*callbacks_p)->time_ms = time_ms;
1382 gettimeofday(&now, NULL);
1383 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
1384 time_ms -= (time_ms % 1000);
1385 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
1386 if ((*callbacks_p)->when.tv_usec > 1000000) {
1387 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
1388 (*callbacks_p)->when.tv_sec += 1;
1391 (*callbacks_p)->priv = priv;
1392 (*callbacks_p)->next = NULL;
1397 int target_unregister_event_callback(int (*callback)(struct target *target,
1398 enum target_event event, void *priv), void *priv)
1400 struct target_event_callback **p = &target_event_callbacks;
1401 struct target_event_callback *c = target_event_callbacks;
1403 if (callback == NULL)
1404 return ERROR_COMMAND_SYNTAX_ERROR;
1407 struct target_event_callback *next = c->next;
1408 if ((c->callback == callback) && (c->priv == priv)) {
1420 int target_unregister_reset_callback(int (*callback)(struct target *target,
1421 enum target_reset_mode reset_mode, void *priv), void *priv)
1423 struct target_reset_callback *entry;
1425 if (callback == NULL)
1426 return ERROR_COMMAND_SYNTAX_ERROR;
1428 list_for_each_entry(entry, &target_reset_callback_list, list) {
1429 if (entry->callback == callback && entry->priv == priv) {
1430 list_del(&entry->list);
1439 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1441 struct target_timer_callback **p = &target_timer_callbacks;
1442 struct target_timer_callback *c = target_timer_callbacks;
1444 if (callback == NULL)
1445 return ERROR_COMMAND_SYNTAX_ERROR;
1448 struct target_timer_callback *next = c->next;
1449 if ((c->callback == callback) && (c->priv == priv)) {
1461 int target_call_event_callbacks(struct target *target, enum target_event event)
1463 struct target_event_callback *callback = target_event_callbacks;
1464 struct target_event_callback *next_callback;
1466 if (event == TARGET_EVENT_HALTED) {
1467 /* execute early halted first */
1468 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1471 LOG_DEBUG("target event %i (%s)", event,
1472 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1474 target_handle_event(target, event);
1477 next_callback = callback->next;
1478 callback->callback(target, event, callback->priv);
1479 callback = next_callback;
1485 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1487 struct target_reset_callback *callback;
1489 LOG_DEBUG("target reset %i (%s)", reset_mode,
1490 Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name);
1492 list_for_each_entry(callback, &target_reset_callback_list, list)
1493 callback->callback(target, reset_mode, callback->priv);
1498 static int target_timer_callback_periodic_restart(
1499 struct target_timer_callback *cb, struct timeval *now)
1501 int time_ms = cb->time_ms;
1502 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1503 time_ms -= (time_ms % 1000);
1504 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1505 if (cb->when.tv_usec > 1000000) {
1506 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1507 cb->when.tv_sec += 1;
1512 static int target_call_timer_callback(struct target_timer_callback *cb,
1513 struct timeval *now)
1515 cb->callback(cb->priv);
1518 return target_timer_callback_periodic_restart(cb, now);
1520 return target_unregister_timer_callback(cb->callback, cb->priv);
1523 static int target_call_timer_callbacks_check_time(int checktime)
1528 gettimeofday(&now, NULL);
1530 struct target_timer_callback *callback = target_timer_callbacks;
1532 /* cleaning up may unregister and free this callback */
1533 struct target_timer_callback *next_callback = callback->next;
1535 bool call_it = callback->callback &&
1536 ((!checktime && callback->periodic) ||
1537 now.tv_sec > callback->when.tv_sec ||
1538 (now.tv_sec == callback->when.tv_sec &&
1539 now.tv_usec >= callback->when.tv_usec));
1542 int retval = target_call_timer_callback(callback, &now);
1543 if (retval != ERROR_OK)
1547 callback = next_callback;
1553 int target_call_timer_callbacks(void)
1555 return target_call_timer_callbacks_check_time(1);
1558 /* invoke periodic callbacks immediately */
1559 int target_call_timer_callbacks_now(void)
1561 return target_call_timer_callbacks_check_time(0);
1564 /* Prints the working area layout for debug purposes */
1565 static void print_wa_layout(struct target *target)
1567 struct working_area *c = target->working_areas;
1570 LOG_DEBUG("%c%c 0x%08"PRIx32"-0x%08"PRIx32" (%"PRIu32" bytes)",
1571 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1572 c->address, c->address + c->size - 1, c->size);
1577 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1578 static void target_split_working_area(struct working_area *area, uint32_t size)
1580 assert(area->free); /* Shouldn't split an allocated area */
1581 assert(size <= area->size); /* Caller should guarantee this */
1583 /* Split only if not already the right size */
1584 if (size < area->size) {
1585 struct working_area *new_wa = malloc(sizeof(*new_wa));
1590 new_wa->next = area->next;
1591 new_wa->size = area->size - size;
1592 new_wa->address = area->address + size;
1593 new_wa->backup = NULL;
1594 new_wa->user = NULL;
1595 new_wa->free = true;
1597 area->next = new_wa;
1600 /* If backup memory was allocated to this area, it has the wrong size
1601 * now so free it and it will be reallocated if/when needed */
1604 area->backup = NULL;
1609 /* Merge all adjacent free areas into one */
1610 static void target_merge_working_areas(struct target *target)
1612 struct working_area *c = target->working_areas;
1614 while (c && c->next) {
1615 assert(c->next->address == c->address + c->size); /* This is an invariant */
1617 /* Find two adjacent free areas */
1618 if (c->free && c->next->free) {
1619 /* Merge the last into the first */
1620 c->size += c->next->size;
1622 /* Remove the last */
1623 struct working_area *to_be_freed = c->next;
1624 c->next = c->next->next;
1625 if (to_be_freed->backup)
1626 free(to_be_freed->backup);
1629 /* If backup memory was allocated to the remaining area, it's has
1630 * the wrong size now */
1641 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1643 /* Reevaluate working area address based on MMU state*/
1644 if (target->working_areas == NULL) {
1648 retval = target->type->mmu(target, &enabled);
1649 if (retval != ERROR_OK)
1653 if (target->working_area_phys_spec) {
1654 LOG_DEBUG("MMU disabled, using physical "
1655 "address for working memory 0x%08"PRIx32,
1656 target->working_area_phys);
1657 target->working_area = target->working_area_phys;
1659 LOG_ERROR("No working memory available. "
1660 "Specify -work-area-phys to target.");
1661 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1664 if (target->working_area_virt_spec) {
1665 LOG_DEBUG("MMU enabled, using virtual "
1666 "address for working memory 0x%08"PRIx32,
1667 target->working_area_virt);
1668 target->working_area = target->working_area_virt;
1670 LOG_ERROR("No working memory available. "
1671 "Specify -work-area-virt to target.");
1672 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1676 /* Set up initial working area on first call */
1677 struct working_area *new_wa = malloc(sizeof(*new_wa));
1679 new_wa->next = NULL;
1680 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1681 new_wa->address = target->working_area;
1682 new_wa->backup = NULL;
1683 new_wa->user = NULL;
1684 new_wa->free = true;
1687 target->working_areas = new_wa;
1690 /* only allocate multiples of 4 byte */
1692 size = (size + 3) & (~3UL);
1694 struct working_area *c = target->working_areas;
1696 /* Find the first large enough working area */
1698 if (c->free && c->size >= size)
1704 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1706 /* Split the working area into the requested size */
1707 target_split_working_area(c, size);
1709 LOG_DEBUG("allocated new working area of %"PRIu32" bytes at address 0x%08"PRIx32, size, c->address);
1711 if (target->backup_working_area) {
1712 if (c->backup == NULL) {
1713 c->backup = malloc(c->size);
1714 if (c->backup == NULL)
1718 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1719 if (retval != ERROR_OK)
1723 /* mark as used, and return the new (reused) area */
1730 print_wa_layout(target);
1735 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1739 retval = target_alloc_working_area_try(target, size, area);
1740 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1741 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1746 static int target_restore_working_area(struct target *target, struct working_area *area)
1748 int retval = ERROR_OK;
1750 if (target->backup_working_area && area->backup != NULL) {
1751 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1752 if (retval != ERROR_OK)
1753 LOG_ERROR("failed to restore %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1754 area->size, area->address);
1760 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1761 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1763 int retval = ERROR_OK;
1769 retval = target_restore_working_area(target, area);
1770 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1771 if (retval != ERROR_OK)
1777 LOG_DEBUG("freed %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1778 area->size, area->address);
1780 /* mark user pointer invalid */
1781 /* TODO: Is this really safe? It points to some previous caller's memory.
1782 * How could we know that the area pointer is still in that place and not
1783 * some other vital data? What's the purpose of this, anyway? */
1787 target_merge_working_areas(target);
1789 print_wa_layout(target);
1794 int target_free_working_area(struct target *target, struct working_area *area)
1796 return target_free_working_area_restore(target, area, 1);
1799 /* free resources and restore memory, if restoring memory fails,
1800 * free up resources anyway
1802 static void target_free_all_working_areas_restore(struct target *target, int restore)
1804 struct working_area *c = target->working_areas;
1806 LOG_DEBUG("freeing all working areas");
1808 /* Loop through all areas, restoring the allocated ones and marking them as free */
1812 target_restore_working_area(target, c);
1814 *c->user = NULL; /* Same as above */
1820 /* Run a merge pass to combine all areas into one */
1821 target_merge_working_areas(target);
1823 print_wa_layout(target);
1826 void target_free_all_working_areas(struct target *target)
1828 target_free_all_working_areas_restore(target, 1);
1831 /* Find the largest number of bytes that can be allocated */
1832 uint32_t target_get_working_area_avail(struct target *target)
1834 struct working_area *c = target->working_areas;
1835 uint32_t max_size = 0;
1838 return target->working_area_size;
1841 if (c->free && max_size < c->size)
1850 int target_arch_state(struct target *target)
1853 if (target == NULL) {
1854 LOG_USER("No target has been configured");
1858 LOG_USER("target state: %s", target_state_name(target));
1860 if (target->state != TARGET_HALTED)
1863 retval = target->type->arch_state(target);
1867 static int target_get_gdb_fileio_info_default(struct target *target,
1868 struct gdb_fileio_info *fileio_info)
1870 /* If target does not support semi-hosting function, target
1871 has no need to provide .get_gdb_fileio_info callback.
1872 It just return ERROR_FAIL and gdb_server will return "Txx"
1873 as target halted every time. */
1877 static int target_gdb_fileio_end_default(struct target *target,
1878 int retcode, int fileio_errno, bool ctrl_c)
1883 static int target_profiling_default(struct target *target, uint32_t *samples,
1884 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1886 struct timeval timeout, now;
1888 gettimeofday(&timeout, NULL);
1889 timeval_add_time(&timeout, seconds, 0);
1891 LOG_INFO("Starting profiling. Halting and resuming the"
1892 " target as often as we can...");
1894 uint32_t sample_count = 0;
1895 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
1896 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
1898 int retval = ERROR_OK;
1900 target_poll(target);
1901 if (target->state == TARGET_HALTED) {
1902 uint32_t t = buf_get_u32(reg->value, 0, 32);
1903 samples[sample_count++] = t;
1904 /* current pc, addr = 0, do not handle breakpoints, not debugging */
1905 retval = target_resume(target, 1, 0, 0, 0);
1906 target_poll(target);
1907 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
1908 } else if (target->state == TARGET_RUNNING) {
1909 /* We want to quickly sample the PC. */
1910 retval = target_halt(target);
1912 LOG_INFO("Target not halted or running");
1917 if (retval != ERROR_OK)
1920 gettimeofday(&now, NULL);
1921 if ((sample_count >= max_num_samples) ||
1922 ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec))) {
1923 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
1928 *num_samples = sample_count;
1932 /* Single aligned words are guaranteed to use 16 or 32 bit access
1933 * mode respectively, otherwise data is handled as quickly as
1936 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1938 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1939 (int)size, (unsigned)address);
1941 if (!target_was_examined(target)) {
1942 LOG_ERROR("Target not examined yet");
1949 if ((address + size - 1) < address) {
1950 /* GDB can request this when e.g. PC is 0xfffffffc*/
1951 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1957 return target->type->write_buffer(target, address, size, buffer);
1960 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t count, const uint8_t *buffer)
1964 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
1965 * will have something to do with the size we leave to it. */
1966 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
1967 if (address & size) {
1968 int retval = target_write_memory(target, address, size, 1, buffer);
1969 if (retval != ERROR_OK)
1977 /* Write the data with as large access size as possible. */
1978 for (; size > 0; size /= 2) {
1979 uint32_t aligned = count - count % size;
1981 int retval = target_write_memory(target, address, size, aligned / size, buffer);
1982 if (retval != ERROR_OK)
1993 /* Single aligned words are guaranteed to use 16 or 32 bit access
1994 * mode respectively, otherwise data is handled as quickly as
1997 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1999 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
2000 (int)size, (unsigned)address);
2002 if (!target_was_examined(target)) {
2003 LOG_ERROR("Target not examined yet");
2010 if ((address + size - 1) < address) {
2011 /* GDB can request this when e.g. PC is 0xfffffffc*/
2012 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
2018 return target->type->read_buffer(target, address, size, buffer);
2021 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t count, uint8_t *buffer)
2025 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2026 * will have something to do with the size we leave to it. */
2027 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2028 if (address & size) {
2029 int retval = target_read_memory(target, address, size, 1, buffer);
2030 if (retval != ERROR_OK)
2038 /* Read the data with as large access size as possible. */
2039 for (; size > 0; size /= 2) {
2040 uint32_t aligned = count - count % size;
2042 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2043 if (retval != ERROR_OK)
2054 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
2059 uint32_t checksum = 0;
2060 if (!target_was_examined(target)) {
2061 LOG_ERROR("Target not examined yet");
2065 retval = target->type->checksum_memory(target, address, size, &checksum);
2066 if (retval != ERROR_OK) {
2067 buffer = malloc(size);
2068 if (buffer == NULL) {
2069 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
2070 return ERROR_COMMAND_SYNTAX_ERROR;
2072 retval = target_read_buffer(target, address, size, buffer);
2073 if (retval != ERROR_OK) {
2078 /* convert to target endianness */
2079 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2080 uint32_t target_data;
2081 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2082 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2085 retval = image_calculate_checksum(buffer, size, &checksum);
2094 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
2097 if (!target_was_examined(target)) {
2098 LOG_ERROR("Target not examined yet");
2102 if (target->type->blank_check_memory == 0)
2103 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2105 retval = target->type->blank_check_memory(target, address, size, blank);
2110 int target_read_u64(struct target *target, uint64_t address, uint64_t *value)
2112 uint8_t value_buf[8];
2113 if (!target_was_examined(target)) {
2114 LOG_ERROR("Target not examined yet");
2118 int retval = target_read_memory(target, address, 8, 1, value_buf);
2120 if (retval == ERROR_OK) {
2121 *value = target_buffer_get_u64(target, value_buf);
2122 LOG_DEBUG("address: 0x%" PRIx64 ", value: 0x%16.16" PRIx64 "",
2127 LOG_DEBUG("address: 0x%" PRIx64 " failed",
2134 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
2136 uint8_t value_buf[4];
2137 if (!target_was_examined(target)) {
2138 LOG_ERROR("Target not examined yet");
2142 int retval = target_read_memory(target, address, 4, 1, value_buf);
2144 if (retval == ERROR_OK) {
2145 *value = target_buffer_get_u32(target, value_buf);
2146 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2151 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2158 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
2160 uint8_t value_buf[2];
2161 if (!target_was_examined(target)) {
2162 LOG_ERROR("Target not examined yet");
2166 int retval = target_read_memory(target, address, 2, 1, value_buf);
2168 if (retval == ERROR_OK) {
2169 *value = target_buffer_get_u16(target, value_buf);
2170 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
2175 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2182 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
2184 if (!target_was_examined(target)) {
2185 LOG_ERROR("Target not examined yet");
2189 int retval = target_read_memory(target, address, 1, 1, value);
2191 if (retval == ERROR_OK) {
2192 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2197 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2204 int target_write_u64(struct target *target, uint64_t address, uint64_t value)
2207 uint8_t value_buf[8];
2208 if (!target_was_examined(target)) {
2209 LOG_ERROR("Target not examined yet");
2213 LOG_DEBUG("address: 0x%" PRIx64 ", value: 0x%16.16" PRIx64 "",
2217 target_buffer_set_u64(target, value_buf, value);
2218 retval = target_write_memory(target, address, 8, 1, value_buf);
2219 if (retval != ERROR_OK)
2220 LOG_DEBUG("failed: %i", retval);
2225 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
2228 uint8_t value_buf[4];
2229 if (!target_was_examined(target)) {
2230 LOG_ERROR("Target not examined yet");
2234 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2238 target_buffer_set_u32(target, value_buf, value);
2239 retval = target_write_memory(target, address, 4, 1, value_buf);
2240 if (retval != ERROR_OK)
2241 LOG_DEBUG("failed: %i", retval);
2246 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
2249 uint8_t value_buf[2];
2250 if (!target_was_examined(target)) {
2251 LOG_ERROR("Target not examined yet");
2255 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
2259 target_buffer_set_u16(target, value_buf, value);
2260 retval = target_write_memory(target, address, 2, 1, value_buf);
2261 if (retval != ERROR_OK)
2262 LOG_DEBUG("failed: %i", retval);
2267 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
2270 if (!target_was_examined(target)) {
2271 LOG_ERROR("Target not examined yet");
2275 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2278 retval = target_write_memory(target, address, 1, 1, &value);
2279 if (retval != ERROR_OK)
2280 LOG_DEBUG("failed: %i", retval);
2285 static int find_target(struct command_context *cmd_ctx, const char *name)
2287 struct target *target = get_target(name);
2288 if (target == NULL) {
2289 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2292 if (!target->tap->enabled) {
2293 LOG_USER("Target: TAP %s is disabled, "
2294 "can't be the current target\n",
2295 target->tap->dotted_name);
2299 cmd_ctx->current_target = target->target_number;
2304 COMMAND_HANDLER(handle_targets_command)
2306 int retval = ERROR_OK;
2307 if (CMD_ARGC == 1) {
2308 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2309 if (retval == ERROR_OK) {
2315 struct target *target = all_targets;
2316 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2317 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2322 if (target->tap->enabled)
2323 state = target_state_name(target);
2325 state = "tap-disabled";
2327 if (CMD_CTX->current_target == target->target_number)
2330 /* keep columns lined up to match the headers above */
2331 command_print(CMD_CTX,
2332 "%2d%c %-18s %-10s %-6s %-18s %s",
2333 target->target_number,
2335 target_name(target),
2336 target_type_name(target),
2337 Jim_Nvp_value2name_simple(nvp_target_endian,
2338 target->endianness)->name,
2339 target->tap->dotted_name,
2341 target = target->next;
2347 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2349 static int powerDropout;
2350 static int srstAsserted;
2352 static int runPowerRestore;
2353 static int runPowerDropout;
2354 static int runSrstAsserted;
2355 static int runSrstDeasserted;
2357 static int sense_handler(void)
2359 static int prevSrstAsserted;
2360 static int prevPowerdropout;
2362 int retval = jtag_power_dropout(&powerDropout);
2363 if (retval != ERROR_OK)
2367 powerRestored = prevPowerdropout && !powerDropout;
2369 runPowerRestore = 1;
2371 long long current = timeval_ms();
2372 static long long lastPower;
2373 int waitMore = lastPower + 2000 > current;
2374 if (powerDropout && !waitMore) {
2375 runPowerDropout = 1;
2376 lastPower = current;
2379 retval = jtag_srst_asserted(&srstAsserted);
2380 if (retval != ERROR_OK)
2384 srstDeasserted = prevSrstAsserted && !srstAsserted;
2386 static long long lastSrst;
2387 waitMore = lastSrst + 2000 > current;
2388 if (srstDeasserted && !waitMore) {
2389 runSrstDeasserted = 1;
2393 if (!prevSrstAsserted && srstAsserted)
2394 runSrstAsserted = 1;
2396 prevSrstAsserted = srstAsserted;
2397 prevPowerdropout = powerDropout;
2399 if (srstDeasserted || powerRestored) {
2400 /* Other than logging the event we can't do anything here.
2401 * Issuing a reset is a particularly bad idea as we might
2402 * be inside a reset already.
2409 /* process target state changes */
2410 static int handle_target(void *priv)
2412 Jim_Interp *interp = (Jim_Interp *)priv;
2413 int retval = ERROR_OK;
2415 if (!is_jtag_poll_safe()) {
2416 /* polling is disabled currently */
2420 /* we do not want to recurse here... */
2421 static int recursive;
2425 /* danger! running these procedures can trigger srst assertions and power dropouts.
2426 * We need to avoid an infinite loop/recursion here and we do that by
2427 * clearing the flags after running these events.
2429 int did_something = 0;
2430 if (runSrstAsserted) {
2431 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2432 Jim_Eval(interp, "srst_asserted");
2435 if (runSrstDeasserted) {
2436 Jim_Eval(interp, "srst_deasserted");
2439 if (runPowerDropout) {
2440 LOG_INFO("Power dropout detected, running power_dropout proc.");
2441 Jim_Eval(interp, "power_dropout");
2444 if (runPowerRestore) {
2445 Jim_Eval(interp, "power_restore");
2449 if (did_something) {
2450 /* clear detect flags */
2454 /* clear action flags */
2456 runSrstAsserted = 0;
2457 runSrstDeasserted = 0;
2458 runPowerRestore = 0;
2459 runPowerDropout = 0;
2464 /* Poll targets for state changes unless that's globally disabled.
2465 * Skip targets that are currently disabled.
2467 for (struct target *target = all_targets;
2468 is_jtag_poll_safe() && target;
2469 target = target->next) {
2471 if (!target_was_examined(target))
2474 if (!target->tap->enabled)
2477 if (target->backoff.times > target->backoff.count) {
2478 /* do not poll this time as we failed previously */
2479 target->backoff.count++;
2482 target->backoff.count = 0;
2484 /* only poll target if we've got power and srst isn't asserted */
2485 if (!powerDropout && !srstAsserted) {
2486 /* polling may fail silently until the target has been examined */
2487 retval = target_poll(target);
2488 if (retval != ERROR_OK) {
2489 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2490 if (target->backoff.times * polling_interval < 5000) {
2491 target->backoff.times *= 2;
2492 target->backoff.times++;
2494 LOG_USER("Polling target %s failed, GDB will be halted. Polling again in %dms",
2495 target_name(target),
2496 target->backoff.times * polling_interval);
2498 /* Tell GDB to halt the debugger. This allows the user to
2499 * run monitor commands to handle the situation.
2501 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2504 /* Since we succeeded, we reset backoff count */
2505 if (target->backoff.times > 0) {
2506 LOG_USER("Polling target %s succeeded again, trying to reexamine", target_name(target));
2507 target_reset_examined(target);
2508 retval = target_examine_one(target);
2509 /* Target examination could have failed due to unstable connection,
2510 * but we set the examined flag anyway to repoll it later */
2511 if (retval != ERROR_OK) {
2512 target->examined = true;
2517 target->backoff.times = 0;
2524 COMMAND_HANDLER(handle_reg_command)
2526 struct target *target;
2527 struct reg *reg = NULL;
2533 target = get_current_target(CMD_CTX);
2535 /* list all available registers for the current target */
2536 if (CMD_ARGC == 0) {
2537 struct reg_cache *cache = target->reg_cache;
2543 command_print(CMD_CTX, "===== %s", cache->name);
2545 for (i = 0, reg = cache->reg_list;
2546 i < cache->num_regs;
2547 i++, reg++, count++) {
2548 /* only print cached values if they are valid */
2550 value = buf_to_str(reg->value,
2552 command_print(CMD_CTX,
2553 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2561 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2566 cache = cache->next;
2572 /* access a single register by its ordinal number */
2573 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2575 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2577 struct reg_cache *cache = target->reg_cache;
2581 for (i = 0; i < cache->num_regs; i++) {
2582 if (count++ == num) {
2583 reg = &cache->reg_list[i];
2589 cache = cache->next;
2593 command_print(CMD_CTX, "%i is out of bounds, the current target "
2594 "has only %i registers (0 - %i)", num, count, count - 1);
2598 /* access a single register by its name */
2599 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2602 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2607 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2609 /* display a register */
2610 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2611 && (CMD_ARGV[1][0] <= '9')))) {
2612 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2615 if (reg->valid == 0)
2616 reg->type->get(reg);
2617 value = buf_to_str(reg->value, reg->size, 16);
2618 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2623 /* set register value */
2624 if (CMD_ARGC == 2) {
2625 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2628 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2630 reg->type->set(reg, buf);
2632 value = buf_to_str(reg->value, reg->size, 16);
2633 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2641 return ERROR_COMMAND_SYNTAX_ERROR;
2644 COMMAND_HANDLER(handle_poll_command)
2646 int retval = ERROR_OK;
2647 struct target *target = get_current_target(CMD_CTX);
2649 if (CMD_ARGC == 0) {
2650 command_print(CMD_CTX, "background polling: %s",
2651 jtag_poll_get_enabled() ? "on" : "off");
2652 command_print(CMD_CTX, "TAP: %s (%s)",
2653 target->tap->dotted_name,
2654 target->tap->enabled ? "enabled" : "disabled");
2655 if (!target->tap->enabled)
2657 retval = target_poll(target);
2658 if (retval != ERROR_OK)
2660 retval = target_arch_state(target);
2661 if (retval != ERROR_OK)
2663 } else if (CMD_ARGC == 1) {
2665 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2666 jtag_poll_set_enabled(enable);
2668 return ERROR_COMMAND_SYNTAX_ERROR;
2673 COMMAND_HANDLER(handle_wait_halt_command)
2676 return ERROR_COMMAND_SYNTAX_ERROR;
2678 unsigned ms = DEFAULT_HALT_TIMEOUT;
2679 if (1 == CMD_ARGC) {
2680 int retval = parse_uint(CMD_ARGV[0], &ms);
2681 if (ERROR_OK != retval)
2682 return ERROR_COMMAND_SYNTAX_ERROR;
2685 struct target *target = get_current_target(CMD_CTX);
2686 return target_wait_state(target, TARGET_HALTED, ms);
2689 /* wait for target state to change. The trick here is to have a low
2690 * latency for short waits and not to suck up all the CPU time
2693 * After 500ms, keep_alive() is invoked
2695 int target_wait_state(struct target *target, enum target_state state, int ms)
2698 long long then = 0, cur;
2702 retval = target_poll(target);
2703 if (retval != ERROR_OK)
2705 if (target->state == state)
2710 then = timeval_ms();
2711 LOG_DEBUG("waiting for target %s...",
2712 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2718 if ((cur-then) > ms) {
2719 LOG_ERROR("timed out while waiting for target %s",
2720 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2728 COMMAND_HANDLER(handle_halt_command)
2732 struct target *target = get_current_target(CMD_CTX);
2733 int retval = target_halt(target);
2734 if (ERROR_OK != retval)
2737 if (CMD_ARGC == 1) {
2738 unsigned wait_local;
2739 retval = parse_uint(CMD_ARGV[0], &wait_local);
2740 if (ERROR_OK != retval)
2741 return ERROR_COMMAND_SYNTAX_ERROR;
2746 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2749 COMMAND_HANDLER(handle_soft_reset_halt_command)
2751 struct target *target = get_current_target(CMD_CTX);
2753 LOG_USER("requesting target halt and executing a soft reset");
2755 target_soft_reset_halt(target);
2760 COMMAND_HANDLER(handle_reset_command)
2763 return ERROR_COMMAND_SYNTAX_ERROR;
2765 enum target_reset_mode reset_mode = RESET_RUN;
2766 if (CMD_ARGC == 1) {
2768 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2769 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2770 return ERROR_COMMAND_SYNTAX_ERROR;
2771 reset_mode = n->value;
2774 /* reset *all* targets */
2775 return target_process_reset(CMD_CTX, reset_mode);
2779 COMMAND_HANDLER(handle_resume_command)
2783 return ERROR_COMMAND_SYNTAX_ERROR;
2785 struct target *target = get_current_target(CMD_CTX);
2787 /* with no CMD_ARGV, resume from current pc, addr = 0,
2788 * with one arguments, addr = CMD_ARGV[0],
2789 * handle breakpoints, not debugging */
2791 if (CMD_ARGC == 1) {
2792 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2796 return target_resume(target, current, addr, 1, 0);
2799 COMMAND_HANDLER(handle_step_command)
2802 return ERROR_COMMAND_SYNTAX_ERROR;
2806 /* with no CMD_ARGV, step from current pc, addr = 0,
2807 * with one argument addr = CMD_ARGV[0],
2808 * handle breakpoints, debugging */
2811 if (CMD_ARGC == 1) {
2812 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2816 struct target *target = get_current_target(CMD_CTX);
2818 return target->type->step(target, current_pc, addr, 1);
2821 static void handle_md_output(struct command_context *cmd_ctx,
2822 struct target *target, uint32_t address, unsigned size,
2823 unsigned count, const uint8_t *buffer)
2825 const unsigned line_bytecnt = 32;
2826 unsigned line_modulo = line_bytecnt / size;
2828 char output[line_bytecnt * 4 + 1];
2829 unsigned output_len = 0;
2831 const char *value_fmt;
2834 value_fmt = "%8.8x ";
2837 value_fmt = "%4.4x ";
2840 value_fmt = "%2.2x ";
2843 /* "can't happen", caller checked */
2844 LOG_ERROR("invalid memory read size: %u", size);
2848 for (unsigned i = 0; i < count; i++) {
2849 if (i % line_modulo == 0) {
2850 output_len += snprintf(output + output_len,
2851 sizeof(output) - output_len,
2853 (unsigned)(address + (i*size)));
2857 const uint8_t *value_ptr = buffer + i * size;
2860 value = target_buffer_get_u32(target, value_ptr);
2863 value = target_buffer_get_u16(target, value_ptr);
2868 output_len += snprintf(output + output_len,
2869 sizeof(output) - output_len,
2872 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2873 command_print(cmd_ctx, "%s", output);
2879 COMMAND_HANDLER(handle_md_command)
2882 return ERROR_COMMAND_SYNTAX_ERROR;
2885 switch (CMD_NAME[2]) {
2896 return ERROR_COMMAND_SYNTAX_ERROR;
2899 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2900 int (*fn)(struct target *target,
2901 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2905 fn = target_read_phys_memory;
2907 fn = target_read_memory;
2908 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2909 return ERROR_COMMAND_SYNTAX_ERROR;
2912 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2916 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2918 uint8_t *buffer = calloc(count, size);
2920 struct target *target = get_current_target(CMD_CTX);
2921 int retval = fn(target, address, size, count, buffer);
2922 if (ERROR_OK == retval)
2923 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2930 typedef int (*target_write_fn)(struct target *target,
2931 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2933 static int target_fill_mem(struct target *target,
2942 /* We have to write in reasonably large chunks to be able
2943 * to fill large memory areas with any sane speed */
2944 const unsigned chunk_size = 16384;
2945 uint8_t *target_buf = malloc(chunk_size * data_size);
2946 if (target_buf == NULL) {
2947 LOG_ERROR("Out of memory");
2951 for (unsigned i = 0; i < chunk_size; i++) {
2952 switch (data_size) {
2954 target_buffer_set_u32(target, target_buf + i * data_size, b);
2957 target_buffer_set_u16(target, target_buf + i * data_size, b);
2960 target_buffer_set_u8(target, target_buf + i * data_size, b);
2967 int retval = ERROR_OK;
2969 for (unsigned x = 0; x < c; x += chunk_size) {
2972 if (current > chunk_size)
2973 current = chunk_size;
2974 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2975 if (retval != ERROR_OK)
2977 /* avoid GDB timeouts */
2986 COMMAND_HANDLER(handle_mw_command)
2989 return ERROR_COMMAND_SYNTAX_ERROR;
2990 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2995 fn = target_write_phys_memory;
2997 fn = target_write_memory;
2998 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2999 return ERROR_COMMAND_SYNTAX_ERROR;
3002 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
3005 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
3009 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3011 struct target *target = get_current_target(CMD_CTX);
3013 switch (CMD_NAME[2]) {
3024 return ERROR_COMMAND_SYNTAX_ERROR;
3027 return target_fill_mem(target, address, fn, wordsize, value, count);
3030 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
3031 uint32_t *min_address, uint32_t *max_address)
3033 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3034 return ERROR_COMMAND_SYNTAX_ERROR;
3036 /* a base address isn't always necessary,
3037 * default to 0x0 (i.e. don't relocate) */
3038 if (CMD_ARGC >= 2) {
3040 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3041 image->base_address = addr;
3042 image->base_address_set = 1;
3044 image->base_address_set = 0;
3046 image->start_address_set = 0;
3049 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
3050 if (CMD_ARGC == 5) {
3051 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
3052 /* use size (given) to find max (required) */
3053 *max_address += *min_address;
3056 if (*min_address > *max_address)
3057 return ERROR_COMMAND_SYNTAX_ERROR;
3062 COMMAND_HANDLER(handle_load_image_command)
3066 uint32_t image_size;
3067 uint32_t min_address = 0;
3068 uint32_t max_address = 0xffffffff;
3072 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
3073 &image, &min_address, &max_address);
3074 if (ERROR_OK != retval)
3077 struct target *target = get_current_target(CMD_CTX);
3079 struct duration bench;
3080 duration_start(&bench);
3082 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3087 for (i = 0; i < image.num_sections; i++) {
3088 buffer = malloc(image.sections[i].size);
3089 if (buffer == NULL) {
3090 command_print(CMD_CTX,
3091 "error allocating buffer for section (%d bytes)",
3092 (int)(image.sections[i].size));
3096 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3097 if (retval != ERROR_OK) {
3102 uint32_t offset = 0;
3103 uint32_t length = buf_cnt;
3105 /* DANGER!!! beware of unsigned comparision here!!! */
3107 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3108 (image.sections[i].base_address < max_address)) {
3110 if (image.sections[i].base_address < min_address) {
3111 /* clip addresses below */
3112 offset += min_address-image.sections[i].base_address;
3116 if (image.sections[i].base_address + buf_cnt > max_address)
3117 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3119 retval = target_write_buffer(target,
3120 image.sections[i].base_address + offset, length, buffer + offset);
3121 if (retval != ERROR_OK) {
3125 image_size += length;
3126 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
3127 (unsigned int)length,
3128 image.sections[i].base_address + offset);
3134 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3135 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
3136 "in %fs (%0.3f KiB/s)", image_size,
3137 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3140 image_close(&image);
3146 COMMAND_HANDLER(handle_dump_image_command)
3148 struct fileio fileio;
3150 int retval, retvaltemp;
3151 uint32_t address, size;
3152 struct duration bench;
3153 struct target *target = get_current_target(CMD_CTX);
3156 return ERROR_COMMAND_SYNTAX_ERROR;
3158 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
3159 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
3161 uint32_t buf_size = (size > 4096) ? 4096 : size;
3162 buffer = malloc(buf_size);
3166 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3167 if (retval != ERROR_OK) {
3172 duration_start(&bench);
3175 size_t size_written;
3176 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3177 retval = target_read_buffer(target, address, this_run_size, buffer);
3178 if (retval != ERROR_OK)
3181 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
3182 if (retval != ERROR_OK)
3185 size -= this_run_size;
3186 address += this_run_size;
3191 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3193 retval = fileio_size(&fileio, &filesize);
3194 if (retval != ERROR_OK)
3196 command_print(CMD_CTX,
3197 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
3198 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3201 retvaltemp = fileio_close(&fileio);
3202 if (retvaltemp != ERROR_OK)
3208 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
3212 uint32_t image_size;
3215 uint32_t checksum = 0;
3216 uint32_t mem_checksum = 0;
3220 struct target *target = get_current_target(CMD_CTX);
3223 return ERROR_COMMAND_SYNTAX_ERROR;
3226 LOG_ERROR("no target selected");
3230 struct duration bench;
3231 duration_start(&bench);
3233 if (CMD_ARGC >= 2) {
3235 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3236 image.base_address = addr;
3237 image.base_address_set = 1;
3239 image.base_address_set = 0;
3240 image.base_address = 0x0;
3243 image.start_address_set = 0;
3245 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3246 if (retval != ERROR_OK)
3252 for (i = 0; i < image.num_sections; i++) {
3253 buffer = malloc(image.sections[i].size);
3254 if (buffer == NULL) {
3255 command_print(CMD_CTX,
3256 "error allocating buffer for section (%d bytes)",
3257 (int)(image.sections[i].size));
3260 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3261 if (retval != ERROR_OK) {
3267 /* calculate checksum of image */
3268 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3269 if (retval != ERROR_OK) {
3274 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3275 if (retval != ERROR_OK) {
3280 if (checksum != mem_checksum) {
3281 /* failed crc checksum, fall back to a binary compare */
3285 LOG_ERROR("checksum mismatch - attempting binary compare");
3287 data = malloc(buf_cnt);
3289 /* Can we use 32bit word accesses? */
3291 int count = buf_cnt;
3292 if ((count % 4) == 0) {
3296 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3297 if (retval == ERROR_OK) {
3299 for (t = 0; t < buf_cnt; t++) {
3300 if (data[t] != buffer[t]) {
3301 command_print(CMD_CTX,
3302 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3304 (unsigned)(t + image.sections[i].base_address),
3307 if (diffs++ >= 127) {
3308 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3320 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3321 image.sections[i].base_address,
3326 image_size += buf_cnt;
3329 command_print(CMD_CTX, "No more differences found.");
3332 retval = ERROR_FAIL;
3333 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3334 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3335 "in %fs (%0.3f KiB/s)", image_size,
3336 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3339 image_close(&image);
3344 COMMAND_HANDLER(handle_verify_image_command)
3346 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3349 COMMAND_HANDLER(handle_test_image_command)
3351 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3354 static int handle_bp_command_list(struct command_context *cmd_ctx)
3356 struct target *target = get_current_target(cmd_ctx);
3357 struct breakpoint *breakpoint = target->breakpoints;
3358 while (breakpoint) {
3359 if (breakpoint->type == BKPT_SOFT) {
3360 char *buf = buf_to_str(breakpoint->orig_instr,
3361 breakpoint->length, 16);
3362 command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3363 breakpoint->address,
3365 breakpoint->set, buf);
3368 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3369 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3371 breakpoint->length, breakpoint->set);
3372 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3373 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3374 breakpoint->address,
3375 breakpoint->length, breakpoint->set);
3376 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3379 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3380 breakpoint->address,
3381 breakpoint->length, breakpoint->set);
3384 breakpoint = breakpoint->next;
3389 static int handle_bp_command_set(struct command_context *cmd_ctx,
3390 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3392 struct target *target = get_current_target(cmd_ctx);
3396 retval = breakpoint_add(target, addr, length, hw);
3397 if (ERROR_OK == retval)
3398 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3400 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3403 } else if (addr == 0) {
3404 if (target->type->add_context_breakpoint == NULL) {
3405 LOG_WARNING("Context breakpoint not available");
3408 retval = context_breakpoint_add(target, asid, length, hw);
3409 if (ERROR_OK == retval)
3410 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3412 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3416 if (target->type->add_hybrid_breakpoint == NULL) {
3417 LOG_WARNING("Hybrid breakpoint not available");
3420 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3421 if (ERROR_OK == retval)
3422 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3424 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3431 COMMAND_HANDLER(handle_bp_command)
3440 return handle_bp_command_list(CMD_CTX);
3444 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3445 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3446 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3449 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3451 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3453 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3456 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3457 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3459 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3460 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3462 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3467 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3468 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3469 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3470 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3473 return ERROR_COMMAND_SYNTAX_ERROR;
3477 COMMAND_HANDLER(handle_rbp_command)
3480 return ERROR_COMMAND_SYNTAX_ERROR;
3483 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3485 struct target *target = get_current_target(CMD_CTX);
3486 breakpoint_remove(target, addr);
3491 COMMAND_HANDLER(handle_wp_command)
3493 struct target *target = get_current_target(CMD_CTX);
3495 if (CMD_ARGC == 0) {
3496 struct watchpoint *watchpoint = target->watchpoints;
3498 while (watchpoint) {
3499 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3500 ", len: 0x%8.8" PRIx32
3501 ", r/w/a: %i, value: 0x%8.8" PRIx32
3502 ", mask: 0x%8.8" PRIx32,
3503 watchpoint->address,
3505 (int)watchpoint->rw,
3508 watchpoint = watchpoint->next;
3513 enum watchpoint_rw type = WPT_ACCESS;
3515 uint32_t length = 0;
3516 uint32_t data_value = 0x0;
3517 uint32_t data_mask = 0xffffffff;
3521 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3524 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3527 switch (CMD_ARGV[2][0]) {
3538 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3539 return ERROR_COMMAND_SYNTAX_ERROR;
3543 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3544 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3548 return ERROR_COMMAND_SYNTAX_ERROR;
3551 int retval = watchpoint_add(target, addr, length, type,
3552 data_value, data_mask);
3553 if (ERROR_OK != retval)
3554 LOG_ERROR("Failure setting watchpoints");
3559 COMMAND_HANDLER(handle_rwp_command)
3562 return ERROR_COMMAND_SYNTAX_ERROR;
3565 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3567 struct target *target = get_current_target(CMD_CTX);
3568 watchpoint_remove(target, addr);
3574 * Translate a virtual address to a physical address.
3576 * The low-level target implementation must have logged a detailed error
3577 * which is forwarded to telnet/GDB session.
3579 COMMAND_HANDLER(handle_virt2phys_command)
3582 return ERROR_COMMAND_SYNTAX_ERROR;
3585 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3588 struct target *target = get_current_target(CMD_CTX);
3589 int retval = target->type->virt2phys(target, va, &pa);
3590 if (retval == ERROR_OK)
3591 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3596 static void writeData(FILE *f, const void *data, size_t len)
3598 size_t written = fwrite(data, 1, len, f);
3600 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3603 static void writeLong(FILE *f, int l, struct target *target)
3607 target_buffer_set_u32(target, val, l);
3608 writeData(f, val, 4);
3611 static void writeString(FILE *f, char *s)
3613 writeData(f, s, strlen(s));
3616 typedef unsigned char UNIT[2]; /* unit of profiling */
3618 /* Dump a gmon.out histogram file. */
3619 static void write_gmon(uint32_t *samples, uint32_t sampleNum, const char *filename, bool with_range,
3620 uint32_t start_address, uint32_t end_address, struct target *target)
3623 FILE *f = fopen(filename, "w");
3626 writeString(f, "gmon");
3627 writeLong(f, 0x00000001, target); /* Version */
3628 writeLong(f, 0, target); /* padding */
3629 writeLong(f, 0, target); /* padding */
3630 writeLong(f, 0, target); /* padding */
3632 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3633 writeData(f, &zero, 1);
3635 /* figure out bucket size */
3639 min = start_address;
3644 for (i = 0; i < sampleNum; i++) {
3645 if (min > samples[i])
3647 if (max < samples[i])
3651 /* max should be (largest sample + 1)
3652 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
3656 int addressSpace = max - min;
3657 assert(addressSpace >= 2);
3659 /* FIXME: What is the reasonable number of buckets?
3660 * The profiling result will be more accurate if there are enough buckets. */
3661 static const uint32_t maxBuckets = 128 * 1024; /* maximum buckets. */
3662 uint32_t numBuckets = addressSpace / sizeof(UNIT);
3663 if (numBuckets > maxBuckets)
3664 numBuckets = maxBuckets;
3665 int *buckets = malloc(sizeof(int) * numBuckets);
3666 if (buckets == NULL) {
3670 memset(buckets, 0, sizeof(int) * numBuckets);
3671 for (i = 0; i < sampleNum; i++) {
3672 uint32_t address = samples[i];
3674 if ((address < min) || (max <= address))
3677 long long a = address - min;
3678 long long b = numBuckets;
3679 long long c = addressSpace;
3680 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3684 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3685 writeLong(f, min, target); /* low_pc */
3686 writeLong(f, max, target); /* high_pc */
3687 writeLong(f, numBuckets, target); /* # of buckets */
3688 writeLong(f, 100, target); /* KLUDGE! We lie, ca. 100Hz best case. */
3689 writeString(f, "seconds");
3690 for (i = 0; i < (15-strlen("seconds")); i++)
3691 writeData(f, &zero, 1);
3692 writeString(f, "s");
3694 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3696 char *data = malloc(2 * numBuckets);
3698 for (i = 0; i < numBuckets; i++) {
3703 data[i * 2] = val&0xff;
3704 data[i * 2 + 1] = (val >> 8) & 0xff;
3707 writeData(f, data, numBuckets * 2);
3715 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3716 * which will be used as a random sampling of PC */
3717 COMMAND_HANDLER(handle_profile_command)
3719 struct target *target = get_current_target(CMD_CTX);
3721 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
3722 return ERROR_COMMAND_SYNTAX_ERROR;
3724 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
3726 uint32_t num_of_samples;
3727 int retval = ERROR_OK;
3729 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
3731 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
3732 if (samples == NULL) {
3733 LOG_ERROR("No memory to store samples.");
3738 * Some cores let us sample the PC without the
3739 * annoying halt/resume step; for example, ARMv7 PCSR.
3740 * Provide a way to use that more efficient mechanism.
3742 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
3743 &num_of_samples, offset);
3744 if (retval != ERROR_OK) {
3749 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
3751 retval = target_poll(target);
3752 if (retval != ERROR_OK) {
3756 if (target->state == TARGET_RUNNING) {
3757 retval = target_halt(target);
3758 if (retval != ERROR_OK) {
3764 retval = target_poll(target);
3765 if (retval != ERROR_OK) {
3770 uint32_t start_address = 0;
3771 uint32_t end_address = 0;
3772 bool with_range = false;
3773 if (CMD_ARGC == 4) {
3775 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
3776 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
3779 write_gmon(samples, num_of_samples, CMD_ARGV[1],
3780 with_range, start_address, end_address, target);
3781 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3787 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3790 Jim_Obj *nameObjPtr, *valObjPtr;
3793 namebuf = alloc_printf("%s(%d)", varname, idx);
3797 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3798 valObjPtr = Jim_NewIntObj(interp, val);
3799 if (!nameObjPtr || !valObjPtr) {
3804 Jim_IncrRefCount(nameObjPtr);
3805 Jim_IncrRefCount(valObjPtr);
3806 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3807 Jim_DecrRefCount(interp, nameObjPtr);
3808 Jim_DecrRefCount(interp, valObjPtr);
3810 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3814 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3816 struct command_context *context;
3817 struct target *target;
3819 context = current_command_context(interp);
3820 assert(context != NULL);
3822 target = get_current_target(context);
3823 if (target == NULL) {
3824 LOG_ERROR("mem2array: no current target");
3828 return target_mem2array(interp, target, argc - 1, argv + 1);
3831 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3839 const char *varname;
3843 /* argv[1] = name of array to receive the data
3844 * argv[2] = desired width
3845 * argv[3] = memory address
3846 * argv[4] = count of times to read
3849 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3852 varname = Jim_GetString(argv[0], &len);
3853 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3855 e = Jim_GetLong(interp, argv[1], &l);
3860 e = Jim_GetLong(interp, argv[2], &l);
3864 e = Jim_GetLong(interp, argv[3], &l);
3879 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3880 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3884 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3885 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3888 if ((addr + (len * width)) < addr) {
3889 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3890 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3893 /* absurd transfer size? */
3895 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3896 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3901 ((width == 2) && ((addr & 1) == 0)) ||
3902 ((width == 4) && ((addr & 3) == 0))) {
3906 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3907 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3910 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3919 size_t buffersize = 4096;
3920 uint8_t *buffer = malloc(buffersize);
3927 /* Slurp... in buffer size chunks */
3929 count = len; /* in objects.. */
3930 if (count > (buffersize / width))
3931 count = (buffersize / width);
3933 retval = target_read_memory(target, addr, width, count, buffer);
3934 if (retval != ERROR_OK) {
3936 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3940 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3941 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3945 v = 0; /* shut up gcc */
3946 for (i = 0; i < count ; i++, n++) {
3949 v = target_buffer_get_u32(target, &buffer[i*width]);
3952 v = target_buffer_get_u16(target, &buffer[i*width]);
3955 v = buffer[i] & 0x0ff;
3958 new_int_array_element(interp, varname, n, v);
3961 addr += count * width;
3967 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3972 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
3975 Jim_Obj *nameObjPtr, *valObjPtr;
3979 namebuf = alloc_printf("%s(%d)", varname, idx);
3983 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3989 Jim_IncrRefCount(nameObjPtr);
3990 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3991 Jim_DecrRefCount(interp, nameObjPtr);
3993 if (valObjPtr == NULL)
3996 result = Jim_GetLong(interp, valObjPtr, &l);
3997 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
4002 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4004 struct command_context *context;
4005 struct target *target;
4007 context = current_command_context(interp);
4008 assert(context != NULL);
4010 target = get_current_target(context);
4011 if (target == NULL) {
4012 LOG_ERROR("array2mem: no current target");
4016 return target_array2mem(interp, target, argc-1, argv + 1);
4019 static int target_array2mem(Jim_Interp *interp, struct target *target,
4020 int argc, Jim_Obj *const *argv)
4028 const char *varname;
4032 /* argv[1] = name of array to get the data
4033 * argv[2] = desired width
4034 * argv[3] = memory address
4035 * argv[4] = count to write
4038 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
4041 varname = Jim_GetString(argv[0], &len);
4042 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
4044 e = Jim_GetLong(interp, argv[1], &l);
4049 e = Jim_GetLong(interp, argv[2], &l);
4053 e = Jim_GetLong(interp, argv[3], &l);
4068 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4069 Jim_AppendStrings(interp, Jim_GetResult(interp),
4070 "Invalid width param, must be 8/16/32", NULL);
4074 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4075 Jim_AppendStrings(interp, Jim_GetResult(interp),
4076 "array2mem: zero width read?", NULL);
4079 if ((addr + (len * width)) < addr) {
4080 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4081 Jim_AppendStrings(interp, Jim_GetResult(interp),
4082 "array2mem: addr + len - wraps to zero?", NULL);
4085 /* absurd transfer size? */
4087 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4088 Jim_AppendStrings(interp, Jim_GetResult(interp),
4089 "array2mem: absurd > 64K item request", NULL);
4094 ((width == 2) && ((addr & 1) == 0)) ||
4095 ((width == 4) && ((addr & 3) == 0))) {
4099 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4100 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
4103 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
4114 size_t buffersize = 4096;
4115 uint8_t *buffer = malloc(buffersize);
4120 /* Slurp... in buffer size chunks */
4122 count = len; /* in objects.. */
4123 if (count > (buffersize / width))
4124 count = (buffersize / width);
4126 v = 0; /* shut up gcc */
4127 for (i = 0; i < count; i++, n++) {
4128 get_int_array_element(interp, varname, n, &v);
4131 target_buffer_set_u32(target, &buffer[i * width], v);
4134 target_buffer_set_u16(target, &buffer[i * width], v);
4137 buffer[i] = v & 0x0ff;
4143 retval = target_write_memory(target, addr, width, count, buffer);
4144 if (retval != ERROR_OK) {
4146 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
4150 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4151 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4155 addr += count * width;
4160 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4165 /* FIX? should we propagate errors here rather than printing them
4168 void target_handle_event(struct target *target, enum target_event e)
4170 struct target_event_action *teap;
4172 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4173 if (teap->event == e) {
4174 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
4175 target->target_number,
4176 target_name(target),
4177 target_type_name(target),
4179 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
4180 Jim_GetString(teap->body, NULL));
4181 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
4182 Jim_MakeErrorMessage(teap->interp);
4183 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
4190 * Returns true only if the target has a handler for the specified event.
4192 bool target_has_event_action(struct target *target, enum target_event event)
4194 struct target_event_action *teap;
4196 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4197 if (teap->event == event)
4203 enum target_cfg_param {
4206 TCFG_WORK_AREA_VIRT,
4207 TCFG_WORK_AREA_PHYS,
4208 TCFG_WORK_AREA_SIZE,
4209 TCFG_WORK_AREA_BACKUP,
4212 TCFG_CHAIN_POSITION,
4217 static Jim_Nvp nvp_config_opts[] = {
4218 { .name = "-type", .value = TCFG_TYPE },
4219 { .name = "-event", .value = TCFG_EVENT },
4220 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4221 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4222 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4223 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4224 { .name = "-endian" , .value = TCFG_ENDIAN },
4225 { .name = "-coreid", .value = TCFG_COREID },
4226 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4227 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4228 { .name = "-rtos", .value = TCFG_RTOS },
4229 { .name = NULL, .value = -1 }
4232 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
4239 /* parse config or cget options ... */
4240 while (goi->argc > 0) {
4241 Jim_SetEmptyResult(goi->interp);
4242 /* Jim_GetOpt_Debug(goi); */
4244 if (target->type->target_jim_configure) {
4245 /* target defines a configure function */
4246 /* target gets first dibs on parameters */
4247 e = (*(target->type->target_jim_configure))(target, goi);
4256 /* otherwise we 'continue' below */
4258 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
4260 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
4266 if (goi->isconfigure) {
4267 Jim_SetResultFormatted(goi->interp,
4268 "not settable: %s", n->name);
4272 if (goi->argc != 0) {
4273 Jim_WrongNumArgs(goi->interp,
4274 goi->argc, goi->argv,
4279 Jim_SetResultString(goi->interp,
4280 target_type_name(target), -1);
4284 if (goi->argc == 0) {
4285 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4289 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4291 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4295 if (goi->isconfigure) {
4296 if (goi->argc != 1) {
4297 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4301 if (goi->argc != 0) {
4302 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4308 struct target_event_action *teap;
4310 teap = target->event_action;
4311 /* replace existing? */
4313 if (teap->event == (enum target_event)n->value)
4318 if (goi->isconfigure) {
4319 bool replace = true;
4322 teap = calloc(1, sizeof(*teap));
4325 teap->event = n->value;
4326 teap->interp = goi->interp;
4327 Jim_GetOpt_Obj(goi, &o);
4329 Jim_DecrRefCount(teap->interp, teap->body);
4330 teap->body = Jim_DuplicateObj(goi->interp, o);
4333 * Tcl/TK - "tk events" have a nice feature.
4334 * See the "BIND" command.
4335 * We should support that here.
4336 * You can specify %X and %Y in the event code.
4337 * The idea is: %T - target name.
4338 * The idea is: %N - target number
4339 * The idea is: %E - event name.
4341 Jim_IncrRefCount(teap->body);
4344 /* add to head of event list */
4345 teap->next = target->event_action;
4346 target->event_action = teap;
4348 Jim_SetEmptyResult(goi->interp);
4352 Jim_SetEmptyResult(goi->interp);
4354 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4360 case TCFG_WORK_AREA_VIRT:
4361 if (goi->isconfigure) {
4362 target_free_all_working_areas(target);
4363 e = Jim_GetOpt_Wide(goi, &w);
4366 target->working_area_virt = w;
4367 target->working_area_virt_spec = true;
4372 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4376 case TCFG_WORK_AREA_PHYS:
4377 if (goi->isconfigure) {
4378 target_free_all_working_areas(target);
4379 e = Jim_GetOpt_Wide(goi, &w);
4382 target->working_area_phys = w;
4383 target->working_area_phys_spec = true;
4388 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4392 case TCFG_WORK_AREA_SIZE:
4393 if (goi->isconfigure) {
4394 target_free_all_working_areas(target);
4395 e = Jim_GetOpt_Wide(goi, &w);
4398 target->working_area_size = w;
4403 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4407 case TCFG_WORK_AREA_BACKUP:
4408 if (goi->isconfigure) {
4409 target_free_all_working_areas(target);
4410 e = Jim_GetOpt_Wide(goi, &w);
4413 /* make this exactly 1 or 0 */
4414 target->backup_working_area = (!!w);
4419 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4420 /* loop for more e*/
4425 if (goi->isconfigure) {
4426 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4428 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4431 target->endianness = n->value;
4436 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4437 if (n->name == NULL) {
4438 target->endianness = TARGET_LITTLE_ENDIAN;
4439 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4441 Jim_SetResultString(goi->interp, n->name, -1);
4446 if (goi->isconfigure) {
4447 e = Jim_GetOpt_Wide(goi, &w);
4450 target->coreid = (int32_t)w;
4455 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4459 case TCFG_CHAIN_POSITION:
4460 if (goi->isconfigure) {
4462 struct jtag_tap *tap;
4463 target_free_all_working_areas(target);
4464 e = Jim_GetOpt_Obj(goi, &o_t);
4467 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4470 /* make this exactly 1 or 0 */
4476 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4477 /* loop for more e*/
4480 if (goi->isconfigure) {
4481 e = Jim_GetOpt_Wide(goi, &w);
4484 target->dbgbase = (uint32_t)w;
4485 target->dbgbase_set = true;
4490 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4497 int result = rtos_create(goi, target);
4498 if (result != JIM_OK)
4504 } /* while (goi->argc) */
4507 /* done - we return */
4511 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4515 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4516 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4517 int need_args = 1 + goi.isconfigure;
4518 if (goi.argc < need_args) {
4519 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4521 ? "missing: -option VALUE ..."
4522 : "missing: -option ...");
4525 struct target *target = Jim_CmdPrivData(goi.interp);
4526 return target_configure(&goi, target);
4529 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4531 const char *cmd_name = Jim_GetString(argv[0], NULL);
4534 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4536 if (goi.argc < 2 || goi.argc > 4) {
4537 Jim_SetResultFormatted(goi.interp,
4538 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4543 fn = target_write_memory;
4546 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4548 struct Jim_Obj *obj;
4549 e = Jim_GetOpt_Obj(&goi, &obj);
4553 fn = target_write_phys_memory;
4557 e = Jim_GetOpt_Wide(&goi, &a);
4562 e = Jim_GetOpt_Wide(&goi, &b);
4567 if (goi.argc == 1) {
4568 e = Jim_GetOpt_Wide(&goi, &c);
4573 /* all args must be consumed */
4577 struct target *target = Jim_CmdPrivData(goi.interp);
4579 if (strcasecmp(cmd_name, "mww") == 0)
4581 else if (strcasecmp(cmd_name, "mwh") == 0)
4583 else if (strcasecmp(cmd_name, "mwb") == 0)
4586 LOG_ERROR("command '%s' unknown: ", cmd_name);
4590 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4594 * @brief Reads an array of words/halfwords/bytes from target memory starting at specified address.
4596 * Usage: mdw [phys] <address> [<count>] - for 32 bit reads
4597 * mdh [phys] <address> [<count>] - for 16 bit reads
4598 * mdb [phys] <address> [<count>] - for 8 bit reads
4600 * Count defaults to 1.
4602 * Calls target_read_memory or target_read_phys_memory depending on
4603 * the presence of the "phys" argument
4604 * Reads the target memory in blocks of max. 32 bytes, and returns an array of ints formatted
4605 * to int representation in base16.
4606 * Also outputs read data in a human readable form using command_print
4608 * @param phys if present target_read_phys_memory will be used instead of target_read_memory
4609 * @param address address where to start the read. May be specified in decimal or hex using the standard "0x" prefix
4610 * @param count optional count parameter to read an array of values. If not specified, defaults to 1.
4611 * @returns: JIM_ERR on error or JIM_OK on success and sets the result string to an array of ascii formatted numbers
4612 * on success, with [<count>] number of elements.
4614 * In case of little endian target:
4615 * Example1: "mdw 0x00000000" returns "10123456"
4616 * Exmaple2: "mdh 0x00000000 1" returns "3456"
4617 * Example3: "mdb 0x00000000" returns "56"
4618 * Example4: "mdh 0x00000000 2" returns "3456 1012"
4619 * Example5: "mdb 0x00000000 3" returns "56 34 12"
4621 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4623 const char *cmd_name = Jim_GetString(argv[0], NULL);
4626 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4628 if ((goi.argc < 1) || (goi.argc > 3)) {
4629 Jim_SetResultFormatted(goi.interp,
4630 "usage: %s [phys] <address> [<count>]", cmd_name);
4634 int (*fn)(struct target *target,
4635 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4636 fn = target_read_memory;
4639 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4641 struct Jim_Obj *obj;
4642 e = Jim_GetOpt_Obj(&goi, &obj);
4646 fn = target_read_phys_memory;
4649 /* Read address parameter */
4651 e = Jim_GetOpt_Wide(&goi, &addr);
4655 /* If next parameter exists, read it out as the count parameter, if not, set it to 1 (default) */
4657 if (goi.argc == 1) {
4658 e = Jim_GetOpt_Wide(&goi, &count);
4664 /* all args must be consumed */
4668 jim_wide dwidth = 1; /* shut up gcc */
4669 if (strcasecmp(cmd_name, "mdw") == 0)
4671 else if (strcasecmp(cmd_name, "mdh") == 0)
4673 else if (strcasecmp(cmd_name, "mdb") == 0)
4676 LOG_ERROR("command '%s' unknown: ", cmd_name);
4680 /* convert count to "bytes" */
4681 int bytes = count * dwidth;
4683 struct target *target = Jim_CmdPrivData(goi.interp);
4684 uint8_t target_buf[32];
4687 y = (bytes < 16) ? bytes : 16; /* y = min(bytes, 16); */
4689 /* Try to read out next block */
4690 e = fn(target, addr, dwidth, y / dwidth, target_buf);
4692 if (e != ERROR_OK) {
4693 Jim_SetResultFormatted(interp, "error reading target @ 0x%08lx", (long)addr);
4697 command_print_sameline(NULL, "0x%08x ", (int)(addr));
4700 for (x = 0; x < 16 && x < y; x += 4) {
4701 z = target_buffer_get_u32(target, &(target_buf[x]));
4702 command_print_sameline(NULL, "%08x ", (int)(z));
4704 for (; (x < 16) ; x += 4)
4705 command_print_sameline(NULL, " ");
4708 for (x = 0; x < 16 && x < y; x += 2) {
4709 z = target_buffer_get_u16(target, &(target_buf[x]));
4710 command_print_sameline(NULL, "%04x ", (int)(z));
4712 for (; (x < 16) ; x += 2)
4713 command_print_sameline(NULL, " ");
4717 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4718 z = target_buffer_get_u8(target, &(target_buf[x]));
4719 command_print_sameline(NULL, "%02x ", (int)(z));
4721 for (; (x < 16) ; x += 1)
4722 command_print_sameline(NULL, " ");
4725 /* ascii-ify the bytes */
4726 for (x = 0 ; x < y ; x++) {
4727 if ((target_buf[x] >= 0x20) &&
4728 (target_buf[x] <= 0x7e)) {
4732 target_buf[x] = '.';
4737 target_buf[x] = ' ';
4742 /* print - with a newline */
4743 command_print_sameline(NULL, "%s\n", target_buf);
4751 static int jim_target_mem2array(Jim_Interp *interp,
4752 int argc, Jim_Obj *const *argv)
4754 struct target *target = Jim_CmdPrivData(interp);
4755 return target_mem2array(interp, target, argc - 1, argv + 1);
4758 static int jim_target_array2mem(Jim_Interp *interp,
4759 int argc, Jim_Obj *const *argv)
4761 struct target *target = Jim_CmdPrivData(interp);
4762 return target_array2mem(interp, target, argc - 1, argv + 1);
4765 static int jim_target_tap_disabled(Jim_Interp *interp)
4767 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4771 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4774 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4777 struct target *target = Jim_CmdPrivData(interp);
4778 if (!target->tap->enabled)
4779 return jim_target_tap_disabled(interp);
4781 int e = target->type->examine(target);
4787 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4790 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4793 struct target *target = Jim_CmdPrivData(interp);
4795 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4801 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4804 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4807 struct target *target = Jim_CmdPrivData(interp);
4808 if (!target->tap->enabled)
4809 return jim_target_tap_disabled(interp);
4812 if (!(target_was_examined(target)))
4813 e = ERROR_TARGET_NOT_EXAMINED;
4815 e = target->type->poll(target);
4821 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4824 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4826 if (goi.argc != 2) {
4827 Jim_WrongNumArgs(interp, 0, argv,
4828 "([tT]|[fF]|assert|deassert) BOOL");
4833 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4835 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4838 /* the halt or not param */
4840 e = Jim_GetOpt_Wide(&goi, &a);
4844 struct target *target = Jim_CmdPrivData(goi.interp);
4845 if (!target->tap->enabled)
4846 return jim_target_tap_disabled(interp);
4847 if (!(target_was_examined(target))) {
4848 LOG_ERROR("Target not examined yet");
4849 return ERROR_TARGET_NOT_EXAMINED;
4851 if (!target->type->assert_reset || !target->type->deassert_reset) {
4852 Jim_SetResultFormatted(interp,
4853 "No target-specific reset for %s",
4854 target_name(target));
4857 /* determine if we should halt or not. */
4858 target->reset_halt = !!a;
4859 /* When this happens - all workareas are invalid. */
4860 target_free_all_working_areas_restore(target, 0);
4863 if (n->value == NVP_ASSERT)
4864 e = target->type->assert_reset(target);
4866 e = target->type->deassert_reset(target);
4867 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4870 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4873 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4876 struct target *target = Jim_CmdPrivData(interp);
4877 if (!target->tap->enabled)
4878 return jim_target_tap_disabled(interp);
4879 int e = target->type->halt(target);
4880 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4883 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4886 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4888 /* params: <name> statename timeoutmsecs */
4889 if (goi.argc != 2) {
4890 const char *cmd_name = Jim_GetString(argv[0], NULL);
4891 Jim_SetResultFormatted(goi.interp,
4892 "%s <state_name> <timeout_in_msec>", cmd_name);
4897 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4899 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
4903 e = Jim_GetOpt_Wide(&goi, &a);
4906 struct target *target = Jim_CmdPrivData(interp);
4907 if (!target->tap->enabled)
4908 return jim_target_tap_disabled(interp);
4910 e = target_wait_state(target, n->value, a);
4911 if (e != ERROR_OK) {
4912 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4913 Jim_SetResultFormatted(goi.interp,
4914 "target: %s wait %s fails (%#s) %s",
4915 target_name(target), n->name,
4916 eObj, target_strerror_safe(e));
4917 Jim_FreeNewObj(interp, eObj);
4922 /* List for human, Events defined for this target.
4923 * scripts/programs should use 'name cget -event NAME'
4925 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4927 struct command_context *cmd_ctx = current_command_context(interp);
4928 assert(cmd_ctx != NULL);
4930 struct target *target = Jim_CmdPrivData(interp);
4931 struct target_event_action *teap = target->event_action;
4932 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4933 target->target_number,
4934 target_name(target));
4935 command_print(cmd_ctx, "%-25s | Body", "Event");
4936 command_print(cmd_ctx, "------------------------- | "
4937 "----------------------------------------");
4939 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4940 command_print(cmd_ctx, "%-25s | %s",
4941 opt->name, Jim_GetString(teap->body, NULL));
4944 command_print(cmd_ctx, "***END***");
4947 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4950 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4953 struct target *target = Jim_CmdPrivData(interp);
4954 Jim_SetResultString(interp, target_state_name(target), -1);
4957 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4960 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4961 if (goi.argc != 1) {
4962 const char *cmd_name = Jim_GetString(argv[0], NULL);
4963 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4967 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4969 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4972 struct target *target = Jim_CmdPrivData(interp);
4973 target_handle_event(target, n->value);
4977 static const struct command_registration target_instance_command_handlers[] = {
4979 .name = "configure",
4980 .mode = COMMAND_CONFIG,
4981 .jim_handler = jim_target_configure,
4982 .help = "configure a new target for use",
4983 .usage = "[target_attribute ...]",
4987 .mode = COMMAND_ANY,
4988 .jim_handler = jim_target_configure,
4989 .help = "returns the specified target attribute",
4990 .usage = "target_attribute",
4994 .mode = COMMAND_EXEC,
4995 .jim_handler = jim_target_mw,
4996 .help = "Write 32-bit word(s) to target memory",
4997 .usage = "address data [count]",
5001 .mode = COMMAND_EXEC,
5002 .jim_handler = jim_target_mw,
5003 .help = "Write 16-bit half-word(s) to target memory",
5004 .usage = "address data [count]",
5008 .mode = COMMAND_EXEC,
5009 .jim_handler = jim_target_mw,
5010 .help = "Write byte(s) to target memory",
5011 .usage = "address data [count]",
5015 .mode = COMMAND_EXEC,
5016 .jim_handler = jim_target_md,
5017 .help = "Display target memory as 32-bit words",
5018 .usage = "address [count]",
5022 .mode = COMMAND_EXEC,
5023 .jim_handler = jim_target_md,
5024 .help = "Display target memory as 16-bit half-words",
5025 .usage = "address [count]",
5029 .mode = COMMAND_EXEC,
5030 .jim_handler = jim_target_md,
5031 .help = "Display target memory as 8-bit bytes",
5032 .usage = "address [count]",
5035 .name = "array2mem",
5036 .mode = COMMAND_EXEC,
5037 .jim_handler = jim_target_array2mem,
5038 .help = "Writes Tcl array of 8/16/32 bit numbers "
5040 .usage = "arrayname bitwidth address count",
5043 .name = "mem2array",
5044 .mode = COMMAND_EXEC,
5045 .jim_handler = jim_target_mem2array,
5046 .help = "Loads Tcl array of 8/16/32 bit numbers "
5047 "from target memory",
5048 .usage = "arrayname bitwidth address count",
5051 .name = "eventlist",
5052 .mode = COMMAND_EXEC,
5053 .jim_handler = jim_target_event_list,
5054 .help = "displays a table of events defined for this target",
5058 .mode = COMMAND_EXEC,
5059 .jim_handler = jim_target_current_state,
5060 .help = "displays the current state of this target",
5063 .name = "arp_examine",
5064 .mode = COMMAND_EXEC,
5065 .jim_handler = jim_target_examine,
5066 .help = "used internally for reset processing",
5069 .name = "arp_halt_gdb",
5070 .mode = COMMAND_EXEC,
5071 .jim_handler = jim_target_halt_gdb,
5072 .help = "used internally for reset processing to halt GDB",
5076 .mode = COMMAND_EXEC,
5077 .jim_handler = jim_target_poll,
5078 .help = "used internally for reset processing",
5081 .name = "arp_reset",
5082 .mode = COMMAND_EXEC,
5083 .jim_handler = jim_target_reset,
5084 .help = "used internally for reset processing",
5088 .mode = COMMAND_EXEC,
5089 .jim_handler = jim_target_halt,
5090 .help = "used internally for reset processing",
5093 .name = "arp_waitstate",
5094 .mode = COMMAND_EXEC,
5095 .jim_handler = jim_target_wait_state,
5096 .help = "used internally for reset processing",
5099 .name = "invoke-event",
5100 .mode = COMMAND_EXEC,
5101 .jim_handler = jim_target_invoke_event,
5102 .help = "invoke handler for specified event",
5103 .usage = "event_name",
5105 COMMAND_REGISTRATION_DONE
5108 static int target_create(Jim_GetOptInfo *goi)
5116 struct target *target;
5117 struct command_context *cmd_ctx;
5119 cmd_ctx = current_command_context(goi->interp);
5120 assert(cmd_ctx != NULL);
5122 if (goi->argc < 3) {
5123 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5128 Jim_GetOpt_Obj(goi, &new_cmd);
5129 /* does this command exist? */
5130 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
5132 cp = Jim_GetString(new_cmd, NULL);
5133 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5138 e = Jim_GetOpt_String(goi, &cp2, NULL);
5142 struct transport *tr = get_current_transport();
5143 if (tr->override_target) {
5144 e = tr->override_target(&cp);
5145 if (e != ERROR_OK) {
5146 LOG_ERROR("The selected transport doesn't support this target");
5149 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5151 /* now does target type exist */
5152 for (x = 0 ; target_types[x] ; x++) {
5153 if (0 == strcmp(cp, target_types[x]->name)) {
5158 /* check for deprecated name */
5159 if (target_types[x]->deprecated_name) {
5160 if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
5162 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
5167 if (target_types[x] == NULL) {
5168 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5169 for (x = 0 ; target_types[x] ; x++) {
5170 if (target_types[x + 1]) {
5171 Jim_AppendStrings(goi->interp,
5172 Jim_GetResult(goi->interp),
5173 target_types[x]->name,
5176 Jim_AppendStrings(goi->interp,
5177 Jim_GetResult(goi->interp),
5179 target_types[x]->name, NULL);
5186 target = calloc(1, sizeof(struct target));
5187 /* set target number */
5188 target->target_number = new_target_number();
5189 cmd_ctx->current_target = target->target_number;
5191 /* allocate memory for each unique target type */
5192 target->type = calloc(1, sizeof(struct target_type));
5194 memcpy(target->type, target_types[x], sizeof(struct target_type));
5196 /* will be set by "-endian" */
5197 target->endianness = TARGET_ENDIAN_UNKNOWN;
5199 /* default to first core, override with -coreid */
5202 target->working_area = 0x0;
5203 target->working_area_size = 0x0;
5204 target->working_areas = NULL;
5205 target->backup_working_area = 0;
5207 target->state = TARGET_UNKNOWN;
5208 target->debug_reason = DBG_REASON_UNDEFINED;
5209 target->reg_cache = NULL;
5210 target->breakpoints = NULL;
5211 target->watchpoints = NULL;
5212 target->next = NULL;
5213 target->arch_info = NULL;
5215 target->display = 1;
5217 target->halt_issued = false;
5219 /* initialize trace information */
5220 target->trace_info = malloc(sizeof(struct trace));
5221 target->trace_info->num_trace_points = 0;
5222 target->trace_info->trace_points_size = 0;
5223 target->trace_info->trace_points = NULL;
5224 target->trace_info->trace_history_size = 0;
5225 target->trace_info->trace_history = NULL;
5226 target->trace_info->trace_history_pos = 0;
5227 target->trace_info->trace_history_overflowed = 0;
5229 target->dbgmsg = NULL;
5230 target->dbg_msg_enabled = 0;
5232 target->endianness = TARGET_ENDIAN_UNKNOWN;
5234 target->rtos = NULL;
5235 target->rtos_auto_detect = false;
5237 /* Do the rest as "configure" options */
5238 goi->isconfigure = 1;
5239 e = target_configure(goi, target);
5241 if (target->tap == NULL) {
5242 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
5252 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5253 /* default endian to little if not specified */
5254 target->endianness = TARGET_LITTLE_ENDIAN;
5257 cp = Jim_GetString(new_cmd, NULL);
5258 target->cmd_name = strdup(cp);
5260 /* create the target specific commands */
5261 if (target->type->commands) {
5262 e = register_commands(cmd_ctx, NULL, target->type->commands);
5264 LOG_ERROR("unable to register '%s' commands", cp);
5266 if (target->type->target_create)
5267 (*(target->type->target_create))(target, goi->interp);
5269 /* append to end of list */
5271 struct target **tpp;
5272 tpp = &(all_targets);
5274 tpp = &((*tpp)->next);
5278 /* now - create the new target name command */
5279 const struct command_registration target_subcommands[] = {
5281 .chain = target_instance_command_handlers,
5284 .chain = target->type->commands,
5286 COMMAND_REGISTRATION_DONE
5288 const struct command_registration target_commands[] = {
5291 .mode = COMMAND_ANY,
5292 .help = "target command group",
5294 .chain = target_subcommands,
5296 COMMAND_REGISTRATION_DONE
5298 e = register_commands(cmd_ctx, NULL, target_commands);
5302 struct command *c = command_find_in_context(cmd_ctx, cp);
5304 command_set_handler_data(c, target);
5306 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5309 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5312 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5315 struct command_context *cmd_ctx = current_command_context(interp);
5316 assert(cmd_ctx != NULL);
5318 Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5322 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5325 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5328 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5329 for (unsigned x = 0; NULL != target_types[x]; x++) {
5330 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5331 Jim_NewStringObj(interp, target_types[x]->name, -1));
5336 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5339 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5342 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5343 struct target *target = all_targets;
5345 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5346 Jim_NewStringObj(interp, target_name(target), -1));
5347 target = target->next;
5352 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5355 const char *targetname;
5357 struct target *target = (struct target *) NULL;
5358 struct target_list *head, *curr, *new;
5359 curr = (struct target_list *) NULL;
5360 head = (struct target_list *) NULL;
5363 LOG_DEBUG("%d", argc);
5364 /* argv[1] = target to associate in smp
5365 * argv[2] = target to assoicate in smp
5369 for (i = 1; i < argc; i++) {
5371 targetname = Jim_GetString(argv[i], &len);
5372 target = get_target(targetname);
5373 LOG_DEBUG("%s ", targetname);
5375 new = malloc(sizeof(struct target_list));
5376 new->target = target;
5377 new->next = (struct target_list *)NULL;
5378 if (head == (struct target_list *)NULL) {
5387 /* now parse the list of cpu and put the target in smp mode*/
5390 while (curr != (struct target_list *)NULL) {
5391 target = curr->target;
5393 target->head = head;
5397 if (target && target->rtos)
5398 retval = rtos_smp_init(head->target);
5404 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5407 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5409 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5410 "<name> <target_type> [<target_options> ...]");
5413 return target_create(&goi);
5416 static const struct command_registration target_subcommand_handlers[] = {
5419 .mode = COMMAND_CONFIG,
5420 .handler = handle_target_init_command,
5421 .help = "initialize targets",
5425 /* REVISIT this should be COMMAND_CONFIG ... */
5426 .mode = COMMAND_ANY,
5427 .jim_handler = jim_target_create,
5428 .usage = "name type '-chain-position' name [options ...]",
5429 .help = "Creates and selects a new target",
5433 .mode = COMMAND_ANY,
5434 .jim_handler = jim_target_current,
5435 .help = "Returns the currently selected target",
5439 .mode = COMMAND_ANY,
5440 .jim_handler = jim_target_types,
5441 .help = "Returns the available target types as "
5442 "a list of strings",
5446 .mode = COMMAND_ANY,
5447 .jim_handler = jim_target_names,
5448 .help = "Returns the names of all targets as a list of strings",
5452 .mode = COMMAND_ANY,
5453 .jim_handler = jim_target_smp,
5454 .usage = "targetname1 targetname2 ...",
5455 .help = "gather several target in a smp list"
5458 COMMAND_REGISTRATION_DONE
5468 static int fastload_num;
5469 static struct FastLoad *fastload;
5471 static void free_fastload(void)
5473 if (fastload != NULL) {
5475 for (i = 0; i < fastload_num; i++) {
5476 if (fastload[i].data)
5477 free(fastload[i].data);
5484 COMMAND_HANDLER(handle_fast_load_image_command)
5488 uint32_t image_size;
5489 uint32_t min_address = 0;
5490 uint32_t max_address = 0xffffffff;
5495 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5496 &image, &min_address, &max_address);
5497 if (ERROR_OK != retval)
5500 struct duration bench;
5501 duration_start(&bench);
5503 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5504 if (retval != ERROR_OK)
5509 fastload_num = image.num_sections;
5510 fastload = malloc(sizeof(struct FastLoad)*image.num_sections);
5511 if (fastload == NULL) {
5512 command_print(CMD_CTX, "out of memory");
5513 image_close(&image);
5516 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5517 for (i = 0; i < image.num_sections; i++) {
5518 buffer = malloc(image.sections[i].size);
5519 if (buffer == NULL) {
5520 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5521 (int)(image.sections[i].size));
5522 retval = ERROR_FAIL;
5526 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5527 if (retval != ERROR_OK) {
5532 uint32_t offset = 0;
5533 uint32_t length = buf_cnt;
5535 /* DANGER!!! beware of unsigned comparision here!!! */
5537 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5538 (image.sections[i].base_address < max_address)) {
5539 if (image.sections[i].base_address < min_address) {
5540 /* clip addresses below */
5541 offset += min_address-image.sections[i].base_address;
5545 if (image.sections[i].base_address + buf_cnt > max_address)
5546 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5548 fastload[i].address = image.sections[i].base_address + offset;
5549 fastload[i].data = malloc(length);
5550 if (fastload[i].data == NULL) {
5552 command_print(CMD_CTX, "error allocating buffer for section (%" PRIu32 " bytes)",
5554 retval = ERROR_FAIL;
5557 memcpy(fastload[i].data, buffer + offset, length);
5558 fastload[i].length = length;
5560 image_size += length;
5561 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5562 (unsigned int)length,
5563 ((unsigned int)(image.sections[i].base_address + offset)));
5569 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5570 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5571 "in %fs (%0.3f KiB/s)", image_size,
5572 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5574 command_print(CMD_CTX,
5575 "WARNING: image has not been loaded to target!"
5576 "You can issue a 'fast_load' to finish loading.");
5579 image_close(&image);
5581 if (retval != ERROR_OK)
5587 COMMAND_HANDLER(handle_fast_load_command)
5590 return ERROR_COMMAND_SYNTAX_ERROR;
5591 if (fastload == NULL) {
5592 LOG_ERROR("No image in memory");
5596 int ms = timeval_ms();
5598 int retval = ERROR_OK;
5599 for (i = 0; i < fastload_num; i++) {
5600 struct target *target = get_current_target(CMD_CTX);
5601 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5602 (unsigned int)(fastload[i].address),
5603 (unsigned int)(fastload[i].length));
5604 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5605 if (retval != ERROR_OK)
5607 size += fastload[i].length;
5609 if (retval == ERROR_OK) {
5610 int after = timeval_ms();
5611 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5616 static const struct command_registration target_command_handlers[] = {
5619 .handler = handle_targets_command,
5620 .mode = COMMAND_ANY,
5621 .help = "change current default target (one parameter) "
5622 "or prints table of all targets (no parameters)",
5623 .usage = "[target]",
5627 .mode = COMMAND_CONFIG,
5628 .help = "configure target",
5630 .chain = target_subcommand_handlers,
5632 COMMAND_REGISTRATION_DONE
5635 int target_register_commands(struct command_context *cmd_ctx)
5637 return register_commands(cmd_ctx, NULL, target_command_handlers);
5640 static bool target_reset_nag = true;
5642 bool get_target_reset_nag(void)
5644 return target_reset_nag;
5647 COMMAND_HANDLER(handle_target_reset_nag)
5649 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5650 &target_reset_nag, "Nag after each reset about options to improve "
5654 COMMAND_HANDLER(handle_ps_command)
5656 struct target *target = get_current_target(CMD_CTX);
5658 if (target->state != TARGET_HALTED) {
5659 LOG_INFO("target not halted !!");
5663 if ((target->rtos) && (target->rtos->type)
5664 && (target->rtos->type->ps_command)) {
5665 display = target->rtos->type->ps_command(target);
5666 command_print(CMD_CTX, "%s", display);
5671 return ERROR_TARGET_FAILURE;
5675 static void binprint(struct command_context *cmd_ctx, const char *text, const uint8_t *buf, int size)
5678 command_print_sameline(cmd_ctx, "%s", text);
5679 for (int i = 0; i < size; i++)
5680 command_print_sameline(cmd_ctx, " %02x", buf[i]);
5681 command_print(cmd_ctx, " ");
5684 COMMAND_HANDLER(handle_test_mem_access_command)
5686 struct target *target = get_current_target(CMD_CTX);
5688 int retval = ERROR_OK;
5690 if (target->state != TARGET_HALTED) {
5691 LOG_INFO("target not halted !!");
5696 return ERROR_COMMAND_SYNTAX_ERROR;
5698 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
5701 size_t num_bytes = test_size + 4;
5703 struct working_area *wa = NULL;
5704 retval = target_alloc_working_area(target, num_bytes, &wa);
5705 if (retval != ERROR_OK) {
5706 LOG_ERROR("Not enough working area");
5710 uint8_t *test_pattern = malloc(num_bytes);
5712 for (size_t i = 0; i < num_bytes; i++)
5713 test_pattern[i] = rand();
5715 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
5716 if (retval != ERROR_OK) {
5717 LOG_ERROR("Test pattern write failed");
5721 for (int host_offset = 0; host_offset <= 1; host_offset++) {
5722 for (int size = 1; size <= 4; size *= 2) {
5723 for (int offset = 0; offset < 4; offset++) {
5724 uint32_t count = test_size / size;
5725 size_t host_bufsiz = (count + 2) * size + host_offset;
5726 uint8_t *read_ref = malloc(host_bufsiz);
5727 uint8_t *read_buf = malloc(host_bufsiz);
5729 for (size_t i = 0; i < host_bufsiz; i++) {
5730 read_ref[i] = rand();
5731 read_buf[i] = read_ref[i];
5733 command_print_sameline(CMD_CTX,
5734 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
5735 size, offset, host_offset ? "un" : "");
5737 struct duration bench;
5738 duration_start(&bench);
5740 retval = target_read_memory(target, wa->address + offset, size, count,
5741 read_buf + size + host_offset);
5743 duration_measure(&bench);
5745 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
5746 command_print(CMD_CTX, "Unsupported alignment");
5748 } else if (retval != ERROR_OK) {
5749 command_print(CMD_CTX, "Memory read failed");
5753 /* replay on host */
5754 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
5757 int result = memcmp(read_ref, read_buf, host_bufsiz);
5759 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
5760 duration_elapsed(&bench),
5761 duration_kbps(&bench, count * size));
5763 command_print(CMD_CTX, "Compare failed");
5764 binprint(CMD_CTX, "ref:", read_ref, host_bufsiz);
5765 binprint(CMD_CTX, "buf:", read_buf, host_bufsiz);
5778 target_free_working_area(target, wa);
5781 num_bytes = test_size + 4 + 4 + 4;
5783 retval = target_alloc_working_area(target, num_bytes, &wa);
5784 if (retval != ERROR_OK) {
5785 LOG_ERROR("Not enough working area");
5789 test_pattern = malloc(num_bytes);
5791 for (size_t i = 0; i < num_bytes; i++)
5792 test_pattern[i] = rand();
5794 for (int host_offset = 0; host_offset <= 1; host_offset++) {
5795 for (int size = 1; size <= 4; size *= 2) {
5796 for (int offset = 0; offset < 4; offset++) {
5797 uint32_t count = test_size / size;
5798 size_t host_bufsiz = count * size + host_offset;
5799 uint8_t *read_ref = malloc(num_bytes);
5800 uint8_t *read_buf = malloc(num_bytes);
5801 uint8_t *write_buf = malloc(host_bufsiz);
5803 for (size_t i = 0; i < host_bufsiz; i++)
5804 write_buf[i] = rand();
5805 command_print_sameline(CMD_CTX,
5806 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
5807 size, offset, host_offset ? "un" : "");
5809 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
5810 if (retval != ERROR_OK) {
5811 command_print(CMD_CTX, "Test pattern write failed");
5815 /* replay on host */
5816 memcpy(read_ref, test_pattern, num_bytes);
5817 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
5819 struct duration bench;
5820 duration_start(&bench);
5822 retval = target_write_memory(target, wa->address + size + offset, size, count,
5823 write_buf + host_offset);
5825 duration_measure(&bench);
5827 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
5828 command_print(CMD_CTX, "Unsupported alignment");
5830 } else if (retval != ERROR_OK) {
5831 command_print(CMD_CTX, "Memory write failed");
5836 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
5837 if (retval != ERROR_OK) {
5838 command_print(CMD_CTX, "Test pattern write failed");
5843 int result = memcmp(read_ref, read_buf, num_bytes);
5845 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
5846 duration_elapsed(&bench),
5847 duration_kbps(&bench, count * size));
5849 command_print(CMD_CTX, "Compare failed");
5850 binprint(CMD_CTX, "ref:", read_ref, num_bytes);
5851 binprint(CMD_CTX, "buf:", read_buf, num_bytes);
5863 target_free_working_area(target, wa);
5867 static const struct command_registration target_exec_command_handlers[] = {
5869 .name = "fast_load_image",
5870 .handler = handle_fast_load_image_command,
5871 .mode = COMMAND_ANY,
5872 .help = "Load image into server memory for later use by "
5873 "fast_load; primarily for profiling",
5874 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5875 "[min_address [max_length]]",
5878 .name = "fast_load",
5879 .handler = handle_fast_load_command,
5880 .mode = COMMAND_EXEC,
5881 .help = "loads active fast load image to current target "
5882 "- mainly for profiling purposes",
5887 .handler = handle_profile_command,
5888 .mode = COMMAND_EXEC,
5889 .usage = "seconds filename [start end]",
5890 .help = "profiling samples the CPU PC",
5892 /** @todo don't register virt2phys() unless target supports it */
5894 .name = "virt2phys",
5895 .handler = handle_virt2phys_command,
5896 .mode = COMMAND_ANY,
5897 .help = "translate a virtual address into a physical address",
5898 .usage = "virtual_address",
5902 .handler = handle_reg_command,
5903 .mode = COMMAND_EXEC,
5904 .help = "display (reread from target with \"force\") or set a register; "
5905 "with no arguments, displays all registers and their values",
5906 .usage = "[(register_number|register_name) [(value|'force')]]",
5910 .handler = handle_poll_command,
5911 .mode = COMMAND_EXEC,
5912 .help = "poll target state; or reconfigure background polling",
5913 .usage = "['on'|'off']",
5916 .name = "wait_halt",
5917 .handler = handle_wait_halt_command,
5918 .mode = COMMAND_EXEC,
5919 .help = "wait up to the specified number of milliseconds "
5920 "(default 5000) for a previously requested halt",
5921 .usage = "[milliseconds]",
5925 .handler = handle_halt_command,
5926 .mode = COMMAND_EXEC,
5927 .help = "request target to halt, then wait up to the specified"
5928 "number of milliseconds (default 5000) for it to complete",
5929 .usage = "[milliseconds]",
5933 .handler = handle_resume_command,
5934 .mode = COMMAND_EXEC,
5935 .help = "resume target execution from current PC or address",
5936 .usage = "[address]",
5940 .handler = handle_reset_command,
5941 .mode = COMMAND_EXEC,
5942 .usage = "[run|halt|init]",
5943 .help = "Reset all targets into the specified mode."
5944 "Default reset mode is run, if not given.",
5947 .name = "soft_reset_halt",
5948 .handler = handle_soft_reset_halt_command,
5949 .mode = COMMAND_EXEC,
5951 .help = "halt the target and do a soft reset",
5955 .handler = handle_step_command,
5956 .mode = COMMAND_EXEC,
5957 .help = "step one instruction from current PC or address",
5958 .usage = "[address]",
5962 .handler = handle_md_command,
5963 .mode = COMMAND_EXEC,
5964 .help = "display memory words",
5965 .usage = "['phys'] address [count]",
5969 .handler = handle_md_command,
5970 .mode = COMMAND_EXEC,
5971 .help = "display memory half-words",
5972 .usage = "['phys'] address [count]",
5976 .handler = handle_md_command,
5977 .mode = COMMAND_EXEC,
5978 .help = "display memory bytes",
5979 .usage = "['phys'] address [count]",
5983 .handler = handle_mw_command,
5984 .mode = COMMAND_EXEC,
5985 .help = "write memory word",
5986 .usage = "['phys'] address value [count]",
5990 .handler = handle_mw_command,
5991 .mode = COMMAND_EXEC,
5992 .help = "write memory half-word",
5993 .usage = "['phys'] address value [count]",
5997 .handler = handle_mw_command,
5998 .mode = COMMAND_EXEC,
5999 .help = "write memory byte",
6000 .usage = "['phys'] address value [count]",
6004 .handler = handle_bp_command,
6005 .mode = COMMAND_EXEC,
6006 .help = "list or set hardware or software breakpoint",
6007 .usage = "<address> [<asid>]<length> ['hw'|'hw_ctx']",
6011 .handler = handle_rbp_command,
6012 .mode = COMMAND_EXEC,
6013 .help = "remove breakpoint",
6018 .handler = handle_wp_command,
6019 .mode = COMMAND_EXEC,
6020 .help = "list (no params) or create watchpoints",
6021 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
6025 .handler = handle_rwp_command,
6026 .mode = COMMAND_EXEC,
6027 .help = "remove watchpoint",
6031 .name = "load_image",
6032 .handler = handle_load_image_command,
6033 .mode = COMMAND_EXEC,
6034 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6035 "[min_address] [max_length]",
6038 .name = "dump_image",
6039 .handler = handle_dump_image_command,
6040 .mode = COMMAND_EXEC,
6041 .usage = "filename address size",
6044 .name = "verify_image",
6045 .handler = handle_verify_image_command,
6046 .mode = COMMAND_EXEC,
6047 .usage = "filename [offset [type]]",
6050 .name = "test_image",
6051 .handler = handle_test_image_command,
6052 .mode = COMMAND_EXEC,
6053 .usage = "filename [offset [type]]",
6056 .name = "mem2array",
6057 .mode = COMMAND_EXEC,
6058 .jim_handler = jim_mem2array,
6059 .help = "read 8/16/32 bit memory and return as a TCL array "
6060 "for script processing",
6061 .usage = "arrayname bitwidth address count",
6064 .name = "array2mem",
6065 .mode = COMMAND_EXEC,
6066 .jim_handler = jim_array2mem,
6067 .help = "convert a TCL array to memory locations "
6068 "and write the 8/16/32 bit values",
6069 .usage = "arrayname bitwidth address count",
6072 .name = "reset_nag",
6073 .handler = handle_target_reset_nag,
6074 .mode = COMMAND_ANY,
6075 .help = "Nag after each reset about options that could have been "
6076 "enabled to improve performance. ",
6077 .usage = "['enable'|'disable']",
6081 .handler = handle_ps_command,
6082 .mode = COMMAND_EXEC,
6083 .help = "list all tasks ",
6087 .name = "test_mem_access",
6088 .handler = handle_test_mem_access_command,
6089 .mode = COMMAND_EXEC,
6090 .help = "Test the target's memory access functions",
6094 COMMAND_REGISTRATION_DONE
6096 static int target_register_user_commands(struct command_context *cmd_ctx)
6098 int retval = ERROR_OK;
6099 retval = target_request_register_commands(cmd_ctx);
6100 if (retval != ERROR_OK)
6103 retval = trace_register_commands(cmd_ctx);
6104 if (retval != ERROR_OK)
6108 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);