target: fix messages and return values of failed op because not halted
[openocd.git] / src / target / target.c
blob89eaa23d846a2a2103d069399c93e501fd9d870b
1 // SPDX-License-Identifier: GPL-2.0-or-later
3 /***************************************************************************
4 * Copyright (C) 2005 by Dominic Rath *
5 * Dominic.Rath@gmx.de *
6 * *
7 * Copyright (C) 2007-2010 Øyvind Harboe *
8 * oyvind.harboe@zylin.com *
9 * *
10 * Copyright (C) 2008, Duane Ellis *
11 * openocd@duaneeellis.com *
12 * *
13 * Copyright (C) 2008 by Spencer Oliver *
14 * spen@spen-soft.co.uk *
15 * *
16 * Copyright (C) 2008 by Rick Altherr *
17 * kc8apf@kc8apf.net> *
18 * *
19 * Copyright (C) 2011 by Broadcom Corporation *
20 * Evan Hunter - ehunter@broadcom.com *
21 * *
22 * Copyright (C) ST-Ericsson SA 2011 *
23 * michel.jaouen@stericsson.com : smp minimum support *
24 * *
25 * Copyright (C) 2011 Andreas Fritiofson *
26 * andreas.fritiofson@gmail.com *
27 ***************************************************************************/
29 #ifdef HAVE_CONFIG_H
30 #include "config.h"
31 #endif
33 #include <helper/align.h>
34 #include <helper/nvp.h>
35 #include <helper/time_support.h>
36 #include <jtag/jtag.h>
37 #include <flash/nor/core.h>
39 #include "target.h"
40 #include "target_type.h"
41 #include "target_request.h"
42 #include "breakpoints.h"
43 #include "register.h"
44 #include "trace.h"
45 #include "image.h"
46 #include "rtos/rtos.h"
47 #include "transport/transport.h"
48 #include "arm_cti.h"
49 #include "smp.h"
50 #include "semihosting_common.h"
52 /* default halt wait timeout (ms) */
53 #define DEFAULT_HALT_TIMEOUT 5000
55 static int target_read_buffer_default(struct target *target, target_addr_t address,
56 uint32_t count, uint8_t *buffer);
57 static int target_write_buffer_default(struct target *target, target_addr_t address,
58 uint32_t count, const uint8_t *buffer);
59 static int target_array2mem(Jim_Interp *interp, struct target *target,
60 int argc, Jim_Obj * const *argv);
61 static int target_mem2array(Jim_Interp *interp, struct target *target,
62 int argc, Jim_Obj * const *argv);
63 static int target_register_user_commands(struct command_context *cmd_ctx);
64 static int target_get_gdb_fileio_info_default(struct target *target,
65 struct gdb_fileio_info *fileio_info);
66 static int target_gdb_fileio_end_default(struct target *target, int retcode,
67 int fileio_errno, bool ctrl_c);
69 static struct target_type *target_types[] = {
70 &arm7tdmi_target,
71 &arm9tdmi_target,
72 &arm920t_target,
73 &arm720t_target,
74 &arm966e_target,
75 &arm946e_target,
76 &arm926ejs_target,
77 &fa526_target,
78 &feroceon_target,
79 &dragonite_target,
80 &xscale_target,
81 &xtensa_chip_target,
82 &cortexm_target,
83 &cortexa_target,
84 &cortexr4_target,
85 &arm11_target,
86 &ls1_sap_target,
87 &mips_m4k_target,
88 &avr_target,
89 &dsp563xx_target,
90 &dsp5680xx_target,
91 &testee_target,
92 &avr32_ap7k_target,
93 &hla_target,
94 &esp32_target,
95 &esp32s2_target,
96 &esp32s3_target,
97 &or1k_target,
98 &quark_x10xx_target,
99 &quark_d20xx_target,
100 &stm8_target,
101 &riscv_target,
102 &mem_ap_target,
103 &esirisc_target,
104 &arcv2_target,
105 &aarch64_target,
106 &armv8r_target,
107 &mips_mips64_target,
108 NULL,
111 struct target *all_targets;
112 static struct target_event_callback *target_event_callbacks;
113 static struct target_timer_callback *target_timer_callbacks;
114 static int64_t target_timer_next_event_value;
115 static LIST_HEAD(target_reset_callback_list);
116 static LIST_HEAD(target_trace_callback_list);
117 static const int polling_interval = TARGET_DEFAULT_POLLING_INTERVAL;
118 static LIST_HEAD(empty_smp_targets);
120 enum nvp_assert {
121 NVP_DEASSERT,
122 NVP_ASSERT,
125 static const struct nvp nvp_assert[] = {
126 { .name = "assert", NVP_ASSERT },
127 { .name = "deassert", NVP_DEASSERT },
128 { .name = "T", NVP_ASSERT },
129 { .name = "F", NVP_DEASSERT },
130 { .name = "t", NVP_ASSERT },
131 { .name = "f", NVP_DEASSERT },
132 { .name = NULL, .value = -1 }
135 static const struct nvp nvp_error_target[] = {
136 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
137 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
138 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
139 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
140 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
141 { .value = ERROR_TARGET_UNALIGNED_ACCESS, .name = "err-unaligned-access" },
142 { .value = ERROR_TARGET_DATA_ABORT, .name = "err-data-abort" },
143 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE, .name = "err-resource-not-available" },
144 { .value = ERROR_TARGET_TRANSLATION_FAULT, .name = "err-translation-fault" },
145 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
146 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
147 { .value = -1, .name = NULL }
150 static const char *target_strerror_safe(int err)
152 const struct nvp *n;
154 n = nvp_value2name(nvp_error_target, err);
155 if (!n->name)
156 return "unknown";
157 else
158 return n->name;
161 static const struct jim_nvp nvp_target_event[] = {
163 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
164 { .value = TARGET_EVENT_HALTED, .name = "halted" },
165 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
166 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
167 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
168 { .value = TARGET_EVENT_STEP_START, .name = "step-start" },
169 { .value = TARGET_EVENT_STEP_END, .name = "step-end" },
171 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
172 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
174 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
175 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
176 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
177 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
178 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
179 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
180 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
181 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
183 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
184 { .value = TARGET_EVENT_EXAMINE_FAIL, .name = "examine-fail" },
185 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
187 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
188 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
190 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
191 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
193 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
194 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END, .name = "gdb-flash-write-end" },
196 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
197 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END, .name = "gdb-flash-erase-end" },
199 { .value = TARGET_EVENT_TRACE_CONFIG, .name = "trace-config" },
201 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X100, .name = "semihosting-user-cmd-0x100" },
202 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X101, .name = "semihosting-user-cmd-0x101" },
203 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X102, .name = "semihosting-user-cmd-0x102" },
204 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X103, .name = "semihosting-user-cmd-0x103" },
205 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X104, .name = "semihosting-user-cmd-0x104" },
206 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X105, .name = "semihosting-user-cmd-0x105" },
207 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X106, .name = "semihosting-user-cmd-0x106" },
208 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X107, .name = "semihosting-user-cmd-0x107" },
210 { .name = NULL, .value = -1 }
213 static const struct nvp nvp_target_state[] = {
214 { .name = "unknown", .value = TARGET_UNKNOWN },
215 { .name = "running", .value = TARGET_RUNNING },
216 { .name = "halted", .value = TARGET_HALTED },
217 { .name = "reset", .value = TARGET_RESET },
218 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
219 { .name = NULL, .value = -1 },
222 static const struct nvp nvp_target_debug_reason[] = {
223 { .name = "debug-request", .value = DBG_REASON_DBGRQ },
224 { .name = "breakpoint", .value = DBG_REASON_BREAKPOINT },
225 { .name = "watchpoint", .value = DBG_REASON_WATCHPOINT },
226 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
227 { .name = "single-step", .value = DBG_REASON_SINGLESTEP },
228 { .name = "target-not-halted", .value = DBG_REASON_NOTHALTED },
229 { .name = "program-exit", .value = DBG_REASON_EXIT },
230 { .name = "exception-catch", .value = DBG_REASON_EXC_CATCH },
231 { .name = "undefined", .value = DBG_REASON_UNDEFINED },
232 { .name = NULL, .value = -1 },
235 static const struct jim_nvp nvp_target_endian[] = {
236 { .name = "big", .value = TARGET_BIG_ENDIAN },
237 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
238 { .name = "be", .value = TARGET_BIG_ENDIAN },
239 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
240 { .name = NULL, .value = -1 },
243 static const struct nvp nvp_reset_modes[] = {
244 { .name = "unknown", .value = RESET_UNKNOWN },
245 { .name = "run", .value = RESET_RUN },
246 { .name = "halt", .value = RESET_HALT },
247 { .name = "init", .value = RESET_INIT },
248 { .name = NULL, .value = -1 },
251 const char *debug_reason_name(struct target *t)
253 const char *cp;
255 cp = nvp_value2name(nvp_target_debug_reason,
256 t->debug_reason)->name;
257 if (!cp) {
258 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
259 cp = "(*BUG*unknown*BUG*)";
261 return cp;
264 const char *target_state_name(struct target *t)
266 const char *cp;
267 cp = nvp_value2name(nvp_target_state, t->state)->name;
268 if (!cp) {
269 LOG_ERROR("Invalid target state: %d", (int)(t->state));
270 cp = "(*BUG*unknown*BUG*)";
273 if (!target_was_examined(t) && t->defer_examine)
274 cp = "examine deferred";
276 return cp;
279 const char *target_event_name(enum target_event event)
281 const char *cp;
282 cp = jim_nvp_value2name_simple(nvp_target_event, event)->name;
283 if (!cp) {
284 LOG_ERROR("Invalid target event: %d", (int)(event));
285 cp = "(*BUG*unknown*BUG*)";
287 return cp;
290 const char *target_reset_mode_name(enum target_reset_mode reset_mode)
292 const char *cp;
293 cp = nvp_value2name(nvp_reset_modes, reset_mode)->name;
294 if (!cp) {
295 LOG_ERROR("Invalid target reset mode: %d", (int)(reset_mode));
296 cp = "(*BUG*unknown*BUG*)";
298 return cp;
301 /* determine the number of the new target */
302 static int new_target_number(void)
304 struct target *t;
305 int x;
307 /* number is 0 based */
308 x = -1;
309 t = all_targets;
310 while (t) {
311 if (x < t->target_number)
312 x = t->target_number;
313 t = t->next;
315 return x + 1;
318 static void append_to_list_all_targets(struct target *target)
320 struct target **t = &all_targets;
322 while (*t)
323 t = &((*t)->next);
324 *t = target;
327 /* read a uint64_t from a buffer in target memory endianness */
328 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
330 if (target->endianness == TARGET_LITTLE_ENDIAN)
331 return le_to_h_u64(buffer);
332 else
333 return be_to_h_u64(buffer);
336 /* read a uint32_t from a buffer in target memory endianness */
337 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
339 if (target->endianness == TARGET_LITTLE_ENDIAN)
340 return le_to_h_u32(buffer);
341 else
342 return be_to_h_u32(buffer);
345 /* read a uint24_t from a buffer in target memory endianness */
346 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
348 if (target->endianness == TARGET_LITTLE_ENDIAN)
349 return le_to_h_u24(buffer);
350 else
351 return be_to_h_u24(buffer);
354 /* read a uint16_t from a buffer in target memory endianness */
355 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
357 if (target->endianness == TARGET_LITTLE_ENDIAN)
358 return le_to_h_u16(buffer);
359 else
360 return be_to_h_u16(buffer);
363 /* write a uint64_t to a buffer in target memory endianness */
364 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
366 if (target->endianness == TARGET_LITTLE_ENDIAN)
367 h_u64_to_le(buffer, value);
368 else
369 h_u64_to_be(buffer, value);
372 /* write a uint32_t to a buffer in target memory endianness */
373 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
375 if (target->endianness == TARGET_LITTLE_ENDIAN)
376 h_u32_to_le(buffer, value);
377 else
378 h_u32_to_be(buffer, value);
381 /* write a uint24_t to a buffer in target memory endianness */
382 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
384 if (target->endianness == TARGET_LITTLE_ENDIAN)
385 h_u24_to_le(buffer, value);
386 else
387 h_u24_to_be(buffer, value);
390 /* write a uint16_t to a buffer in target memory endianness */
391 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
393 if (target->endianness == TARGET_LITTLE_ENDIAN)
394 h_u16_to_le(buffer, value);
395 else
396 h_u16_to_be(buffer, value);
399 /* write a uint8_t to a buffer in target memory endianness */
400 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
402 *buffer = value;
405 /* write a uint64_t array to a buffer in target memory endianness */
406 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
408 uint32_t i;
409 for (i = 0; i < count; i++)
410 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
413 /* write a uint32_t array to a buffer in target memory endianness */
414 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
416 uint32_t i;
417 for (i = 0; i < count; i++)
418 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
421 /* write a uint16_t array to a buffer in target memory endianness */
422 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
424 uint32_t i;
425 for (i = 0; i < count; i++)
426 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
429 /* write a uint64_t array to a buffer in target memory endianness */
430 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
432 uint32_t i;
433 for (i = 0; i < count; i++)
434 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
437 /* write a uint32_t array to a buffer in target memory endianness */
438 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
440 uint32_t i;
441 for (i = 0; i < count; i++)
442 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
445 /* write a uint16_t array to a buffer in target memory endianness */
446 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
448 uint32_t i;
449 for (i = 0; i < count; i++)
450 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
453 /* return a pointer to a configured target; id is name or number */
454 struct target *get_target(const char *id)
456 struct target *target;
458 /* try as tcltarget name */
459 for (target = all_targets; target; target = target->next) {
460 if (!target_name(target))
461 continue;
462 if (strcmp(id, target_name(target)) == 0)
463 return target;
466 /* It's OK to remove this fallback sometime after August 2010 or so */
468 /* no match, try as number */
469 unsigned num;
470 if (parse_uint(id, &num) != ERROR_OK)
471 return NULL;
473 for (target = all_targets; target; target = target->next) {
474 if (target->target_number == (int)num) {
475 LOG_WARNING("use '%s' as target identifier, not '%u'",
476 target_name(target), num);
477 return target;
481 return NULL;
484 /* returns a pointer to the n-th configured target */
485 struct target *get_target_by_num(int num)
487 struct target *target = all_targets;
489 while (target) {
490 if (target->target_number == num)
491 return target;
492 target = target->next;
495 return NULL;
498 struct target *get_current_target(struct command_context *cmd_ctx)
500 struct target *target = get_current_target_or_null(cmd_ctx);
502 if (!target) {
503 LOG_ERROR("BUG: current_target out of bounds");
504 exit(-1);
507 return target;
510 struct target *get_current_target_or_null(struct command_context *cmd_ctx)
512 return cmd_ctx->current_target_override
513 ? cmd_ctx->current_target_override
514 : cmd_ctx->current_target;
517 int target_poll(struct target *target)
519 int retval;
521 /* We can't poll until after examine */
522 if (!target_was_examined(target)) {
523 /* Fail silently lest we pollute the log */
524 return ERROR_FAIL;
527 retval = target->type->poll(target);
528 if (retval != ERROR_OK)
529 return retval;
531 if (target->halt_issued) {
532 if (target->state == TARGET_HALTED)
533 target->halt_issued = false;
534 else {
535 int64_t t = timeval_ms() - target->halt_issued_time;
536 if (t > DEFAULT_HALT_TIMEOUT) {
537 target->halt_issued = false;
538 LOG_INFO("Halt timed out, wake up GDB.");
539 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
544 return ERROR_OK;
547 int target_halt(struct target *target)
549 int retval;
550 /* We can't poll until after examine */
551 if (!target_was_examined(target)) {
552 LOG_ERROR("Target not examined yet");
553 return ERROR_FAIL;
556 retval = target->type->halt(target);
557 if (retval != ERROR_OK)
558 return retval;
560 target->halt_issued = true;
561 target->halt_issued_time = timeval_ms();
563 return ERROR_OK;
567 * Make the target (re)start executing using its saved execution
568 * context (possibly with some modifications).
570 * @param target Which target should start executing.
571 * @param current True to use the target's saved program counter instead
572 * of the address parameter
573 * @param address Optionally used as the program counter.
574 * @param handle_breakpoints True iff breakpoints at the resumption PC
575 * should be skipped. (For example, maybe execution was stopped by
576 * such a breakpoint, in which case it would be counterproductive to
577 * let it re-trigger.
578 * @param debug_execution False if all working areas allocated by OpenOCD
579 * should be released and/or restored to their original contents.
580 * (This would for example be true to run some downloaded "helper"
581 * algorithm code, which resides in one such working buffer and uses
582 * another for data storage.)
584 * @todo Resolve the ambiguity about what the "debug_execution" flag
585 * signifies. For example, Target implementations don't agree on how
586 * it relates to invalidation of the register cache, or to whether
587 * breakpoints and watchpoints should be enabled. (It would seem wrong
588 * to enable breakpoints when running downloaded "helper" algorithms
589 * (debug_execution true), since the breakpoints would be set to match
590 * target firmware being debugged, not the helper algorithm.... and
591 * enabling them could cause such helpers to malfunction (for example,
592 * by overwriting data with a breakpoint instruction. On the other
593 * hand the infrastructure for running such helpers might use this
594 * procedure but rely on hardware breakpoint to detect termination.)
596 int target_resume(struct target *target, int current, target_addr_t address,
597 int handle_breakpoints, int debug_execution)
599 int retval;
601 /* We can't poll until after examine */
602 if (!target_was_examined(target)) {
603 LOG_ERROR("Target not examined yet");
604 return ERROR_FAIL;
607 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
609 /* note that resume *must* be asynchronous. The CPU can halt before
610 * we poll. The CPU can even halt at the current PC as a result of
611 * a software breakpoint being inserted by (a bug?) the application.
614 * resume() triggers the event 'resumed'. The execution of TCL commands
615 * in the event handler causes the polling of targets. If the target has
616 * already halted for a breakpoint, polling will run the 'halted' event
617 * handler before the pending 'resumed' handler.
618 * Disable polling during resume() to guarantee the execution of handlers
619 * in the correct order.
621 bool save_poll_mask = jtag_poll_mask();
622 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
623 jtag_poll_unmask(save_poll_mask);
625 if (retval != ERROR_OK)
626 return retval;
628 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
630 return retval;
633 static int target_process_reset(struct command_invocation *cmd, enum target_reset_mode reset_mode)
635 char buf[100];
636 int retval;
637 const struct nvp *n;
638 n = nvp_value2name(nvp_reset_modes, reset_mode);
639 if (!n->name) {
640 LOG_ERROR("invalid reset mode");
641 return ERROR_FAIL;
644 struct target *target;
645 for (target = all_targets; target; target = target->next)
646 target_call_reset_callbacks(target, reset_mode);
648 /* disable polling during reset to make reset event scripts
649 * more predictable, i.e. dr/irscan & pathmove in events will
650 * not have JTAG operations injected into the middle of a sequence.
652 bool save_poll_mask = jtag_poll_mask();
654 sprintf(buf, "ocd_process_reset %s", n->name);
655 retval = Jim_Eval(cmd->ctx->interp, buf);
657 jtag_poll_unmask(save_poll_mask);
659 if (retval != JIM_OK) {
660 Jim_MakeErrorMessage(cmd->ctx->interp);
661 command_print(cmd, "%s", Jim_GetString(Jim_GetResult(cmd->ctx->interp), NULL));
662 return ERROR_FAIL;
665 /* We want any events to be processed before the prompt */
666 retval = target_call_timer_callbacks_now();
668 for (target = all_targets; target; target = target->next) {
669 target->type->check_reset(target);
670 target->running_alg = false;
673 return retval;
676 static int identity_virt2phys(struct target *target,
677 target_addr_t virtual, target_addr_t *physical)
679 *physical = virtual;
680 return ERROR_OK;
683 static int no_mmu(struct target *target, int *enabled)
685 *enabled = 0;
686 return ERROR_OK;
690 * Reset the @c examined flag for the given target.
691 * Pure paranoia -- targets are zeroed on allocation.
693 static inline void target_reset_examined(struct target *target)
695 target->examined = false;
698 static int default_examine(struct target *target)
700 target_set_examined(target);
701 return ERROR_OK;
704 /* no check by default */
705 static int default_check_reset(struct target *target)
707 return ERROR_OK;
710 /* Equivalent Tcl code arp_examine_one is in src/target/startup.tcl
711 * Keep in sync */
712 int target_examine_one(struct target *target)
714 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
716 int retval = target->type->examine(target);
717 if (retval != ERROR_OK) {
718 target_reset_examined(target);
719 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_FAIL);
720 return retval;
723 target_set_examined(target);
724 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
726 return ERROR_OK;
729 static int jtag_enable_callback(enum jtag_event event, void *priv)
731 struct target *target = priv;
733 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
734 return ERROR_OK;
736 jtag_unregister_event_callback(jtag_enable_callback, target);
738 return target_examine_one(target);
741 /* Targets that correctly implement init + examine, i.e.
742 * no communication with target during init:
744 * XScale
746 int target_examine(void)
748 int retval = ERROR_OK;
749 struct target *target;
751 for (target = all_targets; target; target = target->next) {
752 /* defer examination, but don't skip it */
753 if (!target->tap->enabled) {
754 jtag_register_event_callback(jtag_enable_callback,
755 target);
756 continue;
759 if (target->defer_examine)
760 continue;
762 int retval2 = target_examine_one(target);
763 if (retval2 != ERROR_OK) {
764 LOG_WARNING("target %s examination failed", target_name(target));
765 retval = retval2;
768 return retval;
771 const char *target_type_name(struct target *target)
773 return target->type->name;
776 static int target_soft_reset_halt(struct target *target)
778 if (!target_was_examined(target)) {
779 LOG_ERROR("Target not examined yet");
780 return ERROR_FAIL;
782 if (!target->type->soft_reset_halt) {
783 LOG_ERROR("Target %s does not support soft_reset_halt",
784 target_name(target));
785 return ERROR_FAIL;
787 return target->type->soft_reset_halt(target);
791 * Downloads a target-specific native code algorithm to the target,
792 * and executes it. * Note that some targets may need to set up, enable,
793 * and tear down a breakpoint (hard or * soft) to detect algorithm
794 * termination, while others may support lower overhead schemes where
795 * soft breakpoints embedded in the algorithm automatically terminate the
796 * algorithm.
798 * @param target used to run the algorithm
799 * @param num_mem_params
800 * @param mem_params
801 * @param num_reg_params
802 * @param reg_param
803 * @param entry_point
804 * @param exit_point
805 * @param timeout_ms
806 * @param arch_info target-specific description of the algorithm.
808 int target_run_algorithm(struct target *target,
809 int num_mem_params, struct mem_param *mem_params,
810 int num_reg_params, struct reg_param *reg_param,
811 target_addr_t entry_point, target_addr_t exit_point,
812 unsigned int timeout_ms, void *arch_info)
814 int retval = ERROR_FAIL;
816 if (!target_was_examined(target)) {
817 LOG_ERROR("Target not examined yet");
818 goto done;
820 if (!target->type->run_algorithm) {
821 LOG_ERROR("Target type '%s' does not support %s",
822 target_type_name(target), __func__);
823 goto done;
826 target->running_alg = true;
827 retval = target->type->run_algorithm(target,
828 num_mem_params, mem_params,
829 num_reg_params, reg_param,
830 entry_point, exit_point, timeout_ms, arch_info);
831 target->running_alg = false;
833 done:
834 return retval;
838 * Executes a target-specific native code algorithm and leaves it running.
840 * @param target used to run the algorithm
841 * @param num_mem_params
842 * @param mem_params
843 * @param num_reg_params
844 * @param reg_params
845 * @param entry_point
846 * @param exit_point
847 * @param arch_info target-specific description of the algorithm.
849 int target_start_algorithm(struct target *target,
850 int num_mem_params, struct mem_param *mem_params,
851 int num_reg_params, struct reg_param *reg_params,
852 target_addr_t entry_point, target_addr_t exit_point,
853 void *arch_info)
855 int retval = ERROR_FAIL;
857 if (!target_was_examined(target)) {
858 LOG_ERROR("Target not examined yet");
859 goto done;
861 if (!target->type->start_algorithm) {
862 LOG_ERROR("Target type '%s' does not support %s",
863 target_type_name(target), __func__);
864 goto done;
866 if (target->running_alg) {
867 LOG_ERROR("Target is already running an algorithm");
868 goto done;
871 target->running_alg = true;
872 retval = target->type->start_algorithm(target,
873 num_mem_params, mem_params,
874 num_reg_params, reg_params,
875 entry_point, exit_point, arch_info);
877 done:
878 return retval;
882 * Waits for an algorithm started with target_start_algorithm() to complete.
884 * @param target used to run the algorithm
885 * @param num_mem_params
886 * @param mem_params
887 * @param num_reg_params
888 * @param reg_params
889 * @param exit_point
890 * @param timeout_ms
891 * @param arch_info target-specific description of the algorithm.
893 int target_wait_algorithm(struct target *target,
894 int num_mem_params, struct mem_param *mem_params,
895 int num_reg_params, struct reg_param *reg_params,
896 target_addr_t exit_point, unsigned int timeout_ms,
897 void *arch_info)
899 int retval = ERROR_FAIL;
901 if (!target->type->wait_algorithm) {
902 LOG_ERROR("Target type '%s' does not support %s",
903 target_type_name(target), __func__);
904 goto done;
906 if (!target->running_alg) {
907 LOG_ERROR("Target is not running an algorithm");
908 goto done;
911 retval = target->type->wait_algorithm(target,
912 num_mem_params, mem_params,
913 num_reg_params, reg_params,
914 exit_point, timeout_ms, arch_info);
915 if (retval != ERROR_TARGET_TIMEOUT)
916 target->running_alg = false;
918 done:
919 return retval;
923 * Streams data to a circular buffer on target intended for consumption by code
924 * running asynchronously on target.
926 * This is intended for applications where target-specific native code runs
927 * on the target, receives data from the circular buffer, does something with
928 * it (most likely writing it to a flash memory), and advances the circular
929 * buffer pointer.
931 * This assumes that the helper algorithm has already been loaded to the target,
932 * but has not been started yet. Given memory and register parameters are passed
933 * to the algorithm.
935 * The buffer is defined by (buffer_start, buffer_size) arguments and has the
936 * following format:
938 * [buffer_start + 0, buffer_start + 4):
939 * Write Pointer address (aka head). Written and updated by this
940 * routine when new data is written to the circular buffer.
941 * [buffer_start + 4, buffer_start + 8):
942 * Read Pointer address (aka tail). Updated by code running on the
943 * target after it consumes data.
944 * [buffer_start + 8, buffer_start + buffer_size):
945 * Circular buffer contents.
947 * See contrib/loaders/flash/stm32f1x.S for an example.
949 * @param target used to run the algorithm
950 * @param buffer address on the host where data to be sent is located
951 * @param count number of blocks to send
952 * @param block_size size in bytes of each block
953 * @param num_mem_params count of memory-based params to pass to algorithm
954 * @param mem_params memory-based params to pass to algorithm
955 * @param num_reg_params count of register-based params to pass to algorithm
956 * @param reg_params memory-based params to pass to algorithm
957 * @param buffer_start address on the target of the circular buffer structure
958 * @param buffer_size size of the circular buffer structure
959 * @param entry_point address on the target to execute to start the algorithm
960 * @param exit_point address at which to set a breakpoint to catch the
961 * end of the algorithm; can be 0 if target triggers a breakpoint itself
962 * @param arch_info
965 int target_run_flash_async_algorithm(struct target *target,
966 const uint8_t *buffer, uint32_t count, int block_size,
967 int num_mem_params, struct mem_param *mem_params,
968 int num_reg_params, struct reg_param *reg_params,
969 uint32_t buffer_start, uint32_t buffer_size,
970 uint32_t entry_point, uint32_t exit_point, void *arch_info)
972 int retval;
973 int timeout = 0;
975 const uint8_t *buffer_orig = buffer;
977 /* Set up working area. First word is write pointer, second word is read pointer,
978 * rest is fifo data area. */
979 uint32_t wp_addr = buffer_start;
980 uint32_t rp_addr = buffer_start + 4;
981 uint32_t fifo_start_addr = buffer_start + 8;
982 uint32_t fifo_end_addr = buffer_start + buffer_size;
984 uint32_t wp = fifo_start_addr;
985 uint32_t rp = fifo_start_addr;
987 /* validate block_size is 2^n */
988 assert(IS_PWR_OF_2(block_size));
990 retval = target_write_u32(target, wp_addr, wp);
991 if (retval != ERROR_OK)
992 return retval;
993 retval = target_write_u32(target, rp_addr, rp);
994 if (retval != ERROR_OK)
995 return retval;
997 /* Start up algorithm on target and let it idle while writing the first chunk */
998 retval = target_start_algorithm(target, num_mem_params, mem_params,
999 num_reg_params, reg_params,
1000 entry_point,
1001 exit_point,
1002 arch_info);
1004 if (retval != ERROR_OK) {
1005 LOG_ERROR("error starting target flash write algorithm");
1006 return retval;
1009 while (count > 0) {
1011 retval = target_read_u32(target, rp_addr, &rp);
1012 if (retval != ERROR_OK) {
1013 LOG_ERROR("failed to get read pointer");
1014 break;
1017 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1018 (size_t) (buffer - buffer_orig), count, wp, rp);
1020 if (rp == 0) {
1021 LOG_ERROR("flash write algorithm aborted by target");
1022 retval = ERROR_FLASH_OPERATION_FAILED;
1023 break;
1026 if (!IS_ALIGNED(rp - fifo_start_addr, block_size) || rp < fifo_start_addr || rp >= fifo_end_addr) {
1027 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
1028 break;
1031 /* Count the number of bytes available in the fifo without
1032 * crossing the wrap around. Make sure to not fill it completely,
1033 * because that would make wp == rp and that's the empty condition. */
1034 uint32_t thisrun_bytes;
1035 if (rp > wp)
1036 thisrun_bytes = rp - wp - block_size;
1037 else if (rp > fifo_start_addr)
1038 thisrun_bytes = fifo_end_addr - wp;
1039 else
1040 thisrun_bytes = fifo_end_addr - wp - block_size;
1042 if (thisrun_bytes == 0) {
1043 /* Throttle polling a bit if transfer is (much) faster than flash
1044 * programming. The exact delay shouldn't matter as long as it's
1045 * less than buffer size / flash speed. This is very unlikely to
1046 * run when using high latency connections such as USB. */
1047 alive_sleep(2);
1049 /* to stop an infinite loop on some targets check and increment a timeout
1050 * this issue was observed on a stellaris using the new ICDI interface */
1051 if (timeout++ >= 2500) {
1052 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1053 return ERROR_FLASH_OPERATION_FAILED;
1055 continue;
1058 /* reset our timeout */
1059 timeout = 0;
1061 /* Limit to the amount of data we actually want to write */
1062 if (thisrun_bytes > count * block_size)
1063 thisrun_bytes = count * block_size;
1065 /* Force end of large blocks to be word aligned */
1066 if (thisrun_bytes >= 16)
1067 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1069 /* Write data to fifo */
1070 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
1071 if (retval != ERROR_OK)
1072 break;
1074 /* Update counters and wrap write pointer */
1075 buffer += thisrun_bytes;
1076 count -= thisrun_bytes / block_size;
1077 wp += thisrun_bytes;
1078 if (wp >= fifo_end_addr)
1079 wp = fifo_start_addr;
1081 /* Store updated write pointer to target */
1082 retval = target_write_u32(target, wp_addr, wp);
1083 if (retval != ERROR_OK)
1084 break;
1086 /* Avoid GDB timeouts */
1087 keep_alive();
1090 if (retval != ERROR_OK) {
1091 /* abort flash write algorithm on target */
1092 target_write_u32(target, wp_addr, 0);
1095 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1096 num_reg_params, reg_params,
1097 exit_point,
1098 10000,
1099 arch_info);
1101 if (retval2 != ERROR_OK) {
1102 LOG_ERROR("error waiting for target flash write algorithm");
1103 retval = retval2;
1106 if (retval == ERROR_OK) {
1107 /* check if algorithm set rp = 0 after fifo writer loop finished */
1108 retval = target_read_u32(target, rp_addr, &rp);
1109 if (retval == ERROR_OK && rp == 0) {
1110 LOG_ERROR("flash write algorithm aborted by target");
1111 retval = ERROR_FLASH_OPERATION_FAILED;
1115 return retval;
1118 int target_run_read_async_algorithm(struct target *target,
1119 uint8_t *buffer, uint32_t count, int block_size,
1120 int num_mem_params, struct mem_param *mem_params,
1121 int num_reg_params, struct reg_param *reg_params,
1122 uint32_t buffer_start, uint32_t buffer_size,
1123 uint32_t entry_point, uint32_t exit_point, void *arch_info)
1125 int retval;
1126 int timeout = 0;
1128 const uint8_t *buffer_orig = buffer;
1130 /* Set up working area. First word is write pointer, second word is read pointer,
1131 * rest is fifo data area. */
1132 uint32_t wp_addr = buffer_start;
1133 uint32_t rp_addr = buffer_start + 4;
1134 uint32_t fifo_start_addr = buffer_start + 8;
1135 uint32_t fifo_end_addr = buffer_start + buffer_size;
1137 uint32_t wp = fifo_start_addr;
1138 uint32_t rp = fifo_start_addr;
1140 /* validate block_size is 2^n */
1141 assert(IS_PWR_OF_2(block_size));
1143 retval = target_write_u32(target, wp_addr, wp);
1144 if (retval != ERROR_OK)
1145 return retval;
1146 retval = target_write_u32(target, rp_addr, rp);
1147 if (retval != ERROR_OK)
1148 return retval;
1150 /* Start up algorithm on target */
1151 retval = target_start_algorithm(target, num_mem_params, mem_params,
1152 num_reg_params, reg_params,
1153 entry_point,
1154 exit_point,
1155 arch_info);
1157 if (retval != ERROR_OK) {
1158 LOG_ERROR("error starting target flash read algorithm");
1159 return retval;
1162 while (count > 0) {
1163 retval = target_read_u32(target, wp_addr, &wp);
1164 if (retval != ERROR_OK) {
1165 LOG_ERROR("failed to get write pointer");
1166 break;
1169 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1170 (size_t)(buffer - buffer_orig), count, wp, rp);
1172 if (wp == 0) {
1173 LOG_ERROR("flash read algorithm aborted by target");
1174 retval = ERROR_FLASH_OPERATION_FAILED;
1175 break;
1178 if (!IS_ALIGNED(wp - fifo_start_addr, block_size) || wp < fifo_start_addr || wp >= fifo_end_addr) {
1179 LOG_ERROR("corrupted fifo write pointer 0x%" PRIx32, wp);
1180 break;
1183 /* Count the number of bytes available in the fifo without
1184 * crossing the wrap around. */
1185 uint32_t thisrun_bytes;
1186 if (wp >= rp)
1187 thisrun_bytes = wp - rp;
1188 else
1189 thisrun_bytes = fifo_end_addr - rp;
1191 if (thisrun_bytes == 0) {
1192 /* Throttle polling a bit if transfer is (much) faster than flash
1193 * reading. The exact delay shouldn't matter as long as it's
1194 * less than buffer size / flash speed. This is very unlikely to
1195 * run when using high latency connections such as USB. */
1196 alive_sleep(2);
1198 /* to stop an infinite loop on some targets check and increment a timeout
1199 * this issue was observed on a stellaris using the new ICDI interface */
1200 if (timeout++ >= 2500) {
1201 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1202 return ERROR_FLASH_OPERATION_FAILED;
1204 continue;
1207 /* Reset our timeout */
1208 timeout = 0;
1210 /* Limit to the amount of data we actually want to read */
1211 if (thisrun_bytes > count * block_size)
1212 thisrun_bytes = count * block_size;
1214 /* Force end of large blocks to be word aligned */
1215 if (thisrun_bytes >= 16)
1216 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1218 /* Read data from fifo */
1219 retval = target_read_buffer(target, rp, thisrun_bytes, buffer);
1220 if (retval != ERROR_OK)
1221 break;
1223 /* Update counters and wrap write pointer */
1224 buffer += thisrun_bytes;
1225 count -= thisrun_bytes / block_size;
1226 rp += thisrun_bytes;
1227 if (rp >= fifo_end_addr)
1228 rp = fifo_start_addr;
1230 /* Store updated write pointer to target */
1231 retval = target_write_u32(target, rp_addr, rp);
1232 if (retval != ERROR_OK)
1233 break;
1235 /* Avoid GDB timeouts */
1236 keep_alive();
1240 if (retval != ERROR_OK) {
1241 /* abort flash write algorithm on target */
1242 target_write_u32(target, rp_addr, 0);
1245 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1246 num_reg_params, reg_params,
1247 exit_point,
1248 10000,
1249 arch_info);
1251 if (retval2 != ERROR_OK) {
1252 LOG_ERROR("error waiting for target flash write algorithm");
1253 retval = retval2;
1256 if (retval == ERROR_OK) {
1257 /* check if algorithm set wp = 0 after fifo writer loop finished */
1258 retval = target_read_u32(target, wp_addr, &wp);
1259 if (retval == ERROR_OK && wp == 0) {
1260 LOG_ERROR("flash read algorithm aborted by target");
1261 retval = ERROR_FLASH_OPERATION_FAILED;
1265 return retval;
1268 int target_read_memory(struct target *target,
1269 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1271 if (!target_was_examined(target)) {
1272 LOG_ERROR("Target not examined yet");
1273 return ERROR_FAIL;
1275 if (!target->type->read_memory) {
1276 LOG_ERROR("Target %s doesn't support read_memory", target_name(target));
1277 return ERROR_FAIL;
1279 return target->type->read_memory(target, address, size, count, buffer);
1282 int target_read_phys_memory(struct target *target,
1283 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1285 if (!target_was_examined(target)) {
1286 LOG_ERROR("Target not examined yet");
1287 return ERROR_FAIL;
1289 if (!target->type->read_phys_memory) {
1290 LOG_ERROR("Target %s doesn't support read_phys_memory", target_name(target));
1291 return ERROR_FAIL;
1293 return target->type->read_phys_memory(target, address, size, count, buffer);
1296 int target_write_memory(struct target *target,
1297 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1299 if (!target_was_examined(target)) {
1300 LOG_ERROR("Target not examined yet");
1301 return ERROR_FAIL;
1303 if (!target->type->write_memory) {
1304 LOG_ERROR("Target %s doesn't support write_memory", target_name(target));
1305 return ERROR_FAIL;
1307 return target->type->write_memory(target, address, size, count, buffer);
1310 int target_write_phys_memory(struct target *target,
1311 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1313 if (!target_was_examined(target)) {
1314 LOG_ERROR("Target not examined yet");
1315 return ERROR_FAIL;
1317 if (!target->type->write_phys_memory) {
1318 LOG_ERROR("Target %s doesn't support write_phys_memory", target_name(target));
1319 return ERROR_FAIL;
1321 return target->type->write_phys_memory(target, address, size, count, buffer);
1324 int target_add_breakpoint(struct target *target,
1325 struct breakpoint *breakpoint)
1327 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1328 LOG_TARGET_ERROR(target, "not halted (add breakpoint)");
1329 return ERROR_TARGET_NOT_HALTED;
1331 return target->type->add_breakpoint(target, breakpoint);
1334 int target_add_context_breakpoint(struct target *target,
1335 struct breakpoint *breakpoint)
1337 if (target->state != TARGET_HALTED) {
1338 LOG_TARGET_ERROR(target, "not halted (add context breakpoint)");
1339 return ERROR_TARGET_NOT_HALTED;
1341 return target->type->add_context_breakpoint(target, breakpoint);
1344 int target_add_hybrid_breakpoint(struct target *target,
1345 struct breakpoint *breakpoint)
1347 if (target->state != TARGET_HALTED) {
1348 LOG_TARGET_ERROR(target, "not halted (add hybrid breakpoint)");
1349 return ERROR_TARGET_NOT_HALTED;
1351 return target->type->add_hybrid_breakpoint(target, breakpoint);
1354 int target_remove_breakpoint(struct target *target,
1355 struct breakpoint *breakpoint)
1357 return target->type->remove_breakpoint(target, breakpoint);
1360 int target_add_watchpoint(struct target *target,
1361 struct watchpoint *watchpoint)
1363 if (target->state != TARGET_HALTED) {
1364 LOG_TARGET_ERROR(target, "not halted (add watchpoint)");
1365 return ERROR_TARGET_NOT_HALTED;
1367 return target->type->add_watchpoint(target, watchpoint);
1369 int target_remove_watchpoint(struct target *target,
1370 struct watchpoint *watchpoint)
1372 return target->type->remove_watchpoint(target, watchpoint);
1374 int target_hit_watchpoint(struct target *target,
1375 struct watchpoint **hit_watchpoint)
1377 if (target->state != TARGET_HALTED) {
1378 LOG_TARGET_ERROR(target, "not halted (hit watchpoint)");
1379 return ERROR_TARGET_NOT_HALTED;
1382 if (!target->type->hit_watchpoint) {
1383 /* For backward compatible, if hit_watchpoint is not implemented,
1384 * return ERROR_FAIL such that gdb_server will not take the nonsense
1385 * information. */
1386 return ERROR_FAIL;
1389 return target->type->hit_watchpoint(target, hit_watchpoint);
1392 const char *target_get_gdb_arch(struct target *target)
1394 if (!target->type->get_gdb_arch)
1395 return NULL;
1396 return target->type->get_gdb_arch(target);
1399 int target_get_gdb_reg_list(struct target *target,
1400 struct reg **reg_list[], int *reg_list_size,
1401 enum target_register_class reg_class)
1403 int result = ERROR_FAIL;
1405 if (!target_was_examined(target)) {
1406 LOG_ERROR("Target not examined yet");
1407 goto done;
1410 result = target->type->get_gdb_reg_list(target, reg_list,
1411 reg_list_size, reg_class);
1413 done:
1414 if (result != ERROR_OK) {
1415 *reg_list = NULL;
1416 *reg_list_size = 0;
1418 return result;
1421 int target_get_gdb_reg_list_noread(struct target *target,
1422 struct reg **reg_list[], int *reg_list_size,
1423 enum target_register_class reg_class)
1425 if (target->type->get_gdb_reg_list_noread &&
1426 target->type->get_gdb_reg_list_noread(target, reg_list,
1427 reg_list_size, reg_class) == ERROR_OK)
1428 return ERROR_OK;
1429 return target_get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1432 bool target_supports_gdb_connection(struct target *target)
1435 * exclude all the targets that don't provide get_gdb_reg_list
1436 * or that have explicit gdb_max_connection == 0
1438 return !!target->type->get_gdb_reg_list && !!target->gdb_max_connections;
1441 int target_step(struct target *target,
1442 int current, target_addr_t address, int handle_breakpoints)
1444 int retval;
1446 target_call_event_callbacks(target, TARGET_EVENT_STEP_START);
1448 retval = target->type->step(target, current, address, handle_breakpoints);
1449 if (retval != ERROR_OK)
1450 return retval;
1452 target_call_event_callbacks(target, TARGET_EVENT_STEP_END);
1454 return retval;
1457 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1459 if (target->state != TARGET_HALTED) {
1460 LOG_TARGET_ERROR(target, "not halted (gdb fileio)");
1461 return ERROR_TARGET_NOT_HALTED;
1463 return target->type->get_gdb_fileio_info(target, fileio_info);
1466 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1468 if (target->state != TARGET_HALTED) {
1469 LOG_TARGET_ERROR(target, "not halted (gdb fileio end)");
1470 return ERROR_TARGET_NOT_HALTED;
1472 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1475 target_addr_t target_address_max(struct target *target)
1477 unsigned bits = target_address_bits(target);
1478 if (sizeof(target_addr_t) * 8 == bits)
1479 return (target_addr_t) -1;
1480 else
1481 return (((target_addr_t) 1) << bits) - 1;
1484 unsigned target_address_bits(struct target *target)
1486 if (target->type->address_bits)
1487 return target->type->address_bits(target);
1488 return 32;
1491 unsigned int target_data_bits(struct target *target)
1493 if (target->type->data_bits)
1494 return target->type->data_bits(target);
1495 return 32;
1498 static int target_profiling(struct target *target, uint32_t *samples,
1499 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1501 return target->type->profiling(target, samples, max_num_samples,
1502 num_samples, seconds);
1505 static int handle_target(void *priv);
1507 static int target_init_one(struct command_context *cmd_ctx,
1508 struct target *target)
1510 target_reset_examined(target);
1512 struct target_type *type = target->type;
1513 if (!type->examine)
1514 type->examine = default_examine;
1516 if (!type->check_reset)
1517 type->check_reset = default_check_reset;
1519 assert(type->init_target);
1521 int retval = type->init_target(cmd_ctx, target);
1522 if (retval != ERROR_OK) {
1523 LOG_ERROR("target '%s' init failed", target_name(target));
1524 return retval;
1527 /* Sanity-check MMU support ... stub in what we must, to help
1528 * implement it in stages, but warn if we need to do so.
1530 if (type->mmu) {
1531 if (!type->virt2phys) {
1532 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1533 type->virt2phys = identity_virt2phys;
1535 } else {
1536 /* Make sure no-MMU targets all behave the same: make no
1537 * distinction between physical and virtual addresses, and
1538 * ensure that virt2phys() is always an identity mapping.
1540 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1541 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1543 type->mmu = no_mmu;
1544 type->write_phys_memory = type->write_memory;
1545 type->read_phys_memory = type->read_memory;
1546 type->virt2phys = identity_virt2phys;
1549 if (!target->type->read_buffer)
1550 target->type->read_buffer = target_read_buffer_default;
1552 if (!target->type->write_buffer)
1553 target->type->write_buffer = target_write_buffer_default;
1555 if (!target->type->get_gdb_fileio_info)
1556 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1558 if (!target->type->gdb_fileio_end)
1559 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1561 if (!target->type->profiling)
1562 target->type->profiling = target_profiling_default;
1564 return ERROR_OK;
1567 static int target_init(struct command_context *cmd_ctx)
1569 struct target *target;
1570 int retval;
1572 for (target = all_targets; target; target = target->next) {
1573 retval = target_init_one(cmd_ctx, target);
1574 if (retval != ERROR_OK)
1575 return retval;
1578 if (!all_targets)
1579 return ERROR_OK;
1581 retval = target_register_user_commands(cmd_ctx);
1582 if (retval != ERROR_OK)
1583 return retval;
1585 retval = target_register_timer_callback(&handle_target,
1586 polling_interval, TARGET_TIMER_TYPE_PERIODIC, cmd_ctx->interp);
1587 if (retval != ERROR_OK)
1588 return retval;
1590 return ERROR_OK;
1593 COMMAND_HANDLER(handle_target_init_command)
1595 int retval;
1597 if (CMD_ARGC != 0)
1598 return ERROR_COMMAND_SYNTAX_ERROR;
1600 static bool target_initialized;
1601 if (target_initialized) {
1602 LOG_INFO("'target init' has already been called");
1603 return ERROR_OK;
1605 target_initialized = true;
1607 retval = command_run_line(CMD_CTX, "init_targets");
1608 if (retval != ERROR_OK)
1609 return retval;
1611 retval = command_run_line(CMD_CTX, "init_target_events");
1612 if (retval != ERROR_OK)
1613 return retval;
1615 retval = command_run_line(CMD_CTX, "init_board");
1616 if (retval != ERROR_OK)
1617 return retval;
1619 LOG_DEBUG("Initializing targets...");
1620 return target_init(CMD_CTX);
1623 int target_register_event_callback(int (*callback)(struct target *target,
1624 enum target_event event, void *priv), void *priv)
1626 struct target_event_callback **callbacks_p = &target_event_callbacks;
1628 if (!callback)
1629 return ERROR_COMMAND_SYNTAX_ERROR;
1631 if (*callbacks_p) {
1632 while ((*callbacks_p)->next)
1633 callbacks_p = &((*callbacks_p)->next);
1634 callbacks_p = &((*callbacks_p)->next);
1637 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1638 (*callbacks_p)->callback = callback;
1639 (*callbacks_p)->priv = priv;
1640 (*callbacks_p)->next = NULL;
1642 return ERROR_OK;
1645 int target_register_reset_callback(int (*callback)(struct target *target,
1646 enum target_reset_mode reset_mode, void *priv), void *priv)
1648 struct target_reset_callback *entry;
1650 if (!callback)
1651 return ERROR_COMMAND_SYNTAX_ERROR;
1653 entry = malloc(sizeof(struct target_reset_callback));
1654 if (!entry) {
1655 LOG_ERROR("error allocating buffer for reset callback entry");
1656 return ERROR_COMMAND_SYNTAX_ERROR;
1659 entry->callback = callback;
1660 entry->priv = priv;
1661 list_add(&entry->list, &target_reset_callback_list);
1664 return ERROR_OK;
1667 int target_register_trace_callback(int (*callback)(struct target *target,
1668 size_t len, uint8_t *data, void *priv), void *priv)
1670 struct target_trace_callback *entry;
1672 if (!callback)
1673 return ERROR_COMMAND_SYNTAX_ERROR;
1675 entry = malloc(sizeof(struct target_trace_callback));
1676 if (!entry) {
1677 LOG_ERROR("error allocating buffer for trace callback entry");
1678 return ERROR_COMMAND_SYNTAX_ERROR;
1681 entry->callback = callback;
1682 entry->priv = priv;
1683 list_add(&entry->list, &target_trace_callback_list);
1686 return ERROR_OK;
1689 int target_register_timer_callback(int (*callback)(void *priv),
1690 unsigned int time_ms, enum target_timer_type type, void *priv)
1692 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1694 if (!callback)
1695 return ERROR_COMMAND_SYNTAX_ERROR;
1697 if (*callbacks_p) {
1698 while ((*callbacks_p)->next)
1699 callbacks_p = &((*callbacks_p)->next);
1700 callbacks_p = &((*callbacks_p)->next);
1703 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1704 (*callbacks_p)->callback = callback;
1705 (*callbacks_p)->type = type;
1706 (*callbacks_p)->time_ms = time_ms;
1707 (*callbacks_p)->removed = false;
1709 (*callbacks_p)->when = timeval_ms() + time_ms;
1710 target_timer_next_event_value = MIN(target_timer_next_event_value, (*callbacks_p)->when);
1712 (*callbacks_p)->priv = priv;
1713 (*callbacks_p)->next = NULL;
1715 return ERROR_OK;
1718 int target_unregister_event_callback(int (*callback)(struct target *target,
1719 enum target_event event, void *priv), void *priv)
1721 struct target_event_callback **p = &target_event_callbacks;
1722 struct target_event_callback *c = target_event_callbacks;
1724 if (!callback)
1725 return ERROR_COMMAND_SYNTAX_ERROR;
1727 while (c) {
1728 struct target_event_callback *next = c->next;
1729 if ((c->callback == callback) && (c->priv == priv)) {
1730 *p = next;
1731 free(c);
1732 return ERROR_OK;
1733 } else
1734 p = &(c->next);
1735 c = next;
1738 return ERROR_OK;
1741 int target_unregister_reset_callback(int (*callback)(struct target *target,
1742 enum target_reset_mode reset_mode, void *priv), void *priv)
1744 struct target_reset_callback *entry;
1746 if (!callback)
1747 return ERROR_COMMAND_SYNTAX_ERROR;
1749 list_for_each_entry(entry, &target_reset_callback_list, list) {
1750 if (entry->callback == callback && entry->priv == priv) {
1751 list_del(&entry->list);
1752 free(entry);
1753 break;
1757 return ERROR_OK;
1760 int target_unregister_trace_callback(int (*callback)(struct target *target,
1761 size_t len, uint8_t *data, void *priv), void *priv)
1763 struct target_trace_callback *entry;
1765 if (!callback)
1766 return ERROR_COMMAND_SYNTAX_ERROR;
1768 list_for_each_entry(entry, &target_trace_callback_list, list) {
1769 if (entry->callback == callback && entry->priv == priv) {
1770 list_del(&entry->list);
1771 free(entry);
1772 break;
1776 return ERROR_OK;
1779 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1781 if (!callback)
1782 return ERROR_COMMAND_SYNTAX_ERROR;
1784 for (struct target_timer_callback *c = target_timer_callbacks;
1785 c; c = c->next) {
1786 if ((c->callback == callback) && (c->priv == priv)) {
1787 c->removed = true;
1788 return ERROR_OK;
1792 return ERROR_FAIL;
1795 int target_call_event_callbacks(struct target *target, enum target_event event)
1797 struct target_event_callback *callback = target_event_callbacks;
1798 struct target_event_callback *next_callback;
1800 if (event == TARGET_EVENT_HALTED) {
1801 /* execute early halted first */
1802 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1805 LOG_DEBUG("target event %i (%s) for core %s", event,
1806 target_event_name(event),
1807 target_name(target));
1809 target_handle_event(target, event);
1811 while (callback) {
1812 next_callback = callback->next;
1813 callback->callback(target, event, callback->priv);
1814 callback = next_callback;
1817 return ERROR_OK;
1820 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1822 struct target_reset_callback *callback;
1824 LOG_DEBUG("target reset %i (%s)", reset_mode,
1825 nvp_value2name(nvp_reset_modes, reset_mode)->name);
1827 list_for_each_entry(callback, &target_reset_callback_list, list)
1828 callback->callback(target, reset_mode, callback->priv);
1830 return ERROR_OK;
1833 int target_call_trace_callbacks(struct target *target, size_t len, uint8_t *data)
1835 struct target_trace_callback *callback;
1837 list_for_each_entry(callback, &target_trace_callback_list, list)
1838 callback->callback(target, len, data, callback->priv);
1840 return ERROR_OK;
1843 static int target_timer_callback_periodic_restart(
1844 struct target_timer_callback *cb, int64_t *now)
1846 cb->when = *now + cb->time_ms;
1847 return ERROR_OK;
1850 static int target_call_timer_callback(struct target_timer_callback *cb,
1851 int64_t *now)
1853 cb->callback(cb->priv);
1855 if (cb->type == TARGET_TIMER_TYPE_PERIODIC)
1856 return target_timer_callback_periodic_restart(cb, now);
1858 return target_unregister_timer_callback(cb->callback, cb->priv);
1861 static int target_call_timer_callbacks_check_time(int checktime)
1863 static bool callback_processing;
1865 /* Do not allow nesting */
1866 if (callback_processing)
1867 return ERROR_OK;
1869 callback_processing = true;
1871 keep_alive();
1873 int64_t now = timeval_ms();
1875 /* Initialize to a default value that's a ways into the future.
1876 * The loop below will make it closer to now if there are
1877 * callbacks that want to be called sooner. */
1878 target_timer_next_event_value = now + 1000;
1880 /* Store an address of the place containing a pointer to the
1881 * next item; initially, that's a standalone "root of the
1882 * list" variable. */
1883 struct target_timer_callback **callback = &target_timer_callbacks;
1884 while (callback && *callback) {
1885 if ((*callback)->removed) {
1886 struct target_timer_callback *p = *callback;
1887 *callback = (*callback)->next;
1888 free(p);
1889 continue;
1892 bool call_it = (*callback)->callback &&
1893 ((!checktime && (*callback)->type == TARGET_TIMER_TYPE_PERIODIC) ||
1894 now >= (*callback)->when);
1896 if (call_it)
1897 target_call_timer_callback(*callback, &now);
1899 if (!(*callback)->removed && (*callback)->when < target_timer_next_event_value)
1900 target_timer_next_event_value = (*callback)->when;
1902 callback = &(*callback)->next;
1905 callback_processing = false;
1906 return ERROR_OK;
1909 int target_call_timer_callbacks(void)
1911 return target_call_timer_callbacks_check_time(1);
1914 /* invoke periodic callbacks immediately */
1915 int target_call_timer_callbacks_now(void)
1917 return target_call_timer_callbacks_check_time(0);
1920 int64_t target_timer_next_event(void)
1922 return target_timer_next_event_value;
1925 /* Prints the working area layout for debug purposes */
1926 static void print_wa_layout(struct target *target)
1928 struct working_area *c = target->working_areas;
1930 while (c) {
1931 LOG_DEBUG("%c%c " TARGET_ADDR_FMT "-" TARGET_ADDR_FMT " (%" PRIu32 " bytes)",
1932 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1933 c->address, c->address + c->size - 1, c->size);
1934 c = c->next;
1938 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1939 static void target_split_working_area(struct working_area *area, uint32_t size)
1941 assert(area->free); /* Shouldn't split an allocated area */
1942 assert(size <= area->size); /* Caller should guarantee this */
1944 /* Split only if not already the right size */
1945 if (size < area->size) {
1946 struct working_area *new_wa = malloc(sizeof(*new_wa));
1948 if (!new_wa)
1949 return;
1951 new_wa->next = area->next;
1952 new_wa->size = area->size - size;
1953 new_wa->address = area->address + size;
1954 new_wa->backup = NULL;
1955 new_wa->user = NULL;
1956 new_wa->free = true;
1958 area->next = new_wa;
1959 area->size = size;
1961 /* If backup memory was allocated to this area, it has the wrong size
1962 * now so free it and it will be reallocated if/when needed */
1963 free(area->backup);
1964 area->backup = NULL;
1968 /* Merge all adjacent free areas into one */
1969 static void target_merge_working_areas(struct target *target)
1971 struct working_area *c = target->working_areas;
1973 while (c && c->next) {
1974 assert(c->next->address == c->address + c->size); /* This is an invariant */
1976 /* Find two adjacent free areas */
1977 if (c->free && c->next->free) {
1978 /* Merge the last into the first */
1979 c->size += c->next->size;
1981 /* Remove the last */
1982 struct working_area *to_be_freed = c->next;
1983 c->next = c->next->next;
1984 free(to_be_freed->backup);
1985 free(to_be_freed);
1987 /* If backup memory was allocated to the remaining area, it's has
1988 * the wrong size now */
1989 free(c->backup);
1990 c->backup = NULL;
1991 } else {
1992 c = c->next;
1997 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1999 /* Reevaluate working area address based on MMU state*/
2000 if (!target->working_areas) {
2001 int retval;
2002 int enabled;
2004 retval = target->type->mmu(target, &enabled);
2005 if (retval != ERROR_OK)
2006 return retval;
2008 if (!enabled) {
2009 if (target->working_area_phys_spec) {
2010 LOG_DEBUG("MMU disabled, using physical "
2011 "address for working memory " TARGET_ADDR_FMT,
2012 target->working_area_phys);
2013 target->working_area = target->working_area_phys;
2014 } else {
2015 LOG_ERROR("No working memory available. "
2016 "Specify -work-area-phys to target.");
2017 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2019 } else {
2020 if (target->working_area_virt_spec) {
2021 LOG_DEBUG("MMU enabled, using virtual "
2022 "address for working memory " TARGET_ADDR_FMT,
2023 target->working_area_virt);
2024 target->working_area = target->working_area_virt;
2025 } else {
2026 LOG_ERROR("No working memory available. "
2027 "Specify -work-area-virt to target.");
2028 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2032 /* Set up initial working area on first call */
2033 struct working_area *new_wa = malloc(sizeof(*new_wa));
2034 if (new_wa) {
2035 new_wa->next = NULL;
2036 new_wa->size = ALIGN_DOWN(target->working_area_size, 4); /* 4-byte align */
2037 new_wa->address = target->working_area;
2038 new_wa->backup = NULL;
2039 new_wa->user = NULL;
2040 new_wa->free = true;
2043 target->working_areas = new_wa;
2046 /* only allocate multiples of 4 byte */
2047 size = ALIGN_UP(size, 4);
2049 struct working_area *c = target->working_areas;
2051 /* Find the first large enough working area */
2052 while (c) {
2053 if (c->free && c->size >= size)
2054 break;
2055 c = c->next;
2058 if (!c)
2059 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2061 /* Split the working area into the requested size */
2062 target_split_working_area(c, size);
2064 LOG_DEBUG("allocated new working area of %" PRIu32 " bytes at address " TARGET_ADDR_FMT,
2065 size, c->address);
2067 if (target->backup_working_area) {
2068 if (!c->backup) {
2069 c->backup = malloc(c->size);
2070 if (!c->backup)
2071 return ERROR_FAIL;
2074 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
2075 if (retval != ERROR_OK)
2076 return retval;
2079 /* mark as used, and return the new (reused) area */
2080 c->free = false;
2081 *area = c;
2083 /* user pointer */
2084 c->user = area;
2086 print_wa_layout(target);
2088 return ERROR_OK;
2091 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
2093 int retval;
2095 retval = target_alloc_working_area_try(target, size, area);
2096 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
2097 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
2098 return retval;
2102 static int target_restore_working_area(struct target *target, struct working_area *area)
2104 int retval = ERROR_OK;
2106 if (target->backup_working_area && area->backup) {
2107 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
2108 if (retval != ERROR_OK)
2109 LOG_ERROR("failed to restore %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2110 area->size, area->address);
2113 return retval;
2116 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
2117 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
2119 if (!area || area->free)
2120 return ERROR_OK;
2122 int retval = ERROR_OK;
2123 if (restore) {
2124 retval = target_restore_working_area(target, area);
2125 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
2126 if (retval != ERROR_OK)
2127 return retval;
2130 area->free = true;
2132 LOG_DEBUG("freed %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2133 area->size, area->address);
2135 /* mark user pointer invalid */
2136 /* TODO: Is this really safe? It points to some previous caller's memory.
2137 * How could we know that the area pointer is still in that place and not
2138 * some other vital data? What's the purpose of this, anyway? */
2139 *area->user = NULL;
2140 area->user = NULL;
2142 target_merge_working_areas(target);
2144 print_wa_layout(target);
2146 return retval;
2149 int target_free_working_area(struct target *target, struct working_area *area)
2151 return target_free_working_area_restore(target, area, 1);
2154 /* free resources and restore memory, if restoring memory fails,
2155 * free up resources anyway
2157 static void target_free_all_working_areas_restore(struct target *target, int restore)
2159 struct working_area *c = target->working_areas;
2161 LOG_DEBUG("freeing all working areas");
2163 /* Loop through all areas, restoring the allocated ones and marking them as free */
2164 while (c) {
2165 if (!c->free) {
2166 if (restore)
2167 target_restore_working_area(target, c);
2168 c->free = true;
2169 *c->user = NULL; /* Same as above */
2170 c->user = NULL;
2172 c = c->next;
2175 /* Run a merge pass to combine all areas into one */
2176 target_merge_working_areas(target);
2178 print_wa_layout(target);
2181 void target_free_all_working_areas(struct target *target)
2183 target_free_all_working_areas_restore(target, 1);
2185 /* Now we have none or only one working area marked as free */
2186 if (target->working_areas) {
2187 /* Free the last one to allow on-the-fly moving and resizing */
2188 free(target->working_areas->backup);
2189 free(target->working_areas);
2190 target->working_areas = NULL;
2194 /* Find the largest number of bytes that can be allocated */
2195 uint32_t target_get_working_area_avail(struct target *target)
2197 struct working_area *c = target->working_areas;
2198 uint32_t max_size = 0;
2200 if (!c)
2201 return ALIGN_DOWN(target->working_area_size, 4);
2203 while (c) {
2204 if (c->free && max_size < c->size)
2205 max_size = c->size;
2207 c = c->next;
2210 return max_size;
2213 static void target_destroy(struct target *target)
2215 if (target->type->deinit_target)
2216 target->type->deinit_target(target);
2218 if (target->semihosting)
2219 free(target->semihosting->basedir);
2220 free(target->semihosting);
2222 jtag_unregister_event_callback(jtag_enable_callback, target);
2224 struct target_event_action *teap = target->event_action;
2225 while (teap) {
2226 struct target_event_action *next = teap->next;
2227 Jim_DecrRefCount(teap->interp, teap->body);
2228 free(teap);
2229 teap = next;
2232 target_free_all_working_areas(target);
2234 /* release the targets SMP list */
2235 if (target->smp) {
2236 struct target_list *head, *tmp;
2238 list_for_each_entry_safe(head, tmp, target->smp_targets, lh) {
2239 list_del(&head->lh);
2240 head->target->smp = 0;
2241 free(head);
2243 if (target->smp_targets != &empty_smp_targets)
2244 free(target->smp_targets);
2245 target->smp = 0;
2248 rtos_destroy(target);
2250 free(target->gdb_port_override);
2251 free(target->type);
2252 free(target->trace_info);
2253 free(target->fileio_info);
2254 free(target->cmd_name);
2255 free(target);
2258 void target_quit(void)
2260 struct target_event_callback *pe = target_event_callbacks;
2261 while (pe) {
2262 struct target_event_callback *t = pe->next;
2263 free(pe);
2264 pe = t;
2266 target_event_callbacks = NULL;
2268 struct target_timer_callback *pt = target_timer_callbacks;
2269 while (pt) {
2270 struct target_timer_callback *t = pt->next;
2271 free(pt);
2272 pt = t;
2274 target_timer_callbacks = NULL;
2276 for (struct target *target = all_targets; target;) {
2277 struct target *tmp;
2279 tmp = target->next;
2280 target_destroy(target);
2281 target = tmp;
2284 all_targets = NULL;
2287 int target_arch_state(struct target *target)
2289 int retval;
2290 if (!target) {
2291 LOG_WARNING("No target has been configured");
2292 return ERROR_OK;
2295 if (target->state != TARGET_HALTED)
2296 return ERROR_OK;
2298 retval = target->type->arch_state(target);
2299 return retval;
2302 static int target_get_gdb_fileio_info_default(struct target *target,
2303 struct gdb_fileio_info *fileio_info)
2305 /* If target does not support semi-hosting function, target
2306 has no need to provide .get_gdb_fileio_info callback.
2307 It just return ERROR_FAIL and gdb_server will return "Txx"
2308 as target halted every time. */
2309 return ERROR_FAIL;
2312 static int target_gdb_fileio_end_default(struct target *target,
2313 int retcode, int fileio_errno, bool ctrl_c)
2315 return ERROR_OK;
2318 int target_profiling_default(struct target *target, uint32_t *samples,
2319 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
2321 struct timeval timeout, now;
2323 gettimeofday(&timeout, NULL);
2324 timeval_add_time(&timeout, seconds, 0);
2326 LOG_INFO("Starting profiling. Halting and resuming the"
2327 " target as often as we can...");
2329 uint32_t sample_count = 0;
2330 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2331 struct reg *reg = register_get_by_name(target->reg_cache, "pc", true);
2333 int retval = ERROR_OK;
2334 for (;;) {
2335 target_poll(target);
2336 if (target->state == TARGET_HALTED) {
2337 uint32_t t = buf_get_u32(reg->value, 0, 32);
2338 samples[sample_count++] = t;
2339 /* current pc, addr = 0, do not handle breakpoints, not debugging */
2340 retval = target_resume(target, 1, 0, 0, 0);
2341 target_poll(target);
2342 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2343 } else if (target->state == TARGET_RUNNING) {
2344 /* We want to quickly sample the PC. */
2345 retval = target_halt(target);
2346 } else {
2347 LOG_INFO("Target not halted or running");
2348 retval = ERROR_OK;
2349 break;
2352 if (retval != ERROR_OK)
2353 break;
2355 gettimeofday(&now, NULL);
2356 if ((sample_count >= max_num_samples) || timeval_compare(&now, &timeout) >= 0) {
2357 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2358 break;
2362 *num_samples = sample_count;
2363 return retval;
2366 /* Single aligned words are guaranteed to use 16 or 32 bit access
2367 * mode respectively, otherwise data is handled as quickly as
2368 * possible
2370 int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
2372 LOG_DEBUG("writing buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2373 size, address);
2375 if (!target_was_examined(target)) {
2376 LOG_ERROR("Target not examined yet");
2377 return ERROR_FAIL;
2380 if (size == 0)
2381 return ERROR_OK;
2383 if ((address + size - 1) < address) {
2384 /* GDB can request this when e.g. PC is 0xfffffffc */
2385 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2386 address,
2387 size);
2388 return ERROR_FAIL;
2391 return target->type->write_buffer(target, address, size, buffer);
2394 static int target_write_buffer_default(struct target *target,
2395 target_addr_t address, uint32_t count, const uint8_t *buffer)
2397 uint32_t size;
2398 unsigned int data_bytes = target_data_bits(target) / 8;
2400 /* Align up to maximum bytes. The loop condition makes sure the next pass
2401 * will have something to do with the size we leave to it. */
2402 for (size = 1;
2403 size < data_bytes && count >= size * 2 + (address & size);
2404 size *= 2) {
2405 if (address & size) {
2406 int retval = target_write_memory(target, address, size, 1, buffer);
2407 if (retval != ERROR_OK)
2408 return retval;
2409 address += size;
2410 count -= size;
2411 buffer += size;
2415 /* Write the data with as large access size as possible. */
2416 for (; size > 0; size /= 2) {
2417 uint32_t aligned = count - count % size;
2418 if (aligned > 0) {
2419 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2420 if (retval != ERROR_OK)
2421 return retval;
2422 address += aligned;
2423 count -= aligned;
2424 buffer += aligned;
2428 return ERROR_OK;
2431 /* Single aligned words are guaranteed to use 16 or 32 bit access
2432 * mode respectively, otherwise data is handled as quickly as
2433 * possible
2435 int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
2437 LOG_DEBUG("reading buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2438 size, address);
2440 if (!target_was_examined(target)) {
2441 LOG_ERROR("Target not examined yet");
2442 return ERROR_FAIL;
2445 if (size == 0)
2446 return ERROR_OK;
2448 if ((address + size - 1) < address) {
2449 /* GDB can request this when e.g. PC is 0xfffffffc */
2450 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2451 address,
2452 size);
2453 return ERROR_FAIL;
2456 return target->type->read_buffer(target, address, size, buffer);
2459 static int target_read_buffer_default(struct target *target, target_addr_t address, uint32_t count, uint8_t *buffer)
2461 uint32_t size;
2462 unsigned int data_bytes = target_data_bits(target) / 8;
2464 /* Align up to maximum bytes. The loop condition makes sure the next pass
2465 * will have something to do with the size we leave to it. */
2466 for (size = 1;
2467 size < data_bytes && count >= size * 2 + (address & size);
2468 size *= 2) {
2469 if (address & size) {
2470 int retval = target_read_memory(target, address, size, 1, buffer);
2471 if (retval != ERROR_OK)
2472 return retval;
2473 address += size;
2474 count -= size;
2475 buffer += size;
2479 /* Read the data with as large access size as possible. */
2480 for (; size > 0; size /= 2) {
2481 uint32_t aligned = count - count % size;
2482 if (aligned > 0) {
2483 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2484 if (retval != ERROR_OK)
2485 return retval;
2486 address += aligned;
2487 count -= aligned;
2488 buffer += aligned;
2492 return ERROR_OK;
2495 int target_checksum_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t *crc)
2497 uint8_t *buffer;
2498 int retval;
2499 uint32_t i;
2500 uint32_t checksum = 0;
2501 if (!target_was_examined(target)) {
2502 LOG_ERROR("Target not examined yet");
2503 return ERROR_FAIL;
2505 if (!target->type->checksum_memory) {
2506 LOG_ERROR("Target %s doesn't support checksum_memory", target_name(target));
2507 return ERROR_FAIL;
2510 retval = target->type->checksum_memory(target, address, size, &checksum);
2511 if (retval != ERROR_OK) {
2512 buffer = malloc(size);
2513 if (!buffer) {
2514 LOG_ERROR("error allocating buffer for section (%" PRIu32 " bytes)", size);
2515 return ERROR_COMMAND_SYNTAX_ERROR;
2517 retval = target_read_buffer(target, address, size, buffer);
2518 if (retval != ERROR_OK) {
2519 free(buffer);
2520 return retval;
2523 /* convert to target endianness */
2524 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2525 uint32_t target_data;
2526 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2527 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2530 retval = image_calculate_checksum(buffer, size, &checksum);
2531 free(buffer);
2534 *crc = checksum;
2536 return retval;
2539 int target_blank_check_memory(struct target *target,
2540 struct target_memory_check_block *blocks, int num_blocks,
2541 uint8_t erased_value)
2543 if (!target_was_examined(target)) {
2544 LOG_ERROR("Target not examined yet");
2545 return ERROR_FAIL;
2548 if (!target->type->blank_check_memory)
2549 return ERROR_NOT_IMPLEMENTED;
2551 return target->type->blank_check_memory(target, blocks, num_blocks, erased_value);
2554 int target_read_u64(struct target *target, target_addr_t address, uint64_t *value)
2556 uint8_t value_buf[8];
2557 if (!target_was_examined(target)) {
2558 LOG_ERROR("Target not examined yet");
2559 return ERROR_FAIL;
2562 int retval = target_read_memory(target, address, 8, 1, value_buf);
2564 if (retval == ERROR_OK) {
2565 *value = target_buffer_get_u64(target, value_buf);
2566 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2567 address,
2568 *value);
2569 } else {
2570 *value = 0x0;
2571 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2572 address);
2575 return retval;
2578 int target_read_u32(struct target *target, target_addr_t address, uint32_t *value)
2580 uint8_t value_buf[4];
2581 if (!target_was_examined(target)) {
2582 LOG_ERROR("Target not examined yet");
2583 return ERROR_FAIL;
2586 int retval = target_read_memory(target, address, 4, 1, value_buf);
2588 if (retval == ERROR_OK) {
2589 *value = target_buffer_get_u32(target, value_buf);
2590 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2591 address,
2592 *value);
2593 } else {
2594 *value = 0x0;
2595 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2596 address);
2599 return retval;
2602 int target_read_u16(struct target *target, target_addr_t address, uint16_t *value)
2604 uint8_t value_buf[2];
2605 if (!target_was_examined(target)) {
2606 LOG_ERROR("Target not examined yet");
2607 return ERROR_FAIL;
2610 int retval = target_read_memory(target, address, 2, 1, value_buf);
2612 if (retval == ERROR_OK) {
2613 *value = target_buffer_get_u16(target, value_buf);
2614 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%4.4" PRIx16,
2615 address,
2616 *value);
2617 } else {
2618 *value = 0x0;
2619 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2620 address);
2623 return retval;
2626 int target_read_u8(struct target *target, target_addr_t address, uint8_t *value)
2628 if (!target_was_examined(target)) {
2629 LOG_ERROR("Target not examined yet");
2630 return ERROR_FAIL;
2633 int retval = target_read_memory(target, address, 1, 1, value);
2635 if (retval == ERROR_OK) {
2636 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2637 address,
2638 *value);
2639 } else {
2640 *value = 0x0;
2641 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2642 address);
2645 return retval;
2648 int target_write_u64(struct target *target, target_addr_t address, uint64_t value)
2650 int retval;
2651 uint8_t value_buf[8];
2652 if (!target_was_examined(target)) {
2653 LOG_ERROR("Target not examined yet");
2654 return ERROR_FAIL;
2657 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2658 address,
2659 value);
2661 target_buffer_set_u64(target, value_buf, value);
2662 retval = target_write_memory(target, address, 8, 1, value_buf);
2663 if (retval != ERROR_OK)
2664 LOG_DEBUG("failed: %i", retval);
2666 return retval;
2669 int target_write_u32(struct target *target, target_addr_t address, uint32_t value)
2671 int retval;
2672 uint8_t value_buf[4];
2673 if (!target_was_examined(target)) {
2674 LOG_ERROR("Target not examined yet");
2675 return ERROR_FAIL;
2678 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2679 address,
2680 value);
2682 target_buffer_set_u32(target, value_buf, value);
2683 retval = target_write_memory(target, address, 4, 1, value_buf);
2684 if (retval != ERROR_OK)
2685 LOG_DEBUG("failed: %i", retval);
2687 return retval;
2690 int target_write_u16(struct target *target, target_addr_t address, uint16_t value)
2692 int retval;
2693 uint8_t value_buf[2];
2694 if (!target_was_examined(target)) {
2695 LOG_ERROR("Target not examined yet");
2696 return ERROR_FAIL;
2699 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2700 address,
2701 value);
2703 target_buffer_set_u16(target, value_buf, value);
2704 retval = target_write_memory(target, address, 2, 1, value_buf);
2705 if (retval != ERROR_OK)
2706 LOG_DEBUG("failed: %i", retval);
2708 return retval;
2711 int target_write_u8(struct target *target, target_addr_t address, uint8_t value)
2713 int retval;
2714 if (!target_was_examined(target)) {
2715 LOG_ERROR("Target not examined yet");
2716 return ERROR_FAIL;
2719 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2720 address, value);
2722 retval = target_write_memory(target, address, 1, 1, &value);
2723 if (retval != ERROR_OK)
2724 LOG_DEBUG("failed: %i", retval);
2726 return retval;
2729 int target_write_phys_u64(struct target *target, target_addr_t address, uint64_t value)
2731 int retval;
2732 uint8_t value_buf[8];
2733 if (!target_was_examined(target)) {
2734 LOG_ERROR("Target not examined yet");
2735 return ERROR_FAIL;
2738 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2739 address,
2740 value);
2742 target_buffer_set_u64(target, value_buf, value);
2743 retval = target_write_phys_memory(target, address, 8, 1, value_buf);
2744 if (retval != ERROR_OK)
2745 LOG_DEBUG("failed: %i", retval);
2747 return retval;
2750 int target_write_phys_u32(struct target *target, target_addr_t address, uint32_t value)
2752 int retval;
2753 uint8_t value_buf[4];
2754 if (!target_was_examined(target)) {
2755 LOG_ERROR("Target not examined yet");
2756 return ERROR_FAIL;
2759 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2760 address,
2761 value);
2763 target_buffer_set_u32(target, value_buf, value);
2764 retval = target_write_phys_memory(target, address, 4, 1, value_buf);
2765 if (retval != ERROR_OK)
2766 LOG_DEBUG("failed: %i", retval);
2768 return retval;
2771 int target_write_phys_u16(struct target *target, target_addr_t address, uint16_t value)
2773 int retval;
2774 uint8_t value_buf[2];
2775 if (!target_was_examined(target)) {
2776 LOG_ERROR("Target not examined yet");
2777 return ERROR_FAIL;
2780 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2781 address,
2782 value);
2784 target_buffer_set_u16(target, value_buf, value);
2785 retval = target_write_phys_memory(target, address, 2, 1, value_buf);
2786 if (retval != ERROR_OK)
2787 LOG_DEBUG("failed: %i", retval);
2789 return retval;
2792 int target_write_phys_u8(struct target *target, target_addr_t address, uint8_t value)
2794 int retval;
2795 if (!target_was_examined(target)) {
2796 LOG_ERROR("Target not examined yet");
2797 return ERROR_FAIL;
2800 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2801 address, value);
2803 retval = target_write_phys_memory(target, address, 1, 1, &value);
2804 if (retval != ERROR_OK)
2805 LOG_DEBUG("failed: %i", retval);
2807 return retval;
2810 static int find_target(struct command_invocation *cmd, const char *name)
2812 struct target *target = get_target(name);
2813 if (!target) {
2814 command_print(cmd, "Target: %s is unknown, try one of:\n", name);
2815 return ERROR_FAIL;
2817 if (!target->tap->enabled) {
2818 command_print(cmd, "Target: TAP %s is disabled, "
2819 "can't be the current target\n",
2820 target->tap->dotted_name);
2821 return ERROR_FAIL;
2824 cmd->ctx->current_target = target;
2825 if (cmd->ctx->current_target_override)
2826 cmd->ctx->current_target_override = target;
2828 return ERROR_OK;
2832 COMMAND_HANDLER(handle_targets_command)
2834 int retval = ERROR_OK;
2835 if (CMD_ARGC == 1) {
2836 retval = find_target(CMD, CMD_ARGV[0]);
2837 if (retval == ERROR_OK) {
2838 /* we're done! */
2839 return retval;
2843 struct target *target = all_targets;
2844 command_print(CMD, " TargetName Type Endian TapName State ");
2845 command_print(CMD, "-- ------------------ ---------- ------ ------------------ ------------");
2846 while (target) {
2847 const char *state;
2848 char marker = ' ';
2850 if (target->tap->enabled)
2851 state = target_state_name(target);
2852 else
2853 state = "tap-disabled";
2855 if (CMD_CTX->current_target == target)
2856 marker = '*';
2858 /* keep columns lined up to match the headers above */
2859 command_print(CMD,
2860 "%2d%c %-18s %-10s %-6s %-18s %s",
2861 target->target_number,
2862 marker,
2863 target_name(target),
2864 target_type_name(target),
2865 jim_nvp_value2name_simple(nvp_target_endian,
2866 target->endianness)->name,
2867 target->tap->dotted_name,
2868 state);
2869 target = target->next;
2872 return retval;
2875 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2877 static int power_dropout;
2878 static int srst_asserted;
2880 static int run_power_restore;
2881 static int run_power_dropout;
2882 static int run_srst_asserted;
2883 static int run_srst_deasserted;
2885 static int sense_handler(void)
2887 static int prev_srst_asserted;
2888 static int prev_power_dropout;
2890 int retval = jtag_power_dropout(&power_dropout);
2891 if (retval != ERROR_OK)
2892 return retval;
2894 int power_restored;
2895 power_restored = prev_power_dropout && !power_dropout;
2896 if (power_restored)
2897 run_power_restore = 1;
2899 int64_t current = timeval_ms();
2900 static int64_t last_power;
2901 bool wait_more = last_power + 2000 > current;
2902 if (power_dropout && !wait_more) {
2903 run_power_dropout = 1;
2904 last_power = current;
2907 retval = jtag_srst_asserted(&srst_asserted);
2908 if (retval != ERROR_OK)
2909 return retval;
2911 int srst_deasserted;
2912 srst_deasserted = prev_srst_asserted && !srst_asserted;
2914 static int64_t last_srst;
2915 wait_more = last_srst + 2000 > current;
2916 if (srst_deasserted && !wait_more) {
2917 run_srst_deasserted = 1;
2918 last_srst = current;
2921 if (!prev_srst_asserted && srst_asserted)
2922 run_srst_asserted = 1;
2924 prev_srst_asserted = srst_asserted;
2925 prev_power_dropout = power_dropout;
2927 if (srst_deasserted || power_restored) {
2928 /* Other than logging the event we can't do anything here.
2929 * Issuing a reset is a particularly bad idea as we might
2930 * be inside a reset already.
2934 return ERROR_OK;
2937 /* process target state changes */
2938 static int handle_target(void *priv)
2940 Jim_Interp *interp = (Jim_Interp *)priv;
2941 int retval = ERROR_OK;
2943 if (!is_jtag_poll_safe()) {
2944 /* polling is disabled currently */
2945 return ERROR_OK;
2948 /* we do not want to recurse here... */
2949 static int recursive;
2950 if (!recursive) {
2951 recursive = 1;
2952 sense_handler();
2953 /* danger! running these procedures can trigger srst assertions and power dropouts.
2954 * We need to avoid an infinite loop/recursion here and we do that by
2955 * clearing the flags after running these events.
2957 int did_something = 0;
2958 if (run_srst_asserted) {
2959 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2960 Jim_Eval(interp, "srst_asserted");
2961 did_something = 1;
2963 if (run_srst_deasserted) {
2964 Jim_Eval(interp, "srst_deasserted");
2965 did_something = 1;
2967 if (run_power_dropout) {
2968 LOG_INFO("Power dropout detected, running power_dropout proc.");
2969 Jim_Eval(interp, "power_dropout");
2970 did_something = 1;
2972 if (run_power_restore) {
2973 Jim_Eval(interp, "power_restore");
2974 did_something = 1;
2977 if (did_something) {
2978 /* clear detect flags */
2979 sense_handler();
2982 /* clear action flags */
2984 run_srst_asserted = 0;
2985 run_srst_deasserted = 0;
2986 run_power_restore = 0;
2987 run_power_dropout = 0;
2989 recursive = 0;
2992 /* Poll targets for state changes unless that's globally disabled.
2993 * Skip targets that are currently disabled.
2995 for (struct target *target = all_targets;
2996 is_jtag_poll_safe() && target;
2997 target = target->next) {
2999 if (!target_was_examined(target))
3000 continue;
3002 if (!target->tap->enabled)
3003 continue;
3005 if (target->backoff.times > target->backoff.count) {
3006 /* do not poll this time as we failed previously */
3007 target->backoff.count++;
3008 continue;
3010 target->backoff.count = 0;
3012 /* only poll target if we've got power and srst isn't asserted */
3013 if (!power_dropout && !srst_asserted) {
3014 /* polling may fail silently until the target has been examined */
3015 retval = target_poll(target);
3016 if (retval != ERROR_OK) {
3017 /* 100ms polling interval. Increase interval between polling up to 5000ms */
3018 if (target->backoff.times * polling_interval < 5000) {
3019 target->backoff.times *= 2;
3020 target->backoff.times++;
3023 /* Tell GDB to halt the debugger. This allows the user to
3024 * run monitor commands to handle the situation.
3026 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
3028 if (target->backoff.times > 0) {
3029 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
3030 target_reset_examined(target);
3031 retval = target_examine_one(target);
3032 /* Target examination could have failed due to unstable connection,
3033 * but we set the examined flag anyway to repoll it later */
3034 if (retval != ERROR_OK) {
3035 target_set_examined(target);
3036 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
3037 target->backoff.times * polling_interval);
3038 return retval;
3042 /* Since we succeeded, we reset backoff count */
3043 target->backoff.times = 0;
3047 return retval;
3050 COMMAND_HANDLER(handle_reg_command)
3052 LOG_DEBUG("-");
3054 struct target *target = get_current_target(CMD_CTX);
3055 struct reg *reg = NULL;
3057 /* list all available registers for the current target */
3058 if (CMD_ARGC == 0) {
3059 struct reg_cache *cache = target->reg_cache;
3061 unsigned int count = 0;
3062 while (cache) {
3063 unsigned i;
3065 command_print(CMD, "===== %s", cache->name);
3067 for (i = 0, reg = cache->reg_list;
3068 i < cache->num_regs;
3069 i++, reg++, count++) {
3070 if (reg->exist == false || reg->hidden)
3071 continue;
3072 /* only print cached values if they are valid */
3073 if (reg->valid) {
3074 char *value = buf_to_hex_str(reg->value,
3075 reg->size);
3076 command_print(CMD,
3077 "(%i) %s (/%" PRIu32 "): 0x%s%s",
3078 count, reg->name,
3079 reg->size, value,
3080 reg->dirty
3081 ? " (dirty)"
3082 : "");
3083 free(value);
3084 } else {
3085 command_print(CMD, "(%i) %s (/%" PRIu32 ")",
3086 count, reg->name,
3087 reg->size);
3090 cache = cache->next;
3093 return ERROR_OK;
3096 /* access a single register by its ordinal number */
3097 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
3098 unsigned num;
3099 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
3101 struct reg_cache *cache = target->reg_cache;
3102 unsigned int count = 0;
3103 while (cache) {
3104 unsigned i;
3105 for (i = 0; i < cache->num_regs; i++) {
3106 if (count++ == num) {
3107 reg = &cache->reg_list[i];
3108 break;
3111 if (reg)
3112 break;
3113 cache = cache->next;
3116 if (!reg) {
3117 command_print(CMD, "%i is out of bounds, the current target "
3118 "has only %i registers (0 - %i)", num, count, count - 1);
3119 return ERROR_OK;
3121 } else {
3122 /* access a single register by its name */
3123 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], true);
3125 if (!reg)
3126 goto not_found;
3129 assert(reg); /* give clang a hint that we *know* reg is != NULL here */
3131 if (!reg->exist)
3132 goto not_found;
3134 /* display a register */
3135 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
3136 && (CMD_ARGV[1][0] <= '9')))) {
3137 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
3138 reg->valid = 0;
3140 if (reg->valid == 0) {
3141 int retval = reg->type->get(reg);
3142 if (retval != ERROR_OK) {
3143 LOG_ERROR("Could not read register '%s'", reg->name);
3144 return retval;
3147 char *value = buf_to_hex_str(reg->value, reg->size);
3148 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3149 free(value);
3150 return ERROR_OK;
3153 /* set register value */
3154 if (CMD_ARGC == 2) {
3155 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
3156 if (!buf)
3157 return ERROR_FAIL;
3158 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
3160 int retval = reg->type->set(reg, buf);
3161 if (retval != ERROR_OK) {
3162 LOG_ERROR("Could not write to register '%s'", reg->name);
3163 } else {
3164 char *value = buf_to_hex_str(reg->value, reg->size);
3165 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3166 free(value);
3169 free(buf);
3171 return retval;
3174 return ERROR_COMMAND_SYNTAX_ERROR;
3176 not_found:
3177 command_print(CMD, "register %s not found in current target", CMD_ARGV[0]);
3178 return ERROR_OK;
3181 COMMAND_HANDLER(handle_poll_command)
3183 int retval = ERROR_OK;
3184 struct target *target = get_current_target(CMD_CTX);
3186 if (CMD_ARGC == 0) {
3187 command_print(CMD, "background polling: %s",
3188 jtag_poll_get_enabled() ? "on" : "off");
3189 command_print(CMD, "TAP: %s (%s)",
3190 target->tap->dotted_name,
3191 target->tap->enabled ? "enabled" : "disabled");
3192 if (!target->tap->enabled)
3193 return ERROR_OK;
3194 retval = target_poll(target);
3195 if (retval != ERROR_OK)
3196 return retval;
3197 retval = target_arch_state(target);
3198 if (retval != ERROR_OK)
3199 return retval;
3200 } else if (CMD_ARGC == 1) {
3201 bool enable;
3202 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
3203 jtag_poll_set_enabled(enable);
3204 } else
3205 return ERROR_COMMAND_SYNTAX_ERROR;
3207 return retval;
3210 COMMAND_HANDLER(handle_wait_halt_command)
3212 if (CMD_ARGC > 1)
3213 return ERROR_COMMAND_SYNTAX_ERROR;
3215 unsigned ms = DEFAULT_HALT_TIMEOUT;
3216 if (1 == CMD_ARGC) {
3217 int retval = parse_uint(CMD_ARGV[0], &ms);
3218 if (retval != ERROR_OK)
3219 return ERROR_COMMAND_SYNTAX_ERROR;
3222 struct target *target = get_current_target(CMD_CTX);
3223 return target_wait_state(target, TARGET_HALTED, ms);
3226 /* wait for target state to change. The trick here is to have a low
3227 * latency for short waits and not to suck up all the CPU time
3228 * on longer waits.
3230 * After 500ms, keep_alive() is invoked
3232 int target_wait_state(struct target *target, enum target_state state, unsigned int ms)
3234 int retval;
3235 int64_t then = 0, cur;
3236 bool once = true;
3238 for (;;) {
3239 retval = target_poll(target);
3240 if (retval != ERROR_OK)
3241 return retval;
3242 if (target->state == state)
3243 break;
3244 cur = timeval_ms();
3245 if (once) {
3246 once = false;
3247 then = timeval_ms();
3248 LOG_DEBUG("waiting for target %s...",
3249 nvp_value2name(nvp_target_state, state)->name);
3252 if (cur-then > 500)
3253 keep_alive();
3255 if ((cur-then) > ms) {
3256 LOG_ERROR("timed out while waiting for target %s",
3257 nvp_value2name(nvp_target_state, state)->name);
3258 return ERROR_FAIL;
3262 return ERROR_OK;
3265 COMMAND_HANDLER(handle_halt_command)
3267 LOG_DEBUG("-");
3269 struct target *target = get_current_target(CMD_CTX);
3271 target->verbose_halt_msg = true;
3273 int retval = target_halt(target);
3274 if (retval != ERROR_OK)
3275 return retval;
3277 if (CMD_ARGC == 1) {
3278 unsigned wait_local;
3279 retval = parse_uint(CMD_ARGV[0], &wait_local);
3280 if (retval != ERROR_OK)
3281 return ERROR_COMMAND_SYNTAX_ERROR;
3282 if (!wait_local)
3283 return ERROR_OK;
3286 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
3289 COMMAND_HANDLER(handle_soft_reset_halt_command)
3291 struct target *target = get_current_target(CMD_CTX);
3293 LOG_TARGET_INFO(target, "requesting target halt and executing a soft reset");
3295 target_soft_reset_halt(target);
3297 return ERROR_OK;
3300 COMMAND_HANDLER(handle_reset_command)
3302 if (CMD_ARGC > 1)
3303 return ERROR_COMMAND_SYNTAX_ERROR;
3305 enum target_reset_mode reset_mode = RESET_RUN;
3306 if (CMD_ARGC == 1) {
3307 const struct nvp *n;
3308 n = nvp_name2value(nvp_reset_modes, CMD_ARGV[0]);
3309 if ((!n->name) || (n->value == RESET_UNKNOWN))
3310 return ERROR_COMMAND_SYNTAX_ERROR;
3311 reset_mode = n->value;
3314 /* reset *all* targets */
3315 return target_process_reset(CMD, reset_mode);
3319 COMMAND_HANDLER(handle_resume_command)
3321 int current = 1;
3322 if (CMD_ARGC > 1)
3323 return ERROR_COMMAND_SYNTAX_ERROR;
3325 struct target *target = get_current_target(CMD_CTX);
3327 /* with no CMD_ARGV, resume from current pc, addr = 0,
3328 * with one arguments, addr = CMD_ARGV[0],
3329 * handle breakpoints, not debugging */
3330 target_addr_t addr = 0;
3331 if (CMD_ARGC == 1) {
3332 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3333 current = 0;
3336 return target_resume(target, current, addr, 1, 0);
3339 COMMAND_HANDLER(handle_step_command)
3341 if (CMD_ARGC > 1)
3342 return ERROR_COMMAND_SYNTAX_ERROR;
3344 LOG_DEBUG("-");
3346 /* with no CMD_ARGV, step from current pc, addr = 0,
3347 * with one argument addr = CMD_ARGV[0],
3348 * handle breakpoints, debugging */
3349 target_addr_t addr = 0;
3350 int current_pc = 1;
3351 if (CMD_ARGC == 1) {
3352 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3353 current_pc = 0;
3356 struct target *target = get_current_target(CMD_CTX);
3358 return target_step(target, current_pc, addr, 1);
3361 void target_handle_md_output(struct command_invocation *cmd,
3362 struct target *target, target_addr_t address, unsigned size,
3363 unsigned count, const uint8_t *buffer)
3365 const unsigned line_bytecnt = 32;
3366 unsigned line_modulo = line_bytecnt / size;
3368 char output[line_bytecnt * 4 + 1];
3369 unsigned output_len = 0;
3371 const char *value_fmt;
3372 switch (size) {
3373 case 8:
3374 value_fmt = "%16.16"PRIx64" ";
3375 break;
3376 case 4:
3377 value_fmt = "%8.8"PRIx64" ";
3378 break;
3379 case 2:
3380 value_fmt = "%4.4"PRIx64" ";
3381 break;
3382 case 1:
3383 value_fmt = "%2.2"PRIx64" ";
3384 break;
3385 default:
3386 /* "can't happen", caller checked */
3387 LOG_ERROR("invalid memory read size: %u", size);
3388 return;
3391 for (unsigned i = 0; i < count; i++) {
3392 if (i % line_modulo == 0) {
3393 output_len += snprintf(output + output_len,
3394 sizeof(output) - output_len,
3395 TARGET_ADDR_FMT ": ",
3396 (address + (i * size)));
3399 uint64_t value = 0;
3400 const uint8_t *value_ptr = buffer + i * size;
3401 switch (size) {
3402 case 8:
3403 value = target_buffer_get_u64(target, value_ptr);
3404 break;
3405 case 4:
3406 value = target_buffer_get_u32(target, value_ptr);
3407 break;
3408 case 2:
3409 value = target_buffer_get_u16(target, value_ptr);
3410 break;
3411 case 1:
3412 value = *value_ptr;
3414 output_len += snprintf(output + output_len,
3415 sizeof(output) - output_len,
3416 value_fmt, value);
3418 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
3419 command_print(cmd, "%s", output);
3420 output_len = 0;
3425 COMMAND_HANDLER(handle_md_command)
3427 if (CMD_ARGC < 1)
3428 return ERROR_COMMAND_SYNTAX_ERROR;
3430 unsigned size = 0;
3431 switch (CMD_NAME[2]) {
3432 case 'd':
3433 size = 8;
3434 break;
3435 case 'w':
3436 size = 4;
3437 break;
3438 case 'h':
3439 size = 2;
3440 break;
3441 case 'b':
3442 size = 1;
3443 break;
3444 default:
3445 return ERROR_COMMAND_SYNTAX_ERROR;
3448 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3449 int (*fn)(struct target *target,
3450 target_addr_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
3451 if (physical) {
3452 CMD_ARGC--;
3453 CMD_ARGV++;
3454 fn = target_read_phys_memory;
3455 } else
3456 fn = target_read_memory;
3457 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
3458 return ERROR_COMMAND_SYNTAX_ERROR;
3460 target_addr_t address;
3461 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3463 unsigned count = 1;
3464 if (CMD_ARGC == 2)
3465 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3467 uint8_t *buffer = calloc(count, size);
3468 if (!buffer) {
3469 LOG_ERROR("Failed to allocate md read buffer");
3470 return ERROR_FAIL;
3473 struct target *target = get_current_target(CMD_CTX);
3474 int retval = fn(target, address, size, count, buffer);
3475 if (retval == ERROR_OK)
3476 target_handle_md_output(CMD, target, address, size, count, buffer);
3478 free(buffer);
3480 return retval;
3483 typedef int (*target_write_fn)(struct target *target,
3484 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3486 static int target_fill_mem(struct target *target,
3487 target_addr_t address,
3488 target_write_fn fn,
3489 unsigned data_size,
3490 /* value */
3491 uint64_t b,
3492 /* count */
3493 unsigned c)
3495 /* We have to write in reasonably large chunks to be able
3496 * to fill large memory areas with any sane speed */
3497 const unsigned chunk_size = 16384;
3498 uint8_t *target_buf = malloc(chunk_size * data_size);
3499 if (!target_buf) {
3500 LOG_ERROR("Out of memory");
3501 return ERROR_FAIL;
3504 for (unsigned i = 0; i < chunk_size; i++) {
3505 switch (data_size) {
3506 case 8:
3507 target_buffer_set_u64(target, target_buf + i * data_size, b);
3508 break;
3509 case 4:
3510 target_buffer_set_u32(target, target_buf + i * data_size, b);
3511 break;
3512 case 2:
3513 target_buffer_set_u16(target, target_buf + i * data_size, b);
3514 break;
3515 case 1:
3516 target_buffer_set_u8(target, target_buf + i * data_size, b);
3517 break;
3518 default:
3519 exit(-1);
3523 int retval = ERROR_OK;
3525 for (unsigned x = 0; x < c; x += chunk_size) {
3526 unsigned current;
3527 current = c - x;
3528 if (current > chunk_size)
3529 current = chunk_size;
3530 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3531 if (retval != ERROR_OK)
3532 break;
3533 /* avoid GDB timeouts */
3534 keep_alive();
3536 free(target_buf);
3538 return retval;
3542 COMMAND_HANDLER(handle_mw_command)
3544 if (CMD_ARGC < 2)
3545 return ERROR_COMMAND_SYNTAX_ERROR;
3546 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3547 target_write_fn fn;
3548 if (physical) {
3549 CMD_ARGC--;
3550 CMD_ARGV++;
3551 fn = target_write_phys_memory;
3552 } else
3553 fn = target_write_memory;
3554 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3555 return ERROR_COMMAND_SYNTAX_ERROR;
3557 target_addr_t address;
3558 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3560 uint64_t value;
3561 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[1], value);
3563 unsigned count = 1;
3564 if (CMD_ARGC == 3)
3565 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3567 struct target *target = get_current_target(CMD_CTX);
3568 unsigned wordsize;
3569 switch (CMD_NAME[2]) {
3570 case 'd':
3571 wordsize = 8;
3572 break;
3573 case 'w':
3574 wordsize = 4;
3575 break;
3576 case 'h':
3577 wordsize = 2;
3578 break;
3579 case 'b':
3580 wordsize = 1;
3581 break;
3582 default:
3583 return ERROR_COMMAND_SYNTAX_ERROR;
3586 return target_fill_mem(target, address, fn, wordsize, value, count);
3589 static COMMAND_HELPER(parse_load_image_command, struct image *image,
3590 target_addr_t *min_address, target_addr_t *max_address)
3592 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3593 return ERROR_COMMAND_SYNTAX_ERROR;
3595 /* a base address isn't always necessary,
3596 * default to 0x0 (i.e. don't relocate) */
3597 if (CMD_ARGC >= 2) {
3598 target_addr_t addr;
3599 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3600 image->base_address = addr;
3601 image->base_address_set = true;
3602 } else
3603 image->base_address_set = false;
3605 image->start_address_set = false;
3607 if (CMD_ARGC >= 4)
3608 COMMAND_PARSE_ADDRESS(CMD_ARGV[3], *min_address);
3609 if (CMD_ARGC == 5) {
3610 COMMAND_PARSE_ADDRESS(CMD_ARGV[4], *max_address);
3611 /* use size (given) to find max (required) */
3612 *max_address += *min_address;
3615 if (*min_address > *max_address)
3616 return ERROR_COMMAND_SYNTAX_ERROR;
3618 return ERROR_OK;
3621 COMMAND_HANDLER(handle_load_image_command)
3623 uint8_t *buffer;
3624 size_t buf_cnt;
3625 uint32_t image_size;
3626 target_addr_t min_address = 0;
3627 target_addr_t max_address = -1;
3628 struct image image;
3630 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
3631 &image, &min_address, &max_address);
3632 if (retval != ERROR_OK)
3633 return retval;
3635 struct target *target = get_current_target(CMD_CTX);
3637 struct duration bench;
3638 duration_start(&bench);
3640 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3641 return ERROR_FAIL;
3643 image_size = 0x0;
3644 retval = ERROR_OK;
3645 for (unsigned int i = 0; i < image.num_sections; i++) {
3646 buffer = malloc(image.sections[i].size);
3647 if (!buffer) {
3648 command_print(CMD,
3649 "error allocating buffer for section (%d bytes)",
3650 (int)(image.sections[i].size));
3651 retval = ERROR_FAIL;
3652 break;
3655 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3656 if (retval != ERROR_OK) {
3657 free(buffer);
3658 break;
3661 uint32_t offset = 0;
3662 uint32_t length = buf_cnt;
3664 /* DANGER!!! beware of unsigned comparison here!!! */
3666 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3667 (image.sections[i].base_address < max_address)) {
3669 if (image.sections[i].base_address < min_address) {
3670 /* clip addresses below */
3671 offset += min_address-image.sections[i].base_address;
3672 length -= offset;
3675 if (image.sections[i].base_address + buf_cnt > max_address)
3676 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3678 retval = target_write_buffer(target,
3679 image.sections[i].base_address + offset, length, buffer + offset);
3680 if (retval != ERROR_OK) {
3681 free(buffer);
3682 break;
3684 image_size += length;
3685 command_print(CMD, "%u bytes written at address " TARGET_ADDR_FMT "",
3686 (unsigned int)length,
3687 image.sections[i].base_address + offset);
3690 free(buffer);
3693 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3694 command_print(CMD, "downloaded %" PRIu32 " bytes "
3695 "in %fs (%0.3f KiB/s)", image_size,
3696 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3699 image_close(&image);
3701 return retval;
3705 COMMAND_HANDLER(handle_dump_image_command)
3707 struct fileio *fileio;
3708 uint8_t *buffer;
3709 int retval, retvaltemp;
3710 target_addr_t address, size;
3711 struct duration bench;
3712 struct target *target = get_current_target(CMD_CTX);
3714 if (CMD_ARGC != 3)
3715 return ERROR_COMMAND_SYNTAX_ERROR;
3717 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], address);
3718 COMMAND_PARSE_ADDRESS(CMD_ARGV[2], size);
3720 uint32_t buf_size = (size > 4096) ? 4096 : size;
3721 buffer = malloc(buf_size);
3722 if (!buffer)
3723 return ERROR_FAIL;
3725 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3726 if (retval != ERROR_OK) {
3727 free(buffer);
3728 return retval;
3731 duration_start(&bench);
3733 while (size > 0) {
3734 size_t size_written;
3735 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3736 retval = target_read_buffer(target, address, this_run_size, buffer);
3737 if (retval != ERROR_OK)
3738 break;
3740 retval = fileio_write(fileio, this_run_size, buffer, &size_written);
3741 if (retval != ERROR_OK)
3742 break;
3744 size -= this_run_size;
3745 address += this_run_size;
3748 free(buffer);
3750 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3751 size_t filesize;
3752 retval = fileio_size(fileio, &filesize);
3753 if (retval != ERROR_OK)
3754 return retval;
3755 command_print(CMD,
3756 "dumped %zu bytes in %fs (%0.3f KiB/s)", filesize,
3757 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3760 retvaltemp = fileio_close(fileio);
3761 if (retvaltemp != ERROR_OK)
3762 return retvaltemp;
3764 return retval;
3767 enum verify_mode {
3768 IMAGE_TEST = 0,
3769 IMAGE_VERIFY = 1,
3770 IMAGE_CHECKSUM_ONLY = 2
3773 static COMMAND_HELPER(handle_verify_image_command_internal, enum verify_mode verify)
3775 uint8_t *buffer;
3776 size_t buf_cnt;
3777 uint32_t image_size;
3778 int retval;
3779 uint32_t checksum = 0;
3780 uint32_t mem_checksum = 0;
3782 struct image image;
3784 struct target *target = get_current_target(CMD_CTX);
3786 if (CMD_ARGC < 1)
3787 return ERROR_COMMAND_SYNTAX_ERROR;
3789 if (!target) {
3790 LOG_ERROR("no target selected");
3791 return ERROR_FAIL;
3794 struct duration bench;
3795 duration_start(&bench);
3797 if (CMD_ARGC >= 2) {
3798 target_addr_t addr;
3799 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3800 image.base_address = addr;
3801 image.base_address_set = true;
3802 } else {
3803 image.base_address_set = false;
3804 image.base_address = 0x0;
3807 image.start_address_set = false;
3809 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3810 if (retval != ERROR_OK)
3811 return retval;
3813 image_size = 0x0;
3814 int diffs = 0;
3815 retval = ERROR_OK;
3816 for (unsigned int i = 0; i < image.num_sections; i++) {
3817 buffer = malloc(image.sections[i].size);
3818 if (!buffer) {
3819 command_print(CMD,
3820 "error allocating buffer for section (%" PRIu32 " bytes)",
3821 image.sections[i].size);
3822 break;
3824 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3825 if (retval != ERROR_OK) {
3826 free(buffer);
3827 break;
3830 if (verify >= IMAGE_VERIFY) {
3831 /* calculate checksum of image */
3832 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3833 if (retval != ERROR_OK) {
3834 free(buffer);
3835 break;
3838 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3839 if (retval != ERROR_OK) {
3840 free(buffer);
3841 break;
3843 if ((checksum != mem_checksum) && (verify == IMAGE_CHECKSUM_ONLY)) {
3844 LOG_ERROR("checksum mismatch");
3845 free(buffer);
3846 retval = ERROR_FAIL;
3847 goto done;
3849 if (checksum != mem_checksum) {
3850 /* failed crc checksum, fall back to a binary compare */
3851 uint8_t *data;
3853 if (diffs == 0)
3854 LOG_ERROR("checksum mismatch - attempting binary compare");
3856 data = malloc(buf_cnt);
3858 retval = target_read_buffer(target, image.sections[i].base_address, buf_cnt, data);
3859 if (retval == ERROR_OK) {
3860 uint32_t t;
3861 for (t = 0; t < buf_cnt; t++) {
3862 if (data[t] != buffer[t]) {
3863 command_print(CMD,
3864 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3865 diffs,
3866 (unsigned)(t + image.sections[i].base_address),
3867 data[t],
3868 buffer[t]);
3869 if (diffs++ >= 127) {
3870 command_print(CMD, "More than 128 errors, the rest are not printed.");
3871 free(data);
3872 free(buffer);
3873 goto done;
3876 keep_alive();
3879 free(data);
3881 } else {
3882 command_print(CMD, "address " TARGET_ADDR_FMT " length 0x%08zx",
3883 image.sections[i].base_address,
3884 buf_cnt);
3887 free(buffer);
3888 image_size += buf_cnt;
3890 if (diffs > 0)
3891 command_print(CMD, "No more differences found.");
3892 done:
3893 if (diffs > 0)
3894 retval = ERROR_FAIL;
3895 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3896 command_print(CMD, "verified %" PRIu32 " bytes "
3897 "in %fs (%0.3f KiB/s)", image_size,
3898 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3901 image_close(&image);
3903 return retval;
3906 COMMAND_HANDLER(handle_verify_image_checksum_command)
3908 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_CHECKSUM_ONLY);
3911 COMMAND_HANDLER(handle_verify_image_command)
3913 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_VERIFY);
3916 COMMAND_HANDLER(handle_test_image_command)
3918 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_TEST);
3921 static int handle_bp_command_list(struct command_invocation *cmd)
3923 struct target *target = get_current_target(cmd->ctx);
3924 struct breakpoint *breakpoint = target->breakpoints;
3925 while (breakpoint) {
3926 if (breakpoint->type == BKPT_SOFT) {
3927 char *buf = buf_to_hex_str(breakpoint->orig_instr,
3928 breakpoint->length);
3929 command_print(cmd, "IVA breakpoint: " TARGET_ADDR_FMT ", 0x%x, 0x%s",
3930 breakpoint->address,
3931 breakpoint->length,
3932 buf);
3933 free(buf);
3934 } else {
3935 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3936 command_print(cmd, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %u",
3937 breakpoint->asid,
3938 breakpoint->length, breakpoint->number);
3939 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3940 command_print(cmd, "Hybrid breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %u",
3941 breakpoint->address,
3942 breakpoint->length, breakpoint->number);
3943 command_print(cmd, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3944 breakpoint->asid);
3945 } else
3946 command_print(cmd, "Breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %u",
3947 breakpoint->address,
3948 breakpoint->length, breakpoint->number);
3951 breakpoint = breakpoint->next;
3953 return ERROR_OK;
3956 static int handle_bp_command_set(struct command_invocation *cmd,
3957 target_addr_t addr, uint32_t asid, uint32_t length, int hw)
3959 struct target *target = get_current_target(cmd->ctx);
3960 int retval;
3962 if (asid == 0) {
3963 retval = breakpoint_add(target, addr, length, hw);
3964 /* error is always logged in breakpoint_add(), do not print it again */
3965 if (retval == ERROR_OK)
3966 command_print(cmd, "breakpoint set at " TARGET_ADDR_FMT "", addr);
3968 } else if (addr == 0) {
3969 if (!target->type->add_context_breakpoint) {
3970 LOG_ERROR("Context breakpoint not available");
3971 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
3973 retval = context_breakpoint_add(target, asid, length, hw);
3974 /* error is always logged in context_breakpoint_add(), do not print it again */
3975 if (retval == ERROR_OK)
3976 command_print(cmd, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3978 } else {
3979 if (!target->type->add_hybrid_breakpoint) {
3980 LOG_ERROR("Hybrid breakpoint not available");
3981 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
3983 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3984 /* error is always logged in hybrid_breakpoint_add(), do not print it again */
3985 if (retval == ERROR_OK)
3986 command_print(cmd, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3988 return retval;
3991 COMMAND_HANDLER(handle_bp_command)
3993 target_addr_t addr;
3994 uint32_t asid;
3995 uint32_t length;
3996 int hw = BKPT_SOFT;
3998 switch (CMD_ARGC) {
3999 case 0:
4000 return handle_bp_command_list(CMD);
4002 case 2:
4003 asid = 0;
4004 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4005 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4006 return handle_bp_command_set(CMD, addr, asid, length, hw);
4008 case 3:
4009 if (strcmp(CMD_ARGV[2], "hw") == 0) {
4010 hw = BKPT_HARD;
4011 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4012 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4013 asid = 0;
4014 return handle_bp_command_set(CMD, addr, asid, length, hw);
4015 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
4016 hw = BKPT_HARD;
4017 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
4018 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4019 addr = 0;
4020 return handle_bp_command_set(CMD, addr, asid, length, hw);
4022 /* fallthrough */
4023 case 4:
4024 hw = BKPT_HARD;
4025 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4026 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
4027 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
4028 return handle_bp_command_set(CMD, addr, asid, length, hw);
4030 default:
4031 return ERROR_COMMAND_SYNTAX_ERROR;
4035 COMMAND_HANDLER(handle_rbp_command)
4037 if (CMD_ARGC != 1)
4038 return ERROR_COMMAND_SYNTAX_ERROR;
4040 struct target *target = get_current_target(CMD_CTX);
4042 if (!strcmp(CMD_ARGV[0], "all")) {
4043 breakpoint_remove_all(target);
4044 } else {
4045 target_addr_t addr;
4046 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4048 breakpoint_remove(target, addr);
4051 return ERROR_OK;
4054 COMMAND_HANDLER(handle_wp_command)
4056 struct target *target = get_current_target(CMD_CTX);
4058 if (CMD_ARGC == 0) {
4059 struct watchpoint *watchpoint = target->watchpoints;
4061 while (watchpoint) {
4062 command_print(CMD, "address: " TARGET_ADDR_FMT
4063 ", len: 0x%8.8" PRIx32
4064 ", r/w/a: %i, value: 0x%8.8" PRIx32
4065 ", mask: 0x%8.8" PRIx32,
4066 watchpoint->address,
4067 watchpoint->length,
4068 (int)watchpoint->rw,
4069 watchpoint->value,
4070 watchpoint->mask);
4071 watchpoint = watchpoint->next;
4073 return ERROR_OK;
4076 enum watchpoint_rw type = WPT_ACCESS;
4077 target_addr_t addr = 0;
4078 uint32_t length = 0;
4079 uint32_t data_value = 0x0;
4080 uint32_t data_mask = 0xffffffff;
4082 switch (CMD_ARGC) {
4083 case 5:
4084 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
4085 /* fall through */
4086 case 4:
4087 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
4088 /* fall through */
4089 case 3:
4090 switch (CMD_ARGV[2][0]) {
4091 case 'r':
4092 type = WPT_READ;
4093 break;
4094 case 'w':
4095 type = WPT_WRITE;
4096 break;
4097 case 'a':
4098 type = WPT_ACCESS;
4099 break;
4100 default:
4101 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
4102 return ERROR_COMMAND_SYNTAX_ERROR;
4104 /* fall through */
4105 case 2:
4106 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4107 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4108 break;
4110 default:
4111 return ERROR_COMMAND_SYNTAX_ERROR;
4114 int retval = watchpoint_add(target, addr, length, type,
4115 data_value, data_mask);
4116 if (retval != ERROR_OK)
4117 LOG_ERROR("Failure setting watchpoints");
4119 return retval;
4122 COMMAND_HANDLER(handle_rwp_command)
4124 if (CMD_ARGC != 1)
4125 return ERROR_COMMAND_SYNTAX_ERROR;
4127 target_addr_t addr;
4128 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4130 struct target *target = get_current_target(CMD_CTX);
4131 watchpoint_remove(target, addr);
4133 return ERROR_OK;
4137 * Translate a virtual address to a physical address.
4139 * The low-level target implementation must have logged a detailed error
4140 * which is forwarded to telnet/GDB session.
4142 COMMAND_HANDLER(handle_virt2phys_command)
4144 if (CMD_ARGC != 1)
4145 return ERROR_COMMAND_SYNTAX_ERROR;
4147 target_addr_t va;
4148 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], va);
4149 target_addr_t pa;
4151 struct target *target = get_current_target(CMD_CTX);
4152 int retval = target->type->virt2phys(target, va, &pa);
4153 if (retval == ERROR_OK)
4154 command_print(CMD, "Physical address " TARGET_ADDR_FMT "", pa);
4156 return retval;
4159 static void write_data(FILE *f, const void *data, size_t len)
4161 size_t written = fwrite(data, 1, len, f);
4162 if (written != len)
4163 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
4166 static void write_long(FILE *f, int l, struct target *target)
4168 uint8_t val[4];
4170 target_buffer_set_u32(target, val, l);
4171 write_data(f, val, 4);
4174 static void write_string(FILE *f, char *s)
4176 write_data(f, s, strlen(s));
4179 typedef unsigned char UNIT[2]; /* unit of profiling */
4181 /* Dump a gmon.out histogram file. */
4182 static void write_gmon(uint32_t *samples, uint32_t sample_num, const char *filename, bool with_range,
4183 uint32_t start_address, uint32_t end_address, struct target *target, uint32_t duration_ms)
4185 uint32_t i;
4186 FILE *f = fopen(filename, "w");
4187 if (!f)
4188 return;
4189 write_string(f, "gmon");
4190 write_long(f, 0x00000001, target); /* Version */
4191 write_long(f, 0, target); /* padding */
4192 write_long(f, 0, target); /* padding */
4193 write_long(f, 0, target); /* padding */
4195 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
4196 write_data(f, &zero, 1);
4198 /* figure out bucket size */
4199 uint32_t min;
4200 uint32_t max;
4201 if (with_range) {
4202 min = start_address;
4203 max = end_address;
4204 } else {
4205 min = samples[0];
4206 max = samples[0];
4207 for (i = 0; i < sample_num; i++) {
4208 if (min > samples[i])
4209 min = samples[i];
4210 if (max < samples[i])
4211 max = samples[i];
4214 /* max should be (largest sample + 1)
4215 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
4216 if (max < UINT32_MAX)
4217 max++;
4219 /* gprof requires (max - min) >= 2 */
4220 while ((max - min) < 2) {
4221 if (max < UINT32_MAX)
4222 max++;
4223 else
4224 min--;
4228 uint32_t address_space = max - min;
4230 /* FIXME: What is the reasonable number of buckets?
4231 * The profiling result will be more accurate if there are enough buckets. */
4232 static const uint32_t max_buckets = 128 * 1024; /* maximum buckets. */
4233 uint32_t num_buckets = address_space / sizeof(UNIT);
4234 if (num_buckets > max_buckets)
4235 num_buckets = max_buckets;
4236 int *buckets = malloc(sizeof(int) * num_buckets);
4237 if (!buckets) {
4238 fclose(f);
4239 return;
4241 memset(buckets, 0, sizeof(int) * num_buckets);
4242 for (i = 0; i < sample_num; i++) {
4243 uint32_t address = samples[i];
4245 if ((address < min) || (max <= address))
4246 continue;
4248 long long a = address - min;
4249 long long b = num_buckets;
4250 long long c = address_space;
4251 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
4252 buckets[index_t]++;
4255 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
4256 write_long(f, min, target); /* low_pc */
4257 write_long(f, max, target); /* high_pc */
4258 write_long(f, num_buckets, target); /* # of buckets */
4259 float sample_rate = sample_num / (duration_ms / 1000.0);
4260 write_long(f, sample_rate, target);
4261 write_string(f, "seconds");
4262 for (i = 0; i < (15-strlen("seconds")); i++)
4263 write_data(f, &zero, 1);
4264 write_string(f, "s");
4266 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
4268 char *data = malloc(2 * num_buckets);
4269 if (data) {
4270 for (i = 0; i < num_buckets; i++) {
4271 int val;
4272 val = buckets[i];
4273 if (val > 65535)
4274 val = 65535;
4275 data[i * 2] = val&0xff;
4276 data[i * 2 + 1] = (val >> 8) & 0xff;
4278 free(buckets);
4279 write_data(f, data, num_buckets * 2);
4280 free(data);
4281 } else
4282 free(buckets);
4284 fclose(f);
4287 /* profiling samples the CPU PC as quickly as OpenOCD is able,
4288 * which will be used as a random sampling of PC */
4289 COMMAND_HANDLER(handle_profile_command)
4291 struct target *target = get_current_target(CMD_CTX);
4293 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
4294 return ERROR_COMMAND_SYNTAX_ERROR;
4296 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
4297 uint32_t offset;
4298 uint32_t num_of_samples;
4299 int retval = ERROR_OK;
4300 bool halted_before_profiling = target->state == TARGET_HALTED;
4302 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
4304 uint32_t start_address = 0;
4305 uint32_t end_address = 0;
4306 bool with_range = false;
4307 if (CMD_ARGC == 4) {
4308 with_range = true;
4309 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
4310 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
4311 if (start_address > end_address || (end_address - start_address) < 2) {
4312 command_print(CMD, "Error: end - start < 2");
4313 return ERROR_COMMAND_ARGUMENT_INVALID;
4317 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
4318 if (!samples) {
4319 LOG_ERROR("No memory to store samples.");
4320 return ERROR_FAIL;
4323 uint64_t timestart_ms = timeval_ms();
4325 * Some cores let us sample the PC without the
4326 * annoying halt/resume step; for example, ARMv7 PCSR.
4327 * Provide a way to use that more efficient mechanism.
4329 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
4330 &num_of_samples, offset);
4331 if (retval != ERROR_OK) {
4332 free(samples);
4333 return retval;
4335 uint32_t duration_ms = timeval_ms() - timestart_ms;
4337 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
4339 retval = target_poll(target);
4340 if (retval != ERROR_OK) {
4341 free(samples);
4342 return retval;
4345 if (target->state == TARGET_RUNNING && halted_before_profiling) {
4346 /* The target was halted before we started and is running now. Halt it,
4347 * for consistency. */
4348 retval = target_halt(target);
4349 if (retval != ERROR_OK) {
4350 free(samples);
4351 return retval;
4353 } else if (target->state == TARGET_HALTED && !halted_before_profiling) {
4354 /* The target was running before we started and is halted now. Resume
4355 * it, for consistency. */
4356 retval = target_resume(target, 1, 0, 0, 0);
4357 if (retval != ERROR_OK) {
4358 free(samples);
4359 return retval;
4363 retval = target_poll(target);
4364 if (retval != ERROR_OK) {
4365 free(samples);
4366 return retval;
4369 write_gmon(samples, num_of_samples, CMD_ARGV[1],
4370 with_range, start_address, end_address, target, duration_ms);
4371 command_print(CMD, "Wrote %s", CMD_ARGV[1]);
4373 free(samples);
4374 return retval;
4377 static int new_u64_array_element(Jim_Interp *interp, const char *varname, int idx, uint64_t val)
4379 char *namebuf;
4380 Jim_Obj *obj_name, *obj_val;
4381 int result;
4383 namebuf = alloc_printf("%s(%d)", varname, idx);
4384 if (!namebuf)
4385 return JIM_ERR;
4387 obj_name = Jim_NewStringObj(interp, namebuf, -1);
4388 jim_wide wide_val = val;
4389 obj_val = Jim_NewWideObj(interp, wide_val);
4390 if (!obj_name || !obj_val) {
4391 free(namebuf);
4392 return JIM_ERR;
4395 Jim_IncrRefCount(obj_name);
4396 Jim_IncrRefCount(obj_val);
4397 result = Jim_SetVariable(interp, obj_name, obj_val);
4398 Jim_DecrRefCount(interp, obj_name);
4399 Jim_DecrRefCount(interp, obj_val);
4400 free(namebuf);
4401 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
4402 return result;
4405 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
4407 int e;
4409 LOG_WARNING("DEPRECATED! use 'read_memory' not 'mem2array'");
4411 /* argv[0] = name of array to receive the data
4412 * argv[1] = desired element width in bits
4413 * argv[2] = memory address
4414 * argv[3] = count of times to read
4415 * argv[4] = optional "phys"
4417 if (argc < 4 || argc > 5) {
4418 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4419 return JIM_ERR;
4422 /* Arg 0: Name of the array variable */
4423 const char *varname = Jim_GetString(argv[0], NULL);
4425 /* Arg 1: Bit width of one element */
4426 long l;
4427 e = Jim_GetLong(interp, argv[1], &l);
4428 if (e != JIM_OK)
4429 return e;
4430 const unsigned int width_bits = l;
4432 if (width_bits != 8 &&
4433 width_bits != 16 &&
4434 width_bits != 32 &&
4435 width_bits != 64) {
4436 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4437 Jim_AppendStrings(interp, Jim_GetResult(interp),
4438 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4439 return JIM_ERR;
4441 const unsigned int width = width_bits / 8;
4443 /* Arg 2: Memory address */
4444 jim_wide wide_addr;
4445 e = Jim_GetWide(interp, argv[2], &wide_addr);
4446 if (e != JIM_OK)
4447 return e;
4448 target_addr_t addr = (target_addr_t)wide_addr;
4450 /* Arg 3: Number of elements to read */
4451 e = Jim_GetLong(interp, argv[3], &l);
4452 if (e != JIM_OK)
4453 return e;
4454 size_t len = l;
4456 /* Arg 4: phys */
4457 bool is_phys = false;
4458 if (argc > 4) {
4459 int str_len = 0;
4460 const char *phys = Jim_GetString(argv[4], &str_len);
4461 if (!strncmp(phys, "phys", str_len))
4462 is_phys = true;
4463 else
4464 return JIM_ERR;
4467 /* Argument checks */
4468 if (len == 0) {
4469 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4470 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
4471 return JIM_ERR;
4473 if ((addr + (len * width)) < addr) {
4474 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4475 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
4476 return JIM_ERR;
4478 if (len > 65536) {
4479 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4480 Jim_AppendStrings(interp, Jim_GetResult(interp),
4481 "mem2array: too large read request, exceeds 64K items", NULL);
4482 return JIM_ERR;
4485 if ((width == 1) ||
4486 ((width == 2) && ((addr & 1) == 0)) ||
4487 ((width == 4) && ((addr & 3) == 0)) ||
4488 ((width == 8) && ((addr & 7) == 0))) {
4489 /* alignment correct */
4490 } else {
4491 char buf[100];
4492 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4493 sprintf(buf, "mem2array address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4494 addr,
4495 width);
4496 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4497 return JIM_ERR;
4500 /* Transfer loop */
4502 /* index counter */
4503 size_t idx = 0;
4505 const size_t buffersize = 4096;
4506 uint8_t *buffer = malloc(buffersize);
4507 if (!buffer)
4508 return JIM_ERR;
4510 /* assume ok */
4511 e = JIM_OK;
4512 while (len) {
4513 /* Slurp... in buffer size chunks */
4514 const unsigned int max_chunk_len = buffersize / width;
4515 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4517 int retval;
4518 if (is_phys)
4519 retval = target_read_phys_memory(target, addr, width, chunk_len, buffer);
4520 else
4521 retval = target_read_memory(target, addr, width, chunk_len, buffer);
4522 if (retval != ERROR_OK) {
4523 /* BOO !*/
4524 LOG_ERROR("mem2array: Read @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4525 addr,
4526 width,
4527 chunk_len);
4528 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4529 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
4530 e = JIM_ERR;
4531 break;
4532 } else {
4533 for (size_t i = 0; i < chunk_len ; i++, idx++) {
4534 uint64_t v = 0;
4535 switch (width) {
4536 case 8:
4537 v = target_buffer_get_u64(target, &buffer[i*width]);
4538 break;
4539 case 4:
4540 v = target_buffer_get_u32(target, &buffer[i*width]);
4541 break;
4542 case 2:
4543 v = target_buffer_get_u16(target, &buffer[i*width]);
4544 break;
4545 case 1:
4546 v = buffer[i] & 0x0ff;
4547 break;
4549 new_u64_array_element(interp, varname, idx, v);
4551 len -= chunk_len;
4552 addr += chunk_len * width;
4556 free(buffer);
4558 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4560 return e;
4563 COMMAND_HANDLER(handle_target_read_memory)
4566 * CMD_ARGV[0] = memory address
4567 * CMD_ARGV[1] = desired element width in bits
4568 * CMD_ARGV[2] = number of elements to read
4569 * CMD_ARGV[3] = optional "phys"
4572 if (CMD_ARGC < 3 || CMD_ARGC > 4)
4573 return ERROR_COMMAND_SYNTAX_ERROR;
4575 /* Arg 1: Memory address. */
4576 target_addr_t addr;
4577 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[0], addr);
4579 /* Arg 2: Bit width of one element. */
4580 unsigned int width_bits;
4581 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], width_bits);
4583 /* Arg 3: Number of elements to read. */
4584 unsigned int count;
4585 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
4587 /* Arg 4: Optional 'phys'. */
4588 bool is_phys = false;
4589 if (CMD_ARGC == 4) {
4590 if (strcmp(CMD_ARGV[3], "phys")) {
4591 command_print(CMD, "invalid argument '%s', must be 'phys'", CMD_ARGV[3]);
4592 return ERROR_COMMAND_ARGUMENT_INVALID;
4595 is_phys = true;
4598 switch (width_bits) {
4599 case 8:
4600 case 16:
4601 case 32:
4602 case 64:
4603 break;
4604 default:
4605 command_print(CMD, "invalid width, must be 8, 16, 32 or 64");
4606 return ERROR_COMMAND_ARGUMENT_INVALID;
4609 const unsigned int width = width_bits / 8;
4611 if ((addr + (count * width)) < addr) {
4612 command_print(CMD, "read_memory: addr + count wraps to zero");
4613 return ERROR_COMMAND_ARGUMENT_INVALID;
4616 if (count > 65536) {
4617 command_print(CMD, "read_memory: too large read request, exceeds 64K elements");
4618 return ERROR_COMMAND_ARGUMENT_INVALID;
4621 struct target *target = get_current_target(CMD_CTX);
4623 const size_t buffersize = 4096;
4624 uint8_t *buffer = malloc(buffersize);
4626 if (!buffer) {
4627 LOG_ERROR("Failed to allocate memory");
4628 return ERROR_FAIL;
4631 char *separator = "";
4632 while (count > 0) {
4633 const unsigned int max_chunk_len = buffersize / width;
4634 const size_t chunk_len = MIN(count, max_chunk_len);
4636 int retval;
4638 if (is_phys)
4639 retval = target_read_phys_memory(target, addr, width, chunk_len, buffer);
4640 else
4641 retval = target_read_memory(target, addr, width, chunk_len, buffer);
4643 if (retval != ERROR_OK) {
4644 LOG_DEBUG("read_memory: read at " TARGET_ADDR_FMT " with width=%u and count=%zu failed",
4645 addr, width_bits, chunk_len);
4647 * FIXME: we append the errmsg to the list of value already read.
4648 * Add a way to flush and replace old output, but LOG_DEBUG() it
4650 command_print(CMD, "read_memory: failed to read memory");
4651 free(buffer);
4652 return retval;
4655 for (size_t i = 0; i < chunk_len ; i++) {
4656 uint64_t v = 0;
4658 switch (width) {
4659 case 8:
4660 v = target_buffer_get_u64(target, &buffer[i * width]);
4661 break;
4662 case 4:
4663 v = target_buffer_get_u32(target, &buffer[i * width]);
4664 break;
4665 case 2:
4666 v = target_buffer_get_u16(target, &buffer[i * width]);
4667 break;
4668 case 1:
4669 v = buffer[i];
4670 break;
4673 command_print_sameline(CMD, "%s0x%" PRIx64, separator, v);
4674 separator = " ";
4677 count -= chunk_len;
4678 addr += chunk_len * width;
4681 free(buffer);
4683 return ERROR_OK;
4686 static int get_u64_array_element(Jim_Interp *interp, const char *varname, size_t idx, uint64_t *val)
4688 char *namebuf = alloc_printf("%s(%zu)", varname, idx);
4689 if (!namebuf)
4690 return JIM_ERR;
4692 Jim_Obj *obj_name = Jim_NewStringObj(interp, namebuf, -1);
4693 if (!obj_name) {
4694 free(namebuf);
4695 return JIM_ERR;
4698 Jim_IncrRefCount(obj_name);
4699 Jim_Obj *obj_val = Jim_GetVariable(interp, obj_name, JIM_ERRMSG);
4700 Jim_DecrRefCount(interp, obj_name);
4701 free(namebuf);
4702 if (!obj_val)
4703 return JIM_ERR;
4705 jim_wide wide_val;
4706 int result = Jim_GetWide(interp, obj_val, &wide_val);
4707 *val = wide_val;
4708 return result;
4711 static int target_array2mem(Jim_Interp *interp, struct target *target,
4712 int argc, Jim_Obj *const *argv)
4714 int e;
4716 LOG_WARNING("DEPRECATED! use 'write_memory' not 'array2mem'");
4718 /* argv[0] = name of array from which to read the data
4719 * argv[1] = desired element width in bits
4720 * argv[2] = memory address
4721 * argv[3] = number of elements to write
4722 * argv[4] = optional "phys"
4724 if (argc < 4 || argc > 5) {
4725 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4726 return JIM_ERR;
4729 /* Arg 0: Name of the array variable */
4730 const char *varname = Jim_GetString(argv[0], NULL);
4732 /* Arg 1: Bit width of one element */
4733 long l;
4734 e = Jim_GetLong(interp, argv[1], &l);
4735 if (e != JIM_OK)
4736 return e;
4737 const unsigned int width_bits = l;
4739 if (width_bits != 8 &&
4740 width_bits != 16 &&
4741 width_bits != 32 &&
4742 width_bits != 64) {
4743 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4744 Jim_AppendStrings(interp, Jim_GetResult(interp),
4745 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4746 return JIM_ERR;
4748 const unsigned int width = width_bits / 8;
4750 /* Arg 2: Memory address */
4751 jim_wide wide_addr;
4752 e = Jim_GetWide(interp, argv[2], &wide_addr);
4753 if (e != JIM_OK)
4754 return e;
4755 target_addr_t addr = (target_addr_t)wide_addr;
4757 /* Arg 3: Number of elements to write */
4758 e = Jim_GetLong(interp, argv[3], &l);
4759 if (e != JIM_OK)
4760 return e;
4761 size_t len = l;
4763 /* Arg 4: Phys */
4764 bool is_phys = false;
4765 if (argc > 4) {
4766 int str_len = 0;
4767 const char *phys = Jim_GetString(argv[4], &str_len);
4768 if (!strncmp(phys, "phys", str_len))
4769 is_phys = true;
4770 else
4771 return JIM_ERR;
4774 /* Argument checks */
4775 if (len == 0) {
4776 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4777 Jim_AppendStrings(interp, Jim_GetResult(interp),
4778 "array2mem: zero width read?", NULL);
4779 return JIM_ERR;
4782 if ((addr + (len * width)) < addr) {
4783 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4784 Jim_AppendStrings(interp, Jim_GetResult(interp),
4785 "array2mem: addr + len - wraps to zero?", NULL);
4786 return JIM_ERR;
4789 if (len > 65536) {
4790 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4791 Jim_AppendStrings(interp, Jim_GetResult(interp),
4792 "array2mem: too large memory write request, exceeds 64K items", NULL);
4793 return JIM_ERR;
4796 if ((width == 1) ||
4797 ((width == 2) && ((addr & 1) == 0)) ||
4798 ((width == 4) && ((addr & 3) == 0)) ||
4799 ((width == 8) && ((addr & 7) == 0))) {
4800 /* alignment correct */
4801 } else {
4802 char buf[100];
4803 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4804 sprintf(buf, "array2mem address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4805 addr,
4806 width);
4807 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4808 return JIM_ERR;
4811 /* Transfer loop */
4813 /* assume ok */
4814 e = JIM_OK;
4816 const size_t buffersize = 4096;
4817 uint8_t *buffer = malloc(buffersize);
4818 if (!buffer)
4819 return JIM_ERR;
4821 /* index counter */
4822 size_t idx = 0;
4824 while (len) {
4825 /* Slurp... in buffer size chunks */
4826 const unsigned int max_chunk_len = buffersize / width;
4828 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4830 /* Fill the buffer */
4831 for (size_t i = 0; i < chunk_len; i++, idx++) {
4832 uint64_t v = 0;
4833 if (get_u64_array_element(interp, varname, idx, &v) != JIM_OK) {
4834 free(buffer);
4835 return JIM_ERR;
4837 switch (width) {
4838 case 8:
4839 target_buffer_set_u64(target, &buffer[i * width], v);
4840 break;
4841 case 4:
4842 target_buffer_set_u32(target, &buffer[i * width], v);
4843 break;
4844 case 2:
4845 target_buffer_set_u16(target, &buffer[i * width], v);
4846 break;
4847 case 1:
4848 buffer[i] = v & 0x0ff;
4849 break;
4852 len -= chunk_len;
4854 /* Write the buffer to memory */
4855 int retval;
4856 if (is_phys)
4857 retval = target_write_phys_memory(target, addr, width, chunk_len, buffer);
4858 else
4859 retval = target_write_memory(target, addr, width, chunk_len, buffer);
4860 if (retval != ERROR_OK) {
4861 /* BOO !*/
4862 LOG_ERROR("array2mem: Write @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4863 addr,
4864 width,
4865 chunk_len);
4866 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4867 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4868 e = JIM_ERR;
4869 break;
4871 addr += chunk_len * width;
4874 free(buffer);
4876 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4878 return e;
4881 static int target_jim_write_memory(Jim_Interp *interp, int argc,
4882 Jim_Obj * const *argv)
4885 * argv[1] = memory address
4886 * argv[2] = desired element width in bits
4887 * argv[3] = list of data to write
4888 * argv[4] = optional "phys"
4891 if (argc < 4 || argc > 5) {
4892 Jim_WrongNumArgs(interp, 1, argv, "address width data ['phys']");
4893 return JIM_ERR;
4896 /* Arg 1: Memory address. */
4897 int e;
4898 jim_wide wide_addr;
4899 e = Jim_GetWide(interp, argv[1], &wide_addr);
4901 if (e != JIM_OK)
4902 return e;
4904 target_addr_t addr = (target_addr_t)wide_addr;
4906 /* Arg 2: Bit width of one element. */
4907 long l;
4908 e = Jim_GetLong(interp, argv[2], &l);
4910 if (e != JIM_OK)
4911 return e;
4913 const unsigned int width_bits = l;
4914 size_t count = Jim_ListLength(interp, argv[3]);
4916 /* Arg 4: Optional 'phys'. */
4917 bool is_phys = false;
4919 if (argc > 4) {
4920 const char *phys = Jim_GetString(argv[4], NULL);
4922 if (strcmp(phys, "phys")) {
4923 Jim_SetResultFormatted(interp, "invalid argument '%s', must be 'phys'", phys);
4924 return JIM_ERR;
4927 is_phys = true;
4930 switch (width_bits) {
4931 case 8:
4932 case 16:
4933 case 32:
4934 case 64:
4935 break;
4936 default:
4937 Jim_SetResultString(interp, "invalid width, must be 8, 16, 32 or 64", -1);
4938 return JIM_ERR;
4941 const unsigned int width = width_bits / 8;
4943 if ((addr + (count * width)) < addr) {
4944 Jim_SetResultString(interp, "write_memory: addr + len wraps to zero", -1);
4945 return JIM_ERR;
4948 if (count > 65536) {
4949 Jim_SetResultString(interp, "write_memory: too large memory write request, exceeds 64K elements", -1);
4950 return JIM_ERR;
4953 struct command_context *cmd_ctx = current_command_context(interp);
4954 assert(cmd_ctx != NULL);
4955 struct target *target = get_current_target(cmd_ctx);
4957 const size_t buffersize = 4096;
4958 uint8_t *buffer = malloc(buffersize);
4960 if (!buffer) {
4961 LOG_ERROR("Failed to allocate memory");
4962 return JIM_ERR;
4965 size_t j = 0;
4967 while (count > 0) {
4968 const unsigned int max_chunk_len = buffersize / width;
4969 const size_t chunk_len = MIN(count, max_chunk_len);
4971 for (size_t i = 0; i < chunk_len; i++, j++) {
4972 Jim_Obj *tmp = Jim_ListGetIndex(interp, argv[3], j);
4973 jim_wide element_wide;
4974 Jim_GetWide(interp, tmp, &element_wide);
4976 const uint64_t v = element_wide;
4978 switch (width) {
4979 case 8:
4980 target_buffer_set_u64(target, &buffer[i * width], v);
4981 break;
4982 case 4:
4983 target_buffer_set_u32(target, &buffer[i * width], v);
4984 break;
4985 case 2:
4986 target_buffer_set_u16(target, &buffer[i * width], v);
4987 break;
4988 case 1:
4989 buffer[i] = v & 0x0ff;
4990 break;
4994 count -= chunk_len;
4996 int retval;
4998 if (is_phys)
4999 retval = target_write_phys_memory(target, addr, width, chunk_len, buffer);
5000 else
5001 retval = target_write_memory(target, addr, width, chunk_len, buffer);
5003 if (retval != ERROR_OK) {
5004 LOG_ERROR("write_memory: write at " TARGET_ADDR_FMT " with width=%u and count=%zu failed",
5005 addr, width_bits, chunk_len);
5006 Jim_SetResultString(interp, "write_memory: failed to write memory", -1);
5007 e = JIM_ERR;
5008 break;
5011 addr += chunk_len * width;
5014 free(buffer);
5016 return e;
5019 /* FIX? should we propagate errors here rather than printing them
5020 * and continuing?
5022 void target_handle_event(struct target *target, enum target_event e)
5024 struct target_event_action *teap;
5025 int retval;
5027 for (teap = target->event_action; teap; teap = teap->next) {
5028 if (teap->event == e) {
5029 LOG_DEBUG("target(%d): %s (%s) event: %d (%s) action: %s",
5030 target->target_number,
5031 target_name(target),
5032 target_type_name(target),
5034 target_event_name(e),
5035 Jim_GetString(teap->body, NULL));
5037 /* Override current target by the target an event
5038 * is issued from (lot of scripts need it).
5039 * Return back to previous override as soon
5040 * as the handler processing is done */
5041 struct command_context *cmd_ctx = current_command_context(teap->interp);
5042 struct target *saved_target_override = cmd_ctx->current_target_override;
5043 cmd_ctx->current_target_override = target;
5045 retval = Jim_EvalObj(teap->interp, teap->body);
5047 cmd_ctx->current_target_override = saved_target_override;
5049 if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
5050 return;
5052 if (retval == JIM_RETURN)
5053 retval = teap->interp->returnCode;
5055 if (retval != JIM_OK) {
5056 Jim_MakeErrorMessage(teap->interp);
5057 LOG_USER("Error executing event %s on target %s:\n%s",
5058 target_event_name(e),
5059 target_name(target),
5060 Jim_GetString(Jim_GetResult(teap->interp), NULL));
5061 /* clean both error code and stacktrace before return */
5062 Jim_Eval(teap->interp, "error \"\" \"\"");
5068 static int target_jim_get_reg(Jim_Interp *interp, int argc,
5069 Jim_Obj * const *argv)
5071 bool force = false;
5073 if (argc == 3) {
5074 const char *option = Jim_GetString(argv[1], NULL);
5076 if (!strcmp(option, "-force")) {
5077 argc--;
5078 argv++;
5079 force = true;
5080 } else {
5081 Jim_SetResultFormatted(interp, "invalid option '%s'", option);
5082 return JIM_ERR;
5086 if (argc != 2) {
5087 Jim_WrongNumArgs(interp, 1, argv, "[-force] list");
5088 return JIM_ERR;
5091 const int length = Jim_ListLength(interp, argv[1]);
5093 Jim_Obj *result_dict = Jim_NewDictObj(interp, NULL, 0);
5095 if (!result_dict)
5096 return JIM_ERR;
5098 struct command_context *cmd_ctx = current_command_context(interp);
5099 assert(cmd_ctx != NULL);
5100 const struct target *target = get_current_target(cmd_ctx);
5102 for (int i = 0; i < length; i++) {
5103 Jim_Obj *elem = Jim_ListGetIndex(interp, argv[1], i);
5105 if (!elem)
5106 return JIM_ERR;
5108 const char *reg_name = Jim_String(elem);
5110 struct reg *reg = register_get_by_name(target->reg_cache, reg_name,
5111 false);
5113 if (!reg || !reg->exist) {
5114 Jim_SetResultFormatted(interp, "unknown register '%s'", reg_name);
5115 return JIM_ERR;
5118 if (force) {
5119 int retval = reg->type->get(reg);
5121 if (retval != ERROR_OK) {
5122 Jim_SetResultFormatted(interp, "failed to read register '%s'",
5123 reg_name);
5124 return JIM_ERR;
5128 char *reg_value = buf_to_hex_str(reg->value, reg->size);
5130 if (!reg_value) {
5131 LOG_ERROR("Failed to allocate memory");
5132 return JIM_ERR;
5135 char *tmp = alloc_printf("0x%s", reg_value);
5137 free(reg_value);
5139 if (!tmp) {
5140 LOG_ERROR("Failed to allocate memory");
5141 return JIM_ERR;
5144 Jim_DictAddElement(interp, result_dict, elem,
5145 Jim_NewStringObj(interp, tmp, -1));
5147 free(tmp);
5150 Jim_SetResult(interp, result_dict);
5152 return JIM_OK;
5155 static int target_jim_set_reg(Jim_Interp *interp, int argc,
5156 Jim_Obj * const *argv)
5158 if (argc != 2) {
5159 Jim_WrongNumArgs(interp, 1, argv, "dict");
5160 return JIM_ERR;
5163 int tmp;
5164 #if JIM_VERSION >= 80
5165 Jim_Obj **dict = Jim_DictPairs(interp, argv[1], &tmp);
5167 if (!dict)
5168 return JIM_ERR;
5169 #else
5170 Jim_Obj **dict;
5171 int ret = Jim_DictPairs(interp, argv[1], &dict, &tmp);
5173 if (ret != JIM_OK)
5174 return ret;
5175 #endif
5177 const unsigned int length = tmp;
5178 struct command_context *cmd_ctx = current_command_context(interp);
5179 assert(cmd_ctx);
5180 const struct target *target = get_current_target(cmd_ctx);
5182 for (unsigned int i = 0; i < length; i += 2) {
5183 const char *reg_name = Jim_String(dict[i]);
5184 const char *reg_value = Jim_String(dict[i + 1]);
5185 struct reg *reg = register_get_by_name(target->reg_cache, reg_name,
5186 false);
5188 if (!reg || !reg->exist) {
5189 Jim_SetResultFormatted(interp, "unknown register '%s'", reg_name);
5190 return JIM_ERR;
5193 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
5195 if (!buf) {
5196 LOG_ERROR("Failed to allocate memory");
5197 return JIM_ERR;
5200 str_to_buf(reg_value, strlen(reg_value), buf, reg->size, 0);
5201 int retval = reg->type->set(reg, buf);
5202 free(buf);
5204 if (retval != ERROR_OK) {
5205 Jim_SetResultFormatted(interp, "failed to set '%s' to register '%s'",
5206 reg_value, reg_name);
5207 return JIM_ERR;
5211 return JIM_OK;
5215 * Returns true only if the target has a handler for the specified event.
5217 bool target_has_event_action(struct target *target, enum target_event event)
5219 struct target_event_action *teap;
5221 for (teap = target->event_action; teap; teap = teap->next) {
5222 if (teap->event == event)
5223 return true;
5225 return false;
5228 enum target_cfg_param {
5229 TCFG_TYPE,
5230 TCFG_EVENT,
5231 TCFG_WORK_AREA_VIRT,
5232 TCFG_WORK_AREA_PHYS,
5233 TCFG_WORK_AREA_SIZE,
5234 TCFG_WORK_AREA_BACKUP,
5235 TCFG_ENDIAN,
5236 TCFG_COREID,
5237 TCFG_CHAIN_POSITION,
5238 TCFG_DBGBASE,
5239 TCFG_RTOS,
5240 TCFG_DEFER_EXAMINE,
5241 TCFG_GDB_PORT,
5242 TCFG_GDB_MAX_CONNECTIONS,
5245 static struct jim_nvp nvp_config_opts[] = {
5246 { .name = "-type", .value = TCFG_TYPE },
5247 { .name = "-event", .value = TCFG_EVENT },
5248 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
5249 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
5250 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
5251 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
5252 { .name = "-endian", .value = TCFG_ENDIAN },
5253 { .name = "-coreid", .value = TCFG_COREID },
5254 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
5255 { .name = "-dbgbase", .value = TCFG_DBGBASE },
5256 { .name = "-rtos", .value = TCFG_RTOS },
5257 { .name = "-defer-examine", .value = TCFG_DEFER_EXAMINE },
5258 { .name = "-gdb-port", .value = TCFG_GDB_PORT },
5259 { .name = "-gdb-max-connections", .value = TCFG_GDB_MAX_CONNECTIONS },
5260 { .name = NULL, .value = -1 }
5263 static int target_configure(struct jim_getopt_info *goi, struct target *target)
5265 struct jim_nvp *n;
5266 Jim_Obj *o;
5267 jim_wide w;
5268 int e;
5270 /* parse config or cget options ... */
5271 while (goi->argc > 0) {
5272 Jim_SetEmptyResult(goi->interp);
5273 /* jim_getopt_debug(goi); */
5275 if (target->type->target_jim_configure) {
5276 /* target defines a configure function */
5277 /* target gets first dibs on parameters */
5278 e = (*(target->type->target_jim_configure))(target, goi);
5279 if (e == JIM_OK) {
5280 /* more? */
5281 continue;
5283 if (e == JIM_ERR) {
5284 /* An error */
5285 return e;
5287 /* otherwise we 'continue' below */
5289 e = jim_getopt_nvp(goi, nvp_config_opts, &n);
5290 if (e != JIM_OK) {
5291 jim_getopt_nvp_unknown(goi, nvp_config_opts, 0);
5292 return e;
5294 switch (n->value) {
5295 case TCFG_TYPE:
5296 /* not settable */
5297 if (goi->isconfigure) {
5298 Jim_SetResultFormatted(goi->interp,
5299 "not settable: %s", n->name);
5300 return JIM_ERR;
5301 } else {
5302 no_params:
5303 if (goi->argc != 0) {
5304 Jim_WrongNumArgs(goi->interp,
5305 goi->argc, goi->argv,
5306 "NO PARAMS");
5307 return JIM_ERR;
5310 Jim_SetResultString(goi->interp,
5311 target_type_name(target), -1);
5312 /* loop for more */
5313 break;
5314 case TCFG_EVENT:
5315 if (goi->argc == 0) {
5316 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
5317 return JIM_ERR;
5320 e = jim_getopt_nvp(goi, nvp_target_event, &n);
5321 if (e != JIM_OK) {
5322 jim_getopt_nvp_unknown(goi, nvp_target_event, 1);
5323 return e;
5326 if (goi->isconfigure) {
5327 if (goi->argc != 1) {
5328 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
5329 return JIM_ERR;
5331 } else {
5332 if (goi->argc != 0) {
5333 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
5334 return JIM_ERR;
5339 struct target_event_action *teap;
5341 teap = target->event_action;
5342 /* replace existing? */
5343 while (teap) {
5344 if (teap->event == (enum target_event)n->value)
5345 break;
5346 teap = teap->next;
5349 if (goi->isconfigure) {
5350 /* START_DEPRECATED_TPIU */
5351 if (n->value == TARGET_EVENT_TRACE_CONFIG)
5352 LOG_INFO("DEPRECATED target event %s; use TPIU events {pre,post}-{enable,disable}", n->name);
5353 /* END_DEPRECATED_TPIU */
5355 bool replace = true;
5356 if (!teap) {
5357 /* create new */
5358 teap = calloc(1, sizeof(*teap));
5359 replace = false;
5361 teap->event = n->value;
5362 teap->interp = goi->interp;
5363 jim_getopt_obj(goi, &o);
5364 if (teap->body)
5365 Jim_DecrRefCount(teap->interp, teap->body);
5366 teap->body = Jim_DuplicateObj(goi->interp, o);
5368 * FIXME:
5369 * Tcl/TK - "tk events" have a nice feature.
5370 * See the "BIND" command.
5371 * We should support that here.
5372 * You can specify %X and %Y in the event code.
5373 * The idea is: %T - target name.
5374 * The idea is: %N - target number
5375 * The idea is: %E - event name.
5377 Jim_IncrRefCount(teap->body);
5379 if (!replace) {
5380 /* add to head of event list */
5381 teap->next = target->event_action;
5382 target->event_action = teap;
5384 Jim_SetEmptyResult(goi->interp);
5385 } else {
5386 /* get */
5387 if (!teap)
5388 Jim_SetEmptyResult(goi->interp);
5389 else
5390 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
5393 /* loop for more */
5394 break;
5396 case TCFG_WORK_AREA_VIRT:
5397 if (goi->isconfigure) {
5398 target_free_all_working_areas(target);
5399 e = jim_getopt_wide(goi, &w);
5400 if (e != JIM_OK)
5401 return e;
5402 target->working_area_virt = w;
5403 target->working_area_virt_spec = true;
5404 } else {
5405 if (goi->argc != 0)
5406 goto no_params;
5408 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
5409 /* loop for more */
5410 break;
5412 case TCFG_WORK_AREA_PHYS:
5413 if (goi->isconfigure) {
5414 target_free_all_working_areas(target);
5415 e = jim_getopt_wide(goi, &w);
5416 if (e != JIM_OK)
5417 return e;
5418 target->working_area_phys = w;
5419 target->working_area_phys_spec = true;
5420 } else {
5421 if (goi->argc != 0)
5422 goto no_params;
5424 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
5425 /* loop for more */
5426 break;
5428 case TCFG_WORK_AREA_SIZE:
5429 if (goi->isconfigure) {
5430 target_free_all_working_areas(target);
5431 e = jim_getopt_wide(goi, &w);
5432 if (e != JIM_OK)
5433 return e;
5434 target->working_area_size = w;
5435 } else {
5436 if (goi->argc != 0)
5437 goto no_params;
5439 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
5440 /* loop for more */
5441 break;
5443 case TCFG_WORK_AREA_BACKUP:
5444 if (goi->isconfigure) {
5445 target_free_all_working_areas(target);
5446 e = jim_getopt_wide(goi, &w);
5447 if (e != JIM_OK)
5448 return e;
5449 /* make this exactly 1 or 0 */
5450 target->backup_working_area = (!!w);
5451 } else {
5452 if (goi->argc != 0)
5453 goto no_params;
5455 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
5456 /* loop for more e*/
5457 break;
5460 case TCFG_ENDIAN:
5461 if (goi->isconfigure) {
5462 e = jim_getopt_nvp(goi, nvp_target_endian, &n);
5463 if (e != JIM_OK) {
5464 jim_getopt_nvp_unknown(goi, nvp_target_endian, 1);
5465 return e;
5467 target->endianness = n->value;
5468 } else {
5469 if (goi->argc != 0)
5470 goto no_params;
5472 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5473 if (!n->name) {
5474 target->endianness = TARGET_LITTLE_ENDIAN;
5475 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5477 Jim_SetResultString(goi->interp, n->name, -1);
5478 /* loop for more */
5479 break;
5481 case TCFG_COREID:
5482 if (goi->isconfigure) {
5483 e = jim_getopt_wide(goi, &w);
5484 if (e != JIM_OK)
5485 return e;
5486 target->coreid = (int32_t)w;
5487 } else {
5488 if (goi->argc != 0)
5489 goto no_params;
5491 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->coreid));
5492 /* loop for more */
5493 break;
5495 case TCFG_CHAIN_POSITION:
5496 if (goi->isconfigure) {
5497 Jim_Obj *o_t;
5498 struct jtag_tap *tap;
5500 if (target->has_dap) {
5501 Jim_SetResultString(goi->interp,
5502 "target requires -dap parameter instead of -chain-position!", -1);
5503 return JIM_ERR;
5506 target_free_all_working_areas(target);
5507 e = jim_getopt_obj(goi, &o_t);
5508 if (e != JIM_OK)
5509 return e;
5510 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
5511 if (!tap)
5512 return JIM_ERR;
5513 target->tap = tap;
5514 target->tap_configured = true;
5515 } else {
5516 if (goi->argc != 0)
5517 goto no_params;
5519 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
5520 /* loop for more e*/
5521 break;
5522 case TCFG_DBGBASE:
5523 if (goi->isconfigure) {
5524 e = jim_getopt_wide(goi, &w);
5525 if (e != JIM_OK)
5526 return e;
5527 target->dbgbase = (uint32_t)w;
5528 target->dbgbase_set = true;
5529 } else {
5530 if (goi->argc != 0)
5531 goto no_params;
5533 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
5534 /* loop for more */
5535 break;
5536 case TCFG_RTOS:
5537 /* RTOS */
5539 int result = rtos_create(goi, target);
5540 if (result != JIM_OK)
5541 return result;
5543 /* loop for more */
5544 break;
5546 case TCFG_DEFER_EXAMINE:
5547 /* DEFER_EXAMINE */
5548 target->defer_examine = true;
5549 /* loop for more */
5550 break;
5552 case TCFG_GDB_PORT:
5553 if (goi->isconfigure) {
5554 struct command_context *cmd_ctx = current_command_context(goi->interp);
5555 if (cmd_ctx->mode != COMMAND_CONFIG) {
5556 Jim_SetResultString(goi->interp, "-gdb-port must be configured before 'init'", -1);
5557 return JIM_ERR;
5560 const char *s;
5561 e = jim_getopt_string(goi, &s, NULL);
5562 if (e != JIM_OK)
5563 return e;
5564 free(target->gdb_port_override);
5565 target->gdb_port_override = strdup(s);
5566 } else {
5567 if (goi->argc != 0)
5568 goto no_params;
5570 Jim_SetResultString(goi->interp, target->gdb_port_override ? target->gdb_port_override : "undefined", -1);
5571 /* loop for more */
5572 break;
5574 case TCFG_GDB_MAX_CONNECTIONS:
5575 if (goi->isconfigure) {
5576 struct command_context *cmd_ctx = current_command_context(goi->interp);
5577 if (cmd_ctx->mode != COMMAND_CONFIG) {
5578 Jim_SetResultString(goi->interp, "-gdb-max-connections must be configured before 'init'", -1);
5579 return JIM_ERR;
5582 e = jim_getopt_wide(goi, &w);
5583 if (e != JIM_OK)
5584 return e;
5585 target->gdb_max_connections = (w < 0) ? CONNECTION_LIMIT_UNLIMITED : (int)w;
5586 } else {
5587 if (goi->argc != 0)
5588 goto no_params;
5590 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->gdb_max_connections));
5591 break;
5593 } /* while (goi->argc) */
5596 /* done - we return */
5597 return JIM_OK;
5600 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5602 struct command *c = jim_to_command(interp);
5603 struct jim_getopt_info goi;
5605 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5606 goi.isconfigure = !strcmp(c->name, "configure");
5607 if (goi.argc < 1) {
5608 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5609 "missing: -option ...");
5610 return JIM_ERR;
5612 struct command_context *cmd_ctx = current_command_context(interp);
5613 assert(cmd_ctx);
5614 struct target *target = get_current_target(cmd_ctx);
5615 return target_configure(&goi, target);
5618 static int jim_target_mem2array(Jim_Interp *interp,
5619 int argc, Jim_Obj *const *argv)
5621 struct command_context *cmd_ctx = current_command_context(interp);
5622 assert(cmd_ctx);
5623 struct target *target = get_current_target(cmd_ctx);
5624 return target_mem2array(interp, target, argc - 1, argv + 1);
5627 static int jim_target_array2mem(Jim_Interp *interp,
5628 int argc, Jim_Obj *const *argv)
5630 struct command_context *cmd_ctx = current_command_context(interp);
5631 assert(cmd_ctx);
5632 struct target *target = get_current_target(cmd_ctx);
5633 return target_array2mem(interp, target, argc - 1, argv + 1);
5636 COMMAND_HANDLER(handle_target_examine)
5638 bool allow_defer = false;
5640 if (CMD_ARGC > 1)
5641 return ERROR_COMMAND_SYNTAX_ERROR;
5643 if (CMD_ARGC == 1) {
5644 if (strcmp(CMD_ARGV[0], "allow-defer"))
5645 return ERROR_COMMAND_ARGUMENT_INVALID;
5646 allow_defer = true;
5649 struct target *target = get_current_target(CMD_CTX);
5650 if (!target->tap->enabled) {
5651 command_print(CMD, "[TAP is disabled]");
5652 return ERROR_FAIL;
5655 if (allow_defer && target->defer_examine) {
5656 LOG_INFO("Deferring arp_examine of %s", target_name(target));
5657 LOG_INFO("Use arp_examine command to examine it manually!");
5658 return ERROR_OK;
5661 int retval = target->type->examine(target);
5662 if (retval != ERROR_OK) {
5663 target_reset_examined(target);
5664 return retval;
5667 target_set_examined(target);
5669 return ERROR_OK;
5672 COMMAND_HANDLER(handle_target_was_examined)
5674 if (CMD_ARGC != 0)
5675 return ERROR_COMMAND_SYNTAX_ERROR;
5677 struct target *target = get_current_target(CMD_CTX);
5679 command_print(CMD, "%d", target_was_examined(target) ? 1 : 0);
5681 return ERROR_OK;
5684 COMMAND_HANDLER(handle_target_examine_deferred)
5686 if (CMD_ARGC != 0)
5687 return ERROR_COMMAND_SYNTAX_ERROR;
5689 struct target *target = get_current_target(CMD_CTX);
5691 command_print(CMD, "%d", target->defer_examine ? 1 : 0);
5693 return ERROR_OK;
5696 COMMAND_HANDLER(handle_target_halt_gdb)
5698 if (CMD_ARGC != 0)
5699 return ERROR_COMMAND_SYNTAX_ERROR;
5701 struct target *target = get_current_target(CMD_CTX);
5703 return target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
5706 COMMAND_HANDLER(handle_target_poll)
5708 if (CMD_ARGC != 0)
5709 return ERROR_COMMAND_SYNTAX_ERROR;
5711 struct target *target = get_current_target(CMD_CTX);
5712 if (!target->tap->enabled) {
5713 command_print(CMD, "[TAP is disabled]");
5714 return ERROR_FAIL;
5717 if (!(target_was_examined(target)))
5718 return ERROR_TARGET_NOT_EXAMINED;
5720 return target->type->poll(target);
5723 COMMAND_HANDLER(handle_target_reset)
5725 if (CMD_ARGC != 2)
5726 return ERROR_COMMAND_SYNTAX_ERROR;
5728 const struct nvp *n = nvp_name2value(nvp_assert, CMD_ARGV[0]);
5729 if (!n->name) {
5730 nvp_unknown_command_print(CMD, nvp_assert, NULL, CMD_ARGV[0]);
5731 return ERROR_COMMAND_ARGUMENT_INVALID;
5734 /* the halt or not param */
5735 int a;
5736 COMMAND_PARSE_NUMBER(int, CMD_ARGV[1], a);
5738 struct target *target = get_current_target(CMD_CTX);
5739 if (!target->tap->enabled) {
5740 command_print(CMD, "[TAP is disabled]");
5741 return ERROR_FAIL;
5744 if (!target->type->assert_reset || !target->type->deassert_reset) {
5745 command_print(CMD, "No target-specific reset for %s", target_name(target));
5746 return ERROR_FAIL;
5749 if (target->defer_examine)
5750 target_reset_examined(target);
5752 /* determine if we should halt or not. */
5753 target->reset_halt = (a != 0);
5754 /* When this happens - all workareas are invalid. */
5755 target_free_all_working_areas_restore(target, 0);
5757 /* do the assert */
5758 if (n->value == NVP_ASSERT)
5759 return target->type->assert_reset(target);
5760 return target->type->deassert_reset(target);
5763 COMMAND_HANDLER(handle_target_halt)
5765 if (CMD_ARGC != 0)
5766 return ERROR_COMMAND_SYNTAX_ERROR;
5768 struct target *target = get_current_target(CMD_CTX);
5769 if (!target->tap->enabled) {
5770 command_print(CMD, "[TAP is disabled]");
5771 return ERROR_FAIL;
5774 return target->type->halt(target);
5777 COMMAND_HANDLER(handle_target_wait_state)
5779 if (CMD_ARGC != 2)
5780 return ERROR_COMMAND_SYNTAX_ERROR;
5782 const struct nvp *n = nvp_name2value(nvp_target_state, CMD_ARGV[0]);
5783 if (!n->name) {
5784 nvp_unknown_command_print(CMD, nvp_target_state, NULL, CMD_ARGV[0]);
5785 return ERROR_COMMAND_ARGUMENT_INVALID;
5788 unsigned int a;
5789 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], a);
5791 struct target *target = get_current_target(CMD_CTX);
5792 if (!target->tap->enabled) {
5793 command_print(CMD, "[TAP is disabled]");
5794 return ERROR_FAIL;
5797 int retval = target_wait_state(target, n->value, a);
5798 if (retval != ERROR_OK) {
5799 command_print(CMD,
5800 "target: %s wait %s fails (%d) %s",
5801 target_name(target), n->name,
5802 retval, target_strerror_safe(retval));
5803 return retval;
5805 return ERROR_OK;
5807 /* List for human, Events defined for this target.
5808 * scripts/programs should use 'name cget -event NAME'
5810 COMMAND_HANDLER(handle_target_event_list)
5812 struct target *target = get_current_target(CMD_CTX);
5813 struct target_event_action *teap = target->event_action;
5815 command_print(CMD, "Event actions for target (%d) %s\n",
5816 target->target_number,
5817 target_name(target));
5818 command_print(CMD, "%-25s | Body", "Event");
5819 command_print(CMD, "------------------------- | "
5820 "----------------------------------------");
5821 while (teap) {
5822 command_print(CMD, "%-25s | %s",
5823 target_event_name(teap->event),
5824 Jim_GetString(teap->body, NULL));
5825 teap = teap->next;
5827 command_print(CMD, "***END***");
5828 return ERROR_OK;
5831 COMMAND_HANDLER(handle_target_current_state)
5833 if (CMD_ARGC != 0)
5834 return ERROR_COMMAND_SYNTAX_ERROR;
5836 struct target *target = get_current_target(CMD_CTX);
5838 command_print(CMD, "%s", target_state_name(target));
5840 return ERROR_OK;
5843 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5845 struct jim_getopt_info goi;
5846 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5847 if (goi.argc != 1) {
5848 const char *cmd_name = Jim_GetString(argv[0], NULL);
5849 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5850 return JIM_ERR;
5852 struct jim_nvp *n;
5853 int e = jim_getopt_nvp(&goi, nvp_target_event, &n);
5854 if (e != JIM_OK) {
5855 jim_getopt_nvp_unknown(&goi, nvp_target_event, 1);
5856 return e;
5858 struct command_context *cmd_ctx = current_command_context(interp);
5859 assert(cmd_ctx);
5860 struct target *target = get_current_target(cmd_ctx);
5861 target_handle_event(target, n->value);
5862 return JIM_OK;
5865 static const struct command_registration target_instance_command_handlers[] = {
5867 .name = "configure",
5868 .mode = COMMAND_ANY,
5869 .jim_handler = jim_target_configure,
5870 .help = "configure a new target for use",
5871 .usage = "[target_attribute ...]",
5874 .name = "cget",
5875 .mode = COMMAND_ANY,
5876 .jim_handler = jim_target_configure,
5877 .help = "returns the specified target attribute",
5878 .usage = "target_attribute",
5881 .name = "mwd",
5882 .handler = handle_mw_command,
5883 .mode = COMMAND_EXEC,
5884 .help = "Write 64-bit word(s) to target memory",
5885 .usage = "address data [count]",
5888 .name = "mww",
5889 .handler = handle_mw_command,
5890 .mode = COMMAND_EXEC,
5891 .help = "Write 32-bit word(s) to target memory",
5892 .usage = "address data [count]",
5895 .name = "mwh",
5896 .handler = handle_mw_command,
5897 .mode = COMMAND_EXEC,
5898 .help = "Write 16-bit half-word(s) to target memory",
5899 .usage = "address data [count]",
5902 .name = "mwb",
5903 .handler = handle_mw_command,
5904 .mode = COMMAND_EXEC,
5905 .help = "Write byte(s) to target memory",
5906 .usage = "address data [count]",
5909 .name = "mdd",
5910 .handler = handle_md_command,
5911 .mode = COMMAND_EXEC,
5912 .help = "Display target memory as 64-bit words",
5913 .usage = "address [count]",
5916 .name = "mdw",
5917 .handler = handle_md_command,
5918 .mode = COMMAND_EXEC,
5919 .help = "Display target memory as 32-bit words",
5920 .usage = "address [count]",
5923 .name = "mdh",
5924 .handler = handle_md_command,
5925 .mode = COMMAND_EXEC,
5926 .help = "Display target memory as 16-bit half-words",
5927 .usage = "address [count]",
5930 .name = "mdb",
5931 .handler = handle_md_command,
5932 .mode = COMMAND_EXEC,
5933 .help = "Display target memory as 8-bit bytes",
5934 .usage = "address [count]",
5937 .name = "array2mem",
5938 .mode = COMMAND_EXEC,
5939 .jim_handler = jim_target_array2mem,
5940 .help = "Writes Tcl array of 8/16/32 bit numbers "
5941 "to target memory",
5942 .usage = "arrayname bitwidth address count",
5945 .name = "mem2array",
5946 .mode = COMMAND_EXEC,
5947 .jim_handler = jim_target_mem2array,
5948 .help = "Loads Tcl array of 8/16/32 bit numbers "
5949 "from target memory",
5950 .usage = "arrayname bitwidth address count",
5953 .name = "get_reg",
5954 .mode = COMMAND_EXEC,
5955 .jim_handler = target_jim_get_reg,
5956 .help = "Get register values from the target",
5957 .usage = "list",
5960 .name = "set_reg",
5961 .mode = COMMAND_EXEC,
5962 .jim_handler = target_jim_set_reg,
5963 .help = "Set target register values",
5964 .usage = "dict",
5967 .name = "read_memory",
5968 .mode = COMMAND_EXEC,
5969 .handler = handle_target_read_memory,
5970 .help = "Read Tcl list of 8/16/32/64 bit numbers from target memory",
5971 .usage = "address width count ['phys']",
5974 .name = "write_memory",
5975 .mode = COMMAND_EXEC,
5976 .jim_handler = target_jim_write_memory,
5977 .help = "Write Tcl list of 8/16/32/64 bit numbers to target memory",
5978 .usage = "address width data ['phys']",
5981 .name = "eventlist",
5982 .handler = handle_target_event_list,
5983 .mode = COMMAND_EXEC,
5984 .help = "displays a table of events defined for this target",
5985 .usage = "",
5988 .name = "curstate",
5989 .mode = COMMAND_EXEC,
5990 .handler = handle_target_current_state,
5991 .help = "displays the current state of this target",
5992 .usage = "",
5995 .name = "arp_examine",
5996 .mode = COMMAND_EXEC,
5997 .handler = handle_target_examine,
5998 .help = "used internally for reset processing",
5999 .usage = "['allow-defer']",
6002 .name = "was_examined",
6003 .mode = COMMAND_EXEC,
6004 .handler = handle_target_was_examined,
6005 .help = "used internally for reset processing",
6006 .usage = "",
6009 .name = "examine_deferred",
6010 .mode = COMMAND_EXEC,
6011 .handler = handle_target_examine_deferred,
6012 .help = "used internally for reset processing",
6013 .usage = "",
6016 .name = "arp_halt_gdb",
6017 .mode = COMMAND_EXEC,
6018 .handler = handle_target_halt_gdb,
6019 .help = "used internally for reset processing to halt GDB",
6020 .usage = "",
6023 .name = "arp_poll",
6024 .mode = COMMAND_EXEC,
6025 .handler = handle_target_poll,
6026 .help = "used internally for reset processing",
6027 .usage = "",
6030 .name = "arp_reset",
6031 .mode = COMMAND_EXEC,
6032 .handler = handle_target_reset,
6033 .help = "used internally for reset processing",
6034 .usage = "'assert'|'deassert' halt",
6037 .name = "arp_halt",
6038 .mode = COMMAND_EXEC,
6039 .handler = handle_target_halt,
6040 .help = "used internally for reset processing",
6041 .usage = "",
6044 .name = "arp_waitstate",
6045 .mode = COMMAND_EXEC,
6046 .handler = handle_target_wait_state,
6047 .help = "used internally for reset processing",
6048 .usage = "statename timeoutmsecs",
6051 .name = "invoke-event",
6052 .mode = COMMAND_EXEC,
6053 .jim_handler = jim_target_invoke_event,
6054 .help = "invoke handler for specified event",
6055 .usage = "event_name",
6057 COMMAND_REGISTRATION_DONE
6060 static int target_create(struct jim_getopt_info *goi)
6062 Jim_Obj *new_cmd;
6063 Jim_Cmd *cmd;
6064 const char *cp;
6065 int e;
6066 int x;
6067 struct target *target;
6068 struct command_context *cmd_ctx;
6070 cmd_ctx = current_command_context(goi->interp);
6071 assert(cmd_ctx);
6073 if (goi->argc < 3) {
6074 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
6075 return JIM_ERR;
6078 /* COMMAND */
6079 jim_getopt_obj(goi, &new_cmd);
6080 /* does this command exist? */
6081 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_NONE);
6082 if (cmd) {
6083 cp = Jim_GetString(new_cmd, NULL);
6084 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
6085 return JIM_ERR;
6088 /* TYPE */
6089 e = jim_getopt_string(goi, &cp, NULL);
6090 if (e != JIM_OK)
6091 return e;
6092 struct transport *tr = get_current_transport();
6093 if (tr->override_target) {
6094 e = tr->override_target(&cp);
6095 if (e != ERROR_OK) {
6096 LOG_ERROR("The selected transport doesn't support this target");
6097 return JIM_ERR;
6099 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
6101 /* now does target type exist */
6102 for (x = 0 ; target_types[x] ; x++) {
6103 if (strcmp(cp, target_types[x]->name) == 0) {
6104 /* found */
6105 break;
6108 if (!target_types[x]) {
6109 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
6110 for (x = 0 ; target_types[x] ; x++) {
6111 if (target_types[x + 1]) {
6112 Jim_AppendStrings(goi->interp,
6113 Jim_GetResult(goi->interp),
6114 target_types[x]->name,
6115 ", ", NULL);
6116 } else {
6117 Jim_AppendStrings(goi->interp,
6118 Jim_GetResult(goi->interp),
6119 " or ",
6120 target_types[x]->name, NULL);
6123 return JIM_ERR;
6126 /* Create it */
6127 target = calloc(1, sizeof(struct target));
6128 if (!target) {
6129 LOG_ERROR("Out of memory");
6130 return JIM_ERR;
6133 /* set empty smp cluster */
6134 target->smp_targets = &empty_smp_targets;
6136 /* set target number */
6137 target->target_number = new_target_number();
6139 /* allocate memory for each unique target type */
6140 target->type = malloc(sizeof(struct target_type));
6141 if (!target->type) {
6142 LOG_ERROR("Out of memory");
6143 free(target);
6144 return JIM_ERR;
6147 memcpy(target->type, target_types[x], sizeof(struct target_type));
6149 /* default to first core, override with -coreid */
6150 target->coreid = 0;
6152 target->working_area = 0x0;
6153 target->working_area_size = 0x0;
6154 target->working_areas = NULL;
6155 target->backup_working_area = 0;
6157 target->state = TARGET_UNKNOWN;
6158 target->debug_reason = DBG_REASON_UNDEFINED;
6159 target->reg_cache = NULL;
6160 target->breakpoints = NULL;
6161 target->watchpoints = NULL;
6162 target->next = NULL;
6163 target->arch_info = NULL;
6165 target->verbose_halt_msg = true;
6167 target->halt_issued = false;
6169 /* initialize trace information */
6170 target->trace_info = calloc(1, sizeof(struct trace));
6171 if (!target->trace_info) {
6172 LOG_ERROR("Out of memory");
6173 free(target->type);
6174 free(target);
6175 return JIM_ERR;
6178 target->dbgmsg = NULL;
6179 target->dbg_msg_enabled = 0;
6181 target->endianness = TARGET_ENDIAN_UNKNOWN;
6183 target->rtos = NULL;
6184 target->rtos_auto_detect = false;
6186 target->gdb_port_override = NULL;
6187 target->gdb_max_connections = 1;
6189 /* Do the rest as "configure" options */
6190 goi->isconfigure = 1;
6191 e = target_configure(goi, target);
6193 if (e == JIM_OK) {
6194 if (target->has_dap) {
6195 if (!target->dap_configured) {
6196 Jim_SetResultString(goi->interp, "-dap ?name? required when creating target", -1);
6197 e = JIM_ERR;
6199 } else {
6200 if (!target->tap_configured) {
6201 Jim_SetResultString(goi->interp, "-chain-position ?name? required when creating target", -1);
6202 e = JIM_ERR;
6205 /* tap must be set after target was configured */
6206 if (!target->tap)
6207 e = JIM_ERR;
6210 if (e != JIM_OK) {
6211 rtos_destroy(target);
6212 free(target->gdb_port_override);
6213 free(target->trace_info);
6214 free(target->type);
6215 free(target);
6216 return e;
6219 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
6220 /* default endian to little if not specified */
6221 target->endianness = TARGET_LITTLE_ENDIAN;
6224 cp = Jim_GetString(new_cmd, NULL);
6225 target->cmd_name = strdup(cp);
6226 if (!target->cmd_name) {
6227 LOG_ERROR("Out of memory");
6228 rtos_destroy(target);
6229 free(target->gdb_port_override);
6230 free(target->trace_info);
6231 free(target->type);
6232 free(target);
6233 return JIM_ERR;
6236 if (target->type->target_create) {
6237 e = (*(target->type->target_create))(target, goi->interp);
6238 if (e != ERROR_OK) {
6239 LOG_DEBUG("target_create failed");
6240 free(target->cmd_name);
6241 rtos_destroy(target);
6242 free(target->gdb_port_override);
6243 free(target->trace_info);
6244 free(target->type);
6245 free(target);
6246 return JIM_ERR;
6250 /* create the target specific commands */
6251 if (target->type->commands) {
6252 e = register_commands(cmd_ctx, NULL, target->type->commands);
6253 if (e != ERROR_OK)
6254 LOG_ERROR("unable to register '%s' commands", cp);
6257 /* now - create the new target name command */
6258 const struct command_registration target_subcommands[] = {
6260 .chain = target_instance_command_handlers,
6263 .chain = target->type->commands,
6265 COMMAND_REGISTRATION_DONE
6267 const struct command_registration target_commands[] = {
6269 .name = cp,
6270 .mode = COMMAND_ANY,
6271 .help = "target command group",
6272 .usage = "",
6273 .chain = target_subcommands,
6275 COMMAND_REGISTRATION_DONE
6277 e = register_commands_override_target(cmd_ctx, NULL, target_commands, target);
6278 if (e != ERROR_OK) {
6279 if (target->type->deinit_target)
6280 target->type->deinit_target(target);
6281 free(target->cmd_name);
6282 rtos_destroy(target);
6283 free(target->gdb_port_override);
6284 free(target->trace_info);
6285 free(target->type);
6286 free(target);
6287 return JIM_ERR;
6290 /* append to end of list */
6291 append_to_list_all_targets(target);
6293 cmd_ctx->current_target = target;
6294 return JIM_OK;
6297 COMMAND_HANDLER(handle_target_current)
6299 if (CMD_ARGC != 0)
6300 return ERROR_COMMAND_SYNTAX_ERROR;
6302 struct target *target = get_current_target_or_null(CMD_CTX);
6303 if (target)
6304 command_print(CMD, "%s", target_name(target));
6306 return ERROR_OK;
6309 COMMAND_HANDLER(handle_target_types)
6311 if (CMD_ARGC != 0)
6312 return ERROR_COMMAND_SYNTAX_ERROR;
6314 for (unsigned int x = 0; target_types[x]; x++)
6315 command_print(CMD, "%s", target_types[x]->name);
6317 return ERROR_OK;
6320 COMMAND_HANDLER(handle_target_names)
6322 if (CMD_ARGC != 0)
6323 return ERROR_COMMAND_SYNTAX_ERROR;
6325 struct target *target = all_targets;
6326 while (target) {
6327 command_print(CMD, "%s", target_name(target));
6328 target = target->next;
6331 return ERROR_OK;
6334 static struct target_list *
6335 __attribute__((warn_unused_result))
6336 create_target_list_node(const char *targetname)
6338 struct target *target = get_target(targetname);
6339 LOG_DEBUG("%s ", targetname);
6340 if (!target)
6341 return NULL;
6343 struct target_list *new = malloc(sizeof(struct target_list));
6344 if (!new) {
6345 LOG_ERROR("Out of memory");
6346 return new;
6349 new->target = target;
6350 return new;
6353 static int get_target_with_common_rtos_type(struct command_invocation *cmd,
6354 struct list_head *lh, struct target **result)
6356 struct target *target = NULL;
6357 struct target_list *curr;
6358 foreach_smp_target(curr, lh) {
6359 struct rtos *curr_rtos = curr->target->rtos;
6360 if (curr_rtos) {
6361 if (target && target->rtos && target->rtos->type != curr_rtos->type) {
6362 command_print(cmd, "Different rtos types in members of one smp target!");
6363 return ERROR_FAIL;
6365 target = curr->target;
6368 *result = target;
6369 return ERROR_OK;
6372 COMMAND_HANDLER(handle_target_smp)
6374 static int smp_group = 1;
6376 if (CMD_ARGC == 0) {
6377 LOG_DEBUG("Empty SMP target");
6378 return ERROR_OK;
6380 LOG_DEBUG("%d", CMD_ARGC);
6381 /* CMD_ARGC[0] = target to associate in smp
6382 * CMD_ARGC[1] = target to associate in smp
6383 * CMD_ARGC[2] ...
6386 struct list_head *lh = malloc(sizeof(*lh));
6387 if (!lh) {
6388 LOG_ERROR("Out of memory");
6389 return ERROR_FAIL;
6391 INIT_LIST_HEAD(lh);
6393 for (unsigned int i = 0; i < CMD_ARGC; i++) {
6394 struct target_list *new = create_target_list_node(CMD_ARGV[i]);
6395 if (new)
6396 list_add_tail(&new->lh, lh);
6398 /* now parse the list of cpu and put the target in smp mode*/
6399 struct target_list *curr;
6400 foreach_smp_target(curr, lh) {
6401 struct target *target = curr->target;
6402 target->smp = smp_group;
6403 target->smp_targets = lh;
6405 smp_group++;
6407 struct target *rtos_target;
6408 int retval = get_target_with_common_rtos_type(CMD, lh, &rtos_target);
6409 if (retval == ERROR_OK && rtos_target)
6410 retval = rtos_smp_init(rtos_target);
6412 return retval;
6415 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6417 struct jim_getopt_info goi;
6418 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
6419 if (goi.argc < 3) {
6420 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
6421 "<name> <target_type> [<target_options> ...]");
6422 return JIM_ERR;
6424 return target_create(&goi);
6427 static const struct command_registration target_subcommand_handlers[] = {
6429 .name = "init",
6430 .mode = COMMAND_CONFIG,
6431 .handler = handle_target_init_command,
6432 .help = "initialize targets",
6433 .usage = "",
6436 .name = "create",
6437 .mode = COMMAND_CONFIG,
6438 .jim_handler = jim_target_create,
6439 .usage = "name type '-chain-position' name [options ...]",
6440 .help = "Creates and selects a new target",
6443 .name = "current",
6444 .mode = COMMAND_ANY,
6445 .handler = handle_target_current,
6446 .help = "Returns the currently selected target",
6447 .usage = "",
6450 .name = "types",
6451 .mode = COMMAND_ANY,
6452 .handler = handle_target_types,
6453 .help = "Returns the available target types as "
6454 "a list of strings",
6455 .usage = "",
6458 .name = "names",
6459 .mode = COMMAND_ANY,
6460 .handler = handle_target_names,
6461 .help = "Returns the names of all targets as a list of strings",
6462 .usage = "",
6465 .name = "smp",
6466 .mode = COMMAND_ANY,
6467 .handler = handle_target_smp,
6468 .usage = "targetname1 targetname2 ...",
6469 .help = "gather several target in a smp list"
6472 COMMAND_REGISTRATION_DONE
6475 struct fast_load {
6476 target_addr_t address;
6477 uint8_t *data;
6478 int length;
6482 static int fastload_num;
6483 static struct fast_load *fastload;
6485 static void free_fastload(void)
6487 if (fastload) {
6488 for (int i = 0; i < fastload_num; i++)
6489 free(fastload[i].data);
6490 free(fastload);
6491 fastload = NULL;
6495 COMMAND_HANDLER(handle_fast_load_image_command)
6497 uint8_t *buffer;
6498 size_t buf_cnt;
6499 uint32_t image_size;
6500 target_addr_t min_address = 0;
6501 target_addr_t max_address = -1;
6503 struct image image;
6505 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
6506 &image, &min_address, &max_address);
6507 if (retval != ERROR_OK)
6508 return retval;
6510 struct duration bench;
6511 duration_start(&bench);
6513 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
6514 if (retval != ERROR_OK)
6515 return retval;
6517 image_size = 0x0;
6518 retval = ERROR_OK;
6519 fastload_num = image.num_sections;
6520 fastload = malloc(sizeof(struct fast_load)*image.num_sections);
6521 if (!fastload) {
6522 command_print(CMD, "out of memory");
6523 image_close(&image);
6524 return ERROR_FAIL;
6526 memset(fastload, 0, sizeof(struct fast_load)*image.num_sections);
6527 for (unsigned int i = 0; i < image.num_sections; i++) {
6528 buffer = malloc(image.sections[i].size);
6529 if (!buffer) {
6530 command_print(CMD, "error allocating buffer for section (%d bytes)",
6531 (int)(image.sections[i].size));
6532 retval = ERROR_FAIL;
6533 break;
6536 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
6537 if (retval != ERROR_OK) {
6538 free(buffer);
6539 break;
6542 uint32_t offset = 0;
6543 uint32_t length = buf_cnt;
6545 /* DANGER!!! beware of unsigned comparison here!!! */
6547 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
6548 (image.sections[i].base_address < max_address)) {
6549 if (image.sections[i].base_address < min_address) {
6550 /* clip addresses below */
6551 offset += min_address-image.sections[i].base_address;
6552 length -= offset;
6555 if (image.sections[i].base_address + buf_cnt > max_address)
6556 length -= (image.sections[i].base_address + buf_cnt)-max_address;
6558 fastload[i].address = image.sections[i].base_address + offset;
6559 fastload[i].data = malloc(length);
6560 if (!fastload[i].data) {
6561 free(buffer);
6562 command_print(CMD, "error allocating buffer for section (%" PRIu32 " bytes)",
6563 length);
6564 retval = ERROR_FAIL;
6565 break;
6567 memcpy(fastload[i].data, buffer + offset, length);
6568 fastload[i].length = length;
6570 image_size += length;
6571 command_print(CMD, "%u bytes written at address 0x%8.8x",
6572 (unsigned int)length,
6573 ((unsigned int)(image.sections[i].base_address + offset)));
6576 free(buffer);
6579 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
6580 command_print(CMD, "Loaded %" PRIu32 " bytes "
6581 "in %fs (%0.3f KiB/s)", image_size,
6582 duration_elapsed(&bench), duration_kbps(&bench, image_size));
6584 command_print(CMD,
6585 "WARNING: image has not been loaded to target!"
6586 "You can issue a 'fast_load' to finish loading.");
6589 image_close(&image);
6591 if (retval != ERROR_OK)
6592 free_fastload();
6594 return retval;
6597 COMMAND_HANDLER(handle_fast_load_command)
6599 if (CMD_ARGC > 0)
6600 return ERROR_COMMAND_SYNTAX_ERROR;
6601 if (!fastload) {
6602 LOG_ERROR("No image in memory");
6603 return ERROR_FAIL;
6605 int i;
6606 int64_t ms = timeval_ms();
6607 int size = 0;
6608 int retval = ERROR_OK;
6609 for (i = 0; i < fastload_num; i++) {
6610 struct target *target = get_current_target(CMD_CTX);
6611 command_print(CMD, "Write to 0x%08x, length 0x%08x",
6612 (unsigned int)(fastload[i].address),
6613 (unsigned int)(fastload[i].length));
6614 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
6615 if (retval != ERROR_OK)
6616 break;
6617 size += fastload[i].length;
6619 if (retval == ERROR_OK) {
6620 int64_t after = timeval_ms();
6621 command_print(CMD, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
6623 return retval;
6626 static const struct command_registration target_command_handlers[] = {
6628 .name = "targets",
6629 .handler = handle_targets_command,
6630 .mode = COMMAND_ANY,
6631 .help = "change current default target (one parameter) "
6632 "or prints table of all targets (no parameters)",
6633 .usage = "[target]",
6636 .name = "target",
6637 .mode = COMMAND_CONFIG,
6638 .help = "configure target",
6639 .chain = target_subcommand_handlers,
6640 .usage = "",
6642 COMMAND_REGISTRATION_DONE
6645 int target_register_commands(struct command_context *cmd_ctx)
6647 return register_commands(cmd_ctx, NULL, target_command_handlers);
6650 static bool target_reset_nag = true;
6652 bool get_target_reset_nag(void)
6654 return target_reset_nag;
6657 COMMAND_HANDLER(handle_target_reset_nag)
6659 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
6660 &target_reset_nag, "Nag after each reset about options to improve "
6661 "performance");
6664 COMMAND_HANDLER(handle_ps_command)
6666 struct target *target = get_current_target(CMD_CTX);
6667 char *display;
6668 if (target->state != TARGET_HALTED) {
6669 command_print(CMD, "Error: [%s] not halted", target_name(target));
6670 return ERROR_TARGET_NOT_HALTED;
6673 if ((target->rtos) && (target->rtos->type)
6674 && (target->rtos->type->ps_command)) {
6675 display = target->rtos->type->ps_command(target);
6676 command_print(CMD, "%s", display);
6677 free(display);
6678 return ERROR_OK;
6679 } else {
6680 LOG_INFO("failed");
6681 return ERROR_TARGET_FAILURE;
6685 static void binprint(struct command_invocation *cmd, const char *text, const uint8_t *buf, int size)
6687 if (text)
6688 command_print_sameline(cmd, "%s", text);
6689 for (int i = 0; i < size; i++)
6690 command_print_sameline(cmd, " %02x", buf[i]);
6691 command_print(cmd, " ");
6694 COMMAND_HANDLER(handle_test_mem_access_command)
6696 struct target *target = get_current_target(CMD_CTX);
6697 uint32_t test_size;
6698 int retval = ERROR_OK;
6700 if (target->state != TARGET_HALTED) {
6701 command_print(CMD, "Error: [%s] not halted", target_name(target));
6702 return ERROR_TARGET_NOT_HALTED;
6705 if (CMD_ARGC != 1)
6706 return ERROR_COMMAND_SYNTAX_ERROR;
6708 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
6710 /* Test reads */
6711 size_t num_bytes = test_size + 4;
6713 struct working_area *wa = NULL;
6714 retval = target_alloc_working_area(target, num_bytes, &wa);
6715 if (retval != ERROR_OK) {
6716 LOG_ERROR("Not enough working area");
6717 return ERROR_FAIL;
6720 uint8_t *test_pattern = malloc(num_bytes);
6722 for (size_t i = 0; i < num_bytes; i++)
6723 test_pattern[i] = rand();
6725 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6726 if (retval != ERROR_OK) {
6727 LOG_ERROR("Test pattern write failed");
6728 goto out;
6731 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6732 for (int size = 1; size <= 4; size *= 2) {
6733 for (int offset = 0; offset < 4; offset++) {
6734 uint32_t count = test_size / size;
6735 size_t host_bufsiz = (count + 2) * size + host_offset;
6736 uint8_t *read_ref = malloc(host_bufsiz);
6737 uint8_t *read_buf = malloc(host_bufsiz);
6739 for (size_t i = 0; i < host_bufsiz; i++) {
6740 read_ref[i] = rand();
6741 read_buf[i] = read_ref[i];
6743 command_print_sameline(CMD,
6744 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
6745 size, offset, host_offset ? "un" : "");
6747 struct duration bench;
6748 duration_start(&bench);
6750 retval = target_read_memory(target, wa->address + offset, size, count,
6751 read_buf + size + host_offset);
6753 duration_measure(&bench);
6755 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6756 command_print(CMD, "Unsupported alignment");
6757 goto next;
6758 } else if (retval != ERROR_OK) {
6759 command_print(CMD, "Memory read failed");
6760 goto next;
6763 /* replay on host */
6764 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
6766 /* check result */
6767 int result = memcmp(read_ref, read_buf, host_bufsiz);
6768 if (result == 0) {
6769 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6770 duration_elapsed(&bench),
6771 duration_kbps(&bench, count * size));
6772 } else {
6773 command_print(CMD, "Compare failed");
6774 binprint(CMD, "ref:", read_ref, host_bufsiz);
6775 binprint(CMD, "buf:", read_buf, host_bufsiz);
6777 next:
6778 free(read_ref);
6779 free(read_buf);
6784 out:
6785 free(test_pattern);
6787 target_free_working_area(target, wa);
6789 /* Test writes */
6790 num_bytes = test_size + 4 + 4 + 4;
6792 retval = target_alloc_working_area(target, num_bytes, &wa);
6793 if (retval != ERROR_OK) {
6794 LOG_ERROR("Not enough working area");
6795 return ERROR_FAIL;
6798 test_pattern = malloc(num_bytes);
6800 for (size_t i = 0; i < num_bytes; i++)
6801 test_pattern[i] = rand();
6803 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6804 for (int size = 1; size <= 4; size *= 2) {
6805 for (int offset = 0; offset < 4; offset++) {
6806 uint32_t count = test_size / size;
6807 size_t host_bufsiz = count * size + host_offset;
6808 uint8_t *read_ref = malloc(num_bytes);
6809 uint8_t *read_buf = malloc(num_bytes);
6810 uint8_t *write_buf = malloc(host_bufsiz);
6812 for (size_t i = 0; i < host_bufsiz; i++)
6813 write_buf[i] = rand();
6814 command_print_sameline(CMD,
6815 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
6816 size, offset, host_offset ? "un" : "");
6818 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6819 if (retval != ERROR_OK) {
6820 command_print(CMD, "Test pattern write failed");
6821 goto nextw;
6824 /* replay on host */
6825 memcpy(read_ref, test_pattern, num_bytes);
6826 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
6828 struct duration bench;
6829 duration_start(&bench);
6831 retval = target_write_memory(target, wa->address + size + offset, size, count,
6832 write_buf + host_offset);
6834 duration_measure(&bench);
6836 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6837 command_print(CMD, "Unsupported alignment");
6838 goto nextw;
6839 } else if (retval != ERROR_OK) {
6840 command_print(CMD, "Memory write failed");
6841 goto nextw;
6844 /* read back */
6845 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
6846 if (retval != ERROR_OK) {
6847 command_print(CMD, "Test pattern write failed");
6848 goto nextw;
6851 /* check result */
6852 int result = memcmp(read_ref, read_buf, num_bytes);
6853 if (result == 0) {
6854 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6855 duration_elapsed(&bench),
6856 duration_kbps(&bench, count * size));
6857 } else {
6858 command_print(CMD, "Compare failed");
6859 binprint(CMD, "ref:", read_ref, num_bytes);
6860 binprint(CMD, "buf:", read_buf, num_bytes);
6862 nextw:
6863 free(read_ref);
6864 free(read_buf);
6869 free(test_pattern);
6871 target_free_working_area(target, wa);
6872 return retval;
6875 static const struct command_registration target_exec_command_handlers[] = {
6877 .name = "fast_load_image",
6878 .handler = handle_fast_load_image_command,
6879 .mode = COMMAND_ANY,
6880 .help = "Load image into server memory for later use by "
6881 "fast_load; primarily for profiling",
6882 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6883 "[min_address [max_length]]",
6886 .name = "fast_load",
6887 .handler = handle_fast_load_command,
6888 .mode = COMMAND_EXEC,
6889 .help = "loads active fast load image to current target "
6890 "- mainly for profiling purposes",
6891 .usage = "",
6894 .name = "profile",
6895 .handler = handle_profile_command,
6896 .mode = COMMAND_EXEC,
6897 .usage = "seconds filename [start end]",
6898 .help = "profiling samples the CPU PC",
6900 /** @todo don't register virt2phys() unless target supports it */
6902 .name = "virt2phys",
6903 .handler = handle_virt2phys_command,
6904 .mode = COMMAND_ANY,
6905 .help = "translate a virtual address into a physical address",
6906 .usage = "virtual_address",
6909 .name = "reg",
6910 .handler = handle_reg_command,
6911 .mode = COMMAND_EXEC,
6912 .help = "display (reread from target with \"force\") or set a register; "
6913 "with no arguments, displays all registers and their values",
6914 .usage = "[(register_number|register_name) [(value|'force')]]",
6917 .name = "poll",
6918 .handler = handle_poll_command,
6919 .mode = COMMAND_EXEC,
6920 .help = "poll target state; or reconfigure background polling",
6921 .usage = "['on'|'off']",
6924 .name = "wait_halt",
6925 .handler = handle_wait_halt_command,
6926 .mode = COMMAND_EXEC,
6927 .help = "wait up to the specified number of milliseconds "
6928 "(default 5000) for a previously requested halt",
6929 .usage = "[milliseconds]",
6932 .name = "halt",
6933 .handler = handle_halt_command,
6934 .mode = COMMAND_EXEC,
6935 .help = "request target to halt, then wait up to the specified "
6936 "number of milliseconds (default 5000) for it to complete",
6937 .usage = "[milliseconds]",
6940 .name = "resume",
6941 .handler = handle_resume_command,
6942 .mode = COMMAND_EXEC,
6943 .help = "resume target execution from current PC or address",
6944 .usage = "[address]",
6947 .name = "reset",
6948 .handler = handle_reset_command,
6949 .mode = COMMAND_EXEC,
6950 .usage = "[run|halt|init]",
6951 .help = "Reset all targets into the specified mode. "
6952 "Default reset mode is run, if not given.",
6955 .name = "soft_reset_halt",
6956 .handler = handle_soft_reset_halt_command,
6957 .mode = COMMAND_EXEC,
6958 .usage = "",
6959 .help = "halt the target and do a soft reset",
6962 .name = "step",
6963 .handler = handle_step_command,
6964 .mode = COMMAND_EXEC,
6965 .help = "step one instruction from current PC or address",
6966 .usage = "[address]",
6969 .name = "mdd",
6970 .handler = handle_md_command,
6971 .mode = COMMAND_EXEC,
6972 .help = "display memory double-words",
6973 .usage = "['phys'] address [count]",
6976 .name = "mdw",
6977 .handler = handle_md_command,
6978 .mode = COMMAND_EXEC,
6979 .help = "display memory words",
6980 .usage = "['phys'] address [count]",
6983 .name = "mdh",
6984 .handler = handle_md_command,
6985 .mode = COMMAND_EXEC,
6986 .help = "display memory half-words",
6987 .usage = "['phys'] address [count]",
6990 .name = "mdb",
6991 .handler = handle_md_command,
6992 .mode = COMMAND_EXEC,
6993 .help = "display memory bytes",
6994 .usage = "['phys'] address [count]",
6997 .name = "mwd",
6998 .handler = handle_mw_command,
6999 .mode = COMMAND_EXEC,
7000 .help = "write memory double-word",
7001 .usage = "['phys'] address value [count]",
7004 .name = "mww",
7005 .handler = handle_mw_command,
7006 .mode = COMMAND_EXEC,
7007 .help = "write memory word",
7008 .usage = "['phys'] address value [count]",
7011 .name = "mwh",
7012 .handler = handle_mw_command,
7013 .mode = COMMAND_EXEC,
7014 .help = "write memory half-word",
7015 .usage = "['phys'] address value [count]",
7018 .name = "mwb",
7019 .handler = handle_mw_command,
7020 .mode = COMMAND_EXEC,
7021 .help = "write memory byte",
7022 .usage = "['phys'] address value [count]",
7025 .name = "bp",
7026 .handler = handle_bp_command,
7027 .mode = COMMAND_EXEC,
7028 .help = "list or set hardware or software breakpoint",
7029 .usage = "[<address> [<asid>] <length> ['hw'|'hw_ctx']]",
7032 .name = "rbp",
7033 .handler = handle_rbp_command,
7034 .mode = COMMAND_EXEC,
7035 .help = "remove breakpoint",
7036 .usage = "'all' | address",
7039 .name = "wp",
7040 .handler = handle_wp_command,
7041 .mode = COMMAND_EXEC,
7042 .help = "list (no params) or create watchpoints",
7043 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
7046 .name = "rwp",
7047 .handler = handle_rwp_command,
7048 .mode = COMMAND_EXEC,
7049 .help = "remove watchpoint",
7050 .usage = "address",
7053 .name = "load_image",
7054 .handler = handle_load_image_command,
7055 .mode = COMMAND_EXEC,
7056 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
7057 "[min_address] [max_length]",
7060 .name = "dump_image",
7061 .handler = handle_dump_image_command,
7062 .mode = COMMAND_EXEC,
7063 .usage = "filename address size",
7066 .name = "verify_image_checksum",
7067 .handler = handle_verify_image_checksum_command,
7068 .mode = COMMAND_EXEC,
7069 .usage = "filename [offset [type]]",
7072 .name = "verify_image",
7073 .handler = handle_verify_image_command,
7074 .mode = COMMAND_EXEC,
7075 .usage = "filename [offset [type]]",
7078 .name = "test_image",
7079 .handler = handle_test_image_command,
7080 .mode = COMMAND_EXEC,
7081 .usage = "filename [offset [type]]",
7084 .name = "get_reg",
7085 .mode = COMMAND_EXEC,
7086 .jim_handler = target_jim_get_reg,
7087 .help = "Get register values from the target",
7088 .usage = "list",
7091 .name = "set_reg",
7092 .mode = COMMAND_EXEC,
7093 .jim_handler = target_jim_set_reg,
7094 .help = "Set target register values",
7095 .usage = "dict",
7098 .name = "read_memory",
7099 .mode = COMMAND_EXEC,
7100 .handler = handle_target_read_memory,
7101 .help = "Read Tcl list of 8/16/32/64 bit numbers from target memory",
7102 .usage = "address width count ['phys']",
7105 .name = "write_memory",
7106 .mode = COMMAND_EXEC,
7107 .jim_handler = target_jim_write_memory,
7108 .help = "Write Tcl list of 8/16/32/64 bit numbers to target memory",
7109 .usage = "address width data ['phys']",
7112 .name = "reset_nag",
7113 .handler = handle_target_reset_nag,
7114 .mode = COMMAND_ANY,
7115 .help = "Nag after each reset about options that could have been "
7116 "enabled to improve performance.",
7117 .usage = "['enable'|'disable']",
7120 .name = "ps",
7121 .handler = handle_ps_command,
7122 .mode = COMMAND_EXEC,
7123 .help = "list all tasks",
7124 .usage = "",
7127 .name = "test_mem_access",
7128 .handler = handle_test_mem_access_command,
7129 .mode = COMMAND_EXEC,
7130 .help = "Test the target's memory access functions",
7131 .usage = "size",
7134 COMMAND_REGISTRATION_DONE
7136 static int target_register_user_commands(struct command_context *cmd_ctx)
7138 int retval = ERROR_OK;
7139 retval = target_request_register_commands(cmd_ctx);
7140 if (retval != ERROR_OK)
7141 return retval;
7143 retval = trace_register_commands(cmd_ctx);
7144 if (retval != ERROR_OK)
7145 return retval;
7148 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);
7151 const char *target_debug_reason_str(enum target_debug_reason reason)
7153 switch (reason) {
7154 case DBG_REASON_DBGRQ:
7155 return "DBGRQ";
7156 case DBG_REASON_BREAKPOINT:
7157 return "BREAKPOINT";
7158 case DBG_REASON_WATCHPOINT:
7159 return "WATCHPOINT";
7160 case DBG_REASON_WPTANDBKPT:
7161 return "WPTANDBKPT";
7162 case DBG_REASON_SINGLESTEP:
7163 return "SINGLESTEP";
7164 case DBG_REASON_NOTHALTED:
7165 return "NOTHALTED";
7166 case DBG_REASON_EXIT:
7167 return "EXIT";
7168 case DBG_REASON_EXC_CATCH:
7169 return "EXC_CATCH";
7170 case DBG_REASON_UNDEFINED:
7171 return "UNDEFINED";
7172 default:
7173 return "UNKNOWN!";