target/target.c: adding keep_alive() to while loop.
[openocd.git] / src / target / target.c
blob871588393b52bdf76372954722d18a4cb10206f5
1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
4 * *
5 * Copyright (C) 2007-2010 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
7 * *
8 * Copyright (C) 2008, Duane Ellis *
9 * openocd@duaneeellis.com *
10 * *
11 * Copyright (C) 2008 by Spencer Oliver *
12 * spen@spen-soft.co.uk *
13 * *
14 * Copyright (C) 2008 by Rick Altherr *
15 * kc8apf@kc8apf.net> *
16 * *
17 * Copyright (C) 2011 by Broadcom Corporation *
18 * Evan Hunter - ehunter@broadcom.com *
19 * *
20 * Copyright (C) ST-Ericsson SA 2011 *
21 * michel.jaouen@stericsson.com : smp minimum support *
22 * *
23 * Copyright (C) 2011 Andreas Fritiofson *
24 * andreas.fritiofson@gmail.com *
25 * *
26 * This program is free software; you can redistribute it and/or modify *
27 * it under the terms of the GNU General Public License as published by *
28 * the Free Software Foundation; either version 2 of the License, or *
29 * (at your option) any later version. *
30 * *
31 * This program is distributed in the hope that it will be useful, *
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
34 * GNU General Public License for more details. *
35 * *
36 * You should have received a copy of the GNU General Public License *
37 * along with this program. If not, see <http://www.gnu.org/licenses/>. *
38 ***************************************************************************/
40 #ifdef HAVE_CONFIG_H
41 #include "config.h"
42 #endif
44 #include <helper/time_support.h>
45 #include <jtag/jtag.h>
46 #include <flash/nor/core.h>
48 #include "target.h"
49 #include "target_type.h"
50 #include "target_request.h"
51 #include "breakpoints.h"
52 #include "register.h"
53 #include "trace.h"
54 #include "image.h"
55 #include "rtos/rtos.h"
56 #include "transport/transport.h"
57 #include "arm_cti.h"
59 /* default halt wait timeout (ms) */
60 #define DEFAULT_HALT_TIMEOUT 5000
62 static int target_read_buffer_default(struct target *target, target_addr_t address,
63 uint32_t count, uint8_t *buffer);
64 static int target_write_buffer_default(struct target *target, target_addr_t address,
65 uint32_t count, const uint8_t *buffer);
66 static int target_array2mem(Jim_Interp *interp, struct target *target,
67 int argc, Jim_Obj * const *argv);
68 static int target_mem2array(Jim_Interp *interp, struct target *target,
69 int argc, Jim_Obj * const *argv);
70 static int target_register_user_commands(struct command_context *cmd_ctx);
71 static int target_get_gdb_fileio_info_default(struct target *target,
72 struct gdb_fileio_info *fileio_info);
73 static int target_gdb_fileio_end_default(struct target *target, int retcode,
74 int fileio_errno, bool ctrl_c);
75 static int target_profiling_default(struct target *target, uint32_t *samples,
76 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds);
78 /* targets */
79 extern struct target_type arm7tdmi_target;
80 extern struct target_type arm720t_target;
81 extern struct target_type arm9tdmi_target;
82 extern struct target_type arm920t_target;
83 extern struct target_type arm966e_target;
84 extern struct target_type arm946e_target;
85 extern struct target_type arm926ejs_target;
86 extern struct target_type fa526_target;
87 extern struct target_type feroceon_target;
88 extern struct target_type dragonite_target;
89 extern struct target_type xscale_target;
90 extern struct target_type cortexm_target;
91 extern struct target_type cortexa_target;
92 extern struct target_type aarch64_target;
93 extern struct target_type cortexr4_target;
94 extern struct target_type arm11_target;
95 extern struct target_type ls1_sap_target;
96 extern struct target_type mips_m4k_target;
97 extern struct target_type avr_target;
98 extern struct target_type dsp563xx_target;
99 extern struct target_type dsp5680xx_target;
100 extern struct target_type testee_target;
101 extern struct target_type avr32_ap7k_target;
102 extern struct target_type hla_target;
103 extern struct target_type nds32_v2_target;
104 extern struct target_type nds32_v3_target;
105 extern struct target_type nds32_v3m_target;
106 extern struct target_type or1k_target;
107 extern struct target_type quark_x10xx_target;
108 extern struct target_type quark_d20xx_target;
109 extern struct target_type stm8_target;
110 extern struct target_type riscv_target;
111 extern struct target_type mem_ap_target;
112 extern struct target_type esirisc_target;
114 static struct target_type *target_types[] = {
115 &arm7tdmi_target,
116 &arm9tdmi_target,
117 &arm920t_target,
118 &arm720t_target,
119 &arm966e_target,
120 &arm946e_target,
121 &arm926ejs_target,
122 &fa526_target,
123 &feroceon_target,
124 &dragonite_target,
125 &xscale_target,
126 &cortexm_target,
127 &cortexa_target,
128 &cortexr4_target,
129 &arm11_target,
130 &ls1_sap_target,
131 &mips_m4k_target,
132 &avr_target,
133 &dsp563xx_target,
134 &dsp5680xx_target,
135 &testee_target,
136 &avr32_ap7k_target,
137 &hla_target,
138 &nds32_v2_target,
139 &nds32_v3_target,
140 &nds32_v3m_target,
141 &or1k_target,
142 &quark_x10xx_target,
143 &quark_d20xx_target,
144 &stm8_target,
145 &riscv_target,
146 &mem_ap_target,
147 &esirisc_target,
148 #if BUILD_TARGET64
149 &aarch64_target,
150 #endif
151 NULL,
154 struct target *all_targets;
155 static struct target_event_callback *target_event_callbacks;
156 static struct target_timer_callback *target_timer_callbacks;
157 LIST_HEAD(target_reset_callback_list);
158 LIST_HEAD(target_trace_callback_list);
159 static const int polling_interval = 100;
161 static const Jim_Nvp nvp_assert[] = {
162 { .name = "assert", NVP_ASSERT },
163 { .name = "deassert", NVP_DEASSERT },
164 { .name = "T", NVP_ASSERT },
165 { .name = "F", NVP_DEASSERT },
166 { .name = "t", NVP_ASSERT },
167 { .name = "f", NVP_DEASSERT },
168 { .name = NULL, .value = -1 }
171 static const Jim_Nvp nvp_error_target[] = {
172 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
173 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
174 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
175 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
176 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
177 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
178 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
179 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
180 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
181 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
182 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
183 { .value = -1, .name = NULL }
186 static const char *target_strerror_safe(int err)
188 const Jim_Nvp *n;
190 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
191 if (n->name == NULL)
192 return "unknown";
193 else
194 return n->name;
197 static const Jim_Nvp nvp_target_event[] = {
199 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
200 { .value = TARGET_EVENT_HALTED, .name = "halted" },
201 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
202 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
203 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
205 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
206 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
208 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
209 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
210 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
211 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
212 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
213 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
214 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
215 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
217 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
218 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
220 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
221 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
223 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
224 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
226 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
227 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
229 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
230 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
232 { .value = TARGET_EVENT_TRACE_CONFIG, .name = "trace-config" },
234 { .name = NULL, .value = -1 }
237 static const Jim_Nvp nvp_target_state[] = {
238 { .name = "unknown", .value = TARGET_UNKNOWN },
239 { .name = "running", .value = TARGET_RUNNING },
240 { .name = "halted", .value = TARGET_HALTED },
241 { .name = "reset", .value = TARGET_RESET },
242 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
243 { .name = NULL, .value = -1 },
246 static const Jim_Nvp nvp_target_debug_reason[] = {
247 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
248 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
249 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
250 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
251 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
252 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
253 { .name = "program-exit" , .value = DBG_REASON_EXIT },
254 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
255 { .name = NULL, .value = -1 },
258 static const Jim_Nvp nvp_target_endian[] = {
259 { .name = "big", .value = TARGET_BIG_ENDIAN },
260 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
261 { .name = "be", .value = TARGET_BIG_ENDIAN },
262 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
263 { .name = NULL, .value = -1 },
266 static const Jim_Nvp nvp_reset_modes[] = {
267 { .name = "unknown", .value = RESET_UNKNOWN },
268 { .name = "run" , .value = RESET_RUN },
269 { .name = "halt" , .value = RESET_HALT },
270 { .name = "init" , .value = RESET_INIT },
271 { .name = NULL , .value = -1 },
274 const char *debug_reason_name(struct target *t)
276 const char *cp;
278 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
279 t->debug_reason)->name;
280 if (!cp) {
281 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
282 cp = "(*BUG*unknown*BUG*)";
284 return cp;
287 const char *target_state_name(struct target *t)
289 const char *cp;
290 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
291 if (!cp) {
292 LOG_ERROR("Invalid target state: %d", (int)(t->state));
293 cp = "(*BUG*unknown*BUG*)";
296 if (!target_was_examined(t) && t->defer_examine)
297 cp = "examine deferred";
299 return cp;
302 const char *target_event_name(enum target_event event)
304 const char *cp;
305 cp = Jim_Nvp_value2name_simple(nvp_target_event, event)->name;
306 if (!cp) {
307 LOG_ERROR("Invalid target event: %d", (int)(event));
308 cp = "(*BUG*unknown*BUG*)";
310 return cp;
313 const char *target_reset_mode_name(enum target_reset_mode reset_mode)
315 const char *cp;
316 cp = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name;
317 if (!cp) {
318 LOG_ERROR("Invalid target reset mode: %d", (int)(reset_mode));
319 cp = "(*BUG*unknown*BUG*)";
321 return cp;
324 /* determine the number of the new target */
325 static int new_target_number(void)
327 struct target *t;
328 int x;
330 /* number is 0 based */
331 x = -1;
332 t = all_targets;
333 while (t) {
334 if (x < t->target_number)
335 x = t->target_number;
336 t = t->next;
338 return x + 1;
341 /* read a uint64_t from a buffer in target memory endianness */
342 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
344 if (target->endianness == TARGET_LITTLE_ENDIAN)
345 return le_to_h_u64(buffer);
346 else
347 return be_to_h_u64(buffer);
350 /* read a uint32_t from a buffer in target memory endianness */
351 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
353 if (target->endianness == TARGET_LITTLE_ENDIAN)
354 return le_to_h_u32(buffer);
355 else
356 return be_to_h_u32(buffer);
359 /* read a uint24_t from a buffer in target memory endianness */
360 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
362 if (target->endianness == TARGET_LITTLE_ENDIAN)
363 return le_to_h_u24(buffer);
364 else
365 return be_to_h_u24(buffer);
368 /* read a uint16_t from a buffer in target memory endianness */
369 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
371 if (target->endianness == TARGET_LITTLE_ENDIAN)
372 return le_to_h_u16(buffer);
373 else
374 return be_to_h_u16(buffer);
377 /* read a uint8_t from a buffer in target memory endianness */
378 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
380 return *buffer & 0x0ff;
383 /* write a uint64_t to a buffer in target memory endianness */
384 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
386 if (target->endianness == TARGET_LITTLE_ENDIAN)
387 h_u64_to_le(buffer, value);
388 else
389 h_u64_to_be(buffer, value);
392 /* write a uint32_t to a buffer in target memory endianness */
393 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
395 if (target->endianness == TARGET_LITTLE_ENDIAN)
396 h_u32_to_le(buffer, value);
397 else
398 h_u32_to_be(buffer, value);
401 /* write a uint24_t to a buffer in target memory endianness */
402 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
404 if (target->endianness == TARGET_LITTLE_ENDIAN)
405 h_u24_to_le(buffer, value);
406 else
407 h_u24_to_be(buffer, value);
410 /* write a uint16_t to a buffer in target memory endianness */
411 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
413 if (target->endianness == TARGET_LITTLE_ENDIAN)
414 h_u16_to_le(buffer, value);
415 else
416 h_u16_to_be(buffer, value);
419 /* write a uint8_t to a buffer in target memory endianness */
420 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
422 *buffer = value;
425 /* write a uint64_t array to a buffer in target memory endianness */
426 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
428 uint32_t i;
429 for (i = 0; i < count; i++)
430 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
433 /* write a uint32_t array to a buffer in target memory endianness */
434 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
436 uint32_t i;
437 for (i = 0; i < count; i++)
438 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
441 /* write a uint16_t array to a buffer in target memory endianness */
442 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
444 uint32_t i;
445 for (i = 0; i < count; i++)
446 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
449 /* write a uint64_t array to a buffer in target memory endianness */
450 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
452 uint32_t i;
453 for (i = 0; i < count; i++)
454 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
457 /* write a uint32_t array to a buffer in target memory endianness */
458 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
460 uint32_t i;
461 for (i = 0; i < count; i++)
462 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
465 /* write a uint16_t array to a buffer in target memory endianness */
466 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
468 uint32_t i;
469 for (i = 0; i < count; i++)
470 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
473 /* return a pointer to a configured target; id is name or number */
474 struct target *get_target(const char *id)
476 struct target *target;
478 /* try as tcltarget name */
479 for (target = all_targets; target; target = target->next) {
480 if (target_name(target) == NULL)
481 continue;
482 if (strcmp(id, target_name(target)) == 0)
483 return target;
486 /* It's OK to remove this fallback sometime after August 2010 or so */
488 /* no match, try as number */
489 unsigned num;
490 if (parse_uint(id, &num) != ERROR_OK)
491 return NULL;
493 for (target = all_targets; target; target = target->next) {
494 if (target->target_number == (int)num) {
495 LOG_WARNING("use '%s' as target identifier, not '%u'",
496 target_name(target), num);
497 return target;
501 return NULL;
504 /* returns a pointer to the n-th configured target */
505 struct target *get_target_by_num(int num)
507 struct target *target = all_targets;
509 while (target) {
510 if (target->target_number == num)
511 return target;
512 target = target->next;
515 return NULL;
518 struct target *get_current_target(struct command_context *cmd_ctx)
520 struct target *target = cmd_ctx->current_target_override
521 ? cmd_ctx->current_target_override
522 : cmd_ctx->current_target;
524 if (target == NULL) {
525 LOG_ERROR("BUG: current_target out of bounds");
526 exit(-1);
529 return target;
532 int target_poll(struct target *target)
534 int retval;
536 /* We can't poll until after examine */
537 if (!target_was_examined(target)) {
538 /* Fail silently lest we pollute the log */
539 return ERROR_FAIL;
542 retval = target->type->poll(target);
543 if (retval != ERROR_OK)
544 return retval;
546 if (target->halt_issued) {
547 if (target->state == TARGET_HALTED)
548 target->halt_issued = false;
549 else {
550 int64_t t = timeval_ms() - target->halt_issued_time;
551 if (t > DEFAULT_HALT_TIMEOUT) {
552 target->halt_issued = false;
553 LOG_INFO("Halt timed out, wake up GDB.");
554 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
559 return ERROR_OK;
562 int target_halt(struct target *target)
564 int retval;
565 /* We can't poll until after examine */
566 if (!target_was_examined(target)) {
567 LOG_ERROR("Target not examined yet");
568 return ERROR_FAIL;
571 retval = target->type->halt(target);
572 if (retval != ERROR_OK)
573 return retval;
575 target->halt_issued = true;
576 target->halt_issued_time = timeval_ms();
578 return ERROR_OK;
582 * Make the target (re)start executing using its saved execution
583 * context (possibly with some modifications).
585 * @param target Which target should start executing.
586 * @param current True to use the target's saved program counter instead
587 * of the address parameter
588 * @param address Optionally used as the program counter.
589 * @param handle_breakpoints True iff breakpoints at the resumption PC
590 * should be skipped. (For example, maybe execution was stopped by
591 * such a breakpoint, in which case it would be counterprodutive to
592 * let it re-trigger.
593 * @param debug_execution False if all working areas allocated by OpenOCD
594 * should be released and/or restored to their original contents.
595 * (This would for example be true to run some downloaded "helper"
596 * algorithm code, which resides in one such working buffer and uses
597 * another for data storage.)
599 * @todo Resolve the ambiguity about what the "debug_execution" flag
600 * signifies. For example, Target implementations don't agree on how
601 * it relates to invalidation of the register cache, or to whether
602 * breakpoints and watchpoints should be enabled. (It would seem wrong
603 * to enable breakpoints when running downloaded "helper" algorithms
604 * (debug_execution true), since the breakpoints would be set to match
605 * target firmware being debugged, not the helper algorithm.... and
606 * enabling them could cause such helpers to malfunction (for example,
607 * by overwriting data with a breakpoint instruction. On the other
608 * hand the infrastructure for running such helpers might use this
609 * procedure but rely on hardware breakpoint to detect termination.)
611 int target_resume(struct target *target, int current, target_addr_t address,
612 int handle_breakpoints, int debug_execution)
614 int retval;
616 /* We can't poll until after examine */
617 if (!target_was_examined(target)) {
618 LOG_ERROR("Target not examined yet");
619 return ERROR_FAIL;
622 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
624 /* note that resume *must* be asynchronous. The CPU can halt before
625 * we poll. The CPU can even halt at the current PC as a result of
626 * a software breakpoint being inserted by (a bug?) the application.
628 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
629 if (retval != ERROR_OK)
630 return retval;
632 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
634 return retval;
637 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
639 char buf[100];
640 int retval;
641 Jim_Nvp *n;
642 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
643 if (n->name == NULL) {
644 LOG_ERROR("invalid reset mode");
645 return ERROR_FAIL;
648 struct target *target;
649 for (target = all_targets; target; target = target->next)
650 target_call_reset_callbacks(target, reset_mode);
652 /* disable polling during reset to make reset event scripts
653 * more predictable, i.e. dr/irscan & pathmove in events will
654 * not have JTAG operations injected into the middle of a sequence.
656 bool save_poll = jtag_poll_get_enabled();
658 jtag_poll_set_enabled(false);
660 sprintf(buf, "ocd_process_reset %s", n->name);
661 retval = Jim_Eval(cmd_ctx->interp, buf);
663 jtag_poll_set_enabled(save_poll);
665 if (retval != JIM_OK) {
666 Jim_MakeErrorMessage(cmd_ctx->interp);
667 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
668 return ERROR_FAIL;
671 /* We want any events to be processed before the prompt */
672 retval = target_call_timer_callbacks_now();
674 for (target = all_targets; target; target = target->next) {
675 target->type->check_reset(target);
676 target->running_alg = false;
679 return retval;
682 static int identity_virt2phys(struct target *target,
683 target_addr_t virtual, target_addr_t *physical)
685 *physical = virtual;
686 return ERROR_OK;
689 static int no_mmu(struct target *target, int *enabled)
691 *enabled = 0;
692 return ERROR_OK;
695 static int default_examine(struct target *target)
697 target_set_examined(target);
698 return ERROR_OK;
701 /* no check by default */
702 static int default_check_reset(struct target *target)
704 return ERROR_OK;
707 int target_examine_one(struct target *target)
709 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
711 int retval = target->type->examine(target);
712 if (retval != ERROR_OK)
713 return retval;
715 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
717 return ERROR_OK;
720 static int jtag_enable_callback(enum jtag_event event, void *priv)
722 struct target *target = priv;
724 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
725 return ERROR_OK;
727 jtag_unregister_event_callback(jtag_enable_callback, target);
729 return target_examine_one(target);
732 /* Targets that correctly implement init + examine, i.e.
733 * no communication with target during init:
735 * XScale
737 int target_examine(void)
739 int retval = ERROR_OK;
740 struct target *target;
742 for (target = all_targets; target; target = target->next) {
743 /* defer examination, but don't skip it */
744 if (!target->tap->enabled) {
745 jtag_register_event_callback(jtag_enable_callback,
746 target);
747 continue;
750 if (target->defer_examine)
751 continue;
753 retval = target_examine_one(target);
754 if (retval != ERROR_OK)
755 return retval;
757 return retval;
760 const char *target_type_name(struct target *target)
762 return target->type->name;
765 static int target_soft_reset_halt(struct target *target)
767 if (!target_was_examined(target)) {
768 LOG_ERROR("Target not examined yet");
769 return ERROR_FAIL;
771 if (!target->type->soft_reset_halt) {
772 LOG_ERROR("Target %s does not support soft_reset_halt",
773 target_name(target));
774 return ERROR_FAIL;
776 return target->type->soft_reset_halt(target);
780 * Downloads a target-specific native code algorithm to the target,
781 * and executes it. * Note that some targets may need to set up, enable,
782 * and tear down a breakpoint (hard or * soft) to detect algorithm
783 * termination, while others may support lower overhead schemes where
784 * soft breakpoints embedded in the algorithm automatically terminate the
785 * algorithm.
787 * @param target used to run the algorithm
788 * @param arch_info target-specific description of the algorithm.
790 int target_run_algorithm(struct target *target,
791 int num_mem_params, struct mem_param *mem_params,
792 int num_reg_params, struct reg_param *reg_param,
793 uint32_t entry_point, uint32_t exit_point,
794 int timeout_ms, void *arch_info)
796 int retval = ERROR_FAIL;
798 if (!target_was_examined(target)) {
799 LOG_ERROR("Target not examined yet");
800 goto done;
802 if (!target->type->run_algorithm) {
803 LOG_ERROR("Target type '%s' does not support %s",
804 target_type_name(target), __func__);
805 goto done;
808 target->running_alg = true;
809 retval = target->type->run_algorithm(target,
810 num_mem_params, mem_params,
811 num_reg_params, reg_param,
812 entry_point, exit_point, timeout_ms, arch_info);
813 target->running_alg = false;
815 done:
816 return retval;
820 * Executes a target-specific native code algorithm and leaves it running.
822 * @param target used to run the algorithm
823 * @param arch_info target-specific description of the algorithm.
825 int target_start_algorithm(struct target *target,
826 int num_mem_params, struct mem_param *mem_params,
827 int num_reg_params, struct reg_param *reg_params,
828 uint32_t entry_point, uint32_t exit_point,
829 void *arch_info)
831 int retval = ERROR_FAIL;
833 if (!target_was_examined(target)) {
834 LOG_ERROR("Target not examined yet");
835 goto done;
837 if (!target->type->start_algorithm) {
838 LOG_ERROR("Target type '%s' does not support %s",
839 target_type_name(target), __func__);
840 goto done;
842 if (target->running_alg) {
843 LOG_ERROR("Target is already running an algorithm");
844 goto done;
847 target->running_alg = true;
848 retval = target->type->start_algorithm(target,
849 num_mem_params, mem_params,
850 num_reg_params, reg_params,
851 entry_point, exit_point, arch_info);
853 done:
854 return retval;
858 * Waits for an algorithm started with target_start_algorithm() to complete.
860 * @param target used to run the algorithm
861 * @param arch_info target-specific description of the algorithm.
863 int target_wait_algorithm(struct target *target,
864 int num_mem_params, struct mem_param *mem_params,
865 int num_reg_params, struct reg_param *reg_params,
866 uint32_t exit_point, int timeout_ms,
867 void *arch_info)
869 int retval = ERROR_FAIL;
871 if (!target->type->wait_algorithm) {
872 LOG_ERROR("Target type '%s' does not support %s",
873 target_type_name(target), __func__);
874 goto done;
876 if (!target->running_alg) {
877 LOG_ERROR("Target is not running an algorithm");
878 goto done;
881 retval = target->type->wait_algorithm(target,
882 num_mem_params, mem_params,
883 num_reg_params, reg_params,
884 exit_point, timeout_ms, arch_info);
885 if (retval != ERROR_TARGET_TIMEOUT)
886 target->running_alg = false;
888 done:
889 return retval;
893 * Streams data to a circular buffer on target intended for consumption by code
894 * running asynchronously on target.
896 * This is intended for applications where target-specific native code runs
897 * on the target, receives data from the circular buffer, does something with
898 * it (most likely writing it to a flash memory), and advances the circular
899 * buffer pointer.
901 * This assumes that the helper algorithm has already been loaded to the target,
902 * but has not been started yet. Given memory and register parameters are passed
903 * to the algorithm.
905 * The buffer is defined by (buffer_start, buffer_size) arguments and has the
906 * following format:
908 * [buffer_start + 0, buffer_start + 4):
909 * Write Pointer address (aka head). Written and updated by this
910 * routine when new data is written to the circular buffer.
911 * [buffer_start + 4, buffer_start + 8):
912 * Read Pointer address (aka tail). Updated by code running on the
913 * target after it consumes data.
914 * [buffer_start + 8, buffer_start + buffer_size):
915 * Circular buffer contents.
917 * See contrib/loaders/flash/stm32f1x.S for an example.
919 * @param target used to run the algorithm
920 * @param buffer address on the host where data to be sent is located
921 * @param count number of blocks to send
922 * @param block_size size in bytes of each block
923 * @param num_mem_params count of memory-based params to pass to algorithm
924 * @param mem_params memory-based params to pass to algorithm
925 * @param num_reg_params count of register-based params to pass to algorithm
926 * @param reg_params memory-based params to pass to algorithm
927 * @param buffer_start address on the target of the circular buffer structure
928 * @param buffer_size size of the circular buffer structure
929 * @param entry_point address on the target to execute to start the algorithm
930 * @param exit_point address at which to set a breakpoint to catch the
931 * end of the algorithm; can be 0 if target triggers a breakpoint itself
934 int target_run_flash_async_algorithm(struct target *target,
935 const uint8_t *buffer, uint32_t count, int block_size,
936 int num_mem_params, struct mem_param *mem_params,
937 int num_reg_params, struct reg_param *reg_params,
938 uint32_t buffer_start, uint32_t buffer_size,
939 uint32_t entry_point, uint32_t exit_point, void *arch_info)
941 int retval;
942 int timeout = 0;
944 const uint8_t *buffer_orig = buffer;
946 /* Set up working area. First word is write pointer, second word is read pointer,
947 * rest is fifo data area. */
948 uint32_t wp_addr = buffer_start;
949 uint32_t rp_addr = buffer_start + 4;
950 uint32_t fifo_start_addr = buffer_start + 8;
951 uint32_t fifo_end_addr = buffer_start + buffer_size;
953 uint32_t wp = fifo_start_addr;
954 uint32_t rp = fifo_start_addr;
956 /* validate block_size is 2^n */
957 assert(!block_size || !(block_size & (block_size - 1)));
959 retval = target_write_u32(target, wp_addr, wp);
960 if (retval != ERROR_OK)
961 return retval;
962 retval = target_write_u32(target, rp_addr, rp);
963 if (retval != ERROR_OK)
964 return retval;
966 /* Start up algorithm on target and let it idle while writing the first chunk */
967 retval = target_start_algorithm(target, num_mem_params, mem_params,
968 num_reg_params, reg_params,
969 entry_point,
970 exit_point,
971 arch_info);
973 if (retval != ERROR_OK) {
974 LOG_ERROR("error starting target flash write algorithm");
975 return retval;
978 while (count > 0) {
980 retval = target_read_u32(target, rp_addr, &rp);
981 if (retval != ERROR_OK) {
982 LOG_ERROR("failed to get read pointer");
983 break;
986 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
987 (size_t) (buffer - buffer_orig), count, wp, rp);
989 if (rp == 0) {
990 LOG_ERROR("flash write algorithm aborted by target");
991 retval = ERROR_FLASH_OPERATION_FAILED;
992 break;
995 if (((rp - fifo_start_addr) & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
996 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
997 break;
1000 /* Count the number of bytes available in the fifo without
1001 * crossing the wrap around. Make sure to not fill it completely,
1002 * because that would make wp == rp and that's the empty condition. */
1003 uint32_t thisrun_bytes;
1004 if (rp > wp)
1005 thisrun_bytes = rp - wp - block_size;
1006 else if (rp > fifo_start_addr)
1007 thisrun_bytes = fifo_end_addr - wp;
1008 else
1009 thisrun_bytes = fifo_end_addr - wp - block_size;
1011 if (thisrun_bytes == 0) {
1012 /* Throttle polling a bit if transfer is (much) faster than flash
1013 * programming. The exact delay shouldn't matter as long as it's
1014 * less than buffer size / flash speed. This is very unlikely to
1015 * run when using high latency connections such as USB. */
1016 alive_sleep(10);
1018 /* to stop an infinite loop on some targets check and increment a timeout
1019 * this issue was observed on a stellaris using the new ICDI interface */
1020 if (timeout++ >= 500) {
1021 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1022 return ERROR_FLASH_OPERATION_FAILED;
1024 continue;
1027 /* reset our timeout */
1028 timeout = 0;
1030 /* Limit to the amount of data we actually want to write */
1031 if (thisrun_bytes > count * block_size)
1032 thisrun_bytes = count * block_size;
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_read_memory(struct target *target,
1084 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1086 if (!target_was_examined(target)) {
1087 LOG_ERROR("Target not examined yet");
1088 return ERROR_FAIL;
1090 if (!target->type->read_memory) {
1091 LOG_ERROR("Target %s doesn't support read_memory", target_name(target));
1092 return ERROR_FAIL;
1094 return target->type->read_memory(target, address, size, count, buffer);
1097 int target_read_phys_memory(struct target *target,
1098 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1100 if (!target_was_examined(target)) {
1101 LOG_ERROR("Target not examined yet");
1102 return ERROR_FAIL;
1104 if (!target->type->read_phys_memory) {
1105 LOG_ERROR("Target %s doesn't support read_phys_memory", target_name(target));
1106 return ERROR_FAIL;
1108 return target->type->read_phys_memory(target, address, size, count, buffer);
1111 int target_write_memory(struct target *target,
1112 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1114 if (!target_was_examined(target)) {
1115 LOG_ERROR("Target not examined yet");
1116 return ERROR_FAIL;
1118 if (!target->type->write_memory) {
1119 LOG_ERROR("Target %s doesn't support write_memory", target_name(target));
1120 return ERROR_FAIL;
1122 return target->type->write_memory(target, address, size, count, buffer);
1125 int target_write_phys_memory(struct target *target,
1126 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1128 if (!target_was_examined(target)) {
1129 LOG_ERROR("Target not examined yet");
1130 return ERROR_FAIL;
1132 if (!target->type->write_phys_memory) {
1133 LOG_ERROR("Target %s doesn't support write_phys_memory", target_name(target));
1134 return ERROR_FAIL;
1136 return target->type->write_phys_memory(target, address, size, count, buffer);
1139 int target_add_breakpoint(struct target *target,
1140 struct breakpoint *breakpoint)
1142 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1143 LOG_WARNING("target %s is not halted (add breakpoint)", target_name(target));
1144 return ERROR_TARGET_NOT_HALTED;
1146 return target->type->add_breakpoint(target, breakpoint);
1149 int target_add_context_breakpoint(struct target *target,
1150 struct breakpoint *breakpoint)
1152 if (target->state != TARGET_HALTED) {
1153 LOG_WARNING("target %s is not halted (add context breakpoint)", target_name(target));
1154 return ERROR_TARGET_NOT_HALTED;
1156 return target->type->add_context_breakpoint(target, breakpoint);
1159 int target_add_hybrid_breakpoint(struct target *target,
1160 struct breakpoint *breakpoint)
1162 if (target->state != TARGET_HALTED) {
1163 LOG_WARNING("target %s is not halted (add hybrid breakpoint)", target_name(target));
1164 return ERROR_TARGET_NOT_HALTED;
1166 return target->type->add_hybrid_breakpoint(target, breakpoint);
1169 int target_remove_breakpoint(struct target *target,
1170 struct breakpoint *breakpoint)
1172 return target->type->remove_breakpoint(target, breakpoint);
1175 int target_add_watchpoint(struct target *target,
1176 struct watchpoint *watchpoint)
1178 if (target->state != TARGET_HALTED) {
1179 LOG_WARNING("target %s is not halted (add watchpoint)", target_name(target));
1180 return ERROR_TARGET_NOT_HALTED;
1182 return target->type->add_watchpoint(target, watchpoint);
1184 int target_remove_watchpoint(struct target *target,
1185 struct watchpoint *watchpoint)
1187 return target->type->remove_watchpoint(target, watchpoint);
1189 int target_hit_watchpoint(struct target *target,
1190 struct watchpoint **hit_watchpoint)
1192 if (target->state != TARGET_HALTED) {
1193 LOG_WARNING("target %s is not halted (hit watchpoint)", target->cmd_name);
1194 return ERROR_TARGET_NOT_HALTED;
1197 if (target->type->hit_watchpoint == NULL) {
1198 /* For backward compatible, if hit_watchpoint is not implemented,
1199 * return ERROR_FAIL such that gdb_server will not take the nonsense
1200 * information. */
1201 return ERROR_FAIL;
1204 return target->type->hit_watchpoint(target, hit_watchpoint);
1207 const char *target_get_gdb_arch(struct target *target)
1209 if (target->type->get_gdb_arch == NULL)
1210 return NULL;
1211 return target->type->get_gdb_arch(target);
1214 int target_get_gdb_reg_list(struct target *target,
1215 struct reg **reg_list[], int *reg_list_size,
1216 enum target_register_class reg_class)
1218 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1221 bool target_supports_gdb_connection(struct target *target)
1224 * based on current code, we can simply exclude all the targets that
1225 * don't provide get_gdb_reg_list; this could change with new targets.
1227 return !!target->type->get_gdb_reg_list;
1230 int target_step(struct target *target,
1231 int current, target_addr_t address, int handle_breakpoints)
1233 return target->type->step(target, current, address, handle_breakpoints);
1236 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1238 if (target->state != TARGET_HALTED) {
1239 LOG_WARNING("target %s is not halted (gdb fileio)", target->cmd_name);
1240 return ERROR_TARGET_NOT_HALTED;
1242 return target->type->get_gdb_fileio_info(target, fileio_info);
1245 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1247 if (target->state != TARGET_HALTED) {
1248 LOG_WARNING("target %s is not halted (gdb fileio end)", target->cmd_name);
1249 return ERROR_TARGET_NOT_HALTED;
1251 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1254 int target_profiling(struct target *target, uint32_t *samples,
1255 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1257 if (target->state != TARGET_HALTED) {
1258 LOG_WARNING("target %s is not halted (profiling)", target->cmd_name);
1259 return ERROR_TARGET_NOT_HALTED;
1261 return target->type->profiling(target, samples, max_num_samples,
1262 num_samples, seconds);
1266 * Reset the @c examined flag for the given target.
1267 * Pure paranoia -- targets are zeroed on allocation.
1269 static void target_reset_examined(struct target *target)
1271 target->examined = false;
1274 static int handle_target(void *priv);
1276 static int target_init_one(struct command_context *cmd_ctx,
1277 struct target *target)
1279 target_reset_examined(target);
1281 struct target_type *type = target->type;
1282 if (type->examine == NULL)
1283 type->examine = default_examine;
1285 if (type->check_reset == NULL)
1286 type->check_reset = default_check_reset;
1288 assert(type->init_target != NULL);
1290 int retval = type->init_target(cmd_ctx, target);
1291 if (ERROR_OK != retval) {
1292 LOG_ERROR("target '%s' init failed", target_name(target));
1293 return retval;
1296 /* Sanity-check MMU support ... stub in what we must, to help
1297 * implement it in stages, but warn if we need to do so.
1299 if (type->mmu) {
1300 if (type->virt2phys == NULL) {
1301 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1302 type->virt2phys = identity_virt2phys;
1304 } else {
1305 /* Make sure no-MMU targets all behave the same: make no
1306 * distinction between physical and virtual addresses, and
1307 * ensure that virt2phys() is always an identity mapping.
1309 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1310 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1312 type->mmu = no_mmu;
1313 type->write_phys_memory = type->write_memory;
1314 type->read_phys_memory = type->read_memory;
1315 type->virt2phys = identity_virt2phys;
1318 if (target->type->read_buffer == NULL)
1319 target->type->read_buffer = target_read_buffer_default;
1321 if (target->type->write_buffer == NULL)
1322 target->type->write_buffer = target_write_buffer_default;
1324 if (target->type->get_gdb_fileio_info == NULL)
1325 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1327 if (target->type->gdb_fileio_end == NULL)
1328 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1330 if (target->type->profiling == NULL)
1331 target->type->profiling = target_profiling_default;
1333 return ERROR_OK;
1336 static int target_init(struct command_context *cmd_ctx)
1338 struct target *target;
1339 int retval;
1341 for (target = all_targets; target; target = target->next) {
1342 retval = target_init_one(cmd_ctx, target);
1343 if (ERROR_OK != retval)
1344 return retval;
1347 if (!all_targets)
1348 return ERROR_OK;
1350 retval = target_register_user_commands(cmd_ctx);
1351 if (ERROR_OK != retval)
1352 return retval;
1354 retval = target_register_timer_callback(&handle_target,
1355 polling_interval, 1, cmd_ctx->interp);
1356 if (ERROR_OK != retval)
1357 return retval;
1359 return ERROR_OK;
1362 COMMAND_HANDLER(handle_target_init_command)
1364 int retval;
1366 if (CMD_ARGC != 0)
1367 return ERROR_COMMAND_SYNTAX_ERROR;
1369 static bool target_initialized;
1370 if (target_initialized) {
1371 LOG_INFO("'target init' has already been called");
1372 return ERROR_OK;
1374 target_initialized = true;
1376 retval = command_run_line(CMD_CTX, "init_targets");
1377 if (ERROR_OK != retval)
1378 return retval;
1380 retval = command_run_line(CMD_CTX, "init_target_events");
1381 if (ERROR_OK != retval)
1382 return retval;
1384 retval = command_run_line(CMD_CTX, "init_board");
1385 if (ERROR_OK != retval)
1386 return retval;
1388 LOG_DEBUG("Initializing targets...");
1389 return target_init(CMD_CTX);
1392 int target_register_event_callback(int (*callback)(struct target *target,
1393 enum target_event event, void *priv), void *priv)
1395 struct target_event_callback **callbacks_p = &target_event_callbacks;
1397 if (callback == NULL)
1398 return ERROR_COMMAND_SYNTAX_ERROR;
1400 if (*callbacks_p) {
1401 while ((*callbacks_p)->next)
1402 callbacks_p = &((*callbacks_p)->next);
1403 callbacks_p = &((*callbacks_p)->next);
1406 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1407 (*callbacks_p)->callback = callback;
1408 (*callbacks_p)->priv = priv;
1409 (*callbacks_p)->next = NULL;
1411 return ERROR_OK;
1414 int target_register_reset_callback(int (*callback)(struct target *target,
1415 enum target_reset_mode reset_mode, void *priv), void *priv)
1417 struct target_reset_callback *entry;
1419 if (callback == NULL)
1420 return ERROR_COMMAND_SYNTAX_ERROR;
1422 entry = malloc(sizeof(struct target_reset_callback));
1423 if (entry == NULL) {
1424 LOG_ERROR("error allocating buffer for reset callback entry");
1425 return ERROR_COMMAND_SYNTAX_ERROR;
1428 entry->callback = callback;
1429 entry->priv = priv;
1430 list_add(&entry->list, &target_reset_callback_list);
1433 return ERROR_OK;
1436 int target_register_trace_callback(int (*callback)(struct target *target,
1437 size_t len, uint8_t *data, void *priv), void *priv)
1439 struct target_trace_callback *entry;
1441 if (callback == NULL)
1442 return ERROR_COMMAND_SYNTAX_ERROR;
1444 entry = malloc(sizeof(struct target_trace_callback));
1445 if (entry == NULL) {
1446 LOG_ERROR("error allocating buffer for trace callback entry");
1447 return ERROR_COMMAND_SYNTAX_ERROR;
1450 entry->callback = callback;
1451 entry->priv = priv;
1452 list_add(&entry->list, &target_trace_callback_list);
1455 return ERROR_OK;
1458 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1460 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1462 if (callback == NULL)
1463 return ERROR_COMMAND_SYNTAX_ERROR;
1465 if (*callbacks_p) {
1466 while ((*callbacks_p)->next)
1467 callbacks_p = &((*callbacks_p)->next);
1468 callbacks_p = &((*callbacks_p)->next);
1471 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1472 (*callbacks_p)->callback = callback;
1473 (*callbacks_p)->periodic = periodic;
1474 (*callbacks_p)->time_ms = time_ms;
1475 (*callbacks_p)->removed = false;
1477 gettimeofday(&(*callbacks_p)->when, NULL);
1478 timeval_add_time(&(*callbacks_p)->when, 0, time_ms * 1000);
1480 (*callbacks_p)->priv = priv;
1481 (*callbacks_p)->next = NULL;
1483 return ERROR_OK;
1486 int target_unregister_event_callback(int (*callback)(struct target *target,
1487 enum target_event event, void *priv), void *priv)
1489 struct target_event_callback **p = &target_event_callbacks;
1490 struct target_event_callback *c = target_event_callbacks;
1492 if (callback == NULL)
1493 return ERROR_COMMAND_SYNTAX_ERROR;
1495 while (c) {
1496 struct target_event_callback *next = c->next;
1497 if ((c->callback == callback) && (c->priv == priv)) {
1498 *p = next;
1499 free(c);
1500 return ERROR_OK;
1501 } else
1502 p = &(c->next);
1503 c = next;
1506 return ERROR_OK;
1509 int target_unregister_reset_callback(int (*callback)(struct target *target,
1510 enum target_reset_mode reset_mode, void *priv), void *priv)
1512 struct target_reset_callback *entry;
1514 if (callback == NULL)
1515 return ERROR_COMMAND_SYNTAX_ERROR;
1517 list_for_each_entry(entry, &target_reset_callback_list, list) {
1518 if (entry->callback == callback && entry->priv == priv) {
1519 list_del(&entry->list);
1520 free(entry);
1521 break;
1525 return ERROR_OK;
1528 int target_unregister_trace_callback(int (*callback)(struct target *target,
1529 size_t len, uint8_t *data, void *priv), void *priv)
1531 struct target_trace_callback *entry;
1533 if (callback == NULL)
1534 return ERROR_COMMAND_SYNTAX_ERROR;
1536 list_for_each_entry(entry, &target_trace_callback_list, list) {
1537 if (entry->callback == callback && entry->priv == priv) {
1538 list_del(&entry->list);
1539 free(entry);
1540 break;
1544 return ERROR_OK;
1547 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1549 if (callback == NULL)
1550 return ERROR_COMMAND_SYNTAX_ERROR;
1552 for (struct target_timer_callback *c = target_timer_callbacks;
1553 c; c = c->next) {
1554 if ((c->callback == callback) && (c->priv == priv)) {
1555 c->removed = true;
1556 return ERROR_OK;
1560 return ERROR_FAIL;
1563 int target_call_event_callbacks(struct target *target, enum target_event event)
1565 struct target_event_callback *callback = target_event_callbacks;
1566 struct target_event_callback *next_callback;
1568 if (event == TARGET_EVENT_HALTED) {
1569 /* execute early halted first */
1570 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1573 LOG_DEBUG("target event %i (%s)", event,
1574 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1576 target_handle_event(target, event);
1578 while (callback) {
1579 next_callback = callback->next;
1580 callback->callback(target, event, callback->priv);
1581 callback = next_callback;
1584 return ERROR_OK;
1587 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1589 struct target_reset_callback *callback;
1591 LOG_DEBUG("target reset %i (%s)", reset_mode,
1592 Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name);
1594 list_for_each_entry(callback, &target_reset_callback_list, list)
1595 callback->callback(target, reset_mode, callback->priv);
1597 return ERROR_OK;
1600 int target_call_trace_callbacks(struct target *target, size_t len, uint8_t *data)
1602 struct target_trace_callback *callback;
1604 list_for_each_entry(callback, &target_trace_callback_list, list)
1605 callback->callback(target, len, data, callback->priv);
1607 return ERROR_OK;
1610 static int target_timer_callback_periodic_restart(
1611 struct target_timer_callback *cb, struct timeval *now)
1613 cb->when = *now;
1614 timeval_add_time(&cb->when, 0, cb->time_ms * 1000L);
1615 return ERROR_OK;
1618 static int target_call_timer_callback(struct target_timer_callback *cb,
1619 struct timeval *now)
1621 cb->callback(cb->priv);
1623 if (cb->periodic)
1624 return target_timer_callback_periodic_restart(cb, now);
1626 return target_unregister_timer_callback(cb->callback, cb->priv);
1629 static int target_call_timer_callbacks_check_time(int checktime)
1631 static bool callback_processing;
1633 /* Do not allow nesting */
1634 if (callback_processing)
1635 return ERROR_OK;
1637 callback_processing = true;
1639 keep_alive();
1641 struct timeval now;
1642 gettimeofday(&now, NULL);
1644 /* Store an address of the place containing a pointer to the
1645 * next item; initially, that's a standalone "root of the
1646 * list" variable. */
1647 struct target_timer_callback **callback = &target_timer_callbacks;
1648 while (*callback) {
1649 if ((*callback)->removed) {
1650 struct target_timer_callback *p = *callback;
1651 *callback = (*callback)->next;
1652 free(p);
1653 continue;
1656 bool call_it = (*callback)->callback &&
1657 ((!checktime && (*callback)->periodic) ||
1658 timeval_compare(&now, &(*callback)->when) >= 0);
1660 if (call_it)
1661 target_call_timer_callback(*callback, &now);
1663 callback = &(*callback)->next;
1666 callback_processing = false;
1667 return ERROR_OK;
1670 int target_call_timer_callbacks(void)
1672 return target_call_timer_callbacks_check_time(1);
1675 /* invoke periodic callbacks immediately */
1676 int target_call_timer_callbacks_now(void)
1678 return target_call_timer_callbacks_check_time(0);
1681 /* Prints the working area layout for debug purposes */
1682 static void print_wa_layout(struct target *target)
1684 struct working_area *c = target->working_areas;
1686 while (c) {
1687 LOG_DEBUG("%c%c " TARGET_ADDR_FMT "-" TARGET_ADDR_FMT " (%" PRIu32 " bytes)",
1688 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1689 c->address, c->address + c->size - 1, c->size);
1690 c = c->next;
1694 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1695 static void target_split_working_area(struct working_area *area, uint32_t size)
1697 assert(area->free); /* Shouldn't split an allocated area */
1698 assert(size <= area->size); /* Caller should guarantee this */
1700 /* Split only if not already the right size */
1701 if (size < area->size) {
1702 struct working_area *new_wa = malloc(sizeof(*new_wa));
1704 if (new_wa == NULL)
1705 return;
1707 new_wa->next = area->next;
1708 new_wa->size = area->size - size;
1709 new_wa->address = area->address + size;
1710 new_wa->backup = NULL;
1711 new_wa->user = NULL;
1712 new_wa->free = true;
1714 area->next = new_wa;
1715 area->size = size;
1717 /* If backup memory was allocated to this area, it has the wrong size
1718 * now so free it and it will be reallocated if/when needed */
1719 if (area->backup) {
1720 free(area->backup);
1721 area->backup = NULL;
1726 /* Merge all adjacent free areas into one */
1727 static void target_merge_working_areas(struct target *target)
1729 struct working_area *c = target->working_areas;
1731 while (c && c->next) {
1732 assert(c->next->address == c->address + c->size); /* This is an invariant */
1734 /* Find two adjacent free areas */
1735 if (c->free && c->next->free) {
1736 /* Merge the last into the first */
1737 c->size += c->next->size;
1739 /* Remove the last */
1740 struct working_area *to_be_freed = c->next;
1741 c->next = c->next->next;
1742 if (to_be_freed->backup)
1743 free(to_be_freed->backup);
1744 free(to_be_freed);
1746 /* If backup memory was allocated to the remaining area, it's has
1747 * the wrong size now */
1748 if (c->backup) {
1749 free(c->backup);
1750 c->backup = NULL;
1752 } else {
1753 c = c->next;
1758 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1760 /* Reevaluate working area address based on MMU state*/
1761 if (target->working_areas == NULL) {
1762 int retval;
1763 int enabled;
1765 retval = target->type->mmu(target, &enabled);
1766 if (retval != ERROR_OK)
1767 return retval;
1769 if (!enabled) {
1770 if (target->working_area_phys_spec) {
1771 LOG_DEBUG("MMU disabled, using physical "
1772 "address for working memory " TARGET_ADDR_FMT,
1773 target->working_area_phys);
1774 target->working_area = target->working_area_phys;
1775 } else {
1776 LOG_ERROR("No working memory available. "
1777 "Specify -work-area-phys to target.");
1778 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1780 } else {
1781 if (target->working_area_virt_spec) {
1782 LOG_DEBUG("MMU enabled, using virtual "
1783 "address for working memory " TARGET_ADDR_FMT,
1784 target->working_area_virt);
1785 target->working_area = target->working_area_virt;
1786 } else {
1787 LOG_ERROR("No working memory available. "
1788 "Specify -work-area-virt to target.");
1789 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1793 /* Set up initial working area on first call */
1794 struct working_area *new_wa = malloc(sizeof(*new_wa));
1795 if (new_wa) {
1796 new_wa->next = NULL;
1797 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1798 new_wa->address = target->working_area;
1799 new_wa->backup = NULL;
1800 new_wa->user = NULL;
1801 new_wa->free = true;
1804 target->working_areas = new_wa;
1807 /* only allocate multiples of 4 byte */
1808 if (size % 4)
1809 size = (size + 3) & (~3UL);
1811 struct working_area *c = target->working_areas;
1813 /* Find the first large enough working area */
1814 while (c) {
1815 if (c->free && c->size >= size)
1816 break;
1817 c = c->next;
1820 if (c == NULL)
1821 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1823 /* Split the working area into the requested size */
1824 target_split_working_area(c, size);
1826 LOG_DEBUG("allocated new working area of %" PRIu32 " bytes at address " TARGET_ADDR_FMT,
1827 size, c->address);
1829 if (target->backup_working_area) {
1830 if (c->backup == NULL) {
1831 c->backup = malloc(c->size);
1832 if (c->backup == NULL)
1833 return ERROR_FAIL;
1836 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1837 if (retval != ERROR_OK)
1838 return retval;
1841 /* mark as used, and return the new (reused) area */
1842 c->free = false;
1843 *area = c;
1845 /* user pointer */
1846 c->user = area;
1848 print_wa_layout(target);
1850 return ERROR_OK;
1853 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1855 int retval;
1857 retval = target_alloc_working_area_try(target, size, area);
1858 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1859 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1860 return retval;
1864 static int target_restore_working_area(struct target *target, struct working_area *area)
1866 int retval = ERROR_OK;
1868 if (target->backup_working_area && area->backup != NULL) {
1869 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1870 if (retval != ERROR_OK)
1871 LOG_ERROR("failed to restore %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
1872 area->size, area->address);
1875 return retval;
1878 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1879 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1881 int retval = ERROR_OK;
1883 if (area->free)
1884 return retval;
1886 if (restore) {
1887 retval = target_restore_working_area(target, area);
1888 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1889 if (retval != ERROR_OK)
1890 return retval;
1893 area->free = true;
1895 LOG_DEBUG("freed %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
1896 area->size, area->address);
1898 /* mark user pointer invalid */
1899 /* TODO: Is this really safe? It points to some previous caller's memory.
1900 * How could we know that the area pointer is still in that place and not
1901 * some other vital data? What's the purpose of this, anyway? */
1902 *area->user = NULL;
1903 area->user = NULL;
1905 target_merge_working_areas(target);
1907 print_wa_layout(target);
1909 return retval;
1912 int target_free_working_area(struct target *target, struct working_area *area)
1914 return target_free_working_area_restore(target, area, 1);
1917 static void target_destroy(struct target *target)
1919 if (target->type->deinit_target)
1920 target->type->deinit_target(target);
1922 if (target->semihosting)
1923 free(target->semihosting);
1925 jtag_unregister_event_callback(jtag_enable_callback, target);
1927 struct target_event_action *teap = target->event_action;
1928 while (teap) {
1929 struct target_event_action *next = teap->next;
1930 Jim_DecrRefCount(teap->interp, teap->body);
1931 free(teap);
1932 teap = next;
1935 target_free_all_working_areas(target);
1936 /* Now we have none or only one working area marked as free */
1937 if (target->working_areas) {
1938 free(target->working_areas->backup);
1939 free(target->working_areas);
1942 /* release the targets SMP list */
1943 if (target->smp) {
1944 struct target_list *head = target->head;
1945 while (head != NULL) {
1946 struct target_list *pos = head->next;
1947 head->target->smp = 0;
1948 free(head);
1949 head = pos;
1951 target->smp = 0;
1954 free(target->gdb_port_override);
1955 free(target->type);
1956 free(target->trace_info);
1957 free(target->fileio_info);
1958 free(target->cmd_name);
1959 free(target);
1962 void target_quit(void)
1964 struct target_event_callback *pe = target_event_callbacks;
1965 while (pe) {
1966 struct target_event_callback *t = pe->next;
1967 free(pe);
1968 pe = t;
1970 target_event_callbacks = NULL;
1972 struct target_timer_callback *pt = target_timer_callbacks;
1973 while (pt) {
1974 struct target_timer_callback *t = pt->next;
1975 free(pt);
1976 pt = t;
1978 target_timer_callbacks = NULL;
1980 for (struct target *target = all_targets; target;) {
1981 struct target *tmp;
1983 tmp = target->next;
1984 target_destroy(target);
1985 target = tmp;
1988 all_targets = NULL;
1991 /* free resources and restore memory, if restoring memory fails,
1992 * free up resources anyway
1994 static void target_free_all_working_areas_restore(struct target *target, int restore)
1996 struct working_area *c = target->working_areas;
1998 LOG_DEBUG("freeing all working areas");
2000 /* Loop through all areas, restoring the allocated ones and marking them as free */
2001 while (c) {
2002 if (!c->free) {
2003 if (restore)
2004 target_restore_working_area(target, c);
2005 c->free = true;
2006 *c->user = NULL; /* Same as above */
2007 c->user = NULL;
2009 c = c->next;
2012 /* Run a merge pass to combine all areas into one */
2013 target_merge_working_areas(target);
2015 print_wa_layout(target);
2018 void target_free_all_working_areas(struct target *target)
2020 target_free_all_working_areas_restore(target, 1);
2023 /* Find the largest number of bytes that can be allocated */
2024 uint32_t target_get_working_area_avail(struct target *target)
2026 struct working_area *c = target->working_areas;
2027 uint32_t max_size = 0;
2029 if (c == NULL)
2030 return target->working_area_size;
2032 while (c) {
2033 if (c->free && max_size < c->size)
2034 max_size = c->size;
2036 c = c->next;
2039 return max_size;
2042 int target_arch_state(struct target *target)
2044 int retval;
2045 if (target == NULL) {
2046 LOG_WARNING("No target has been configured");
2047 return ERROR_OK;
2050 if (target->state != TARGET_HALTED)
2051 return ERROR_OK;
2053 retval = target->type->arch_state(target);
2054 return retval;
2057 static int target_get_gdb_fileio_info_default(struct target *target,
2058 struct gdb_fileio_info *fileio_info)
2060 /* If target does not support semi-hosting function, target
2061 has no need to provide .get_gdb_fileio_info callback.
2062 It just return ERROR_FAIL and gdb_server will return "Txx"
2063 as target halted every time. */
2064 return ERROR_FAIL;
2067 static int target_gdb_fileio_end_default(struct target *target,
2068 int retcode, int fileio_errno, bool ctrl_c)
2070 return ERROR_OK;
2073 static int target_profiling_default(struct target *target, uint32_t *samples,
2074 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
2076 struct timeval timeout, now;
2078 gettimeofday(&timeout, NULL);
2079 timeval_add_time(&timeout, seconds, 0);
2081 LOG_INFO("Starting profiling. Halting and resuming the"
2082 " target as often as we can...");
2084 uint32_t sample_count = 0;
2085 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2086 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
2088 int retval = ERROR_OK;
2089 for (;;) {
2090 target_poll(target);
2091 if (target->state == TARGET_HALTED) {
2092 uint32_t t = buf_get_u32(reg->value, 0, 32);
2093 samples[sample_count++] = t;
2094 /* current pc, addr = 0, do not handle breakpoints, not debugging */
2095 retval = target_resume(target, 1, 0, 0, 0);
2096 target_poll(target);
2097 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2098 } else if (target->state == TARGET_RUNNING) {
2099 /* We want to quickly sample the PC. */
2100 retval = target_halt(target);
2101 } else {
2102 LOG_INFO("Target not halted or running");
2103 retval = ERROR_OK;
2104 break;
2107 if (retval != ERROR_OK)
2108 break;
2110 gettimeofday(&now, NULL);
2111 if ((sample_count >= max_num_samples) || timeval_compare(&now, &timeout) >= 0) {
2112 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2113 break;
2117 *num_samples = sample_count;
2118 return retval;
2121 /* Single aligned words are guaranteed to use 16 or 32 bit access
2122 * mode respectively, otherwise data is handled as quickly as
2123 * possible
2125 int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
2127 LOG_DEBUG("writing buffer of %" PRIi32 " byte at " TARGET_ADDR_FMT,
2128 size, address);
2130 if (!target_was_examined(target)) {
2131 LOG_ERROR("Target not examined yet");
2132 return ERROR_FAIL;
2135 if (size == 0)
2136 return ERROR_OK;
2138 if ((address + size - 1) < address) {
2139 /* GDB can request this when e.g. PC is 0xfffffffc */
2140 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2141 address,
2142 size);
2143 return ERROR_FAIL;
2146 return target->type->write_buffer(target, address, size, buffer);
2149 static int target_write_buffer_default(struct target *target,
2150 target_addr_t address, uint32_t count, const uint8_t *buffer)
2152 uint32_t size;
2154 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2155 * will have something to do with the size we leave to it. */
2156 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2157 if (address & size) {
2158 int retval = target_write_memory(target, address, size, 1, buffer);
2159 if (retval != ERROR_OK)
2160 return retval;
2161 address += size;
2162 count -= size;
2163 buffer += size;
2167 /* Write the data with as large access size as possible. */
2168 for (; size > 0; size /= 2) {
2169 uint32_t aligned = count - count % size;
2170 if (aligned > 0) {
2171 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2172 if (retval != ERROR_OK)
2173 return retval;
2174 address += aligned;
2175 count -= aligned;
2176 buffer += aligned;
2180 return ERROR_OK;
2183 /* Single aligned words are guaranteed to use 16 or 32 bit access
2184 * mode respectively, otherwise data is handled as quickly as
2185 * possible
2187 int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
2189 LOG_DEBUG("reading buffer of %" PRIi32 " byte at " TARGET_ADDR_FMT,
2190 size, address);
2192 if (!target_was_examined(target)) {
2193 LOG_ERROR("Target not examined yet");
2194 return ERROR_FAIL;
2197 if (size == 0)
2198 return ERROR_OK;
2200 if ((address + size - 1) < address) {
2201 /* GDB can request this when e.g. PC is 0xfffffffc */
2202 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2203 address,
2204 size);
2205 return ERROR_FAIL;
2208 return target->type->read_buffer(target, address, size, buffer);
2211 static int target_read_buffer_default(struct target *target, target_addr_t address, uint32_t count, uint8_t *buffer)
2213 uint32_t size;
2215 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2216 * will have something to do with the size we leave to it. */
2217 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2218 if (address & size) {
2219 int retval = target_read_memory(target, address, size, 1, buffer);
2220 if (retval != ERROR_OK)
2221 return retval;
2222 address += size;
2223 count -= size;
2224 buffer += size;
2228 /* Read the data with as large access size as possible. */
2229 for (; size > 0; size /= 2) {
2230 uint32_t aligned = count - count % size;
2231 if (aligned > 0) {
2232 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2233 if (retval != ERROR_OK)
2234 return retval;
2235 address += aligned;
2236 count -= aligned;
2237 buffer += aligned;
2241 return ERROR_OK;
2244 int target_checksum_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t* crc)
2246 uint8_t *buffer;
2247 int retval;
2248 uint32_t i;
2249 uint32_t checksum = 0;
2250 if (!target_was_examined(target)) {
2251 LOG_ERROR("Target not examined yet");
2252 return ERROR_FAIL;
2255 retval = target->type->checksum_memory(target, address, size, &checksum);
2256 if (retval != ERROR_OK) {
2257 buffer = malloc(size);
2258 if (buffer == NULL) {
2259 LOG_ERROR("error allocating buffer for section (%" PRId32 " bytes)", size);
2260 return ERROR_COMMAND_SYNTAX_ERROR;
2262 retval = target_read_buffer(target, address, size, buffer);
2263 if (retval != ERROR_OK) {
2264 free(buffer);
2265 return retval;
2268 /* convert to target endianness */
2269 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2270 uint32_t target_data;
2271 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2272 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2275 retval = image_calculate_checksum(buffer, size, &checksum);
2276 free(buffer);
2279 *crc = checksum;
2281 return retval;
2284 int target_blank_check_memory(struct target *target,
2285 struct target_memory_check_block *blocks, int num_blocks,
2286 uint8_t erased_value)
2288 if (!target_was_examined(target)) {
2289 LOG_ERROR("Target not examined yet");
2290 return ERROR_FAIL;
2293 if (target->type->blank_check_memory == NULL)
2294 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2296 return target->type->blank_check_memory(target, blocks, num_blocks, erased_value);
2299 int target_read_u64(struct target *target, target_addr_t address, uint64_t *value)
2301 uint8_t value_buf[8];
2302 if (!target_was_examined(target)) {
2303 LOG_ERROR("Target not examined yet");
2304 return ERROR_FAIL;
2307 int retval = target_read_memory(target, address, 8, 1, value_buf);
2309 if (retval == ERROR_OK) {
2310 *value = target_buffer_get_u64(target, value_buf);
2311 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2312 address,
2313 *value);
2314 } else {
2315 *value = 0x0;
2316 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2317 address);
2320 return retval;
2323 int target_read_u32(struct target *target, target_addr_t address, uint32_t *value)
2325 uint8_t value_buf[4];
2326 if (!target_was_examined(target)) {
2327 LOG_ERROR("Target not examined yet");
2328 return ERROR_FAIL;
2331 int retval = target_read_memory(target, address, 4, 1, value_buf);
2333 if (retval == ERROR_OK) {
2334 *value = target_buffer_get_u32(target, value_buf);
2335 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2336 address,
2337 *value);
2338 } else {
2339 *value = 0x0;
2340 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2341 address);
2344 return retval;
2347 int target_read_u16(struct target *target, target_addr_t address, uint16_t *value)
2349 uint8_t value_buf[2];
2350 if (!target_was_examined(target)) {
2351 LOG_ERROR("Target not examined yet");
2352 return ERROR_FAIL;
2355 int retval = target_read_memory(target, address, 2, 1, value_buf);
2357 if (retval == ERROR_OK) {
2358 *value = target_buffer_get_u16(target, value_buf);
2359 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%4.4" PRIx16,
2360 address,
2361 *value);
2362 } else {
2363 *value = 0x0;
2364 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2365 address);
2368 return retval;
2371 int target_read_u8(struct target *target, target_addr_t address, uint8_t *value)
2373 if (!target_was_examined(target)) {
2374 LOG_ERROR("Target not examined yet");
2375 return ERROR_FAIL;
2378 int retval = target_read_memory(target, address, 1, 1, value);
2380 if (retval == ERROR_OK) {
2381 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2382 address,
2383 *value);
2384 } else {
2385 *value = 0x0;
2386 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2387 address);
2390 return retval;
2393 int target_write_u64(struct target *target, target_addr_t address, uint64_t value)
2395 int retval;
2396 uint8_t value_buf[8];
2397 if (!target_was_examined(target)) {
2398 LOG_ERROR("Target not examined yet");
2399 return ERROR_FAIL;
2402 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2403 address,
2404 value);
2406 target_buffer_set_u64(target, value_buf, value);
2407 retval = target_write_memory(target, address, 8, 1, value_buf);
2408 if (retval != ERROR_OK)
2409 LOG_DEBUG("failed: %i", retval);
2411 return retval;
2414 int target_write_u32(struct target *target, target_addr_t address, uint32_t value)
2416 int retval;
2417 uint8_t value_buf[4];
2418 if (!target_was_examined(target)) {
2419 LOG_ERROR("Target not examined yet");
2420 return ERROR_FAIL;
2423 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2424 address,
2425 value);
2427 target_buffer_set_u32(target, value_buf, value);
2428 retval = target_write_memory(target, address, 4, 1, value_buf);
2429 if (retval != ERROR_OK)
2430 LOG_DEBUG("failed: %i", retval);
2432 return retval;
2435 int target_write_u16(struct target *target, target_addr_t address, uint16_t value)
2437 int retval;
2438 uint8_t value_buf[2];
2439 if (!target_was_examined(target)) {
2440 LOG_ERROR("Target not examined yet");
2441 return ERROR_FAIL;
2444 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2445 address,
2446 value);
2448 target_buffer_set_u16(target, value_buf, value);
2449 retval = target_write_memory(target, address, 2, 1, value_buf);
2450 if (retval != ERROR_OK)
2451 LOG_DEBUG("failed: %i", retval);
2453 return retval;
2456 int target_write_u8(struct target *target, target_addr_t address, uint8_t value)
2458 int retval;
2459 if (!target_was_examined(target)) {
2460 LOG_ERROR("Target not examined yet");
2461 return ERROR_FAIL;
2464 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2465 address, value);
2467 retval = target_write_memory(target, address, 1, 1, &value);
2468 if (retval != ERROR_OK)
2469 LOG_DEBUG("failed: %i", retval);
2471 return retval;
2474 int target_write_phys_u64(struct target *target, target_addr_t address, uint64_t value)
2476 int retval;
2477 uint8_t value_buf[8];
2478 if (!target_was_examined(target)) {
2479 LOG_ERROR("Target not examined yet");
2480 return ERROR_FAIL;
2483 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2484 address,
2485 value);
2487 target_buffer_set_u64(target, value_buf, value);
2488 retval = target_write_phys_memory(target, address, 8, 1, value_buf);
2489 if (retval != ERROR_OK)
2490 LOG_DEBUG("failed: %i", retval);
2492 return retval;
2495 int target_write_phys_u32(struct target *target, target_addr_t address, uint32_t value)
2497 int retval;
2498 uint8_t value_buf[4];
2499 if (!target_was_examined(target)) {
2500 LOG_ERROR("Target not examined yet");
2501 return ERROR_FAIL;
2504 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2505 address,
2506 value);
2508 target_buffer_set_u32(target, value_buf, value);
2509 retval = target_write_phys_memory(target, address, 4, 1, value_buf);
2510 if (retval != ERROR_OK)
2511 LOG_DEBUG("failed: %i", retval);
2513 return retval;
2516 int target_write_phys_u16(struct target *target, target_addr_t address, uint16_t value)
2518 int retval;
2519 uint8_t value_buf[2];
2520 if (!target_was_examined(target)) {
2521 LOG_ERROR("Target not examined yet");
2522 return ERROR_FAIL;
2525 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2526 address,
2527 value);
2529 target_buffer_set_u16(target, value_buf, value);
2530 retval = target_write_phys_memory(target, address, 2, 1, value_buf);
2531 if (retval != ERROR_OK)
2532 LOG_DEBUG("failed: %i", retval);
2534 return retval;
2537 int target_write_phys_u8(struct target *target, target_addr_t address, uint8_t value)
2539 int retval;
2540 if (!target_was_examined(target)) {
2541 LOG_ERROR("Target not examined yet");
2542 return ERROR_FAIL;
2545 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2546 address, value);
2548 retval = target_write_phys_memory(target, address, 1, 1, &value);
2549 if (retval != ERROR_OK)
2550 LOG_DEBUG("failed: %i", retval);
2552 return retval;
2555 static int find_target(struct command_context *cmd_ctx, const char *name)
2557 struct target *target = get_target(name);
2558 if (target == NULL) {
2559 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2560 return ERROR_FAIL;
2562 if (!target->tap->enabled) {
2563 LOG_USER("Target: TAP %s is disabled, "
2564 "can't be the current target\n",
2565 target->tap->dotted_name);
2566 return ERROR_FAIL;
2569 cmd_ctx->current_target = target;
2570 if (cmd_ctx->current_target_override)
2571 cmd_ctx->current_target_override = target;
2573 return ERROR_OK;
2577 COMMAND_HANDLER(handle_targets_command)
2579 int retval = ERROR_OK;
2580 if (CMD_ARGC == 1) {
2581 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2582 if (retval == ERROR_OK) {
2583 /* we're done! */
2584 return retval;
2588 struct target *target = all_targets;
2589 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2590 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2591 while (target) {
2592 const char *state;
2593 char marker = ' ';
2595 if (target->tap->enabled)
2596 state = target_state_name(target);
2597 else
2598 state = "tap-disabled";
2600 if (CMD_CTX->current_target == target)
2601 marker = '*';
2603 /* keep columns lined up to match the headers above */
2604 command_print(CMD_CTX,
2605 "%2d%c %-18s %-10s %-6s %-18s %s",
2606 target->target_number,
2607 marker,
2608 target_name(target),
2609 target_type_name(target),
2610 Jim_Nvp_value2name_simple(nvp_target_endian,
2611 target->endianness)->name,
2612 target->tap->dotted_name,
2613 state);
2614 target = target->next;
2617 return retval;
2620 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2622 static int powerDropout;
2623 static int srstAsserted;
2625 static int runPowerRestore;
2626 static int runPowerDropout;
2627 static int runSrstAsserted;
2628 static int runSrstDeasserted;
2630 static int sense_handler(void)
2632 static int prevSrstAsserted;
2633 static int prevPowerdropout;
2635 int retval = jtag_power_dropout(&powerDropout);
2636 if (retval != ERROR_OK)
2637 return retval;
2639 int powerRestored;
2640 powerRestored = prevPowerdropout && !powerDropout;
2641 if (powerRestored)
2642 runPowerRestore = 1;
2644 int64_t current = timeval_ms();
2645 static int64_t lastPower;
2646 bool waitMore = lastPower + 2000 > current;
2647 if (powerDropout && !waitMore) {
2648 runPowerDropout = 1;
2649 lastPower = current;
2652 retval = jtag_srst_asserted(&srstAsserted);
2653 if (retval != ERROR_OK)
2654 return retval;
2656 int srstDeasserted;
2657 srstDeasserted = prevSrstAsserted && !srstAsserted;
2659 static int64_t lastSrst;
2660 waitMore = lastSrst + 2000 > current;
2661 if (srstDeasserted && !waitMore) {
2662 runSrstDeasserted = 1;
2663 lastSrst = current;
2666 if (!prevSrstAsserted && srstAsserted)
2667 runSrstAsserted = 1;
2669 prevSrstAsserted = srstAsserted;
2670 prevPowerdropout = powerDropout;
2672 if (srstDeasserted || powerRestored) {
2673 /* Other than logging the event we can't do anything here.
2674 * Issuing a reset is a particularly bad idea as we might
2675 * be inside a reset already.
2679 return ERROR_OK;
2682 /* process target state changes */
2683 static int handle_target(void *priv)
2685 Jim_Interp *interp = (Jim_Interp *)priv;
2686 int retval = ERROR_OK;
2688 if (!is_jtag_poll_safe()) {
2689 /* polling is disabled currently */
2690 return ERROR_OK;
2693 /* we do not want to recurse here... */
2694 static int recursive;
2695 if (!recursive) {
2696 recursive = 1;
2697 sense_handler();
2698 /* danger! running these procedures can trigger srst assertions and power dropouts.
2699 * We need to avoid an infinite loop/recursion here and we do that by
2700 * clearing the flags after running these events.
2702 int did_something = 0;
2703 if (runSrstAsserted) {
2704 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2705 Jim_Eval(interp, "srst_asserted");
2706 did_something = 1;
2708 if (runSrstDeasserted) {
2709 Jim_Eval(interp, "srst_deasserted");
2710 did_something = 1;
2712 if (runPowerDropout) {
2713 LOG_INFO("Power dropout detected, running power_dropout proc.");
2714 Jim_Eval(interp, "power_dropout");
2715 did_something = 1;
2717 if (runPowerRestore) {
2718 Jim_Eval(interp, "power_restore");
2719 did_something = 1;
2722 if (did_something) {
2723 /* clear detect flags */
2724 sense_handler();
2727 /* clear action flags */
2729 runSrstAsserted = 0;
2730 runSrstDeasserted = 0;
2731 runPowerRestore = 0;
2732 runPowerDropout = 0;
2734 recursive = 0;
2737 /* Poll targets for state changes unless that's globally disabled.
2738 * Skip targets that are currently disabled.
2740 for (struct target *target = all_targets;
2741 is_jtag_poll_safe() && target;
2742 target = target->next) {
2744 if (!target_was_examined(target))
2745 continue;
2747 if (!target->tap->enabled)
2748 continue;
2750 if (target->backoff.times > target->backoff.count) {
2751 /* do not poll this time as we failed previously */
2752 target->backoff.count++;
2753 continue;
2755 target->backoff.count = 0;
2757 /* only poll target if we've got power and srst isn't asserted */
2758 if (!powerDropout && !srstAsserted) {
2759 /* polling may fail silently until the target has been examined */
2760 retval = target_poll(target);
2761 if (retval != ERROR_OK) {
2762 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2763 if (target->backoff.times * polling_interval < 5000) {
2764 target->backoff.times *= 2;
2765 target->backoff.times++;
2768 /* Tell GDB to halt the debugger. This allows the user to
2769 * run monitor commands to handle the situation.
2771 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2773 if (target->backoff.times > 0) {
2774 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
2775 target_reset_examined(target);
2776 retval = target_examine_one(target);
2777 /* Target examination could have failed due to unstable connection,
2778 * but we set the examined flag anyway to repoll it later */
2779 if (retval != ERROR_OK) {
2780 target->examined = true;
2781 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
2782 target->backoff.times * polling_interval);
2783 return retval;
2787 /* Since we succeeded, we reset backoff count */
2788 target->backoff.times = 0;
2792 return retval;
2795 COMMAND_HANDLER(handle_reg_command)
2797 struct target *target;
2798 struct reg *reg = NULL;
2799 unsigned count = 0;
2800 char *value;
2802 LOG_DEBUG("-");
2804 target = get_current_target(CMD_CTX);
2806 /* list all available registers for the current target */
2807 if (CMD_ARGC == 0) {
2808 struct reg_cache *cache = target->reg_cache;
2810 count = 0;
2811 while (cache) {
2812 unsigned i;
2814 command_print(CMD_CTX, "===== %s", cache->name);
2816 for (i = 0, reg = cache->reg_list;
2817 i < cache->num_regs;
2818 i++, reg++, count++) {
2819 if (reg->exist == false)
2820 continue;
2821 /* only print cached values if they are valid */
2822 if (reg->valid) {
2823 value = buf_to_str(reg->value,
2824 reg->size, 16);
2825 command_print(CMD_CTX,
2826 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2827 count, reg->name,
2828 reg->size, value,
2829 reg->dirty
2830 ? " (dirty)"
2831 : "");
2832 free(value);
2833 } else {
2834 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2835 count, reg->name,
2836 reg->size) ;
2839 cache = cache->next;
2842 return ERROR_OK;
2845 /* access a single register by its ordinal number */
2846 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2847 unsigned num;
2848 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2850 struct reg_cache *cache = target->reg_cache;
2851 count = 0;
2852 while (cache) {
2853 unsigned i;
2854 for (i = 0; i < cache->num_regs; i++) {
2855 if (count++ == num) {
2856 reg = &cache->reg_list[i];
2857 break;
2860 if (reg)
2861 break;
2862 cache = cache->next;
2865 if (!reg) {
2866 command_print(CMD_CTX, "%i is out of bounds, the current target "
2867 "has only %i registers (0 - %i)", num, count, count - 1);
2868 return ERROR_OK;
2870 } else {
2871 /* access a single register by its name */
2872 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2874 if (!reg)
2875 goto not_found;
2878 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2880 if (!reg->exist)
2881 goto not_found;
2883 /* display a register */
2884 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2885 && (CMD_ARGV[1][0] <= '9')))) {
2886 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2887 reg->valid = 0;
2889 if (reg->valid == 0)
2890 reg->type->get(reg);
2891 value = buf_to_str(reg->value, reg->size, 16);
2892 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2893 free(value);
2894 return ERROR_OK;
2897 /* set register value */
2898 if (CMD_ARGC == 2) {
2899 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2900 if (buf == NULL)
2901 return ERROR_FAIL;
2902 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2904 reg->type->set(reg, buf);
2906 value = buf_to_str(reg->value, reg->size, 16);
2907 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2908 free(value);
2910 free(buf);
2912 return ERROR_OK;
2915 return ERROR_COMMAND_SYNTAX_ERROR;
2917 not_found:
2918 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2919 return ERROR_OK;
2922 COMMAND_HANDLER(handle_poll_command)
2924 int retval = ERROR_OK;
2925 struct target *target = get_current_target(CMD_CTX);
2927 if (CMD_ARGC == 0) {
2928 command_print(CMD_CTX, "background polling: %s",
2929 jtag_poll_get_enabled() ? "on" : "off");
2930 command_print(CMD_CTX, "TAP: %s (%s)",
2931 target->tap->dotted_name,
2932 target->tap->enabled ? "enabled" : "disabled");
2933 if (!target->tap->enabled)
2934 return ERROR_OK;
2935 retval = target_poll(target);
2936 if (retval != ERROR_OK)
2937 return retval;
2938 retval = target_arch_state(target);
2939 if (retval != ERROR_OK)
2940 return retval;
2941 } else if (CMD_ARGC == 1) {
2942 bool enable;
2943 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2944 jtag_poll_set_enabled(enable);
2945 } else
2946 return ERROR_COMMAND_SYNTAX_ERROR;
2948 return retval;
2951 COMMAND_HANDLER(handle_wait_halt_command)
2953 if (CMD_ARGC > 1)
2954 return ERROR_COMMAND_SYNTAX_ERROR;
2956 unsigned ms = DEFAULT_HALT_TIMEOUT;
2957 if (1 == CMD_ARGC) {
2958 int retval = parse_uint(CMD_ARGV[0], &ms);
2959 if (ERROR_OK != retval)
2960 return ERROR_COMMAND_SYNTAX_ERROR;
2963 struct target *target = get_current_target(CMD_CTX);
2964 return target_wait_state(target, TARGET_HALTED, ms);
2967 /* wait for target state to change. The trick here is to have a low
2968 * latency for short waits and not to suck up all the CPU time
2969 * on longer waits.
2971 * After 500ms, keep_alive() is invoked
2973 int target_wait_state(struct target *target, enum target_state state, int ms)
2975 int retval;
2976 int64_t then = 0, cur;
2977 bool once = true;
2979 for (;;) {
2980 retval = target_poll(target);
2981 if (retval != ERROR_OK)
2982 return retval;
2983 if (target->state == state)
2984 break;
2985 cur = timeval_ms();
2986 if (once) {
2987 once = false;
2988 then = timeval_ms();
2989 LOG_DEBUG("waiting for target %s...",
2990 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2993 if (cur-then > 500)
2994 keep_alive();
2996 if ((cur-then) > ms) {
2997 LOG_ERROR("timed out while waiting for target %s",
2998 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2999 return ERROR_FAIL;
3003 return ERROR_OK;
3006 COMMAND_HANDLER(handle_halt_command)
3008 LOG_DEBUG("-");
3010 struct target *target = get_current_target(CMD_CTX);
3012 target->verbose_halt_msg = true;
3014 int retval = target_halt(target);
3015 if (ERROR_OK != retval)
3016 return retval;
3018 if (CMD_ARGC == 1) {
3019 unsigned wait_local;
3020 retval = parse_uint(CMD_ARGV[0], &wait_local);
3021 if (ERROR_OK != retval)
3022 return ERROR_COMMAND_SYNTAX_ERROR;
3023 if (!wait_local)
3024 return ERROR_OK;
3027 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
3030 COMMAND_HANDLER(handle_soft_reset_halt_command)
3032 struct target *target = get_current_target(CMD_CTX);
3034 LOG_USER("requesting target halt and executing a soft reset");
3036 target_soft_reset_halt(target);
3038 return ERROR_OK;
3041 COMMAND_HANDLER(handle_reset_command)
3043 if (CMD_ARGC > 1)
3044 return ERROR_COMMAND_SYNTAX_ERROR;
3046 enum target_reset_mode reset_mode = RESET_RUN;
3047 if (CMD_ARGC == 1) {
3048 const Jim_Nvp *n;
3049 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
3050 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
3051 return ERROR_COMMAND_SYNTAX_ERROR;
3052 reset_mode = n->value;
3055 /* reset *all* targets */
3056 return target_process_reset(CMD_CTX, reset_mode);
3060 COMMAND_HANDLER(handle_resume_command)
3062 int current = 1;
3063 if (CMD_ARGC > 1)
3064 return ERROR_COMMAND_SYNTAX_ERROR;
3066 struct target *target = get_current_target(CMD_CTX);
3068 /* with no CMD_ARGV, resume from current pc, addr = 0,
3069 * with one arguments, addr = CMD_ARGV[0],
3070 * handle breakpoints, not debugging */
3071 target_addr_t addr = 0;
3072 if (CMD_ARGC == 1) {
3073 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3074 current = 0;
3077 return target_resume(target, current, addr, 1, 0);
3080 COMMAND_HANDLER(handle_step_command)
3082 if (CMD_ARGC > 1)
3083 return ERROR_COMMAND_SYNTAX_ERROR;
3085 LOG_DEBUG("-");
3087 /* with no CMD_ARGV, step from current pc, addr = 0,
3088 * with one argument addr = CMD_ARGV[0],
3089 * handle breakpoints, debugging */
3090 target_addr_t addr = 0;
3091 int current_pc = 1;
3092 if (CMD_ARGC == 1) {
3093 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3094 current_pc = 0;
3097 struct target *target = get_current_target(CMD_CTX);
3099 return target->type->step(target, current_pc, addr, 1);
3102 static void handle_md_output(struct command_context *cmd_ctx,
3103 struct target *target, target_addr_t address, unsigned size,
3104 unsigned count, const uint8_t *buffer)
3106 const unsigned line_bytecnt = 32;
3107 unsigned line_modulo = line_bytecnt / size;
3109 char output[line_bytecnt * 4 + 1];
3110 unsigned output_len = 0;
3112 const char *value_fmt;
3113 switch (size) {
3114 case 8:
3115 value_fmt = "%16.16"PRIx64" ";
3116 break;
3117 case 4:
3118 value_fmt = "%8.8"PRIx64" ";
3119 break;
3120 case 2:
3121 value_fmt = "%4.4"PRIx64" ";
3122 break;
3123 case 1:
3124 value_fmt = "%2.2"PRIx64" ";
3125 break;
3126 default:
3127 /* "can't happen", caller checked */
3128 LOG_ERROR("invalid memory read size: %u", size);
3129 return;
3132 for (unsigned i = 0; i < count; i++) {
3133 if (i % line_modulo == 0) {
3134 output_len += snprintf(output + output_len,
3135 sizeof(output) - output_len,
3136 TARGET_ADDR_FMT ": ",
3137 (address + (i * size)));
3140 uint64_t value = 0;
3141 const uint8_t *value_ptr = buffer + i * size;
3142 switch (size) {
3143 case 8:
3144 value = target_buffer_get_u64(target, value_ptr);
3145 break;
3146 case 4:
3147 value = target_buffer_get_u32(target, value_ptr);
3148 break;
3149 case 2:
3150 value = target_buffer_get_u16(target, value_ptr);
3151 break;
3152 case 1:
3153 value = *value_ptr;
3155 output_len += snprintf(output + output_len,
3156 sizeof(output) - output_len,
3157 value_fmt, value);
3159 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
3160 command_print(cmd_ctx, "%s", output);
3161 output_len = 0;
3166 COMMAND_HANDLER(handle_md_command)
3168 if (CMD_ARGC < 1)
3169 return ERROR_COMMAND_SYNTAX_ERROR;
3171 unsigned size = 0;
3172 switch (CMD_NAME[2]) {
3173 case 'd':
3174 size = 8;
3175 break;
3176 case 'w':
3177 size = 4;
3178 break;
3179 case 'h':
3180 size = 2;
3181 break;
3182 case 'b':
3183 size = 1;
3184 break;
3185 default:
3186 return ERROR_COMMAND_SYNTAX_ERROR;
3189 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3190 int (*fn)(struct target *target,
3191 target_addr_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
3192 if (physical) {
3193 CMD_ARGC--;
3194 CMD_ARGV++;
3195 fn = target_read_phys_memory;
3196 } else
3197 fn = target_read_memory;
3198 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
3199 return ERROR_COMMAND_SYNTAX_ERROR;
3201 target_addr_t address;
3202 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3204 unsigned count = 1;
3205 if (CMD_ARGC == 2)
3206 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3208 uint8_t *buffer = calloc(count, size);
3209 if (buffer == NULL) {
3210 LOG_ERROR("Failed to allocate md read buffer");
3211 return ERROR_FAIL;
3214 struct target *target = get_current_target(CMD_CTX);
3215 int retval = fn(target, address, size, count, buffer);
3216 if (ERROR_OK == retval)
3217 handle_md_output(CMD_CTX, target, address, size, count, buffer);
3219 free(buffer);
3221 return retval;
3224 typedef int (*target_write_fn)(struct target *target,
3225 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3227 static int target_fill_mem(struct target *target,
3228 target_addr_t address,
3229 target_write_fn fn,
3230 unsigned data_size,
3231 /* value */
3232 uint64_t b,
3233 /* count */
3234 unsigned c)
3236 /* We have to write in reasonably large chunks to be able
3237 * to fill large memory areas with any sane speed */
3238 const unsigned chunk_size = 16384;
3239 uint8_t *target_buf = malloc(chunk_size * data_size);
3240 if (target_buf == NULL) {
3241 LOG_ERROR("Out of memory");
3242 return ERROR_FAIL;
3245 for (unsigned i = 0; i < chunk_size; i++) {
3246 switch (data_size) {
3247 case 8:
3248 target_buffer_set_u64(target, target_buf + i * data_size, b);
3249 break;
3250 case 4:
3251 target_buffer_set_u32(target, target_buf + i * data_size, b);
3252 break;
3253 case 2:
3254 target_buffer_set_u16(target, target_buf + i * data_size, b);
3255 break;
3256 case 1:
3257 target_buffer_set_u8(target, target_buf + i * data_size, b);
3258 break;
3259 default:
3260 exit(-1);
3264 int retval = ERROR_OK;
3266 for (unsigned x = 0; x < c; x += chunk_size) {
3267 unsigned current;
3268 current = c - x;
3269 if (current > chunk_size)
3270 current = chunk_size;
3271 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3272 if (retval != ERROR_OK)
3273 break;
3274 /* avoid GDB timeouts */
3275 keep_alive();
3277 free(target_buf);
3279 return retval;
3283 COMMAND_HANDLER(handle_mw_command)
3285 if (CMD_ARGC < 2)
3286 return ERROR_COMMAND_SYNTAX_ERROR;
3287 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3288 target_write_fn fn;
3289 if (physical) {
3290 CMD_ARGC--;
3291 CMD_ARGV++;
3292 fn = target_write_phys_memory;
3293 } else
3294 fn = target_write_memory;
3295 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3296 return ERROR_COMMAND_SYNTAX_ERROR;
3298 target_addr_t address;
3299 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3301 target_addr_t value;
3302 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], value);
3304 unsigned count = 1;
3305 if (CMD_ARGC == 3)
3306 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3308 struct target *target = get_current_target(CMD_CTX);
3309 unsigned wordsize;
3310 switch (CMD_NAME[2]) {
3311 case 'd':
3312 wordsize = 8;
3313 break;
3314 case 'w':
3315 wordsize = 4;
3316 break;
3317 case 'h':
3318 wordsize = 2;
3319 break;
3320 case 'b':
3321 wordsize = 1;
3322 break;
3323 default:
3324 return ERROR_COMMAND_SYNTAX_ERROR;
3327 return target_fill_mem(target, address, fn, wordsize, value, count);
3330 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
3331 target_addr_t *min_address, target_addr_t *max_address)
3333 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3334 return ERROR_COMMAND_SYNTAX_ERROR;
3336 /* a base address isn't always necessary,
3337 * default to 0x0 (i.e. don't relocate) */
3338 if (CMD_ARGC >= 2) {
3339 target_addr_t addr;
3340 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3341 image->base_address = addr;
3342 image->base_address_set = 1;
3343 } else
3344 image->base_address_set = 0;
3346 image->start_address_set = 0;
3348 if (CMD_ARGC >= 4)
3349 COMMAND_PARSE_ADDRESS(CMD_ARGV[3], *min_address);
3350 if (CMD_ARGC == 5) {
3351 COMMAND_PARSE_ADDRESS(CMD_ARGV[4], *max_address);
3352 /* use size (given) to find max (required) */
3353 *max_address += *min_address;
3356 if (*min_address > *max_address)
3357 return ERROR_COMMAND_SYNTAX_ERROR;
3359 return ERROR_OK;
3362 COMMAND_HANDLER(handle_load_image_command)
3364 uint8_t *buffer;
3365 size_t buf_cnt;
3366 uint32_t image_size;
3367 target_addr_t min_address = 0;
3368 target_addr_t max_address = -1;
3369 int i;
3370 struct image image;
3372 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
3373 &image, &min_address, &max_address);
3374 if (ERROR_OK != retval)
3375 return retval;
3377 struct target *target = get_current_target(CMD_CTX);
3379 struct duration bench;
3380 duration_start(&bench);
3382 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3383 return ERROR_FAIL;
3385 image_size = 0x0;
3386 retval = ERROR_OK;
3387 for (i = 0; i < image.num_sections; i++) {
3388 buffer = malloc(image.sections[i].size);
3389 if (buffer == NULL) {
3390 command_print(CMD_CTX,
3391 "error allocating buffer for section (%d bytes)",
3392 (int)(image.sections[i].size));
3393 retval = ERROR_FAIL;
3394 break;
3397 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3398 if (retval != ERROR_OK) {
3399 free(buffer);
3400 break;
3403 uint32_t offset = 0;
3404 uint32_t length = buf_cnt;
3406 /* DANGER!!! beware of unsigned comparision here!!! */
3408 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3409 (image.sections[i].base_address < max_address)) {
3411 if (image.sections[i].base_address < min_address) {
3412 /* clip addresses below */
3413 offset += min_address-image.sections[i].base_address;
3414 length -= offset;
3417 if (image.sections[i].base_address + buf_cnt > max_address)
3418 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3420 retval = target_write_buffer(target,
3421 image.sections[i].base_address + offset, length, buffer + offset);
3422 if (retval != ERROR_OK) {
3423 free(buffer);
3424 break;
3426 image_size += length;
3427 command_print(CMD_CTX, "%u bytes written at address " TARGET_ADDR_FMT "",
3428 (unsigned int)length,
3429 image.sections[i].base_address + offset);
3432 free(buffer);
3435 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3436 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
3437 "in %fs (%0.3f KiB/s)", image_size,
3438 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3441 image_close(&image);
3443 return retval;
3447 COMMAND_HANDLER(handle_dump_image_command)
3449 struct fileio *fileio;
3450 uint8_t *buffer;
3451 int retval, retvaltemp;
3452 target_addr_t address, size;
3453 struct duration bench;
3454 struct target *target = get_current_target(CMD_CTX);
3456 if (CMD_ARGC != 3)
3457 return ERROR_COMMAND_SYNTAX_ERROR;
3459 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], address);
3460 COMMAND_PARSE_ADDRESS(CMD_ARGV[2], size);
3462 uint32_t buf_size = (size > 4096) ? 4096 : size;
3463 buffer = malloc(buf_size);
3464 if (!buffer)
3465 return ERROR_FAIL;
3467 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3468 if (retval != ERROR_OK) {
3469 free(buffer);
3470 return retval;
3473 duration_start(&bench);
3475 while (size > 0) {
3476 size_t size_written;
3477 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3478 retval = target_read_buffer(target, address, this_run_size, buffer);
3479 if (retval != ERROR_OK)
3480 break;
3482 retval = fileio_write(fileio, this_run_size, buffer, &size_written);
3483 if (retval != ERROR_OK)
3484 break;
3486 size -= this_run_size;
3487 address += this_run_size;
3490 free(buffer);
3492 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3493 size_t filesize;
3494 retval = fileio_size(fileio, &filesize);
3495 if (retval != ERROR_OK)
3496 return retval;
3497 command_print(CMD_CTX,
3498 "dumped %zu bytes in %fs (%0.3f KiB/s)", filesize,
3499 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3502 retvaltemp = fileio_close(fileio);
3503 if (retvaltemp != ERROR_OK)
3504 return retvaltemp;
3506 return retval;
3509 enum verify_mode {
3510 IMAGE_TEST = 0,
3511 IMAGE_VERIFY = 1,
3512 IMAGE_CHECKSUM_ONLY = 2
3515 static COMMAND_HELPER(handle_verify_image_command_internal, enum verify_mode verify)
3517 uint8_t *buffer;
3518 size_t buf_cnt;
3519 uint32_t image_size;
3520 int i;
3521 int retval;
3522 uint32_t checksum = 0;
3523 uint32_t mem_checksum = 0;
3525 struct image image;
3527 struct target *target = get_current_target(CMD_CTX);
3529 if (CMD_ARGC < 1)
3530 return ERROR_COMMAND_SYNTAX_ERROR;
3532 if (!target) {
3533 LOG_ERROR("no target selected");
3534 return ERROR_FAIL;
3537 struct duration bench;
3538 duration_start(&bench);
3540 if (CMD_ARGC >= 2) {
3541 target_addr_t addr;
3542 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3543 image.base_address = addr;
3544 image.base_address_set = 1;
3545 } else {
3546 image.base_address_set = 0;
3547 image.base_address = 0x0;
3550 image.start_address_set = 0;
3552 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3553 if (retval != ERROR_OK)
3554 return retval;
3556 image_size = 0x0;
3557 int diffs = 0;
3558 retval = ERROR_OK;
3559 for (i = 0; i < image.num_sections; i++) {
3560 buffer = malloc(image.sections[i].size);
3561 if (buffer == NULL) {
3562 command_print(CMD_CTX,
3563 "error allocating buffer for section (%d bytes)",
3564 (int)(image.sections[i].size));
3565 break;
3567 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3568 if (retval != ERROR_OK) {
3569 free(buffer);
3570 break;
3573 if (verify >= IMAGE_VERIFY) {
3574 /* calculate checksum of image */
3575 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3576 if (retval != ERROR_OK) {
3577 free(buffer);
3578 break;
3581 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3582 if (retval != ERROR_OK) {
3583 free(buffer);
3584 break;
3586 if ((checksum != mem_checksum) && (verify == IMAGE_CHECKSUM_ONLY)) {
3587 LOG_ERROR("checksum mismatch");
3588 free(buffer);
3589 retval = ERROR_FAIL;
3590 goto done;
3592 if (checksum != mem_checksum) {
3593 /* failed crc checksum, fall back to a binary compare */
3594 uint8_t *data;
3596 if (diffs == 0)
3597 LOG_ERROR("checksum mismatch - attempting binary compare");
3599 data = malloc(buf_cnt);
3601 /* Can we use 32bit word accesses? */
3602 int size = 1;
3603 int count = buf_cnt;
3604 if ((count % 4) == 0) {
3605 size *= 4;
3606 count /= 4;
3608 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3609 if (retval == ERROR_OK) {
3610 uint32_t t;
3611 for (t = 0; t < buf_cnt; t++) {
3612 if (data[t] != buffer[t]) {
3613 command_print(CMD_CTX,
3614 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3615 diffs,
3616 (unsigned)(t + image.sections[i].base_address),
3617 data[t],
3618 buffer[t]);
3619 if (diffs++ >= 127) {
3620 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3621 free(data);
3622 free(buffer);
3623 goto done;
3626 keep_alive();
3629 free(data);
3631 } else {
3632 command_print(CMD_CTX, "address " TARGET_ADDR_FMT " length 0x%08zx",
3633 image.sections[i].base_address,
3634 buf_cnt);
3637 free(buffer);
3638 image_size += buf_cnt;
3640 if (diffs > 0)
3641 command_print(CMD_CTX, "No more differences found.");
3642 done:
3643 if (diffs > 0)
3644 retval = ERROR_FAIL;
3645 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3646 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3647 "in %fs (%0.3f KiB/s)", image_size,
3648 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3651 image_close(&image);
3653 return retval;
3656 COMMAND_HANDLER(handle_verify_image_checksum_command)
3658 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_CHECKSUM_ONLY);
3661 COMMAND_HANDLER(handle_verify_image_command)
3663 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_VERIFY);
3666 COMMAND_HANDLER(handle_test_image_command)
3668 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_TEST);
3671 static int handle_bp_command_list(struct command_context *cmd_ctx)
3673 struct target *target = get_current_target(cmd_ctx);
3674 struct breakpoint *breakpoint = target->breakpoints;
3675 while (breakpoint) {
3676 if (breakpoint->type == BKPT_SOFT) {
3677 char *buf = buf_to_str(breakpoint->orig_instr,
3678 breakpoint->length, 16);
3679 command_print(cmd_ctx, "IVA breakpoint: " TARGET_ADDR_FMT ", 0x%x, %i, 0x%s",
3680 breakpoint->address,
3681 breakpoint->length,
3682 breakpoint->set, buf);
3683 free(buf);
3684 } else {
3685 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3686 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3687 breakpoint->asid,
3688 breakpoint->length, breakpoint->set);
3689 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3690 command_print(cmd_ctx, "Hybrid breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3691 breakpoint->address,
3692 breakpoint->length, breakpoint->set);
3693 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3694 breakpoint->asid);
3695 } else
3696 command_print(cmd_ctx, "Breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3697 breakpoint->address,
3698 breakpoint->length, breakpoint->set);
3701 breakpoint = breakpoint->next;
3703 return ERROR_OK;
3706 static int handle_bp_command_set(struct command_context *cmd_ctx,
3707 target_addr_t addr, uint32_t asid, uint32_t length, int hw)
3709 struct target *target = get_current_target(cmd_ctx);
3710 int retval;
3712 if (asid == 0) {
3713 retval = breakpoint_add(target, addr, length, hw);
3714 if (ERROR_OK == retval)
3715 command_print(cmd_ctx, "breakpoint set at " TARGET_ADDR_FMT "", addr);
3716 else {
3717 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3718 return retval;
3720 } else if (addr == 0) {
3721 if (target->type->add_context_breakpoint == NULL) {
3722 LOG_WARNING("Context breakpoint not available");
3723 return ERROR_OK;
3725 retval = context_breakpoint_add(target, asid, length, hw);
3726 if (ERROR_OK == retval)
3727 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3728 else {
3729 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3730 return retval;
3732 } else {
3733 if (target->type->add_hybrid_breakpoint == NULL) {
3734 LOG_WARNING("Hybrid breakpoint not available");
3735 return ERROR_OK;
3737 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3738 if (ERROR_OK == retval)
3739 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3740 else {
3741 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3742 return retval;
3745 return ERROR_OK;
3748 COMMAND_HANDLER(handle_bp_command)
3750 target_addr_t addr;
3751 uint32_t asid;
3752 uint32_t length;
3753 int hw = BKPT_SOFT;
3755 switch (CMD_ARGC) {
3756 case 0:
3757 return handle_bp_command_list(CMD_CTX);
3759 case 2:
3760 asid = 0;
3761 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3762 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3763 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3765 case 3:
3766 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3767 hw = BKPT_HARD;
3768 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3769 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3770 asid = 0;
3771 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3772 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3773 hw = BKPT_HARD;
3774 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3775 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3776 addr = 0;
3777 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3779 /* fallthrough */
3780 case 4:
3781 hw = BKPT_HARD;
3782 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3783 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3784 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3785 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3787 default:
3788 return ERROR_COMMAND_SYNTAX_ERROR;
3792 COMMAND_HANDLER(handle_rbp_command)
3794 if (CMD_ARGC != 1)
3795 return ERROR_COMMAND_SYNTAX_ERROR;
3797 target_addr_t addr;
3798 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3800 struct target *target = get_current_target(CMD_CTX);
3801 breakpoint_remove(target, addr);
3803 return ERROR_OK;
3806 COMMAND_HANDLER(handle_wp_command)
3808 struct target *target = get_current_target(CMD_CTX);
3810 if (CMD_ARGC == 0) {
3811 struct watchpoint *watchpoint = target->watchpoints;
3813 while (watchpoint) {
3814 command_print(CMD_CTX, "address: " TARGET_ADDR_FMT
3815 ", len: 0x%8.8" PRIx32
3816 ", r/w/a: %i, value: 0x%8.8" PRIx32
3817 ", mask: 0x%8.8" PRIx32,
3818 watchpoint->address,
3819 watchpoint->length,
3820 (int)watchpoint->rw,
3821 watchpoint->value,
3822 watchpoint->mask);
3823 watchpoint = watchpoint->next;
3825 return ERROR_OK;
3828 enum watchpoint_rw type = WPT_ACCESS;
3829 uint32_t addr = 0;
3830 uint32_t length = 0;
3831 uint32_t data_value = 0x0;
3832 uint32_t data_mask = 0xffffffff;
3834 switch (CMD_ARGC) {
3835 case 5:
3836 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3837 /* fall through */
3838 case 4:
3839 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3840 /* fall through */
3841 case 3:
3842 switch (CMD_ARGV[2][0]) {
3843 case 'r':
3844 type = WPT_READ;
3845 break;
3846 case 'w':
3847 type = WPT_WRITE;
3848 break;
3849 case 'a':
3850 type = WPT_ACCESS;
3851 break;
3852 default:
3853 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3854 return ERROR_COMMAND_SYNTAX_ERROR;
3856 /* fall through */
3857 case 2:
3858 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3859 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3860 break;
3862 default:
3863 return ERROR_COMMAND_SYNTAX_ERROR;
3866 int retval = watchpoint_add(target, addr, length, type,
3867 data_value, data_mask);
3868 if (ERROR_OK != retval)
3869 LOG_ERROR("Failure setting watchpoints");
3871 return retval;
3874 COMMAND_HANDLER(handle_rwp_command)
3876 if (CMD_ARGC != 1)
3877 return ERROR_COMMAND_SYNTAX_ERROR;
3879 uint32_t addr;
3880 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3882 struct target *target = get_current_target(CMD_CTX);
3883 watchpoint_remove(target, addr);
3885 return ERROR_OK;
3889 * Translate a virtual address to a physical address.
3891 * The low-level target implementation must have logged a detailed error
3892 * which is forwarded to telnet/GDB session.
3894 COMMAND_HANDLER(handle_virt2phys_command)
3896 if (CMD_ARGC != 1)
3897 return ERROR_COMMAND_SYNTAX_ERROR;
3899 target_addr_t va;
3900 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], va);
3901 target_addr_t pa;
3903 struct target *target = get_current_target(CMD_CTX);
3904 int retval = target->type->virt2phys(target, va, &pa);
3905 if (retval == ERROR_OK)
3906 command_print(CMD_CTX, "Physical address " TARGET_ADDR_FMT "", pa);
3908 return retval;
3911 static void writeData(FILE *f, const void *data, size_t len)
3913 size_t written = fwrite(data, 1, len, f);
3914 if (written != len)
3915 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3918 static void writeLong(FILE *f, int l, struct target *target)
3920 uint8_t val[4];
3922 target_buffer_set_u32(target, val, l);
3923 writeData(f, val, 4);
3926 static void writeString(FILE *f, char *s)
3928 writeData(f, s, strlen(s));
3931 typedef unsigned char UNIT[2]; /* unit of profiling */
3933 /* Dump a gmon.out histogram file. */
3934 static void write_gmon(uint32_t *samples, uint32_t sampleNum, const char *filename, bool with_range,
3935 uint32_t start_address, uint32_t end_address, struct target *target, uint32_t duration_ms)
3937 uint32_t i;
3938 FILE *f = fopen(filename, "w");
3939 if (f == NULL)
3940 return;
3941 writeString(f, "gmon");
3942 writeLong(f, 0x00000001, target); /* Version */
3943 writeLong(f, 0, target); /* padding */
3944 writeLong(f, 0, target); /* padding */
3945 writeLong(f, 0, target); /* padding */
3947 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3948 writeData(f, &zero, 1);
3950 /* figure out bucket size */
3951 uint32_t min;
3952 uint32_t max;
3953 if (with_range) {
3954 min = start_address;
3955 max = end_address;
3956 } else {
3957 min = samples[0];
3958 max = samples[0];
3959 for (i = 0; i < sampleNum; i++) {
3960 if (min > samples[i])
3961 min = samples[i];
3962 if (max < samples[i])
3963 max = samples[i];
3966 /* max should be (largest sample + 1)
3967 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
3968 max++;
3971 int addressSpace = max - min;
3972 assert(addressSpace >= 2);
3974 /* FIXME: What is the reasonable number of buckets?
3975 * The profiling result will be more accurate if there are enough buckets. */
3976 static const uint32_t maxBuckets = 128 * 1024; /* maximum buckets. */
3977 uint32_t numBuckets = addressSpace / sizeof(UNIT);
3978 if (numBuckets > maxBuckets)
3979 numBuckets = maxBuckets;
3980 int *buckets = malloc(sizeof(int) * numBuckets);
3981 if (buckets == NULL) {
3982 fclose(f);
3983 return;
3985 memset(buckets, 0, sizeof(int) * numBuckets);
3986 for (i = 0; i < sampleNum; i++) {
3987 uint32_t address = samples[i];
3989 if ((address < min) || (max <= address))
3990 continue;
3992 long long a = address - min;
3993 long long b = numBuckets;
3994 long long c = addressSpace;
3995 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3996 buckets[index_t]++;
3999 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
4000 writeLong(f, min, target); /* low_pc */
4001 writeLong(f, max, target); /* high_pc */
4002 writeLong(f, numBuckets, target); /* # of buckets */
4003 float sample_rate = sampleNum / (duration_ms / 1000.0);
4004 writeLong(f, sample_rate, target);
4005 writeString(f, "seconds");
4006 for (i = 0; i < (15-strlen("seconds")); i++)
4007 writeData(f, &zero, 1);
4008 writeString(f, "s");
4010 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
4012 char *data = malloc(2 * numBuckets);
4013 if (data != NULL) {
4014 for (i = 0; i < numBuckets; i++) {
4015 int val;
4016 val = buckets[i];
4017 if (val > 65535)
4018 val = 65535;
4019 data[i * 2] = val&0xff;
4020 data[i * 2 + 1] = (val >> 8) & 0xff;
4022 free(buckets);
4023 writeData(f, data, numBuckets * 2);
4024 free(data);
4025 } else
4026 free(buckets);
4028 fclose(f);
4031 /* profiling samples the CPU PC as quickly as OpenOCD is able,
4032 * which will be used as a random sampling of PC */
4033 COMMAND_HANDLER(handle_profile_command)
4035 struct target *target = get_current_target(CMD_CTX);
4037 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
4038 return ERROR_COMMAND_SYNTAX_ERROR;
4040 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
4041 uint32_t offset;
4042 uint32_t num_of_samples;
4043 int retval = ERROR_OK;
4045 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
4047 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
4048 if (samples == NULL) {
4049 LOG_ERROR("No memory to store samples.");
4050 return ERROR_FAIL;
4053 uint64_t timestart_ms = timeval_ms();
4055 * Some cores let us sample the PC without the
4056 * annoying halt/resume step; for example, ARMv7 PCSR.
4057 * Provide a way to use that more efficient mechanism.
4059 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
4060 &num_of_samples, offset);
4061 if (retval != ERROR_OK) {
4062 free(samples);
4063 return retval;
4065 uint32_t duration_ms = timeval_ms() - timestart_ms;
4067 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
4069 retval = target_poll(target);
4070 if (retval != ERROR_OK) {
4071 free(samples);
4072 return retval;
4074 if (target->state == TARGET_RUNNING) {
4075 retval = target_halt(target);
4076 if (retval != ERROR_OK) {
4077 free(samples);
4078 return retval;
4082 retval = target_poll(target);
4083 if (retval != ERROR_OK) {
4084 free(samples);
4085 return retval;
4088 uint32_t start_address = 0;
4089 uint32_t end_address = 0;
4090 bool with_range = false;
4091 if (CMD_ARGC == 4) {
4092 with_range = true;
4093 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
4094 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
4097 write_gmon(samples, num_of_samples, CMD_ARGV[1],
4098 with_range, start_address, end_address, target, duration_ms);
4099 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
4101 free(samples);
4102 return retval;
4105 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
4107 char *namebuf;
4108 Jim_Obj *nameObjPtr, *valObjPtr;
4109 int result;
4111 namebuf = alloc_printf("%s(%d)", varname, idx);
4112 if (!namebuf)
4113 return JIM_ERR;
4115 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
4116 valObjPtr = Jim_NewIntObj(interp, val);
4117 if (!nameObjPtr || !valObjPtr) {
4118 free(namebuf);
4119 return JIM_ERR;
4122 Jim_IncrRefCount(nameObjPtr);
4123 Jim_IncrRefCount(valObjPtr);
4124 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
4125 Jim_DecrRefCount(interp, nameObjPtr);
4126 Jim_DecrRefCount(interp, valObjPtr);
4127 free(namebuf);
4128 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
4129 return result;
4132 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4134 struct command_context *context;
4135 struct target *target;
4137 context = current_command_context(interp);
4138 assert(context != NULL);
4140 target = get_current_target(context);
4141 if (target == NULL) {
4142 LOG_ERROR("mem2array: no current target");
4143 return JIM_ERR;
4146 return target_mem2array(interp, target, argc - 1, argv + 1);
4149 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
4151 long l;
4152 uint32_t width;
4153 int len;
4154 uint32_t addr;
4155 uint32_t count;
4156 uint32_t v;
4157 const char *varname;
4158 const char *phys;
4159 bool is_phys;
4160 int n, e, retval;
4161 uint32_t i;
4163 /* argv[1] = name of array to receive the data
4164 * argv[2] = desired width
4165 * argv[3] = memory address
4166 * argv[4] = count of times to read
4169 if (argc < 4 || argc > 5) {
4170 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4171 return JIM_ERR;
4173 varname = Jim_GetString(argv[0], &len);
4174 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
4176 e = Jim_GetLong(interp, argv[1], &l);
4177 width = l;
4178 if (e != JIM_OK)
4179 return e;
4181 e = Jim_GetLong(interp, argv[2], &l);
4182 addr = l;
4183 if (e != JIM_OK)
4184 return e;
4185 e = Jim_GetLong(interp, argv[3], &l);
4186 len = l;
4187 if (e != JIM_OK)
4188 return e;
4189 is_phys = false;
4190 if (argc > 4) {
4191 phys = Jim_GetString(argv[4], &n);
4192 if (!strncmp(phys, "phys", n))
4193 is_phys = true;
4194 else
4195 return JIM_ERR;
4197 switch (width) {
4198 case 8:
4199 width = 1;
4200 break;
4201 case 16:
4202 width = 2;
4203 break;
4204 case 32:
4205 width = 4;
4206 break;
4207 default:
4208 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4209 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
4210 return JIM_ERR;
4212 if (len == 0) {
4213 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4214 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
4215 return JIM_ERR;
4217 if ((addr + (len * width)) < addr) {
4218 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4219 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
4220 return JIM_ERR;
4222 /* absurd transfer size? */
4223 if (len > 65536) {
4224 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4225 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
4226 return JIM_ERR;
4229 if ((width == 1) ||
4230 ((width == 2) && ((addr & 1) == 0)) ||
4231 ((width == 4) && ((addr & 3) == 0))) {
4232 /* all is well */
4233 } else {
4234 char buf[100];
4235 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4236 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
4237 addr,
4238 width);
4239 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4240 return JIM_ERR;
4243 /* Transfer loop */
4245 /* index counter */
4246 n = 0;
4248 size_t buffersize = 4096;
4249 uint8_t *buffer = malloc(buffersize);
4250 if (buffer == NULL)
4251 return JIM_ERR;
4253 /* assume ok */
4254 e = JIM_OK;
4255 while (len) {
4256 /* Slurp... in buffer size chunks */
4258 count = len; /* in objects.. */
4259 if (count > (buffersize / width))
4260 count = (buffersize / width);
4262 if (is_phys)
4263 retval = target_read_phys_memory(target, addr, width, count, buffer);
4264 else
4265 retval = target_read_memory(target, addr, width, count, buffer);
4266 if (retval != ERROR_OK) {
4267 /* BOO !*/
4268 LOG_ERROR("mem2array: Read @ 0x%08" PRIx32 ", w=%" PRId32 ", cnt=%" PRId32 ", failed",
4269 addr,
4270 width,
4271 count);
4272 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4273 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
4274 e = JIM_ERR;
4275 break;
4276 } else {
4277 v = 0; /* shut up gcc */
4278 for (i = 0; i < count ; i++, n++) {
4279 switch (width) {
4280 case 4:
4281 v = target_buffer_get_u32(target, &buffer[i*width]);
4282 break;
4283 case 2:
4284 v = target_buffer_get_u16(target, &buffer[i*width]);
4285 break;
4286 case 1:
4287 v = buffer[i] & 0x0ff;
4288 break;
4290 new_int_array_element(interp, varname, n, v);
4292 len -= count;
4293 addr += count * width;
4297 free(buffer);
4299 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4301 return e;
4304 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
4306 char *namebuf;
4307 Jim_Obj *nameObjPtr, *valObjPtr;
4308 int result;
4309 long l;
4311 namebuf = alloc_printf("%s(%d)", varname, idx);
4312 if (!namebuf)
4313 return JIM_ERR;
4315 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
4316 if (!nameObjPtr) {
4317 free(namebuf);
4318 return JIM_ERR;
4321 Jim_IncrRefCount(nameObjPtr);
4322 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
4323 Jim_DecrRefCount(interp, nameObjPtr);
4324 free(namebuf);
4325 if (valObjPtr == NULL)
4326 return JIM_ERR;
4328 result = Jim_GetLong(interp, valObjPtr, &l);
4329 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
4330 *val = l;
4331 return result;
4334 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4336 struct command_context *context;
4337 struct target *target;
4339 context = current_command_context(interp);
4340 assert(context != NULL);
4342 target = get_current_target(context);
4343 if (target == NULL) {
4344 LOG_ERROR("array2mem: no current target");
4345 return JIM_ERR;
4348 return target_array2mem(interp, target, argc-1, argv + 1);
4351 static int target_array2mem(Jim_Interp *interp, struct target *target,
4352 int argc, Jim_Obj *const *argv)
4354 long l;
4355 uint32_t width;
4356 int len;
4357 uint32_t addr;
4358 uint32_t count;
4359 uint32_t v;
4360 const char *varname;
4361 const char *phys;
4362 bool is_phys;
4363 int n, e, retval;
4364 uint32_t i;
4366 /* argv[1] = name of array to get the data
4367 * argv[2] = desired width
4368 * argv[3] = memory address
4369 * argv[4] = count to write
4371 if (argc < 4 || argc > 5) {
4372 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4373 return JIM_ERR;
4375 varname = Jim_GetString(argv[0], &len);
4376 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
4378 e = Jim_GetLong(interp, argv[1], &l);
4379 width = l;
4380 if (e != JIM_OK)
4381 return e;
4383 e = Jim_GetLong(interp, argv[2], &l);
4384 addr = l;
4385 if (e != JIM_OK)
4386 return e;
4387 e = Jim_GetLong(interp, argv[3], &l);
4388 len = l;
4389 if (e != JIM_OK)
4390 return e;
4391 is_phys = false;
4392 if (argc > 4) {
4393 phys = Jim_GetString(argv[4], &n);
4394 if (!strncmp(phys, "phys", n))
4395 is_phys = true;
4396 else
4397 return JIM_ERR;
4399 switch (width) {
4400 case 8:
4401 width = 1;
4402 break;
4403 case 16:
4404 width = 2;
4405 break;
4406 case 32:
4407 width = 4;
4408 break;
4409 default:
4410 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4411 Jim_AppendStrings(interp, Jim_GetResult(interp),
4412 "Invalid width param, must be 8/16/32", NULL);
4413 return JIM_ERR;
4415 if (len == 0) {
4416 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4417 Jim_AppendStrings(interp, Jim_GetResult(interp),
4418 "array2mem: zero width read?", NULL);
4419 return JIM_ERR;
4421 if ((addr + (len * width)) < addr) {
4422 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4423 Jim_AppendStrings(interp, Jim_GetResult(interp),
4424 "array2mem: addr + len - wraps to zero?", NULL);
4425 return JIM_ERR;
4427 /* absurd transfer size? */
4428 if (len > 65536) {
4429 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4430 Jim_AppendStrings(interp, Jim_GetResult(interp),
4431 "array2mem: absurd > 64K item request", NULL);
4432 return JIM_ERR;
4435 if ((width == 1) ||
4436 ((width == 2) && ((addr & 1) == 0)) ||
4437 ((width == 4) && ((addr & 3) == 0))) {
4438 /* all is well */
4439 } else {
4440 char buf[100];
4441 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4442 sprintf(buf, "array2mem address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
4443 addr,
4444 width);
4445 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4446 return JIM_ERR;
4449 /* Transfer loop */
4451 /* index counter */
4452 n = 0;
4453 /* assume ok */
4454 e = JIM_OK;
4456 size_t buffersize = 4096;
4457 uint8_t *buffer = malloc(buffersize);
4458 if (buffer == NULL)
4459 return JIM_ERR;
4461 while (len) {
4462 /* Slurp... in buffer size chunks */
4464 count = len; /* in objects.. */
4465 if (count > (buffersize / width))
4466 count = (buffersize / width);
4468 v = 0; /* shut up gcc */
4469 for (i = 0; i < count; i++, n++) {
4470 get_int_array_element(interp, varname, n, &v);
4471 switch (width) {
4472 case 4:
4473 target_buffer_set_u32(target, &buffer[i * width], v);
4474 break;
4475 case 2:
4476 target_buffer_set_u16(target, &buffer[i * width], v);
4477 break;
4478 case 1:
4479 buffer[i] = v & 0x0ff;
4480 break;
4483 len -= count;
4485 if (is_phys)
4486 retval = target_write_phys_memory(target, addr, width, count, buffer);
4487 else
4488 retval = target_write_memory(target, addr, width, count, buffer);
4489 if (retval != ERROR_OK) {
4490 /* BOO !*/
4491 LOG_ERROR("array2mem: Write @ 0x%08" PRIx32 ", w=%" PRId32 ", cnt=%" PRId32 ", failed",
4492 addr,
4493 width,
4494 count);
4495 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4496 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4497 e = JIM_ERR;
4498 break;
4500 addr += count * width;
4503 free(buffer);
4505 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4507 return e;
4510 /* FIX? should we propagate errors here rather than printing them
4511 * and continuing?
4513 void target_handle_event(struct target *target, enum target_event e)
4515 struct target_event_action *teap;
4517 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4518 if (teap->event == e) {
4519 LOG_DEBUG("target(%d): %s (%s) event: %d (%s) action: %s",
4520 target->target_number,
4521 target_name(target),
4522 target_type_name(target),
4524 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
4525 Jim_GetString(teap->body, NULL));
4527 /* Override current target by the target an event
4528 * is issued from (lot of scripts need it).
4529 * Return back to previous override as soon
4530 * as the handler processing is done */
4531 struct command_context *cmd_ctx = current_command_context(teap->interp);
4532 struct target *saved_target_override = cmd_ctx->current_target_override;
4533 cmd_ctx->current_target_override = target;
4535 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
4536 Jim_MakeErrorMessage(teap->interp);
4537 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
4540 cmd_ctx->current_target_override = saved_target_override;
4546 * Returns true only if the target has a handler for the specified event.
4548 bool target_has_event_action(struct target *target, enum target_event event)
4550 struct target_event_action *teap;
4552 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4553 if (teap->event == event)
4554 return true;
4556 return false;
4559 enum target_cfg_param {
4560 TCFG_TYPE,
4561 TCFG_EVENT,
4562 TCFG_WORK_AREA_VIRT,
4563 TCFG_WORK_AREA_PHYS,
4564 TCFG_WORK_AREA_SIZE,
4565 TCFG_WORK_AREA_BACKUP,
4566 TCFG_ENDIAN,
4567 TCFG_COREID,
4568 TCFG_CHAIN_POSITION,
4569 TCFG_DBGBASE,
4570 TCFG_RTOS,
4571 TCFG_DEFER_EXAMINE,
4572 TCFG_GDB_PORT,
4575 static Jim_Nvp nvp_config_opts[] = {
4576 { .name = "-type", .value = TCFG_TYPE },
4577 { .name = "-event", .value = TCFG_EVENT },
4578 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4579 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4580 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4581 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4582 { .name = "-endian" , .value = TCFG_ENDIAN },
4583 { .name = "-coreid", .value = TCFG_COREID },
4584 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4585 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4586 { .name = "-rtos", .value = TCFG_RTOS },
4587 { .name = "-defer-examine", .value = TCFG_DEFER_EXAMINE },
4588 { .name = "-gdb-port", .value = TCFG_GDB_PORT },
4589 { .name = NULL, .value = -1 }
4592 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
4594 Jim_Nvp *n;
4595 Jim_Obj *o;
4596 jim_wide w;
4597 int e;
4599 /* parse config or cget options ... */
4600 while (goi->argc > 0) {
4601 Jim_SetEmptyResult(goi->interp);
4602 /* Jim_GetOpt_Debug(goi); */
4604 if (target->type->target_jim_configure) {
4605 /* target defines a configure function */
4606 /* target gets first dibs on parameters */
4607 e = (*(target->type->target_jim_configure))(target, goi);
4608 if (e == JIM_OK) {
4609 /* more? */
4610 continue;
4612 if (e == JIM_ERR) {
4613 /* An error */
4614 return e;
4616 /* otherwise we 'continue' below */
4618 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
4619 if (e != JIM_OK) {
4620 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
4621 return e;
4623 switch (n->value) {
4624 case TCFG_TYPE:
4625 /* not setable */
4626 if (goi->isconfigure) {
4627 Jim_SetResultFormatted(goi->interp,
4628 "not settable: %s", n->name);
4629 return JIM_ERR;
4630 } else {
4631 no_params:
4632 if (goi->argc != 0) {
4633 Jim_WrongNumArgs(goi->interp,
4634 goi->argc, goi->argv,
4635 "NO PARAMS");
4636 return JIM_ERR;
4639 Jim_SetResultString(goi->interp,
4640 target_type_name(target), -1);
4641 /* loop for more */
4642 break;
4643 case TCFG_EVENT:
4644 if (goi->argc == 0) {
4645 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4646 return JIM_ERR;
4649 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4650 if (e != JIM_OK) {
4651 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4652 return e;
4655 if (goi->isconfigure) {
4656 if (goi->argc != 1) {
4657 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4658 return JIM_ERR;
4660 } else {
4661 if (goi->argc != 0) {
4662 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4663 return JIM_ERR;
4668 struct target_event_action *teap;
4670 teap = target->event_action;
4671 /* replace existing? */
4672 while (teap) {
4673 if (teap->event == (enum target_event)n->value)
4674 break;
4675 teap = teap->next;
4678 if (goi->isconfigure) {
4679 bool replace = true;
4680 if (teap == NULL) {
4681 /* create new */
4682 teap = calloc(1, sizeof(*teap));
4683 replace = false;
4685 teap->event = n->value;
4686 teap->interp = goi->interp;
4687 Jim_GetOpt_Obj(goi, &o);
4688 if (teap->body)
4689 Jim_DecrRefCount(teap->interp, teap->body);
4690 teap->body = Jim_DuplicateObj(goi->interp, o);
4692 * FIXME:
4693 * Tcl/TK - "tk events" have a nice feature.
4694 * See the "BIND" command.
4695 * We should support that here.
4696 * You can specify %X and %Y in the event code.
4697 * The idea is: %T - target name.
4698 * The idea is: %N - target number
4699 * The idea is: %E - event name.
4701 Jim_IncrRefCount(teap->body);
4703 if (!replace) {
4704 /* add to head of event list */
4705 teap->next = target->event_action;
4706 target->event_action = teap;
4708 Jim_SetEmptyResult(goi->interp);
4709 } else {
4710 /* get */
4711 if (teap == NULL)
4712 Jim_SetEmptyResult(goi->interp);
4713 else
4714 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4717 /* loop for more */
4718 break;
4720 case TCFG_WORK_AREA_VIRT:
4721 if (goi->isconfigure) {
4722 target_free_all_working_areas(target);
4723 e = Jim_GetOpt_Wide(goi, &w);
4724 if (e != JIM_OK)
4725 return e;
4726 target->working_area_virt = w;
4727 target->working_area_virt_spec = true;
4728 } else {
4729 if (goi->argc != 0)
4730 goto no_params;
4732 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4733 /* loop for more */
4734 break;
4736 case TCFG_WORK_AREA_PHYS:
4737 if (goi->isconfigure) {
4738 target_free_all_working_areas(target);
4739 e = Jim_GetOpt_Wide(goi, &w);
4740 if (e != JIM_OK)
4741 return e;
4742 target->working_area_phys = w;
4743 target->working_area_phys_spec = true;
4744 } else {
4745 if (goi->argc != 0)
4746 goto no_params;
4748 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4749 /* loop for more */
4750 break;
4752 case TCFG_WORK_AREA_SIZE:
4753 if (goi->isconfigure) {
4754 target_free_all_working_areas(target);
4755 e = Jim_GetOpt_Wide(goi, &w);
4756 if (e != JIM_OK)
4757 return e;
4758 target->working_area_size = w;
4759 } else {
4760 if (goi->argc != 0)
4761 goto no_params;
4763 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4764 /* loop for more */
4765 break;
4767 case TCFG_WORK_AREA_BACKUP:
4768 if (goi->isconfigure) {
4769 target_free_all_working_areas(target);
4770 e = Jim_GetOpt_Wide(goi, &w);
4771 if (e != JIM_OK)
4772 return e;
4773 /* make this exactly 1 or 0 */
4774 target->backup_working_area = (!!w);
4775 } else {
4776 if (goi->argc != 0)
4777 goto no_params;
4779 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4780 /* loop for more e*/
4781 break;
4784 case TCFG_ENDIAN:
4785 if (goi->isconfigure) {
4786 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4787 if (e != JIM_OK) {
4788 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4789 return e;
4791 target->endianness = n->value;
4792 } else {
4793 if (goi->argc != 0)
4794 goto no_params;
4796 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4797 if (n->name == NULL) {
4798 target->endianness = TARGET_LITTLE_ENDIAN;
4799 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4801 Jim_SetResultString(goi->interp, n->name, -1);
4802 /* loop for more */
4803 break;
4805 case TCFG_COREID:
4806 if (goi->isconfigure) {
4807 e = Jim_GetOpt_Wide(goi, &w);
4808 if (e != JIM_OK)
4809 return e;
4810 target->coreid = (int32_t)w;
4811 } else {
4812 if (goi->argc != 0)
4813 goto no_params;
4815 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4816 /* loop for more */
4817 break;
4819 case TCFG_CHAIN_POSITION:
4820 if (goi->isconfigure) {
4821 Jim_Obj *o_t;
4822 struct jtag_tap *tap;
4824 if (target->has_dap) {
4825 Jim_SetResultString(goi->interp,
4826 "target requires -dap parameter instead of -chain-position!", -1);
4827 return JIM_ERR;
4830 target_free_all_working_areas(target);
4831 e = Jim_GetOpt_Obj(goi, &o_t);
4832 if (e != JIM_OK)
4833 return e;
4834 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4835 if (tap == NULL)
4836 return JIM_ERR;
4837 target->tap = tap;
4838 target->tap_configured = true;
4839 } else {
4840 if (goi->argc != 0)
4841 goto no_params;
4843 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4844 /* loop for more e*/
4845 break;
4846 case TCFG_DBGBASE:
4847 if (goi->isconfigure) {
4848 e = Jim_GetOpt_Wide(goi, &w);
4849 if (e != JIM_OK)
4850 return e;
4851 target->dbgbase = (uint32_t)w;
4852 target->dbgbase_set = true;
4853 } else {
4854 if (goi->argc != 0)
4855 goto no_params;
4857 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4858 /* loop for more */
4859 break;
4860 case TCFG_RTOS:
4861 /* RTOS */
4863 int result = rtos_create(goi, target);
4864 if (result != JIM_OK)
4865 return result;
4867 /* loop for more */
4868 break;
4870 case TCFG_DEFER_EXAMINE:
4871 /* DEFER_EXAMINE */
4872 target->defer_examine = true;
4873 /* loop for more */
4874 break;
4876 case TCFG_GDB_PORT:
4877 if (goi->isconfigure) {
4878 const char *s;
4879 e = Jim_GetOpt_String(goi, &s, NULL);
4880 if (e != JIM_OK)
4881 return e;
4882 target->gdb_port_override = strdup(s);
4883 } else {
4884 if (goi->argc != 0)
4885 goto no_params;
4887 Jim_SetResultString(goi->interp, target->gdb_port_override ? : "undefined", -1);
4888 /* loop for more */
4889 break;
4891 } /* while (goi->argc) */
4894 /* done - we return */
4895 return JIM_OK;
4898 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4900 Jim_GetOptInfo goi;
4902 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4903 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4904 if (goi.argc < 1) {
4905 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4906 "missing: -option ...");
4907 return JIM_ERR;
4909 struct target *target = Jim_CmdPrivData(goi.interp);
4910 return target_configure(&goi, target);
4913 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4915 const char *cmd_name = Jim_GetString(argv[0], NULL);
4917 Jim_GetOptInfo goi;
4918 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4920 if (goi.argc < 2 || goi.argc > 4) {
4921 Jim_SetResultFormatted(goi.interp,
4922 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4923 return JIM_ERR;
4926 target_write_fn fn;
4927 fn = target_write_memory;
4929 int e;
4930 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4931 /* consume it */
4932 struct Jim_Obj *obj;
4933 e = Jim_GetOpt_Obj(&goi, &obj);
4934 if (e != JIM_OK)
4935 return e;
4937 fn = target_write_phys_memory;
4940 jim_wide a;
4941 e = Jim_GetOpt_Wide(&goi, &a);
4942 if (e != JIM_OK)
4943 return e;
4945 jim_wide b;
4946 e = Jim_GetOpt_Wide(&goi, &b);
4947 if (e != JIM_OK)
4948 return e;
4950 jim_wide c = 1;
4951 if (goi.argc == 1) {
4952 e = Jim_GetOpt_Wide(&goi, &c);
4953 if (e != JIM_OK)
4954 return e;
4957 /* all args must be consumed */
4958 if (goi.argc != 0)
4959 return JIM_ERR;
4961 struct target *target = Jim_CmdPrivData(goi.interp);
4962 unsigned data_size;
4963 if (strcasecmp(cmd_name, "mww") == 0)
4964 data_size = 4;
4965 else if (strcasecmp(cmd_name, "mwh") == 0)
4966 data_size = 2;
4967 else if (strcasecmp(cmd_name, "mwb") == 0)
4968 data_size = 1;
4969 else {
4970 LOG_ERROR("command '%s' unknown: ", cmd_name);
4971 return JIM_ERR;
4974 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4978 * @brief Reads an array of words/halfwords/bytes from target memory starting at specified address.
4980 * Usage: mdw [phys] <address> [<count>] - for 32 bit reads
4981 * mdh [phys] <address> [<count>] - for 16 bit reads
4982 * mdb [phys] <address> [<count>] - for 8 bit reads
4984 * Count defaults to 1.
4986 * Calls target_read_memory or target_read_phys_memory depending on
4987 * the presence of the "phys" argument
4988 * Reads the target memory in blocks of max. 32 bytes, and returns an array of ints formatted
4989 * to int representation in base16.
4990 * Also outputs read data in a human readable form using command_print
4992 * @param phys if present target_read_phys_memory will be used instead of target_read_memory
4993 * @param address address where to start the read. May be specified in decimal or hex using the standard "0x" prefix
4994 * @param count optional count parameter to read an array of values. If not specified, defaults to 1.
4995 * @returns: JIM_ERR on error or JIM_OK on success and sets the result string to an array of ascii formatted numbers
4996 * on success, with [<count>] number of elements.
4998 * In case of little endian target:
4999 * Example1: "mdw 0x00000000" returns "10123456"
5000 * Exmaple2: "mdh 0x00000000 1" returns "3456"
5001 * Example3: "mdb 0x00000000" returns "56"
5002 * Example4: "mdh 0x00000000 2" returns "3456 1012"
5003 * Example5: "mdb 0x00000000 3" returns "56 34 12"
5005 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5007 const char *cmd_name = Jim_GetString(argv[0], NULL);
5009 Jim_GetOptInfo goi;
5010 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5012 if ((goi.argc < 1) || (goi.argc > 3)) {
5013 Jim_SetResultFormatted(goi.interp,
5014 "usage: %s [phys] <address> [<count>]", cmd_name);
5015 return JIM_ERR;
5018 int (*fn)(struct target *target,
5019 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer);
5020 fn = target_read_memory;
5022 int e;
5023 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
5024 /* consume it */
5025 struct Jim_Obj *obj;
5026 e = Jim_GetOpt_Obj(&goi, &obj);
5027 if (e != JIM_OK)
5028 return e;
5030 fn = target_read_phys_memory;
5033 /* Read address parameter */
5034 jim_wide addr;
5035 e = Jim_GetOpt_Wide(&goi, &addr);
5036 if (e != JIM_OK)
5037 return JIM_ERR;
5039 /* If next parameter exists, read it out as the count parameter, if not, set it to 1 (default) */
5040 jim_wide count;
5041 if (goi.argc == 1) {
5042 e = Jim_GetOpt_Wide(&goi, &count);
5043 if (e != JIM_OK)
5044 return JIM_ERR;
5045 } else
5046 count = 1;
5048 /* all args must be consumed */
5049 if (goi.argc != 0)
5050 return JIM_ERR;
5052 jim_wide dwidth = 1; /* shut up gcc */
5053 if (strcasecmp(cmd_name, "mdw") == 0)
5054 dwidth = 4;
5055 else if (strcasecmp(cmd_name, "mdh") == 0)
5056 dwidth = 2;
5057 else if (strcasecmp(cmd_name, "mdb") == 0)
5058 dwidth = 1;
5059 else {
5060 LOG_ERROR("command '%s' unknown: ", cmd_name);
5061 return JIM_ERR;
5064 /* convert count to "bytes" */
5065 int bytes = count * dwidth;
5067 struct target *target = Jim_CmdPrivData(goi.interp);
5068 uint8_t target_buf[32];
5069 jim_wide x, y, z;
5070 while (bytes > 0) {
5071 y = (bytes < 16) ? bytes : 16; /* y = min(bytes, 16); */
5073 /* Try to read out next block */
5074 e = fn(target, addr, dwidth, y / dwidth, target_buf);
5076 if (e != ERROR_OK) {
5077 Jim_SetResultFormatted(interp, "error reading target @ 0x%08lx", (long)addr);
5078 return JIM_ERR;
5081 command_print_sameline(NULL, "0x%08x ", (int)(addr));
5082 switch (dwidth) {
5083 case 4:
5084 for (x = 0; x < 16 && x < y; x += 4) {
5085 z = target_buffer_get_u32(target, &(target_buf[x]));
5086 command_print_sameline(NULL, "%08x ", (int)(z));
5088 for (; (x < 16) ; x += 4)
5089 command_print_sameline(NULL, " ");
5090 break;
5091 case 2:
5092 for (x = 0; x < 16 && x < y; x += 2) {
5093 z = target_buffer_get_u16(target, &(target_buf[x]));
5094 command_print_sameline(NULL, "%04x ", (int)(z));
5096 for (; (x < 16) ; x += 2)
5097 command_print_sameline(NULL, " ");
5098 break;
5099 case 1:
5100 default:
5101 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
5102 z = target_buffer_get_u8(target, &(target_buf[x]));
5103 command_print_sameline(NULL, "%02x ", (int)(z));
5105 for (; (x < 16) ; x += 1)
5106 command_print_sameline(NULL, " ");
5107 break;
5109 /* ascii-ify the bytes */
5110 for (x = 0 ; x < y ; x++) {
5111 if ((target_buf[x] >= 0x20) &&
5112 (target_buf[x] <= 0x7e)) {
5113 /* good */
5114 } else {
5115 /* smack it */
5116 target_buf[x] = '.';
5119 /* space pad */
5120 while (x < 16) {
5121 target_buf[x] = ' ';
5122 x++;
5124 /* terminate */
5125 target_buf[16] = 0;
5126 /* print - with a newline */
5127 command_print_sameline(NULL, "%s\n", target_buf);
5128 /* NEXT... */
5129 bytes -= 16;
5130 addr += 16;
5132 return JIM_OK;
5135 static int jim_target_mem2array(Jim_Interp *interp,
5136 int argc, Jim_Obj *const *argv)
5138 struct target *target = Jim_CmdPrivData(interp);
5139 return target_mem2array(interp, target, argc - 1, argv + 1);
5142 static int jim_target_array2mem(Jim_Interp *interp,
5143 int argc, Jim_Obj *const *argv)
5145 struct target *target = Jim_CmdPrivData(interp);
5146 return target_array2mem(interp, target, argc - 1, argv + 1);
5149 static int jim_target_tap_disabled(Jim_Interp *interp)
5151 Jim_SetResultFormatted(interp, "[TAP is disabled]");
5152 return JIM_ERR;
5155 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5157 bool allow_defer = false;
5159 Jim_GetOptInfo goi;
5160 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5161 if (goi.argc > 1) {
5162 const char *cmd_name = Jim_GetString(argv[0], NULL);
5163 Jim_SetResultFormatted(goi.interp,
5164 "usage: %s ['allow-defer']", cmd_name);
5165 return JIM_ERR;
5167 if (goi.argc > 0 &&
5168 strcmp(Jim_GetString(argv[1], NULL), "allow-defer") == 0) {
5169 /* consume it */
5170 struct Jim_Obj *obj;
5171 int e = Jim_GetOpt_Obj(&goi, &obj);
5172 if (e != JIM_OK)
5173 return e;
5174 allow_defer = true;
5177 struct target *target = Jim_CmdPrivData(interp);
5178 if (!target->tap->enabled)
5179 return jim_target_tap_disabled(interp);
5181 if (allow_defer && target->defer_examine) {
5182 LOG_INFO("Deferring arp_examine of %s", target_name(target));
5183 LOG_INFO("Use arp_examine command to examine it manually!");
5184 return JIM_OK;
5187 int e = target->type->examine(target);
5188 if (e != ERROR_OK)
5189 return JIM_ERR;
5190 return JIM_OK;
5193 static int jim_target_was_examined(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5195 struct target *target = Jim_CmdPrivData(interp);
5197 Jim_SetResultBool(interp, target_was_examined(target));
5198 return JIM_OK;
5201 static int jim_target_examine_deferred(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5203 struct target *target = Jim_CmdPrivData(interp);
5205 Jim_SetResultBool(interp, target->defer_examine);
5206 return JIM_OK;
5209 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5211 if (argc != 1) {
5212 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5213 return JIM_ERR;
5215 struct target *target = Jim_CmdPrivData(interp);
5217 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
5218 return JIM_ERR;
5220 return JIM_OK;
5223 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5225 if (argc != 1) {
5226 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5227 return JIM_ERR;
5229 struct target *target = Jim_CmdPrivData(interp);
5230 if (!target->tap->enabled)
5231 return jim_target_tap_disabled(interp);
5233 int e;
5234 if (!(target_was_examined(target)))
5235 e = ERROR_TARGET_NOT_EXAMINED;
5236 else
5237 e = target->type->poll(target);
5238 if (e != ERROR_OK)
5239 return JIM_ERR;
5240 return JIM_OK;
5243 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5245 Jim_GetOptInfo goi;
5246 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5248 if (goi.argc != 2) {
5249 Jim_WrongNumArgs(interp, 0, argv,
5250 "([tT]|[fF]|assert|deassert) BOOL");
5251 return JIM_ERR;
5254 Jim_Nvp *n;
5255 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
5256 if (e != JIM_OK) {
5257 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
5258 return e;
5260 /* the halt or not param */
5261 jim_wide a;
5262 e = Jim_GetOpt_Wide(&goi, &a);
5263 if (e != JIM_OK)
5264 return e;
5266 struct target *target = Jim_CmdPrivData(goi.interp);
5267 if (!target->tap->enabled)
5268 return jim_target_tap_disabled(interp);
5270 if (!target->type->assert_reset || !target->type->deassert_reset) {
5271 Jim_SetResultFormatted(interp,
5272 "No target-specific reset for %s",
5273 target_name(target));
5274 return JIM_ERR;
5277 if (target->defer_examine)
5278 target_reset_examined(target);
5280 /* determine if we should halt or not. */
5281 target->reset_halt = !!a;
5282 /* When this happens - all workareas are invalid. */
5283 target_free_all_working_areas_restore(target, 0);
5285 /* do the assert */
5286 if (n->value == NVP_ASSERT)
5287 e = target->type->assert_reset(target);
5288 else
5289 e = target->type->deassert_reset(target);
5290 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5293 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5295 if (argc != 1) {
5296 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5297 return JIM_ERR;
5299 struct target *target = Jim_CmdPrivData(interp);
5300 if (!target->tap->enabled)
5301 return jim_target_tap_disabled(interp);
5302 int e = target->type->halt(target);
5303 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5306 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5308 Jim_GetOptInfo goi;
5309 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5311 /* params: <name> statename timeoutmsecs */
5312 if (goi.argc != 2) {
5313 const char *cmd_name = Jim_GetString(argv[0], NULL);
5314 Jim_SetResultFormatted(goi.interp,
5315 "%s <state_name> <timeout_in_msec>", cmd_name);
5316 return JIM_ERR;
5319 Jim_Nvp *n;
5320 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
5321 if (e != JIM_OK) {
5322 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
5323 return e;
5325 jim_wide a;
5326 e = Jim_GetOpt_Wide(&goi, &a);
5327 if (e != JIM_OK)
5328 return e;
5329 struct target *target = Jim_CmdPrivData(interp);
5330 if (!target->tap->enabled)
5331 return jim_target_tap_disabled(interp);
5333 e = target_wait_state(target, n->value, a);
5334 if (e != ERROR_OK) {
5335 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
5336 Jim_SetResultFormatted(goi.interp,
5337 "target: %s wait %s fails (%#s) %s",
5338 target_name(target), n->name,
5339 eObj, target_strerror_safe(e));
5340 Jim_FreeNewObj(interp, eObj);
5341 return JIM_ERR;
5343 return JIM_OK;
5345 /* List for human, Events defined for this target.
5346 * scripts/programs should use 'name cget -event NAME'
5348 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5350 struct command_context *cmd_ctx = current_command_context(interp);
5351 assert(cmd_ctx != NULL);
5353 struct target *target = Jim_CmdPrivData(interp);
5354 struct target_event_action *teap = target->event_action;
5355 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
5356 target->target_number,
5357 target_name(target));
5358 command_print(cmd_ctx, "%-25s | Body", "Event");
5359 command_print(cmd_ctx, "------------------------- | "
5360 "----------------------------------------");
5361 while (teap) {
5362 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
5363 command_print(cmd_ctx, "%-25s | %s",
5364 opt->name, Jim_GetString(teap->body, NULL));
5365 teap = teap->next;
5367 command_print(cmd_ctx, "***END***");
5368 return JIM_OK;
5370 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5372 if (argc != 1) {
5373 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5374 return JIM_ERR;
5376 struct target *target = Jim_CmdPrivData(interp);
5377 Jim_SetResultString(interp, target_state_name(target), -1);
5378 return JIM_OK;
5380 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5382 Jim_GetOptInfo goi;
5383 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5384 if (goi.argc != 1) {
5385 const char *cmd_name = Jim_GetString(argv[0], NULL);
5386 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5387 return JIM_ERR;
5389 Jim_Nvp *n;
5390 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
5391 if (e != JIM_OK) {
5392 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
5393 return e;
5395 struct target *target = Jim_CmdPrivData(interp);
5396 target_handle_event(target, n->value);
5397 return JIM_OK;
5400 static const struct command_registration target_instance_command_handlers[] = {
5402 .name = "configure",
5403 .mode = COMMAND_CONFIG,
5404 .jim_handler = jim_target_configure,
5405 .help = "configure a new target for use",
5406 .usage = "[target_attribute ...]",
5409 .name = "cget",
5410 .mode = COMMAND_ANY,
5411 .jim_handler = jim_target_configure,
5412 .help = "returns the specified target attribute",
5413 .usage = "target_attribute",
5416 .name = "mww",
5417 .mode = COMMAND_EXEC,
5418 .jim_handler = jim_target_mw,
5419 .help = "Write 32-bit word(s) to target memory",
5420 .usage = "address data [count]",
5423 .name = "mwh",
5424 .mode = COMMAND_EXEC,
5425 .jim_handler = jim_target_mw,
5426 .help = "Write 16-bit half-word(s) to target memory",
5427 .usage = "address data [count]",
5430 .name = "mwb",
5431 .mode = COMMAND_EXEC,
5432 .jim_handler = jim_target_mw,
5433 .help = "Write byte(s) to target memory",
5434 .usage = "address data [count]",
5437 .name = "mdw",
5438 .mode = COMMAND_EXEC,
5439 .jim_handler = jim_target_md,
5440 .help = "Display target memory as 32-bit words",
5441 .usage = "address [count]",
5444 .name = "mdh",
5445 .mode = COMMAND_EXEC,
5446 .jim_handler = jim_target_md,
5447 .help = "Display target memory as 16-bit half-words",
5448 .usage = "address [count]",
5451 .name = "mdb",
5452 .mode = COMMAND_EXEC,
5453 .jim_handler = jim_target_md,
5454 .help = "Display target memory as 8-bit bytes",
5455 .usage = "address [count]",
5458 .name = "array2mem",
5459 .mode = COMMAND_EXEC,
5460 .jim_handler = jim_target_array2mem,
5461 .help = "Writes Tcl array of 8/16/32 bit numbers "
5462 "to target memory",
5463 .usage = "arrayname bitwidth address count",
5466 .name = "mem2array",
5467 .mode = COMMAND_EXEC,
5468 .jim_handler = jim_target_mem2array,
5469 .help = "Loads Tcl array of 8/16/32 bit numbers "
5470 "from target memory",
5471 .usage = "arrayname bitwidth address count",
5474 .name = "eventlist",
5475 .mode = COMMAND_EXEC,
5476 .jim_handler = jim_target_event_list,
5477 .help = "displays a table of events defined for this target",
5480 .name = "curstate",
5481 .mode = COMMAND_EXEC,
5482 .jim_handler = jim_target_current_state,
5483 .help = "displays the current state of this target",
5486 .name = "arp_examine",
5487 .mode = COMMAND_EXEC,
5488 .jim_handler = jim_target_examine,
5489 .help = "used internally for reset processing",
5490 .usage = "['allow-defer']",
5493 .name = "was_examined",
5494 .mode = COMMAND_EXEC,
5495 .jim_handler = jim_target_was_examined,
5496 .help = "used internally for reset processing",
5499 .name = "examine_deferred",
5500 .mode = COMMAND_EXEC,
5501 .jim_handler = jim_target_examine_deferred,
5502 .help = "used internally for reset processing",
5505 .name = "arp_halt_gdb",
5506 .mode = COMMAND_EXEC,
5507 .jim_handler = jim_target_halt_gdb,
5508 .help = "used internally for reset processing to halt GDB",
5511 .name = "arp_poll",
5512 .mode = COMMAND_EXEC,
5513 .jim_handler = jim_target_poll,
5514 .help = "used internally for reset processing",
5517 .name = "arp_reset",
5518 .mode = COMMAND_EXEC,
5519 .jim_handler = jim_target_reset,
5520 .help = "used internally for reset processing",
5523 .name = "arp_halt",
5524 .mode = COMMAND_EXEC,
5525 .jim_handler = jim_target_halt,
5526 .help = "used internally for reset processing",
5529 .name = "arp_waitstate",
5530 .mode = COMMAND_EXEC,
5531 .jim_handler = jim_target_wait_state,
5532 .help = "used internally for reset processing",
5535 .name = "invoke-event",
5536 .mode = COMMAND_EXEC,
5537 .jim_handler = jim_target_invoke_event,
5538 .help = "invoke handler for specified event",
5539 .usage = "event_name",
5541 COMMAND_REGISTRATION_DONE
5544 static int target_create(Jim_GetOptInfo *goi)
5546 Jim_Obj *new_cmd;
5547 Jim_Cmd *cmd;
5548 const char *cp;
5549 int e;
5550 int x;
5551 struct target *target;
5552 struct command_context *cmd_ctx;
5554 cmd_ctx = current_command_context(goi->interp);
5555 assert(cmd_ctx != NULL);
5557 if (goi->argc < 3) {
5558 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5559 return JIM_ERR;
5562 /* COMMAND */
5563 Jim_GetOpt_Obj(goi, &new_cmd);
5564 /* does this command exist? */
5565 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
5566 if (cmd) {
5567 cp = Jim_GetString(new_cmd, NULL);
5568 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5569 return JIM_ERR;
5572 /* TYPE */
5573 e = Jim_GetOpt_String(goi, &cp, NULL);
5574 if (e != JIM_OK)
5575 return e;
5576 struct transport *tr = get_current_transport();
5577 if (tr->override_target) {
5578 e = tr->override_target(&cp);
5579 if (e != ERROR_OK) {
5580 LOG_ERROR("The selected transport doesn't support this target");
5581 return JIM_ERR;
5583 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5585 /* now does target type exist */
5586 for (x = 0 ; target_types[x] ; x++) {
5587 if (0 == strcmp(cp, target_types[x]->name)) {
5588 /* found */
5589 break;
5592 /* check for deprecated name */
5593 if (target_types[x]->deprecated_name) {
5594 if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
5595 /* found */
5596 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
5597 break;
5601 if (target_types[x] == NULL) {
5602 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5603 for (x = 0 ; target_types[x] ; x++) {
5604 if (target_types[x + 1]) {
5605 Jim_AppendStrings(goi->interp,
5606 Jim_GetResult(goi->interp),
5607 target_types[x]->name,
5608 ", ", NULL);
5609 } else {
5610 Jim_AppendStrings(goi->interp,
5611 Jim_GetResult(goi->interp),
5612 " or ",
5613 target_types[x]->name, NULL);
5616 return JIM_ERR;
5619 /* Create it */
5620 target = calloc(1, sizeof(struct target));
5621 /* set target number */
5622 target->target_number = new_target_number();
5623 cmd_ctx->current_target = target;
5625 /* allocate memory for each unique target type */
5626 target->type = calloc(1, sizeof(struct target_type));
5628 memcpy(target->type, target_types[x], sizeof(struct target_type));
5630 /* will be set by "-endian" */
5631 target->endianness = TARGET_ENDIAN_UNKNOWN;
5633 /* default to first core, override with -coreid */
5634 target->coreid = 0;
5636 target->working_area = 0x0;
5637 target->working_area_size = 0x0;
5638 target->working_areas = NULL;
5639 target->backup_working_area = 0;
5641 target->state = TARGET_UNKNOWN;
5642 target->debug_reason = DBG_REASON_UNDEFINED;
5643 target->reg_cache = NULL;
5644 target->breakpoints = NULL;
5645 target->watchpoints = NULL;
5646 target->next = NULL;
5647 target->arch_info = NULL;
5649 target->verbose_halt_msg = true;
5651 target->halt_issued = false;
5653 /* initialize trace information */
5654 target->trace_info = calloc(1, sizeof(struct trace));
5656 target->dbgmsg = NULL;
5657 target->dbg_msg_enabled = 0;
5659 target->endianness = TARGET_ENDIAN_UNKNOWN;
5661 target->rtos = NULL;
5662 target->rtos_auto_detect = false;
5664 target->gdb_port_override = NULL;
5666 /* Do the rest as "configure" options */
5667 goi->isconfigure = 1;
5668 e = target_configure(goi, target);
5670 if (e == JIM_OK) {
5671 if (target->has_dap) {
5672 if (!target->dap_configured) {
5673 Jim_SetResultString(goi->interp, "-dap ?name? required when creating target", -1);
5674 e = JIM_ERR;
5676 } else {
5677 if (!target->tap_configured) {
5678 Jim_SetResultString(goi->interp, "-chain-position ?name? required when creating target", -1);
5679 e = JIM_ERR;
5682 /* tap must be set after target was configured */
5683 if (target->tap == NULL)
5684 e = JIM_ERR;
5687 if (e != JIM_OK) {
5688 free(target->gdb_port_override);
5689 free(target->type);
5690 free(target);
5691 return e;
5694 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5695 /* default endian to little if not specified */
5696 target->endianness = TARGET_LITTLE_ENDIAN;
5699 cp = Jim_GetString(new_cmd, NULL);
5700 target->cmd_name = strdup(cp);
5702 if (target->type->target_create) {
5703 e = (*(target->type->target_create))(target, goi->interp);
5704 if (e != ERROR_OK) {
5705 LOG_DEBUG("target_create failed");
5706 free(target->gdb_port_override);
5707 free(target->type);
5708 free(target->cmd_name);
5709 free(target);
5710 return JIM_ERR;
5714 /* create the target specific commands */
5715 if (target->type->commands) {
5716 e = register_commands(cmd_ctx, NULL, target->type->commands);
5717 if (ERROR_OK != e)
5718 LOG_ERROR("unable to register '%s' commands", cp);
5721 /* append to end of list */
5723 struct target **tpp;
5724 tpp = &(all_targets);
5725 while (*tpp)
5726 tpp = &((*tpp)->next);
5727 *tpp = target;
5730 /* now - create the new target name command */
5731 const struct command_registration target_subcommands[] = {
5733 .chain = target_instance_command_handlers,
5736 .chain = target->type->commands,
5738 COMMAND_REGISTRATION_DONE
5740 const struct command_registration target_commands[] = {
5742 .name = cp,
5743 .mode = COMMAND_ANY,
5744 .help = "target command group",
5745 .usage = "",
5746 .chain = target_subcommands,
5748 COMMAND_REGISTRATION_DONE
5750 e = register_commands(cmd_ctx, NULL, target_commands);
5751 if (ERROR_OK != e)
5752 return JIM_ERR;
5754 struct command *c = command_find_in_context(cmd_ctx, cp);
5755 assert(c);
5756 command_set_handler_data(c, target);
5758 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5761 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5763 if (argc != 1) {
5764 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5765 return JIM_ERR;
5767 struct command_context *cmd_ctx = current_command_context(interp);
5768 assert(cmd_ctx != NULL);
5770 Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5771 return JIM_OK;
5774 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5776 if (argc != 1) {
5777 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5778 return JIM_ERR;
5780 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5781 for (unsigned x = 0; NULL != target_types[x]; x++) {
5782 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5783 Jim_NewStringObj(interp, target_types[x]->name, -1));
5785 return JIM_OK;
5788 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5790 if (argc != 1) {
5791 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5792 return JIM_ERR;
5794 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5795 struct target *target = all_targets;
5796 while (target) {
5797 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5798 Jim_NewStringObj(interp, target_name(target), -1));
5799 target = target->next;
5801 return JIM_OK;
5804 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5806 int i;
5807 const char *targetname;
5808 int retval, len;
5809 struct target *target = (struct target *) NULL;
5810 struct target_list *head, *curr, *new;
5811 curr = (struct target_list *) NULL;
5812 head = (struct target_list *) NULL;
5814 retval = 0;
5815 LOG_DEBUG("%d", argc);
5816 /* argv[1] = target to associate in smp
5817 * argv[2] = target to assoicate in smp
5818 * argv[3] ...
5821 for (i = 1; i < argc; i++) {
5823 targetname = Jim_GetString(argv[i], &len);
5824 target = get_target(targetname);
5825 LOG_DEBUG("%s ", targetname);
5826 if (target) {
5827 new = malloc(sizeof(struct target_list));
5828 new->target = target;
5829 new->next = (struct target_list *)NULL;
5830 if (head == (struct target_list *)NULL) {
5831 head = new;
5832 curr = head;
5833 } else {
5834 curr->next = new;
5835 curr = new;
5839 /* now parse the list of cpu and put the target in smp mode*/
5840 curr = head;
5842 while (curr != (struct target_list *)NULL) {
5843 target = curr->target;
5844 target->smp = 1;
5845 target->head = head;
5846 curr = curr->next;
5849 if (target && target->rtos)
5850 retval = rtos_smp_init(head->target);
5852 return retval;
5856 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5858 Jim_GetOptInfo goi;
5859 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5860 if (goi.argc < 3) {
5861 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5862 "<name> <target_type> [<target_options> ...]");
5863 return JIM_ERR;
5865 return target_create(&goi);
5868 static const struct command_registration target_subcommand_handlers[] = {
5870 .name = "init",
5871 .mode = COMMAND_CONFIG,
5872 .handler = handle_target_init_command,
5873 .help = "initialize targets",
5876 .name = "create",
5877 /* REVISIT this should be COMMAND_CONFIG ... */
5878 .mode = COMMAND_ANY,
5879 .jim_handler = jim_target_create,
5880 .usage = "name type '-chain-position' name [options ...]",
5881 .help = "Creates and selects a new target",
5884 .name = "current",
5885 .mode = COMMAND_ANY,
5886 .jim_handler = jim_target_current,
5887 .help = "Returns the currently selected target",
5890 .name = "types",
5891 .mode = COMMAND_ANY,
5892 .jim_handler = jim_target_types,
5893 .help = "Returns the available target types as "
5894 "a list of strings",
5897 .name = "names",
5898 .mode = COMMAND_ANY,
5899 .jim_handler = jim_target_names,
5900 .help = "Returns the names of all targets as a list of strings",
5903 .name = "smp",
5904 .mode = COMMAND_ANY,
5905 .jim_handler = jim_target_smp,
5906 .usage = "targetname1 targetname2 ...",
5907 .help = "gather several target in a smp list"
5910 COMMAND_REGISTRATION_DONE
5913 struct FastLoad {
5914 target_addr_t address;
5915 uint8_t *data;
5916 int length;
5920 static int fastload_num;
5921 static struct FastLoad *fastload;
5923 static void free_fastload(void)
5925 if (fastload != NULL) {
5926 int i;
5927 for (i = 0; i < fastload_num; i++) {
5928 if (fastload[i].data)
5929 free(fastload[i].data);
5931 free(fastload);
5932 fastload = NULL;
5936 COMMAND_HANDLER(handle_fast_load_image_command)
5938 uint8_t *buffer;
5939 size_t buf_cnt;
5940 uint32_t image_size;
5941 target_addr_t min_address = 0;
5942 target_addr_t max_address = -1;
5943 int i;
5945 struct image image;
5947 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5948 &image, &min_address, &max_address);
5949 if (ERROR_OK != retval)
5950 return retval;
5952 struct duration bench;
5953 duration_start(&bench);
5955 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5956 if (retval != ERROR_OK)
5957 return retval;
5959 image_size = 0x0;
5960 retval = ERROR_OK;
5961 fastload_num = image.num_sections;
5962 fastload = malloc(sizeof(struct FastLoad)*image.num_sections);
5963 if (fastload == NULL) {
5964 command_print(CMD_CTX, "out of memory");
5965 image_close(&image);
5966 return ERROR_FAIL;
5968 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5969 for (i = 0; i < image.num_sections; i++) {
5970 buffer = malloc(image.sections[i].size);
5971 if (buffer == NULL) {
5972 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5973 (int)(image.sections[i].size));
5974 retval = ERROR_FAIL;
5975 break;
5978 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5979 if (retval != ERROR_OK) {
5980 free(buffer);
5981 break;
5984 uint32_t offset = 0;
5985 uint32_t length = buf_cnt;
5987 /* DANGER!!! beware of unsigned comparision here!!! */
5989 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5990 (image.sections[i].base_address < max_address)) {
5991 if (image.sections[i].base_address < min_address) {
5992 /* clip addresses below */
5993 offset += min_address-image.sections[i].base_address;
5994 length -= offset;
5997 if (image.sections[i].base_address + buf_cnt > max_address)
5998 length -= (image.sections[i].base_address + buf_cnt)-max_address;
6000 fastload[i].address = image.sections[i].base_address + offset;
6001 fastload[i].data = malloc(length);
6002 if (fastload[i].data == NULL) {
6003 free(buffer);
6004 command_print(CMD_CTX, "error allocating buffer for section (%" PRIu32 " bytes)",
6005 length);
6006 retval = ERROR_FAIL;
6007 break;
6009 memcpy(fastload[i].data, buffer + offset, length);
6010 fastload[i].length = length;
6012 image_size += length;
6013 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
6014 (unsigned int)length,
6015 ((unsigned int)(image.sections[i].base_address + offset)));
6018 free(buffer);
6021 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
6022 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
6023 "in %fs (%0.3f KiB/s)", image_size,
6024 duration_elapsed(&bench), duration_kbps(&bench, image_size));
6026 command_print(CMD_CTX,
6027 "WARNING: image has not been loaded to target!"
6028 "You can issue a 'fast_load' to finish loading.");
6031 image_close(&image);
6033 if (retval != ERROR_OK)
6034 free_fastload();
6036 return retval;
6039 COMMAND_HANDLER(handle_fast_load_command)
6041 if (CMD_ARGC > 0)
6042 return ERROR_COMMAND_SYNTAX_ERROR;
6043 if (fastload == NULL) {
6044 LOG_ERROR("No image in memory");
6045 return ERROR_FAIL;
6047 int i;
6048 int64_t ms = timeval_ms();
6049 int size = 0;
6050 int retval = ERROR_OK;
6051 for (i = 0; i < fastload_num; i++) {
6052 struct target *target = get_current_target(CMD_CTX);
6053 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
6054 (unsigned int)(fastload[i].address),
6055 (unsigned int)(fastload[i].length));
6056 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
6057 if (retval != ERROR_OK)
6058 break;
6059 size += fastload[i].length;
6061 if (retval == ERROR_OK) {
6062 int64_t after = timeval_ms();
6063 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
6065 return retval;
6068 static const struct command_registration target_command_handlers[] = {
6070 .name = "targets",
6071 .handler = handle_targets_command,
6072 .mode = COMMAND_ANY,
6073 .help = "change current default target (one parameter) "
6074 "or prints table of all targets (no parameters)",
6075 .usage = "[target]",
6078 .name = "target",
6079 .mode = COMMAND_CONFIG,
6080 .help = "configure target",
6082 .chain = target_subcommand_handlers,
6084 COMMAND_REGISTRATION_DONE
6087 int target_register_commands(struct command_context *cmd_ctx)
6089 return register_commands(cmd_ctx, NULL, target_command_handlers);
6092 static bool target_reset_nag = true;
6094 bool get_target_reset_nag(void)
6096 return target_reset_nag;
6099 COMMAND_HANDLER(handle_target_reset_nag)
6101 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
6102 &target_reset_nag, "Nag after each reset about options to improve "
6103 "performance");
6106 COMMAND_HANDLER(handle_ps_command)
6108 struct target *target = get_current_target(CMD_CTX);
6109 char *display;
6110 if (target->state != TARGET_HALTED) {
6111 LOG_INFO("target not halted !!");
6112 return ERROR_OK;
6115 if ((target->rtos) && (target->rtos->type)
6116 && (target->rtos->type->ps_command)) {
6117 display = target->rtos->type->ps_command(target);
6118 command_print(CMD_CTX, "%s", display);
6119 free(display);
6120 return ERROR_OK;
6121 } else {
6122 LOG_INFO("failed");
6123 return ERROR_TARGET_FAILURE;
6127 static void binprint(struct command_context *cmd_ctx, const char *text, const uint8_t *buf, int size)
6129 if (text != NULL)
6130 command_print_sameline(cmd_ctx, "%s", text);
6131 for (int i = 0; i < size; i++)
6132 command_print_sameline(cmd_ctx, " %02x", buf[i]);
6133 command_print(cmd_ctx, " ");
6136 COMMAND_HANDLER(handle_test_mem_access_command)
6138 struct target *target = get_current_target(CMD_CTX);
6139 uint32_t test_size;
6140 int retval = ERROR_OK;
6142 if (target->state != TARGET_HALTED) {
6143 LOG_INFO("target not halted !!");
6144 return ERROR_FAIL;
6147 if (CMD_ARGC != 1)
6148 return ERROR_COMMAND_SYNTAX_ERROR;
6150 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
6152 /* Test reads */
6153 size_t num_bytes = test_size + 4;
6155 struct working_area *wa = NULL;
6156 retval = target_alloc_working_area(target, num_bytes, &wa);
6157 if (retval != ERROR_OK) {
6158 LOG_ERROR("Not enough working area");
6159 return ERROR_FAIL;
6162 uint8_t *test_pattern = malloc(num_bytes);
6164 for (size_t i = 0; i < num_bytes; i++)
6165 test_pattern[i] = rand();
6167 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6168 if (retval != ERROR_OK) {
6169 LOG_ERROR("Test pattern write failed");
6170 goto out;
6173 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6174 for (int size = 1; size <= 4; size *= 2) {
6175 for (int offset = 0; offset < 4; offset++) {
6176 uint32_t count = test_size / size;
6177 size_t host_bufsiz = (count + 2) * size + host_offset;
6178 uint8_t *read_ref = malloc(host_bufsiz);
6179 uint8_t *read_buf = malloc(host_bufsiz);
6181 for (size_t i = 0; i < host_bufsiz; i++) {
6182 read_ref[i] = rand();
6183 read_buf[i] = read_ref[i];
6185 command_print_sameline(CMD_CTX,
6186 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
6187 size, offset, host_offset ? "un" : "");
6189 struct duration bench;
6190 duration_start(&bench);
6192 retval = target_read_memory(target, wa->address + offset, size, count,
6193 read_buf + size + host_offset);
6195 duration_measure(&bench);
6197 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6198 command_print(CMD_CTX, "Unsupported alignment");
6199 goto next;
6200 } else if (retval != ERROR_OK) {
6201 command_print(CMD_CTX, "Memory read failed");
6202 goto next;
6205 /* replay on host */
6206 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
6208 /* check result */
6209 int result = memcmp(read_ref, read_buf, host_bufsiz);
6210 if (result == 0) {
6211 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
6212 duration_elapsed(&bench),
6213 duration_kbps(&bench, count * size));
6214 } else {
6215 command_print(CMD_CTX, "Compare failed");
6216 binprint(CMD_CTX, "ref:", read_ref, host_bufsiz);
6217 binprint(CMD_CTX, "buf:", read_buf, host_bufsiz);
6219 next:
6220 free(read_ref);
6221 free(read_buf);
6226 out:
6227 free(test_pattern);
6229 if (wa != NULL)
6230 target_free_working_area(target, wa);
6232 /* Test writes */
6233 num_bytes = test_size + 4 + 4 + 4;
6235 retval = target_alloc_working_area(target, num_bytes, &wa);
6236 if (retval != ERROR_OK) {
6237 LOG_ERROR("Not enough working area");
6238 return ERROR_FAIL;
6241 test_pattern = malloc(num_bytes);
6243 for (size_t i = 0; i < num_bytes; i++)
6244 test_pattern[i] = rand();
6246 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6247 for (int size = 1; size <= 4; size *= 2) {
6248 for (int offset = 0; offset < 4; offset++) {
6249 uint32_t count = test_size / size;
6250 size_t host_bufsiz = count * size + host_offset;
6251 uint8_t *read_ref = malloc(num_bytes);
6252 uint8_t *read_buf = malloc(num_bytes);
6253 uint8_t *write_buf = malloc(host_bufsiz);
6255 for (size_t i = 0; i < host_bufsiz; i++)
6256 write_buf[i] = rand();
6257 command_print_sameline(CMD_CTX,
6258 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
6259 size, offset, host_offset ? "un" : "");
6261 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6262 if (retval != ERROR_OK) {
6263 command_print(CMD_CTX, "Test pattern write failed");
6264 goto nextw;
6267 /* replay on host */
6268 memcpy(read_ref, test_pattern, num_bytes);
6269 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
6271 struct duration bench;
6272 duration_start(&bench);
6274 retval = target_write_memory(target, wa->address + size + offset, size, count,
6275 write_buf + host_offset);
6277 duration_measure(&bench);
6279 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6280 command_print(CMD_CTX, "Unsupported alignment");
6281 goto nextw;
6282 } else if (retval != ERROR_OK) {
6283 command_print(CMD_CTX, "Memory write failed");
6284 goto nextw;
6287 /* read back */
6288 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
6289 if (retval != ERROR_OK) {
6290 command_print(CMD_CTX, "Test pattern write failed");
6291 goto nextw;
6294 /* check result */
6295 int result = memcmp(read_ref, read_buf, num_bytes);
6296 if (result == 0) {
6297 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
6298 duration_elapsed(&bench),
6299 duration_kbps(&bench, count * size));
6300 } else {
6301 command_print(CMD_CTX, "Compare failed");
6302 binprint(CMD_CTX, "ref:", read_ref, num_bytes);
6303 binprint(CMD_CTX, "buf:", read_buf, num_bytes);
6305 nextw:
6306 free(read_ref);
6307 free(read_buf);
6312 free(test_pattern);
6314 if (wa != NULL)
6315 target_free_working_area(target, wa);
6316 return retval;
6319 static const struct command_registration target_exec_command_handlers[] = {
6321 .name = "fast_load_image",
6322 .handler = handle_fast_load_image_command,
6323 .mode = COMMAND_ANY,
6324 .help = "Load image into server memory for later use by "
6325 "fast_load; primarily for profiling",
6326 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6327 "[min_address [max_length]]",
6330 .name = "fast_load",
6331 .handler = handle_fast_load_command,
6332 .mode = COMMAND_EXEC,
6333 .help = "loads active fast load image to current target "
6334 "- mainly for profiling purposes",
6335 .usage = "",
6338 .name = "profile",
6339 .handler = handle_profile_command,
6340 .mode = COMMAND_EXEC,
6341 .usage = "seconds filename [start end]",
6342 .help = "profiling samples the CPU PC",
6344 /** @todo don't register virt2phys() unless target supports it */
6346 .name = "virt2phys",
6347 .handler = handle_virt2phys_command,
6348 .mode = COMMAND_ANY,
6349 .help = "translate a virtual address into a physical address",
6350 .usage = "virtual_address",
6353 .name = "reg",
6354 .handler = handle_reg_command,
6355 .mode = COMMAND_EXEC,
6356 .help = "display (reread from target with \"force\") or set a register; "
6357 "with no arguments, displays all registers and their values",
6358 .usage = "[(register_number|register_name) [(value|'force')]]",
6361 .name = "poll",
6362 .handler = handle_poll_command,
6363 .mode = COMMAND_EXEC,
6364 .help = "poll target state; or reconfigure background polling",
6365 .usage = "['on'|'off']",
6368 .name = "wait_halt",
6369 .handler = handle_wait_halt_command,
6370 .mode = COMMAND_EXEC,
6371 .help = "wait up to the specified number of milliseconds "
6372 "(default 5000) for a previously requested halt",
6373 .usage = "[milliseconds]",
6376 .name = "halt",
6377 .handler = handle_halt_command,
6378 .mode = COMMAND_EXEC,
6379 .help = "request target to halt, then wait up to the specified"
6380 "number of milliseconds (default 5000) for it to complete",
6381 .usage = "[milliseconds]",
6384 .name = "resume",
6385 .handler = handle_resume_command,
6386 .mode = COMMAND_EXEC,
6387 .help = "resume target execution from current PC or address",
6388 .usage = "[address]",
6391 .name = "reset",
6392 .handler = handle_reset_command,
6393 .mode = COMMAND_EXEC,
6394 .usage = "[run|halt|init]",
6395 .help = "Reset all targets into the specified mode."
6396 "Default reset mode is run, if not given.",
6399 .name = "soft_reset_halt",
6400 .handler = handle_soft_reset_halt_command,
6401 .mode = COMMAND_EXEC,
6402 .usage = "",
6403 .help = "halt the target and do a soft reset",
6406 .name = "step",
6407 .handler = handle_step_command,
6408 .mode = COMMAND_EXEC,
6409 .help = "step one instruction from current PC or address",
6410 .usage = "[address]",
6413 .name = "mdd",
6414 .handler = handle_md_command,
6415 .mode = COMMAND_EXEC,
6416 .help = "display memory words",
6417 .usage = "['phys'] address [count]",
6420 .name = "mdw",
6421 .handler = handle_md_command,
6422 .mode = COMMAND_EXEC,
6423 .help = "display memory words",
6424 .usage = "['phys'] address [count]",
6427 .name = "mdh",
6428 .handler = handle_md_command,
6429 .mode = COMMAND_EXEC,
6430 .help = "display memory half-words",
6431 .usage = "['phys'] address [count]",
6434 .name = "mdb",
6435 .handler = handle_md_command,
6436 .mode = COMMAND_EXEC,
6437 .help = "display memory bytes",
6438 .usage = "['phys'] address [count]",
6441 .name = "mwd",
6442 .handler = handle_mw_command,
6443 .mode = COMMAND_EXEC,
6444 .help = "write memory word",
6445 .usage = "['phys'] address value [count]",
6448 .name = "mww",
6449 .handler = handle_mw_command,
6450 .mode = COMMAND_EXEC,
6451 .help = "write memory word",
6452 .usage = "['phys'] address value [count]",
6455 .name = "mwh",
6456 .handler = handle_mw_command,
6457 .mode = COMMAND_EXEC,
6458 .help = "write memory half-word",
6459 .usage = "['phys'] address value [count]",
6462 .name = "mwb",
6463 .handler = handle_mw_command,
6464 .mode = COMMAND_EXEC,
6465 .help = "write memory byte",
6466 .usage = "['phys'] address value [count]",
6469 .name = "bp",
6470 .handler = handle_bp_command,
6471 .mode = COMMAND_EXEC,
6472 .help = "list or set hardware or software breakpoint",
6473 .usage = "<address> [<asid>] <length> ['hw'|'hw_ctx']",
6476 .name = "rbp",
6477 .handler = handle_rbp_command,
6478 .mode = COMMAND_EXEC,
6479 .help = "remove breakpoint",
6480 .usage = "address",
6483 .name = "wp",
6484 .handler = handle_wp_command,
6485 .mode = COMMAND_EXEC,
6486 .help = "list (no params) or create watchpoints",
6487 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
6490 .name = "rwp",
6491 .handler = handle_rwp_command,
6492 .mode = COMMAND_EXEC,
6493 .help = "remove watchpoint",
6494 .usage = "address",
6497 .name = "load_image",
6498 .handler = handle_load_image_command,
6499 .mode = COMMAND_EXEC,
6500 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6501 "[min_address] [max_length]",
6504 .name = "dump_image",
6505 .handler = handle_dump_image_command,
6506 .mode = COMMAND_EXEC,
6507 .usage = "filename address size",
6510 .name = "verify_image_checksum",
6511 .handler = handle_verify_image_checksum_command,
6512 .mode = COMMAND_EXEC,
6513 .usage = "filename [offset [type]]",
6516 .name = "verify_image",
6517 .handler = handle_verify_image_command,
6518 .mode = COMMAND_EXEC,
6519 .usage = "filename [offset [type]]",
6522 .name = "test_image",
6523 .handler = handle_test_image_command,
6524 .mode = COMMAND_EXEC,
6525 .usage = "filename [offset [type]]",
6528 .name = "mem2array",
6529 .mode = COMMAND_EXEC,
6530 .jim_handler = jim_mem2array,
6531 .help = "read 8/16/32 bit memory and return as a TCL array "
6532 "for script processing",
6533 .usage = "arrayname bitwidth address count",
6536 .name = "array2mem",
6537 .mode = COMMAND_EXEC,
6538 .jim_handler = jim_array2mem,
6539 .help = "convert a TCL array to memory locations "
6540 "and write the 8/16/32 bit values",
6541 .usage = "arrayname bitwidth address count",
6544 .name = "reset_nag",
6545 .handler = handle_target_reset_nag,
6546 .mode = COMMAND_ANY,
6547 .help = "Nag after each reset about options that could have been "
6548 "enabled to improve performance. ",
6549 .usage = "['enable'|'disable']",
6552 .name = "ps",
6553 .handler = handle_ps_command,
6554 .mode = COMMAND_EXEC,
6555 .help = "list all tasks ",
6556 .usage = " ",
6559 .name = "test_mem_access",
6560 .handler = handle_test_mem_access_command,
6561 .mode = COMMAND_EXEC,
6562 .help = "Test the target's memory access functions",
6563 .usage = "size",
6566 COMMAND_REGISTRATION_DONE
6568 static int target_register_user_commands(struct command_context *cmd_ctx)
6570 int retval = ERROR_OK;
6571 retval = target_request_register_commands(cmd_ctx);
6572 if (retval != ERROR_OK)
6573 return retval;
6575 retval = trace_register_commands(cmd_ctx);
6576 if (retval != ERROR_OK)
6577 return retval;
6580 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);