jtag: linuxgpiod: drop extra parenthesis
[openocd.git] / src / target / target.c
blob45698a66c59879a6221ddb4b2b3ee32d2583922c
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_register_user_commands(struct command_context *cmd_ctx);
60 static int target_get_gdb_fileio_info_default(struct target *target,
61 struct gdb_fileio_info *fileio_info);
62 static int target_gdb_fileio_end_default(struct target *target, int retcode,
63 int fileio_errno, bool ctrl_c);
65 static struct target_type *target_types[] = {
66 &arm7tdmi_target,
67 &arm9tdmi_target,
68 &arm920t_target,
69 &arm720t_target,
70 &arm966e_target,
71 &arm946e_target,
72 &arm926ejs_target,
73 &fa526_target,
74 &feroceon_target,
75 &dragonite_target,
76 &xscale_target,
77 &xtensa_chip_target,
78 &cortexm_target,
79 &cortexa_target,
80 &cortexr4_target,
81 &arm11_target,
82 &ls1_sap_target,
83 &mips_m4k_target,
84 &avr_target,
85 &dsp563xx_target,
86 &dsp5680xx_target,
87 &testee_target,
88 &avr32_ap7k_target,
89 &hla_target,
90 &esp32_target,
91 &esp32s2_target,
92 &esp32s3_target,
93 &or1k_target,
94 &quark_x10xx_target,
95 &quark_d20xx_target,
96 &stm8_target,
97 &riscv_target,
98 &mem_ap_target,
99 &esirisc_target,
100 &arcv2_target,
101 &aarch64_target,
102 &armv8r_target,
103 &mips_mips64_target,
104 NULL,
107 struct target *all_targets;
108 static struct target_event_callback *target_event_callbacks;
109 static struct target_timer_callback *target_timer_callbacks;
110 static int64_t target_timer_next_event_value;
111 static LIST_HEAD(target_reset_callback_list);
112 static LIST_HEAD(target_trace_callback_list);
113 static const int polling_interval = TARGET_DEFAULT_POLLING_INTERVAL;
114 static LIST_HEAD(empty_smp_targets);
116 enum nvp_assert {
117 NVP_DEASSERT,
118 NVP_ASSERT,
121 static const struct nvp nvp_assert[] = {
122 { .name = "assert", NVP_ASSERT },
123 { .name = "deassert", NVP_DEASSERT },
124 { .name = "T", NVP_ASSERT },
125 { .name = "F", NVP_DEASSERT },
126 { .name = "t", NVP_ASSERT },
127 { .name = "f", NVP_DEASSERT },
128 { .name = NULL, .value = -1 }
131 static const struct nvp nvp_error_target[] = {
132 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
133 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
134 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
135 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
136 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
137 { .value = ERROR_TARGET_UNALIGNED_ACCESS, .name = "err-unaligned-access" },
138 { .value = ERROR_TARGET_DATA_ABORT, .name = "err-data-abort" },
139 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE, .name = "err-resource-not-available" },
140 { .value = ERROR_TARGET_TRANSLATION_FAULT, .name = "err-translation-fault" },
141 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
142 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
143 { .value = -1, .name = NULL }
146 static const char *target_strerror_safe(int err)
148 const struct nvp *n;
150 n = nvp_value2name(nvp_error_target, err);
151 if (!n->name)
152 return "unknown";
153 else
154 return n->name;
157 static const struct jim_nvp nvp_target_event[] = {
159 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
160 { .value = TARGET_EVENT_HALTED, .name = "halted" },
161 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
162 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
163 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
164 { .value = TARGET_EVENT_STEP_START, .name = "step-start" },
165 { .value = TARGET_EVENT_STEP_END, .name = "step-end" },
167 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
168 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
170 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
171 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
172 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
173 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
174 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
175 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
176 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
177 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
179 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
180 { .value = TARGET_EVENT_EXAMINE_FAIL, .name = "examine-fail" },
181 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
183 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
184 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
186 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
187 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
189 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
190 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END, .name = "gdb-flash-write-end" },
192 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
193 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END, .name = "gdb-flash-erase-end" },
195 { .value = TARGET_EVENT_TRACE_CONFIG, .name = "trace-config" },
197 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X100, .name = "semihosting-user-cmd-0x100" },
198 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X101, .name = "semihosting-user-cmd-0x101" },
199 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X102, .name = "semihosting-user-cmd-0x102" },
200 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X103, .name = "semihosting-user-cmd-0x103" },
201 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X104, .name = "semihosting-user-cmd-0x104" },
202 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X105, .name = "semihosting-user-cmd-0x105" },
203 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X106, .name = "semihosting-user-cmd-0x106" },
204 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X107, .name = "semihosting-user-cmd-0x107" },
206 { .name = NULL, .value = -1 }
209 static const struct nvp nvp_target_state[] = {
210 { .name = "unknown", .value = TARGET_UNKNOWN },
211 { .name = "running", .value = TARGET_RUNNING },
212 { .name = "halted", .value = TARGET_HALTED },
213 { .name = "reset", .value = TARGET_RESET },
214 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
215 { .name = NULL, .value = -1 },
218 static const struct nvp nvp_target_debug_reason[] = {
219 { .name = "debug-request", .value = DBG_REASON_DBGRQ },
220 { .name = "breakpoint", .value = DBG_REASON_BREAKPOINT },
221 { .name = "watchpoint", .value = DBG_REASON_WATCHPOINT },
222 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
223 { .name = "single-step", .value = DBG_REASON_SINGLESTEP },
224 { .name = "target-not-halted", .value = DBG_REASON_NOTHALTED },
225 { .name = "program-exit", .value = DBG_REASON_EXIT },
226 { .name = "exception-catch", .value = DBG_REASON_EXC_CATCH },
227 { .name = "undefined", .value = DBG_REASON_UNDEFINED },
228 { .name = NULL, .value = -1 },
231 static const struct jim_nvp nvp_target_endian[] = {
232 { .name = "big", .value = TARGET_BIG_ENDIAN },
233 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
234 { .name = "be", .value = TARGET_BIG_ENDIAN },
235 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
236 { .name = NULL, .value = -1 },
239 static const struct nvp nvp_reset_modes[] = {
240 { .name = "unknown", .value = RESET_UNKNOWN },
241 { .name = "run", .value = RESET_RUN },
242 { .name = "halt", .value = RESET_HALT },
243 { .name = "init", .value = RESET_INIT },
244 { .name = NULL, .value = -1 },
247 const char *debug_reason_name(const struct target *t)
249 const char *cp;
251 cp = nvp_value2name(nvp_target_debug_reason,
252 t->debug_reason)->name;
253 if (!cp) {
254 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
255 cp = "(*BUG*unknown*BUG*)";
257 return cp;
260 const char *target_state_name(const struct target *t)
262 const char *cp;
263 cp = nvp_value2name(nvp_target_state, t->state)->name;
264 if (!cp) {
265 LOG_ERROR("Invalid target state: %d", (int)(t->state));
266 cp = "(*BUG*unknown*BUG*)";
269 if (!target_was_examined(t) && t->defer_examine)
270 cp = "examine deferred";
272 return cp;
275 const char *target_event_name(enum target_event event)
277 const char *cp;
278 cp = jim_nvp_value2name_simple(nvp_target_event, event)->name;
279 if (!cp) {
280 LOG_ERROR("Invalid target event: %d", (int)(event));
281 cp = "(*BUG*unknown*BUG*)";
283 return cp;
286 const char *target_reset_mode_name(enum target_reset_mode reset_mode)
288 const char *cp;
289 cp = nvp_value2name(nvp_reset_modes, reset_mode)->name;
290 if (!cp) {
291 LOG_ERROR("Invalid target reset mode: %d", (int)(reset_mode));
292 cp = "(*BUG*unknown*BUG*)";
294 return cp;
297 static void append_to_list_all_targets(struct target *target)
299 struct target **t = &all_targets;
301 while (*t)
302 t = &((*t)->next);
303 *t = target;
306 /* read a uint64_t from a buffer in target memory endianness */
307 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
309 if (target->endianness == TARGET_LITTLE_ENDIAN)
310 return le_to_h_u64(buffer);
311 else
312 return be_to_h_u64(buffer);
315 /* read a uint32_t from a buffer in target memory endianness */
316 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
318 if (target->endianness == TARGET_LITTLE_ENDIAN)
319 return le_to_h_u32(buffer);
320 else
321 return be_to_h_u32(buffer);
324 /* read a uint24_t from a buffer in target memory endianness */
325 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
327 if (target->endianness == TARGET_LITTLE_ENDIAN)
328 return le_to_h_u24(buffer);
329 else
330 return be_to_h_u24(buffer);
333 /* read a uint16_t from a buffer in target memory endianness */
334 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
336 if (target->endianness == TARGET_LITTLE_ENDIAN)
337 return le_to_h_u16(buffer);
338 else
339 return be_to_h_u16(buffer);
342 /* write a uint64_t to a buffer in target memory endianness */
343 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
345 if (target->endianness == TARGET_LITTLE_ENDIAN)
346 h_u64_to_le(buffer, value);
347 else
348 h_u64_to_be(buffer, value);
351 /* write a uint32_t to a buffer in target memory endianness */
352 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
354 if (target->endianness == TARGET_LITTLE_ENDIAN)
355 h_u32_to_le(buffer, value);
356 else
357 h_u32_to_be(buffer, value);
360 /* write a uint24_t to a buffer in target memory endianness */
361 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
363 if (target->endianness == TARGET_LITTLE_ENDIAN)
364 h_u24_to_le(buffer, value);
365 else
366 h_u24_to_be(buffer, value);
369 /* write a uint16_t to a buffer in target memory endianness */
370 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
372 if (target->endianness == TARGET_LITTLE_ENDIAN)
373 h_u16_to_le(buffer, value);
374 else
375 h_u16_to_be(buffer, value);
378 /* write a uint8_t to a buffer in target memory endianness */
379 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
381 *buffer = value;
384 /* write a uint64_t array to a buffer in target memory endianness */
385 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
387 uint32_t i;
388 for (i = 0; i < count; i++)
389 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
392 /* write a uint32_t array to a buffer in target memory endianness */
393 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
395 uint32_t i;
396 for (i = 0; i < count; i++)
397 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
400 /* write a uint16_t array to a buffer in target memory endianness */
401 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
403 uint32_t i;
404 for (i = 0; i < count; i++)
405 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
408 /* write a uint64_t array to a buffer in target memory endianness */
409 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
411 uint32_t i;
412 for (i = 0; i < count; i++)
413 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
416 /* write a uint32_t array to a buffer in target memory endianness */
417 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
419 uint32_t i;
420 for (i = 0; i < count; i++)
421 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
424 /* write a uint16_t array to a buffer in target memory endianness */
425 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
427 uint32_t i;
428 for (i = 0; i < count; i++)
429 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
432 /* return a pointer to a configured target; id is name or index in all_targets */
433 struct target *get_target(const char *id)
435 struct target *target;
437 /* try as tcltarget name */
438 for (target = all_targets; target; target = target->next) {
439 if (!target_name(target))
440 continue;
441 if (strcmp(id, target_name(target)) == 0)
442 return target;
445 /* try as index */
446 unsigned int index, counter;
447 if (parse_uint(id, &index) != ERROR_OK)
448 return NULL;
450 for (target = all_targets, counter = index;
451 target && counter;
452 target = target->next, --counter)
455 return target;
458 struct target *get_current_target(struct command_context *cmd_ctx)
460 struct target *target = get_current_target_or_null(cmd_ctx);
462 if (!target) {
463 LOG_ERROR("BUG: current_target out of bounds");
464 exit(-1);
467 return target;
470 struct target *get_current_target_or_null(struct command_context *cmd_ctx)
472 return cmd_ctx->current_target_override
473 ? cmd_ctx->current_target_override
474 : cmd_ctx->current_target;
477 int target_poll(struct target *target)
479 int retval;
481 /* We can't poll until after examine */
482 if (!target_was_examined(target)) {
483 /* Fail silently lest we pollute the log */
484 return ERROR_FAIL;
487 retval = target->type->poll(target);
488 if (retval != ERROR_OK)
489 return retval;
491 if (target->halt_issued) {
492 if (target->state == TARGET_HALTED)
493 target->halt_issued = false;
494 else {
495 int64_t t = timeval_ms() - target->halt_issued_time;
496 if (t > DEFAULT_HALT_TIMEOUT) {
497 target->halt_issued = false;
498 LOG_INFO("Halt timed out, wake up GDB.");
499 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
504 return ERROR_OK;
507 int target_halt(struct target *target)
509 int retval;
510 /* We can't poll until after examine */
511 if (!target_was_examined(target)) {
512 LOG_ERROR("Target not examined yet");
513 return ERROR_FAIL;
516 retval = target->type->halt(target);
517 if (retval != ERROR_OK)
518 return retval;
520 target->halt_issued = true;
521 target->halt_issued_time = timeval_ms();
523 return ERROR_OK;
527 * Make the target (re)start executing using its saved execution
528 * context (possibly with some modifications).
530 * @param target Which target should start executing.
531 * @param current True to use the target's saved program counter instead
532 * of the address parameter
533 * @param address Optionally used as the program counter.
534 * @param handle_breakpoints True iff breakpoints at the resumption PC
535 * should be skipped. (For example, maybe execution was stopped by
536 * such a breakpoint, in which case it would be counterproductive to
537 * let it re-trigger.
538 * @param debug_execution False if all working areas allocated by OpenOCD
539 * should be released and/or restored to their original contents.
540 * (This would for example be true to run some downloaded "helper"
541 * algorithm code, which resides in one such working buffer and uses
542 * another for data storage.)
544 * @todo Resolve the ambiguity about what the "debug_execution" flag
545 * signifies. For example, Target implementations don't agree on how
546 * it relates to invalidation of the register cache, or to whether
547 * breakpoints and watchpoints should be enabled. (It would seem wrong
548 * to enable breakpoints when running downloaded "helper" algorithms
549 * (debug_execution true), since the breakpoints would be set to match
550 * target firmware being debugged, not the helper algorithm.... and
551 * enabling them could cause such helpers to malfunction (for example,
552 * by overwriting data with a breakpoint instruction. On the other
553 * hand the infrastructure for running such helpers might use this
554 * procedure but rely on hardware breakpoint to detect termination.)
556 int target_resume(struct target *target, int current, target_addr_t address,
557 int handle_breakpoints, int debug_execution)
559 int retval;
561 /* We can't poll until after examine */
562 if (!target_was_examined(target)) {
563 LOG_ERROR("Target not examined yet");
564 return ERROR_FAIL;
567 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
569 /* note that resume *must* be asynchronous. The CPU can halt before
570 * we poll. The CPU can even halt at the current PC as a result of
571 * a software breakpoint being inserted by (a bug?) the application.
574 * resume() triggers the event 'resumed'. The execution of TCL commands
575 * in the event handler causes the polling of targets. If the target has
576 * already halted for a breakpoint, polling will run the 'halted' event
577 * handler before the pending 'resumed' handler.
578 * Disable polling during resume() to guarantee the execution of handlers
579 * in the correct order.
581 bool save_poll_mask = jtag_poll_mask();
582 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
583 jtag_poll_unmask(save_poll_mask);
585 if (retval != ERROR_OK)
586 return retval;
588 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
590 return retval;
593 static int target_process_reset(struct command_invocation *cmd, enum target_reset_mode reset_mode)
595 char buf[100];
596 int retval;
597 const struct nvp *n;
598 n = nvp_value2name(nvp_reset_modes, reset_mode);
599 if (!n->name) {
600 LOG_ERROR("invalid reset mode");
601 return ERROR_FAIL;
604 struct target *target;
605 for (target = all_targets; target; target = target->next)
606 target_call_reset_callbacks(target, reset_mode);
608 /* disable polling during reset to make reset event scripts
609 * more predictable, i.e. dr/irscan & pathmove in events will
610 * not have JTAG operations injected into the middle of a sequence.
612 bool save_poll_mask = jtag_poll_mask();
614 sprintf(buf, "ocd_process_reset %s", n->name);
615 retval = Jim_Eval(cmd->ctx->interp, buf);
617 jtag_poll_unmask(save_poll_mask);
619 if (retval != JIM_OK) {
620 Jim_MakeErrorMessage(cmd->ctx->interp);
621 command_print(cmd, "%s", Jim_GetString(Jim_GetResult(cmd->ctx->interp), NULL));
622 return ERROR_FAIL;
625 /* We want any events to be processed before the prompt */
626 retval = target_call_timer_callbacks_now();
628 for (target = all_targets; target; target = target->next) {
629 target->type->check_reset(target);
630 target->running_alg = false;
633 return retval;
636 static int identity_virt2phys(struct target *target,
637 target_addr_t virtual, target_addr_t *physical)
639 *physical = virtual;
640 return ERROR_OK;
643 static int no_mmu(struct target *target, int *enabled)
645 *enabled = 0;
646 return ERROR_OK;
650 * Reset the @c examined flag for the given target.
651 * Pure paranoia -- targets are zeroed on allocation.
653 static inline void target_reset_examined(struct target *target)
655 target->examined = false;
658 static int default_examine(struct target *target)
660 target_set_examined(target);
661 return ERROR_OK;
664 /* no check by default */
665 static int default_check_reset(struct target *target)
667 return ERROR_OK;
670 /* Equivalent Tcl code arp_examine_one is in src/target/startup.tcl
671 * Keep in sync */
672 int target_examine_one(struct target *target)
674 LOG_TARGET_DEBUG(target, "Examination started");
676 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
678 int retval = target->type->examine(target);
679 if (retval != ERROR_OK) {
680 LOG_TARGET_ERROR(target, "Examination failed");
681 LOG_TARGET_DEBUG(target, "examine() returned error code %d", retval);
682 target_reset_examined(target);
683 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_FAIL);
684 return retval;
687 target_set_examined(target);
688 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
690 LOG_TARGET_INFO(target, "Examination succeed");
691 return ERROR_OK;
694 static int jtag_enable_callback(enum jtag_event event, void *priv)
696 struct target *target = priv;
698 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
699 return ERROR_OK;
701 jtag_unregister_event_callback(jtag_enable_callback, target);
703 return target_examine_one(target);
706 /* Targets that correctly implement init + examine, i.e.
707 * no communication with target during init:
709 * XScale
711 int target_examine(void)
713 int retval = ERROR_OK;
714 struct target *target;
716 for (target = all_targets; target; target = target->next) {
717 /* defer examination, but don't skip it */
718 if (!target->tap->enabled) {
719 jtag_register_event_callback(jtag_enable_callback,
720 target);
721 continue;
724 if (target->defer_examine)
725 continue;
727 int retval2 = target_examine_one(target);
728 if (retval2 != ERROR_OK) {
729 LOG_WARNING("target %s examination failed", target_name(target));
730 retval = retval2;
733 return retval;
736 const char *target_type_name(const struct target *target)
738 return target->type->name;
741 static int target_soft_reset_halt(struct target *target)
743 if (!target_was_examined(target)) {
744 LOG_ERROR("Target not examined yet");
745 return ERROR_FAIL;
747 if (!target->type->soft_reset_halt) {
748 LOG_ERROR("Target %s does not support soft_reset_halt",
749 target_name(target));
750 return ERROR_FAIL;
752 return target->type->soft_reset_halt(target);
756 * Downloads a target-specific native code algorithm to the target,
757 * and executes it. * Note that some targets may need to set up, enable,
758 * and tear down a breakpoint (hard or * soft) to detect algorithm
759 * termination, while others may support lower overhead schemes where
760 * soft breakpoints embedded in the algorithm automatically terminate the
761 * algorithm.
763 * @param target used to run the algorithm
764 * @param num_mem_params
765 * @param mem_params
766 * @param num_reg_params
767 * @param reg_param
768 * @param entry_point
769 * @param exit_point
770 * @param timeout_ms
771 * @param arch_info target-specific description of the algorithm.
773 int target_run_algorithm(struct target *target,
774 int num_mem_params, struct mem_param *mem_params,
775 int num_reg_params, struct reg_param *reg_param,
776 target_addr_t entry_point, target_addr_t exit_point,
777 unsigned int timeout_ms, void *arch_info)
779 int retval = ERROR_FAIL;
781 if (!target_was_examined(target)) {
782 LOG_ERROR("Target not examined yet");
783 goto done;
785 if (!target->type->run_algorithm) {
786 LOG_ERROR("Target type '%s' does not support %s",
787 target_type_name(target), __func__);
788 goto done;
791 target->running_alg = true;
792 retval = target->type->run_algorithm(target,
793 num_mem_params, mem_params,
794 num_reg_params, reg_param,
795 entry_point, exit_point, timeout_ms, arch_info);
796 target->running_alg = false;
798 done:
799 return retval;
803 * Executes a target-specific native code algorithm and leaves it running.
805 * @param target used to run the algorithm
806 * @param num_mem_params
807 * @param mem_params
808 * @param num_reg_params
809 * @param reg_params
810 * @param entry_point
811 * @param exit_point
812 * @param arch_info target-specific description of the algorithm.
814 int target_start_algorithm(struct target *target,
815 int num_mem_params, struct mem_param *mem_params,
816 int num_reg_params, struct reg_param *reg_params,
817 target_addr_t entry_point, target_addr_t exit_point,
818 void *arch_info)
820 int retval = ERROR_FAIL;
822 if (!target_was_examined(target)) {
823 LOG_ERROR("Target not examined yet");
824 goto done;
826 if (!target->type->start_algorithm) {
827 LOG_ERROR("Target type '%s' does not support %s",
828 target_type_name(target), __func__);
829 goto done;
831 if (target->running_alg) {
832 LOG_ERROR("Target is already running an algorithm");
833 goto done;
836 target->running_alg = true;
837 retval = target->type->start_algorithm(target,
838 num_mem_params, mem_params,
839 num_reg_params, reg_params,
840 entry_point, exit_point, arch_info);
842 done:
843 return retval;
847 * Waits for an algorithm started with target_start_algorithm() to complete.
849 * @param target used to run the algorithm
850 * @param num_mem_params
851 * @param mem_params
852 * @param num_reg_params
853 * @param reg_params
854 * @param exit_point
855 * @param timeout_ms
856 * @param arch_info target-specific description of the algorithm.
858 int target_wait_algorithm(struct target *target,
859 int num_mem_params, struct mem_param *mem_params,
860 int num_reg_params, struct reg_param *reg_params,
861 target_addr_t exit_point, unsigned int timeout_ms,
862 void *arch_info)
864 int retval = ERROR_FAIL;
866 if (!target->type->wait_algorithm) {
867 LOG_ERROR("Target type '%s' does not support %s",
868 target_type_name(target), __func__);
869 goto done;
871 if (!target->running_alg) {
872 LOG_ERROR("Target is not running an algorithm");
873 goto done;
876 retval = target->type->wait_algorithm(target,
877 num_mem_params, mem_params,
878 num_reg_params, reg_params,
879 exit_point, timeout_ms, arch_info);
880 if (retval != ERROR_TARGET_TIMEOUT)
881 target->running_alg = false;
883 done:
884 return retval;
888 * Streams data to a circular buffer on target intended for consumption by code
889 * running asynchronously on target.
891 * This is intended for applications where target-specific native code runs
892 * on the target, receives data from the circular buffer, does something with
893 * it (most likely writing it to a flash memory), and advances the circular
894 * buffer pointer.
896 * This assumes that the helper algorithm has already been loaded to the target,
897 * but has not been started yet. Given memory and register parameters are passed
898 * to the algorithm.
900 * The buffer is defined by (buffer_start, buffer_size) arguments and has the
901 * following format:
903 * [buffer_start + 0, buffer_start + 4):
904 * Write Pointer address (aka head). Written and updated by this
905 * routine when new data is written to the circular buffer.
906 * [buffer_start + 4, buffer_start + 8):
907 * Read Pointer address (aka tail). Updated by code running on the
908 * target after it consumes data.
909 * [buffer_start + 8, buffer_start + buffer_size):
910 * Circular buffer contents.
912 * See contrib/loaders/flash/stm32f1x.S for an example.
914 * @param target used to run the algorithm
915 * @param buffer address on the host where data to be sent is located
916 * @param count number of blocks to send
917 * @param block_size size in bytes of each block
918 * @param num_mem_params count of memory-based params to pass to algorithm
919 * @param mem_params memory-based params to pass to algorithm
920 * @param num_reg_params count of register-based params to pass to algorithm
921 * @param reg_params memory-based params to pass to algorithm
922 * @param buffer_start address on the target of the circular buffer structure
923 * @param buffer_size size of the circular buffer structure
924 * @param entry_point address on the target to execute to start the algorithm
925 * @param exit_point address at which to set a breakpoint to catch the
926 * end of the algorithm; can be 0 if target triggers a breakpoint itself
927 * @param arch_info
930 int target_run_flash_async_algorithm(struct target *target,
931 const uint8_t *buffer, uint32_t count, int block_size,
932 int num_mem_params, struct mem_param *mem_params,
933 int num_reg_params, struct reg_param *reg_params,
934 uint32_t buffer_start, uint32_t buffer_size,
935 uint32_t entry_point, uint32_t exit_point, void *arch_info)
937 int retval;
938 int timeout = 0;
940 const uint8_t *buffer_orig = buffer;
942 /* Set up working area. First word is write pointer, second word is read pointer,
943 * rest is fifo data area. */
944 uint32_t wp_addr = buffer_start;
945 uint32_t rp_addr = buffer_start + 4;
946 uint32_t fifo_start_addr = buffer_start + 8;
947 uint32_t fifo_end_addr = buffer_start + buffer_size;
949 uint32_t wp = fifo_start_addr;
950 uint32_t rp = fifo_start_addr;
952 /* validate block_size is 2^n */
953 assert(IS_PWR_OF_2(block_size));
955 retval = target_write_u32(target, wp_addr, wp);
956 if (retval != ERROR_OK)
957 return retval;
958 retval = target_write_u32(target, rp_addr, rp);
959 if (retval != ERROR_OK)
960 return retval;
962 /* Start up algorithm on target and let it idle while writing the first chunk */
963 retval = target_start_algorithm(target, num_mem_params, mem_params,
964 num_reg_params, reg_params,
965 entry_point,
966 exit_point,
967 arch_info);
969 if (retval != ERROR_OK) {
970 LOG_ERROR("error starting target flash write algorithm");
971 return retval;
974 while (count > 0) {
976 retval = target_read_u32(target, rp_addr, &rp);
977 if (retval != ERROR_OK) {
978 LOG_ERROR("failed to get read pointer");
979 break;
982 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
983 (size_t) (buffer - buffer_orig), count, wp, rp);
985 if (rp == 0) {
986 LOG_ERROR("flash write algorithm aborted by target");
987 retval = ERROR_FLASH_OPERATION_FAILED;
988 break;
991 if (!IS_ALIGNED(rp - fifo_start_addr, block_size) || rp < fifo_start_addr || rp >= fifo_end_addr) {
992 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
993 break;
996 /* Count the number of bytes available in the fifo without
997 * crossing the wrap around. Make sure to not fill it completely,
998 * because that would make wp == rp and that's the empty condition. */
999 uint32_t thisrun_bytes;
1000 if (rp > wp)
1001 thisrun_bytes = rp - wp - block_size;
1002 else if (rp > fifo_start_addr)
1003 thisrun_bytes = fifo_end_addr - wp;
1004 else
1005 thisrun_bytes = fifo_end_addr - wp - block_size;
1007 if (thisrun_bytes == 0) {
1008 /* Throttle polling a bit if transfer is (much) faster than flash
1009 * programming. The exact delay shouldn't matter as long as it's
1010 * less than buffer size / flash speed. This is very unlikely to
1011 * run when using high latency connections such as USB. */
1012 alive_sleep(2);
1014 /* to stop an infinite loop on some targets check and increment a timeout
1015 * this issue was observed on a stellaris using the new ICDI interface */
1016 if (timeout++ >= 2500) {
1017 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1018 return ERROR_FLASH_OPERATION_FAILED;
1020 continue;
1023 /* reset our timeout */
1024 timeout = 0;
1026 /* Limit to the amount of data we actually want to write */
1027 if (thisrun_bytes > count * block_size)
1028 thisrun_bytes = count * block_size;
1030 /* Force end of large blocks to be word aligned */
1031 if (thisrun_bytes >= 16)
1032 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1034 /* Write data to fifo */
1035 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
1036 if (retval != ERROR_OK)
1037 break;
1039 /* Update counters and wrap write pointer */
1040 buffer += thisrun_bytes;
1041 count -= thisrun_bytes / block_size;
1042 wp += thisrun_bytes;
1043 if (wp >= fifo_end_addr)
1044 wp = fifo_start_addr;
1046 /* Store updated write pointer to target */
1047 retval = target_write_u32(target, wp_addr, wp);
1048 if (retval != ERROR_OK)
1049 break;
1051 /* Avoid GDB timeouts */
1052 keep_alive();
1055 if (retval != ERROR_OK) {
1056 /* abort flash write algorithm on target */
1057 target_write_u32(target, wp_addr, 0);
1060 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1061 num_reg_params, reg_params,
1062 exit_point,
1063 10000,
1064 arch_info);
1066 if (retval2 != ERROR_OK) {
1067 LOG_ERROR("error waiting for target flash write algorithm");
1068 retval = retval2;
1071 if (retval == ERROR_OK) {
1072 /* check if algorithm set rp = 0 after fifo writer loop finished */
1073 retval = target_read_u32(target, rp_addr, &rp);
1074 if (retval == ERROR_OK && rp == 0) {
1075 LOG_ERROR("flash write algorithm aborted by target");
1076 retval = ERROR_FLASH_OPERATION_FAILED;
1080 return retval;
1083 int target_run_read_async_algorithm(struct target *target,
1084 uint8_t *buffer, uint32_t count, int block_size,
1085 int num_mem_params, struct mem_param *mem_params,
1086 int num_reg_params, struct reg_param *reg_params,
1087 uint32_t buffer_start, uint32_t buffer_size,
1088 uint32_t entry_point, uint32_t exit_point, void *arch_info)
1090 int retval;
1091 int timeout = 0;
1093 const uint8_t *buffer_orig = buffer;
1095 /* Set up working area. First word is write pointer, second word is read pointer,
1096 * rest is fifo data area. */
1097 uint32_t wp_addr = buffer_start;
1098 uint32_t rp_addr = buffer_start + 4;
1099 uint32_t fifo_start_addr = buffer_start + 8;
1100 uint32_t fifo_end_addr = buffer_start + buffer_size;
1102 uint32_t wp = fifo_start_addr;
1103 uint32_t rp = fifo_start_addr;
1105 /* validate block_size is 2^n */
1106 assert(IS_PWR_OF_2(block_size));
1108 retval = target_write_u32(target, wp_addr, wp);
1109 if (retval != ERROR_OK)
1110 return retval;
1111 retval = target_write_u32(target, rp_addr, rp);
1112 if (retval != ERROR_OK)
1113 return retval;
1115 /* Start up algorithm on target */
1116 retval = target_start_algorithm(target, num_mem_params, mem_params,
1117 num_reg_params, reg_params,
1118 entry_point,
1119 exit_point,
1120 arch_info);
1122 if (retval != ERROR_OK) {
1123 LOG_ERROR("error starting target flash read algorithm");
1124 return retval;
1127 while (count > 0) {
1128 retval = target_read_u32(target, wp_addr, &wp);
1129 if (retval != ERROR_OK) {
1130 LOG_ERROR("failed to get write pointer");
1131 break;
1134 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1135 (size_t)(buffer - buffer_orig), count, wp, rp);
1137 if (wp == 0) {
1138 LOG_ERROR("flash read algorithm aborted by target");
1139 retval = ERROR_FLASH_OPERATION_FAILED;
1140 break;
1143 if (!IS_ALIGNED(wp - fifo_start_addr, block_size) || wp < fifo_start_addr || wp >= fifo_end_addr) {
1144 LOG_ERROR("corrupted fifo write pointer 0x%" PRIx32, wp);
1145 break;
1148 /* Count the number of bytes available in the fifo without
1149 * crossing the wrap around. */
1150 uint32_t thisrun_bytes;
1151 if (wp >= rp)
1152 thisrun_bytes = wp - rp;
1153 else
1154 thisrun_bytes = fifo_end_addr - rp;
1156 if (thisrun_bytes == 0) {
1157 /* Throttle polling a bit if transfer is (much) faster than flash
1158 * reading. The exact delay shouldn't matter as long as it's
1159 * less than buffer size / flash speed. This is very unlikely to
1160 * run when using high latency connections such as USB. */
1161 alive_sleep(2);
1163 /* to stop an infinite loop on some targets check and increment a timeout
1164 * this issue was observed on a stellaris using the new ICDI interface */
1165 if (timeout++ >= 2500) {
1166 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1167 return ERROR_FLASH_OPERATION_FAILED;
1169 continue;
1172 /* Reset our timeout */
1173 timeout = 0;
1175 /* Limit to the amount of data we actually want to read */
1176 if (thisrun_bytes > count * block_size)
1177 thisrun_bytes = count * block_size;
1179 /* Force end of large blocks to be word aligned */
1180 if (thisrun_bytes >= 16)
1181 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1183 /* Read data from fifo */
1184 retval = target_read_buffer(target, rp, thisrun_bytes, buffer);
1185 if (retval != ERROR_OK)
1186 break;
1188 /* Update counters and wrap write pointer */
1189 buffer += thisrun_bytes;
1190 count -= thisrun_bytes / block_size;
1191 rp += thisrun_bytes;
1192 if (rp >= fifo_end_addr)
1193 rp = fifo_start_addr;
1195 /* Store updated write pointer to target */
1196 retval = target_write_u32(target, rp_addr, rp);
1197 if (retval != ERROR_OK)
1198 break;
1200 /* Avoid GDB timeouts */
1201 keep_alive();
1203 if (openocd_is_shutdown_pending()) {
1204 retval = ERROR_SERVER_INTERRUPTED;
1205 break;
1209 if (retval != ERROR_OK) {
1210 /* abort flash write algorithm on target */
1211 target_write_u32(target, rp_addr, 0);
1214 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1215 num_reg_params, reg_params,
1216 exit_point,
1217 10000,
1218 arch_info);
1220 if (retval2 != ERROR_OK) {
1221 LOG_ERROR("error waiting for target flash write algorithm");
1222 retval = retval2;
1225 if (retval == ERROR_OK) {
1226 /* check if algorithm set wp = 0 after fifo writer loop finished */
1227 retval = target_read_u32(target, wp_addr, &wp);
1228 if (retval == ERROR_OK && wp == 0) {
1229 LOG_ERROR("flash read algorithm aborted by target");
1230 retval = ERROR_FLASH_OPERATION_FAILED;
1234 return retval;
1237 int target_read_memory(struct target *target,
1238 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1240 if (!target_was_examined(target)) {
1241 LOG_ERROR("Target not examined yet");
1242 return ERROR_FAIL;
1244 if (!target->type->read_memory) {
1245 LOG_ERROR("Target %s doesn't support read_memory", target_name(target));
1246 return ERROR_FAIL;
1248 return target->type->read_memory(target, address, size, count, buffer);
1251 int target_read_phys_memory(struct target *target,
1252 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1254 if (!target_was_examined(target)) {
1255 LOG_ERROR("Target not examined yet");
1256 return ERROR_FAIL;
1258 if (!target->type->read_phys_memory) {
1259 LOG_ERROR("Target %s doesn't support read_phys_memory", target_name(target));
1260 return ERROR_FAIL;
1262 return target->type->read_phys_memory(target, address, size, count, buffer);
1265 int target_write_memory(struct target *target,
1266 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1268 if (!target_was_examined(target)) {
1269 LOG_ERROR("Target not examined yet");
1270 return ERROR_FAIL;
1272 if (!target->type->write_memory) {
1273 LOG_ERROR("Target %s doesn't support write_memory", target_name(target));
1274 return ERROR_FAIL;
1276 return target->type->write_memory(target, address, size, count, buffer);
1279 int target_write_phys_memory(struct target *target,
1280 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1282 if (!target_was_examined(target)) {
1283 LOG_ERROR("Target not examined yet");
1284 return ERROR_FAIL;
1286 if (!target->type->write_phys_memory) {
1287 LOG_ERROR("Target %s doesn't support write_phys_memory", target_name(target));
1288 return ERROR_FAIL;
1290 return target->type->write_phys_memory(target, address, size, count, buffer);
1293 int target_add_breakpoint(struct target *target,
1294 struct breakpoint *breakpoint)
1296 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1297 LOG_TARGET_ERROR(target, "not halted (add breakpoint)");
1298 return ERROR_TARGET_NOT_HALTED;
1300 return target->type->add_breakpoint(target, breakpoint);
1303 int target_add_context_breakpoint(struct target *target,
1304 struct breakpoint *breakpoint)
1306 if (target->state != TARGET_HALTED) {
1307 LOG_TARGET_ERROR(target, "not halted (add context breakpoint)");
1308 return ERROR_TARGET_NOT_HALTED;
1310 return target->type->add_context_breakpoint(target, breakpoint);
1313 int target_add_hybrid_breakpoint(struct target *target,
1314 struct breakpoint *breakpoint)
1316 if (target->state != TARGET_HALTED) {
1317 LOG_TARGET_ERROR(target, "not halted (add hybrid breakpoint)");
1318 return ERROR_TARGET_NOT_HALTED;
1320 return target->type->add_hybrid_breakpoint(target, breakpoint);
1323 int target_remove_breakpoint(struct target *target,
1324 struct breakpoint *breakpoint)
1326 return target->type->remove_breakpoint(target, breakpoint);
1329 int target_add_watchpoint(struct target *target,
1330 struct watchpoint *watchpoint)
1332 if (target->state != TARGET_HALTED) {
1333 LOG_TARGET_ERROR(target, "not halted (add watchpoint)");
1334 return ERROR_TARGET_NOT_HALTED;
1336 return target->type->add_watchpoint(target, watchpoint);
1338 int target_remove_watchpoint(struct target *target,
1339 struct watchpoint *watchpoint)
1341 return target->type->remove_watchpoint(target, watchpoint);
1343 int target_hit_watchpoint(struct target *target,
1344 struct watchpoint **hit_watchpoint)
1346 if (target->state != TARGET_HALTED) {
1347 LOG_TARGET_ERROR(target, "not halted (hit watchpoint)");
1348 return ERROR_TARGET_NOT_HALTED;
1351 if (!target->type->hit_watchpoint) {
1352 /* For backward compatible, if hit_watchpoint is not implemented,
1353 * return ERROR_FAIL such that gdb_server will not take the nonsense
1354 * information. */
1355 return ERROR_FAIL;
1358 return target->type->hit_watchpoint(target, hit_watchpoint);
1361 const char *target_get_gdb_arch(const struct target *target)
1363 if (!target->type->get_gdb_arch)
1364 return NULL;
1365 return target->type->get_gdb_arch(target);
1368 int target_get_gdb_reg_list(struct target *target,
1369 struct reg **reg_list[], int *reg_list_size,
1370 enum target_register_class reg_class)
1372 int result = ERROR_FAIL;
1374 if (!target_was_examined(target)) {
1375 LOG_ERROR("Target not examined yet");
1376 goto done;
1379 result = target->type->get_gdb_reg_list(target, reg_list,
1380 reg_list_size, reg_class);
1382 done:
1383 if (result != ERROR_OK) {
1384 *reg_list = NULL;
1385 *reg_list_size = 0;
1387 return result;
1390 int target_get_gdb_reg_list_noread(struct target *target,
1391 struct reg **reg_list[], int *reg_list_size,
1392 enum target_register_class reg_class)
1394 if (target->type->get_gdb_reg_list_noread &&
1395 target->type->get_gdb_reg_list_noread(target, reg_list,
1396 reg_list_size, reg_class) == ERROR_OK)
1397 return ERROR_OK;
1398 return target_get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1401 bool target_supports_gdb_connection(const struct target *target)
1404 * exclude all the targets that don't provide get_gdb_reg_list
1405 * or that have explicit gdb_max_connection == 0
1407 return !!target->type->get_gdb_reg_list && !!target->gdb_max_connections;
1410 int target_step(struct target *target,
1411 int current, target_addr_t address, int handle_breakpoints)
1413 int retval;
1415 target_call_event_callbacks(target, TARGET_EVENT_STEP_START);
1417 retval = target->type->step(target, current, address, handle_breakpoints);
1418 if (retval != ERROR_OK)
1419 return retval;
1421 target_call_event_callbacks(target, TARGET_EVENT_STEP_END);
1423 return retval;
1426 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1428 if (target->state != TARGET_HALTED) {
1429 LOG_TARGET_ERROR(target, "not halted (gdb fileio)");
1430 return ERROR_TARGET_NOT_HALTED;
1432 return target->type->get_gdb_fileio_info(target, fileio_info);
1435 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1437 if (target->state != TARGET_HALTED) {
1438 LOG_TARGET_ERROR(target, "not halted (gdb fileio end)");
1439 return ERROR_TARGET_NOT_HALTED;
1441 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1444 target_addr_t target_address_max(struct target *target)
1446 unsigned bits = target_address_bits(target);
1447 if (sizeof(target_addr_t) * 8 == bits)
1448 return (target_addr_t) -1;
1449 else
1450 return (((target_addr_t) 1) << bits) - 1;
1453 unsigned target_address_bits(struct target *target)
1455 if (target->type->address_bits)
1456 return target->type->address_bits(target);
1457 return 32;
1460 unsigned int target_data_bits(struct target *target)
1462 if (target->type->data_bits)
1463 return target->type->data_bits(target);
1464 return 32;
1467 static int target_profiling(struct target *target, uint32_t *samples,
1468 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1470 return target->type->profiling(target, samples, max_num_samples,
1471 num_samples, seconds);
1474 static int handle_target(void *priv);
1476 static int target_init_one(struct command_context *cmd_ctx,
1477 struct target *target)
1479 target_reset_examined(target);
1481 struct target_type *type = target->type;
1482 if (!type->examine)
1483 type->examine = default_examine;
1485 if (!type->check_reset)
1486 type->check_reset = default_check_reset;
1488 assert(type->init_target);
1490 int retval = type->init_target(cmd_ctx, target);
1491 if (retval != ERROR_OK) {
1492 LOG_ERROR("target '%s' init failed", target_name(target));
1493 return retval;
1496 /* Sanity-check MMU support ... stub in what we must, to help
1497 * implement it in stages, but warn if we need to do so.
1499 if (type->mmu) {
1500 if (!type->virt2phys) {
1501 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1502 type->virt2phys = identity_virt2phys;
1504 } else {
1505 /* Make sure no-MMU targets all behave the same: make no
1506 * distinction between physical and virtual addresses, and
1507 * ensure that virt2phys() is always an identity mapping.
1509 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1510 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1512 type->mmu = no_mmu;
1513 type->write_phys_memory = type->write_memory;
1514 type->read_phys_memory = type->read_memory;
1515 type->virt2phys = identity_virt2phys;
1518 if (!target->type->read_buffer)
1519 target->type->read_buffer = target_read_buffer_default;
1521 if (!target->type->write_buffer)
1522 target->type->write_buffer = target_write_buffer_default;
1524 if (!target->type->get_gdb_fileio_info)
1525 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1527 if (!target->type->gdb_fileio_end)
1528 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1530 if (!target->type->profiling)
1531 target->type->profiling = target_profiling_default;
1533 return ERROR_OK;
1536 static int target_init(struct command_context *cmd_ctx)
1538 struct target *target;
1539 int retval;
1541 for (target = all_targets; target; target = target->next) {
1542 retval = target_init_one(cmd_ctx, target);
1543 if (retval != ERROR_OK)
1544 return retval;
1547 if (!all_targets)
1548 return ERROR_OK;
1550 retval = target_register_user_commands(cmd_ctx);
1551 if (retval != ERROR_OK)
1552 return retval;
1554 retval = target_register_timer_callback(&handle_target,
1555 polling_interval, TARGET_TIMER_TYPE_PERIODIC, cmd_ctx->interp);
1556 if (retval != ERROR_OK)
1557 return retval;
1559 return ERROR_OK;
1562 COMMAND_HANDLER(handle_target_init_command)
1564 int retval;
1566 if (CMD_ARGC != 0)
1567 return ERROR_COMMAND_SYNTAX_ERROR;
1569 static bool target_initialized;
1570 if (target_initialized) {
1571 LOG_INFO("'target init' has already been called");
1572 return ERROR_OK;
1574 target_initialized = true;
1576 retval = command_run_line(CMD_CTX, "init_targets");
1577 if (retval != ERROR_OK)
1578 return retval;
1580 retval = command_run_line(CMD_CTX, "init_target_events");
1581 if (retval != ERROR_OK)
1582 return retval;
1584 retval = command_run_line(CMD_CTX, "init_board");
1585 if (retval != ERROR_OK)
1586 return retval;
1588 LOG_DEBUG("Initializing targets...");
1589 return target_init(CMD_CTX);
1592 int target_register_event_callback(int (*callback)(struct target *target,
1593 enum target_event event, void *priv), void *priv)
1595 struct target_event_callback **callbacks_p = &target_event_callbacks;
1597 if (!callback)
1598 return ERROR_COMMAND_SYNTAX_ERROR;
1600 if (*callbacks_p) {
1601 while ((*callbacks_p)->next)
1602 callbacks_p = &((*callbacks_p)->next);
1603 callbacks_p = &((*callbacks_p)->next);
1606 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1607 (*callbacks_p)->callback = callback;
1608 (*callbacks_p)->priv = priv;
1609 (*callbacks_p)->next = NULL;
1611 return ERROR_OK;
1614 int target_register_reset_callback(int (*callback)(struct target *target,
1615 enum target_reset_mode reset_mode, void *priv), void *priv)
1617 struct target_reset_callback *entry;
1619 if (!callback)
1620 return ERROR_COMMAND_SYNTAX_ERROR;
1622 entry = malloc(sizeof(struct target_reset_callback));
1623 if (!entry) {
1624 LOG_ERROR("error allocating buffer for reset callback entry");
1625 return ERROR_COMMAND_SYNTAX_ERROR;
1628 entry->callback = callback;
1629 entry->priv = priv;
1630 list_add(&entry->list, &target_reset_callback_list);
1633 return ERROR_OK;
1636 int target_register_trace_callback(int (*callback)(struct target *target,
1637 size_t len, uint8_t *data, void *priv), void *priv)
1639 struct target_trace_callback *entry;
1641 if (!callback)
1642 return ERROR_COMMAND_SYNTAX_ERROR;
1644 entry = malloc(sizeof(struct target_trace_callback));
1645 if (!entry) {
1646 LOG_ERROR("error allocating buffer for trace callback entry");
1647 return ERROR_COMMAND_SYNTAX_ERROR;
1650 entry->callback = callback;
1651 entry->priv = priv;
1652 list_add(&entry->list, &target_trace_callback_list);
1655 return ERROR_OK;
1658 int target_register_timer_callback(int (*callback)(void *priv),
1659 unsigned int time_ms, enum target_timer_type type, void *priv)
1661 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1663 if (!callback)
1664 return ERROR_COMMAND_SYNTAX_ERROR;
1666 if (*callbacks_p) {
1667 while ((*callbacks_p)->next)
1668 callbacks_p = &((*callbacks_p)->next);
1669 callbacks_p = &((*callbacks_p)->next);
1672 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1673 (*callbacks_p)->callback = callback;
1674 (*callbacks_p)->type = type;
1675 (*callbacks_p)->time_ms = time_ms;
1676 (*callbacks_p)->removed = false;
1678 (*callbacks_p)->when = timeval_ms() + time_ms;
1679 target_timer_next_event_value = MIN(target_timer_next_event_value, (*callbacks_p)->when);
1681 (*callbacks_p)->priv = priv;
1682 (*callbacks_p)->next = NULL;
1684 return ERROR_OK;
1687 int target_unregister_event_callback(int (*callback)(struct target *target,
1688 enum target_event event, void *priv), void *priv)
1690 struct target_event_callback **p = &target_event_callbacks;
1691 struct target_event_callback *c = target_event_callbacks;
1693 if (!callback)
1694 return ERROR_COMMAND_SYNTAX_ERROR;
1696 while (c) {
1697 struct target_event_callback *next = c->next;
1698 if ((c->callback == callback) && (c->priv == priv)) {
1699 *p = next;
1700 free(c);
1701 return ERROR_OK;
1702 } else
1703 p = &(c->next);
1704 c = next;
1707 return ERROR_OK;
1710 int target_unregister_reset_callback(int (*callback)(struct target *target,
1711 enum target_reset_mode reset_mode, void *priv), void *priv)
1713 struct target_reset_callback *entry;
1715 if (!callback)
1716 return ERROR_COMMAND_SYNTAX_ERROR;
1718 list_for_each_entry(entry, &target_reset_callback_list, list) {
1719 if (entry->callback == callback && entry->priv == priv) {
1720 list_del(&entry->list);
1721 free(entry);
1722 break;
1726 return ERROR_OK;
1729 int target_unregister_trace_callback(int (*callback)(struct target *target,
1730 size_t len, uint8_t *data, void *priv), void *priv)
1732 struct target_trace_callback *entry;
1734 if (!callback)
1735 return ERROR_COMMAND_SYNTAX_ERROR;
1737 list_for_each_entry(entry, &target_trace_callback_list, list) {
1738 if (entry->callback == callback && entry->priv == priv) {
1739 list_del(&entry->list);
1740 free(entry);
1741 break;
1745 return ERROR_OK;
1748 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1750 if (!callback)
1751 return ERROR_COMMAND_SYNTAX_ERROR;
1753 for (struct target_timer_callback *c = target_timer_callbacks;
1754 c; c = c->next) {
1755 if ((c->callback == callback) && (c->priv == priv)) {
1756 c->removed = true;
1757 return ERROR_OK;
1761 return ERROR_FAIL;
1764 int target_call_event_callbacks(struct target *target, enum target_event event)
1766 struct target_event_callback *callback = target_event_callbacks;
1767 struct target_event_callback *next_callback;
1769 if (event == TARGET_EVENT_HALTED) {
1770 /* execute early halted first */
1771 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1774 LOG_DEBUG("target event %i (%s) for core %s", event,
1775 target_event_name(event),
1776 target_name(target));
1778 target_handle_event(target, event);
1780 while (callback) {
1781 next_callback = callback->next;
1782 callback->callback(target, event, callback->priv);
1783 callback = next_callback;
1786 return ERROR_OK;
1789 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1791 struct target_reset_callback *callback;
1793 LOG_DEBUG("target reset %i (%s)", reset_mode,
1794 nvp_value2name(nvp_reset_modes, reset_mode)->name);
1796 list_for_each_entry(callback, &target_reset_callback_list, list)
1797 callback->callback(target, reset_mode, callback->priv);
1799 return ERROR_OK;
1802 int target_call_trace_callbacks(struct target *target, size_t len, uint8_t *data)
1804 struct target_trace_callback *callback;
1806 list_for_each_entry(callback, &target_trace_callback_list, list)
1807 callback->callback(target, len, data, callback->priv);
1809 return ERROR_OK;
1812 static int target_timer_callback_periodic_restart(
1813 struct target_timer_callback *cb, int64_t *now)
1815 cb->when = *now + cb->time_ms;
1816 return ERROR_OK;
1819 static int target_call_timer_callback(struct target_timer_callback *cb,
1820 int64_t *now)
1822 cb->callback(cb->priv);
1824 if (cb->type == TARGET_TIMER_TYPE_PERIODIC)
1825 return target_timer_callback_periodic_restart(cb, now);
1827 return target_unregister_timer_callback(cb->callback, cb->priv);
1830 static int target_call_timer_callbacks_check_time(int checktime)
1832 static bool callback_processing;
1834 /* Do not allow nesting */
1835 if (callback_processing)
1836 return ERROR_OK;
1838 callback_processing = true;
1840 keep_alive();
1842 int64_t now = timeval_ms();
1844 /* Initialize to a default value that's a ways into the future.
1845 * The loop below will make it closer to now if there are
1846 * callbacks that want to be called sooner. */
1847 target_timer_next_event_value = now + 1000;
1849 /* Store an address of the place containing a pointer to the
1850 * next item; initially, that's a standalone "root of the
1851 * list" variable. */
1852 struct target_timer_callback **callback = &target_timer_callbacks;
1853 while (callback && *callback) {
1854 if ((*callback)->removed) {
1855 struct target_timer_callback *p = *callback;
1856 *callback = (*callback)->next;
1857 free(p);
1858 continue;
1861 bool call_it = (*callback)->callback &&
1862 ((!checktime && (*callback)->type == TARGET_TIMER_TYPE_PERIODIC) ||
1863 now >= (*callback)->when);
1865 if (call_it)
1866 target_call_timer_callback(*callback, &now);
1868 if (!(*callback)->removed && (*callback)->when < target_timer_next_event_value)
1869 target_timer_next_event_value = (*callback)->when;
1871 callback = &(*callback)->next;
1874 callback_processing = false;
1875 return ERROR_OK;
1878 int target_call_timer_callbacks(void)
1880 return target_call_timer_callbacks_check_time(1);
1883 /* invoke periodic callbacks immediately */
1884 int target_call_timer_callbacks_now(void)
1886 return target_call_timer_callbacks_check_time(0);
1889 int64_t target_timer_next_event(void)
1891 return target_timer_next_event_value;
1894 /* Prints the working area layout for debug purposes */
1895 static void print_wa_layout(struct target *target)
1897 struct working_area *c = target->working_areas;
1899 while (c) {
1900 LOG_DEBUG("%c%c " TARGET_ADDR_FMT "-" TARGET_ADDR_FMT " (%" PRIu32 " bytes)",
1901 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1902 c->address, c->address + c->size - 1, c->size);
1903 c = c->next;
1907 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1908 static void target_split_working_area(struct working_area *area, uint32_t size)
1910 assert(area->free); /* Shouldn't split an allocated area */
1911 assert(size <= area->size); /* Caller should guarantee this */
1913 /* Split only if not already the right size */
1914 if (size < area->size) {
1915 struct working_area *new_wa = malloc(sizeof(*new_wa));
1917 if (!new_wa)
1918 return;
1920 new_wa->next = area->next;
1921 new_wa->size = area->size - size;
1922 new_wa->address = area->address + size;
1923 new_wa->backup = NULL;
1924 new_wa->user = NULL;
1925 new_wa->free = true;
1927 area->next = new_wa;
1928 area->size = size;
1930 /* If backup memory was allocated to this area, it has the wrong size
1931 * now so free it and it will be reallocated if/when needed */
1932 free(area->backup);
1933 area->backup = NULL;
1937 /* Merge all adjacent free areas into one */
1938 static void target_merge_working_areas(struct target *target)
1940 struct working_area *c = target->working_areas;
1942 while (c && c->next) {
1943 assert(c->next->address == c->address + c->size); /* This is an invariant */
1945 /* Find two adjacent free areas */
1946 if (c->free && c->next->free) {
1947 /* Merge the last into the first */
1948 c->size += c->next->size;
1950 /* Remove the last */
1951 struct working_area *to_be_freed = c->next;
1952 c->next = c->next->next;
1953 free(to_be_freed->backup);
1954 free(to_be_freed);
1956 /* If backup memory was allocated to the remaining area, it's has
1957 * the wrong size now */
1958 free(c->backup);
1959 c->backup = NULL;
1960 } else {
1961 c = c->next;
1966 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1968 /* Reevaluate working area address based on MMU state*/
1969 if (!target->working_areas) {
1970 int retval;
1971 int enabled;
1973 retval = target->type->mmu(target, &enabled);
1974 if (retval != ERROR_OK)
1975 return retval;
1977 if (!enabled) {
1978 if (target->working_area_phys_spec) {
1979 LOG_DEBUG("MMU disabled, using physical "
1980 "address for working memory " TARGET_ADDR_FMT,
1981 target->working_area_phys);
1982 target->working_area = target->working_area_phys;
1983 } else {
1984 LOG_ERROR("No working memory available. "
1985 "Specify -work-area-phys to target.");
1986 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1988 } else {
1989 if (target->working_area_virt_spec) {
1990 LOG_DEBUG("MMU enabled, using virtual "
1991 "address for working memory " TARGET_ADDR_FMT,
1992 target->working_area_virt);
1993 target->working_area = target->working_area_virt;
1994 } else {
1995 LOG_ERROR("No working memory available. "
1996 "Specify -work-area-virt to target.");
1997 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2001 /* Set up initial working area on first call */
2002 struct working_area *new_wa = malloc(sizeof(*new_wa));
2003 if (new_wa) {
2004 new_wa->next = NULL;
2005 new_wa->size = ALIGN_DOWN(target->working_area_size, 4); /* 4-byte align */
2006 new_wa->address = target->working_area;
2007 new_wa->backup = NULL;
2008 new_wa->user = NULL;
2009 new_wa->free = true;
2012 target->working_areas = new_wa;
2015 /* only allocate multiples of 4 byte */
2016 size = ALIGN_UP(size, 4);
2018 struct working_area *c = target->working_areas;
2020 /* Find the first large enough working area */
2021 while (c) {
2022 if (c->free && c->size >= size)
2023 break;
2024 c = c->next;
2027 if (!c)
2028 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2030 /* Split the working area into the requested size */
2031 target_split_working_area(c, size);
2033 LOG_DEBUG("allocated new working area of %" PRIu32 " bytes at address " TARGET_ADDR_FMT,
2034 size, c->address);
2036 if (target->backup_working_area) {
2037 if (!c->backup) {
2038 c->backup = malloc(c->size);
2039 if (!c->backup)
2040 return ERROR_FAIL;
2043 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
2044 if (retval != ERROR_OK)
2045 return retval;
2048 /* mark as used, and return the new (reused) area */
2049 c->free = false;
2050 *area = c;
2052 /* user pointer */
2053 c->user = area;
2055 print_wa_layout(target);
2057 return ERROR_OK;
2060 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
2062 int retval;
2064 retval = target_alloc_working_area_try(target, size, area);
2065 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
2066 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
2067 return retval;
2071 static int target_restore_working_area(struct target *target, struct working_area *area)
2073 int retval = ERROR_OK;
2075 if (target->backup_working_area && area->backup) {
2076 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
2077 if (retval != ERROR_OK)
2078 LOG_ERROR("failed to restore %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2079 area->size, area->address);
2082 return retval;
2085 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
2086 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
2088 if (!area || area->free)
2089 return ERROR_OK;
2091 int retval = ERROR_OK;
2092 if (restore) {
2093 retval = target_restore_working_area(target, area);
2094 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
2095 if (retval != ERROR_OK)
2096 return retval;
2099 area->free = true;
2101 LOG_DEBUG("freed %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2102 area->size, area->address);
2104 /* mark user pointer invalid */
2105 /* TODO: Is this really safe? It points to some previous caller's memory.
2106 * How could we know that the area pointer is still in that place and not
2107 * some other vital data? What's the purpose of this, anyway? */
2108 *area->user = NULL;
2109 area->user = NULL;
2111 target_merge_working_areas(target);
2113 print_wa_layout(target);
2115 return retval;
2118 int target_free_working_area(struct target *target, struct working_area *area)
2120 return target_free_working_area_restore(target, area, 1);
2123 /* free resources and restore memory, if restoring memory fails,
2124 * free up resources anyway
2126 static void target_free_all_working_areas_restore(struct target *target, int restore)
2128 struct working_area *c = target->working_areas;
2130 LOG_DEBUG("freeing all working areas");
2132 /* Loop through all areas, restoring the allocated ones and marking them as free */
2133 while (c) {
2134 if (!c->free) {
2135 if (restore)
2136 target_restore_working_area(target, c);
2137 c->free = true;
2138 *c->user = NULL; /* Same as above */
2139 c->user = NULL;
2141 c = c->next;
2144 /* Run a merge pass to combine all areas into one */
2145 target_merge_working_areas(target);
2147 print_wa_layout(target);
2150 void target_free_all_working_areas(struct target *target)
2152 target_free_all_working_areas_restore(target, 1);
2154 /* Now we have none or only one working area marked as free */
2155 if (target->working_areas) {
2156 /* Free the last one to allow on-the-fly moving and resizing */
2157 free(target->working_areas->backup);
2158 free(target->working_areas);
2159 target->working_areas = NULL;
2163 /* Find the largest number of bytes that can be allocated */
2164 uint32_t target_get_working_area_avail(struct target *target)
2166 struct working_area *c = target->working_areas;
2167 uint32_t max_size = 0;
2169 if (!c)
2170 return ALIGN_DOWN(target->working_area_size, 4);
2172 while (c) {
2173 if (c->free && max_size < c->size)
2174 max_size = c->size;
2176 c = c->next;
2179 return max_size;
2182 static void target_destroy(struct target *target)
2184 breakpoint_remove_all(target);
2185 watchpoint_remove_all(target);
2187 if (target->type->deinit_target)
2188 target->type->deinit_target(target);
2190 if (target->semihosting)
2191 free(target->semihosting->basedir);
2192 free(target->semihosting);
2194 jtag_unregister_event_callback(jtag_enable_callback, target);
2196 struct target_event_action *teap = target->event_action;
2197 while (teap) {
2198 struct target_event_action *next = teap->next;
2199 Jim_DecrRefCount(teap->interp, teap->body);
2200 free(teap);
2201 teap = next;
2204 target_free_all_working_areas(target);
2206 /* release the targets SMP list */
2207 if (target->smp) {
2208 struct target_list *head, *tmp;
2210 list_for_each_entry_safe(head, tmp, target->smp_targets, lh) {
2211 list_del(&head->lh);
2212 head->target->smp = 0;
2213 free(head);
2215 if (target->smp_targets != &empty_smp_targets)
2216 free(target->smp_targets);
2217 target->smp = 0;
2220 rtos_destroy(target);
2222 free(target->gdb_port_override);
2223 free(target->type);
2224 free(target->trace_info);
2225 free(target->fileio_info);
2226 free(target->cmd_name);
2227 free(target);
2230 void target_quit(void)
2232 struct target_event_callback *pe = target_event_callbacks;
2233 while (pe) {
2234 struct target_event_callback *t = pe->next;
2235 free(pe);
2236 pe = t;
2238 target_event_callbacks = NULL;
2240 struct target_timer_callback *pt = target_timer_callbacks;
2241 while (pt) {
2242 struct target_timer_callback *t = pt->next;
2243 free(pt);
2244 pt = t;
2246 target_timer_callbacks = NULL;
2248 for (struct target *target = all_targets; target;) {
2249 struct target *tmp;
2251 tmp = target->next;
2252 target_destroy(target);
2253 target = tmp;
2256 all_targets = NULL;
2259 int target_arch_state(struct target *target)
2261 int retval;
2262 if (!target) {
2263 LOG_WARNING("No target has been configured");
2264 return ERROR_OK;
2267 if (target->state != TARGET_HALTED)
2268 return ERROR_OK;
2270 retval = target->type->arch_state(target);
2271 return retval;
2274 static int target_get_gdb_fileio_info_default(struct target *target,
2275 struct gdb_fileio_info *fileio_info)
2277 /* If target does not support semi-hosting function, target
2278 has no need to provide .get_gdb_fileio_info callback.
2279 It just return ERROR_FAIL and gdb_server will return "Txx"
2280 as target halted every time. */
2281 return ERROR_FAIL;
2284 static int target_gdb_fileio_end_default(struct target *target,
2285 int retcode, int fileio_errno, bool ctrl_c)
2287 return ERROR_OK;
2290 int target_profiling_default(struct target *target, uint32_t *samples,
2291 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
2293 struct timeval timeout, now;
2295 gettimeofday(&timeout, NULL);
2296 timeval_add_time(&timeout, seconds, 0);
2298 LOG_INFO("Starting profiling. Halting and resuming the"
2299 " target as often as we can...");
2301 uint32_t sample_count = 0;
2302 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2303 struct reg *reg = register_get_by_name(target->reg_cache, "pc", true);
2305 int retval = ERROR_OK;
2306 for (;;) {
2307 target_poll(target);
2308 if (target->state == TARGET_HALTED) {
2309 uint32_t t = buf_get_u32(reg->value, 0, 32);
2310 samples[sample_count++] = t;
2311 /* current pc, addr = 0, do not handle breakpoints, not debugging */
2312 retval = target_resume(target, 1, 0, 0, 0);
2313 target_poll(target);
2314 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2315 } else if (target->state == TARGET_RUNNING) {
2316 /* We want to quickly sample the PC. */
2317 retval = target_halt(target);
2318 } else {
2319 LOG_INFO("Target not halted or running");
2320 retval = ERROR_OK;
2321 break;
2324 if (retval != ERROR_OK)
2325 break;
2327 gettimeofday(&now, NULL);
2328 if ((sample_count >= max_num_samples) || timeval_compare(&now, &timeout) >= 0) {
2329 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2330 break;
2334 *num_samples = sample_count;
2335 return retval;
2338 /* Single aligned words are guaranteed to use 16 or 32 bit access
2339 * mode respectively, otherwise data is handled as quickly as
2340 * possible
2342 int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
2344 LOG_DEBUG("writing buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2345 size, address);
2347 if (!target_was_examined(target)) {
2348 LOG_ERROR("Target not examined yet");
2349 return ERROR_FAIL;
2352 if (size == 0)
2353 return ERROR_OK;
2355 if ((address + size - 1) < address) {
2356 /* GDB can request this when e.g. PC is 0xfffffffc */
2357 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2358 address,
2359 size);
2360 return ERROR_FAIL;
2363 return target->type->write_buffer(target, address, size, buffer);
2366 static int target_write_buffer_default(struct target *target,
2367 target_addr_t address, uint32_t count, const uint8_t *buffer)
2369 uint32_t size;
2370 unsigned int data_bytes = target_data_bits(target) / 8;
2372 /* Align up to maximum bytes. The loop condition makes sure the next pass
2373 * will have something to do with the size we leave to it. */
2374 for (size = 1;
2375 size < data_bytes && count >= size * 2 + (address & size);
2376 size *= 2) {
2377 if (address & size) {
2378 int retval = target_write_memory(target, address, size, 1, buffer);
2379 if (retval != ERROR_OK)
2380 return retval;
2381 address += size;
2382 count -= size;
2383 buffer += size;
2387 /* Write the data with as large access size as possible. */
2388 for (; size > 0; size /= 2) {
2389 uint32_t aligned = count - count % size;
2390 if (aligned > 0) {
2391 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2392 if (retval != ERROR_OK)
2393 return retval;
2394 address += aligned;
2395 count -= aligned;
2396 buffer += aligned;
2400 return ERROR_OK;
2403 /* Single aligned words are guaranteed to use 16 or 32 bit access
2404 * mode respectively, otherwise data is handled as quickly as
2405 * possible
2407 int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
2409 LOG_DEBUG("reading buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2410 size, address);
2412 if (!target_was_examined(target)) {
2413 LOG_ERROR("Target not examined yet");
2414 return ERROR_FAIL;
2417 if (size == 0)
2418 return ERROR_OK;
2420 if ((address + size - 1) < address) {
2421 /* GDB can request this when e.g. PC is 0xfffffffc */
2422 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2423 address,
2424 size);
2425 return ERROR_FAIL;
2428 return target->type->read_buffer(target, address, size, buffer);
2431 static int target_read_buffer_default(struct target *target, target_addr_t address, uint32_t count, uint8_t *buffer)
2433 uint32_t size;
2434 unsigned int data_bytes = target_data_bits(target) / 8;
2436 /* Align up to maximum bytes. The loop condition makes sure the next pass
2437 * will have something to do with the size we leave to it. */
2438 for (size = 1;
2439 size < data_bytes && count >= size * 2 + (address & size);
2440 size *= 2) {
2441 if (address & size) {
2442 int retval = target_read_memory(target, address, size, 1, buffer);
2443 if (retval != ERROR_OK)
2444 return retval;
2445 address += size;
2446 count -= size;
2447 buffer += size;
2451 /* Read the data with as large access size as possible. */
2452 for (; size > 0; size /= 2) {
2453 uint32_t aligned = count - count % size;
2454 if (aligned > 0) {
2455 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2456 if (retval != ERROR_OK)
2457 return retval;
2458 address += aligned;
2459 count -= aligned;
2460 buffer += aligned;
2464 return ERROR_OK;
2467 int target_checksum_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t *crc)
2469 uint8_t *buffer;
2470 int retval;
2471 uint32_t i;
2472 uint32_t checksum = 0;
2473 if (!target_was_examined(target)) {
2474 LOG_ERROR("Target not examined yet");
2475 return ERROR_FAIL;
2477 if (!target->type->checksum_memory) {
2478 LOG_ERROR("Target %s doesn't support checksum_memory", target_name(target));
2479 return ERROR_FAIL;
2482 retval = target->type->checksum_memory(target, address, size, &checksum);
2483 if (retval != ERROR_OK) {
2484 buffer = malloc(size);
2485 if (!buffer) {
2486 LOG_ERROR("error allocating buffer for section (%" PRIu32 " bytes)", size);
2487 return ERROR_COMMAND_SYNTAX_ERROR;
2489 retval = target_read_buffer(target, address, size, buffer);
2490 if (retval != ERROR_OK) {
2491 free(buffer);
2492 return retval;
2495 /* convert to target endianness */
2496 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2497 uint32_t target_data;
2498 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2499 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2502 retval = image_calculate_checksum(buffer, size, &checksum);
2503 free(buffer);
2506 *crc = checksum;
2508 return retval;
2511 int target_blank_check_memory(struct target *target,
2512 struct target_memory_check_block *blocks, int num_blocks,
2513 uint8_t erased_value)
2515 if (!target_was_examined(target)) {
2516 LOG_ERROR("Target not examined yet");
2517 return ERROR_FAIL;
2520 if (!target->type->blank_check_memory)
2521 return ERROR_NOT_IMPLEMENTED;
2523 return target->type->blank_check_memory(target, blocks, num_blocks, erased_value);
2526 int target_read_u64(struct target *target, target_addr_t address, uint64_t *value)
2528 uint8_t value_buf[8];
2529 if (!target_was_examined(target)) {
2530 LOG_ERROR("Target not examined yet");
2531 return ERROR_FAIL;
2534 int retval = target_read_memory(target, address, 8, 1, value_buf);
2536 if (retval == ERROR_OK) {
2537 *value = target_buffer_get_u64(target, value_buf);
2538 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2539 address,
2540 *value);
2541 } else {
2542 *value = 0x0;
2543 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2544 address);
2547 return retval;
2550 int target_read_u32(struct target *target, target_addr_t address, uint32_t *value)
2552 uint8_t value_buf[4];
2553 if (!target_was_examined(target)) {
2554 LOG_ERROR("Target not examined yet");
2555 return ERROR_FAIL;
2558 int retval = target_read_memory(target, address, 4, 1, value_buf);
2560 if (retval == ERROR_OK) {
2561 *value = target_buffer_get_u32(target, value_buf);
2562 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2563 address,
2564 *value);
2565 } else {
2566 *value = 0x0;
2567 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2568 address);
2571 return retval;
2574 int target_read_u16(struct target *target, target_addr_t address, uint16_t *value)
2576 uint8_t value_buf[2];
2577 if (!target_was_examined(target)) {
2578 LOG_ERROR("Target not examined yet");
2579 return ERROR_FAIL;
2582 int retval = target_read_memory(target, address, 2, 1, value_buf);
2584 if (retval == ERROR_OK) {
2585 *value = target_buffer_get_u16(target, value_buf);
2586 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%4.4" PRIx16,
2587 address,
2588 *value);
2589 } else {
2590 *value = 0x0;
2591 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2592 address);
2595 return retval;
2598 int target_read_u8(struct target *target, target_addr_t address, uint8_t *value)
2600 if (!target_was_examined(target)) {
2601 LOG_ERROR("Target not examined yet");
2602 return ERROR_FAIL;
2605 int retval = target_read_memory(target, address, 1, 1, value);
2607 if (retval == ERROR_OK) {
2608 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2609 address,
2610 *value);
2611 } else {
2612 *value = 0x0;
2613 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2614 address);
2617 return retval;
2620 int target_write_u64(struct target *target, target_addr_t address, uint64_t value)
2622 int retval;
2623 uint8_t value_buf[8];
2624 if (!target_was_examined(target)) {
2625 LOG_ERROR("Target not examined yet");
2626 return ERROR_FAIL;
2629 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2630 address,
2631 value);
2633 target_buffer_set_u64(target, value_buf, value);
2634 retval = target_write_memory(target, address, 8, 1, value_buf);
2635 if (retval != ERROR_OK)
2636 LOG_DEBUG("failed: %i", retval);
2638 return retval;
2641 int target_write_u32(struct target *target, target_addr_t address, uint32_t value)
2643 int retval;
2644 uint8_t value_buf[4];
2645 if (!target_was_examined(target)) {
2646 LOG_ERROR("Target not examined yet");
2647 return ERROR_FAIL;
2650 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2651 address,
2652 value);
2654 target_buffer_set_u32(target, value_buf, value);
2655 retval = target_write_memory(target, address, 4, 1, value_buf);
2656 if (retval != ERROR_OK)
2657 LOG_DEBUG("failed: %i", retval);
2659 return retval;
2662 int target_write_u16(struct target *target, target_addr_t address, uint16_t value)
2664 int retval;
2665 uint8_t value_buf[2];
2666 if (!target_was_examined(target)) {
2667 LOG_ERROR("Target not examined yet");
2668 return ERROR_FAIL;
2671 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2672 address,
2673 value);
2675 target_buffer_set_u16(target, value_buf, value);
2676 retval = target_write_memory(target, address, 2, 1, value_buf);
2677 if (retval != ERROR_OK)
2678 LOG_DEBUG("failed: %i", retval);
2680 return retval;
2683 int target_write_u8(struct target *target, target_addr_t address, uint8_t value)
2685 int retval;
2686 if (!target_was_examined(target)) {
2687 LOG_ERROR("Target not examined yet");
2688 return ERROR_FAIL;
2691 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2692 address, value);
2694 retval = target_write_memory(target, address, 1, 1, &value);
2695 if (retval != ERROR_OK)
2696 LOG_DEBUG("failed: %i", retval);
2698 return retval;
2701 int target_write_phys_u64(struct target *target, target_addr_t address, uint64_t value)
2703 int retval;
2704 uint8_t value_buf[8];
2705 if (!target_was_examined(target)) {
2706 LOG_ERROR("Target not examined yet");
2707 return ERROR_FAIL;
2710 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2711 address,
2712 value);
2714 target_buffer_set_u64(target, value_buf, value);
2715 retval = target_write_phys_memory(target, address, 8, 1, value_buf);
2716 if (retval != ERROR_OK)
2717 LOG_DEBUG("failed: %i", retval);
2719 return retval;
2722 int target_write_phys_u32(struct target *target, target_addr_t address, uint32_t value)
2724 int retval;
2725 uint8_t value_buf[4];
2726 if (!target_was_examined(target)) {
2727 LOG_ERROR("Target not examined yet");
2728 return ERROR_FAIL;
2731 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2732 address,
2733 value);
2735 target_buffer_set_u32(target, value_buf, value);
2736 retval = target_write_phys_memory(target, address, 4, 1, value_buf);
2737 if (retval != ERROR_OK)
2738 LOG_DEBUG("failed: %i", retval);
2740 return retval;
2743 int target_write_phys_u16(struct target *target, target_addr_t address, uint16_t value)
2745 int retval;
2746 uint8_t value_buf[2];
2747 if (!target_was_examined(target)) {
2748 LOG_ERROR("Target not examined yet");
2749 return ERROR_FAIL;
2752 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2753 address,
2754 value);
2756 target_buffer_set_u16(target, value_buf, value);
2757 retval = target_write_phys_memory(target, address, 2, 1, value_buf);
2758 if (retval != ERROR_OK)
2759 LOG_DEBUG("failed: %i", retval);
2761 return retval;
2764 int target_write_phys_u8(struct target *target, target_addr_t address, uint8_t value)
2766 int retval;
2767 if (!target_was_examined(target)) {
2768 LOG_ERROR("Target not examined yet");
2769 return ERROR_FAIL;
2772 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2773 address, value);
2775 retval = target_write_phys_memory(target, address, 1, 1, &value);
2776 if (retval != ERROR_OK)
2777 LOG_DEBUG("failed: %i", retval);
2779 return retval;
2782 static int find_target(struct command_invocation *cmd, const char *name)
2784 struct target *target = get_target(name);
2785 if (!target) {
2786 command_print(cmd, "Target: %s is unknown, try one of:\n", name);
2787 return ERROR_FAIL;
2789 if (!target->tap->enabled) {
2790 command_print(cmd, "Target: TAP %s is disabled, "
2791 "can't be the current target\n",
2792 target->tap->dotted_name);
2793 return ERROR_FAIL;
2796 cmd->ctx->current_target = target;
2797 if (cmd->ctx->current_target_override)
2798 cmd->ctx->current_target_override = target;
2800 return ERROR_OK;
2804 COMMAND_HANDLER(handle_targets_command)
2806 int retval = ERROR_OK;
2807 if (CMD_ARGC == 1) {
2808 retval = find_target(CMD, CMD_ARGV[0]);
2809 if (retval == ERROR_OK) {
2810 /* we're done! */
2811 return retval;
2815 unsigned int index = 0;
2816 command_print(CMD, " TargetName Type Endian TapName State ");
2817 command_print(CMD, "-- ------------------ ---------- ------ ------------------ ------------");
2818 for (struct target *target = all_targets; target; target = target->next, ++index) {
2819 const char *state;
2820 char marker = ' ';
2822 if (target->tap->enabled)
2823 state = target_state_name(target);
2824 else
2825 state = "tap-disabled";
2827 if (CMD_CTX->current_target == target)
2828 marker = '*';
2830 /* keep columns lined up to match the headers above */
2831 command_print(CMD,
2832 "%2d%c %-18s %-10s %-6s %-18s %s",
2833 index,
2834 marker,
2835 target_name(target),
2836 target_type_name(target),
2837 jim_nvp_value2name_simple(nvp_target_endian,
2838 target->endianness)->name,
2839 target->tap->dotted_name,
2840 state);
2843 return retval;
2846 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2848 static int power_dropout;
2849 static int srst_asserted;
2851 static int run_power_restore;
2852 static int run_power_dropout;
2853 static int run_srst_asserted;
2854 static int run_srst_deasserted;
2856 static int sense_handler(void)
2858 static int prev_srst_asserted;
2859 static int prev_power_dropout;
2861 int retval = jtag_power_dropout(&power_dropout);
2862 if (retval != ERROR_OK)
2863 return retval;
2865 int power_restored;
2866 power_restored = prev_power_dropout && !power_dropout;
2867 if (power_restored)
2868 run_power_restore = 1;
2870 int64_t current = timeval_ms();
2871 static int64_t last_power;
2872 bool wait_more = last_power + 2000 > current;
2873 if (power_dropout && !wait_more) {
2874 run_power_dropout = 1;
2875 last_power = current;
2878 retval = jtag_srst_asserted(&srst_asserted);
2879 if (retval != ERROR_OK)
2880 return retval;
2882 int srst_deasserted;
2883 srst_deasserted = prev_srst_asserted && !srst_asserted;
2885 static int64_t last_srst;
2886 wait_more = last_srst + 2000 > current;
2887 if (srst_deasserted && !wait_more) {
2888 run_srst_deasserted = 1;
2889 last_srst = current;
2892 if (!prev_srst_asserted && srst_asserted)
2893 run_srst_asserted = 1;
2895 prev_srst_asserted = srst_asserted;
2896 prev_power_dropout = power_dropout;
2898 if (srst_deasserted || power_restored) {
2899 /* Other than logging the event we can't do anything here.
2900 * Issuing a reset is a particularly bad idea as we might
2901 * be inside a reset already.
2905 return ERROR_OK;
2908 /* process target state changes */
2909 static int handle_target(void *priv)
2911 Jim_Interp *interp = (Jim_Interp *)priv;
2912 int retval = ERROR_OK;
2914 if (!is_jtag_poll_safe()) {
2915 /* polling is disabled currently */
2916 return ERROR_OK;
2919 /* we do not want to recurse here... */
2920 static int recursive;
2921 if (!recursive) {
2922 recursive = 1;
2923 sense_handler();
2924 /* danger! running these procedures can trigger srst assertions and power dropouts.
2925 * We need to avoid an infinite loop/recursion here and we do that by
2926 * clearing the flags after running these events.
2928 int did_something = 0;
2929 if (run_srst_asserted) {
2930 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2931 Jim_Eval(interp, "srst_asserted");
2932 did_something = 1;
2934 if (run_srst_deasserted) {
2935 Jim_Eval(interp, "srst_deasserted");
2936 did_something = 1;
2938 if (run_power_dropout) {
2939 LOG_INFO("Power dropout detected, running power_dropout proc.");
2940 Jim_Eval(interp, "power_dropout");
2941 did_something = 1;
2943 if (run_power_restore) {
2944 Jim_Eval(interp, "power_restore");
2945 did_something = 1;
2948 if (did_something) {
2949 /* clear detect flags */
2950 sense_handler();
2953 /* clear action flags */
2955 run_srst_asserted = 0;
2956 run_srst_deasserted = 0;
2957 run_power_restore = 0;
2958 run_power_dropout = 0;
2960 recursive = 0;
2963 /* Poll targets for state changes unless that's globally disabled.
2964 * Skip targets that are currently disabled.
2966 for (struct target *target = all_targets;
2967 is_jtag_poll_safe() && target;
2968 target = target->next) {
2970 if (!target_was_examined(target))
2971 continue;
2973 if (!target->tap->enabled)
2974 continue;
2976 if (target->backoff.times > target->backoff.count) {
2977 /* do not poll this time as we failed previously */
2978 target->backoff.count++;
2979 continue;
2981 target->backoff.count = 0;
2983 /* only poll target if we've got power and srst isn't asserted */
2984 if (!power_dropout && !srst_asserted) {
2985 /* polling may fail silently until the target has been examined */
2986 retval = target_poll(target);
2987 if (retval != ERROR_OK) {
2988 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2989 if (target->backoff.times * polling_interval < 5000) {
2990 target->backoff.times *= 2;
2991 target->backoff.times++;
2994 /* Tell GDB to halt the debugger. This allows the user to
2995 * run monitor commands to handle the situation.
2997 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2999 if (target->backoff.times > 0) {
3000 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
3001 target_reset_examined(target);
3002 retval = target_examine_one(target);
3003 /* Target examination could have failed due to unstable connection,
3004 * but we set the examined flag anyway to repoll it later */
3005 if (retval != ERROR_OK) {
3006 target_set_examined(target);
3007 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
3008 target->backoff.times * polling_interval);
3009 return retval;
3013 /* Since we succeeded, we reset backoff count */
3014 target->backoff.times = 0;
3018 return retval;
3021 COMMAND_HANDLER(handle_reg_command)
3023 LOG_DEBUG("-");
3025 struct target *target = get_current_target(CMD_CTX);
3026 if (!target_was_examined(target)) {
3027 LOG_ERROR("Target not examined yet");
3028 return ERROR_TARGET_NOT_EXAMINED;
3030 struct reg *reg = NULL;
3032 /* list all available registers for the current target */
3033 if (CMD_ARGC == 0) {
3034 struct reg_cache *cache = target->reg_cache;
3036 unsigned int count = 0;
3037 while (cache) {
3038 unsigned i;
3040 command_print(CMD, "===== %s", cache->name);
3042 for (i = 0, reg = cache->reg_list;
3043 i < cache->num_regs;
3044 i++, reg++, count++) {
3045 if (reg->exist == false || reg->hidden)
3046 continue;
3047 /* only print cached values if they are valid */
3048 if (reg->valid) {
3049 char *value = buf_to_hex_str(reg->value,
3050 reg->size);
3051 command_print(CMD,
3052 "(%i) %s (/%" PRIu32 "): 0x%s%s",
3053 count, reg->name,
3054 reg->size, value,
3055 reg->dirty
3056 ? " (dirty)"
3057 : "");
3058 free(value);
3059 } else {
3060 command_print(CMD, "(%i) %s (/%" PRIu32 ")",
3061 count, reg->name,
3062 reg->size);
3065 cache = cache->next;
3068 return ERROR_OK;
3071 /* access a single register by its ordinal number */
3072 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
3073 unsigned num;
3074 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
3076 struct reg_cache *cache = target->reg_cache;
3077 unsigned int count = 0;
3078 while (cache) {
3079 unsigned i;
3080 for (i = 0; i < cache->num_regs; i++) {
3081 if (count++ == num) {
3082 reg = &cache->reg_list[i];
3083 break;
3086 if (reg)
3087 break;
3088 cache = cache->next;
3091 if (!reg) {
3092 command_print(CMD, "%i is out of bounds, the current target "
3093 "has only %i registers (0 - %i)", num, count, count - 1);
3094 return ERROR_FAIL;
3096 } else {
3097 /* access a single register by its name */
3098 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], true);
3100 if (!reg)
3101 goto not_found;
3104 assert(reg); /* give clang a hint that we *know* reg is != NULL here */
3106 if (!reg->exist)
3107 goto not_found;
3109 /* display a register */
3110 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
3111 && (CMD_ARGV[1][0] <= '9')))) {
3112 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
3113 reg->valid = false;
3115 if (!reg->valid) {
3116 int retval = reg->type->get(reg);
3117 if (retval != ERROR_OK) {
3118 LOG_ERROR("Could not read register '%s'", reg->name);
3119 return retval;
3122 char *value = buf_to_hex_str(reg->value, reg->size);
3123 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3124 free(value);
3125 return ERROR_OK;
3128 /* set register value */
3129 if (CMD_ARGC == 2) {
3130 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
3131 if (!buf)
3132 return ERROR_FAIL;
3133 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
3135 int retval = reg->type->set(reg, buf);
3136 if (retval != ERROR_OK) {
3137 LOG_ERROR("Could not write to register '%s'", reg->name);
3138 } else {
3139 char *value = buf_to_hex_str(reg->value, reg->size);
3140 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3141 free(value);
3144 free(buf);
3146 return retval;
3149 return ERROR_COMMAND_SYNTAX_ERROR;
3151 not_found:
3152 command_print(CMD, "register %s not found in current target", CMD_ARGV[0]);
3153 return ERROR_FAIL;
3156 COMMAND_HANDLER(handle_poll_command)
3158 int retval = ERROR_OK;
3159 struct target *target = get_current_target(CMD_CTX);
3161 if (CMD_ARGC == 0) {
3162 command_print(CMD, "background polling: %s",
3163 jtag_poll_get_enabled() ? "on" : "off");
3164 command_print(CMD, "TAP: %s (%s)",
3165 target->tap->dotted_name,
3166 target->tap->enabled ? "enabled" : "disabled");
3167 if (!target->tap->enabled)
3168 return ERROR_OK;
3169 retval = target_poll(target);
3170 if (retval != ERROR_OK)
3171 return retval;
3172 retval = target_arch_state(target);
3173 if (retval != ERROR_OK)
3174 return retval;
3175 } else if (CMD_ARGC == 1) {
3176 bool enable;
3177 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
3178 jtag_poll_set_enabled(enable);
3179 } else
3180 return ERROR_COMMAND_SYNTAX_ERROR;
3182 return retval;
3185 COMMAND_HANDLER(handle_wait_halt_command)
3187 if (CMD_ARGC > 1)
3188 return ERROR_COMMAND_SYNTAX_ERROR;
3190 unsigned ms = DEFAULT_HALT_TIMEOUT;
3191 if (1 == CMD_ARGC) {
3192 int retval = parse_uint(CMD_ARGV[0], &ms);
3193 if (retval != ERROR_OK)
3194 return ERROR_COMMAND_SYNTAX_ERROR;
3197 struct target *target = get_current_target(CMD_CTX);
3198 return target_wait_state(target, TARGET_HALTED, ms);
3201 /* wait for target state to change. The trick here is to have a low
3202 * latency for short waits and not to suck up all the CPU time
3203 * on longer waits.
3205 * After 500ms, keep_alive() is invoked
3207 int target_wait_state(struct target *target, enum target_state state, unsigned int ms)
3209 int retval;
3210 int64_t then = 0, cur;
3211 bool once = true;
3213 for (;;) {
3214 retval = target_poll(target);
3215 if (retval != ERROR_OK)
3216 return retval;
3217 if (target->state == state)
3218 break;
3219 cur = timeval_ms();
3220 if (once) {
3221 once = false;
3222 then = timeval_ms();
3223 LOG_DEBUG("waiting for target %s...",
3224 nvp_value2name(nvp_target_state, state)->name);
3227 if (cur - then > 500) {
3228 keep_alive();
3229 if (openocd_is_shutdown_pending())
3230 return ERROR_SERVER_INTERRUPTED;
3233 if ((cur-then) > ms) {
3234 LOG_ERROR("timed out while waiting for target %s",
3235 nvp_value2name(nvp_target_state, state)->name);
3236 return ERROR_FAIL;
3240 return ERROR_OK;
3243 COMMAND_HANDLER(handle_halt_command)
3245 LOG_DEBUG("-");
3247 struct target *target = get_current_target(CMD_CTX);
3249 target->verbose_halt_msg = true;
3251 int retval = target_halt(target);
3252 if (retval != ERROR_OK)
3253 return retval;
3255 if (CMD_ARGC == 1) {
3256 unsigned wait_local;
3257 retval = parse_uint(CMD_ARGV[0], &wait_local);
3258 if (retval != ERROR_OK)
3259 return ERROR_COMMAND_SYNTAX_ERROR;
3260 if (!wait_local)
3261 return ERROR_OK;
3264 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
3267 COMMAND_HANDLER(handle_soft_reset_halt_command)
3269 struct target *target = get_current_target(CMD_CTX);
3271 LOG_TARGET_INFO(target, "requesting target halt and executing a soft reset");
3273 target_soft_reset_halt(target);
3275 return ERROR_OK;
3278 COMMAND_HANDLER(handle_reset_command)
3280 if (CMD_ARGC > 1)
3281 return ERROR_COMMAND_SYNTAX_ERROR;
3283 enum target_reset_mode reset_mode = RESET_RUN;
3284 if (CMD_ARGC == 1) {
3285 const struct nvp *n;
3286 n = nvp_name2value(nvp_reset_modes, CMD_ARGV[0]);
3287 if ((!n->name) || (n->value == RESET_UNKNOWN))
3288 return ERROR_COMMAND_SYNTAX_ERROR;
3289 reset_mode = n->value;
3292 /* reset *all* targets */
3293 return target_process_reset(CMD, reset_mode);
3297 COMMAND_HANDLER(handle_resume_command)
3299 int current = 1;
3300 if (CMD_ARGC > 1)
3301 return ERROR_COMMAND_SYNTAX_ERROR;
3303 struct target *target = get_current_target(CMD_CTX);
3305 /* with no CMD_ARGV, resume from current pc, addr = 0,
3306 * with one arguments, addr = CMD_ARGV[0],
3307 * handle breakpoints, not debugging */
3308 target_addr_t addr = 0;
3309 if (CMD_ARGC == 1) {
3310 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3311 current = 0;
3314 return target_resume(target, current, addr, 1, 0);
3317 COMMAND_HANDLER(handle_step_command)
3319 if (CMD_ARGC > 1)
3320 return ERROR_COMMAND_SYNTAX_ERROR;
3322 LOG_DEBUG("-");
3324 /* with no CMD_ARGV, step from current pc, addr = 0,
3325 * with one argument addr = CMD_ARGV[0],
3326 * handle breakpoints, debugging */
3327 target_addr_t addr = 0;
3328 int current_pc = 1;
3329 if (CMD_ARGC == 1) {
3330 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3331 current_pc = 0;
3334 struct target *target = get_current_target(CMD_CTX);
3336 return target_step(target, current_pc, addr, 1);
3339 void target_handle_md_output(struct command_invocation *cmd,
3340 struct target *target, target_addr_t address, unsigned size,
3341 unsigned count, const uint8_t *buffer)
3343 const unsigned line_bytecnt = 32;
3344 unsigned line_modulo = line_bytecnt / size;
3346 char output[line_bytecnt * 4 + 1];
3347 unsigned output_len = 0;
3349 const char *value_fmt;
3350 switch (size) {
3351 case 8:
3352 value_fmt = "%16.16"PRIx64" ";
3353 break;
3354 case 4:
3355 value_fmt = "%8.8"PRIx64" ";
3356 break;
3357 case 2:
3358 value_fmt = "%4.4"PRIx64" ";
3359 break;
3360 case 1:
3361 value_fmt = "%2.2"PRIx64" ";
3362 break;
3363 default:
3364 /* "can't happen", caller checked */
3365 LOG_ERROR("invalid memory read size: %u", size);
3366 return;
3369 for (unsigned i = 0; i < count; i++) {
3370 if (i % line_modulo == 0) {
3371 output_len += snprintf(output + output_len,
3372 sizeof(output) - output_len,
3373 TARGET_ADDR_FMT ": ",
3374 (address + (i * size)));
3377 uint64_t value = 0;
3378 const uint8_t *value_ptr = buffer + i * size;
3379 switch (size) {
3380 case 8:
3381 value = target_buffer_get_u64(target, value_ptr);
3382 break;
3383 case 4:
3384 value = target_buffer_get_u32(target, value_ptr);
3385 break;
3386 case 2:
3387 value = target_buffer_get_u16(target, value_ptr);
3388 break;
3389 case 1:
3390 value = *value_ptr;
3392 output_len += snprintf(output + output_len,
3393 sizeof(output) - output_len,
3394 value_fmt, value);
3396 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
3397 command_print(cmd, "%s", output);
3398 output_len = 0;
3403 COMMAND_HANDLER(handle_md_command)
3405 if (CMD_ARGC < 1)
3406 return ERROR_COMMAND_SYNTAX_ERROR;
3408 unsigned size = 0;
3409 switch (CMD_NAME[2]) {
3410 case 'd':
3411 size = 8;
3412 break;
3413 case 'w':
3414 size = 4;
3415 break;
3416 case 'h':
3417 size = 2;
3418 break;
3419 case 'b':
3420 size = 1;
3421 break;
3422 default:
3423 return ERROR_COMMAND_SYNTAX_ERROR;
3426 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3427 int (*fn)(struct target *target,
3428 target_addr_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
3429 if (physical) {
3430 CMD_ARGC--;
3431 CMD_ARGV++;
3432 fn = target_read_phys_memory;
3433 } else
3434 fn = target_read_memory;
3435 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
3436 return ERROR_COMMAND_SYNTAX_ERROR;
3438 target_addr_t address;
3439 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3441 unsigned count = 1;
3442 if (CMD_ARGC == 2)
3443 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3445 uint8_t *buffer = calloc(count, size);
3446 if (!buffer) {
3447 LOG_ERROR("Failed to allocate md read buffer");
3448 return ERROR_FAIL;
3451 struct target *target = get_current_target(CMD_CTX);
3452 int retval = fn(target, address, size, count, buffer);
3453 if (retval == ERROR_OK)
3454 target_handle_md_output(CMD, target, address, size, count, buffer);
3456 free(buffer);
3458 return retval;
3461 typedef int (*target_write_fn)(struct target *target,
3462 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3464 static int target_fill_mem(struct target *target,
3465 target_addr_t address,
3466 target_write_fn fn,
3467 unsigned data_size,
3468 /* value */
3469 uint64_t b,
3470 /* count */
3471 unsigned c)
3473 /* We have to write in reasonably large chunks to be able
3474 * to fill large memory areas with any sane speed */
3475 const unsigned chunk_size = 16384;
3476 uint8_t *target_buf = malloc(chunk_size * data_size);
3477 if (!target_buf) {
3478 LOG_ERROR("Out of memory");
3479 return ERROR_FAIL;
3482 for (unsigned i = 0; i < chunk_size; i++) {
3483 switch (data_size) {
3484 case 8:
3485 target_buffer_set_u64(target, target_buf + i * data_size, b);
3486 break;
3487 case 4:
3488 target_buffer_set_u32(target, target_buf + i * data_size, b);
3489 break;
3490 case 2:
3491 target_buffer_set_u16(target, target_buf + i * data_size, b);
3492 break;
3493 case 1:
3494 target_buffer_set_u8(target, target_buf + i * data_size, b);
3495 break;
3496 default:
3497 exit(-1);
3501 int retval = ERROR_OK;
3503 for (unsigned x = 0; x < c; x += chunk_size) {
3504 unsigned current;
3505 current = c - x;
3506 if (current > chunk_size)
3507 current = chunk_size;
3508 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3509 if (retval != ERROR_OK)
3510 break;
3511 /* avoid GDB timeouts */
3512 keep_alive();
3514 if (openocd_is_shutdown_pending()) {
3515 retval = ERROR_SERVER_INTERRUPTED;
3516 break;
3519 free(target_buf);
3521 return retval;
3525 COMMAND_HANDLER(handle_mw_command)
3527 if (CMD_ARGC < 2)
3528 return ERROR_COMMAND_SYNTAX_ERROR;
3529 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3530 target_write_fn fn;
3531 if (physical) {
3532 CMD_ARGC--;
3533 CMD_ARGV++;
3534 fn = target_write_phys_memory;
3535 } else
3536 fn = target_write_memory;
3537 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3538 return ERROR_COMMAND_SYNTAX_ERROR;
3540 target_addr_t address;
3541 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3543 uint64_t value;
3544 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[1], value);
3546 unsigned count = 1;
3547 if (CMD_ARGC == 3)
3548 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3550 struct target *target = get_current_target(CMD_CTX);
3551 unsigned wordsize;
3552 switch (CMD_NAME[2]) {
3553 case 'd':
3554 wordsize = 8;
3555 break;
3556 case 'w':
3557 wordsize = 4;
3558 break;
3559 case 'h':
3560 wordsize = 2;
3561 break;
3562 case 'b':
3563 wordsize = 1;
3564 break;
3565 default:
3566 return ERROR_COMMAND_SYNTAX_ERROR;
3569 return target_fill_mem(target, address, fn, wordsize, value, count);
3572 static COMMAND_HELPER(parse_load_image_command, struct image *image,
3573 target_addr_t *min_address, target_addr_t *max_address)
3575 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3576 return ERROR_COMMAND_SYNTAX_ERROR;
3578 /* a base address isn't always necessary,
3579 * default to 0x0 (i.e. don't relocate) */
3580 if (CMD_ARGC >= 2) {
3581 target_addr_t addr;
3582 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3583 image->base_address = addr;
3584 image->base_address_set = true;
3585 } else
3586 image->base_address_set = false;
3588 image->start_address_set = false;
3590 if (CMD_ARGC >= 4)
3591 COMMAND_PARSE_ADDRESS(CMD_ARGV[3], *min_address);
3592 if (CMD_ARGC == 5) {
3593 COMMAND_PARSE_ADDRESS(CMD_ARGV[4], *max_address);
3594 /* use size (given) to find max (required) */
3595 *max_address += *min_address;
3598 if (*min_address > *max_address)
3599 return ERROR_COMMAND_SYNTAX_ERROR;
3601 return ERROR_OK;
3604 COMMAND_HANDLER(handle_load_image_command)
3606 uint8_t *buffer;
3607 size_t buf_cnt;
3608 uint32_t image_size;
3609 target_addr_t min_address = 0;
3610 target_addr_t max_address = -1;
3611 struct image image;
3613 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
3614 &image, &min_address, &max_address);
3615 if (retval != ERROR_OK)
3616 return retval;
3618 struct target *target = get_current_target(CMD_CTX);
3620 struct duration bench;
3621 duration_start(&bench);
3623 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3624 return ERROR_FAIL;
3626 image_size = 0x0;
3627 retval = ERROR_OK;
3628 for (unsigned int i = 0; i < image.num_sections; i++) {
3629 buffer = malloc(image.sections[i].size);
3630 if (!buffer) {
3631 command_print(CMD,
3632 "error allocating buffer for section (%d bytes)",
3633 (int)(image.sections[i].size));
3634 retval = ERROR_FAIL;
3635 break;
3638 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3639 if (retval != ERROR_OK) {
3640 free(buffer);
3641 break;
3644 uint32_t offset = 0;
3645 uint32_t length = buf_cnt;
3647 /* DANGER!!! beware of unsigned comparison here!!! */
3649 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3650 (image.sections[i].base_address < max_address)) {
3652 if (image.sections[i].base_address < min_address) {
3653 /* clip addresses below */
3654 offset += min_address-image.sections[i].base_address;
3655 length -= offset;
3658 if (image.sections[i].base_address + buf_cnt > max_address)
3659 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3661 retval = target_write_buffer(target,
3662 image.sections[i].base_address + offset, length, buffer + offset);
3663 if (retval != ERROR_OK) {
3664 free(buffer);
3665 break;
3667 image_size += length;
3668 command_print(CMD, "%u bytes written at address " TARGET_ADDR_FMT "",
3669 (unsigned int)length,
3670 image.sections[i].base_address + offset);
3673 free(buffer);
3676 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3677 command_print(CMD, "downloaded %" PRIu32 " bytes "
3678 "in %fs (%0.3f KiB/s)", image_size,
3679 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3682 image_close(&image);
3684 return retval;
3688 COMMAND_HANDLER(handle_dump_image_command)
3690 struct fileio *fileio;
3691 uint8_t *buffer;
3692 int retval, retvaltemp;
3693 target_addr_t address, size;
3694 struct duration bench;
3695 struct target *target = get_current_target(CMD_CTX);
3697 if (CMD_ARGC != 3)
3698 return ERROR_COMMAND_SYNTAX_ERROR;
3700 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], address);
3701 COMMAND_PARSE_ADDRESS(CMD_ARGV[2], size);
3703 uint32_t buf_size = (size > 4096) ? 4096 : size;
3704 buffer = malloc(buf_size);
3705 if (!buffer)
3706 return ERROR_FAIL;
3708 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3709 if (retval != ERROR_OK) {
3710 free(buffer);
3711 return retval;
3714 duration_start(&bench);
3716 while (size > 0) {
3717 size_t size_written;
3718 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3719 retval = target_read_buffer(target, address, this_run_size, buffer);
3720 if (retval != ERROR_OK)
3721 break;
3723 retval = fileio_write(fileio, this_run_size, buffer, &size_written);
3724 if (retval != ERROR_OK)
3725 break;
3727 size -= this_run_size;
3728 address += this_run_size;
3731 free(buffer);
3733 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3734 size_t filesize;
3735 retval = fileio_size(fileio, &filesize);
3736 if (retval != ERROR_OK)
3737 return retval;
3738 command_print(CMD,
3739 "dumped %zu bytes in %fs (%0.3f KiB/s)", filesize,
3740 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3743 retvaltemp = fileio_close(fileio);
3744 if (retvaltemp != ERROR_OK)
3745 return retvaltemp;
3747 return retval;
3750 enum verify_mode {
3751 IMAGE_TEST = 0,
3752 IMAGE_VERIFY = 1,
3753 IMAGE_CHECKSUM_ONLY = 2
3756 static COMMAND_HELPER(handle_verify_image_command_internal, enum verify_mode verify)
3758 uint8_t *buffer;
3759 size_t buf_cnt;
3760 uint32_t image_size;
3761 int retval;
3762 uint32_t checksum = 0;
3763 uint32_t mem_checksum = 0;
3765 struct image image;
3767 struct target *target = get_current_target(CMD_CTX);
3769 if (CMD_ARGC < 1)
3770 return ERROR_COMMAND_SYNTAX_ERROR;
3772 if (!target) {
3773 LOG_ERROR("no target selected");
3774 return ERROR_FAIL;
3777 struct duration bench;
3778 duration_start(&bench);
3780 if (CMD_ARGC >= 2) {
3781 target_addr_t addr;
3782 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3783 image.base_address = addr;
3784 image.base_address_set = true;
3785 } else {
3786 image.base_address_set = false;
3787 image.base_address = 0x0;
3790 image.start_address_set = false;
3792 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3793 if (retval != ERROR_OK)
3794 return retval;
3796 image_size = 0x0;
3797 int diffs = 0;
3798 retval = ERROR_OK;
3799 for (unsigned int i = 0; i < image.num_sections; i++) {
3800 buffer = malloc(image.sections[i].size);
3801 if (!buffer) {
3802 command_print(CMD,
3803 "error allocating buffer for section (%" PRIu32 " bytes)",
3804 image.sections[i].size);
3805 break;
3807 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3808 if (retval != ERROR_OK) {
3809 free(buffer);
3810 break;
3813 if (verify >= IMAGE_VERIFY) {
3814 /* calculate checksum of image */
3815 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3816 if (retval != ERROR_OK) {
3817 free(buffer);
3818 break;
3821 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3822 if (retval != ERROR_OK) {
3823 free(buffer);
3824 break;
3826 if ((checksum != mem_checksum) && (verify == IMAGE_CHECKSUM_ONLY)) {
3827 LOG_ERROR("checksum mismatch");
3828 free(buffer);
3829 retval = ERROR_FAIL;
3830 goto done;
3832 if (checksum != mem_checksum) {
3833 /* failed crc checksum, fall back to a binary compare */
3834 uint8_t *data;
3836 if (diffs == 0)
3837 LOG_ERROR("checksum mismatch - attempting binary compare");
3839 data = malloc(buf_cnt);
3841 retval = target_read_buffer(target, image.sections[i].base_address, buf_cnt, data);
3842 if (retval == ERROR_OK) {
3843 uint32_t t;
3844 for (t = 0; t < buf_cnt; t++) {
3845 if (data[t] != buffer[t]) {
3846 command_print(CMD,
3847 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3848 diffs,
3849 (unsigned)(t + image.sections[i].base_address),
3850 data[t],
3851 buffer[t]);
3852 if (diffs++ >= 127) {
3853 command_print(CMD, "More than 128 errors, the rest are not printed.");
3854 free(data);
3855 free(buffer);
3856 goto done;
3859 keep_alive();
3860 if (openocd_is_shutdown_pending()) {
3861 retval = ERROR_SERVER_INTERRUPTED;
3862 free(data);
3863 free(buffer);
3864 goto done;
3868 free(data);
3870 } else {
3871 command_print(CMD, "address " TARGET_ADDR_FMT " length 0x%08zx",
3872 image.sections[i].base_address,
3873 buf_cnt);
3876 free(buffer);
3877 image_size += buf_cnt;
3879 if (diffs > 0)
3880 command_print(CMD, "No more differences found.");
3881 done:
3882 if (diffs > 0)
3883 retval = ERROR_FAIL;
3884 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3885 command_print(CMD, "verified %" PRIu32 " bytes "
3886 "in %fs (%0.3f KiB/s)", image_size,
3887 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3890 image_close(&image);
3892 return retval;
3895 COMMAND_HANDLER(handle_verify_image_checksum_command)
3897 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_CHECKSUM_ONLY);
3900 COMMAND_HANDLER(handle_verify_image_command)
3902 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_VERIFY);
3905 COMMAND_HANDLER(handle_test_image_command)
3907 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_TEST);
3910 static int handle_bp_command_list(struct command_invocation *cmd)
3912 struct target *target = get_current_target(cmd->ctx);
3913 struct breakpoint *breakpoint = target->breakpoints;
3914 while (breakpoint) {
3915 if (breakpoint->type == BKPT_SOFT) {
3916 char *buf = buf_to_hex_str(breakpoint->orig_instr,
3917 breakpoint->length);
3918 command_print(cmd, "Software breakpoint(IVA): addr=" TARGET_ADDR_FMT ", len=0x%x, orig_instr=0x%s",
3919 breakpoint->address,
3920 breakpoint->length,
3921 buf);
3922 free(buf);
3923 } else {
3924 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3925 command_print(cmd, "Context breakpoint: asid=0x%8.8" PRIx32 ", len=0x%x, num=%u",
3926 breakpoint->asid,
3927 breakpoint->length, breakpoint->number);
3928 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3929 command_print(cmd, "Hybrid breakpoint(IVA): addr=" TARGET_ADDR_FMT ", len=0x%x, num=%u",
3930 breakpoint->address,
3931 breakpoint->length, breakpoint->number);
3932 command_print(cmd, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3933 breakpoint->asid);
3934 } else
3935 command_print(cmd, "Hardware breakpoint(IVA): addr=" TARGET_ADDR_FMT ", len=0x%x, num=%u",
3936 breakpoint->address,
3937 breakpoint->length, breakpoint->number);
3940 breakpoint = breakpoint->next;
3942 return ERROR_OK;
3945 static int handle_bp_command_set(struct command_invocation *cmd,
3946 target_addr_t addr, uint32_t asid, uint32_t length, int hw)
3948 struct target *target = get_current_target(cmd->ctx);
3949 int retval;
3951 if (asid == 0) {
3952 retval = breakpoint_add(target, addr, length, hw);
3953 /* error is always logged in breakpoint_add(), do not print it again */
3954 if (retval == ERROR_OK)
3955 command_print(cmd, "breakpoint set at " TARGET_ADDR_FMT "", addr);
3957 } else if (addr == 0) {
3958 if (!target->type->add_context_breakpoint) {
3959 LOG_TARGET_ERROR(target, "Context breakpoint not available");
3960 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
3962 retval = context_breakpoint_add(target, asid, length, hw);
3963 /* error is always logged in context_breakpoint_add(), do not print it again */
3964 if (retval == ERROR_OK)
3965 command_print(cmd, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3967 } else {
3968 if (!target->type->add_hybrid_breakpoint) {
3969 LOG_TARGET_ERROR(target, "Hybrid breakpoint not available");
3970 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
3972 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3973 /* error is always logged in hybrid_breakpoint_add(), do not print it again */
3974 if (retval == ERROR_OK)
3975 command_print(cmd, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3977 return retval;
3980 COMMAND_HANDLER(handle_bp_command)
3982 target_addr_t addr;
3983 uint32_t asid;
3984 uint32_t length;
3985 int hw = BKPT_SOFT;
3987 switch (CMD_ARGC) {
3988 case 0:
3989 return handle_bp_command_list(CMD);
3991 case 2:
3992 asid = 0;
3993 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3994 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3995 return handle_bp_command_set(CMD, addr, asid, length, hw);
3997 case 3:
3998 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3999 hw = BKPT_HARD;
4000 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4001 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4002 asid = 0;
4003 return handle_bp_command_set(CMD, addr, asid, length, hw);
4004 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
4005 hw = BKPT_HARD;
4006 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
4007 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4008 addr = 0;
4009 return handle_bp_command_set(CMD, addr, asid, length, hw);
4011 /* fallthrough */
4012 case 4:
4013 hw = BKPT_HARD;
4014 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4015 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
4016 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
4017 return handle_bp_command_set(CMD, addr, asid, length, hw);
4019 default:
4020 return ERROR_COMMAND_SYNTAX_ERROR;
4024 COMMAND_HANDLER(handle_rbp_command)
4026 int retval;
4028 if (CMD_ARGC != 1)
4029 return ERROR_COMMAND_SYNTAX_ERROR;
4031 struct target *target = get_current_target(CMD_CTX);
4033 if (!strcmp(CMD_ARGV[0], "all")) {
4034 retval = breakpoint_remove_all(target);
4036 if (retval != ERROR_OK) {
4037 command_print(CMD, "Error encountered during removal of all breakpoints.");
4038 command_print(CMD, "Some breakpoints may have remained set.");
4040 } else {
4041 target_addr_t addr;
4042 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4044 retval = breakpoint_remove(target, addr);
4046 if (retval != ERROR_OK)
4047 command_print(CMD, "Error during removal of breakpoint at address " TARGET_ADDR_FMT, addr);
4050 return retval;
4053 COMMAND_HANDLER(handle_wp_command)
4055 struct target *target = get_current_target(CMD_CTX);
4057 if (CMD_ARGC == 0) {
4058 struct watchpoint *watchpoint = target->watchpoints;
4060 while (watchpoint) {
4061 char wp_type = (watchpoint->rw == WPT_READ ? 'r' : (watchpoint->rw == WPT_WRITE ? 'w' : 'a'));
4062 command_print(CMD, "address: " TARGET_ADDR_FMT
4063 ", len: 0x%8.8" PRIx32
4064 ", r/w/a: %c, value: 0x%8.8" PRIx64
4065 ", mask: 0x%8.8" PRIx64,
4066 watchpoint->address,
4067 watchpoint->length,
4068 wp_type,
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 uint64_t data_value = 0x0;
4080 uint64_t data_mask = WATCHPOINT_IGNORE_DATA_VALUE_MASK;
4081 bool mask_specified = false;
4083 switch (CMD_ARGC) {
4084 case 5:
4085 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[4], data_mask);
4086 mask_specified = true;
4087 /* fall through */
4088 case 4:
4089 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[3], data_value);
4090 // if user specified only data value without mask - the mask should be 0
4091 if (!mask_specified)
4092 data_mask = 0;
4093 /* fall through */
4094 case 3:
4095 switch (CMD_ARGV[2][0]) {
4096 case 'r':
4097 type = WPT_READ;
4098 break;
4099 case 'w':
4100 type = WPT_WRITE;
4101 break;
4102 case 'a':
4103 type = WPT_ACCESS;
4104 break;
4105 default:
4106 LOG_TARGET_ERROR(target, "invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
4107 return ERROR_COMMAND_SYNTAX_ERROR;
4109 /* fall through */
4110 case 2:
4111 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4112 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4113 break;
4115 default:
4116 return ERROR_COMMAND_SYNTAX_ERROR;
4119 int retval = watchpoint_add(target, addr, length, type,
4120 data_value, data_mask);
4121 if (retval != ERROR_OK)
4122 LOG_TARGET_ERROR(target, "Failure setting watchpoints");
4124 return retval;
4127 COMMAND_HANDLER(handle_rwp_command)
4129 int retval;
4131 if (CMD_ARGC != 1)
4132 return ERROR_COMMAND_SYNTAX_ERROR;
4134 struct target *target = get_current_target(CMD_CTX);
4135 if (!strcmp(CMD_ARGV[0], "all")) {
4136 retval = watchpoint_remove_all(target);
4138 if (retval != ERROR_OK) {
4139 command_print(CMD, "Error encountered during removal of all watchpoints.");
4140 command_print(CMD, "Some watchpoints may have remained set.");
4142 } else {
4143 target_addr_t addr;
4144 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4146 retval = watchpoint_remove(target, addr);
4148 if (retval != ERROR_OK)
4149 command_print(CMD, "Error during removal of watchpoint at address " TARGET_ADDR_FMT, addr);
4152 return retval;
4156 * Translate a virtual address to a physical address.
4158 * The low-level target implementation must have logged a detailed error
4159 * which is forwarded to telnet/GDB session.
4161 COMMAND_HANDLER(handle_virt2phys_command)
4163 if (CMD_ARGC != 1)
4164 return ERROR_COMMAND_SYNTAX_ERROR;
4166 target_addr_t va;
4167 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], va);
4168 target_addr_t pa;
4170 struct target *target = get_current_target(CMD_CTX);
4171 int retval = target->type->virt2phys(target, va, &pa);
4172 if (retval == ERROR_OK)
4173 command_print(CMD, "Physical address " TARGET_ADDR_FMT "", pa);
4175 return retval;
4178 static void write_data(FILE *f, const void *data, size_t len)
4180 size_t written = fwrite(data, 1, len, f);
4181 if (written != len)
4182 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
4185 static void write_long(FILE *f, int l, struct target *target)
4187 uint8_t val[4];
4189 target_buffer_set_u32(target, val, l);
4190 write_data(f, val, 4);
4193 static void write_string(FILE *f, char *s)
4195 write_data(f, s, strlen(s));
4198 typedef unsigned char UNIT[2]; /* unit of profiling */
4200 /* Dump a gmon.out histogram file. */
4201 static void write_gmon(uint32_t *samples, uint32_t sample_num, const char *filename, bool with_range,
4202 uint32_t start_address, uint32_t end_address, struct target *target, uint32_t duration_ms)
4204 uint32_t i;
4205 FILE *f = fopen(filename, "w");
4206 if (!f)
4207 return;
4208 write_string(f, "gmon");
4209 write_long(f, 0x00000001, target); /* Version */
4210 write_long(f, 0, target); /* padding */
4211 write_long(f, 0, target); /* padding */
4212 write_long(f, 0, target); /* padding */
4214 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
4215 write_data(f, &zero, 1);
4217 /* figure out bucket size */
4218 uint32_t min;
4219 uint32_t max;
4220 if (with_range) {
4221 min = start_address;
4222 max = end_address;
4223 } else {
4224 min = samples[0];
4225 max = samples[0];
4226 for (i = 0; i < sample_num; i++) {
4227 if (min > samples[i])
4228 min = samples[i];
4229 if (max < samples[i])
4230 max = samples[i];
4233 /* max should be (largest sample + 1)
4234 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
4235 if (max < UINT32_MAX)
4236 max++;
4238 /* gprof requires (max - min) >= 2 */
4239 while ((max - min) < 2) {
4240 if (max < UINT32_MAX)
4241 max++;
4242 else
4243 min--;
4247 uint32_t address_space = max - min;
4249 /* FIXME: What is the reasonable number of buckets?
4250 * The profiling result will be more accurate if there are enough buckets. */
4251 static const uint32_t max_buckets = 128 * 1024; /* maximum buckets. */
4252 uint32_t num_buckets = address_space / sizeof(UNIT);
4253 if (num_buckets > max_buckets)
4254 num_buckets = max_buckets;
4255 int *buckets = malloc(sizeof(int) * num_buckets);
4256 if (!buckets) {
4257 fclose(f);
4258 return;
4260 memset(buckets, 0, sizeof(int) * num_buckets);
4261 for (i = 0; i < sample_num; i++) {
4262 uint32_t address = samples[i];
4264 if ((address < min) || (max <= address))
4265 continue;
4267 long long a = address - min;
4268 long long b = num_buckets;
4269 long long c = address_space;
4270 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
4271 buckets[index_t]++;
4274 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
4275 write_long(f, min, target); /* low_pc */
4276 write_long(f, max, target); /* high_pc */
4277 write_long(f, num_buckets, target); /* # of buckets */
4278 float sample_rate = sample_num / (duration_ms / 1000.0);
4279 write_long(f, sample_rate, target);
4280 write_string(f, "seconds");
4281 for (i = 0; i < (15-strlen("seconds")); i++)
4282 write_data(f, &zero, 1);
4283 write_string(f, "s");
4285 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
4287 char *data = malloc(2 * num_buckets);
4288 if (data) {
4289 for (i = 0; i < num_buckets; i++) {
4290 int val;
4291 val = buckets[i];
4292 if (val > 65535)
4293 val = 65535;
4294 data[i * 2] = val&0xff;
4295 data[i * 2 + 1] = (val >> 8) & 0xff;
4297 free(buckets);
4298 write_data(f, data, num_buckets * 2);
4299 free(data);
4300 } else
4301 free(buckets);
4303 fclose(f);
4306 /* profiling samples the CPU PC as quickly as OpenOCD is able,
4307 * which will be used as a random sampling of PC */
4308 COMMAND_HANDLER(handle_profile_command)
4310 struct target *target = get_current_target(CMD_CTX);
4312 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
4313 return ERROR_COMMAND_SYNTAX_ERROR;
4315 const uint32_t MAX_PROFILE_SAMPLE_NUM = 1000000;
4316 uint32_t offset;
4317 uint32_t num_of_samples;
4318 int retval = ERROR_OK;
4319 bool halted_before_profiling = target->state == TARGET_HALTED;
4321 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
4323 uint32_t start_address = 0;
4324 uint32_t end_address = 0;
4325 bool with_range = false;
4326 if (CMD_ARGC == 4) {
4327 with_range = true;
4328 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
4329 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
4330 if (start_address > end_address || (end_address - start_address) < 2) {
4331 command_print(CMD, "Error: end - start < 2");
4332 return ERROR_COMMAND_ARGUMENT_INVALID;
4336 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
4337 if (!samples) {
4338 LOG_ERROR("No memory to store samples.");
4339 return ERROR_FAIL;
4342 uint64_t timestart_ms = timeval_ms();
4344 * Some cores let us sample the PC without the
4345 * annoying halt/resume step; for example, ARMv7 PCSR.
4346 * Provide a way to use that more efficient mechanism.
4348 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
4349 &num_of_samples, offset);
4350 if (retval != ERROR_OK) {
4351 free(samples);
4352 return retval;
4354 uint32_t duration_ms = timeval_ms() - timestart_ms;
4356 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
4358 retval = target_poll(target);
4359 if (retval != ERROR_OK) {
4360 free(samples);
4361 return retval;
4364 if (target->state == TARGET_RUNNING && halted_before_profiling) {
4365 /* The target was halted before we started and is running now. Halt it,
4366 * for consistency. */
4367 retval = target_halt(target);
4368 if (retval != ERROR_OK) {
4369 free(samples);
4370 return retval;
4372 } else if (target->state == TARGET_HALTED && !halted_before_profiling) {
4373 /* The target was running before we started and is halted now. Resume
4374 * it, for consistency. */
4375 retval = target_resume(target, 1, 0, 0, 0);
4376 if (retval != ERROR_OK) {
4377 free(samples);
4378 return retval;
4382 retval = target_poll(target);
4383 if (retval != ERROR_OK) {
4384 free(samples);
4385 return retval;
4388 write_gmon(samples, num_of_samples, CMD_ARGV[1],
4389 with_range, start_address, end_address, target, duration_ms);
4390 command_print(CMD, "Wrote %s", CMD_ARGV[1]);
4392 free(samples);
4393 return retval;
4396 COMMAND_HANDLER(handle_target_read_memory)
4399 * CMD_ARGV[0] = memory address
4400 * CMD_ARGV[1] = desired element width in bits
4401 * CMD_ARGV[2] = number of elements to read
4402 * CMD_ARGV[3] = optional "phys"
4405 if (CMD_ARGC < 3 || CMD_ARGC > 4)
4406 return ERROR_COMMAND_SYNTAX_ERROR;
4408 /* Arg 1: Memory address. */
4409 target_addr_t addr;
4410 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[0], addr);
4412 /* Arg 2: Bit width of one element. */
4413 unsigned int width_bits;
4414 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], width_bits);
4416 /* Arg 3: Number of elements to read. */
4417 unsigned int count;
4418 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
4420 /* Arg 4: Optional 'phys'. */
4421 bool is_phys = false;
4422 if (CMD_ARGC == 4) {
4423 if (strcmp(CMD_ARGV[3], "phys")) {
4424 command_print(CMD, "invalid argument '%s', must be 'phys'", CMD_ARGV[3]);
4425 return ERROR_COMMAND_ARGUMENT_INVALID;
4428 is_phys = true;
4431 switch (width_bits) {
4432 case 8:
4433 case 16:
4434 case 32:
4435 case 64:
4436 break;
4437 default:
4438 command_print(CMD, "invalid width, must be 8, 16, 32 or 64");
4439 return ERROR_COMMAND_ARGUMENT_INVALID;
4442 const unsigned int width = width_bits / 8;
4444 if ((addr + (count * width)) < addr) {
4445 command_print(CMD, "read_memory: addr + count wraps to zero");
4446 return ERROR_COMMAND_ARGUMENT_INVALID;
4449 if (count > 65536) {
4450 command_print(CMD, "read_memory: too large read request, exceeds 64K elements");
4451 return ERROR_COMMAND_ARGUMENT_INVALID;
4454 struct target *target = get_current_target(CMD_CTX);
4456 const size_t buffersize = 4096;
4457 uint8_t *buffer = malloc(buffersize);
4459 if (!buffer) {
4460 LOG_ERROR("Failed to allocate memory");
4461 return ERROR_FAIL;
4464 char *separator = "";
4465 while (count > 0) {
4466 const unsigned int max_chunk_len = buffersize / width;
4467 const size_t chunk_len = MIN(count, max_chunk_len);
4469 int retval;
4471 if (is_phys)
4472 retval = target_read_phys_memory(target, addr, width, chunk_len, buffer);
4473 else
4474 retval = target_read_memory(target, addr, width, chunk_len, buffer);
4476 if (retval != ERROR_OK) {
4477 LOG_DEBUG("read_memory: read at " TARGET_ADDR_FMT " with width=%u and count=%zu failed",
4478 addr, width_bits, chunk_len);
4480 * FIXME: we append the errmsg to the list of value already read.
4481 * Add a way to flush and replace old output, but LOG_DEBUG() it
4483 command_print(CMD, "read_memory: failed to read memory");
4484 free(buffer);
4485 return retval;
4488 for (size_t i = 0; i < chunk_len ; i++) {
4489 uint64_t v = 0;
4491 switch (width) {
4492 case 8:
4493 v = target_buffer_get_u64(target, &buffer[i * width]);
4494 break;
4495 case 4:
4496 v = target_buffer_get_u32(target, &buffer[i * width]);
4497 break;
4498 case 2:
4499 v = target_buffer_get_u16(target, &buffer[i * width]);
4500 break;
4501 case 1:
4502 v = buffer[i];
4503 break;
4506 command_print_sameline(CMD, "%s0x%" PRIx64, separator, v);
4507 separator = " ";
4510 count -= chunk_len;
4511 addr += chunk_len * width;
4514 free(buffer);
4516 return ERROR_OK;
4519 static int target_jim_write_memory(Jim_Interp *interp, int argc,
4520 Jim_Obj * const *argv)
4523 * argv[1] = memory address
4524 * argv[2] = desired element width in bits
4525 * argv[3] = list of data to write
4526 * argv[4] = optional "phys"
4529 if (argc < 4 || argc > 5) {
4530 Jim_WrongNumArgs(interp, 1, argv, "address width data ['phys']");
4531 return JIM_ERR;
4534 /* Arg 1: Memory address. */
4535 int e;
4536 jim_wide wide_addr;
4537 e = Jim_GetWide(interp, argv[1], &wide_addr);
4539 if (e != JIM_OK)
4540 return e;
4542 target_addr_t addr = (target_addr_t)wide_addr;
4544 /* Arg 2: Bit width of one element. */
4545 long l;
4546 e = Jim_GetLong(interp, argv[2], &l);
4548 if (e != JIM_OK)
4549 return e;
4551 const unsigned int width_bits = l;
4552 size_t count = Jim_ListLength(interp, argv[3]);
4554 /* Arg 4: Optional 'phys'. */
4555 bool is_phys = false;
4557 if (argc > 4) {
4558 const char *phys = Jim_GetString(argv[4], NULL);
4560 if (strcmp(phys, "phys")) {
4561 Jim_SetResultFormatted(interp, "invalid argument '%s', must be 'phys'", phys);
4562 return JIM_ERR;
4565 is_phys = true;
4568 switch (width_bits) {
4569 case 8:
4570 case 16:
4571 case 32:
4572 case 64:
4573 break;
4574 default:
4575 Jim_SetResultString(interp, "invalid width, must be 8, 16, 32 or 64", -1);
4576 return JIM_ERR;
4579 const unsigned int width = width_bits / 8;
4581 if ((addr + (count * width)) < addr) {
4582 Jim_SetResultString(interp, "write_memory: addr + len wraps to zero", -1);
4583 return JIM_ERR;
4586 if (count > 65536) {
4587 Jim_SetResultString(interp, "write_memory: too large memory write request, exceeds 64K elements", -1);
4588 return JIM_ERR;
4591 struct command_context *cmd_ctx = current_command_context(interp);
4592 assert(cmd_ctx != NULL);
4593 struct target *target = get_current_target(cmd_ctx);
4595 const size_t buffersize = 4096;
4596 uint8_t *buffer = malloc(buffersize);
4598 if (!buffer) {
4599 LOG_ERROR("Failed to allocate memory");
4600 return JIM_ERR;
4603 size_t j = 0;
4605 while (count > 0) {
4606 const unsigned int max_chunk_len = buffersize / width;
4607 const size_t chunk_len = MIN(count, max_chunk_len);
4609 for (size_t i = 0; i < chunk_len; i++, j++) {
4610 Jim_Obj *tmp = Jim_ListGetIndex(interp, argv[3], j);
4611 jim_wide element_wide;
4612 Jim_GetWide(interp, tmp, &element_wide);
4614 const uint64_t v = element_wide;
4616 switch (width) {
4617 case 8:
4618 target_buffer_set_u64(target, &buffer[i * width], v);
4619 break;
4620 case 4:
4621 target_buffer_set_u32(target, &buffer[i * width], v);
4622 break;
4623 case 2:
4624 target_buffer_set_u16(target, &buffer[i * width], v);
4625 break;
4626 case 1:
4627 buffer[i] = v & 0x0ff;
4628 break;
4632 count -= chunk_len;
4634 int retval;
4636 if (is_phys)
4637 retval = target_write_phys_memory(target, addr, width, chunk_len, buffer);
4638 else
4639 retval = target_write_memory(target, addr, width, chunk_len, buffer);
4641 if (retval != ERROR_OK) {
4642 LOG_ERROR("write_memory: write at " TARGET_ADDR_FMT " with width=%u and count=%zu failed",
4643 addr, width_bits, chunk_len);
4644 Jim_SetResultString(interp, "write_memory: failed to write memory", -1);
4645 e = JIM_ERR;
4646 break;
4649 addr += chunk_len * width;
4652 free(buffer);
4654 return e;
4657 /* FIX? should we propagate errors here rather than printing them
4658 * and continuing?
4660 void target_handle_event(struct target *target, enum target_event e)
4662 struct target_event_action *teap;
4663 int retval;
4665 for (teap = target->event_action; teap; teap = teap->next) {
4666 if (teap->event == e) {
4667 LOG_DEBUG("target: %s (%s) event: %d (%s) action: %s",
4668 target_name(target),
4669 target_type_name(target),
4671 target_event_name(e),
4672 Jim_GetString(teap->body, NULL));
4674 /* Override current target by the target an event
4675 * is issued from (lot of scripts need it).
4676 * Return back to previous override as soon
4677 * as the handler processing is done */
4678 struct command_context *cmd_ctx = current_command_context(teap->interp);
4679 struct target *saved_target_override = cmd_ctx->current_target_override;
4680 cmd_ctx->current_target_override = target;
4682 retval = Jim_EvalObj(teap->interp, teap->body);
4684 cmd_ctx->current_target_override = saved_target_override;
4686 if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
4687 return;
4689 if (retval == JIM_RETURN)
4690 retval = teap->interp->returnCode;
4692 if (retval != JIM_OK) {
4693 Jim_MakeErrorMessage(teap->interp);
4694 LOG_USER("Error executing event %s on target %s:\n%s",
4695 target_event_name(e),
4696 target_name(target),
4697 Jim_GetString(Jim_GetResult(teap->interp), NULL));
4698 /* clean both error code and stacktrace before return */
4699 Jim_Eval(teap->interp, "error \"\" \"\"");
4705 static int target_jim_get_reg(Jim_Interp *interp, int argc,
4706 Jim_Obj * const *argv)
4708 bool force = false;
4710 if (argc == 3) {
4711 const char *option = Jim_GetString(argv[1], NULL);
4713 if (!strcmp(option, "-force")) {
4714 argc--;
4715 argv++;
4716 force = true;
4717 } else {
4718 Jim_SetResultFormatted(interp, "invalid option '%s'", option);
4719 return JIM_ERR;
4723 if (argc != 2) {
4724 Jim_WrongNumArgs(interp, 1, argv, "[-force] list");
4725 return JIM_ERR;
4728 const int length = Jim_ListLength(interp, argv[1]);
4730 Jim_Obj *result_dict = Jim_NewDictObj(interp, NULL, 0);
4732 if (!result_dict)
4733 return JIM_ERR;
4735 struct command_context *cmd_ctx = current_command_context(interp);
4736 assert(cmd_ctx != NULL);
4737 const struct target *target = get_current_target(cmd_ctx);
4739 for (int i = 0; i < length; i++) {
4740 Jim_Obj *elem = Jim_ListGetIndex(interp, argv[1], i);
4742 if (!elem)
4743 return JIM_ERR;
4745 const char *reg_name = Jim_String(elem);
4747 struct reg *reg = register_get_by_name(target->reg_cache, reg_name,
4748 false);
4750 if (!reg || !reg->exist) {
4751 Jim_SetResultFormatted(interp, "unknown register '%s'", reg_name);
4752 return JIM_ERR;
4755 if (force || !reg->valid) {
4756 int retval = reg->type->get(reg);
4758 if (retval != ERROR_OK) {
4759 Jim_SetResultFormatted(interp, "failed to read register '%s'",
4760 reg_name);
4761 return JIM_ERR;
4765 char *reg_value = buf_to_hex_str(reg->value, reg->size);
4767 if (!reg_value) {
4768 LOG_ERROR("Failed to allocate memory");
4769 return JIM_ERR;
4772 char *tmp = alloc_printf("0x%s", reg_value);
4774 free(reg_value);
4776 if (!tmp) {
4777 LOG_ERROR("Failed to allocate memory");
4778 return JIM_ERR;
4781 Jim_DictAddElement(interp, result_dict, elem,
4782 Jim_NewStringObj(interp, tmp, -1));
4784 free(tmp);
4787 Jim_SetResult(interp, result_dict);
4789 return JIM_OK;
4792 static int target_jim_set_reg(Jim_Interp *interp, int argc,
4793 Jim_Obj * const *argv)
4795 if (argc != 2) {
4796 Jim_WrongNumArgs(interp, 1, argv, "dict");
4797 return JIM_ERR;
4800 int tmp;
4801 #if JIM_VERSION >= 80
4802 Jim_Obj **dict = Jim_DictPairs(interp, argv[1], &tmp);
4804 if (!dict)
4805 return JIM_ERR;
4806 #else
4807 Jim_Obj **dict;
4808 int ret = Jim_DictPairs(interp, argv[1], &dict, &tmp);
4810 if (ret != JIM_OK)
4811 return ret;
4812 #endif
4814 const unsigned int length = tmp;
4815 struct command_context *cmd_ctx = current_command_context(interp);
4816 assert(cmd_ctx);
4817 const struct target *target = get_current_target(cmd_ctx);
4819 for (unsigned int i = 0; i < length; i += 2) {
4820 const char *reg_name = Jim_String(dict[i]);
4821 const char *reg_value = Jim_String(dict[i + 1]);
4822 struct reg *reg = register_get_by_name(target->reg_cache, reg_name,
4823 false);
4825 if (!reg || !reg->exist) {
4826 Jim_SetResultFormatted(interp, "unknown register '%s'", reg_name);
4827 return JIM_ERR;
4830 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
4832 if (!buf) {
4833 LOG_ERROR("Failed to allocate memory");
4834 return JIM_ERR;
4837 str_to_buf(reg_value, strlen(reg_value), buf, reg->size, 0);
4838 int retval = reg->type->set(reg, buf);
4839 free(buf);
4841 if (retval != ERROR_OK) {
4842 Jim_SetResultFormatted(interp, "failed to set '%s' to register '%s'",
4843 reg_value, reg_name);
4844 return JIM_ERR;
4848 return JIM_OK;
4852 * Returns true only if the target has a handler for the specified event.
4854 bool target_has_event_action(const struct target *target, enum target_event event)
4856 struct target_event_action *teap;
4858 for (teap = target->event_action; teap; teap = teap->next) {
4859 if (teap->event == event)
4860 return true;
4862 return false;
4865 enum target_cfg_param {
4866 TCFG_TYPE,
4867 TCFG_EVENT,
4868 TCFG_WORK_AREA_VIRT,
4869 TCFG_WORK_AREA_PHYS,
4870 TCFG_WORK_AREA_SIZE,
4871 TCFG_WORK_AREA_BACKUP,
4872 TCFG_ENDIAN,
4873 TCFG_COREID,
4874 TCFG_CHAIN_POSITION,
4875 TCFG_DBGBASE,
4876 TCFG_RTOS,
4877 TCFG_DEFER_EXAMINE,
4878 TCFG_GDB_PORT,
4879 TCFG_GDB_MAX_CONNECTIONS,
4882 static struct jim_nvp nvp_config_opts[] = {
4883 { .name = "-type", .value = TCFG_TYPE },
4884 { .name = "-event", .value = TCFG_EVENT },
4885 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4886 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4887 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4888 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4889 { .name = "-endian", .value = TCFG_ENDIAN },
4890 { .name = "-coreid", .value = TCFG_COREID },
4891 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4892 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4893 { .name = "-rtos", .value = TCFG_RTOS },
4894 { .name = "-defer-examine", .value = TCFG_DEFER_EXAMINE },
4895 { .name = "-gdb-port", .value = TCFG_GDB_PORT },
4896 { .name = "-gdb-max-connections", .value = TCFG_GDB_MAX_CONNECTIONS },
4897 { .name = NULL, .value = -1 }
4900 static int target_configure(struct jim_getopt_info *goi, struct target *target)
4902 struct jim_nvp *n;
4903 Jim_Obj *o;
4904 jim_wide w;
4905 int e;
4907 /* parse config or cget options ... */
4908 while (goi->argc > 0) {
4909 Jim_SetEmptyResult(goi->interp);
4910 /* jim_getopt_debug(goi); */
4912 if (target->type->target_jim_configure) {
4913 /* target defines a configure function */
4914 /* target gets first dibs on parameters */
4915 e = (*(target->type->target_jim_configure))(target, goi);
4916 if (e == JIM_OK) {
4917 /* more? */
4918 continue;
4920 if (e == JIM_ERR) {
4921 /* An error */
4922 return e;
4924 /* otherwise we 'continue' below */
4926 e = jim_getopt_nvp(goi, nvp_config_opts, &n);
4927 if (e != JIM_OK) {
4928 jim_getopt_nvp_unknown(goi, nvp_config_opts, 0);
4929 return e;
4931 switch (n->value) {
4932 case TCFG_TYPE:
4933 /* not settable */
4934 if (goi->isconfigure) {
4935 Jim_SetResultFormatted(goi->interp,
4936 "not settable: %s", n->name);
4937 return JIM_ERR;
4938 } else {
4939 no_params:
4940 if (goi->argc != 0) {
4941 Jim_WrongNumArgs(goi->interp,
4942 goi->argc, goi->argv,
4943 "NO PARAMS");
4944 return JIM_ERR;
4947 Jim_SetResultString(goi->interp,
4948 target_type_name(target), -1);
4949 /* loop for more */
4950 break;
4951 case TCFG_EVENT:
4952 if (goi->argc == 0) {
4953 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4954 return JIM_ERR;
4957 e = jim_getopt_nvp(goi, nvp_target_event, &n);
4958 if (e != JIM_OK) {
4959 jim_getopt_nvp_unknown(goi, nvp_target_event, 1);
4960 return e;
4963 if (goi->isconfigure) {
4964 if (goi->argc != 1) {
4965 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4966 return JIM_ERR;
4968 } else {
4969 if (goi->argc != 0) {
4970 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4971 return JIM_ERR;
4976 struct target_event_action *teap;
4978 teap = target->event_action;
4979 /* replace existing? */
4980 while (teap) {
4981 if (teap->event == (enum target_event)n->value)
4982 break;
4983 teap = teap->next;
4986 if (goi->isconfigure) {
4987 /* START_DEPRECATED_TPIU */
4988 if (n->value == TARGET_EVENT_TRACE_CONFIG)
4989 LOG_INFO("DEPRECATED target event %s; use TPIU events {pre,post}-{enable,disable}", n->name);
4990 /* END_DEPRECATED_TPIU */
4992 bool replace = true;
4993 if (!teap) {
4994 /* create new */
4995 teap = calloc(1, sizeof(*teap));
4996 replace = false;
4998 teap->event = n->value;
4999 teap->interp = goi->interp;
5000 jim_getopt_obj(goi, &o);
5001 if (teap->body)
5002 Jim_DecrRefCount(teap->interp, teap->body);
5003 teap->body = Jim_DuplicateObj(goi->interp, o);
5005 * FIXME:
5006 * Tcl/TK - "tk events" have a nice feature.
5007 * See the "BIND" command.
5008 * We should support that here.
5009 * You can specify %X and %Y in the event code.
5010 * The idea is: %T - target name.
5011 * The idea is: %N - target number
5012 * The idea is: %E - event name.
5014 Jim_IncrRefCount(teap->body);
5016 if (!replace) {
5017 /* add to head of event list */
5018 teap->next = target->event_action;
5019 target->event_action = teap;
5021 Jim_SetEmptyResult(goi->interp);
5022 } else {
5023 /* get */
5024 if (!teap)
5025 Jim_SetEmptyResult(goi->interp);
5026 else
5027 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
5030 /* loop for more */
5031 break;
5033 case TCFG_WORK_AREA_VIRT:
5034 if (goi->isconfigure) {
5035 target_free_all_working_areas(target);
5036 e = jim_getopt_wide(goi, &w);
5037 if (e != JIM_OK)
5038 return e;
5039 target->working_area_virt = w;
5040 target->working_area_virt_spec = true;
5041 } else {
5042 if (goi->argc != 0)
5043 goto no_params;
5045 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
5046 /* loop for more */
5047 break;
5049 case TCFG_WORK_AREA_PHYS:
5050 if (goi->isconfigure) {
5051 target_free_all_working_areas(target);
5052 e = jim_getopt_wide(goi, &w);
5053 if (e != JIM_OK)
5054 return e;
5055 target->working_area_phys = w;
5056 target->working_area_phys_spec = true;
5057 } else {
5058 if (goi->argc != 0)
5059 goto no_params;
5061 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
5062 /* loop for more */
5063 break;
5065 case TCFG_WORK_AREA_SIZE:
5066 if (goi->isconfigure) {
5067 target_free_all_working_areas(target);
5068 e = jim_getopt_wide(goi, &w);
5069 if (e != JIM_OK)
5070 return e;
5071 target->working_area_size = w;
5072 } else {
5073 if (goi->argc != 0)
5074 goto no_params;
5076 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
5077 /* loop for more */
5078 break;
5080 case TCFG_WORK_AREA_BACKUP:
5081 if (goi->isconfigure) {
5082 target_free_all_working_areas(target);
5083 e = jim_getopt_wide(goi, &w);
5084 if (e != JIM_OK)
5085 return e;
5086 /* make this boolean */
5087 target->backup_working_area = (w != 0);
5088 } else {
5089 if (goi->argc != 0)
5090 goto no_params;
5092 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area ? 1 : 0));
5093 /* loop for more e*/
5094 break;
5097 case TCFG_ENDIAN:
5098 if (goi->isconfigure) {
5099 e = jim_getopt_nvp(goi, nvp_target_endian, &n);
5100 if (e != JIM_OK) {
5101 jim_getopt_nvp_unknown(goi, nvp_target_endian, 1);
5102 return e;
5104 target->endianness = n->value;
5105 } else {
5106 if (goi->argc != 0)
5107 goto no_params;
5109 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5110 if (!n->name) {
5111 target->endianness = TARGET_LITTLE_ENDIAN;
5112 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5114 Jim_SetResultString(goi->interp, n->name, -1);
5115 /* loop for more */
5116 break;
5118 case TCFG_COREID:
5119 if (goi->isconfigure) {
5120 e = jim_getopt_wide(goi, &w);
5121 if (e != JIM_OK)
5122 return e;
5123 target->coreid = (int32_t)w;
5124 } else {
5125 if (goi->argc != 0)
5126 goto no_params;
5128 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->coreid));
5129 /* loop for more */
5130 break;
5132 case TCFG_CHAIN_POSITION:
5133 if (goi->isconfigure) {
5134 Jim_Obj *o_t;
5135 struct jtag_tap *tap;
5137 if (target->has_dap) {
5138 Jim_SetResultString(goi->interp,
5139 "target requires -dap parameter instead of -chain-position!", -1);
5140 return JIM_ERR;
5143 target_free_all_working_areas(target);
5144 e = jim_getopt_obj(goi, &o_t);
5145 if (e != JIM_OK)
5146 return e;
5147 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
5148 if (!tap)
5149 return JIM_ERR;
5150 target->tap = tap;
5151 target->tap_configured = true;
5152 } else {
5153 if (goi->argc != 0)
5154 goto no_params;
5156 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
5157 /* loop for more e*/
5158 break;
5159 case TCFG_DBGBASE:
5160 if (goi->isconfigure) {
5161 e = jim_getopt_wide(goi, &w);
5162 if (e != JIM_OK)
5163 return e;
5164 target->dbgbase = (uint32_t)w;
5165 target->dbgbase_set = true;
5166 } else {
5167 if (goi->argc != 0)
5168 goto no_params;
5170 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
5171 /* loop for more */
5172 break;
5173 case TCFG_RTOS:
5174 /* RTOS */
5176 int result = rtos_create(goi, target);
5177 if (result != JIM_OK)
5178 return result;
5180 /* loop for more */
5181 break;
5183 case TCFG_DEFER_EXAMINE:
5184 /* DEFER_EXAMINE */
5185 target->defer_examine = true;
5186 /* loop for more */
5187 break;
5189 case TCFG_GDB_PORT:
5190 if (goi->isconfigure) {
5191 struct command_context *cmd_ctx = current_command_context(goi->interp);
5192 if (cmd_ctx->mode != COMMAND_CONFIG) {
5193 Jim_SetResultString(goi->interp, "-gdb-port must be configured before 'init'", -1);
5194 return JIM_ERR;
5197 const char *s;
5198 e = jim_getopt_string(goi, &s, NULL);
5199 if (e != JIM_OK)
5200 return e;
5201 free(target->gdb_port_override);
5202 target->gdb_port_override = strdup(s);
5203 } else {
5204 if (goi->argc != 0)
5205 goto no_params;
5207 Jim_SetResultString(goi->interp, target->gdb_port_override ? target->gdb_port_override : "undefined", -1);
5208 /* loop for more */
5209 break;
5211 case TCFG_GDB_MAX_CONNECTIONS:
5212 if (goi->isconfigure) {
5213 struct command_context *cmd_ctx = current_command_context(goi->interp);
5214 if (cmd_ctx->mode != COMMAND_CONFIG) {
5215 Jim_SetResultString(goi->interp, "-gdb-max-connections must be configured before 'init'", -1);
5216 return JIM_ERR;
5219 e = jim_getopt_wide(goi, &w);
5220 if (e != JIM_OK)
5221 return e;
5222 target->gdb_max_connections = (w < 0) ? CONNECTION_LIMIT_UNLIMITED : (int)w;
5223 } else {
5224 if (goi->argc != 0)
5225 goto no_params;
5227 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->gdb_max_connections));
5228 break;
5230 } /* while (goi->argc) */
5233 /* done - we return */
5234 return JIM_OK;
5237 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5239 struct command *c = jim_to_command(interp);
5240 struct jim_getopt_info goi;
5242 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5243 goi.isconfigure = !strcmp(c->name, "configure");
5244 if (goi.argc < 1) {
5245 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5246 "missing: -option ...");
5247 return JIM_ERR;
5249 struct command_context *cmd_ctx = current_command_context(interp);
5250 assert(cmd_ctx);
5251 struct target *target = get_current_target(cmd_ctx);
5252 return target_configure(&goi, target);
5255 COMMAND_HANDLER(handle_target_examine)
5257 bool allow_defer = false;
5259 if (CMD_ARGC > 1)
5260 return ERROR_COMMAND_SYNTAX_ERROR;
5262 if (CMD_ARGC == 1) {
5263 if (strcmp(CMD_ARGV[0], "allow-defer"))
5264 return ERROR_COMMAND_ARGUMENT_INVALID;
5265 allow_defer = true;
5268 struct target *target = get_current_target(CMD_CTX);
5269 if (!target->tap->enabled) {
5270 command_print(CMD, "[TAP is disabled]");
5271 return ERROR_FAIL;
5274 if (allow_defer && target->defer_examine) {
5275 LOG_INFO("Deferring arp_examine of %s", target_name(target));
5276 LOG_INFO("Use arp_examine command to examine it manually!");
5277 return ERROR_OK;
5280 int retval = target->type->examine(target);
5281 if (retval != ERROR_OK) {
5282 target_reset_examined(target);
5283 return retval;
5286 target_set_examined(target);
5288 return ERROR_OK;
5291 COMMAND_HANDLER(handle_target_was_examined)
5293 if (CMD_ARGC != 0)
5294 return ERROR_COMMAND_SYNTAX_ERROR;
5296 struct target *target = get_current_target(CMD_CTX);
5298 command_print(CMD, "%d", target_was_examined(target) ? 1 : 0);
5300 return ERROR_OK;
5303 COMMAND_HANDLER(handle_target_examine_deferred)
5305 if (CMD_ARGC != 0)
5306 return ERROR_COMMAND_SYNTAX_ERROR;
5308 struct target *target = get_current_target(CMD_CTX);
5310 command_print(CMD, "%d", target->defer_examine ? 1 : 0);
5312 return ERROR_OK;
5315 COMMAND_HANDLER(handle_target_halt_gdb)
5317 if (CMD_ARGC != 0)
5318 return ERROR_COMMAND_SYNTAX_ERROR;
5320 struct target *target = get_current_target(CMD_CTX);
5322 return target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
5325 COMMAND_HANDLER(handle_target_poll)
5327 if (CMD_ARGC != 0)
5328 return ERROR_COMMAND_SYNTAX_ERROR;
5330 struct target *target = get_current_target(CMD_CTX);
5331 if (!target->tap->enabled) {
5332 command_print(CMD, "[TAP is disabled]");
5333 return ERROR_FAIL;
5336 if (!(target_was_examined(target)))
5337 return ERROR_TARGET_NOT_EXAMINED;
5339 return target->type->poll(target);
5342 COMMAND_HANDLER(handle_target_reset)
5344 if (CMD_ARGC != 2)
5345 return ERROR_COMMAND_SYNTAX_ERROR;
5347 const struct nvp *n = nvp_name2value(nvp_assert, CMD_ARGV[0]);
5348 if (!n->name) {
5349 nvp_unknown_command_print(CMD, nvp_assert, NULL, CMD_ARGV[0]);
5350 return ERROR_COMMAND_ARGUMENT_INVALID;
5353 /* the halt or not param */
5354 int a;
5355 COMMAND_PARSE_NUMBER(int, CMD_ARGV[1], a);
5357 struct target *target = get_current_target(CMD_CTX);
5358 if (!target->tap->enabled) {
5359 command_print(CMD, "[TAP is disabled]");
5360 return ERROR_FAIL;
5363 if (!target->type->assert_reset || !target->type->deassert_reset) {
5364 command_print(CMD, "No target-specific reset for %s", target_name(target));
5365 return ERROR_FAIL;
5368 if (target->defer_examine)
5369 target_reset_examined(target);
5371 /* determine if we should halt or not. */
5372 target->reset_halt = (a != 0);
5373 /* When this happens - all workareas are invalid. */
5374 target_free_all_working_areas_restore(target, 0);
5376 /* do the assert */
5377 if (n->value == NVP_ASSERT)
5378 return target->type->assert_reset(target);
5379 return target->type->deassert_reset(target);
5382 COMMAND_HANDLER(handle_target_halt)
5384 if (CMD_ARGC != 0)
5385 return ERROR_COMMAND_SYNTAX_ERROR;
5387 struct target *target = get_current_target(CMD_CTX);
5388 if (!target->tap->enabled) {
5389 command_print(CMD, "[TAP is disabled]");
5390 return ERROR_FAIL;
5393 return target->type->halt(target);
5396 COMMAND_HANDLER(handle_target_wait_state)
5398 if (CMD_ARGC != 2)
5399 return ERROR_COMMAND_SYNTAX_ERROR;
5401 const struct nvp *n = nvp_name2value(nvp_target_state, CMD_ARGV[0]);
5402 if (!n->name) {
5403 nvp_unknown_command_print(CMD, nvp_target_state, NULL, CMD_ARGV[0]);
5404 return ERROR_COMMAND_ARGUMENT_INVALID;
5407 unsigned int a;
5408 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], a);
5410 struct target *target = get_current_target(CMD_CTX);
5411 if (!target->tap->enabled) {
5412 command_print(CMD, "[TAP is disabled]");
5413 return ERROR_FAIL;
5416 int retval = target_wait_state(target, n->value, a);
5417 if (retval != ERROR_OK) {
5418 command_print(CMD,
5419 "target: %s wait %s fails (%d) %s",
5420 target_name(target), n->name,
5421 retval, target_strerror_safe(retval));
5422 return retval;
5424 return ERROR_OK;
5426 /* List for human, Events defined for this target.
5427 * scripts/programs should use 'name cget -event NAME'
5429 COMMAND_HANDLER(handle_target_event_list)
5431 struct target *target = get_current_target(CMD_CTX);
5432 struct target_event_action *teap = target->event_action;
5434 command_print(CMD, "Event actions for target %s\n",
5435 target_name(target));
5436 command_print(CMD, "%-25s | Body", "Event");
5437 command_print(CMD, "------------------------- | "
5438 "----------------------------------------");
5439 while (teap) {
5440 command_print(CMD, "%-25s | %s",
5441 target_event_name(teap->event),
5442 Jim_GetString(teap->body, NULL));
5443 teap = teap->next;
5445 command_print(CMD, "***END***");
5446 return ERROR_OK;
5449 COMMAND_HANDLER(handle_target_current_state)
5451 if (CMD_ARGC != 0)
5452 return ERROR_COMMAND_SYNTAX_ERROR;
5454 struct target *target = get_current_target(CMD_CTX);
5456 command_print(CMD, "%s", target_state_name(target));
5458 return ERROR_OK;
5461 COMMAND_HANDLER(handle_target_debug_reason)
5463 if (CMD_ARGC != 0)
5464 return ERROR_COMMAND_SYNTAX_ERROR;
5466 struct target *target = get_current_target(CMD_CTX);
5469 const char *debug_reason = nvp_value2name(nvp_target_debug_reason,
5470 target->debug_reason)->name;
5472 if (!debug_reason) {
5473 command_print(CMD, "bug: invalid debug reason (%d)",
5474 target->debug_reason);
5475 return ERROR_FAIL;
5478 command_print(CMD, "%s", debug_reason);
5480 return ERROR_OK;
5483 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5485 struct jim_getopt_info goi;
5486 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5487 if (goi.argc != 1) {
5488 const char *cmd_name = Jim_GetString(argv[0], NULL);
5489 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5490 return JIM_ERR;
5492 struct jim_nvp *n;
5493 int e = jim_getopt_nvp(&goi, nvp_target_event, &n);
5494 if (e != JIM_OK) {
5495 jim_getopt_nvp_unknown(&goi, nvp_target_event, 1);
5496 return e;
5498 struct command_context *cmd_ctx = current_command_context(interp);
5499 assert(cmd_ctx);
5500 struct target *target = get_current_target(cmd_ctx);
5501 target_handle_event(target, n->value);
5502 return JIM_OK;
5505 static const struct command_registration target_instance_command_handlers[] = {
5507 .name = "configure",
5508 .mode = COMMAND_ANY,
5509 .jim_handler = jim_target_configure,
5510 .help = "configure a new target for use",
5511 .usage = "[target_attribute ...]",
5514 .name = "cget",
5515 .mode = COMMAND_ANY,
5516 .jim_handler = jim_target_configure,
5517 .help = "returns the specified target attribute",
5518 .usage = "target_attribute",
5521 .name = "mwd",
5522 .handler = handle_mw_command,
5523 .mode = COMMAND_EXEC,
5524 .help = "Write 64-bit word(s) to target memory",
5525 .usage = "address data [count]",
5528 .name = "mww",
5529 .handler = handle_mw_command,
5530 .mode = COMMAND_EXEC,
5531 .help = "Write 32-bit word(s) to target memory",
5532 .usage = "address data [count]",
5535 .name = "mwh",
5536 .handler = handle_mw_command,
5537 .mode = COMMAND_EXEC,
5538 .help = "Write 16-bit half-word(s) to target memory",
5539 .usage = "address data [count]",
5542 .name = "mwb",
5543 .handler = handle_mw_command,
5544 .mode = COMMAND_EXEC,
5545 .help = "Write byte(s) to target memory",
5546 .usage = "address data [count]",
5549 .name = "mdd",
5550 .handler = handle_md_command,
5551 .mode = COMMAND_EXEC,
5552 .help = "Display target memory as 64-bit words",
5553 .usage = "address [count]",
5556 .name = "mdw",
5557 .handler = handle_md_command,
5558 .mode = COMMAND_EXEC,
5559 .help = "Display target memory as 32-bit words",
5560 .usage = "address [count]",
5563 .name = "mdh",
5564 .handler = handle_md_command,
5565 .mode = COMMAND_EXEC,
5566 .help = "Display target memory as 16-bit half-words",
5567 .usage = "address [count]",
5570 .name = "mdb",
5571 .handler = handle_md_command,
5572 .mode = COMMAND_EXEC,
5573 .help = "Display target memory as 8-bit bytes",
5574 .usage = "address [count]",
5577 .name = "get_reg",
5578 .mode = COMMAND_EXEC,
5579 .jim_handler = target_jim_get_reg,
5580 .help = "Get register values from the target",
5581 .usage = "list",
5584 .name = "set_reg",
5585 .mode = COMMAND_EXEC,
5586 .jim_handler = target_jim_set_reg,
5587 .help = "Set target register values",
5588 .usage = "dict",
5591 .name = "read_memory",
5592 .mode = COMMAND_EXEC,
5593 .handler = handle_target_read_memory,
5594 .help = "Read Tcl list of 8/16/32/64 bit numbers from target memory",
5595 .usage = "address width count ['phys']",
5598 .name = "write_memory",
5599 .mode = COMMAND_EXEC,
5600 .jim_handler = target_jim_write_memory,
5601 .help = "Write Tcl list of 8/16/32/64 bit numbers to target memory",
5602 .usage = "address width data ['phys']",
5605 .name = "eventlist",
5606 .handler = handle_target_event_list,
5607 .mode = COMMAND_EXEC,
5608 .help = "displays a table of events defined for this target",
5609 .usage = "",
5612 .name = "curstate",
5613 .mode = COMMAND_EXEC,
5614 .handler = handle_target_current_state,
5615 .help = "displays the current state of this target",
5616 .usage = "",
5619 .name = "debug_reason",
5620 .mode = COMMAND_EXEC,
5621 .handler = handle_target_debug_reason,
5622 .help = "displays the debug reason of this target",
5623 .usage = "",
5626 .name = "arp_examine",
5627 .mode = COMMAND_EXEC,
5628 .handler = handle_target_examine,
5629 .help = "used internally for reset processing",
5630 .usage = "['allow-defer']",
5633 .name = "was_examined",
5634 .mode = COMMAND_EXEC,
5635 .handler = handle_target_was_examined,
5636 .help = "used internally for reset processing",
5637 .usage = "",
5640 .name = "examine_deferred",
5641 .mode = COMMAND_EXEC,
5642 .handler = handle_target_examine_deferred,
5643 .help = "used internally for reset processing",
5644 .usage = "",
5647 .name = "arp_halt_gdb",
5648 .mode = COMMAND_EXEC,
5649 .handler = handle_target_halt_gdb,
5650 .help = "used internally for reset processing to halt GDB",
5651 .usage = "",
5654 .name = "arp_poll",
5655 .mode = COMMAND_EXEC,
5656 .handler = handle_target_poll,
5657 .help = "used internally for reset processing",
5658 .usage = "",
5661 .name = "arp_reset",
5662 .mode = COMMAND_EXEC,
5663 .handler = handle_target_reset,
5664 .help = "used internally for reset processing",
5665 .usage = "'assert'|'deassert' halt",
5668 .name = "arp_halt",
5669 .mode = COMMAND_EXEC,
5670 .handler = handle_target_halt,
5671 .help = "used internally for reset processing",
5672 .usage = "",
5675 .name = "arp_waitstate",
5676 .mode = COMMAND_EXEC,
5677 .handler = handle_target_wait_state,
5678 .help = "used internally for reset processing",
5679 .usage = "statename timeoutmsecs",
5682 .name = "invoke-event",
5683 .mode = COMMAND_EXEC,
5684 .jim_handler = jim_target_invoke_event,
5685 .help = "invoke handler for specified event",
5686 .usage = "event_name",
5688 COMMAND_REGISTRATION_DONE
5691 static int target_create(struct jim_getopt_info *goi)
5693 Jim_Obj *new_cmd;
5694 Jim_Cmd *cmd;
5695 const char *cp;
5696 int e;
5697 int x;
5698 struct target *target;
5699 struct command_context *cmd_ctx;
5701 cmd_ctx = current_command_context(goi->interp);
5702 assert(cmd_ctx);
5704 if (goi->argc < 3) {
5705 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5706 return JIM_ERR;
5709 /* COMMAND */
5710 jim_getopt_obj(goi, &new_cmd);
5711 /* does this command exist? */
5712 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_NONE);
5713 if (cmd) {
5714 cp = Jim_GetString(new_cmd, NULL);
5715 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5716 return JIM_ERR;
5719 /* TYPE */
5720 e = jim_getopt_string(goi, &cp, NULL);
5721 if (e != JIM_OK)
5722 return e;
5723 struct transport *tr = get_current_transport();
5724 if (tr && tr->override_target) {
5725 e = tr->override_target(&cp);
5726 if (e != ERROR_OK) {
5727 LOG_ERROR("The selected transport doesn't support this target");
5728 return JIM_ERR;
5730 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5732 /* now does target type exist */
5733 for (x = 0 ; target_types[x] ; x++) {
5734 if (strcmp(cp, target_types[x]->name) == 0) {
5735 /* found */
5736 break;
5739 if (!target_types[x]) {
5740 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5741 for (x = 0 ; target_types[x] ; x++) {
5742 if (target_types[x + 1]) {
5743 Jim_AppendStrings(goi->interp,
5744 Jim_GetResult(goi->interp),
5745 target_types[x]->name,
5746 ", ", NULL);
5747 } else {
5748 Jim_AppendStrings(goi->interp,
5749 Jim_GetResult(goi->interp),
5750 " or ",
5751 target_types[x]->name, NULL);
5754 return JIM_ERR;
5757 /* Create it */
5758 target = calloc(1, sizeof(struct target));
5759 if (!target) {
5760 LOG_ERROR("Out of memory");
5761 return JIM_ERR;
5764 /* set empty smp cluster */
5765 target->smp_targets = &empty_smp_targets;
5767 /* allocate memory for each unique target type */
5768 target->type = malloc(sizeof(struct target_type));
5769 if (!target->type) {
5770 LOG_ERROR("Out of memory");
5771 free(target);
5772 return JIM_ERR;
5775 memcpy(target->type, target_types[x], sizeof(struct target_type));
5777 /* default to first core, override with -coreid */
5778 target->coreid = 0;
5780 target->working_area = 0x0;
5781 target->working_area_size = 0x0;
5782 target->working_areas = NULL;
5783 target->backup_working_area = false;
5785 target->state = TARGET_UNKNOWN;
5786 target->debug_reason = DBG_REASON_UNDEFINED;
5787 target->reg_cache = NULL;
5788 target->breakpoints = NULL;
5789 target->watchpoints = NULL;
5790 target->next = NULL;
5791 target->arch_info = NULL;
5793 target->verbose_halt_msg = true;
5795 target->halt_issued = false;
5797 /* initialize trace information */
5798 target->trace_info = calloc(1, sizeof(struct trace));
5799 if (!target->trace_info) {
5800 LOG_ERROR("Out of memory");
5801 free(target->type);
5802 free(target);
5803 return JIM_ERR;
5806 target->dbgmsg = NULL;
5807 target->dbg_msg_enabled = 0;
5809 target->endianness = TARGET_ENDIAN_UNKNOWN;
5811 target->rtos = NULL;
5812 target->rtos_auto_detect = false;
5814 target->gdb_port_override = NULL;
5815 target->gdb_max_connections = 1;
5817 /* Do the rest as "configure" options */
5818 goi->isconfigure = 1;
5819 e = target_configure(goi, target);
5821 if (e == JIM_OK) {
5822 if (target->has_dap) {
5823 if (!target->dap_configured) {
5824 Jim_SetResultString(goi->interp, "-dap ?name? required when creating target", -1);
5825 e = JIM_ERR;
5827 } else {
5828 if (!target->tap_configured) {
5829 Jim_SetResultString(goi->interp, "-chain-position ?name? required when creating target", -1);
5830 e = JIM_ERR;
5833 /* tap must be set after target was configured */
5834 if (!target->tap)
5835 e = JIM_ERR;
5838 if (e != JIM_OK) {
5839 rtos_destroy(target);
5840 free(target->gdb_port_override);
5841 free(target->trace_info);
5842 free(target->type);
5843 free(target);
5844 return e;
5847 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5848 /* default endian to little if not specified */
5849 target->endianness = TARGET_LITTLE_ENDIAN;
5852 cp = Jim_GetString(new_cmd, NULL);
5853 target->cmd_name = strdup(cp);
5854 if (!target->cmd_name) {
5855 LOG_ERROR("Out of memory");
5856 rtos_destroy(target);
5857 free(target->gdb_port_override);
5858 free(target->trace_info);
5859 free(target->type);
5860 free(target);
5861 return JIM_ERR;
5864 if (target->type->target_create) {
5865 e = (*(target->type->target_create))(target, goi->interp);
5866 if (e != ERROR_OK) {
5867 LOG_DEBUG("target_create failed");
5868 free(target->cmd_name);
5869 rtos_destroy(target);
5870 free(target->gdb_port_override);
5871 free(target->trace_info);
5872 free(target->type);
5873 free(target);
5874 return JIM_ERR;
5878 /* create the target specific commands */
5879 if (target->type->commands) {
5880 e = register_commands(cmd_ctx, NULL, target->type->commands);
5881 if (e != ERROR_OK)
5882 LOG_ERROR("unable to register '%s' commands", cp);
5885 /* now - create the new target name command */
5886 const struct command_registration target_subcommands[] = {
5888 .chain = target_instance_command_handlers,
5891 .chain = target->type->commands,
5893 COMMAND_REGISTRATION_DONE
5895 const struct command_registration target_commands[] = {
5897 .name = cp,
5898 .mode = COMMAND_ANY,
5899 .help = "target command group",
5900 .usage = "",
5901 .chain = target_subcommands,
5903 COMMAND_REGISTRATION_DONE
5905 e = register_commands_override_target(cmd_ctx, NULL, target_commands, target);
5906 if (e != ERROR_OK) {
5907 if (target->type->deinit_target)
5908 target->type->deinit_target(target);
5909 free(target->cmd_name);
5910 rtos_destroy(target);
5911 free(target->gdb_port_override);
5912 free(target->trace_info);
5913 free(target->type);
5914 free(target);
5915 return JIM_ERR;
5918 /* append to end of list */
5919 append_to_list_all_targets(target);
5921 cmd_ctx->current_target = target;
5922 return JIM_OK;
5925 COMMAND_HANDLER(handle_target_current)
5927 if (CMD_ARGC != 0)
5928 return ERROR_COMMAND_SYNTAX_ERROR;
5930 struct target *target = get_current_target_or_null(CMD_CTX);
5931 if (target)
5932 command_print(CMD, "%s", target_name(target));
5934 return ERROR_OK;
5937 COMMAND_HANDLER(handle_target_types)
5939 if (CMD_ARGC != 0)
5940 return ERROR_COMMAND_SYNTAX_ERROR;
5942 for (unsigned int x = 0; target_types[x]; x++)
5943 command_print(CMD, "%s", target_types[x]->name);
5945 return ERROR_OK;
5948 COMMAND_HANDLER(handle_target_names)
5950 if (CMD_ARGC != 0)
5951 return ERROR_COMMAND_SYNTAX_ERROR;
5953 struct target *target = all_targets;
5954 while (target) {
5955 command_print(CMD, "%s", target_name(target));
5956 target = target->next;
5959 return ERROR_OK;
5962 static struct target_list *
5963 __attribute__((warn_unused_result))
5964 create_target_list_node(const char *targetname)
5966 struct target *target = get_target(targetname);
5967 LOG_DEBUG("%s ", targetname);
5968 if (!target)
5969 return NULL;
5971 struct target_list *new = malloc(sizeof(struct target_list));
5972 if (!new) {
5973 LOG_ERROR("Out of memory");
5974 return new;
5977 new->target = target;
5978 return new;
5981 static int get_target_with_common_rtos_type(struct command_invocation *cmd,
5982 struct list_head *lh, struct target **result)
5984 struct target *target = NULL;
5985 struct target_list *curr;
5986 foreach_smp_target(curr, lh) {
5987 struct rtos *curr_rtos = curr->target->rtos;
5988 if (curr_rtos) {
5989 if (target && target->rtos && target->rtos->type != curr_rtos->type) {
5990 command_print(cmd, "Different rtos types in members of one smp target!");
5991 return ERROR_FAIL;
5993 target = curr->target;
5996 *result = target;
5997 return ERROR_OK;
6000 COMMAND_HANDLER(handle_target_smp)
6002 static int smp_group = 1;
6004 if (CMD_ARGC == 0) {
6005 LOG_DEBUG("Empty SMP target");
6006 return ERROR_OK;
6008 LOG_DEBUG("%d", CMD_ARGC);
6009 /* CMD_ARGC[0] = target to associate in smp
6010 * CMD_ARGC[1] = target to associate in smp
6011 * CMD_ARGC[2] ...
6014 struct list_head *lh = malloc(sizeof(*lh));
6015 if (!lh) {
6016 LOG_ERROR("Out of memory");
6017 return ERROR_FAIL;
6019 INIT_LIST_HEAD(lh);
6021 for (unsigned int i = 0; i < CMD_ARGC; i++) {
6022 struct target_list *new = create_target_list_node(CMD_ARGV[i]);
6023 if (new)
6024 list_add_tail(&new->lh, lh);
6026 /* now parse the list of cpu and put the target in smp mode*/
6027 struct target_list *curr;
6028 foreach_smp_target(curr, lh) {
6029 struct target *target = curr->target;
6030 target->smp = smp_group;
6031 target->smp_targets = lh;
6033 smp_group++;
6035 struct target *rtos_target;
6036 int retval = get_target_with_common_rtos_type(CMD, lh, &rtos_target);
6037 if (retval == ERROR_OK && rtos_target)
6038 retval = rtos_smp_init(rtos_target);
6040 return retval;
6043 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6045 struct jim_getopt_info goi;
6046 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
6047 if (goi.argc < 3) {
6048 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
6049 "<name> <target_type> [<target_options> ...]");
6050 return JIM_ERR;
6052 return target_create(&goi);
6055 static const struct command_registration target_subcommand_handlers[] = {
6057 .name = "init",
6058 .mode = COMMAND_CONFIG,
6059 .handler = handle_target_init_command,
6060 .help = "initialize targets",
6061 .usage = "",
6064 .name = "create",
6065 .mode = COMMAND_CONFIG,
6066 .jim_handler = jim_target_create,
6067 .usage = "name type '-chain-position' name [options ...]",
6068 .help = "Creates and selects a new target",
6071 .name = "current",
6072 .mode = COMMAND_ANY,
6073 .handler = handle_target_current,
6074 .help = "Returns the currently selected target",
6075 .usage = "",
6078 .name = "types",
6079 .mode = COMMAND_ANY,
6080 .handler = handle_target_types,
6081 .help = "Returns the available target types as "
6082 "a list of strings",
6083 .usage = "",
6086 .name = "names",
6087 .mode = COMMAND_ANY,
6088 .handler = handle_target_names,
6089 .help = "Returns the names of all targets as a list of strings",
6090 .usage = "",
6093 .name = "smp",
6094 .mode = COMMAND_ANY,
6095 .handler = handle_target_smp,
6096 .usage = "targetname1 targetname2 ...",
6097 .help = "gather several target in a smp list"
6100 COMMAND_REGISTRATION_DONE
6103 struct fast_load {
6104 target_addr_t address;
6105 uint8_t *data;
6106 int length;
6110 static int fastload_num;
6111 static struct fast_load *fastload;
6113 static void free_fastload(void)
6115 if (fastload) {
6116 for (int i = 0; i < fastload_num; i++)
6117 free(fastload[i].data);
6118 free(fastload);
6119 fastload = NULL;
6123 COMMAND_HANDLER(handle_fast_load_image_command)
6125 uint8_t *buffer;
6126 size_t buf_cnt;
6127 uint32_t image_size;
6128 target_addr_t min_address = 0;
6129 target_addr_t max_address = -1;
6131 struct image image;
6133 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
6134 &image, &min_address, &max_address);
6135 if (retval != ERROR_OK)
6136 return retval;
6138 struct duration bench;
6139 duration_start(&bench);
6141 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
6142 if (retval != ERROR_OK)
6143 return retval;
6145 image_size = 0x0;
6146 retval = ERROR_OK;
6147 fastload_num = image.num_sections;
6148 fastload = malloc(sizeof(struct fast_load)*image.num_sections);
6149 if (!fastload) {
6150 command_print(CMD, "out of memory");
6151 image_close(&image);
6152 return ERROR_FAIL;
6154 memset(fastload, 0, sizeof(struct fast_load)*image.num_sections);
6155 for (unsigned int i = 0; i < image.num_sections; i++) {
6156 buffer = malloc(image.sections[i].size);
6157 if (!buffer) {
6158 command_print(CMD, "error allocating buffer for section (%d bytes)",
6159 (int)(image.sections[i].size));
6160 retval = ERROR_FAIL;
6161 break;
6164 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
6165 if (retval != ERROR_OK) {
6166 free(buffer);
6167 break;
6170 uint32_t offset = 0;
6171 uint32_t length = buf_cnt;
6173 /* DANGER!!! beware of unsigned comparison here!!! */
6175 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
6176 (image.sections[i].base_address < max_address)) {
6177 if (image.sections[i].base_address < min_address) {
6178 /* clip addresses below */
6179 offset += min_address-image.sections[i].base_address;
6180 length -= offset;
6183 if (image.sections[i].base_address + buf_cnt > max_address)
6184 length -= (image.sections[i].base_address + buf_cnt)-max_address;
6186 fastload[i].address = image.sections[i].base_address + offset;
6187 fastload[i].data = malloc(length);
6188 if (!fastload[i].data) {
6189 free(buffer);
6190 command_print(CMD, "error allocating buffer for section (%" PRIu32 " bytes)",
6191 length);
6192 retval = ERROR_FAIL;
6193 break;
6195 memcpy(fastload[i].data, buffer + offset, length);
6196 fastload[i].length = length;
6198 image_size += length;
6199 command_print(CMD, "%u bytes written at address 0x%8.8x",
6200 (unsigned int)length,
6201 ((unsigned int)(image.sections[i].base_address + offset)));
6204 free(buffer);
6207 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
6208 command_print(CMD, "Loaded %" PRIu32 " bytes "
6209 "in %fs (%0.3f KiB/s)", image_size,
6210 duration_elapsed(&bench), duration_kbps(&bench, image_size));
6212 command_print(CMD,
6213 "WARNING: image has not been loaded to target!"
6214 "You can issue a 'fast_load' to finish loading.");
6217 image_close(&image);
6219 if (retval != ERROR_OK)
6220 free_fastload();
6222 return retval;
6225 COMMAND_HANDLER(handle_fast_load_command)
6227 if (CMD_ARGC > 0)
6228 return ERROR_COMMAND_SYNTAX_ERROR;
6229 if (!fastload) {
6230 LOG_ERROR("No image in memory");
6231 return ERROR_FAIL;
6233 int i;
6234 int64_t ms = timeval_ms();
6235 int size = 0;
6236 int retval = ERROR_OK;
6237 for (i = 0; i < fastload_num; i++) {
6238 struct target *target = get_current_target(CMD_CTX);
6239 command_print(CMD, "Write to 0x%08x, length 0x%08x",
6240 (unsigned int)(fastload[i].address),
6241 (unsigned int)(fastload[i].length));
6242 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
6243 if (retval != ERROR_OK)
6244 break;
6245 size += fastload[i].length;
6247 if (retval == ERROR_OK) {
6248 int64_t after = timeval_ms();
6249 command_print(CMD, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
6251 return retval;
6254 static const struct command_registration target_command_handlers[] = {
6256 .name = "targets",
6257 .handler = handle_targets_command,
6258 .mode = COMMAND_ANY,
6259 .help = "change current default target (one parameter) "
6260 "or prints table of all targets (no parameters)",
6261 .usage = "[target]",
6264 .name = "target",
6265 .mode = COMMAND_CONFIG,
6266 .help = "configure target",
6267 .chain = target_subcommand_handlers,
6268 .usage = "",
6270 COMMAND_REGISTRATION_DONE
6273 int target_register_commands(struct command_context *cmd_ctx)
6275 return register_commands(cmd_ctx, NULL, target_command_handlers);
6278 static bool target_reset_nag = true;
6280 bool get_target_reset_nag(void)
6282 return target_reset_nag;
6285 COMMAND_HANDLER(handle_target_reset_nag)
6287 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
6288 &target_reset_nag, "Nag after each reset about options to improve "
6289 "performance");
6292 COMMAND_HANDLER(handle_ps_command)
6294 struct target *target = get_current_target(CMD_CTX);
6295 char *display;
6296 if (target->state != TARGET_HALTED) {
6297 command_print(CMD, "Error: [%s] not halted", target_name(target));
6298 return ERROR_TARGET_NOT_HALTED;
6301 if ((target->rtos) && (target->rtos->type)
6302 && (target->rtos->type->ps_command)) {
6303 display = target->rtos->type->ps_command(target);
6304 command_print(CMD, "%s", display);
6305 free(display);
6306 return ERROR_OK;
6307 } else {
6308 LOG_INFO("failed");
6309 return ERROR_TARGET_FAILURE;
6313 static void binprint(struct command_invocation *cmd, const char *text, const uint8_t *buf, int size)
6315 if (text)
6316 command_print_sameline(cmd, "%s", text);
6317 for (int i = 0; i < size; i++)
6318 command_print_sameline(cmd, " %02x", buf[i]);
6319 command_print(cmd, " ");
6322 COMMAND_HANDLER(handle_test_mem_access_command)
6324 struct target *target = get_current_target(CMD_CTX);
6325 uint32_t test_size;
6326 int retval = ERROR_OK;
6328 if (target->state != TARGET_HALTED) {
6329 command_print(CMD, "Error: [%s] not halted", target_name(target));
6330 return ERROR_TARGET_NOT_HALTED;
6333 if (CMD_ARGC != 1)
6334 return ERROR_COMMAND_SYNTAX_ERROR;
6336 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
6338 /* Test reads */
6339 size_t num_bytes = test_size + 4;
6341 struct working_area *wa = NULL;
6342 retval = target_alloc_working_area(target, num_bytes, &wa);
6343 if (retval != ERROR_OK) {
6344 LOG_ERROR("Not enough working area");
6345 return ERROR_FAIL;
6348 uint8_t *test_pattern = malloc(num_bytes);
6350 for (size_t i = 0; i < num_bytes; i++)
6351 test_pattern[i] = rand();
6353 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6354 if (retval != ERROR_OK) {
6355 LOG_ERROR("Test pattern write failed");
6356 goto out;
6359 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6360 for (int size = 1; size <= 4; size *= 2) {
6361 for (int offset = 0; offset < 4; offset++) {
6362 uint32_t count = test_size / size;
6363 size_t host_bufsiz = (count + 2) * size + host_offset;
6364 uint8_t *read_ref = malloc(host_bufsiz);
6365 uint8_t *read_buf = malloc(host_bufsiz);
6367 for (size_t i = 0; i < host_bufsiz; i++) {
6368 read_ref[i] = rand();
6369 read_buf[i] = read_ref[i];
6371 command_print_sameline(CMD,
6372 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
6373 size, offset, host_offset ? "un" : "");
6375 struct duration bench;
6376 duration_start(&bench);
6378 retval = target_read_memory(target, wa->address + offset, size, count,
6379 read_buf + size + host_offset);
6381 duration_measure(&bench);
6383 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6384 command_print(CMD, "Unsupported alignment");
6385 goto next;
6386 } else if (retval != ERROR_OK) {
6387 command_print(CMD, "Memory read failed");
6388 goto next;
6391 /* replay on host */
6392 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
6394 /* check result */
6395 int result = memcmp(read_ref, read_buf, host_bufsiz);
6396 if (result == 0) {
6397 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6398 duration_elapsed(&bench),
6399 duration_kbps(&bench, count * size));
6400 } else {
6401 command_print(CMD, "Compare failed");
6402 binprint(CMD, "ref:", read_ref, host_bufsiz);
6403 binprint(CMD, "buf:", read_buf, host_bufsiz);
6405 next:
6406 free(read_ref);
6407 free(read_buf);
6412 out:
6413 free(test_pattern);
6415 target_free_working_area(target, wa);
6417 /* Test writes */
6418 num_bytes = test_size + 4 + 4 + 4;
6420 retval = target_alloc_working_area(target, num_bytes, &wa);
6421 if (retval != ERROR_OK) {
6422 LOG_ERROR("Not enough working area");
6423 return ERROR_FAIL;
6426 test_pattern = malloc(num_bytes);
6428 for (size_t i = 0; i < num_bytes; i++)
6429 test_pattern[i] = rand();
6431 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6432 for (int size = 1; size <= 4; size *= 2) {
6433 for (int offset = 0; offset < 4; offset++) {
6434 uint32_t count = test_size / size;
6435 size_t host_bufsiz = count * size + host_offset;
6436 uint8_t *read_ref = malloc(num_bytes);
6437 uint8_t *read_buf = malloc(num_bytes);
6438 uint8_t *write_buf = malloc(host_bufsiz);
6440 for (size_t i = 0; i < host_bufsiz; i++)
6441 write_buf[i] = rand();
6442 command_print_sameline(CMD,
6443 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
6444 size, offset, host_offset ? "un" : "");
6446 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6447 if (retval != ERROR_OK) {
6448 command_print(CMD, "Test pattern write failed");
6449 goto nextw;
6452 /* replay on host */
6453 memcpy(read_ref, test_pattern, num_bytes);
6454 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
6456 struct duration bench;
6457 duration_start(&bench);
6459 retval = target_write_memory(target, wa->address + size + offset, size, count,
6460 write_buf + host_offset);
6462 duration_measure(&bench);
6464 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6465 command_print(CMD, "Unsupported alignment");
6466 goto nextw;
6467 } else if (retval != ERROR_OK) {
6468 command_print(CMD, "Memory write failed");
6469 goto nextw;
6472 /* read back */
6473 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
6474 if (retval != ERROR_OK) {
6475 command_print(CMD, "Test pattern write failed");
6476 goto nextw;
6479 /* check result */
6480 int result = memcmp(read_ref, read_buf, num_bytes);
6481 if (result == 0) {
6482 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6483 duration_elapsed(&bench),
6484 duration_kbps(&bench, count * size));
6485 } else {
6486 command_print(CMD, "Compare failed");
6487 binprint(CMD, "ref:", read_ref, num_bytes);
6488 binprint(CMD, "buf:", read_buf, num_bytes);
6490 nextw:
6491 free(read_ref);
6492 free(read_buf);
6497 free(test_pattern);
6499 target_free_working_area(target, wa);
6500 return retval;
6503 static const struct command_registration target_exec_command_handlers[] = {
6505 .name = "fast_load_image",
6506 .handler = handle_fast_load_image_command,
6507 .mode = COMMAND_ANY,
6508 .help = "Load image into server memory for later use by "
6509 "fast_load; primarily for profiling",
6510 .usage = "filename [address ['bin'|'ihex'|'elf'|'s19' "
6511 "[min_address [max_length]]]]",
6514 .name = "fast_load",
6515 .handler = handle_fast_load_command,
6516 .mode = COMMAND_EXEC,
6517 .help = "loads active fast load image to current target "
6518 "- mainly for profiling purposes",
6519 .usage = "",
6522 .name = "profile",
6523 .handler = handle_profile_command,
6524 .mode = COMMAND_EXEC,
6525 .usage = "seconds filename [start end]",
6526 .help = "profiling samples the CPU PC",
6528 /** @todo don't register virt2phys() unless target supports it */
6530 .name = "virt2phys",
6531 .handler = handle_virt2phys_command,
6532 .mode = COMMAND_ANY,
6533 .help = "translate a virtual address into a physical address",
6534 .usage = "virtual_address",
6537 .name = "reg",
6538 .handler = handle_reg_command,
6539 .mode = COMMAND_EXEC,
6540 .help = "display (reread from target with \"force\") or set a register; "
6541 "with no arguments, displays all registers and their values",
6542 .usage = "[(register_number|register_name) [(value|'force')]]",
6545 .name = "poll",
6546 .handler = handle_poll_command,
6547 .mode = COMMAND_EXEC,
6548 .help = "poll target state; or reconfigure background polling",
6549 .usage = "['on'|'off']",
6552 .name = "wait_halt",
6553 .handler = handle_wait_halt_command,
6554 .mode = COMMAND_EXEC,
6555 .help = "wait up to the specified number of milliseconds "
6556 "(default 5000) for a previously requested halt",
6557 .usage = "[milliseconds]",
6560 .name = "halt",
6561 .handler = handle_halt_command,
6562 .mode = COMMAND_EXEC,
6563 .help = "request target to halt, then wait up to the specified "
6564 "number of milliseconds (default 5000) for it to complete",
6565 .usage = "[milliseconds]",
6568 .name = "resume",
6569 .handler = handle_resume_command,
6570 .mode = COMMAND_EXEC,
6571 .help = "resume target execution from current PC or address",
6572 .usage = "[address]",
6575 .name = "reset",
6576 .handler = handle_reset_command,
6577 .mode = COMMAND_EXEC,
6578 .usage = "[run|halt|init]",
6579 .help = "Reset all targets into the specified mode. "
6580 "Default reset mode is run, if not given.",
6583 .name = "soft_reset_halt",
6584 .handler = handle_soft_reset_halt_command,
6585 .mode = COMMAND_EXEC,
6586 .usage = "",
6587 .help = "halt the target and do a soft reset",
6590 .name = "step",
6591 .handler = handle_step_command,
6592 .mode = COMMAND_EXEC,
6593 .help = "step one instruction from current PC or address",
6594 .usage = "[address]",
6597 .name = "mdd",
6598 .handler = handle_md_command,
6599 .mode = COMMAND_EXEC,
6600 .help = "display memory double-words",
6601 .usage = "['phys'] address [count]",
6604 .name = "mdw",
6605 .handler = handle_md_command,
6606 .mode = COMMAND_EXEC,
6607 .help = "display memory words",
6608 .usage = "['phys'] address [count]",
6611 .name = "mdh",
6612 .handler = handle_md_command,
6613 .mode = COMMAND_EXEC,
6614 .help = "display memory half-words",
6615 .usage = "['phys'] address [count]",
6618 .name = "mdb",
6619 .handler = handle_md_command,
6620 .mode = COMMAND_EXEC,
6621 .help = "display memory bytes",
6622 .usage = "['phys'] address [count]",
6625 .name = "mwd",
6626 .handler = handle_mw_command,
6627 .mode = COMMAND_EXEC,
6628 .help = "write memory double-word",
6629 .usage = "['phys'] address value [count]",
6632 .name = "mww",
6633 .handler = handle_mw_command,
6634 .mode = COMMAND_EXEC,
6635 .help = "write memory word",
6636 .usage = "['phys'] address value [count]",
6639 .name = "mwh",
6640 .handler = handle_mw_command,
6641 .mode = COMMAND_EXEC,
6642 .help = "write memory half-word",
6643 .usage = "['phys'] address value [count]",
6646 .name = "mwb",
6647 .handler = handle_mw_command,
6648 .mode = COMMAND_EXEC,
6649 .help = "write memory byte",
6650 .usage = "['phys'] address value [count]",
6653 .name = "bp",
6654 .handler = handle_bp_command,
6655 .mode = COMMAND_EXEC,
6656 .help = "list or set hardware or software breakpoint",
6657 .usage = "[<address> [<asid>] <length> ['hw'|'hw_ctx']]",
6660 .name = "rbp",
6661 .handler = handle_rbp_command,
6662 .mode = COMMAND_EXEC,
6663 .help = "remove breakpoint",
6664 .usage = "'all' | address",
6667 .name = "wp",
6668 .handler = handle_wp_command,
6669 .mode = COMMAND_EXEC,
6670 .help = "list (no params) or create watchpoints",
6671 .usage = "[address length [('r'|'w'|'a') [value [mask]]]]",
6674 .name = "rwp",
6675 .handler = handle_rwp_command,
6676 .mode = COMMAND_EXEC,
6677 .help = "remove watchpoint",
6678 .usage = "'all' | address",
6681 .name = "load_image",
6682 .handler = handle_load_image_command,
6683 .mode = COMMAND_EXEC,
6684 .usage = "filename [address ['bin'|'ihex'|'elf'|'s19' "
6685 "[min_address [max_length]]]]",
6688 .name = "dump_image",
6689 .handler = handle_dump_image_command,
6690 .mode = COMMAND_EXEC,
6691 .usage = "filename address size",
6694 .name = "verify_image_checksum",
6695 .handler = handle_verify_image_checksum_command,
6696 .mode = COMMAND_EXEC,
6697 .usage = "filename [offset [type]]",
6700 .name = "verify_image",
6701 .handler = handle_verify_image_command,
6702 .mode = COMMAND_EXEC,
6703 .usage = "filename [offset [type]]",
6706 .name = "test_image",
6707 .handler = handle_test_image_command,
6708 .mode = COMMAND_EXEC,
6709 .usage = "filename [offset [type]]",
6712 .name = "get_reg",
6713 .mode = COMMAND_EXEC,
6714 .jim_handler = target_jim_get_reg,
6715 .help = "Get register values from the target",
6716 .usage = "list",
6719 .name = "set_reg",
6720 .mode = COMMAND_EXEC,
6721 .jim_handler = target_jim_set_reg,
6722 .help = "Set target register values",
6723 .usage = "dict",
6726 .name = "read_memory",
6727 .mode = COMMAND_EXEC,
6728 .handler = handle_target_read_memory,
6729 .help = "Read Tcl list of 8/16/32/64 bit numbers from target memory",
6730 .usage = "address width count ['phys']",
6733 .name = "write_memory",
6734 .mode = COMMAND_EXEC,
6735 .jim_handler = target_jim_write_memory,
6736 .help = "Write Tcl list of 8/16/32/64 bit numbers to target memory",
6737 .usage = "address width data ['phys']",
6740 .name = "reset_nag",
6741 .handler = handle_target_reset_nag,
6742 .mode = COMMAND_ANY,
6743 .help = "Nag after each reset about options that could have been "
6744 "enabled to improve performance.",
6745 .usage = "['enable'|'disable']",
6748 .name = "ps",
6749 .handler = handle_ps_command,
6750 .mode = COMMAND_EXEC,
6751 .help = "list all tasks",
6752 .usage = "",
6755 .name = "test_mem_access",
6756 .handler = handle_test_mem_access_command,
6757 .mode = COMMAND_EXEC,
6758 .help = "Test the target's memory access functions",
6759 .usage = "size",
6762 COMMAND_REGISTRATION_DONE
6764 static int target_register_user_commands(struct command_context *cmd_ctx)
6766 int retval = ERROR_OK;
6767 retval = target_request_register_commands(cmd_ctx);
6768 if (retval != ERROR_OK)
6769 return retval;
6771 retval = trace_register_commands(cmd_ctx);
6772 if (retval != ERROR_OK)
6773 return retval;
6776 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);
6779 const char *target_debug_reason_str(enum target_debug_reason reason)
6781 switch (reason) {
6782 case DBG_REASON_DBGRQ:
6783 return "DBGRQ";
6784 case DBG_REASON_BREAKPOINT:
6785 return "BREAKPOINT";
6786 case DBG_REASON_WATCHPOINT:
6787 return "WATCHPOINT";
6788 case DBG_REASON_WPTANDBKPT:
6789 return "WPTANDBKPT";
6790 case DBG_REASON_SINGLESTEP:
6791 return "SINGLESTEP";
6792 case DBG_REASON_NOTHALTED:
6793 return "NOTHALTED";
6794 case DBG_REASON_EXIT:
6795 return "EXIT";
6796 case DBG_REASON_EXC_CATCH:
6797 return "EXC_CATCH";
6798 case DBG_REASON_UNDEFINED:
6799 return "UNDEFINED";
6800 default:
6801 return "UNKNOWN!";