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 LIST_HEAD(target_trace_callback_list);
144 static const int polling_interval = 100;
146 static const Jim_Nvp nvp_assert[] = {
147 { .name = "assert", NVP_ASSERT },
148 { .name = "deassert", NVP_DEASSERT },
149 { .name = "T", NVP_ASSERT },
150 { .name = "F", NVP_DEASSERT },
151 { .name = "t", NVP_ASSERT },
152 { .name = "f", NVP_DEASSERT },
153 { .name = NULL, .value = -1 }
156 static const Jim_Nvp nvp_error_target[] = {
157 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
158 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
159 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
160 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
161 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
162 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
163 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
164 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
165 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
166 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
167 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
168 { .value = -1, .name = NULL }
171 static const char *target_strerror_safe(int err)
175 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
182 static const Jim_Nvp nvp_target_event[] = {
184 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
185 { .value = TARGET_EVENT_HALTED, .name = "halted" },
186 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
187 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
188 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
190 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
191 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
193 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
194 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
195 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
196 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
197 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
198 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
199 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
200 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
201 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
202 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
203 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
204 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
206 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
207 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
209 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
210 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
212 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
213 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
215 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
216 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
218 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
219 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
221 { .value = TARGET_EVENT_TRACE_CONFIG, .name = "trace-config" },
223 { .name = NULL, .value = -1 }
226 static const Jim_Nvp nvp_target_state[] = {
227 { .name = "unknown", .value = TARGET_UNKNOWN },
228 { .name = "running", .value = TARGET_RUNNING },
229 { .name = "halted", .value = TARGET_HALTED },
230 { .name = "reset", .value = TARGET_RESET },
231 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
232 { .name = NULL, .value = -1 },
235 static const Jim_Nvp nvp_target_debug_reason[] = {
236 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
237 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
238 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
239 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
240 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
241 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
242 { .name = "program-exit" , .value = DBG_REASON_EXIT },
243 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
244 { .name = NULL, .value = -1 },
247 static const Jim_Nvp nvp_target_endian[] = {
248 { .name = "big", .value = TARGET_BIG_ENDIAN },
249 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
250 { .name = "be", .value = TARGET_BIG_ENDIAN },
251 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
252 { .name = NULL, .value = -1 },
255 static const Jim_Nvp nvp_reset_modes[] = {
256 { .name = "unknown", .value = RESET_UNKNOWN },
257 { .name = "run" , .value = RESET_RUN },
258 { .name = "halt" , .value = RESET_HALT },
259 { .name = "init" , .value = RESET_INIT },
260 { .name = NULL , .value = -1 },
263 const char *debug_reason_name(struct target *t)
267 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
268 t->debug_reason)->name;
270 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
271 cp = "(*BUG*unknown*BUG*)";
276 const char *target_state_name(struct target *t)
279 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
281 LOG_ERROR("Invalid target state: %d", (int)(t->state));
282 cp = "(*BUG*unknown*BUG*)";
287 const char *target_event_name(enum target_event event)
290 cp = Jim_Nvp_value2name_simple(nvp_target_event, event)->name;
292 LOG_ERROR("Invalid target event: %d", (int)(event));
293 cp = "(*BUG*unknown*BUG*)";
298 const char *target_reset_mode_name(enum target_reset_mode reset_mode)
301 cp = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name;
303 LOG_ERROR("Invalid target reset mode: %d", (int)(reset_mode));
304 cp = "(*BUG*unknown*BUG*)";
309 /* determine the number of the new target */
310 static int new_target_number(void)
315 /* number is 0 based */
319 if (x < t->target_number)
320 x = t->target_number;
326 /* read a uint64_t from a buffer in target memory endianness */
327 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
329 if (target->endianness == TARGET_LITTLE_ENDIAN)
330 return le_to_h_u64(buffer);
332 return be_to_h_u64(buffer);
335 /* read a uint32_t from a buffer in target memory endianness */
336 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
338 if (target->endianness == TARGET_LITTLE_ENDIAN)
339 return le_to_h_u32(buffer);
341 return be_to_h_u32(buffer);
344 /* read a uint24_t from a buffer in target memory endianness */
345 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
347 if (target->endianness == TARGET_LITTLE_ENDIAN)
348 return le_to_h_u24(buffer);
350 return be_to_h_u24(buffer);
353 /* read a uint16_t from a buffer in target memory endianness */
354 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
356 if (target->endianness == TARGET_LITTLE_ENDIAN)
357 return le_to_h_u16(buffer);
359 return be_to_h_u16(buffer);
362 /* read a uint8_t from a buffer in target memory endianness */
363 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
365 return *buffer & 0x0ff;
368 /* write a uint64_t to a buffer in target memory endianness */
369 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
371 if (target->endianness == TARGET_LITTLE_ENDIAN)
372 h_u64_to_le(buffer, value);
374 h_u64_to_be(buffer, value);
377 /* write a uint32_t to a buffer in target memory endianness */
378 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
380 if (target->endianness == TARGET_LITTLE_ENDIAN)
381 h_u32_to_le(buffer, value);
383 h_u32_to_be(buffer, value);
386 /* write a uint24_t to a buffer in target memory endianness */
387 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
389 if (target->endianness == TARGET_LITTLE_ENDIAN)
390 h_u24_to_le(buffer, value);
392 h_u24_to_be(buffer, value);
395 /* write a uint16_t to a buffer in target memory endianness */
396 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
398 if (target->endianness == TARGET_LITTLE_ENDIAN)
399 h_u16_to_le(buffer, value);
401 h_u16_to_be(buffer, value);
404 /* write a uint8_t to a buffer in target memory endianness */
405 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
410 /* write a uint64_t array to a buffer in target memory endianness */
411 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
414 for (i = 0; i < count; i++)
415 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
418 /* write a uint32_t array to a buffer in target memory endianness */
419 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
422 for (i = 0; i < count; i++)
423 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
426 /* write a uint16_t array to a buffer in target memory endianness */
427 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
430 for (i = 0; i < count; i++)
431 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
434 /* write a uint64_t array to a buffer in target memory endianness */
435 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
438 for (i = 0; i < count; i++)
439 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
442 /* write a uint32_t array to a buffer in target memory endianness */
443 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
446 for (i = 0; i < count; i++)
447 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
450 /* write a uint16_t array to a buffer in target memory endianness */
451 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
454 for (i = 0; i < count; i++)
455 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
458 /* return a pointer to a configured target; id is name or number */
459 struct target *get_target(const char *id)
461 struct target *target;
463 /* try as tcltarget name */
464 for (target = all_targets; target; target = target->next) {
465 if (target_name(target) == NULL)
467 if (strcmp(id, target_name(target)) == 0)
471 /* It's OK to remove this fallback sometime after August 2010 or so */
473 /* no match, try as number */
475 if (parse_uint(id, &num) != ERROR_OK)
478 for (target = all_targets; target; target = target->next) {
479 if (target->target_number == (int)num) {
480 LOG_WARNING("use '%s' as target identifier, not '%u'",
481 target_name(target), num);
489 /* returns a pointer to the n-th configured target */
490 struct target *get_target_by_num(int num)
492 struct target *target = all_targets;
495 if (target->target_number == num)
497 target = target->next;
503 struct target *get_current_target(struct command_context *cmd_ctx)
505 struct target *target = get_target_by_num(cmd_ctx->current_target);
507 if (target == NULL) {
508 LOG_ERROR("BUG: current_target out of bounds");
515 int target_poll(struct target *target)
519 /* We can't poll until after examine */
520 if (!target_was_examined(target)) {
521 /* Fail silently lest we pollute the log */
525 retval = target->type->poll(target);
526 if (retval != ERROR_OK)
529 if (target->halt_issued) {
530 if (target->state == TARGET_HALTED)
531 target->halt_issued = false;
533 long long t = timeval_ms() - target->halt_issued_time;
534 if (t > DEFAULT_HALT_TIMEOUT) {
535 target->halt_issued = false;
536 LOG_INFO("Halt timed out, wake up GDB.");
537 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
545 int target_halt(struct target *target)
548 /* We can't poll until after examine */
549 if (!target_was_examined(target)) {
550 LOG_ERROR("Target not examined yet");
554 retval = target->type->halt(target);
555 if (retval != ERROR_OK)
558 target->halt_issued = true;
559 target->halt_issued_time = timeval_ms();
565 * Make the target (re)start executing using its saved execution
566 * context (possibly with some modifications).
568 * @param target Which target should start executing.
569 * @param current True to use the target's saved program counter instead
570 * of the address parameter
571 * @param address Optionally used as the program counter.
572 * @param handle_breakpoints True iff breakpoints at the resumption PC
573 * should be skipped. (For example, maybe execution was stopped by
574 * such a breakpoint, in which case it would be counterprodutive to
576 * @param debug_execution False if all working areas allocated by OpenOCD
577 * should be released and/or restored to their original contents.
578 * (This would for example be true to run some downloaded "helper"
579 * algorithm code, which resides in one such working buffer and uses
580 * another for data storage.)
582 * @todo Resolve the ambiguity about what the "debug_execution" flag
583 * signifies. For example, Target implementations don't agree on how
584 * it relates to invalidation of the register cache, or to whether
585 * breakpoints and watchpoints should be enabled. (It would seem wrong
586 * to enable breakpoints when running downloaded "helper" algorithms
587 * (debug_execution true), since the breakpoints would be set to match
588 * target firmware being debugged, not the helper algorithm.... and
589 * enabling them could cause such helpers to malfunction (for example,
590 * by overwriting data with a breakpoint instruction. On the other
591 * hand the infrastructure for running such helpers might use this
592 * procedure but rely on hardware breakpoint to detect termination.)
594 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
598 /* We can't poll until after examine */
599 if (!target_was_examined(target)) {
600 LOG_ERROR("Target not examined yet");
604 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
606 /* note that resume *must* be asynchronous. The CPU can halt before
607 * we poll. The CPU can even halt at the current PC as a result of
608 * a software breakpoint being inserted by (a bug?) the application.
610 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
611 if (retval != ERROR_OK)
614 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
619 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
624 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
625 if (n->name == NULL) {
626 LOG_ERROR("invalid reset mode");
630 struct target *target;
631 for (target = all_targets; target; target = target->next)
632 target_call_reset_callbacks(target, reset_mode);
634 /* disable polling during reset to make reset event scripts
635 * more predictable, i.e. dr/irscan & pathmove in events will
636 * not have JTAG operations injected into the middle of a sequence.
638 bool save_poll = jtag_poll_get_enabled();
640 jtag_poll_set_enabled(false);
642 sprintf(buf, "ocd_process_reset %s", n->name);
643 retval = Jim_Eval(cmd_ctx->interp, buf);
645 jtag_poll_set_enabled(save_poll);
647 if (retval != JIM_OK) {
648 Jim_MakeErrorMessage(cmd_ctx->interp);
649 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
653 /* We want any events to be processed before the prompt */
654 retval = target_call_timer_callbacks_now();
656 for (target = all_targets; target; target = target->next) {
657 target->type->check_reset(target);
658 target->running_alg = false;
664 static int identity_virt2phys(struct target *target,
665 uint32_t virtual, uint32_t *physical)
671 static int no_mmu(struct target *target, int *enabled)
677 static int default_examine(struct target *target)
679 target_set_examined(target);
683 /* no check by default */
684 static int default_check_reset(struct target *target)
689 int target_examine_one(struct target *target)
691 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
693 int retval = target->type->examine(target);
694 if (retval != ERROR_OK)
697 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
702 static int jtag_enable_callback(enum jtag_event event, void *priv)
704 struct target *target = priv;
706 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
709 jtag_unregister_event_callback(jtag_enable_callback, target);
711 return target_examine_one(target);
714 /* Targets that correctly implement init + examine, i.e.
715 * no communication with target during init:
719 int target_examine(void)
721 int retval = ERROR_OK;
722 struct target *target;
724 for (target = all_targets; target; target = target->next) {
725 /* defer examination, but don't skip it */
726 if (!target->tap->enabled) {
727 jtag_register_event_callback(jtag_enable_callback,
732 retval = target_examine_one(target);
733 if (retval != ERROR_OK)
739 const char *target_type_name(struct target *target)
741 return target->type->name;
744 static int target_soft_reset_halt(struct target *target)
746 if (!target_was_examined(target)) {
747 LOG_ERROR("Target not examined yet");
750 if (!target->type->soft_reset_halt) {
751 LOG_ERROR("Target %s does not support soft_reset_halt",
752 target_name(target));
755 return target->type->soft_reset_halt(target);
759 * Downloads a target-specific native code algorithm to the target,
760 * and executes it. * Note that some targets may need to set up, enable,
761 * and tear down a breakpoint (hard or * soft) to detect algorithm
762 * termination, while others may support lower overhead schemes where
763 * soft breakpoints embedded in the algorithm automatically terminate the
766 * @param target used to run the algorithm
767 * @param arch_info target-specific description of the algorithm.
769 int target_run_algorithm(struct target *target,
770 int num_mem_params, struct mem_param *mem_params,
771 int num_reg_params, struct reg_param *reg_param,
772 uint32_t entry_point, uint32_t exit_point,
773 int timeout_ms, void *arch_info)
775 int retval = ERROR_FAIL;
777 if (!target_was_examined(target)) {
778 LOG_ERROR("Target not examined yet");
781 if (!target->type->run_algorithm) {
782 LOG_ERROR("Target type '%s' does not support %s",
783 target_type_name(target), __func__);
787 target->running_alg = true;
788 retval = target->type->run_algorithm(target,
789 num_mem_params, mem_params,
790 num_reg_params, reg_param,
791 entry_point, exit_point, timeout_ms, arch_info);
792 target->running_alg = false;
799 * Downloads a target-specific native code algorithm to the target,
800 * executes and leaves it running.
802 * @param target used to run the algorithm
803 * @param arch_info target-specific description of the algorithm.
805 int target_start_algorithm(struct target *target,
806 int num_mem_params, struct mem_param *mem_params,
807 int num_reg_params, struct reg_param *reg_params,
808 uint32_t entry_point, uint32_t exit_point,
811 int retval = ERROR_FAIL;
813 if (!target_was_examined(target)) {
814 LOG_ERROR("Target not examined yet");
817 if (!target->type->start_algorithm) {
818 LOG_ERROR("Target type '%s' does not support %s",
819 target_type_name(target), __func__);
822 if (target->running_alg) {
823 LOG_ERROR("Target is already running an algorithm");
827 target->running_alg = true;
828 retval = target->type->start_algorithm(target,
829 num_mem_params, mem_params,
830 num_reg_params, reg_params,
831 entry_point, exit_point, arch_info);
838 * Waits for an algorithm started with target_start_algorithm() to complete.
840 * @param target used to run the algorithm
841 * @param arch_info target-specific description of the algorithm.
843 int target_wait_algorithm(struct target *target,
844 int num_mem_params, struct mem_param *mem_params,
845 int num_reg_params, struct reg_param *reg_params,
846 uint32_t exit_point, int timeout_ms,
849 int retval = ERROR_FAIL;
851 if (!target->type->wait_algorithm) {
852 LOG_ERROR("Target type '%s' does not support %s",
853 target_type_name(target), __func__);
856 if (!target->running_alg) {
857 LOG_ERROR("Target is not running an algorithm");
861 retval = target->type->wait_algorithm(target,
862 num_mem_params, mem_params,
863 num_reg_params, reg_params,
864 exit_point, timeout_ms, arch_info);
865 if (retval != ERROR_TARGET_TIMEOUT)
866 target->running_alg = false;
873 * Executes a target-specific native code algorithm in the target.
874 * It differs from target_run_algorithm in that the algorithm is asynchronous.
875 * Because of this it requires an compliant algorithm:
876 * see contrib/loaders/flash/stm32f1x.S for example.
878 * @param target used to run the algorithm
881 int target_run_flash_async_algorithm(struct target *target,
882 const uint8_t *buffer, uint32_t count, int block_size,
883 int num_mem_params, struct mem_param *mem_params,
884 int num_reg_params, struct reg_param *reg_params,
885 uint32_t buffer_start, uint32_t buffer_size,
886 uint32_t entry_point, uint32_t exit_point, void *arch_info)
891 const uint8_t *buffer_orig = buffer;
893 /* Set up working area. First word is write pointer, second word is read pointer,
894 * rest is fifo data area. */
895 uint32_t wp_addr = buffer_start;
896 uint32_t rp_addr = buffer_start + 4;
897 uint32_t fifo_start_addr = buffer_start + 8;
898 uint32_t fifo_end_addr = buffer_start + buffer_size;
900 uint32_t wp = fifo_start_addr;
901 uint32_t rp = fifo_start_addr;
903 /* validate block_size is 2^n */
904 assert(!block_size || !(block_size & (block_size - 1)));
906 retval = target_write_u32(target, wp_addr, wp);
907 if (retval != ERROR_OK)
909 retval = target_write_u32(target, rp_addr, rp);
910 if (retval != ERROR_OK)
913 /* Start up algorithm on target and let it idle while writing the first chunk */
914 retval = target_start_algorithm(target, num_mem_params, mem_params,
915 num_reg_params, reg_params,
920 if (retval != ERROR_OK) {
921 LOG_ERROR("error starting target flash write algorithm");
927 retval = target_read_u32(target, rp_addr, &rp);
928 if (retval != ERROR_OK) {
929 LOG_ERROR("failed to get read pointer");
933 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
934 (size_t) (buffer - buffer_orig), count, wp, rp);
937 LOG_ERROR("flash write algorithm aborted by target");
938 retval = ERROR_FLASH_OPERATION_FAILED;
942 if (((rp - fifo_start_addr) & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
943 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
947 /* Count the number of bytes available in the fifo without
948 * crossing the wrap around. Make sure to not fill it completely,
949 * because that would make wp == rp and that's the empty condition. */
950 uint32_t thisrun_bytes;
952 thisrun_bytes = rp - wp - block_size;
953 else if (rp > fifo_start_addr)
954 thisrun_bytes = fifo_end_addr - wp;
956 thisrun_bytes = fifo_end_addr - wp - block_size;
958 if (thisrun_bytes == 0) {
959 /* Throttle polling a bit if transfer is (much) faster than flash
960 * programming. The exact delay shouldn't matter as long as it's
961 * less than buffer size / flash speed. This is very unlikely to
962 * run when using high latency connections such as USB. */
965 /* to stop an infinite loop on some targets check and increment a timeout
966 * this issue was observed on a stellaris using the new ICDI interface */
967 if (timeout++ >= 500) {
968 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
969 return ERROR_FLASH_OPERATION_FAILED;
974 /* reset our timeout */
977 /* Limit to the amount of data we actually want to write */
978 if (thisrun_bytes > count * block_size)
979 thisrun_bytes = count * block_size;
981 /* Write data to fifo */
982 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
983 if (retval != ERROR_OK)
986 /* Update counters and wrap write pointer */
987 buffer += thisrun_bytes;
988 count -= thisrun_bytes / block_size;
990 if (wp >= fifo_end_addr)
991 wp = fifo_start_addr;
993 /* Store updated write pointer to target */
994 retval = target_write_u32(target, wp_addr, wp);
995 if (retval != ERROR_OK)
999 if (retval != ERROR_OK) {
1000 /* abort flash write algorithm on target */
1001 target_write_u32(target, wp_addr, 0);
1004 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1005 num_reg_params, reg_params,
1010 if (retval2 != ERROR_OK) {
1011 LOG_ERROR("error waiting for target flash write algorithm");
1018 int target_read_memory(struct target *target,
1019 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1021 if (!target_was_examined(target)) {
1022 LOG_ERROR("Target not examined yet");
1025 if (!target->type->read_memory) {
1026 LOG_ERROR("Target %s doesn't support read_memory", target_name(target));
1029 return target->type->read_memory(target, address, size, count, buffer);
1032 int target_read_phys_memory(struct target *target,
1033 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1035 if (!target_was_examined(target)) {
1036 LOG_ERROR("Target not examined yet");
1039 if (!target->type->read_phys_memory) {
1040 LOG_ERROR("Target %s doesn't support read_phys_memory", target_name(target));
1043 return target->type->read_phys_memory(target, address, size, count, buffer);
1046 int target_write_memory(struct target *target,
1047 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1049 if (!target_was_examined(target)) {
1050 LOG_ERROR("Target not examined yet");
1053 if (!target->type->write_memory) {
1054 LOG_ERROR("Target %s doesn't support write_memory", target_name(target));
1057 return target->type->write_memory(target, address, size, count, buffer);
1060 int target_write_phys_memory(struct target *target,
1061 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1063 if (!target_was_examined(target)) {
1064 LOG_ERROR("Target not examined yet");
1067 if (!target->type->write_phys_memory) {
1068 LOG_ERROR("Target %s doesn't support write_phys_memory", target_name(target));
1071 return target->type->write_phys_memory(target, address, size, count, buffer);
1074 int target_add_breakpoint(struct target *target,
1075 struct breakpoint *breakpoint)
1077 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1078 LOG_WARNING("target %s is not halted", target_name(target));
1079 return ERROR_TARGET_NOT_HALTED;
1081 return target->type->add_breakpoint(target, breakpoint);
1084 int target_add_context_breakpoint(struct target *target,
1085 struct breakpoint *breakpoint)
1087 if (target->state != TARGET_HALTED) {
1088 LOG_WARNING("target %s is not halted", target_name(target));
1089 return ERROR_TARGET_NOT_HALTED;
1091 return target->type->add_context_breakpoint(target, breakpoint);
1094 int target_add_hybrid_breakpoint(struct target *target,
1095 struct breakpoint *breakpoint)
1097 if (target->state != TARGET_HALTED) {
1098 LOG_WARNING("target %s is not halted", target_name(target));
1099 return ERROR_TARGET_NOT_HALTED;
1101 return target->type->add_hybrid_breakpoint(target, breakpoint);
1104 int target_remove_breakpoint(struct target *target,
1105 struct breakpoint *breakpoint)
1107 return target->type->remove_breakpoint(target, breakpoint);
1110 int target_add_watchpoint(struct target *target,
1111 struct watchpoint *watchpoint)
1113 if (target->state != TARGET_HALTED) {
1114 LOG_WARNING("target %s is not halted", target_name(target));
1115 return ERROR_TARGET_NOT_HALTED;
1117 return target->type->add_watchpoint(target, watchpoint);
1119 int target_remove_watchpoint(struct target *target,
1120 struct watchpoint *watchpoint)
1122 return target->type->remove_watchpoint(target, watchpoint);
1124 int target_hit_watchpoint(struct target *target,
1125 struct watchpoint **hit_watchpoint)
1127 if (target->state != TARGET_HALTED) {
1128 LOG_WARNING("target %s is not halted", target->cmd_name);
1129 return ERROR_TARGET_NOT_HALTED;
1132 if (target->type->hit_watchpoint == NULL) {
1133 /* For backward compatible, if hit_watchpoint is not implemented,
1134 * return ERROR_FAIL such that gdb_server will not take the nonsense
1139 return target->type->hit_watchpoint(target, hit_watchpoint);
1142 int target_get_gdb_reg_list(struct target *target,
1143 struct reg **reg_list[], int *reg_list_size,
1144 enum target_register_class reg_class)
1146 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1148 int target_step(struct target *target,
1149 int current, uint32_t address, int handle_breakpoints)
1151 return target->type->step(target, current, address, handle_breakpoints);
1154 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1156 if (target->state != TARGET_HALTED) {
1157 LOG_WARNING("target %s is not halted", target->cmd_name);
1158 return ERROR_TARGET_NOT_HALTED;
1160 return target->type->get_gdb_fileio_info(target, fileio_info);
1163 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1165 if (target->state != TARGET_HALTED) {
1166 LOG_WARNING("target %s is not halted", target->cmd_name);
1167 return ERROR_TARGET_NOT_HALTED;
1169 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1172 int target_profiling(struct target *target, uint32_t *samples,
1173 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1175 if (target->state != TARGET_HALTED) {
1176 LOG_WARNING("target %s is not halted", target->cmd_name);
1177 return ERROR_TARGET_NOT_HALTED;
1179 return target->type->profiling(target, samples, max_num_samples,
1180 num_samples, seconds);
1184 * Reset the @c examined flag for the given target.
1185 * Pure paranoia -- targets are zeroed on allocation.
1187 static void target_reset_examined(struct target *target)
1189 target->examined = false;
1192 static int handle_target(void *priv);
1194 static int target_init_one(struct command_context *cmd_ctx,
1195 struct target *target)
1197 target_reset_examined(target);
1199 struct target_type *type = target->type;
1200 if (type->examine == NULL)
1201 type->examine = default_examine;
1203 if (type->check_reset == NULL)
1204 type->check_reset = default_check_reset;
1206 assert(type->init_target != NULL);
1208 int retval = type->init_target(cmd_ctx, target);
1209 if (ERROR_OK != retval) {
1210 LOG_ERROR("target '%s' init failed", target_name(target));
1214 /* Sanity-check MMU support ... stub in what we must, to help
1215 * implement it in stages, but warn if we need to do so.
1218 if (type->virt2phys == NULL) {
1219 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1220 type->virt2phys = identity_virt2phys;
1223 /* Make sure no-MMU targets all behave the same: make no
1224 * distinction between physical and virtual addresses, and
1225 * ensure that virt2phys() is always an identity mapping.
1227 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1228 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1231 type->write_phys_memory = type->write_memory;
1232 type->read_phys_memory = type->read_memory;
1233 type->virt2phys = identity_virt2phys;
1236 if (target->type->read_buffer == NULL)
1237 target->type->read_buffer = target_read_buffer_default;
1239 if (target->type->write_buffer == NULL)
1240 target->type->write_buffer = target_write_buffer_default;
1242 if (target->type->get_gdb_fileio_info == NULL)
1243 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1245 if (target->type->gdb_fileio_end == NULL)
1246 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1248 if (target->type->profiling == NULL)
1249 target->type->profiling = target_profiling_default;
1254 static int target_init(struct command_context *cmd_ctx)
1256 struct target *target;
1259 for (target = all_targets; target; target = target->next) {
1260 retval = target_init_one(cmd_ctx, target);
1261 if (ERROR_OK != retval)
1268 retval = target_register_user_commands(cmd_ctx);
1269 if (ERROR_OK != retval)
1272 retval = target_register_timer_callback(&handle_target,
1273 polling_interval, 1, cmd_ctx->interp);
1274 if (ERROR_OK != retval)
1280 COMMAND_HANDLER(handle_target_init_command)
1285 return ERROR_COMMAND_SYNTAX_ERROR;
1287 static bool target_initialized;
1288 if (target_initialized) {
1289 LOG_INFO("'target init' has already been called");
1292 target_initialized = true;
1294 retval = command_run_line(CMD_CTX, "init_targets");
1295 if (ERROR_OK != retval)
1298 retval = command_run_line(CMD_CTX, "init_target_events");
1299 if (ERROR_OK != retval)
1302 retval = command_run_line(CMD_CTX, "init_board");
1303 if (ERROR_OK != retval)
1306 LOG_DEBUG("Initializing targets...");
1307 return target_init(CMD_CTX);
1310 int target_register_event_callback(int (*callback)(struct target *target,
1311 enum target_event event, void *priv), void *priv)
1313 struct target_event_callback **callbacks_p = &target_event_callbacks;
1315 if (callback == NULL)
1316 return ERROR_COMMAND_SYNTAX_ERROR;
1319 while ((*callbacks_p)->next)
1320 callbacks_p = &((*callbacks_p)->next);
1321 callbacks_p = &((*callbacks_p)->next);
1324 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1325 (*callbacks_p)->callback = callback;
1326 (*callbacks_p)->priv = priv;
1327 (*callbacks_p)->next = NULL;
1332 int target_register_reset_callback(int (*callback)(struct target *target,
1333 enum target_reset_mode reset_mode, void *priv), void *priv)
1335 struct target_reset_callback *entry;
1337 if (callback == NULL)
1338 return ERROR_COMMAND_SYNTAX_ERROR;
1340 entry = malloc(sizeof(struct target_reset_callback));
1341 if (entry == NULL) {
1342 LOG_ERROR("error allocating buffer for reset callback entry");
1343 return ERROR_COMMAND_SYNTAX_ERROR;
1346 entry->callback = callback;
1348 list_add(&entry->list, &target_reset_callback_list);
1354 int target_register_trace_callback(int (*callback)(struct target *target,
1355 size_t len, uint8_t *data, void *priv), void *priv)
1357 struct target_trace_callback *entry;
1359 if (callback == NULL)
1360 return ERROR_COMMAND_SYNTAX_ERROR;
1362 entry = malloc(sizeof(struct target_trace_callback));
1363 if (entry == NULL) {
1364 LOG_ERROR("error allocating buffer for trace callback entry");
1365 return ERROR_COMMAND_SYNTAX_ERROR;
1368 entry->callback = callback;
1370 list_add(&entry->list, &target_trace_callback_list);
1376 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1378 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1381 if (callback == NULL)
1382 return ERROR_COMMAND_SYNTAX_ERROR;
1385 while ((*callbacks_p)->next)
1386 callbacks_p = &((*callbacks_p)->next);
1387 callbacks_p = &((*callbacks_p)->next);
1390 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1391 (*callbacks_p)->callback = callback;
1392 (*callbacks_p)->periodic = periodic;
1393 (*callbacks_p)->time_ms = time_ms;
1394 (*callbacks_p)->removed = false;
1396 gettimeofday(&now, NULL);
1397 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
1398 time_ms -= (time_ms % 1000);
1399 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
1400 if ((*callbacks_p)->when.tv_usec > 1000000) {
1401 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
1402 (*callbacks_p)->when.tv_sec += 1;
1405 (*callbacks_p)->priv = priv;
1406 (*callbacks_p)->next = NULL;
1411 int target_unregister_event_callback(int (*callback)(struct target *target,
1412 enum target_event event, void *priv), void *priv)
1414 struct target_event_callback **p = &target_event_callbacks;
1415 struct target_event_callback *c = target_event_callbacks;
1417 if (callback == NULL)
1418 return ERROR_COMMAND_SYNTAX_ERROR;
1421 struct target_event_callback *next = c->next;
1422 if ((c->callback == callback) && (c->priv == priv)) {
1434 int target_unregister_reset_callback(int (*callback)(struct target *target,
1435 enum target_reset_mode reset_mode, void *priv), void *priv)
1437 struct target_reset_callback *entry;
1439 if (callback == NULL)
1440 return ERROR_COMMAND_SYNTAX_ERROR;
1442 list_for_each_entry(entry, &target_reset_callback_list, list) {
1443 if (entry->callback == callback && entry->priv == priv) {
1444 list_del(&entry->list);
1453 int target_unregister_trace_callback(int (*callback)(struct target *target,
1454 size_t len, uint8_t *data, void *priv), void *priv)
1456 struct target_trace_callback *entry;
1458 if (callback == NULL)
1459 return ERROR_COMMAND_SYNTAX_ERROR;
1461 list_for_each_entry(entry, &target_trace_callback_list, list) {
1462 if (entry->callback == callback && entry->priv == priv) {
1463 list_del(&entry->list);
1472 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1474 if (callback == NULL)
1475 return ERROR_COMMAND_SYNTAX_ERROR;
1477 for (struct target_timer_callback *c = target_timer_callbacks;
1479 if ((c->callback == callback) && (c->priv == priv)) {
1488 int target_call_event_callbacks(struct target *target, enum target_event event)
1490 struct target_event_callback *callback = target_event_callbacks;
1491 struct target_event_callback *next_callback;
1493 if (event == TARGET_EVENT_HALTED) {
1494 /* execute early halted first */
1495 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1498 LOG_DEBUG("target event %i (%s)", event,
1499 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1501 target_handle_event(target, event);
1504 next_callback = callback->next;
1505 callback->callback(target, event, callback->priv);
1506 callback = next_callback;
1512 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1514 struct target_reset_callback *callback;
1516 LOG_DEBUG("target reset %i (%s)", reset_mode,
1517 Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name);
1519 list_for_each_entry(callback, &target_reset_callback_list, list)
1520 callback->callback(target, reset_mode, callback->priv);
1525 int target_call_trace_callbacks(struct target *target, size_t len, uint8_t *data)
1527 struct target_trace_callback *callback;
1529 list_for_each_entry(callback, &target_trace_callback_list, list)
1530 callback->callback(target, len, data, callback->priv);
1535 static int target_timer_callback_periodic_restart(
1536 struct target_timer_callback *cb, struct timeval *now)
1538 int time_ms = cb->time_ms;
1539 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1540 time_ms -= (time_ms % 1000);
1541 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1542 if (cb->when.tv_usec > 1000000) {
1543 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1544 cb->when.tv_sec += 1;
1549 static int target_call_timer_callback(struct target_timer_callback *cb,
1550 struct timeval *now)
1552 cb->callback(cb->priv);
1555 return target_timer_callback_periodic_restart(cb, now);
1557 return target_unregister_timer_callback(cb->callback, cb->priv);
1560 static int target_call_timer_callbacks_check_time(int checktime)
1562 static bool callback_processing;
1564 /* Do not allow nesting */
1565 if (callback_processing)
1568 callback_processing = true;
1573 gettimeofday(&now, NULL);
1575 /* Store an address of the place containing a pointer to the
1576 * next item; initially, that's a standalone "root of the
1577 * list" variable. */
1578 struct target_timer_callback **callback = &target_timer_callbacks;
1580 if ((*callback)->removed) {
1581 struct target_timer_callback *p = *callback;
1582 *callback = (*callback)->next;
1587 bool call_it = (*callback)->callback &&
1588 ((!checktime && (*callback)->periodic) ||
1589 now.tv_sec > (*callback)->when.tv_sec ||
1590 (now.tv_sec == (*callback)->when.tv_sec &&
1591 now.tv_usec >= (*callback)->when.tv_usec));
1594 target_call_timer_callback(*callback, &now);
1596 callback = &(*callback)->next;
1599 callback_processing = false;
1603 int target_call_timer_callbacks(void)
1605 return target_call_timer_callbacks_check_time(1);
1608 /* invoke periodic callbacks immediately */
1609 int target_call_timer_callbacks_now(void)
1611 return target_call_timer_callbacks_check_time(0);
1614 /* Prints the working area layout for debug purposes */
1615 static void print_wa_layout(struct target *target)
1617 struct working_area *c = target->working_areas;
1620 LOG_DEBUG("%c%c 0x%08"PRIx32"-0x%08"PRIx32" (%"PRIu32" bytes)",
1621 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1622 c->address, c->address + c->size - 1, c->size);
1627 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1628 static void target_split_working_area(struct working_area *area, uint32_t size)
1630 assert(area->free); /* Shouldn't split an allocated area */
1631 assert(size <= area->size); /* Caller should guarantee this */
1633 /* Split only if not already the right size */
1634 if (size < area->size) {
1635 struct working_area *new_wa = malloc(sizeof(*new_wa));
1640 new_wa->next = area->next;
1641 new_wa->size = area->size - size;
1642 new_wa->address = area->address + size;
1643 new_wa->backup = NULL;
1644 new_wa->user = NULL;
1645 new_wa->free = true;
1647 area->next = new_wa;
1650 /* If backup memory was allocated to this area, it has the wrong size
1651 * now so free it and it will be reallocated if/when needed */
1654 area->backup = NULL;
1659 /* Merge all adjacent free areas into one */
1660 static void target_merge_working_areas(struct target *target)
1662 struct working_area *c = target->working_areas;
1664 while (c && c->next) {
1665 assert(c->next->address == c->address + c->size); /* This is an invariant */
1667 /* Find two adjacent free areas */
1668 if (c->free && c->next->free) {
1669 /* Merge the last into the first */
1670 c->size += c->next->size;
1672 /* Remove the last */
1673 struct working_area *to_be_freed = c->next;
1674 c->next = c->next->next;
1675 if (to_be_freed->backup)
1676 free(to_be_freed->backup);
1679 /* If backup memory was allocated to the remaining area, it's has
1680 * the wrong size now */
1691 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1693 /* Reevaluate working area address based on MMU state*/
1694 if (target->working_areas == NULL) {
1698 retval = target->type->mmu(target, &enabled);
1699 if (retval != ERROR_OK)
1703 if (target->working_area_phys_spec) {
1704 LOG_DEBUG("MMU disabled, using physical "
1705 "address for working memory 0x%08"PRIx32,
1706 target->working_area_phys);
1707 target->working_area = target->working_area_phys;
1709 LOG_ERROR("No working memory available. "
1710 "Specify -work-area-phys to target.");
1711 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1714 if (target->working_area_virt_spec) {
1715 LOG_DEBUG("MMU enabled, using virtual "
1716 "address for working memory 0x%08"PRIx32,
1717 target->working_area_virt);
1718 target->working_area = target->working_area_virt;
1720 LOG_ERROR("No working memory available. "
1721 "Specify -work-area-virt to target.");
1722 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1726 /* Set up initial working area on first call */
1727 struct working_area *new_wa = malloc(sizeof(*new_wa));
1729 new_wa->next = NULL;
1730 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1731 new_wa->address = target->working_area;
1732 new_wa->backup = NULL;
1733 new_wa->user = NULL;
1734 new_wa->free = true;
1737 target->working_areas = new_wa;
1740 /* only allocate multiples of 4 byte */
1742 size = (size + 3) & (~3UL);
1744 struct working_area *c = target->working_areas;
1746 /* Find the first large enough working area */
1748 if (c->free && c->size >= size)
1754 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1756 /* Split the working area into the requested size */
1757 target_split_working_area(c, size);
1759 LOG_DEBUG("allocated new working area of %"PRIu32" bytes at address 0x%08"PRIx32, size, c->address);
1761 if (target->backup_working_area) {
1762 if (c->backup == NULL) {
1763 c->backup = malloc(c->size);
1764 if (c->backup == NULL)
1768 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1769 if (retval != ERROR_OK)
1773 /* mark as used, and return the new (reused) area */
1780 print_wa_layout(target);
1785 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1789 retval = target_alloc_working_area_try(target, size, area);
1790 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1791 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1796 static int target_restore_working_area(struct target *target, struct working_area *area)
1798 int retval = ERROR_OK;
1800 if (target->backup_working_area && area->backup != NULL) {
1801 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1802 if (retval != ERROR_OK)
1803 LOG_ERROR("failed to restore %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1804 area->size, area->address);
1810 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1811 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1813 int retval = ERROR_OK;
1819 retval = target_restore_working_area(target, area);
1820 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1821 if (retval != ERROR_OK)
1827 LOG_DEBUG("freed %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1828 area->size, area->address);
1830 /* mark user pointer invalid */
1831 /* TODO: Is this really safe? It points to some previous caller's memory.
1832 * How could we know that the area pointer is still in that place and not
1833 * some other vital data? What's the purpose of this, anyway? */
1837 target_merge_working_areas(target);
1839 print_wa_layout(target);
1844 int target_free_working_area(struct target *target, struct working_area *area)
1846 return target_free_working_area_restore(target, area, 1);
1849 void target_quit(void)
1851 struct target_event_callback *pe = target_event_callbacks;
1853 struct target_event_callback *t = pe->next;
1857 target_event_callbacks = NULL;
1859 struct target_timer_callback *pt = target_timer_callbacks;
1861 struct target_timer_callback *t = pt->next;
1865 target_timer_callbacks = NULL;
1867 for (struct target *target = all_targets;
1868 target; target = target->next) {
1869 if (target->type->deinit_target)
1870 target->type->deinit_target(target);
1874 /* free resources and restore memory, if restoring memory fails,
1875 * free up resources anyway
1877 static void target_free_all_working_areas_restore(struct target *target, int restore)
1879 struct working_area *c = target->working_areas;
1881 LOG_DEBUG("freeing all working areas");
1883 /* Loop through all areas, restoring the allocated ones and marking them as free */
1887 target_restore_working_area(target, c);
1889 *c->user = NULL; /* Same as above */
1895 /* Run a merge pass to combine all areas into one */
1896 target_merge_working_areas(target);
1898 print_wa_layout(target);
1901 void target_free_all_working_areas(struct target *target)
1903 target_free_all_working_areas_restore(target, 1);
1906 /* Find the largest number of bytes that can be allocated */
1907 uint32_t target_get_working_area_avail(struct target *target)
1909 struct working_area *c = target->working_areas;
1910 uint32_t max_size = 0;
1913 return target->working_area_size;
1916 if (c->free && max_size < c->size)
1925 int target_arch_state(struct target *target)
1928 if (target == NULL) {
1929 LOG_USER("No target has been configured");
1933 LOG_USER("target state: %s", target_state_name(target));
1935 if (target->state != TARGET_HALTED)
1938 retval = target->type->arch_state(target);
1942 static int target_get_gdb_fileio_info_default(struct target *target,
1943 struct gdb_fileio_info *fileio_info)
1945 /* If target does not support semi-hosting function, target
1946 has no need to provide .get_gdb_fileio_info callback.
1947 It just return ERROR_FAIL and gdb_server will return "Txx"
1948 as target halted every time. */
1952 static int target_gdb_fileio_end_default(struct target *target,
1953 int retcode, int fileio_errno, bool ctrl_c)
1958 static int target_profiling_default(struct target *target, uint32_t *samples,
1959 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1961 struct timeval timeout, now;
1963 gettimeofday(&timeout, NULL);
1964 timeval_add_time(&timeout, seconds, 0);
1966 LOG_INFO("Starting profiling. Halting and resuming the"
1967 " target as often as we can...");
1969 uint32_t sample_count = 0;
1970 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
1971 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
1973 int retval = ERROR_OK;
1975 target_poll(target);
1976 if (target->state == TARGET_HALTED) {
1977 uint32_t t = buf_get_u32(reg->value, 0, 32);
1978 samples[sample_count++] = t;
1979 /* current pc, addr = 0, do not handle breakpoints, not debugging */
1980 retval = target_resume(target, 1, 0, 0, 0);
1981 target_poll(target);
1982 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
1983 } else if (target->state == TARGET_RUNNING) {
1984 /* We want to quickly sample the PC. */
1985 retval = target_halt(target);
1987 LOG_INFO("Target not halted or running");
1992 if (retval != ERROR_OK)
1995 gettimeofday(&now, NULL);
1996 if ((sample_count >= max_num_samples) ||
1997 ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec))) {
1998 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2003 *num_samples = sample_count;
2007 /* Single aligned words are guaranteed to use 16 or 32 bit access
2008 * mode respectively, otherwise data is handled as quickly as
2011 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
2013 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
2014 (int)size, (unsigned)address);
2016 if (!target_was_examined(target)) {
2017 LOG_ERROR("Target not examined yet");
2024 if ((address + size - 1) < address) {
2025 /* GDB can request this when e.g. PC is 0xfffffffc*/
2026 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
2032 return target->type->write_buffer(target, address, size, buffer);
2035 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t count, const uint8_t *buffer)
2039 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2040 * will have something to do with the size we leave to it. */
2041 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2042 if (address & size) {
2043 int retval = target_write_memory(target, address, size, 1, buffer);
2044 if (retval != ERROR_OK)
2052 /* Write the data with as large access size as possible. */
2053 for (; size > 0; size /= 2) {
2054 uint32_t aligned = count - count % size;
2056 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2057 if (retval != ERROR_OK)
2068 /* Single aligned words are guaranteed to use 16 or 32 bit access
2069 * mode respectively, otherwise data is handled as quickly as
2072 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
2074 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
2075 (int)size, (unsigned)address);
2077 if (!target_was_examined(target)) {
2078 LOG_ERROR("Target not examined yet");
2085 if ((address + size - 1) < address) {
2086 /* GDB can request this when e.g. PC is 0xfffffffc*/
2087 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
2093 return target->type->read_buffer(target, address, size, buffer);
2096 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t count, uint8_t *buffer)
2100 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2101 * will have something to do with the size we leave to it. */
2102 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2103 if (address & size) {
2104 int retval = target_read_memory(target, address, size, 1, buffer);
2105 if (retval != ERROR_OK)
2113 /* Read the data with as large access size as possible. */
2114 for (; size > 0; size /= 2) {
2115 uint32_t aligned = count - count % size;
2117 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2118 if (retval != ERROR_OK)
2129 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
2134 uint32_t checksum = 0;
2135 if (!target_was_examined(target)) {
2136 LOG_ERROR("Target not examined yet");
2140 retval = target->type->checksum_memory(target, address, size, &checksum);
2141 if (retval != ERROR_OK) {
2142 buffer = malloc(size);
2143 if (buffer == NULL) {
2144 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
2145 return ERROR_COMMAND_SYNTAX_ERROR;
2147 retval = target_read_buffer(target, address, size, buffer);
2148 if (retval != ERROR_OK) {
2153 /* convert to target endianness */
2154 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2155 uint32_t target_data;
2156 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2157 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2160 retval = image_calculate_checksum(buffer, size, &checksum);
2169 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
2172 if (!target_was_examined(target)) {
2173 LOG_ERROR("Target not examined yet");
2177 if (target->type->blank_check_memory == 0)
2178 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2180 retval = target->type->blank_check_memory(target, address, size, blank);
2185 int target_read_u64(struct target *target, uint64_t address, uint64_t *value)
2187 uint8_t value_buf[8];
2188 if (!target_was_examined(target)) {
2189 LOG_ERROR("Target not examined yet");
2193 int retval = target_read_memory(target, address, 8, 1, value_buf);
2195 if (retval == ERROR_OK) {
2196 *value = target_buffer_get_u64(target, value_buf);
2197 LOG_DEBUG("address: 0x%" PRIx64 ", value: 0x%16.16" PRIx64 "",
2202 LOG_DEBUG("address: 0x%" PRIx64 " failed",
2209 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
2211 uint8_t value_buf[4];
2212 if (!target_was_examined(target)) {
2213 LOG_ERROR("Target not examined yet");
2217 int retval = target_read_memory(target, address, 4, 1, value_buf);
2219 if (retval == ERROR_OK) {
2220 *value = target_buffer_get_u32(target, value_buf);
2221 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2226 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2233 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
2235 uint8_t value_buf[2];
2236 if (!target_was_examined(target)) {
2237 LOG_ERROR("Target not examined yet");
2241 int retval = target_read_memory(target, address, 2, 1, value_buf);
2243 if (retval == ERROR_OK) {
2244 *value = target_buffer_get_u16(target, value_buf);
2245 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
2250 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2257 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
2259 if (!target_was_examined(target)) {
2260 LOG_ERROR("Target not examined yet");
2264 int retval = target_read_memory(target, address, 1, 1, value);
2266 if (retval == ERROR_OK) {
2267 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2272 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2279 int target_write_u64(struct target *target, uint64_t address, uint64_t value)
2282 uint8_t value_buf[8];
2283 if (!target_was_examined(target)) {
2284 LOG_ERROR("Target not examined yet");
2288 LOG_DEBUG("address: 0x%" PRIx64 ", value: 0x%16.16" PRIx64 "",
2292 target_buffer_set_u64(target, value_buf, value);
2293 retval = target_write_memory(target, address, 8, 1, value_buf);
2294 if (retval != ERROR_OK)
2295 LOG_DEBUG("failed: %i", retval);
2300 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
2303 uint8_t value_buf[4];
2304 if (!target_was_examined(target)) {
2305 LOG_ERROR("Target not examined yet");
2309 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2313 target_buffer_set_u32(target, value_buf, value);
2314 retval = target_write_memory(target, address, 4, 1, value_buf);
2315 if (retval != ERROR_OK)
2316 LOG_DEBUG("failed: %i", retval);
2321 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
2324 uint8_t value_buf[2];
2325 if (!target_was_examined(target)) {
2326 LOG_ERROR("Target not examined yet");
2330 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
2334 target_buffer_set_u16(target, value_buf, value);
2335 retval = target_write_memory(target, address, 2, 1, value_buf);
2336 if (retval != ERROR_OK)
2337 LOG_DEBUG("failed: %i", retval);
2342 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
2345 if (!target_was_examined(target)) {
2346 LOG_ERROR("Target not examined yet");
2350 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2353 retval = target_write_memory(target, address, 1, 1, &value);
2354 if (retval != ERROR_OK)
2355 LOG_DEBUG("failed: %i", retval);
2360 static int find_target(struct command_context *cmd_ctx, const char *name)
2362 struct target *target = get_target(name);
2363 if (target == NULL) {
2364 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2367 if (!target->tap->enabled) {
2368 LOG_USER("Target: TAP %s is disabled, "
2369 "can't be the current target\n",
2370 target->tap->dotted_name);
2374 cmd_ctx->current_target = target->target_number;
2379 COMMAND_HANDLER(handle_targets_command)
2381 int retval = ERROR_OK;
2382 if (CMD_ARGC == 1) {
2383 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2384 if (retval == ERROR_OK) {
2390 struct target *target = all_targets;
2391 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2392 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2397 if (target->tap->enabled)
2398 state = target_state_name(target);
2400 state = "tap-disabled";
2402 if (CMD_CTX->current_target == target->target_number)
2405 /* keep columns lined up to match the headers above */
2406 command_print(CMD_CTX,
2407 "%2d%c %-18s %-10s %-6s %-18s %s",
2408 target->target_number,
2410 target_name(target),
2411 target_type_name(target),
2412 Jim_Nvp_value2name_simple(nvp_target_endian,
2413 target->endianness)->name,
2414 target->tap->dotted_name,
2416 target = target->next;
2422 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2424 static int powerDropout;
2425 static int srstAsserted;
2427 static int runPowerRestore;
2428 static int runPowerDropout;
2429 static int runSrstAsserted;
2430 static int runSrstDeasserted;
2432 static int sense_handler(void)
2434 static int prevSrstAsserted;
2435 static int prevPowerdropout;
2437 int retval = jtag_power_dropout(&powerDropout);
2438 if (retval != ERROR_OK)
2442 powerRestored = prevPowerdropout && !powerDropout;
2444 runPowerRestore = 1;
2446 long long current = timeval_ms();
2447 static long long lastPower;
2448 int waitMore = lastPower + 2000 > current;
2449 if (powerDropout && !waitMore) {
2450 runPowerDropout = 1;
2451 lastPower = current;
2454 retval = jtag_srst_asserted(&srstAsserted);
2455 if (retval != ERROR_OK)
2459 srstDeasserted = prevSrstAsserted && !srstAsserted;
2461 static long long lastSrst;
2462 waitMore = lastSrst + 2000 > current;
2463 if (srstDeasserted && !waitMore) {
2464 runSrstDeasserted = 1;
2468 if (!prevSrstAsserted && srstAsserted)
2469 runSrstAsserted = 1;
2471 prevSrstAsserted = srstAsserted;
2472 prevPowerdropout = powerDropout;
2474 if (srstDeasserted || powerRestored) {
2475 /* Other than logging the event we can't do anything here.
2476 * Issuing a reset is a particularly bad idea as we might
2477 * be inside a reset already.
2484 /* process target state changes */
2485 static int handle_target(void *priv)
2487 Jim_Interp *interp = (Jim_Interp *)priv;
2488 int retval = ERROR_OK;
2490 if (!is_jtag_poll_safe()) {
2491 /* polling is disabled currently */
2495 /* we do not want to recurse here... */
2496 static int recursive;
2500 /* danger! running these procedures can trigger srst assertions and power dropouts.
2501 * We need to avoid an infinite loop/recursion here and we do that by
2502 * clearing the flags after running these events.
2504 int did_something = 0;
2505 if (runSrstAsserted) {
2506 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2507 Jim_Eval(interp, "srst_asserted");
2510 if (runSrstDeasserted) {
2511 Jim_Eval(interp, "srst_deasserted");
2514 if (runPowerDropout) {
2515 LOG_INFO("Power dropout detected, running power_dropout proc.");
2516 Jim_Eval(interp, "power_dropout");
2519 if (runPowerRestore) {
2520 Jim_Eval(interp, "power_restore");
2524 if (did_something) {
2525 /* clear detect flags */
2529 /* clear action flags */
2531 runSrstAsserted = 0;
2532 runSrstDeasserted = 0;
2533 runPowerRestore = 0;
2534 runPowerDropout = 0;
2539 /* Poll targets for state changes unless that's globally disabled.
2540 * Skip targets that are currently disabled.
2542 for (struct target *target = all_targets;
2543 is_jtag_poll_safe() && target;
2544 target = target->next) {
2546 if (!target_was_examined(target))
2549 if (!target->tap->enabled)
2552 if (target->backoff.times > target->backoff.count) {
2553 /* do not poll this time as we failed previously */
2554 target->backoff.count++;
2557 target->backoff.count = 0;
2559 /* only poll target if we've got power and srst isn't asserted */
2560 if (!powerDropout && !srstAsserted) {
2561 /* polling may fail silently until the target has been examined */
2562 retval = target_poll(target);
2563 if (retval != ERROR_OK) {
2564 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2565 if (target->backoff.times * polling_interval < 5000) {
2566 target->backoff.times *= 2;
2567 target->backoff.times++;
2570 /* Tell GDB to halt the debugger. This allows the user to
2571 * run monitor commands to handle the situation.
2573 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2575 if (target->backoff.times > 0) {
2576 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
2577 target_reset_examined(target);
2578 retval = target_examine_one(target);
2579 /* Target examination could have failed due to unstable connection,
2580 * but we set the examined flag anyway to repoll it later */
2581 if (retval != ERROR_OK) {
2582 target->examined = true;
2583 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
2584 target->backoff.times * polling_interval);
2589 /* Since we succeeded, we reset backoff count */
2590 target->backoff.times = 0;
2597 COMMAND_HANDLER(handle_reg_command)
2599 struct target *target;
2600 struct reg *reg = NULL;
2606 target = get_current_target(CMD_CTX);
2608 /* list all available registers for the current target */
2609 if (CMD_ARGC == 0) {
2610 struct reg_cache *cache = target->reg_cache;
2616 command_print(CMD_CTX, "===== %s", cache->name);
2618 for (i = 0, reg = cache->reg_list;
2619 i < cache->num_regs;
2620 i++, reg++, count++) {
2621 /* only print cached values if they are valid */
2623 value = buf_to_str(reg->value,
2625 command_print(CMD_CTX,
2626 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2634 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2639 cache = cache->next;
2645 /* access a single register by its ordinal number */
2646 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2648 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2650 struct reg_cache *cache = target->reg_cache;
2654 for (i = 0; i < cache->num_regs; i++) {
2655 if (count++ == num) {
2656 reg = &cache->reg_list[i];
2662 cache = cache->next;
2666 command_print(CMD_CTX, "%i is out of bounds, the current target "
2667 "has only %i registers (0 - %i)", num, count, count - 1);
2671 /* access a single register by its name */
2672 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2675 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2680 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2682 /* display a register */
2683 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2684 && (CMD_ARGV[1][0] <= '9')))) {
2685 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2688 if (reg->valid == 0)
2689 reg->type->get(reg);
2690 value = buf_to_str(reg->value, reg->size, 16);
2691 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2696 /* set register value */
2697 if (CMD_ARGC == 2) {
2698 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2701 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2703 reg->type->set(reg, buf);
2705 value = buf_to_str(reg->value, reg->size, 16);
2706 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2714 return ERROR_COMMAND_SYNTAX_ERROR;
2717 COMMAND_HANDLER(handle_poll_command)
2719 int retval = ERROR_OK;
2720 struct target *target = get_current_target(CMD_CTX);
2722 if (CMD_ARGC == 0) {
2723 command_print(CMD_CTX, "background polling: %s",
2724 jtag_poll_get_enabled() ? "on" : "off");
2725 command_print(CMD_CTX, "TAP: %s (%s)",
2726 target->tap->dotted_name,
2727 target->tap->enabled ? "enabled" : "disabled");
2728 if (!target->tap->enabled)
2730 retval = target_poll(target);
2731 if (retval != ERROR_OK)
2733 retval = target_arch_state(target);
2734 if (retval != ERROR_OK)
2736 } else if (CMD_ARGC == 1) {
2738 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2739 jtag_poll_set_enabled(enable);
2741 return ERROR_COMMAND_SYNTAX_ERROR;
2746 COMMAND_HANDLER(handle_wait_halt_command)
2749 return ERROR_COMMAND_SYNTAX_ERROR;
2751 unsigned ms = DEFAULT_HALT_TIMEOUT;
2752 if (1 == CMD_ARGC) {
2753 int retval = parse_uint(CMD_ARGV[0], &ms);
2754 if (ERROR_OK != retval)
2755 return ERROR_COMMAND_SYNTAX_ERROR;
2758 struct target *target = get_current_target(CMD_CTX);
2759 return target_wait_state(target, TARGET_HALTED, ms);
2762 /* wait for target state to change. The trick here is to have a low
2763 * latency for short waits and not to suck up all the CPU time
2766 * After 500ms, keep_alive() is invoked
2768 int target_wait_state(struct target *target, enum target_state state, int ms)
2771 long long then = 0, cur;
2775 retval = target_poll(target);
2776 if (retval != ERROR_OK)
2778 if (target->state == state)
2783 then = timeval_ms();
2784 LOG_DEBUG("waiting for target %s...",
2785 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2791 if ((cur-then) > ms) {
2792 LOG_ERROR("timed out while waiting for target %s",
2793 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2801 COMMAND_HANDLER(handle_halt_command)
2805 struct target *target = get_current_target(CMD_CTX);
2806 int retval = target_halt(target);
2807 if (ERROR_OK != retval)
2810 if (CMD_ARGC == 1) {
2811 unsigned wait_local;
2812 retval = parse_uint(CMD_ARGV[0], &wait_local);
2813 if (ERROR_OK != retval)
2814 return ERROR_COMMAND_SYNTAX_ERROR;
2819 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2822 COMMAND_HANDLER(handle_soft_reset_halt_command)
2824 struct target *target = get_current_target(CMD_CTX);
2826 LOG_USER("requesting target halt and executing a soft reset");
2828 target_soft_reset_halt(target);
2833 COMMAND_HANDLER(handle_reset_command)
2836 return ERROR_COMMAND_SYNTAX_ERROR;
2838 enum target_reset_mode reset_mode = RESET_RUN;
2839 if (CMD_ARGC == 1) {
2841 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2842 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2843 return ERROR_COMMAND_SYNTAX_ERROR;
2844 reset_mode = n->value;
2847 /* reset *all* targets */
2848 return target_process_reset(CMD_CTX, reset_mode);
2852 COMMAND_HANDLER(handle_resume_command)
2856 return ERROR_COMMAND_SYNTAX_ERROR;
2858 struct target *target = get_current_target(CMD_CTX);
2860 /* with no CMD_ARGV, resume from current pc, addr = 0,
2861 * with one arguments, addr = CMD_ARGV[0],
2862 * handle breakpoints, not debugging */
2864 if (CMD_ARGC == 1) {
2865 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2869 return target_resume(target, current, addr, 1, 0);
2872 COMMAND_HANDLER(handle_step_command)
2875 return ERROR_COMMAND_SYNTAX_ERROR;
2879 /* with no CMD_ARGV, step from current pc, addr = 0,
2880 * with one argument addr = CMD_ARGV[0],
2881 * handle breakpoints, debugging */
2884 if (CMD_ARGC == 1) {
2885 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2889 struct target *target = get_current_target(CMD_CTX);
2891 return target->type->step(target, current_pc, addr, 1);
2894 static void handle_md_output(struct command_context *cmd_ctx,
2895 struct target *target, uint32_t address, unsigned size,
2896 unsigned count, const uint8_t *buffer)
2898 const unsigned line_bytecnt = 32;
2899 unsigned line_modulo = line_bytecnt / size;
2901 char output[line_bytecnt * 4 + 1];
2902 unsigned output_len = 0;
2904 const char *value_fmt;
2907 value_fmt = "%8.8x ";
2910 value_fmt = "%4.4x ";
2913 value_fmt = "%2.2x ";
2916 /* "can't happen", caller checked */
2917 LOG_ERROR("invalid memory read size: %u", size);
2921 for (unsigned i = 0; i < count; i++) {
2922 if (i % line_modulo == 0) {
2923 output_len += snprintf(output + output_len,
2924 sizeof(output) - output_len,
2926 (unsigned)(address + (i*size)));
2930 const uint8_t *value_ptr = buffer + i * size;
2933 value = target_buffer_get_u32(target, value_ptr);
2936 value = target_buffer_get_u16(target, value_ptr);
2941 output_len += snprintf(output + output_len,
2942 sizeof(output) - output_len,
2945 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2946 command_print(cmd_ctx, "%s", output);
2952 COMMAND_HANDLER(handle_md_command)
2955 return ERROR_COMMAND_SYNTAX_ERROR;
2958 switch (CMD_NAME[2]) {
2969 return ERROR_COMMAND_SYNTAX_ERROR;
2972 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2973 int (*fn)(struct target *target,
2974 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2978 fn = target_read_phys_memory;
2980 fn = target_read_memory;
2981 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2982 return ERROR_COMMAND_SYNTAX_ERROR;
2985 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2989 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2991 uint8_t *buffer = calloc(count, size);
2993 struct target *target = get_current_target(CMD_CTX);
2994 int retval = fn(target, address, size, count, buffer);
2995 if (ERROR_OK == retval)
2996 handle_md_output(CMD_CTX, target, address, size, count, buffer);
3003 typedef int (*target_write_fn)(struct target *target,
3004 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3006 static int target_fill_mem(struct target *target,
3015 /* We have to write in reasonably large chunks to be able
3016 * to fill large memory areas with any sane speed */
3017 const unsigned chunk_size = 16384;
3018 uint8_t *target_buf = malloc(chunk_size * data_size);
3019 if (target_buf == NULL) {
3020 LOG_ERROR("Out of memory");
3024 for (unsigned i = 0; i < chunk_size; i++) {
3025 switch (data_size) {
3027 target_buffer_set_u32(target, target_buf + i * data_size, b);
3030 target_buffer_set_u16(target, target_buf + i * data_size, b);
3033 target_buffer_set_u8(target, target_buf + i * data_size, b);
3040 int retval = ERROR_OK;
3042 for (unsigned x = 0; x < c; x += chunk_size) {
3045 if (current > chunk_size)
3046 current = chunk_size;
3047 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3048 if (retval != ERROR_OK)
3050 /* avoid GDB timeouts */
3059 COMMAND_HANDLER(handle_mw_command)
3062 return ERROR_COMMAND_SYNTAX_ERROR;
3063 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3068 fn = target_write_phys_memory;
3070 fn = target_write_memory;
3071 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3072 return ERROR_COMMAND_SYNTAX_ERROR;
3075 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
3078 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
3082 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3084 struct target *target = get_current_target(CMD_CTX);
3086 switch (CMD_NAME[2]) {
3097 return ERROR_COMMAND_SYNTAX_ERROR;
3100 return target_fill_mem(target, address, fn, wordsize, value, count);
3103 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
3104 uint32_t *min_address, uint32_t *max_address)
3106 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3107 return ERROR_COMMAND_SYNTAX_ERROR;
3109 /* a base address isn't always necessary,
3110 * default to 0x0 (i.e. don't relocate) */
3111 if (CMD_ARGC >= 2) {
3113 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3114 image->base_address = addr;
3115 image->base_address_set = 1;
3117 image->base_address_set = 0;
3119 image->start_address_set = 0;
3122 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
3123 if (CMD_ARGC == 5) {
3124 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
3125 /* use size (given) to find max (required) */
3126 *max_address += *min_address;
3129 if (*min_address > *max_address)
3130 return ERROR_COMMAND_SYNTAX_ERROR;
3135 COMMAND_HANDLER(handle_load_image_command)
3139 uint32_t image_size;
3140 uint32_t min_address = 0;
3141 uint32_t max_address = 0xffffffff;
3145 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
3146 &image, &min_address, &max_address);
3147 if (ERROR_OK != retval)
3150 struct target *target = get_current_target(CMD_CTX);
3152 struct duration bench;
3153 duration_start(&bench);
3155 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3160 for (i = 0; i < image.num_sections; i++) {
3161 buffer = malloc(image.sections[i].size);
3162 if (buffer == NULL) {
3163 command_print(CMD_CTX,
3164 "error allocating buffer for section (%d bytes)",
3165 (int)(image.sections[i].size));
3169 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3170 if (retval != ERROR_OK) {
3175 uint32_t offset = 0;
3176 uint32_t length = buf_cnt;
3178 /* DANGER!!! beware of unsigned comparision here!!! */
3180 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3181 (image.sections[i].base_address < max_address)) {
3183 if (image.sections[i].base_address < min_address) {
3184 /* clip addresses below */
3185 offset += min_address-image.sections[i].base_address;
3189 if (image.sections[i].base_address + buf_cnt > max_address)
3190 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3192 retval = target_write_buffer(target,
3193 image.sections[i].base_address + offset, length, buffer + offset);
3194 if (retval != ERROR_OK) {
3198 image_size += length;
3199 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
3200 (unsigned int)length,
3201 image.sections[i].base_address + offset);
3207 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3208 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
3209 "in %fs (%0.3f KiB/s)", image_size,
3210 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3213 image_close(&image);
3219 COMMAND_HANDLER(handle_dump_image_command)
3221 struct fileio fileio;
3223 int retval, retvaltemp;
3224 uint32_t address, size;
3225 struct duration bench;
3226 struct target *target = get_current_target(CMD_CTX);
3229 return ERROR_COMMAND_SYNTAX_ERROR;
3231 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
3232 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
3234 uint32_t buf_size = (size > 4096) ? 4096 : size;
3235 buffer = malloc(buf_size);
3239 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3240 if (retval != ERROR_OK) {
3245 duration_start(&bench);
3248 size_t size_written;
3249 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3250 retval = target_read_buffer(target, address, this_run_size, buffer);
3251 if (retval != ERROR_OK)
3254 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
3255 if (retval != ERROR_OK)
3258 size -= this_run_size;
3259 address += this_run_size;
3264 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3266 retval = fileio_size(&fileio, &filesize);
3267 if (retval != ERROR_OK)
3269 command_print(CMD_CTX,
3270 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
3271 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3274 retvaltemp = fileio_close(&fileio);
3275 if (retvaltemp != ERROR_OK)
3281 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
3285 uint32_t image_size;
3288 uint32_t checksum = 0;
3289 uint32_t mem_checksum = 0;
3293 struct target *target = get_current_target(CMD_CTX);
3296 return ERROR_COMMAND_SYNTAX_ERROR;
3299 LOG_ERROR("no target selected");
3303 struct duration bench;
3304 duration_start(&bench);
3306 if (CMD_ARGC >= 2) {
3308 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3309 image.base_address = addr;
3310 image.base_address_set = 1;
3312 image.base_address_set = 0;
3313 image.base_address = 0x0;
3316 image.start_address_set = 0;
3318 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3319 if (retval != ERROR_OK)
3325 for (i = 0; i < image.num_sections; i++) {
3326 buffer = malloc(image.sections[i].size);
3327 if (buffer == NULL) {
3328 command_print(CMD_CTX,
3329 "error allocating buffer for section (%d bytes)",
3330 (int)(image.sections[i].size));
3333 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3334 if (retval != ERROR_OK) {
3340 /* calculate checksum of image */
3341 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3342 if (retval != ERROR_OK) {
3347 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3348 if (retval != ERROR_OK) {
3353 if (checksum != mem_checksum) {
3354 /* failed crc checksum, fall back to a binary compare */
3358 LOG_ERROR("checksum mismatch - attempting binary compare");
3360 data = malloc(buf_cnt);
3362 /* Can we use 32bit word accesses? */
3364 int count = buf_cnt;
3365 if ((count % 4) == 0) {
3369 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3370 if (retval == ERROR_OK) {
3372 for (t = 0; t < buf_cnt; t++) {
3373 if (data[t] != buffer[t]) {
3374 command_print(CMD_CTX,
3375 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3377 (unsigned)(t + image.sections[i].base_address),
3380 if (diffs++ >= 127) {
3381 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3393 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3394 image.sections[i].base_address,
3399 image_size += buf_cnt;
3402 command_print(CMD_CTX, "No more differences found.");
3405 retval = ERROR_FAIL;
3406 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3407 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3408 "in %fs (%0.3f KiB/s)", image_size,
3409 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3412 image_close(&image);
3417 COMMAND_HANDLER(handle_verify_image_command)
3419 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3422 COMMAND_HANDLER(handle_test_image_command)
3424 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3427 static int handle_bp_command_list(struct command_context *cmd_ctx)
3429 struct target *target = get_current_target(cmd_ctx);
3430 struct breakpoint *breakpoint = target->breakpoints;
3431 while (breakpoint) {
3432 if (breakpoint->type == BKPT_SOFT) {
3433 char *buf = buf_to_str(breakpoint->orig_instr,
3434 breakpoint->length, 16);
3435 command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3436 breakpoint->address,
3438 breakpoint->set, buf);
3441 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3442 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3444 breakpoint->length, breakpoint->set);
3445 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3446 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3447 breakpoint->address,
3448 breakpoint->length, breakpoint->set);
3449 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3452 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3453 breakpoint->address,
3454 breakpoint->length, breakpoint->set);
3457 breakpoint = breakpoint->next;
3462 static int handle_bp_command_set(struct command_context *cmd_ctx,
3463 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3465 struct target *target = get_current_target(cmd_ctx);
3469 retval = breakpoint_add(target, addr, length, hw);
3470 if (ERROR_OK == retval)
3471 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3473 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3476 } else if (addr == 0) {
3477 if (target->type->add_context_breakpoint == NULL) {
3478 LOG_WARNING("Context breakpoint not available");
3481 retval = context_breakpoint_add(target, asid, length, hw);
3482 if (ERROR_OK == retval)
3483 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3485 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3489 if (target->type->add_hybrid_breakpoint == NULL) {
3490 LOG_WARNING("Hybrid breakpoint not available");
3493 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3494 if (ERROR_OK == retval)
3495 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3497 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3504 COMMAND_HANDLER(handle_bp_command)
3513 return handle_bp_command_list(CMD_CTX);
3517 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3518 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3519 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3522 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3524 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3526 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3529 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3530 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3532 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3533 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3535 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3540 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3541 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3542 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3543 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3546 return ERROR_COMMAND_SYNTAX_ERROR;
3550 COMMAND_HANDLER(handle_rbp_command)
3553 return ERROR_COMMAND_SYNTAX_ERROR;
3556 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3558 struct target *target = get_current_target(CMD_CTX);
3559 breakpoint_remove(target, addr);
3564 COMMAND_HANDLER(handle_wp_command)
3566 struct target *target = get_current_target(CMD_CTX);
3568 if (CMD_ARGC == 0) {
3569 struct watchpoint *watchpoint = target->watchpoints;
3571 while (watchpoint) {
3572 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3573 ", len: 0x%8.8" PRIx32
3574 ", r/w/a: %i, value: 0x%8.8" PRIx32
3575 ", mask: 0x%8.8" PRIx32,
3576 watchpoint->address,
3578 (int)watchpoint->rw,
3581 watchpoint = watchpoint->next;
3586 enum watchpoint_rw type = WPT_ACCESS;
3588 uint32_t length = 0;
3589 uint32_t data_value = 0x0;
3590 uint32_t data_mask = 0xffffffff;
3594 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3597 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3600 switch (CMD_ARGV[2][0]) {
3611 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3612 return ERROR_COMMAND_SYNTAX_ERROR;
3616 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3617 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3621 return ERROR_COMMAND_SYNTAX_ERROR;
3624 int retval = watchpoint_add(target, addr, length, type,
3625 data_value, data_mask);
3626 if (ERROR_OK != retval)
3627 LOG_ERROR("Failure setting watchpoints");
3632 COMMAND_HANDLER(handle_rwp_command)
3635 return ERROR_COMMAND_SYNTAX_ERROR;
3638 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3640 struct target *target = get_current_target(CMD_CTX);
3641 watchpoint_remove(target, addr);
3647 * Translate a virtual address to a physical address.
3649 * The low-level target implementation must have logged a detailed error
3650 * which is forwarded to telnet/GDB session.
3652 COMMAND_HANDLER(handle_virt2phys_command)
3655 return ERROR_COMMAND_SYNTAX_ERROR;
3658 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3661 struct target *target = get_current_target(CMD_CTX);
3662 int retval = target->type->virt2phys(target, va, &pa);
3663 if (retval == ERROR_OK)
3664 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3669 static void writeData(FILE *f, const void *data, size_t len)
3671 size_t written = fwrite(data, 1, len, f);
3673 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3676 static void writeLong(FILE *f, int l, struct target *target)
3680 target_buffer_set_u32(target, val, l);
3681 writeData(f, val, 4);
3684 static void writeString(FILE *f, char *s)
3686 writeData(f, s, strlen(s));
3689 typedef unsigned char UNIT[2]; /* unit of profiling */
3691 /* Dump a gmon.out histogram file. */
3692 static void write_gmon(uint32_t *samples, uint32_t sampleNum, const char *filename, bool with_range,
3693 uint32_t start_address, uint32_t end_address, struct target *target)
3696 FILE *f = fopen(filename, "w");
3699 writeString(f, "gmon");
3700 writeLong(f, 0x00000001, target); /* Version */
3701 writeLong(f, 0, target); /* padding */
3702 writeLong(f, 0, target); /* padding */
3703 writeLong(f, 0, target); /* padding */
3705 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3706 writeData(f, &zero, 1);
3708 /* figure out bucket size */
3712 min = start_address;
3717 for (i = 0; i < sampleNum; i++) {
3718 if (min > samples[i])
3720 if (max < samples[i])
3724 /* max should be (largest sample + 1)
3725 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
3729 int addressSpace = max - min;
3730 assert(addressSpace >= 2);
3732 /* FIXME: What is the reasonable number of buckets?
3733 * The profiling result will be more accurate if there are enough buckets. */
3734 static const uint32_t maxBuckets = 128 * 1024; /* maximum buckets. */
3735 uint32_t numBuckets = addressSpace / sizeof(UNIT);
3736 if (numBuckets > maxBuckets)
3737 numBuckets = maxBuckets;
3738 int *buckets = malloc(sizeof(int) * numBuckets);
3739 if (buckets == NULL) {
3743 memset(buckets, 0, sizeof(int) * numBuckets);
3744 for (i = 0; i < sampleNum; i++) {
3745 uint32_t address = samples[i];
3747 if ((address < min) || (max <= address))
3750 long long a = address - min;
3751 long long b = numBuckets;
3752 long long c = addressSpace;
3753 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3757 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3758 writeLong(f, min, target); /* low_pc */
3759 writeLong(f, max, target); /* high_pc */
3760 writeLong(f, numBuckets, target); /* # of buckets */
3761 writeLong(f, 100, target); /* KLUDGE! We lie, ca. 100Hz best case. */
3762 writeString(f, "seconds");
3763 for (i = 0; i < (15-strlen("seconds")); i++)
3764 writeData(f, &zero, 1);
3765 writeString(f, "s");
3767 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3769 char *data = malloc(2 * numBuckets);
3771 for (i = 0; i < numBuckets; i++) {
3776 data[i * 2] = val&0xff;
3777 data[i * 2 + 1] = (val >> 8) & 0xff;
3780 writeData(f, data, numBuckets * 2);
3788 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3789 * which will be used as a random sampling of PC */
3790 COMMAND_HANDLER(handle_profile_command)
3792 struct target *target = get_current_target(CMD_CTX);
3794 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
3795 return ERROR_COMMAND_SYNTAX_ERROR;
3797 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
3799 uint32_t num_of_samples;
3800 int retval = ERROR_OK;
3802 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
3804 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
3805 if (samples == NULL) {
3806 LOG_ERROR("No memory to store samples.");
3811 * Some cores let us sample the PC without the
3812 * annoying halt/resume step; for example, ARMv7 PCSR.
3813 * Provide a way to use that more efficient mechanism.
3815 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
3816 &num_of_samples, offset);
3817 if (retval != ERROR_OK) {
3822 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
3824 retval = target_poll(target);
3825 if (retval != ERROR_OK) {
3829 if (target->state == TARGET_RUNNING) {
3830 retval = target_halt(target);
3831 if (retval != ERROR_OK) {
3837 retval = target_poll(target);
3838 if (retval != ERROR_OK) {
3843 uint32_t start_address = 0;
3844 uint32_t end_address = 0;
3845 bool with_range = false;
3846 if (CMD_ARGC == 4) {
3848 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
3849 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
3852 write_gmon(samples, num_of_samples, CMD_ARGV[1],
3853 with_range, start_address, end_address, target);
3854 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3860 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3863 Jim_Obj *nameObjPtr, *valObjPtr;
3866 namebuf = alloc_printf("%s(%d)", varname, idx);
3870 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3871 valObjPtr = Jim_NewIntObj(interp, val);
3872 if (!nameObjPtr || !valObjPtr) {
3877 Jim_IncrRefCount(nameObjPtr);
3878 Jim_IncrRefCount(valObjPtr);
3879 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3880 Jim_DecrRefCount(interp, nameObjPtr);
3881 Jim_DecrRefCount(interp, valObjPtr);
3883 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3887 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3889 struct command_context *context;
3890 struct target *target;
3892 context = current_command_context(interp);
3893 assert(context != NULL);
3895 target = get_current_target(context);
3896 if (target == NULL) {
3897 LOG_ERROR("mem2array: no current target");
3901 return target_mem2array(interp, target, argc - 1, argv + 1);
3904 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3912 const char *varname;
3916 /* argv[1] = name of array to receive the data
3917 * argv[2] = desired width
3918 * argv[3] = memory address
3919 * argv[4] = count of times to read
3922 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3925 varname = Jim_GetString(argv[0], &len);
3926 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3928 e = Jim_GetLong(interp, argv[1], &l);
3933 e = Jim_GetLong(interp, argv[2], &l);
3937 e = Jim_GetLong(interp, argv[3], &l);
3952 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3953 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3957 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3958 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3961 if ((addr + (len * width)) < addr) {
3962 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3963 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3966 /* absurd transfer size? */
3968 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3969 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3974 ((width == 2) && ((addr & 1) == 0)) ||
3975 ((width == 4) && ((addr & 3) == 0))) {
3979 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3980 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3983 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3992 size_t buffersize = 4096;
3993 uint8_t *buffer = malloc(buffersize);
4000 /* Slurp... in buffer size chunks */
4002 count = len; /* in objects.. */
4003 if (count > (buffersize / width))
4004 count = (buffersize / width);
4006 retval = target_read_memory(target, addr, width, count, buffer);
4007 if (retval != ERROR_OK) {
4009 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
4013 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4014 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
4018 v = 0; /* shut up gcc */
4019 for (i = 0; i < count ; i++, n++) {
4022 v = target_buffer_get_u32(target, &buffer[i*width]);
4025 v = target_buffer_get_u16(target, &buffer[i*width]);
4028 v = buffer[i] & 0x0ff;
4031 new_int_array_element(interp, varname, n, v);
4034 addr += count * width;
4040 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4045 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
4048 Jim_Obj *nameObjPtr, *valObjPtr;
4052 namebuf = alloc_printf("%s(%d)", varname, idx);
4056 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
4062 Jim_IncrRefCount(nameObjPtr);
4063 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
4064 Jim_DecrRefCount(interp, nameObjPtr);
4066 if (valObjPtr == NULL)
4069 result = Jim_GetLong(interp, valObjPtr, &l);
4070 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
4075 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4077 struct command_context *context;
4078 struct target *target;
4080 context = current_command_context(interp);
4081 assert(context != NULL);
4083 target = get_current_target(context);
4084 if (target == NULL) {
4085 LOG_ERROR("array2mem: no current target");
4089 return target_array2mem(interp, target, argc-1, argv + 1);
4092 static int target_array2mem(Jim_Interp *interp, struct target *target,
4093 int argc, Jim_Obj *const *argv)
4101 const char *varname;
4105 /* argv[1] = name of array to get the data
4106 * argv[2] = desired width
4107 * argv[3] = memory address
4108 * argv[4] = count to write
4111 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
4114 varname = Jim_GetString(argv[0], &len);
4115 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
4117 e = Jim_GetLong(interp, argv[1], &l);
4122 e = Jim_GetLong(interp, argv[2], &l);
4126 e = Jim_GetLong(interp, argv[3], &l);
4141 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4142 Jim_AppendStrings(interp, Jim_GetResult(interp),
4143 "Invalid width param, must be 8/16/32", NULL);
4147 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4148 Jim_AppendStrings(interp, Jim_GetResult(interp),
4149 "array2mem: zero width read?", NULL);
4152 if ((addr + (len * width)) < addr) {
4153 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4154 Jim_AppendStrings(interp, Jim_GetResult(interp),
4155 "array2mem: addr + len - wraps to zero?", NULL);
4158 /* absurd transfer size? */
4160 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4161 Jim_AppendStrings(interp, Jim_GetResult(interp),
4162 "array2mem: absurd > 64K item request", NULL);
4167 ((width == 2) && ((addr & 1) == 0)) ||
4168 ((width == 4) && ((addr & 3) == 0))) {
4172 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4173 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
4176 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
4187 size_t buffersize = 4096;
4188 uint8_t *buffer = malloc(buffersize);
4193 /* Slurp... in buffer size chunks */
4195 count = len; /* in objects.. */
4196 if (count > (buffersize / width))
4197 count = (buffersize / width);
4199 v = 0; /* shut up gcc */
4200 for (i = 0; i < count; i++, n++) {
4201 get_int_array_element(interp, varname, n, &v);
4204 target_buffer_set_u32(target, &buffer[i * width], v);
4207 target_buffer_set_u16(target, &buffer[i * width], v);
4210 buffer[i] = v & 0x0ff;
4216 retval = target_write_memory(target, addr, width, count, buffer);
4217 if (retval != ERROR_OK) {
4219 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
4223 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4224 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4228 addr += count * width;
4233 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4238 /* FIX? should we propagate errors here rather than printing them
4241 void target_handle_event(struct target *target, enum target_event e)
4243 struct target_event_action *teap;
4245 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4246 if (teap->event == e) {
4247 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
4248 target->target_number,
4249 target_name(target),
4250 target_type_name(target),
4252 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
4253 Jim_GetString(teap->body, NULL));
4254 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
4255 Jim_MakeErrorMessage(teap->interp);
4256 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
4263 * Returns true only if the target has a handler for the specified event.
4265 bool target_has_event_action(struct target *target, enum target_event event)
4267 struct target_event_action *teap;
4269 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4270 if (teap->event == event)
4276 enum target_cfg_param {
4279 TCFG_WORK_AREA_VIRT,
4280 TCFG_WORK_AREA_PHYS,
4281 TCFG_WORK_AREA_SIZE,
4282 TCFG_WORK_AREA_BACKUP,
4285 TCFG_CHAIN_POSITION,
4290 static Jim_Nvp nvp_config_opts[] = {
4291 { .name = "-type", .value = TCFG_TYPE },
4292 { .name = "-event", .value = TCFG_EVENT },
4293 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4294 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4295 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4296 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4297 { .name = "-endian" , .value = TCFG_ENDIAN },
4298 { .name = "-coreid", .value = TCFG_COREID },
4299 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4300 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4301 { .name = "-rtos", .value = TCFG_RTOS },
4302 { .name = NULL, .value = -1 }
4305 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
4312 /* parse config or cget options ... */
4313 while (goi->argc > 0) {
4314 Jim_SetEmptyResult(goi->interp);
4315 /* Jim_GetOpt_Debug(goi); */
4317 if (target->type->target_jim_configure) {
4318 /* target defines a configure function */
4319 /* target gets first dibs on parameters */
4320 e = (*(target->type->target_jim_configure))(target, goi);
4329 /* otherwise we 'continue' below */
4331 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
4333 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
4339 if (goi->isconfigure) {
4340 Jim_SetResultFormatted(goi->interp,
4341 "not settable: %s", n->name);
4345 if (goi->argc != 0) {
4346 Jim_WrongNumArgs(goi->interp,
4347 goi->argc, goi->argv,
4352 Jim_SetResultString(goi->interp,
4353 target_type_name(target), -1);
4357 if (goi->argc == 0) {
4358 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4362 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4364 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4368 if (goi->isconfigure) {
4369 if (goi->argc != 1) {
4370 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4374 if (goi->argc != 0) {
4375 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4381 struct target_event_action *teap;
4383 teap = target->event_action;
4384 /* replace existing? */
4386 if (teap->event == (enum target_event)n->value)
4391 if (goi->isconfigure) {
4392 bool replace = true;
4395 teap = calloc(1, sizeof(*teap));
4398 teap->event = n->value;
4399 teap->interp = goi->interp;
4400 Jim_GetOpt_Obj(goi, &o);
4402 Jim_DecrRefCount(teap->interp, teap->body);
4403 teap->body = Jim_DuplicateObj(goi->interp, o);
4406 * Tcl/TK - "tk events" have a nice feature.
4407 * See the "BIND" command.
4408 * We should support that here.
4409 * You can specify %X and %Y in the event code.
4410 * The idea is: %T - target name.
4411 * The idea is: %N - target number
4412 * The idea is: %E - event name.
4414 Jim_IncrRefCount(teap->body);
4417 /* add to head of event list */
4418 teap->next = target->event_action;
4419 target->event_action = teap;
4421 Jim_SetEmptyResult(goi->interp);
4425 Jim_SetEmptyResult(goi->interp);
4427 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4433 case TCFG_WORK_AREA_VIRT:
4434 if (goi->isconfigure) {
4435 target_free_all_working_areas(target);
4436 e = Jim_GetOpt_Wide(goi, &w);
4439 target->working_area_virt = w;
4440 target->working_area_virt_spec = true;
4445 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4449 case TCFG_WORK_AREA_PHYS:
4450 if (goi->isconfigure) {
4451 target_free_all_working_areas(target);
4452 e = Jim_GetOpt_Wide(goi, &w);
4455 target->working_area_phys = w;
4456 target->working_area_phys_spec = true;
4461 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4465 case TCFG_WORK_AREA_SIZE:
4466 if (goi->isconfigure) {
4467 target_free_all_working_areas(target);
4468 e = Jim_GetOpt_Wide(goi, &w);
4471 target->working_area_size = w;
4476 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4480 case TCFG_WORK_AREA_BACKUP:
4481 if (goi->isconfigure) {
4482 target_free_all_working_areas(target);
4483 e = Jim_GetOpt_Wide(goi, &w);
4486 /* make this exactly 1 or 0 */
4487 target->backup_working_area = (!!w);
4492 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4493 /* loop for more e*/
4498 if (goi->isconfigure) {
4499 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4501 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4504 target->endianness = n->value;
4509 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4510 if (n->name == NULL) {
4511 target->endianness = TARGET_LITTLE_ENDIAN;
4512 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4514 Jim_SetResultString(goi->interp, n->name, -1);
4519 if (goi->isconfigure) {
4520 e = Jim_GetOpt_Wide(goi, &w);
4523 target->coreid = (int32_t)w;
4528 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4532 case TCFG_CHAIN_POSITION:
4533 if (goi->isconfigure) {
4535 struct jtag_tap *tap;
4536 target_free_all_working_areas(target);
4537 e = Jim_GetOpt_Obj(goi, &o_t);
4540 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4543 /* make this exactly 1 or 0 */
4549 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4550 /* loop for more e*/
4553 if (goi->isconfigure) {
4554 e = Jim_GetOpt_Wide(goi, &w);
4557 target->dbgbase = (uint32_t)w;
4558 target->dbgbase_set = true;
4563 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4570 int result = rtos_create(goi, target);
4571 if (result != JIM_OK)
4577 } /* while (goi->argc) */
4580 /* done - we return */
4584 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4588 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4589 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4590 int need_args = 1 + goi.isconfigure;
4591 if (goi.argc < need_args) {
4592 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4594 ? "missing: -option VALUE ..."
4595 : "missing: -option ...");
4598 struct target *target = Jim_CmdPrivData(goi.interp);
4599 return target_configure(&goi, target);
4602 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4604 const char *cmd_name = Jim_GetString(argv[0], NULL);
4607 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4609 if (goi.argc < 2 || goi.argc > 4) {
4610 Jim_SetResultFormatted(goi.interp,
4611 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4616 fn = target_write_memory;
4619 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4621 struct Jim_Obj *obj;
4622 e = Jim_GetOpt_Obj(&goi, &obj);
4626 fn = target_write_phys_memory;
4630 e = Jim_GetOpt_Wide(&goi, &a);
4635 e = Jim_GetOpt_Wide(&goi, &b);
4640 if (goi.argc == 1) {
4641 e = Jim_GetOpt_Wide(&goi, &c);
4646 /* all args must be consumed */
4650 struct target *target = Jim_CmdPrivData(goi.interp);
4652 if (strcasecmp(cmd_name, "mww") == 0)
4654 else if (strcasecmp(cmd_name, "mwh") == 0)
4656 else if (strcasecmp(cmd_name, "mwb") == 0)
4659 LOG_ERROR("command '%s' unknown: ", cmd_name);
4663 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4667 * @brief Reads an array of words/halfwords/bytes from target memory starting at specified address.
4669 * Usage: mdw [phys] <address> [<count>] - for 32 bit reads
4670 * mdh [phys] <address> [<count>] - for 16 bit reads
4671 * mdb [phys] <address> [<count>] - for 8 bit reads
4673 * Count defaults to 1.
4675 * Calls target_read_memory or target_read_phys_memory depending on
4676 * the presence of the "phys" argument
4677 * Reads the target memory in blocks of max. 32 bytes, and returns an array of ints formatted
4678 * to int representation in base16.
4679 * Also outputs read data in a human readable form using command_print
4681 * @param phys if present target_read_phys_memory will be used instead of target_read_memory
4682 * @param address address where to start the read. May be specified in decimal or hex using the standard "0x" prefix
4683 * @param count optional count parameter to read an array of values. If not specified, defaults to 1.
4684 * @returns: JIM_ERR on error or JIM_OK on success and sets the result string to an array of ascii formatted numbers
4685 * on success, with [<count>] number of elements.
4687 * In case of little endian target:
4688 * Example1: "mdw 0x00000000" returns "10123456"
4689 * Exmaple2: "mdh 0x00000000 1" returns "3456"
4690 * Example3: "mdb 0x00000000" returns "56"
4691 * Example4: "mdh 0x00000000 2" returns "3456 1012"
4692 * Example5: "mdb 0x00000000 3" returns "56 34 12"
4694 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4696 const char *cmd_name = Jim_GetString(argv[0], NULL);
4699 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4701 if ((goi.argc < 1) || (goi.argc > 3)) {
4702 Jim_SetResultFormatted(goi.interp,
4703 "usage: %s [phys] <address> [<count>]", cmd_name);
4707 int (*fn)(struct target *target,
4708 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4709 fn = target_read_memory;
4712 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4714 struct Jim_Obj *obj;
4715 e = Jim_GetOpt_Obj(&goi, &obj);
4719 fn = target_read_phys_memory;
4722 /* Read address parameter */
4724 e = Jim_GetOpt_Wide(&goi, &addr);
4728 /* If next parameter exists, read it out as the count parameter, if not, set it to 1 (default) */
4730 if (goi.argc == 1) {
4731 e = Jim_GetOpt_Wide(&goi, &count);
4737 /* all args must be consumed */
4741 jim_wide dwidth = 1; /* shut up gcc */
4742 if (strcasecmp(cmd_name, "mdw") == 0)
4744 else if (strcasecmp(cmd_name, "mdh") == 0)
4746 else if (strcasecmp(cmd_name, "mdb") == 0)
4749 LOG_ERROR("command '%s' unknown: ", cmd_name);
4753 /* convert count to "bytes" */
4754 int bytes = count * dwidth;
4756 struct target *target = Jim_CmdPrivData(goi.interp);
4757 uint8_t target_buf[32];
4760 y = (bytes < 16) ? bytes : 16; /* y = min(bytes, 16); */
4762 /* Try to read out next block */
4763 e = fn(target, addr, dwidth, y / dwidth, target_buf);
4765 if (e != ERROR_OK) {
4766 Jim_SetResultFormatted(interp, "error reading target @ 0x%08lx", (long)addr);
4770 command_print_sameline(NULL, "0x%08x ", (int)(addr));
4773 for (x = 0; x < 16 && x < y; x += 4) {
4774 z = target_buffer_get_u32(target, &(target_buf[x]));
4775 command_print_sameline(NULL, "%08x ", (int)(z));
4777 for (; (x < 16) ; x += 4)
4778 command_print_sameline(NULL, " ");
4781 for (x = 0; x < 16 && x < y; x += 2) {
4782 z = target_buffer_get_u16(target, &(target_buf[x]));
4783 command_print_sameline(NULL, "%04x ", (int)(z));
4785 for (; (x < 16) ; x += 2)
4786 command_print_sameline(NULL, " ");
4790 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4791 z = target_buffer_get_u8(target, &(target_buf[x]));
4792 command_print_sameline(NULL, "%02x ", (int)(z));
4794 for (; (x < 16) ; x += 1)
4795 command_print_sameline(NULL, " ");
4798 /* ascii-ify the bytes */
4799 for (x = 0 ; x < y ; x++) {
4800 if ((target_buf[x] >= 0x20) &&
4801 (target_buf[x] <= 0x7e)) {
4805 target_buf[x] = '.';
4810 target_buf[x] = ' ';
4815 /* print - with a newline */
4816 command_print_sameline(NULL, "%s\n", target_buf);
4824 static int jim_target_mem2array(Jim_Interp *interp,
4825 int argc, Jim_Obj *const *argv)
4827 struct target *target = Jim_CmdPrivData(interp);
4828 return target_mem2array(interp, target, argc - 1, argv + 1);
4831 static int jim_target_array2mem(Jim_Interp *interp,
4832 int argc, Jim_Obj *const *argv)
4834 struct target *target = Jim_CmdPrivData(interp);
4835 return target_array2mem(interp, target, argc - 1, argv + 1);
4838 static int jim_target_tap_disabled(Jim_Interp *interp)
4840 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4844 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4847 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4850 struct target *target = Jim_CmdPrivData(interp);
4851 if (!target->tap->enabled)
4852 return jim_target_tap_disabled(interp);
4854 int e = target->type->examine(target);
4860 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4863 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4866 struct target *target = Jim_CmdPrivData(interp);
4868 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4874 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4877 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4880 struct target *target = Jim_CmdPrivData(interp);
4881 if (!target->tap->enabled)
4882 return jim_target_tap_disabled(interp);
4885 if (!(target_was_examined(target)))
4886 e = ERROR_TARGET_NOT_EXAMINED;
4888 e = target->type->poll(target);
4894 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4897 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4899 if (goi.argc != 2) {
4900 Jim_WrongNumArgs(interp, 0, argv,
4901 "([tT]|[fF]|assert|deassert) BOOL");
4906 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4908 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4911 /* the halt or not param */
4913 e = Jim_GetOpt_Wide(&goi, &a);
4917 struct target *target = Jim_CmdPrivData(goi.interp);
4918 if (!target->tap->enabled)
4919 return jim_target_tap_disabled(interp);
4920 if (!(target_was_examined(target))) {
4921 LOG_ERROR("Target not examined yet");
4922 return ERROR_TARGET_NOT_EXAMINED;
4924 if (!target->type->assert_reset || !target->type->deassert_reset) {
4925 Jim_SetResultFormatted(interp,
4926 "No target-specific reset for %s",
4927 target_name(target));
4930 /* determine if we should halt or not. */
4931 target->reset_halt = !!a;
4932 /* When this happens - all workareas are invalid. */
4933 target_free_all_working_areas_restore(target, 0);
4936 if (n->value == NVP_ASSERT)
4937 e = target->type->assert_reset(target);
4939 e = target->type->deassert_reset(target);
4940 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4943 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4946 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4949 struct target *target = Jim_CmdPrivData(interp);
4950 if (!target->tap->enabled)
4951 return jim_target_tap_disabled(interp);
4952 int e = target->type->halt(target);
4953 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4956 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4959 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4961 /* params: <name> statename timeoutmsecs */
4962 if (goi.argc != 2) {
4963 const char *cmd_name = Jim_GetString(argv[0], NULL);
4964 Jim_SetResultFormatted(goi.interp,
4965 "%s <state_name> <timeout_in_msec>", cmd_name);
4970 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4972 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
4976 e = Jim_GetOpt_Wide(&goi, &a);
4979 struct target *target = Jim_CmdPrivData(interp);
4980 if (!target->tap->enabled)
4981 return jim_target_tap_disabled(interp);
4983 e = target_wait_state(target, n->value, a);
4984 if (e != ERROR_OK) {
4985 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4986 Jim_SetResultFormatted(goi.interp,
4987 "target: %s wait %s fails (%#s) %s",
4988 target_name(target), n->name,
4989 eObj, target_strerror_safe(e));
4990 Jim_FreeNewObj(interp, eObj);
4995 /* List for human, Events defined for this target.
4996 * scripts/programs should use 'name cget -event NAME'
4998 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5000 struct command_context *cmd_ctx = current_command_context(interp);
5001 assert(cmd_ctx != NULL);
5003 struct target *target = Jim_CmdPrivData(interp);
5004 struct target_event_action *teap = target->event_action;
5005 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
5006 target->target_number,
5007 target_name(target));
5008 command_print(cmd_ctx, "%-25s | Body", "Event");
5009 command_print(cmd_ctx, "------------------------- | "
5010 "----------------------------------------");
5012 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
5013 command_print(cmd_ctx, "%-25s | %s",
5014 opt->name, Jim_GetString(teap->body, NULL));
5017 command_print(cmd_ctx, "***END***");
5020 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5023 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5026 struct target *target = Jim_CmdPrivData(interp);
5027 Jim_SetResultString(interp, target_state_name(target), -1);
5030 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5033 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5034 if (goi.argc != 1) {
5035 const char *cmd_name = Jim_GetString(argv[0], NULL);
5036 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5040 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
5042 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
5045 struct target *target = Jim_CmdPrivData(interp);
5046 target_handle_event(target, n->value);
5050 static const struct command_registration target_instance_command_handlers[] = {
5052 .name = "configure",
5053 .mode = COMMAND_CONFIG,
5054 .jim_handler = jim_target_configure,
5055 .help = "configure a new target for use",
5056 .usage = "[target_attribute ...]",
5060 .mode = COMMAND_ANY,
5061 .jim_handler = jim_target_configure,
5062 .help = "returns the specified target attribute",
5063 .usage = "target_attribute",
5067 .mode = COMMAND_EXEC,
5068 .jim_handler = jim_target_mw,
5069 .help = "Write 32-bit word(s) to target memory",
5070 .usage = "address data [count]",
5074 .mode = COMMAND_EXEC,
5075 .jim_handler = jim_target_mw,
5076 .help = "Write 16-bit half-word(s) to target memory",
5077 .usage = "address data [count]",
5081 .mode = COMMAND_EXEC,
5082 .jim_handler = jim_target_mw,
5083 .help = "Write byte(s) to target memory",
5084 .usage = "address data [count]",
5088 .mode = COMMAND_EXEC,
5089 .jim_handler = jim_target_md,
5090 .help = "Display target memory as 32-bit words",
5091 .usage = "address [count]",
5095 .mode = COMMAND_EXEC,
5096 .jim_handler = jim_target_md,
5097 .help = "Display target memory as 16-bit half-words",
5098 .usage = "address [count]",
5102 .mode = COMMAND_EXEC,
5103 .jim_handler = jim_target_md,
5104 .help = "Display target memory as 8-bit bytes",
5105 .usage = "address [count]",
5108 .name = "array2mem",
5109 .mode = COMMAND_EXEC,
5110 .jim_handler = jim_target_array2mem,
5111 .help = "Writes Tcl array of 8/16/32 bit numbers "
5113 .usage = "arrayname bitwidth address count",
5116 .name = "mem2array",
5117 .mode = COMMAND_EXEC,
5118 .jim_handler = jim_target_mem2array,
5119 .help = "Loads Tcl array of 8/16/32 bit numbers "
5120 "from target memory",
5121 .usage = "arrayname bitwidth address count",
5124 .name = "eventlist",
5125 .mode = COMMAND_EXEC,
5126 .jim_handler = jim_target_event_list,
5127 .help = "displays a table of events defined for this target",
5131 .mode = COMMAND_EXEC,
5132 .jim_handler = jim_target_current_state,
5133 .help = "displays the current state of this target",
5136 .name = "arp_examine",
5137 .mode = COMMAND_EXEC,
5138 .jim_handler = jim_target_examine,
5139 .help = "used internally for reset processing",
5142 .name = "arp_halt_gdb",
5143 .mode = COMMAND_EXEC,
5144 .jim_handler = jim_target_halt_gdb,
5145 .help = "used internally for reset processing to halt GDB",
5149 .mode = COMMAND_EXEC,
5150 .jim_handler = jim_target_poll,
5151 .help = "used internally for reset processing",
5154 .name = "arp_reset",
5155 .mode = COMMAND_EXEC,
5156 .jim_handler = jim_target_reset,
5157 .help = "used internally for reset processing",
5161 .mode = COMMAND_EXEC,
5162 .jim_handler = jim_target_halt,
5163 .help = "used internally for reset processing",
5166 .name = "arp_waitstate",
5167 .mode = COMMAND_EXEC,
5168 .jim_handler = jim_target_wait_state,
5169 .help = "used internally for reset processing",
5172 .name = "invoke-event",
5173 .mode = COMMAND_EXEC,
5174 .jim_handler = jim_target_invoke_event,
5175 .help = "invoke handler for specified event",
5176 .usage = "event_name",
5178 COMMAND_REGISTRATION_DONE
5181 static int target_create(Jim_GetOptInfo *goi)
5189 struct target *target;
5190 struct command_context *cmd_ctx;
5192 cmd_ctx = current_command_context(goi->interp);
5193 assert(cmd_ctx != NULL);
5195 if (goi->argc < 3) {
5196 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5201 Jim_GetOpt_Obj(goi, &new_cmd);
5202 /* does this command exist? */
5203 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
5205 cp = Jim_GetString(new_cmd, NULL);
5206 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5211 e = Jim_GetOpt_String(goi, &cp2, NULL);
5215 struct transport *tr = get_current_transport();
5216 if (tr->override_target) {
5217 e = tr->override_target(&cp);
5218 if (e != ERROR_OK) {
5219 LOG_ERROR("The selected transport doesn't support this target");
5222 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5224 /* now does target type exist */
5225 for (x = 0 ; target_types[x] ; x++) {
5226 if (0 == strcmp(cp, target_types[x]->name)) {
5231 /* check for deprecated name */
5232 if (target_types[x]->deprecated_name) {
5233 if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
5235 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
5240 if (target_types[x] == NULL) {
5241 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5242 for (x = 0 ; target_types[x] ; x++) {
5243 if (target_types[x + 1]) {
5244 Jim_AppendStrings(goi->interp,
5245 Jim_GetResult(goi->interp),
5246 target_types[x]->name,
5249 Jim_AppendStrings(goi->interp,
5250 Jim_GetResult(goi->interp),
5252 target_types[x]->name, NULL);
5259 target = calloc(1, sizeof(struct target));
5260 /* set target number */
5261 target->target_number = new_target_number();
5262 cmd_ctx->current_target = target->target_number;
5264 /* allocate memory for each unique target type */
5265 target->type = calloc(1, sizeof(struct target_type));
5267 memcpy(target->type, target_types[x], sizeof(struct target_type));
5269 /* will be set by "-endian" */
5270 target->endianness = TARGET_ENDIAN_UNKNOWN;
5272 /* default to first core, override with -coreid */
5275 target->working_area = 0x0;
5276 target->working_area_size = 0x0;
5277 target->working_areas = NULL;
5278 target->backup_working_area = 0;
5280 target->state = TARGET_UNKNOWN;
5281 target->debug_reason = DBG_REASON_UNDEFINED;
5282 target->reg_cache = NULL;
5283 target->breakpoints = NULL;
5284 target->watchpoints = NULL;
5285 target->next = NULL;
5286 target->arch_info = NULL;
5288 target->display = 1;
5290 target->halt_issued = false;
5292 /* initialize trace information */
5293 target->trace_info = malloc(sizeof(struct trace));
5294 target->trace_info->num_trace_points = 0;
5295 target->trace_info->trace_points_size = 0;
5296 target->trace_info->trace_points = NULL;
5297 target->trace_info->trace_history_size = 0;
5298 target->trace_info->trace_history = NULL;
5299 target->trace_info->trace_history_pos = 0;
5300 target->trace_info->trace_history_overflowed = 0;
5302 target->dbgmsg = NULL;
5303 target->dbg_msg_enabled = 0;
5305 target->endianness = TARGET_ENDIAN_UNKNOWN;
5307 target->rtos = NULL;
5308 target->rtos_auto_detect = false;
5310 /* Do the rest as "configure" options */
5311 goi->isconfigure = 1;
5312 e = target_configure(goi, target);
5314 if (target->tap == NULL) {
5315 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
5325 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5326 /* default endian to little if not specified */
5327 target->endianness = TARGET_LITTLE_ENDIAN;
5330 cp = Jim_GetString(new_cmd, NULL);
5331 target->cmd_name = strdup(cp);
5333 /* create the target specific commands */
5334 if (target->type->commands) {
5335 e = register_commands(cmd_ctx, NULL, target->type->commands);
5337 LOG_ERROR("unable to register '%s' commands", cp);
5339 if (target->type->target_create)
5340 (*(target->type->target_create))(target, goi->interp);
5342 /* append to end of list */
5344 struct target **tpp;
5345 tpp = &(all_targets);
5347 tpp = &((*tpp)->next);
5351 /* now - create the new target name command */
5352 const struct command_registration target_subcommands[] = {
5354 .chain = target_instance_command_handlers,
5357 .chain = target->type->commands,
5359 COMMAND_REGISTRATION_DONE
5361 const struct command_registration target_commands[] = {
5364 .mode = COMMAND_ANY,
5365 .help = "target command group",
5367 .chain = target_subcommands,
5369 COMMAND_REGISTRATION_DONE
5371 e = register_commands(cmd_ctx, NULL, target_commands);
5375 struct command *c = command_find_in_context(cmd_ctx, cp);
5377 command_set_handler_data(c, target);
5379 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5382 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5385 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5388 struct command_context *cmd_ctx = current_command_context(interp);
5389 assert(cmd_ctx != NULL);
5391 Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5395 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5398 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5401 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5402 for (unsigned x = 0; NULL != target_types[x]; x++) {
5403 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5404 Jim_NewStringObj(interp, target_types[x]->name, -1));
5409 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5412 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5415 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5416 struct target *target = all_targets;
5418 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5419 Jim_NewStringObj(interp, target_name(target), -1));
5420 target = target->next;
5425 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5428 const char *targetname;
5430 struct target *target = (struct target *) NULL;
5431 struct target_list *head, *curr, *new;
5432 curr = (struct target_list *) NULL;
5433 head = (struct target_list *) NULL;
5436 LOG_DEBUG("%d", argc);
5437 /* argv[1] = target to associate in smp
5438 * argv[2] = target to assoicate in smp
5442 for (i = 1; i < argc; i++) {
5444 targetname = Jim_GetString(argv[i], &len);
5445 target = get_target(targetname);
5446 LOG_DEBUG("%s ", targetname);
5448 new = malloc(sizeof(struct target_list));
5449 new->target = target;
5450 new->next = (struct target_list *)NULL;
5451 if (head == (struct target_list *)NULL) {
5460 /* now parse the list of cpu and put the target in smp mode*/
5463 while (curr != (struct target_list *)NULL) {
5464 target = curr->target;
5466 target->head = head;
5470 if (target && target->rtos)
5471 retval = rtos_smp_init(head->target);
5477 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5480 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5482 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5483 "<name> <target_type> [<target_options> ...]");
5486 return target_create(&goi);
5489 static const struct command_registration target_subcommand_handlers[] = {
5492 .mode = COMMAND_CONFIG,
5493 .handler = handle_target_init_command,
5494 .help = "initialize targets",
5498 /* REVISIT this should be COMMAND_CONFIG ... */
5499 .mode = COMMAND_ANY,
5500 .jim_handler = jim_target_create,
5501 .usage = "name type '-chain-position' name [options ...]",
5502 .help = "Creates and selects a new target",
5506 .mode = COMMAND_ANY,
5507 .jim_handler = jim_target_current,
5508 .help = "Returns the currently selected target",
5512 .mode = COMMAND_ANY,
5513 .jim_handler = jim_target_types,
5514 .help = "Returns the available target types as "
5515 "a list of strings",
5519 .mode = COMMAND_ANY,
5520 .jim_handler = jim_target_names,
5521 .help = "Returns the names of all targets as a list of strings",
5525 .mode = COMMAND_ANY,
5526 .jim_handler = jim_target_smp,
5527 .usage = "targetname1 targetname2 ...",
5528 .help = "gather several target in a smp list"
5531 COMMAND_REGISTRATION_DONE
5541 static int fastload_num;
5542 static struct FastLoad *fastload;
5544 static void free_fastload(void)
5546 if (fastload != NULL) {
5548 for (i = 0; i < fastload_num; i++) {
5549 if (fastload[i].data)
5550 free(fastload[i].data);
5557 COMMAND_HANDLER(handle_fast_load_image_command)
5561 uint32_t image_size;
5562 uint32_t min_address = 0;
5563 uint32_t max_address = 0xffffffff;
5568 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5569 &image, &min_address, &max_address);
5570 if (ERROR_OK != retval)
5573 struct duration bench;
5574 duration_start(&bench);
5576 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5577 if (retval != ERROR_OK)
5582 fastload_num = image.num_sections;
5583 fastload = malloc(sizeof(struct FastLoad)*image.num_sections);
5584 if (fastload == NULL) {
5585 command_print(CMD_CTX, "out of memory");
5586 image_close(&image);
5589 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5590 for (i = 0; i < image.num_sections; i++) {
5591 buffer = malloc(image.sections[i].size);
5592 if (buffer == NULL) {
5593 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5594 (int)(image.sections[i].size));
5595 retval = ERROR_FAIL;
5599 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5600 if (retval != ERROR_OK) {
5605 uint32_t offset = 0;
5606 uint32_t length = buf_cnt;
5608 /* DANGER!!! beware of unsigned comparision here!!! */
5610 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5611 (image.sections[i].base_address < max_address)) {
5612 if (image.sections[i].base_address < min_address) {
5613 /* clip addresses below */
5614 offset += min_address-image.sections[i].base_address;
5618 if (image.sections[i].base_address + buf_cnt > max_address)
5619 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5621 fastload[i].address = image.sections[i].base_address + offset;
5622 fastload[i].data = malloc(length);
5623 if (fastload[i].data == NULL) {
5625 command_print(CMD_CTX, "error allocating buffer for section (%" PRIu32 " bytes)",
5627 retval = ERROR_FAIL;
5630 memcpy(fastload[i].data, buffer + offset, length);
5631 fastload[i].length = length;
5633 image_size += length;
5634 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5635 (unsigned int)length,
5636 ((unsigned int)(image.sections[i].base_address + offset)));
5642 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5643 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5644 "in %fs (%0.3f KiB/s)", image_size,
5645 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5647 command_print(CMD_CTX,
5648 "WARNING: image has not been loaded to target!"
5649 "You can issue a 'fast_load' to finish loading.");
5652 image_close(&image);
5654 if (retval != ERROR_OK)
5660 COMMAND_HANDLER(handle_fast_load_command)
5663 return ERROR_COMMAND_SYNTAX_ERROR;
5664 if (fastload == NULL) {
5665 LOG_ERROR("No image in memory");
5669 int ms = timeval_ms();
5671 int retval = ERROR_OK;
5672 for (i = 0; i < fastload_num; i++) {
5673 struct target *target = get_current_target(CMD_CTX);
5674 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5675 (unsigned int)(fastload[i].address),
5676 (unsigned int)(fastload[i].length));
5677 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5678 if (retval != ERROR_OK)
5680 size += fastload[i].length;
5682 if (retval == ERROR_OK) {
5683 int after = timeval_ms();
5684 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5689 static const struct command_registration target_command_handlers[] = {
5692 .handler = handle_targets_command,
5693 .mode = COMMAND_ANY,
5694 .help = "change current default target (one parameter) "
5695 "or prints table of all targets (no parameters)",
5696 .usage = "[target]",
5700 .mode = COMMAND_CONFIG,
5701 .help = "configure target",
5703 .chain = target_subcommand_handlers,
5705 COMMAND_REGISTRATION_DONE
5708 int target_register_commands(struct command_context *cmd_ctx)
5710 return register_commands(cmd_ctx, NULL, target_command_handlers);
5713 static bool target_reset_nag = true;
5715 bool get_target_reset_nag(void)
5717 return target_reset_nag;
5720 COMMAND_HANDLER(handle_target_reset_nag)
5722 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5723 &target_reset_nag, "Nag after each reset about options to improve "
5727 COMMAND_HANDLER(handle_ps_command)
5729 struct target *target = get_current_target(CMD_CTX);
5731 if (target->state != TARGET_HALTED) {
5732 LOG_INFO("target not halted !!");
5736 if ((target->rtos) && (target->rtos->type)
5737 && (target->rtos->type->ps_command)) {
5738 display = target->rtos->type->ps_command(target);
5739 command_print(CMD_CTX, "%s", display);
5744 return ERROR_TARGET_FAILURE;
5748 static void binprint(struct command_context *cmd_ctx, const char *text, const uint8_t *buf, int size)
5751 command_print_sameline(cmd_ctx, "%s", text);
5752 for (int i = 0; i < size; i++)
5753 command_print_sameline(cmd_ctx, " %02x", buf[i]);
5754 command_print(cmd_ctx, " ");
5757 COMMAND_HANDLER(handle_test_mem_access_command)
5759 struct target *target = get_current_target(CMD_CTX);
5761 int retval = ERROR_OK;
5763 if (target->state != TARGET_HALTED) {
5764 LOG_INFO("target not halted !!");
5769 return ERROR_COMMAND_SYNTAX_ERROR;
5771 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
5774 size_t num_bytes = test_size + 4;
5776 struct working_area *wa = NULL;
5777 retval = target_alloc_working_area(target, num_bytes, &wa);
5778 if (retval != ERROR_OK) {
5779 LOG_ERROR("Not enough working area");
5783 uint8_t *test_pattern = malloc(num_bytes);
5785 for (size_t i = 0; i < num_bytes; i++)
5786 test_pattern[i] = rand();
5788 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
5789 if (retval != ERROR_OK) {
5790 LOG_ERROR("Test pattern write failed");
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 + 2) * size + host_offset;
5799 uint8_t *read_ref = malloc(host_bufsiz);
5800 uint8_t *read_buf = malloc(host_bufsiz);
5802 for (size_t i = 0; i < host_bufsiz; i++) {
5803 read_ref[i] = rand();
5804 read_buf[i] = read_ref[i];
5806 command_print_sameline(CMD_CTX,
5807 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
5808 size, offset, host_offset ? "un" : "");
5810 struct duration bench;
5811 duration_start(&bench);
5813 retval = target_read_memory(target, wa->address + offset, size, count,
5814 read_buf + size + host_offset);
5816 duration_measure(&bench);
5818 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
5819 command_print(CMD_CTX, "Unsupported alignment");
5821 } else if (retval != ERROR_OK) {
5822 command_print(CMD_CTX, "Memory read failed");
5826 /* replay on host */
5827 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
5830 int result = memcmp(read_ref, read_buf, host_bufsiz);
5832 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
5833 duration_elapsed(&bench),
5834 duration_kbps(&bench, count * size));
5836 command_print(CMD_CTX, "Compare failed");
5837 binprint(CMD_CTX, "ref:", read_ref, host_bufsiz);
5838 binprint(CMD_CTX, "buf:", read_buf, host_bufsiz);
5851 target_free_working_area(target, wa);
5854 num_bytes = test_size + 4 + 4 + 4;
5856 retval = target_alloc_working_area(target, num_bytes, &wa);
5857 if (retval != ERROR_OK) {
5858 LOG_ERROR("Not enough working area");
5862 test_pattern = malloc(num_bytes);
5864 for (size_t i = 0; i < num_bytes; i++)
5865 test_pattern[i] = rand();
5867 for (int host_offset = 0; host_offset <= 1; host_offset++) {
5868 for (int size = 1; size <= 4; size *= 2) {
5869 for (int offset = 0; offset < 4; offset++) {
5870 uint32_t count = test_size / size;
5871 size_t host_bufsiz = count * size + host_offset;
5872 uint8_t *read_ref = malloc(num_bytes);
5873 uint8_t *read_buf = malloc(num_bytes);
5874 uint8_t *write_buf = malloc(host_bufsiz);
5876 for (size_t i = 0; i < host_bufsiz; i++)
5877 write_buf[i] = rand();
5878 command_print_sameline(CMD_CTX,
5879 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
5880 size, offset, host_offset ? "un" : "");
5882 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
5883 if (retval != ERROR_OK) {
5884 command_print(CMD_CTX, "Test pattern write failed");
5888 /* replay on host */
5889 memcpy(read_ref, test_pattern, num_bytes);
5890 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
5892 struct duration bench;
5893 duration_start(&bench);
5895 retval = target_write_memory(target, wa->address + size + offset, size, count,
5896 write_buf + host_offset);
5898 duration_measure(&bench);
5900 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
5901 command_print(CMD_CTX, "Unsupported alignment");
5903 } else if (retval != ERROR_OK) {
5904 command_print(CMD_CTX, "Memory write failed");
5909 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
5910 if (retval != ERROR_OK) {
5911 command_print(CMD_CTX, "Test pattern write failed");
5916 int result = memcmp(read_ref, read_buf, num_bytes);
5918 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
5919 duration_elapsed(&bench),
5920 duration_kbps(&bench, count * size));
5922 command_print(CMD_CTX, "Compare failed");
5923 binprint(CMD_CTX, "ref:", read_ref, num_bytes);
5924 binprint(CMD_CTX, "buf:", read_buf, num_bytes);
5936 target_free_working_area(target, wa);
5940 static const struct command_registration target_exec_command_handlers[] = {
5942 .name = "fast_load_image",
5943 .handler = handle_fast_load_image_command,
5944 .mode = COMMAND_ANY,
5945 .help = "Load image into server memory for later use by "
5946 "fast_load; primarily for profiling",
5947 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5948 "[min_address [max_length]]",
5951 .name = "fast_load",
5952 .handler = handle_fast_load_command,
5953 .mode = COMMAND_EXEC,
5954 .help = "loads active fast load image to current target "
5955 "- mainly for profiling purposes",
5960 .handler = handle_profile_command,
5961 .mode = COMMAND_EXEC,
5962 .usage = "seconds filename [start end]",
5963 .help = "profiling samples the CPU PC",
5965 /** @todo don't register virt2phys() unless target supports it */
5967 .name = "virt2phys",
5968 .handler = handle_virt2phys_command,
5969 .mode = COMMAND_ANY,
5970 .help = "translate a virtual address into a physical address",
5971 .usage = "virtual_address",
5975 .handler = handle_reg_command,
5976 .mode = COMMAND_EXEC,
5977 .help = "display (reread from target with \"force\") or set a register; "
5978 "with no arguments, displays all registers and their values",
5979 .usage = "[(register_number|register_name) [(value|'force')]]",
5983 .handler = handle_poll_command,
5984 .mode = COMMAND_EXEC,
5985 .help = "poll target state; or reconfigure background polling",
5986 .usage = "['on'|'off']",
5989 .name = "wait_halt",
5990 .handler = handle_wait_halt_command,
5991 .mode = COMMAND_EXEC,
5992 .help = "wait up to the specified number of milliseconds "
5993 "(default 5000) for a previously requested halt",
5994 .usage = "[milliseconds]",
5998 .handler = handle_halt_command,
5999 .mode = COMMAND_EXEC,
6000 .help = "request target to halt, then wait up to the specified"
6001 "number of milliseconds (default 5000) for it to complete",
6002 .usage = "[milliseconds]",
6006 .handler = handle_resume_command,
6007 .mode = COMMAND_EXEC,
6008 .help = "resume target execution from current PC or address",
6009 .usage = "[address]",
6013 .handler = handle_reset_command,
6014 .mode = COMMAND_EXEC,
6015 .usage = "[run|halt|init]",
6016 .help = "Reset all targets into the specified mode."
6017 "Default reset mode is run, if not given.",
6020 .name = "soft_reset_halt",
6021 .handler = handle_soft_reset_halt_command,
6022 .mode = COMMAND_EXEC,
6024 .help = "halt the target and do a soft reset",
6028 .handler = handle_step_command,
6029 .mode = COMMAND_EXEC,
6030 .help = "step one instruction from current PC or address",
6031 .usage = "[address]",
6035 .handler = handle_md_command,
6036 .mode = COMMAND_EXEC,
6037 .help = "display memory words",
6038 .usage = "['phys'] address [count]",
6042 .handler = handle_md_command,
6043 .mode = COMMAND_EXEC,
6044 .help = "display memory half-words",
6045 .usage = "['phys'] address [count]",
6049 .handler = handle_md_command,
6050 .mode = COMMAND_EXEC,
6051 .help = "display memory bytes",
6052 .usage = "['phys'] address [count]",
6056 .handler = handle_mw_command,
6057 .mode = COMMAND_EXEC,
6058 .help = "write memory word",
6059 .usage = "['phys'] address value [count]",
6063 .handler = handle_mw_command,
6064 .mode = COMMAND_EXEC,
6065 .help = "write memory half-word",
6066 .usage = "['phys'] address value [count]",
6070 .handler = handle_mw_command,
6071 .mode = COMMAND_EXEC,
6072 .help = "write memory byte",
6073 .usage = "['phys'] address value [count]",
6077 .handler = handle_bp_command,
6078 .mode = COMMAND_EXEC,
6079 .help = "list or set hardware or software breakpoint",
6080 .usage = "<address> [<asid>]<length> ['hw'|'hw_ctx']",
6084 .handler = handle_rbp_command,
6085 .mode = COMMAND_EXEC,
6086 .help = "remove breakpoint",
6091 .handler = handle_wp_command,
6092 .mode = COMMAND_EXEC,
6093 .help = "list (no params) or create watchpoints",
6094 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
6098 .handler = handle_rwp_command,
6099 .mode = COMMAND_EXEC,
6100 .help = "remove watchpoint",
6104 .name = "load_image",
6105 .handler = handle_load_image_command,
6106 .mode = COMMAND_EXEC,
6107 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6108 "[min_address] [max_length]",
6111 .name = "dump_image",
6112 .handler = handle_dump_image_command,
6113 .mode = COMMAND_EXEC,
6114 .usage = "filename address size",
6117 .name = "verify_image",
6118 .handler = handle_verify_image_command,
6119 .mode = COMMAND_EXEC,
6120 .usage = "filename [offset [type]]",
6123 .name = "test_image",
6124 .handler = handle_test_image_command,
6125 .mode = COMMAND_EXEC,
6126 .usage = "filename [offset [type]]",
6129 .name = "mem2array",
6130 .mode = COMMAND_EXEC,
6131 .jim_handler = jim_mem2array,
6132 .help = "read 8/16/32 bit memory and return as a TCL array "
6133 "for script processing",
6134 .usage = "arrayname bitwidth address count",
6137 .name = "array2mem",
6138 .mode = COMMAND_EXEC,
6139 .jim_handler = jim_array2mem,
6140 .help = "convert a TCL array to memory locations "
6141 "and write the 8/16/32 bit values",
6142 .usage = "arrayname bitwidth address count",
6145 .name = "reset_nag",
6146 .handler = handle_target_reset_nag,
6147 .mode = COMMAND_ANY,
6148 .help = "Nag after each reset about options that could have been "
6149 "enabled to improve performance. ",
6150 .usage = "['enable'|'disable']",
6154 .handler = handle_ps_command,
6155 .mode = COMMAND_EXEC,
6156 .help = "list all tasks ",
6160 .name = "test_mem_access",
6161 .handler = handle_test_mem_access_command,
6162 .mode = COMMAND_EXEC,
6163 .help = "Test the target's memory access functions",
6167 COMMAND_REGISTRATION_DONE
6169 static int target_register_user_commands(struct command_context *cmd_ctx)
6171 int retval = ERROR_OK;
6172 retval = target_request_register_commands(cmd_ctx);
6173 if (retval != ERROR_OK)
6176 retval = trace_register_commands(cmd_ctx);
6177 if (retval != ERROR_OK)
6181 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);