avoid segfaulting when attempting to set an unavailable type of breackpoint
[openocd.git] / src / target / target.c
blobaf5c5b93737ce03a4701fc300c70286a3adacb87
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, write to the *
38 * Free Software Foundation, Inc., *
39 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
40 ***************************************************************************/
42 #ifdef HAVE_CONFIG_H
43 #include "config.h"
44 #endif
46 #include <helper/time_support.h>
47 #include <jtag/jtag.h>
48 #include <flash/nor/core.h>
50 #include "target.h"
51 #include "target_type.h"
52 #include "target_request.h"
53 #include "breakpoints.h"
54 #include "register.h"
55 #include "trace.h"
56 #include "image.h"
57 #include "rtos/rtos.h"
58 #include "transport/transport.h"
60 /* default halt wait timeout (ms) */
61 #define DEFAULT_HALT_TIMEOUT 5000
63 static int target_read_buffer_default(struct target *target, uint32_t address,
64 uint32_t count, uint8_t *buffer);
65 static int target_write_buffer_default(struct target *target, uint32_t address,
66 uint32_t count, const uint8_t *buffer);
67 static int target_array2mem(Jim_Interp *interp, struct target *target,
68 int argc, Jim_Obj * const *argv);
69 static int target_mem2array(Jim_Interp *interp, struct target *target,
70 int argc, Jim_Obj * const *argv);
71 static int target_register_user_commands(struct command_context *cmd_ctx);
72 static int target_get_gdb_fileio_info_default(struct target *target,
73 struct gdb_fileio_info *fileio_info);
74 static int target_gdb_fileio_end_default(struct target *target, int retcode,
75 int fileio_errno, bool ctrl_c);
76 static int target_profiling_default(struct target *target, uint32_t *samples,
77 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds);
79 /* targets */
80 extern struct target_type arm7tdmi_target;
81 extern struct target_type arm720t_target;
82 extern struct target_type arm9tdmi_target;
83 extern struct target_type arm920t_target;
84 extern struct target_type arm966e_target;
85 extern struct target_type arm946e_target;
86 extern struct target_type arm926ejs_target;
87 extern struct target_type fa526_target;
88 extern struct target_type feroceon_target;
89 extern struct target_type dragonite_target;
90 extern struct target_type xscale_target;
91 extern struct target_type cortexm_target;
92 extern struct target_type cortexa_target;
93 extern struct target_type cortexr4_target;
94 extern struct target_type arm11_target;
95 extern struct target_type mips_m4k_target;
96 extern struct target_type avr_target;
97 extern struct target_type dsp563xx_target;
98 extern struct target_type dsp5680xx_target;
99 extern struct target_type testee_target;
100 extern struct target_type avr32_ap7k_target;
101 extern struct target_type hla_target;
102 extern struct target_type nds32_v2_target;
103 extern struct target_type nds32_v3_target;
104 extern struct target_type nds32_v3m_target;
105 extern struct target_type or1k_target;
106 extern struct target_type quark_x10xx_target;
108 static struct target_type *target_types[] = {
109 &arm7tdmi_target,
110 &arm9tdmi_target,
111 &arm920t_target,
112 &arm720t_target,
113 &arm966e_target,
114 &arm946e_target,
115 &arm926ejs_target,
116 &fa526_target,
117 &feroceon_target,
118 &dragonite_target,
119 &xscale_target,
120 &cortexm_target,
121 &cortexa_target,
122 &cortexr4_target,
123 &arm11_target,
124 &mips_m4k_target,
125 &avr_target,
126 &dsp563xx_target,
127 &dsp5680xx_target,
128 &testee_target,
129 &avr32_ap7k_target,
130 &hla_target,
131 &nds32_v2_target,
132 &nds32_v3_target,
133 &nds32_v3m_target,
134 &or1k_target,
135 &quark_x10xx_target,
136 NULL,
139 struct target *all_targets;
140 static struct target_event_callback *target_event_callbacks;
141 static struct target_timer_callback *target_timer_callbacks;
142 static const int polling_interval = 100;
144 static const Jim_Nvp nvp_assert[] = {
145 { .name = "assert", NVP_ASSERT },
146 { .name = "deassert", NVP_DEASSERT },
147 { .name = "T", NVP_ASSERT },
148 { .name = "F", NVP_DEASSERT },
149 { .name = "t", NVP_ASSERT },
150 { .name = "f", NVP_DEASSERT },
151 { .name = NULL, .value = -1 }
154 static const Jim_Nvp nvp_error_target[] = {
155 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
156 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
157 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
158 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
159 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
160 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
161 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
162 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
163 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
164 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
165 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
166 { .value = -1, .name = NULL }
169 static const char *target_strerror_safe(int err)
171 const Jim_Nvp *n;
173 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
174 if (n->name == NULL)
175 return "unknown";
176 else
177 return n->name;
180 static const Jim_Nvp nvp_target_event[] = {
182 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
183 { .value = TARGET_EVENT_HALTED, .name = "halted" },
184 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
185 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
186 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
188 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
189 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
191 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
192 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
193 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
194 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
195 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
196 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
197 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
198 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
199 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
200 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
201 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
202 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
204 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
205 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
207 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
208 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
210 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
211 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
213 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
214 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
216 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
217 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
219 { .name = NULL, .value = -1 }
222 static const Jim_Nvp nvp_target_state[] = {
223 { .name = "unknown", .value = TARGET_UNKNOWN },
224 { .name = "running", .value = TARGET_RUNNING },
225 { .name = "halted", .value = TARGET_HALTED },
226 { .name = "reset", .value = TARGET_RESET },
227 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
228 { .name = NULL, .value = -1 },
231 static const Jim_Nvp nvp_target_debug_reason[] = {
232 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
233 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
234 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
235 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
236 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
237 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
238 { .name = "program-exit" , .value = DBG_REASON_EXIT },
239 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
240 { .name = NULL, .value = -1 },
243 static const Jim_Nvp nvp_target_endian[] = {
244 { .name = "big", .value = TARGET_BIG_ENDIAN },
245 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
246 { .name = "be", .value = TARGET_BIG_ENDIAN },
247 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
248 { .name = NULL, .value = -1 },
251 static const Jim_Nvp nvp_reset_modes[] = {
252 { .name = "unknown", .value = RESET_UNKNOWN },
253 { .name = "run" , .value = RESET_RUN },
254 { .name = "halt" , .value = RESET_HALT },
255 { .name = "init" , .value = RESET_INIT },
256 { .name = NULL , .value = -1 },
259 const char *debug_reason_name(struct target *t)
261 const char *cp;
263 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
264 t->debug_reason)->name;
265 if (!cp) {
266 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
267 cp = "(*BUG*unknown*BUG*)";
269 return cp;
272 const char *target_state_name(struct target *t)
274 const char *cp;
275 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
276 if (!cp) {
277 LOG_ERROR("Invalid target state: %d", (int)(t->state));
278 cp = "(*BUG*unknown*BUG*)";
280 return cp;
283 /* determine the number of the new target */
284 static int new_target_number(void)
286 struct target *t;
287 int x;
289 /* number is 0 based */
290 x = -1;
291 t = all_targets;
292 while (t) {
293 if (x < t->target_number)
294 x = t->target_number;
295 t = t->next;
297 return x + 1;
300 /* read a uint64_t from a buffer in target memory endianness */
301 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
303 if (target->endianness == TARGET_LITTLE_ENDIAN)
304 return le_to_h_u64(buffer);
305 else
306 return be_to_h_u64(buffer);
309 /* read a uint32_t from a buffer in target memory endianness */
310 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
312 if (target->endianness == TARGET_LITTLE_ENDIAN)
313 return le_to_h_u32(buffer);
314 else
315 return be_to_h_u32(buffer);
318 /* read a uint24_t from a buffer in target memory endianness */
319 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
321 if (target->endianness == TARGET_LITTLE_ENDIAN)
322 return le_to_h_u24(buffer);
323 else
324 return be_to_h_u24(buffer);
327 /* read a uint16_t from a buffer in target memory endianness */
328 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
330 if (target->endianness == TARGET_LITTLE_ENDIAN)
331 return le_to_h_u16(buffer);
332 else
333 return be_to_h_u16(buffer);
336 /* read a uint8_t from a buffer in target memory endianness */
337 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
339 return *buffer & 0x0ff;
342 /* write a uint64_t to a buffer in target memory endianness */
343 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
345 if (target->endianness == TARGET_LITTLE_ENDIAN)
346 h_u64_to_le(buffer, value);
347 else
348 h_u64_to_be(buffer, value);
351 /* write a uint32_t to a buffer in target memory endianness */
352 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
354 if (target->endianness == TARGET_LITTLE_ENDIAN)
355 h_u32_to_le(buffer, value);
356 else
357 h_u32_to_be(buffer, value);
360 /* write a uint24_t to a buffer in target memory endianness */
361 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
363 if (target->endianness == TARGET_LITTLE_ENDIAN)
364 h_u24_to_le(buffer, value);
365 else
366 h_u24_to_be(buffer, value);
369 /* write a uint16_t to a buffer in target memory endianness */
370 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
372 if (target->endianness == TARGET_LITTLE_ENDIAN)
373 h_u16_to_le(buffer, value);
374 else
375 h_u16_to_be(buffer, value);
378 /* write a uint8_t to a buffer in target memory endianness */
379 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
381 *buffer = value;
384 /* write a uint64_t array to a buffer in target memory endianness */
385 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
387 uint32_t i;
388 for (i = 0; i < count; i++)
389 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
392 /* write a uint32_t array to a buffer in target memory endianness */
393 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
395 uint32_t i;
396 for (i = 0; i < count; i++)
397 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
400 /* write a uint16_t array to a buffer in target memory endianness */
401 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
403 uint32_t i;
404 for (i = 0; i < count; i++)
405 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
408 /* write a uint64_t array to a buffer in target memory endianness */
409 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
411 uint32_t i;
412 for (i = 0; i < count; i++)
413 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
416 /* write a uint32_t array to a buffer in target memory endianness */
417 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
419 uint32_t i;
420 for (i = 0; i < count; i++)
421 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
424 /* write a uint16_t array to a buffer in target memory endianness */
425 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
427 uint32_t i;
428 for (i = 0; i < count; i++)
429 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
432 /* return a pointer to a configured target; id is name or number */
433 struct target *get_target(const char *id)
435 struct target *target;
437 /* try as tcltarget name */
438 for (target = all_targets; target; target = target->next) {
439 if (target_name(target) == NULL)
440 continue;
441 if (strcmp(id, target_name(target)) == 0)
442 return target;
445 /* It's OK to remove this fallback sometime after August 2010 or so */
447 /* no match, try as number */
448 unsigned num;
449 if (parse_uint(id, &num) != ERROR_OK)
450 return NULL;
452 for (target = all_targets; target; target = target->next) {
453 if (target->target_number == (int)num) {
454 LOG_WARNING("use '%s' as target identifier, not '%u'",
455 target_name(target), num);
456 return target;
460 return NULL;
463 /* returns a pointer to the n-th configured target */
464 static struct target *get_target_by_num(int num)
466 struct target *target = all_targets;
468 while (target) {
469 if (target->target_number == num)
470 return target;
471 target = target->next;
474 return NULL;
477 struct target *get_current_target(struct command_context *cmd_ctx)
479 struct target *target = get_target_by_num(cmd_ctx->current_target);
481 if (target == NULL) {
482 LOG_ERROR("BUG: current_target out of bounds");
483 exit(-1);
486 return target;
489 int target_poll(struct target *target)
491 int retval;
493 /* We can't poll until after examine */
494 if (!target_was_examined(target)) {
495 /* Fail silently lest we pollute the log */
496 return ERROR_FAIL;
499 retval = target->type->poll(target);
500 if (retval != ERROR_OK)
501 return retval;
503 if (target->halt_issued) {
504 if (target->state == TARGET_HALTED)
505 target->halt_issued = false;
506 else {
507 long long t = timeval_ms() - target->halt_issued_time;
508 if (t > DEFAULT_HALT_TIMEOUT) {
509 target->halt_issued = false;
510 LOG_INFO("Halt timed out, wake up GDB.");
511 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
516 return ERROR_OK;
519 int target_halt(struct target *target)
521 int retval;
522 /* We can't poll until after examine */
523 if (!target_was_examined(target)) {
524 LOG_ERROR("Target not examined yet");
525 return ERROR_FAIL;
528 retval = target->type->halt(target);
529 if (retval != ERROR_OK)
530 return retval;
532 target->halt_issued = true;
533 target->halt_issued_time = timeval_ms();
535 return ERROR_OK;
539 * Make the target (re)start executing using its saved execution
540 * context (possibly with some modifications).
542 * @param target Which target should start executing.
543 * @param current True to use the target's saved program counter instead
544 * of the address parameter
545 * @param address Optionally used as the program counter.
546 * @param handle_breakpoints True iff breakpoints at the resumption PC
547 * should be skipped. (For example, maybe execution was stopped by
548 * such a breakpoint, in which case it would be counterprodutive to
549 * let it re-trigger.
550 * @param debug_execution False if all working areas allocated by OpenOCD
551 * should be released and/or restored to their original contents.
552 * (This would for example be true to run some downloaded "helper"
553 * algorithm code, which resides in one such working buffer and uses
554 * another for data storage.)
556 * @todo Resolve the ambiguity about what the "debug_execution" flag
557 * signifies. For example, Target implementations don't agree on how
558 * it relates to invalidation of the register cache, or to whether
559 * breakpoints and watchpoints should be enabled. (It would seem wrong
560 * to enable breakpoints when running downloaded "helper" algorithms
561 * (debug_execution true), since the breakpoints would be set to match
562 * target firmware being debugged, not the helper algorithm.... and
563 * enabling them could cause such helpers to malfunction (for example,
564 * by overwriting data with a breakpoint instruction. On the other
565 * hand the infrastructure for running such helpers might use this
566 * procedure but rely on hardware breakpoint to detect termination.)
568 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
570 int retval;
572 /* We can't poll until after examine */
573 if (!target_was_examined(target)) {
574 LOG_ERROR("Target not examined yet");
575 return ERROR_FAIL;
578 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
580 /* note that resume *must* be asynchronous. The CPU can halt before
581 * we poll. The CPU can even halt at the current PC as a result of
582 * a software breakpoint being inserted by (a bug?) the application.
584 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
585 if (retval != ERROR_OK)
586 return retval;
588 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
590 return retval;
593 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
595 char buf[100];
596 int retval;
597 Jim_Nvp *n;
598 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
599 if (n->name == NULL) {
600 LOG_ERROR("invalid reset mode");
601 return ERROR_FAIL;
604 /* disable polling during reset to make reset event scripts
605 * more predictable, i.e. dr/irscan & pathmove in events will
606 * not have JTAG operations injected into the middle of a sequence.
608 bool save_poll = jtag_poll_get_enabled();
610 jtag_poll_set_enabled(false);
612 sprintf(buf, "ocd_process_reset %s", n->name);
613 retval = Jim_Eval(cmd_ctx->interp, buf);
615 jtag_poll_set_enabled(save_poll);
617 if (retval != JIM_OK) {
618 Jim_MakeErrorMessage(cmd_ctx->interp);
619 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
620 return ERROR_FAIL;
623 /* We want any events to be processed before the prompt */
624 retval = target_call_timer_callbacks_now();
626 struct target *target;
627 for (target = all_targets; target; target = target->next) {
628 target->type->check_reset(target);
629 target->running_alg = false;
632 return retval;
635 static int identity_virt2phys(struct target *target,
636 uint32_t virtual, uint32_t *physical)
638 *physical = virtual;
639 return ERROR_OK;
642 static int no_mmu(struct target *target, int *enabled)
644 *enabled = 0;
645 return ERROR_OK;
648 static int default_examine(struct target *target)
650 target_set_examined(target);
651 return ERROR_OK;
654 /* no check by default */
655 static int default_check_reset(struct target *target)
657 return ERROR_OK;
660 int target_examine_one(struct target *target)
662 return target->type->examine(target);
665 static int jtag_enable_callback(enum jtag_event event, void *priv)
667 struct target *target = priv;
669 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
670 return ERROR_OK;
672 jtag_unregister_event_callback(jtag_enable_callback, target);
674 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
676 int retval = target_examine_one(target);
677 if (retval != ERROR_OK)
678 return retval;
680 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
682 return retval;
685 /* Targets that correctly implement init + examine, i.e.
686 * no communication with target during init:
688 * XScale
690 int target_examine(void)
692 int retval = ERROR_OK;
693 struct target *target;
695 for (target = all_targets; target; target = target->next) {
696 /* defer examination, but don't skip it */
697 if (!target->tap->enabled) {
698 jtag_register_event_callback(jtag_enable_callback,
699 target);
700 continue;
703 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
705 retval = target_examine_one(target);
706 if (retval != ERROR_OK)
707 return retval;
709 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
711 return retval;
714 const char *target_type_name(struct target *target)
716 return target->type->name;
719 static int target_soft_reset_halt(struct target *target)
721 if (!target_was_examined(target)) {
722 LOG_ERROR("Target not examined yet");
723 return ERROR_FAIL;
725 if (!target->type->soft_reset_halt) {
726 LOG_ERROR("Target %s does not support soft_reset_halt",
727 target_name(target));
728 return ERROR_FAIL;
730 return target->type->soft_reset_halt(target);
734 * Downloads a target-specific native code algorithm to the target,
735 * and executes it. * Note that some targets may need to set up, enable,
736 * and tear down a breakpoint (hard or * soft) to detect algorithm
737 * termination, while others may support lower overhead schemes where
738 * soft breakpoints embedded in the algorithm automatically terminate the
739 * algorithm.
741 * @param target used to run the algorithm
742 * @param arch_info target-specific description of the algorithm.
744 int target_run_algorithm(struct target *target,
745 int num_mem_params, struct mem_param *mem_params,
746 int num_reg_params, struct reg_param *reg_param,
747 uint32_t entry_point, uint32_t exit_point,
748 int timeout_ms, void *arch_info)
750 int retval = ERROR_FAIL;
752 if (!target_was_examined(target)) {
753 LOG_ERROR("Target not examined yet");
754 goto done;
756 if (!target->type->run_algorithm) {
757 LOG_ERROR("Target type '%s' does not support %s",
758 target_type_name(target), __func__);
759 goto done;
762 target->running_alg = true;
763 retval = target->type->run_algorithm(target,
764 num_mem_params, mem_params,
765 num_reg_params, reg_param,
766 entry_point, exit_point, timeout_ms, arch_info);
767 target->running_alg = false;
769 done:
770 return retval;
774 * Downloads a target-specific native code algorithm to the target,
775 * executes and leaves it running.
777 * @param target used to run the algorithm
778 * @param arch_info target-specific description of the algorithm.
780 int target_start_algorithm(struct target *target,
781 int num_mem_params, struct mem_param *mem_params,
782 int num_reg_params, struct reg_param *reg_params,
783 uint32_t entry_point, uint32_t exit_point,
784 void *arch_info)
786 int retval = ERROR_FAIL;
788 if (!target_was_examined(target)) {
789 LOG_ERROR("Target not examined yet");
790 goto done;
792 if (!target->type->start_algorithm) {
793 LOG_ERROR("Target type '%s' does not support %s",
794 target_type_name(target), __func__);
795 goto done;
797 if (target->running_alg) {
798 LOG_ERROR("Target is already running an algorithm");
799 goto done;
802 target->running_alg = true;
803 retval = target->type->start_algorithm(target,
804 num_mem_params, mem_params,
805 num_reg_params, reg_params,
806 entry_point, exit_point, arch_info);
808 done:
809 return retval;
813 * Waits for an algorithm started with target_start_algorithm() to complete.
815 * @param target used to run the algorithm
816 * @param arch_info target-specific description of the algorithm.
818 int target_wait_algorithm(struct target *target,
819 int num_mem_params, struct mem_param *mem_params,
820 int num_reg_params, struct reg_param *reg_params,
821 uint32_t exit_point, int timeout_ms,
822 void *arch_info)
824 int retval = ERROR_FAIL;
826 if (!target->type->wait_algorithm) {
827 LOG_ERROR("Target type '%s' does not support %s",
828 target_type_name(target), __func__);
829 goto done;
831 if (!target->running_alg) {
832 LOG_ERROR("Target is not running an algorithm");
833 goto done;
836 retval = target->type->wait_algorithm(target,
837 num_mem_params, mem_params,
838 num_reg_params, reg_params,
839 exit_point, timeout_ms, arch_info);
840 if (retval != ERROR_TARGET_TIMEOUT)
841 target->running_alg = false;
843 done:
844 return retval;
848 * Executes a target-specific native code algorithm in the target.
849 * It differs from target_run_algorithm in that the algorithm is asynchronous.
850 * Because of this it requires an compliant algorithm:
851 * see contrib/loaders/flash/stm32f1x.S for example.
853 * @param target used to run the algorithm
856 int target_run_flash_async_algorithm(struct target *target,
857 const uint8_t *buffer, uint32_t count, int block_size,
858 int num_mem_params, struct mem_param *mem_params,
859 int num_reg_params, struct reg_param *reg_params,
860 uint32_t buffer_start, uint32_t buffer_size,
861 uint32_t entry_point, uint32_t exit_point, void *arch_info)
863 int retval;
864 int timeout = 0;
866 const uint8_t *buffer_orig = buffer;
868 /* Set up working area. First word is write pointer, second word is read pointer,
869 * rest is fifo data area. */
870 uint32_t wp_addr = buffer_start;
871 uint32_t rp_addr = buffer_start + 4;
872 uint32_t fifo_start_addr = buffer_start + 8;
873 uint32_t fifo_end_addr = buffer_start + buffer_size;
875 uint32_t wp = fifo_start_addr;
876 uint32_t rp = fifo_start_addr;
878 /* validate block_size is 2^n */
879 assert(!block_size || !(block_size & (block_size - 1)));
881 retval = target_write_u32(target, wp_addr, wp);
882 if (retval != ERROR_OK)
883 return retval;
884 retval = target_write_u32(target, rp_addr, rp);
885 if (retval != ERROR_OK)
886 return retval;
888 /* Start up algorithm on target and let it idle while writing the first chunk */
889 retval = target_start_algorithm(target, num_mem_params, mem_params,
890 num_reg_params, reg_params,
891 entry_point,
892 exit_point,
893 arch_info);
895 if (retval != ERROR_OK) {
896 LOG_ERROR("error starting target flash write algorithm");
897 return retval;
900 while (count > 0) {
902 retval = target_read_u32(target, rp_addr, &rp);
903 if (retval != ERROR_OK) {
904 LOG_ERROR("failed to get read pointer");
905 break;
908 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
909 (size_t) (buffer - buffer_orig), count, wp, rp);
911 if (rp == 0) {
912 LOG_ERROR("flash write algorithm aborted by target");
913 retval = ERROR_FLASH_OPERATION_FAILED;
914 break;
917 if ((rp & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
918 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
919 break;
922 /* Count the number of bytes available in the fifo without
923 * crossing the wrap around. Make sure to not fill it completely,
924 * because that would make wp == rp and that's the empty condition. */
925 uint32_t thisrun_bytes;
926 if (rp > wp)
927 thisrun_bytes = rp - wp - block_size;
928 else if (rp > fifo_start_addr)
929 thisrun_bytes = fifo_end_addr - wp;
930 else
931 thisrun_bytes = fifo_end_addr - wp - block_size;
933 if (thisrun_bytes == 0) {
934 /* Throttle polling a bit if transfer is (much) faster than flash
935 * programming. The exact delay shouldn't matter as long as it's
936 * less than buffer size / flash speed. This is very unlikely to
937 * run when using high latency connections such as USB. */
938 alive_sleep(10);
940 /* to stop an infinite loop on some targets check and increment a timeout
941 * this issue was observed on a stellaris using the new ICDI interface */
942 if (timeout++ >= 500) {
943 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
944 return ERROR_FLASH_OPERATION_FAILED;
946 continue;
949 /* reset our timeout */
950 timeout = 0;
952 /* Limit to the amount of data we actually want to write */
953 if (thisrun_bytes > count * block_size)
954 thisrun_bytes = count * block_size;
956 /* Write data to fifo */
957 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
958 if (retval != ERROR_OK)
959 break;
961 /* Update counters and wrap write pointer */
962 buffer += thisrun_bytes;
963 count -= thisrun_bytes / block_size;
964 wp += thisrun_bytes;
965 if (wp >= fifo_end_addr)
966 wp = fifo_start_addr;
968 /* Store updated write pointer to target */
969 retval = target_write_u32(target, wp_addr, wp);
970 if (retval != ERROR_OK)
971 break;
974 if (retval != ERROR_OK) {
975 /* abort flash write algorithm on target */
976 target_write_u32(target, wp_addr, 0);
979 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
980 num_reg_params, reg_params,
981 exit_point,
982 10000,
983 arch_info);
985 if (retval2 != ERROR_OK) {
986 LOG_ERROR("error waiting for target flash write algorithm");
987 retval = retval2;
990 return retval;
993 int target_read_memory(struct target *target,
994 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
996 if (!target_was_examined(target)) {
997 LOG_ERROR("Target not examined yet");
998 return ERROR_FAIL;
1000 return target->type->read_memory(target, address, size, count, buffer);
1003 int target_read_phys_memory(struct target *target,
1004 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1006 if (!target_was_examined(target)) {
1007 LOG_ERROR("Target not examined yet");
1008 return ERROR_FAIL;
1010 return target->type->read_phys_memory(target, address, size, count, buffer);
1013 int target_write_memory(struct target *target,
1014 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1016 if (!target_was_examined(target)) {
1017 LOG_ERROR("Target not examined yet");
1018 return ERROR_FAIL;
1020 return target->type->write_memory(target, address, size, count, buffer);
1023 int target_write_phys_memory(struct target *target,
1024 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1026 if (!target_was_examined(target)) {
1027 LOG_ERROR("Target not examined yet");
1028 return ERROR_FAIL;
1030 return target->type->write_phys_memory(target, address, size, count, buffer);
1033 int target_add_breakpoint(struct target *target,
1034 struct breakpoint *breakpoint)
1036 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1037 LOG_WARNING("target %s is not halted", target_name(target));
1038 return ERROR_TARGET_NOT_HALTED;
1040 return target->type->add_breakpoint(target, breakpoint);
1043 int target_add_context_breakpoint(struct target *target,
1044 struct breakpoint *breakpoint)
1046 if (target->state != TARGET_HALTED) {
1047 LOG_WARNING("target %s is not halted", target_name(target));
1048 return ERROR_TARGET_NOT_HALTED;
1050 return target->type->add_context_breakpoint(target, breakpoint);
1053 int target_add_hybrid_breakpoint(struct target *target,
1054 struct breakpoint *breakpoint)
1056 if (target->state != TARGET_HALTED) {
1057 LOG_WARNING("target %s is not halted", target_name(target));
1058 return ERROR_TARGET_NOT_HALTED;
1060 return target->type->add_hybrid_breakpoint(target, breakpoint);
1063 int target_remove_breakpoint(struct target *target,
1064 struct breakpoint *breakpoint)
1066 return target->type->remove_breakpoint(target, breakpoint);
1069 int target_add_watchpoint(struct target *target,
1070 struct watchpoint *watchpoint)
1072 if (target->state != TARGET_HALTED) {
1073 LOG_WARNING("target %s is not halted", target_name(target));
1074 return ERROR_TARGET_NOT_HALTED;
1076 return target->type->add_watchpoint(target, watchpoint);
1078 int target_remove_watchpoint(struct target *target,
1079 struct watchpoint *watchpoint)
1081 return target->type->remove_watchpoint(target, watchpoint);
1083 int target_hit_watchpoint(struct target *target,
1084 struct watchpoint **hit_watchpoint)
1086 if (target->state != TARGET_HALTED) {
1087 LOG_WARNING("target %s is not halted", target->cmd_name);
1088 return ERROR_TARGET_NOT_HALTED;
1091 if (target->type->hit_watchpoint == NULL) {
1092 /* For backward compatible, if hit_watchpoint is not implemented,
1093 * return ERROR_FAIL such that gdb_server will not take the nonsense
1094 * information. */
1095 return ERROR_FAIL;
1098 return target->type->hit_watchpoint(target, hit_watchpoint);
1101 int target_get_gdb_reg_list(struct target *target,
1102 struct reg **reg_list[], int *reg_list_size,
1103 enum target_register_class reg_class)
1105 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1107 int target_step(struct target *target,
1108 int current, uint32_t address, int handle_breakpoints)
1110 return target->type->step(target, current, address, handle_breakpoints);
1113 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1115 if (target->state != TARGET_HALTED) {
1116 LOG_WARNING("target %s is not halted", target->cmd_name);
1117 return ERROR_TARGET_NOT_HALTED;
1119 return target->type->get_gdb_fileio_info(target, fileio_info);
1122 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1124 if (target->state != TARGET_HALTED) {
1125 LOG_WARNING("target %s is not halted", target->cmd_name);
1126 return ERROR_TARGET_NOT_HALTED;
1128 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1131 int target_profiling(struct target *target, uint32_t *samples,
1132 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1134 if (target->state != TARGET_HALTED) {
1135 LOG_WARNING("target %s is not halted", target->cmd_name);
1136 return ERROR_TARGET_NOT_HALTED;
1138 return target->type->profiling(target, samples, max_num_samples,
1139 num_samples, seconds);
1143 * Reset the @c examined flag for the given target.
1144 * Pure paranoia -- targets are zeroed on allocation.
1146 static void target_reset_examined(struct target *target)
1148 target->examined = false;
1151 static int err_read_phys_memory(struct target *target, uint32_t address,
1152 uint32_t size, uint32_t count, uint8_t *buffer)
1154 LOG_ERROR("Not implemented: %s", __func__);
1155 return ERROR_FAIL;
1158 static int err_write_phys_memory(struct target *target, uint32_t address,
1159 uint32_t size, uint32_t count, const uint8_t *buffer)
1161 LOG_ERROR("Not implemented: %s", __func__);
1162 return ERROR_FAIL;
1165 static int handle_target(void *priv);
1167 static int target_init_one(struct command_context *cmd_ctx,
1168 struct target *target)
1170 target_reset_examined(target);
1172 struct target_type *type = target->type;
1173 if (type->examine == NULL)
1174 type->examine = default_examine;
1176 if (type->check_reset == NULL)
1177 type->check_reset = default_check_reset;
1179 assert(type->init_target != NULL);
1181 int retval = type->init_target(cmd_ctx, target);
1182 if (ERROR_OK != retval) {
1183 LOG_ERROR("target '%s' init failed", target_name(target));
1184 return retval;
1187 /* Sanity-check MMU support ... stub in what we must, to help
1188 * implement it in stages, but warn if we need to do so.
1190 if (type->mmu) {
1191 if (type->write_phys_memory == NULL) {
1192 LOG_ERROR("type '%s' is missing write_phys_memory",
1193 type->name);
1194 type->write_phys_memory = err_write_phys_memory;
1196 if (type->read_phys_memory == NULL) {
1197 LOG_ERROR("type '%s' is missing read_phys_memory",
1198 type->name);
1199 type->read_phys_memory = err_read_phys_memory;
1201 if (type->virt2phys == NULL) {
1202 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1203 type->virt2phys = identity_virt2phys;
1205 } else {
1206 /* Make sure no-MMU targets all behave the same: make no
1207 * distinction between physical and virtual addresses, and
1208 * ensure that virt2phys() is always an identity mapping.
1210 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1211 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1213 type->mmu = no_mmu;
1214 type->write_phys_memory = type->write_memory;
1215 type->read_phys_memory = type->read_memory;
1216 type->virt2phys = identity_virt2phys;
1219 if (target->type->read_buffer == NULL)
1220 target->type->read_buffer = target_read_buffer_default;
1222 if (target->type->write_buffer == NULL)
1223 target->type->write_buffer = target_write_buffer_default;
1225 if (target->type->get_gdb_fileio_info == NULL)
1226 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1228 if (target->type->gdb_fileio_end == NULL)
1229 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1231 if (target->type->profiling == NULL)
1232 target->type->profiling = target_profiling_default;
1234 return ERROR_OK;
1237 static int target_init(struct command_context *cmd_ctx)
1239 struct target *target;
1240 int retval;
1242 for (target = all_targets; target; target = target->next) {
1243 retval = target_init_one(cmd_ctx, target);
1244 if (ERROR_OK != retval)
1245 return retval;
1248 if (!all_targets)
1249 return ERROR_OK;
1251 retval = target_register_user_commands(cmd_ctx);
1252 if (ERROR_OK != retval)
1253 return retval;
1255 retval = target_register_timer_callback(&handle_target,
1256 polling_interval, 1, cmd_ctx->interp);
1257 if (ERROR_OK != retval)
1258 return retval;
1260 return ERROR_OK;
1263 COMMAND_HANDLER(handle_target_init_command)
1265 int retval;
1267 if (CMD_ARGC != 0)
1268 return ERROR_COMMAND_SYNTAX_ERROR;
1270 static bool target_initialized;
1271 if (target_initialized) {
1272 LOG_INFO("'target init' has already been called");
1273 return ERROR_OK;
1275 target_initialized = true;
1277 retval = command_run_line(CMD_CTX, "init_targets");
1278 if (ERROR_OK != retval)
1279 return retval;
1281 retval = command_run_line(CMD_CTX, "init_target_events");
1282 if (ERROR_OK != retval)
1283 return retval;
1285 retval = command_run_line(CMD_CTX, "init_board");
1286 if (ERROR_OK != retval)
1287 return retval;
1289 LOG_DEBUG("Initializing targets...");
1290 return target_init(CMD_CTX);
1293 int target_register_event_callback(int (*callback)(struct target *target,
1294 enum target_event event, void *priv), void *priv)
1296 struct target_event_callback **callbacks_p = &target_event_callbacks;
1298 if (callback == NULL)
1299 return ERROR_COMMAND_SYNTAX_ERROR;
1301 if (*callbacks_p) {
1302 while ((*callbacks_p)->next)
1303 callbacks_p = &((*callbacks_p)->next);
1304 callbacks_p = &((*callbacks_p)->next);
1307 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1308 (*callbacks_p)->callback = callback;
1309 (*callbacks_p)->priv = priv;
1310 (*callbacks_p)->next = NULL;
1312 return ERROR_OK;
1315 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1317 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1318 struct timeval now;
1320 if (callback == NULL)
1321 return ERROR_COMMAND_SYNTAX_ERROR;
1323 if (*callbacks_p) {
1324 while ((*callbacks_p)->next)
1325 callbacks_p = &((*callbacks_p)->next);
1326 callbacks_p = &((*callbacks_p)->next);
1329 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1330 (*callbacks_p)->callback = callback;
1331 (*callbacks_p)->periodic = periodic;
1332 (*callbacks_p)->time_ms = time_ms;
1334 gettimeofday(&now, NULL);
1335 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
1336 time_ms -= (time_ms % 1000);
1337 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
1338 if ((*callbacks_p)->when.tv_usec > 1000000) {
1339 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
1340 (*callbacks_p)->when.tv_sec += 1;
1343 (*callbacks_p)->priv = priv;
1344 (*callbacks_p)->next = NULL;
1346 return ERROR_OK;
1349 int target_unregister_event_callback(int (*callback)(struct target *target,
1350 enum target_event event, void *priv), void *priv)
1352 struct target_event_callback **p = &target_event_callbacks;
1353 struct target_event_callback *c = target_event_callbacks;
1355 if (callback == NULL)
1356 return ERROR_COMMAND_SYNTAX_ERROR;
1358 while (c) {
1359 struct target_event_callback *next = c->next;
1360 if ((c->callback == callback) && (c->priv == priv)) {
1361 *p = next;
1362 free(c);
1363 return ERROR_OK;
1364 } else
1365 p = &(c->next);
1366 c = next;
1369 return ERROR_OK;
1372 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1374 struct target_timer_callback **p = &target_timer_callbacks;
1375 struct target_timer_callback *c = target_timer_callbacks;
1377 if (callback == NULL)
1378 return ERROR_COMMAND_SYNTAX_ERROR;
1380 while (c) {
1381 struct target_timer_callback *next = c->next;
1382 if ((c->callback == callback) && (c->priv == priv)) {
1383 *p = next;
1384 free(c);
1385 return ERROR_OK;
1386 } else
1387 p = &(c->next);
1388 c = next;
1391 return ERROR_OK;
1394 int target_call_event_callbacks(struct target *target, enum target_event event)
1396 struct target_event_callback *callback = target_event_callbacks;
1397 struct target_event_callback *next_callback;
1399 if (event == TARGET_EVENT_HALTED) {
1400 /* execute early halted first */
1401 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1404 LOG_DEBUG("target event %i (%s)", event,
1405 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1407 target_handle_event(target, event);
1409 while (callback) {
1410 next_callback = callback->next;
1411 callback->callback(target, event, callback->priv);
1412 callback = next_callback;
1415 return ERROR_OK;
1418 static int target_timer_callback_periodic_restart(
1419 struct target_timer_callback *cb, struct timeval *now)
1421 int time_ms = cb->time_ms;
1422 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1423 time_ms -= (time_ms % 1000);
1424 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1425 if (cb->when.tv_usec > 1000000) {
1426 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1427 cb->when.tv_sec += 1;
1429 return ERROR_OK;
1432 static int target_call_timer_callback(struct target_timer_callback *cb,
1433 struct timeval *now)
1435 cb->callback(cb->priv);
1437 if (cb->periodic)
1438 return target_timer_callback_periodic_restart(cb, now);
1440 return target_unregister_timer_callback(cb->callback, cb->priv);
1443 static int target_call_timer_callbacks_check_time(int checktime)
1445 keep_alive();
1447 struct timeval now;
1448 gettimeofday(&now, NULL);
1450 struct target_timer_callback *callback = target_timer_callbacks;
1451 while (callback) {
1452 /* cleaning up may unregister and free this callback */
1453 struct target_timer_callback *next_callback = callback->next;
1455 bool call_it = callback->callback &&
1456 ((!checktime && callback->periodic) ||
1457 now.tv_sec > callback->when.tv_sec ||
1458 (now.tv_sec == callback->when.tv_sec &&
1459 now.tv_usec >= callback->when.tv_usec));
1461 if (call_it) {
1462 int retval = target_call_timer_callback(callback, &now);
1463 if (retval != ERROR_OK)
1464 return retval;
1467 callback = next_callback;
1470 return ERROR_OK;
1473 int target_call_timer_callbacks(void)
1475 return target_call_timer_callbacks_check_time(1);
1478 /* invoke periodic callbacks immediately */
1479 int target_call_timer_callbacks_now(void)
1481 return target_call_timer_callbacks_check_time(0);
1484 /* Prints the working area layout for debug purposes */
1485 static void print_wa_layout(struct target *target)
1487 struct working_area *c = target->working_areas;
1489 while (c) {
1490 LOG_DEBUG("%c%c 0x%08"PRIx32"-0x%08"PRIx32" (%"PRIu32" bytes)",
1491 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1492 c->address, c->address + c->size - 1, c->size);
1493 c = c->next;
1497 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1498 static void target_split_working_area(struct working_area *area, uint32_t size)
1500 assert(area->free); /* Shouldn't split an allocated area */
1501 assert(size <= area->size); /* Caller should guarantee this */
1503 /* Split only if not already the right size */
1504 if (size < area->size) {
1505 struct working_area *new_wa = malloc(sizeof(*new_wa));
1507 if (new_wa == NULL)
1508 return;
1510 new_wa->next = area->next;
1511 new_wa->size = area->size - size;
1512 new_wa->address = area->address + size;
1513 new_wa->backup = NULL;
1514 new_wa->user = NULL;
1515 new_wa->free = true;
1517 area->next = new_wa;
1518 area->size = size;
1520 /* If backup memory was allocated to this area, it has the wrong size
1521 * now so free it and it will be reallocated if/when needed */
1522 if (area->backup) {
1523 free(area->backup);
1524 area->backup = NULL;
1529 /* Merge all adjacent free areas into one */
1530 static void target_merge_working_areas(struct target *target)
1532 struct working_area *c = target->working_areas;
1534 while (c && c->next) {
1535 assert(c->next->address == c->address + c->size); /* This is an invariant */
1537 /* Find two adjacent free areas */
1538 if (c->free && c->next->free) {
1539 /* Merge the last into the first */
1540 c->size += c->next->size;
1542 /* Remove the last */
1543 struct working_area *to_be_freed = c->next;
1544 c->next = c->next->next;
1545 if (to_be_freed->backup)
1546 free(to_be_freed->backup);
1547 free(to_be_freed);
1549 /* If backup memory was allocated to the remaining area, it's has
1550 * the wrong size now */
1551 if (c->backup) {
1552 free(c->backup);
1553 c->backup = NULL;
1555 } else {
1556 c = c->next;
1561 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1563 /* Reevaluate working area address based on MMU state*/
1564 if (target->working_areas == NULL) {
1565 int retval;
1566 int enabled;
1568 retval = target->type->mmu(target, &enabled);
1569 if (retval != ERROR_OK)
1570 return retval;
1572 if (!enabled) {
1573 if (target->working_area_phys_spec) {
1574 LOG_DEBUG("MMU disabled, using physical "
1575 "address for working memory 0x%08"PRIx32,
1576 target->working_area_phys);
1577 target->working_area = target->working_area_phys;
1578 } else {
1579 LOG_ERROR("No working memory available. "
1580 "Specify -work-area-phys to target.");
1581 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1583 } else {
1584 if (target->working_area_virt_spec) {
1585 LOG_DEBUG("MMU enabled, using virtual "
1586 "address for working memory 0x%08"PRIx32,
1587 target->working_area_virt);
1588 target->working_area = target->working_area_virt;
1589 } else {
1590 LOG_ERROR("No working memory available. "
1591 "Specify -work-area-virt to target.");
1592 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1596 /* Set up initial working area on first call */
1597 struct working_area *new_wa = malloc(sizeof(*new_wa));
1598 if (new_wa) {
1599 new_wa->next = NULL;
1600 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1601 new_wa->address = target->working_area;
1602 new_wa->backup = NULL;
1603 new_wa->user = NULL;
1604 new_wa->free = true;
1607 target->working_areas = new_wa;
1610 /* only allocate multiples of 4 byte */
1611 if (size % 4)
1612 size = (size + 3) & (~3UL);
1614 struct working_area *c = target->working_areas;
1616 /* Find the first large enough working area */
1617 while (c) {
1618 if (c->free && c->size >= size)
1619 break;
1620 c = c->next;
1623 if (c == NULL)
1624 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1626 /* Split the working area into the requested size */
1627 target_split_working_area(c, size);
1629 LOG_DEBUG("allocated new working area of %"PRIu32" bytes at address 0x%08"PRIx32, size, c->address);
1631 if (target->backup_working_area) {
1632 if (c->backup == NULL) {
1633 c->backup = malloc(c->size);
1634 if (c->backup == NULL)
1635 return ERROR_FAIL;
1638 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1639 if (retval != ERROR_OK)
1640 return retval;
1643 /* mark as used, and return the new (reused) area */
1644 c->free = false;
1645 *area = c;
1647 /* user pointer */
1648 c->user = area;
1650 print_wa_layout(target);
1652 return ERROR_OK;
1655 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1657 int retval;
1659 retval = target_alloc_working_area_try(target, size, area);
1660 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1661 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1662 return retval;
1666 static int target_restore_working_area(struct target *target, struct working_area *area)
1668 int retval = ERROR_OK;
1670 if (target->backup_working_area && area->backup != NULL) {
1671 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1672 if (retval != ERROR_OK)
1673 LOG_ERROR("failed to restore %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1674 area->size, area->address);
1677 return retval;
1680 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1681 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1683 int retval = ERROR_OK;
1685 if (area->free)
1686 return retval;
1688 if (restore) {
1689 retval = target_restore_working_area(target, area);
1690 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1691 if (retval != ERROR_OK)
1692 return retval;
1695 area->free = true;
1697 LOG_DEBUG("freed %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1698 area->size, area->address);
1700 /* mark user pointer invalid */
1701 /* TODO: Is this really safe? It points to some previous caller's memory.
1702 * How could we know that the area pointer is still in that place and not
1703 * some other vital data? What's the purpose of this, anyway? */
1704 *area->user = NULL;
1705 area->user = NULL;
1707 target_merge_working_areas(target);
1709 print_wa_layout(target);
1711 return retval;
1714 int target_free_working_area(struct target *target, struct working_area *area)
1716 return target_free_working_area_restore(target, area, 1);
1719 /* free resources and restore memory, if restoring memory fails,
1720 * free up resources anyway
1722 static void target_free_all_working_areas_restore(struct target *target, int restore)
1724 struct working_area *c = target->working_areas;
1726 LOG_DEBUG("freeing all working areas");
1728 /* Loop through all areas, restoring the allocated ones and marking them as free */
1729 while (c) {
1730 if (!c->free) {
1731 if (restore)
1732 target_restore_working_area(target, c);
1733 c->free = true;
1734 *c->user = NULL; /* Same as above */
1735 c->user = NULL;
1737 c = c->next;
1740 /* Run a merge pass to combine all areas into one */
1741 target_merge_working_areas(target);
1743 print_wa_layout(target);
1746 void target_free_all_working_areas(struct target *target)
1748 target_free_all_working_areas_restore(target, 1);
1751 /* Find the largest number of bytes that can be allocated */
1752 uint32_t target_get_working_area_avail(struct target *target)
1754 struct working_area *c = target->working_areas;
1755 uint32_t max_size = 0;
1757 if (c == NULL)
1758 return target->working_area_size;
1760 while (c) {
1761 if (c->free && max_size < c->size)
1762 max_size = c->size;
1764 c = c->next;
1767 return max_size;
1770 int target_arch_state(struct target *target)
1772 int retval;
1773 if (target == NULL) {
1774 LOG_USER("No target has been configured");
1775 return ERROR_OK;
1778 LOG_USER("target state: %s", target_state_name(target));
1780 if (target->state != TARGET_HALTED)
1781 return ERROR_OK;
1783 retval = target->type->arch_state(target);
1784 return retval;
1787 static int target_get_gdb_fileio_info_default(struct target *target,
1788 struct gdb_fileio_info *fileio_info)
1790 /* If target does not support semi-hosting function, target
1791 has no need to provide .get_gdb_fileio_info callback.
1792 It just return ERROR_FAIL and gdb_server will return "Txx"
1793 as target halted every time. */
1794 return ERROR_FAIL;
1797 static int target_gdb_fileio_end_default(struct target *target,
1798 int retcode, int fileio_errno, bool ctrl_c)
1800 return ERROR_OK;
1803 static int target_profiling_default(struct target *target, uint32_t *samples,
1804 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1806 struct timeval timeout, now;
1808 gettimeofday(&timeout, NULL);
1809 timeval_add_time(&timeout, seconds, 0);
1811 LOG_INFO("Starting profiling. Halting and resuming the"
1812 " target as often as we can...");
1814 uint32_t sample_count = 0;
1815 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
1816 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
1818 int retval = ERROR_OK;
1819 for (;;) {
1820 target_poll(target);
1821 if (target->state == TARGET_HALTED) {
1822 uint32_t t = *((uint32_t *)reg->value);
1823 samples[sample_count++] = t;
1824 /* current pc, addr = 0, do not handle breakpoints, not debugging */
1825 retval = target_resume(target, 1, 0, 0, 0);
1826 target_poll(target);
1827 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
1828 } else if (target->state == TARGET_RUNNING) {
1829 /* We want to quickly sample the PC. */
1830 retval = target_halt(target);
1831 } else {
1832 LOG_INFO("Target not halted or running");
1833 retval = ERROR_OK;
1834 break;
1837 if (retval != ERROR_OK)
1838 break;
1840 gettimeofday(&now, NULL);
1841 if ((sample_count >= max_num_samples) ||
1842 ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec))) {
1843 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
1844 break;
1848 *num_samples = sample_count;
1849 return retval;
1852 /* Single aligned words are guaranteed to use 16 or 32 bit access
1853 * mode respectively, otherwise data is handled as quickly as
1854 * possible
1856 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1858 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1859 (int)size, (unsigned)address);
1861 if (!target_was_examined(target)) {
1862 LOG_ERROR("Target not examined yet");
1863 return ERROR_FAIL;
1866 if (size == 0)
1867 return ERROR_OK;
1869 if ((address + size - 1) < address) {
1870 /* GDB can request this when e.g. PC is 0xfffffffc*/
1871 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1872 (unsigned)address,
1873 (unsigned)size);
1874 return ERROR_FAIL;
1877 return target->type->write_buffer(target, address, size, buffer);
1880 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t count, const uint8_t *buffer)
1882 uint32_t size;
1884 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
1885 * will have something to do with the size we leave to it. */
1886 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
1887 if (address & size) {
1888 int retval = target_write_memory(target, address, size, 1, buffer);
1889 if (retval != ERROR_OK)
1890 return retval;
1891 address += size;
1892 count -= size;
1893 buffer += size;
1897 /* Write the data with as large access size as possible. */
1898 for (; size > 0; size /= 2) {
1899 uint32_t aligned = count - count % size;
1900 if (aligned > 0) {
1901 int retval = target_write_memory(target, address, size, aligned / size, buffer);
1902 if (retval != ERROR_OK)
1903 return retval;
1904 address += aligned;
1905 count -= aligned;
1906 buffer += aligned;
1910 return ERROR_OK;
1913 /* Single aligned words are guaranteed to use 16 or 32 bit access
1914 * mode respectively, otherwise data is handled as quickly as
1915 * possible
1917 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1919 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1920 (int)size, (unsigned)address);
1922 if (!target_was_examined(target)) {
1923 LOG_ERROR("Target not examined yet");
1924 return ERROR_FAIL;
1927 if (size == 0)
1928 return ERROR_OK;
1930 if ((address + size - 1) < address) {
1931 /* GDB can request this when e.g. PC is 0xfffffffc*/
1932 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1933 address,
1934 size);
1935 return ERROR_FAIL;
1938 return target->type->read_buffer(target, address, size, buffer);
1941 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t count, uint8_t *buffer)
1943 uint32_t size;
1945 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
1946 * will have something to do with the size we leave to it. */
1947 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
1948 if (address & size) {
1949 int retval = target_read_memory(target, address, size, 1, buffer);
1950 if (retval != ERROR_OK)
1951 return retval;
1952 address += size;
1953 count -= size;
1954 buffer += size;
1958 /* Read the data with as large access size as possible. */
1959 for (; size > 0; size /= 2) {
1960 uint32_t aligned = count - count % size;
1961 if (aligned > 0) {
1962 int retval = target_read_memory(target, address, size, aligned / size, buffer);
1963 if (retval != ERROR_OK)
1964 return retval;
1965 address += aligned;
1966 count -= aligned;
1967 buffer += aligned;
1971 return ERROR_OK;
1974 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1976 uint8_t *buffer;
1977 int retval;
1978 uint32_t i;
1979 uint32_t checksum = 0;
1980 if (!target_was_examined(target)) {
1981 LOG_ERROR("Target not examined yet");
1982 return ERROR_FAIL;
1985 retval = target->type->checksum_memory(target, address, size, &checksum);
1986 if (retval != ERROR_OK) {
1987 buffer = malloc(size);
1988 if (buffer == NULL) {
1989 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1990 return ERROR_COMMAND_SYNTAX_ERROR;
1992 retval = target_read_buffer(target, address, size, buffer);
1993 if (retval != ERROR_OK) {
1994 free(buffer);
1995 return retval;
1998 /* convert to target endianness */
1999 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2000 uint32_t target_data;
2001 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2002 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2005 retval = image_calculate_checksum(buffer, size, &checksum);
2006 free(buffer);
2009 *crc = checksum;
2011 return retval;
2014 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
2016 int retval;
2017 if (!target_was_examined(target)) {
2018 LOG_ERROR("Target not examined yet");
2019 return ERROR_FAIL;
2022 if (target->type->blank_check_memory == 0)
2023 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2025 retval = target->type->blank_check_memory(target, address, size, blank);
2027 return retval;
2030 int target_read_u64(struct target *target, uint64_t address, uint64_t *value)
2032 uint8_t value_buf[8];
2033 if (!target_was_examined(target)) {
2034 LOG_ERROR("Target not examined yet");
2035 return ERROR_FAIL;
2038 int retval = target_read_memory(target, address, 8, 1, value_buf);
2040 if (retval == ERROR_OK) {
2041 *value = target_buffer_get_u64(target, value_buf);
2042 LOG_DEBUG("address: 0x%" PRIx64 ", value: 0x%16.16" PRIx64 "",
2043 address,
2044 *value);
2045 } else {
2046 *value = 0x0;
2047 LOG_DEBUG("address: 0x%" PRIx64 " failed",
2048 address);
2051 return retval;
2054 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
2056 uint8_t value_buf[4];
2057 if (!target_was_examined(target)) {
2058 LOG_ERROR("Target not examined yet");
2059 return ERROR_FAIL;
2062 int retval = target_read_memory(target, address, 4, 1, value_buf);
2064 if (retval == ERROR_OK) {
2065 *value = target_buffer_get_u32(target, value_buf);
2066 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2067 address,
2068 *value);
2069 } else {
2070 *value = 0x0;
2071 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2072 address);
2075 return retval;
2078 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
2080 uint8_t value_buf[2];
2081 if (!target_was_examined(target)) {
2082 LOG_ERROR("Target not examined yet");
2083 return ERROR_FAIL;
2086 int retval = target_read_memory(target, address, 2, 1, value_buf);
2088 if (retval == ERROR_OK) {
2089 *value = target_buffer_get_u16(target, value_buf);
2090 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
2091 address,
2092 *value);
2093 } else {
2094 *value = 0x0;
2095 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2096 address);
2099 return retval;
2102 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
2104 if (!target_was_examined(target)) {
2105 LOG_ERROR("Target not examined yet");
2106 return ERROR_FAIL;
2109 int retval = target_read_memory(target, address, 1, 1, value);
2111 if (retval == ERROR_OK) {
2112 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2113 address,
2114 *value);
2115 } else {
2116 *value = 0x0;
2117 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2118 address);
2121 return retval;
2124 int target_write_u64(struct target *target, uint64_t address, uint64_t value)
2126 int retval;
2127 uint8_t value_buf[8];
2128 if (!target_was_examined(target)) {
2129 LOG_ERROR("Target not examined yet");
2130 return ERROR_FAIL;
2133 LOG_DEBUG("address: 0x%" PRIx64 ", value: 0x%16.16" PRIx64 "",
2134 address,
2135 value);
2137 target_buffer_set_u64(target, value_buf, value);
2138 retval = target_write_memory(target, address, 8, 1, value_buf);
2139 if (retval != ERROR_OK)
2140 LOG_DEBUG("failed: %i", retval);
2142 return retval;
2145 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
2147 int retval;
2148 uint8_t value_buf[4];
2149 if (!target_was_examined(target)) {
2150 LOG_ERROR("Target not examined yet");
2151 return ERROR_FAIL;
2154 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2155 address,
2156 value);
2158 target_buffer_set_u32(target, value_buf, value);
2159 retval = target_write_memory(target, address, 4, 1, value_buf);
2160 if (retval != ERROR_OK)
2161 LOG_DEBUG("failed: %i", retval);
2163 return retval;
2166 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
2168 int retval;
2169 uint8_t value_buf[2];
2170 if (!target_was_examined(target)) {
2171 LOG_ERROR("Target not examined yet");
2172 return ERROR_FAIL;
2175 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
2176 address,
2177 value);
2179 target_buffer_set_u16(target, value_buf, value);
2180 retval = target_write_memory(target, address, 2, 1, value_buf);
2181 if (retval != ERROR_OK)
2182 LOG_DEBUG("failed: %i", retval);
2184 return retval;
2187 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
2189 int retval;
2190 if (!target_was_examined(target)) {
2191 LOG_ERROR("Target not examined yet");
2192 return ERROR_FAIL;
2195 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2196 address, value);
2198 retval = target_write_memory(target, address, 1, 1, &value);
2199 if (retval != ERROR_OK)
2200 LOG_DEBUG("failed: %i", retval);
2202 return retval;
2205 static int find_target(struct command_context *cmd_ctx, const char *name)
2207 struct target *target = get_target(name);
2208 if (target == NULL) {
2209 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2210 return ERROR_FAIL;
2212 if (!target->tap->enabled) {
2213 LOG_USER("Target: TAP %s is disabled, "
2214 "can't be the current target\n",
2215 target->tap->dotted_name);
2216 return ERROR_FAIL;
2219 cmd_ctx->current_target = target->target_number;
2220 return ERROR_OK;
2224 COMMAND_HANDLER(handle_targets_command)
2226 int retval = ERROR_OK;
2227 if (CMD_ARGC == 1) {
2228 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2229 if (retval == ERROR_OK) {
2230 /* we're done! */
2231 return retval;
2235 struct target *target = all_targets;
2236 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2237 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2238 while (target) {
2239 const char *state;
2240 char marker = ' ';
2242 if (target->tap->enabled)
2243 state = target_state_name(target);
2244 else
2245 state = "tap-disabled";
2247 if (CMD_CTX->current_target == target->target_number)
2248 marker = '*';
2250 /* keep columns lined up to match the headers above */
2251 command_print(CMD_CTX,
2252 "%2d%c %-18s %-10s %-6s %-18s %s",
2253 target->target_number,
2254 marker,
2255 target_name(target),
2256 target_type_name(target),
2257 Jim_Nvp_value2name_simple(nvp_target_endian,
2258 target->endianness)->name,
2259 target->tap->dotted_name,
2260 state);
2261 target = target->next;
2264 return retval;
2267 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2269 static int powerDropout;
2270 static int srstAsserted;
2272 static int runPowerRestore;
2273 static int runPowerDropout;
2274 static int runSrstAsserted;
2275 static int runSrstDeasserted;
2277 static int sense_handler(void)
2279 static int prevSrstAsserted;
2280 static int prevPowerdropout;
2282 int retval = jtag_power_dropout(&powerDropout);
2283 if (retval != ERROR_OK)
2284 return retval;
2286 int powerRestored;
2287 powerRestored = prevPowerdropout && !powerDropout;
2288 if (powerRestored)
2289 runPowerRestore = 1;
2291 long long current = timeval_ms();
2292 static long long lastPower;
2293 int waitMore = lastPower + 2000 > current;
2294 if (powerDropout && !waitMore) {
2295 runPowerDropout = 1;
2296 lastPower = current;
2299 retval = jtag_srst_asserted(&srstAsserted);
2300 if (retval != ERROR_OK)
2301 return retval;
2303 int srstDeasserted;
2304 srstDeasserted = prevSrstAsserted && !srstAsserted;
2306 static long long lastSrst;
2307 waitMore = lastSrst + 2000 > current;
2308 if (srstDeasserted && !waitMore) {
2309 runSrstDeasserted = 1;
2310 lastSrst = current;
2313 if (!prevSrstAsserted && srstAsserted)
2314 runSrstAsserted = 1;
2316 prevSrstAsserted = srstAsserted;
2317 prevPowerdropout = powerDropout;
2319 if (srstDeasserted || powerRestored) {
2320 /* Other than logging the event we can't do anything here.
2321 * Issuing a reset is a particularly bad idea as we might
2322 * be inside a reset already.
2326 return ERROR_OK;
2329 /* process target state changes */
2330 static int handle_target(void *priv)
2332 Jim_Interp *interp = (Jim_Interp *)priv;
2333 int retval = ERROR_OK;
2335 if (!is_jtag_poll_safe()) {
2336 /* polling is disabled currently */
2337 return ERROR_OK;
2340 /* we do not want to recurse here... */
2341 static int recursive;
2342 if (!recursive) {
2343 recursive = 1;
2344 sense_handler();
2345 /* danger! running these procedures can trigger srst assertions and power dropouts.
2346 * We need to avoid an infinite loop/recursion here and we do that by
2347 * clearing the flags after running these events.
2349 int did_something = 0;
2350 if (runSrstAsserted) {
2351 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2352 Jim_Eval(interp, "srst_asserted");
2353 did_something = 1;
2355 if (runSrstDeasserted) {
2356 Jim_Eval(interp, "srst_deasserted");
2357 did_something = 1;
2359 if (runPowerDropout) {
2360 LOG_INFO("Power dropout detected, running power_dropout proc.");
2361 Jim_Eval(interp, "power_dropout");
2362 did_something = 1;
2364 if (runPowerRestore) {
2365 Jim_Eval(interp, "power_restore");
2366 did_something = 1;
2369 if (did_something) {
2370 /* clear detect flags */
2371 sense_handler();
2374 /* clear action flags */
2376 runSrstAsserted = 0;
2377 runSrstDeasserted = 0;
2378 runPowerRestore = 0;
2379 runPowerDropout = 0;
2381 recursive = 0;
2384 /* Poll targets for state changes unless that's globally disabled.
2385 * Skip targets that are currently disabled.
2387 for (struct target *target = all_targets;
2388 is_jtag_poll_safe() && target;
2389 target = target->next) {
2391 if (!target_was_examined(target))
2392 continue;
2394 if (!target->tap->enabled)
2395 continue;
2397 if (target->backoff.times > target->backoff.count) {
2398 /* do not poll this time as we failed previously */
2399 target->backoff.count++;
2400 continue;
2402 target->backoff.count = 0;
2404 /* only poll target if we've got power and srst isn't asserted */
2405 if (!powerDropout && !srstAsserted) {
2406 /* polling may fail silently until the target has been examined */
2407 retval = target_poll(target);
2408 if (retval != ERROR_OK) {
2409 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2410 if (target->backoff.times * polling_interval < 5000) {
2411 target->backoff.times *= 2;
2412 target->backoff.times++;
2414 LOG_USER("Polling target %s failed, GDB will be halted. Polling again in %dms",
2415 target_name(target),
2416 target->backoff.times * polling_interval);
2418 /* Tell GDB to halt the debugger. This allows the user to
2419 * run monitor commands to handle the situation.
2421 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2422 return retval;
2424 /* Since we succeeded, we reset backoff count */
2425 if (target->backoff.times > 0) {
2426 LOG_USER("Polling target %s succeeded again, trying to reexamine", target_name(target));
2427 target_reset_examined(target);
2428 retval = target_examine_one(target);
2429 /* Target examination could have failed due to unstable connection,
2430 * but we set the examined flag anyway to repoll it later */
2431 if (retval != ERROR_OK) {
2432 target->examined = true;
2433 return retval;
2437 target->backoff.times = 0;
2441 return retval;
2444 COMMAND_HANDLER(handle_reg_command)
2446 struct target *target;
2447 struct reg *reg = NULL;
2448 unsigned count = 0;
2449 char *value;
2451 LOG_DEBUG("-");
2453 target = get_current_target(CMD_CTX);
2455 /* list all available registers for the current target */
2456 if (CMD_ARGC == 0) {
2457 struct reg_cache *cache = target->reg_cache;
2459 count = 0;
2460 while (cache) {
2461 unsigned i;
2463 command_print(CMD_CTX, "===== %s", cache->name);
2465 for (i = 0, reg = cache->reg_list;
2466 i < cache->num_regs;
2467 i++, reg++, count++) {
2468 /* only print cached values if they are valid */
2469 if (reg->valid) {
2470 value = buf_to_str(reg->value,
2471 reg->size, 16);
2472 command_print(CMD_CTX,
2473 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2474 count, reg->name,
2475 reg->size, value,
2476 reg->dirty
2477 ? " (dirty)"
2478 : "");
2479 free(value);
2480 } else {
2481 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2482 count, reg->name,
2483 reg->size) ;
2486 cache = cache->next;
2489 return ERROR_OK;
2492 /* access a single register by its ordinal number */
2493 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2494 unsigned num;
2495 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2497 struct reg_cache *cache = target->reg_cache;
2498 count = 0;
2499 while (cache) {
2500 unsigned i;
2501 for (i = 0; i < cache->num_regs; i++) {
2502 if (count++ == num) {
2503 reg = &cache->reg_list[i];
2504 break;
2507 if (reg)
2508 break;
2509 cache = cache->next;
2512 if (!reg) {
2513 command_print(CMD_CTX, "%i is out of bounds, the current target "
2514 "has only %i registers (0 - %i)", num, count, count - 1);
2515 return ERROR_OK;
2517 } else {
2518 /* access a single register by its name */
2519 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2521 if (!reg) {
2522 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2523 return ERROR_OK;
2527 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2529 /* display a register */
2530 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2531 && (CMD_ARGV[1][0] <= '9')))) {
2532 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2533 reg->valid = 0;
2535 if (reg->valid == 0)
2536 reg->type->get(reg);
2537 value = buf_to_str(reg->value, reg->size, 16);
2538 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2539 free(value);
2540 return ERROR_OK;
2543 /* set register value */
2544 if (CMD_ARGC == 2) {
2545 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2546 if (buf == NULL)
2547 return ERROR_FAIL;
2548 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2550 reg->type->set(reg, buf);
2552 value = buf_to_str(reg->value, reg->size, 16);
2553 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2554 free(value);
2556 free(buf);
2558 return ERROR_OK;
2561 return ERROR_COMMAND_SYNTAX_ERROR;
2564 COMMAND_HANDLER(handle_poll_command)
2566 int retval = ERROR_OK;
2567 struct target *target = get_current_target(CMD_CTX);
2569 if (CMD_ARGC == 0) {
2570 command_print(CMD_CTX, "background polling: %s",
2571 jtag_poll_get_enabled() ? "on" : "off");
2572 command_print(CMD_CTX, "TAP: %s (%s)",
2573 target->tap->dotted_name,
2574 target->tap->enabled ? "enabled" : "disabled");
2575 if (!target->tap->enabled)
2576 return ERROR_OK;
2577 retval = target_poll(target);
2578 if (retval != ERROR_OK)
2579 return retval;
2580 retval = target_arch_state(target);
2581 if (retval != ERROR_OK)
2582 return retval;
2583 } else if (CMD_ARGC == 1) {
2584 bool enable;
2585 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2586 jtag_poll_set_enabled(enable);
2587 } else
2588 return ERROR_COMMAND_SYNTAX_ERROR;
2590 return retval;
2593 COMMAND_HANDLER(handle_wait_halt_command)
2595 if (CMD_ARGC > 1)
2596 return ERROR_COMMAND_SYNTAX_ERROR;
2598 unsigned ms = DEFAULT_HALT_TIMEOUT;
2599 if (1 == CMD_ARGC) {
2600 int retval = parse_uint(CMD_ARGV[0], &ms);
2601 if (ERROR_OK != retval)
2602 return ERROR_COMMAND_SYNTAX_ERROR;
2605 struct target *target = get_current_target(CMD_CTX);
2606 return target_wait_state(target, TARGET_HALTED, ms);
2609 /* wait for target state to change. The trick here is to have a low
2610 * latency for short waits and not to suck up all the CPU time
2611 * on longer waits.
2613 * After 500ms, keep_alive() is invoked
2615 int target_wait_state(struct target *target, enum target_state state, int ms)
2617 int retval;
2618 long long then = 0, cur;
2619 int once = 1;
2621 for (;;) {
2622 retval = target_poll(target);
2623 if (retval != ERROR_OK)
2624 return retval;
2625 if (target->state == state)
2626 break;
2627 cur = timeval_ms();
2628 if (once) {
2629 once = 0;
2630 then = timeval_ms();
2631 LOG_DEBUG("waiting for target %s...",
2632 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2635 if (cur-then > 500)
2636 keep_alive();
2638 if ((cur-then) > ms) {
2639 LOG_ERROR("timed out while waiting for target %s",
2640 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2641 return ERROR_FAIL;
2645 return ERROR_OK;
2648 COMMAND_HANDLER(handle_halt_command)
2650 LOG_DEBUG("-");
2652 struct target *target = get_current_target(CMD_CTX);
2653 int retval = target_halt(target);
2654 if (ERROR_OK != retval)
2655 return retval;
2657 if (CMD_ARGC == 1) {
2658 unsigned wait_local;
2659 retval = parse_uint(CMD_ARGV[0], &wait_local);
2660 if (ERROR_OK != retval)
2661 return ERROR_COMMAND_SYNTAX_ERROR;
2662 if (!wait_local)
2663 return ERROR_OK;
2666 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2669 COMMAND_HANDLER(handle_soft_reset_halt_command)
2671 struct target *target = get_current_target(CMD_CTX);
2673 LOG_USER("requesting target halt and executing a soft reset");
2675 target_soft_reset_halt(target);
2677 return ERROR_OK;
2680 COMMAND_HANDLER(handle_reset_command)
2682 if (CMD_ARGC > 1)
2683 return ERROR_COMMAND_SYNTAX_ERROR;
2685 enum target_reset_mode reset_mode = RESET_RUN;
2686 if (CMD_ARGC == 1) {
2687 const Jim_Nvp *n;
2688 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2689 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2690 return ERROR_COMMAND_SYNTAX_ERROR;
2691 reset_mode = n->value;
2694 /* reset *all* targets */
2695 return target_process_reset(CMD_CTX, reset_mode);
2699 COMMAND_HANDLER(handle_resume_command)
2701 int current = 1;
2702 if (CMD_ARGC > 1)
2703 return ERROR_COMMAND_SYNTAX_ERROR;
2705 struct target *target = get_current_target(CMD_CTX);
2707 /* with no CMD_ARGV, resume from current pc, addr = 0,
2708 * with one arguments, addr = CMD_ARGV[0],
2709 * handle breakpoints, not debugging */
2710 uint32_t addr = 0;
2711 if (CMD_ARGC == 1) {
2712 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2713 current = 0;
2716 return target_resume(target, current, addr, 1, 0);
2719 COMMAND_HANDLER(handle_step_command)
2721 if (CMD_ARGC > 1)
2722 return ERROR_COMMAND_SYNTAX_ERROR;
2724 LOG_DEBUG("-");
2726 /* with no CMD_ARGV, step from current pc, addr = 0,
2727 * with one argument addr = CMD_ARGV[0],
2728 * handle breakpoints, debugging */
2729 uint32_t addr = 0;
2730 int current_pc = 1;
2731 if (CMD_ARGC == 1) {
2732 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2733 current_pc = 0;
2736 struct target *target = get_current_target(CMD_CTX);
2738 return target->type->step(target, current_pc, addr, 1);
2741 static void handle_md_output(struct command_context *cmd_ctx,
2742 struct target *target, uint32_t address, unsigned size,
2743 unsigned count, const uint8_t *buffer)
2745 const unsigned line_bytecnt = 32;
2746 unsigned line_modulo = line_bytecnt / size;
2748 char output[line_bytecnt * 4 + 1];
2749 unsigned output_len = 0;
2751 const char *value_fmt;
2752 switch (size) {
2753 case 4:
2754 value_fmt = "%8.8x ";
2755 break;
2756 case 2:
2757 value_fmt = "%4.4x ";
2758 break;
2759 case 1:
2760 value_fmt = "%2.2x ";
2761 break;
2762 default:
2763 /* "can't happen", caller checked */
2764 LOG_ERROR("invalid memory read size: %u", size);
2765 return;
2768 for (unsigned i = 0; i < count; i++) {
2769 if (i % line_modulo == 0) {
2770 output_len += snprintf(output + output_len,
2771 sizeof(output) - output_len,
2772 "0x%8.8x: ",
2773 (unsigned)(address + (i*size)));
2776 uint32_t value = 0;
2777 const uint8_t *value_ptr = buffer + i * size;
2778 switch (size) {
2779 case 4:
2780 value = target_buffer_get_u32(target, value_ptr);
2781 break;
2782 case 2:
2783 value = target_buffer_get_u16(target, value_ptr);
2784 break;
2785 case 1:
2786 value = *value_ptr;
2788 output_len += snprintf(output + output_len,
2789 sizeof(output) - output_len,
2790 value_fmt, value);
2792 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2793 command_print(cmd_ctx, "%s", output);
2794 output_len = 0;
2799 COMMAND_HANDLER(handle_md_command)
2801 if (CMD_ARGC < 1)
2802 return ERROR_COMMAND_SYNTAX_ERROR;
2804 unsigned size = 0;
2805 switch (CMD_NAME[2]) {
2806 case 'w':
2807 size = 4;
2808 break;
2809 case 'h':
2810 size = 2;
2811 break;
2812 case 'b':
2813 size = 1;
2814 break;
2815 default:
2816 return ERROR_COMMAND_SYNTAX_ERROR;
2819 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2820 int (*fn)(struct target *target,
2821 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2822 if (physical) {
2823 CMD_ARGC--;
2824 CMD_ARGV++;
2825 fn = target_read_phys_memory;
2826 } else
2827 fn = target_read_memory;
2828 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2829 return ERROR_COMMAND_SYNTAX_ERROR;
2831 uint32_t address;
2832 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2834 unsigned count = 1;
2835 if (CMD_ARGC == 2)
2836 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2838 uint8_t *buffer = calloc(count, size);
2840 struct target *target = get_current_target(CMD_CTX);
2841 int retval = fn(target, address, size, count, buffer);
2842 if (ERROR_OK == retval)
2843 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2845 free(buffer);
2847 return retval;
2850 typedef int (*target_write_fn)(struct target *target,
2851 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2853 static int target_fill_mem(struct target *target,
2854 uint32_t address,
2855 target_write_fn fn,
2856 unsigned data_size,
2857 /* value */
2858 uint32_t b,
2859 /* count */
2860 unsigned c)
2862 /* We have to write in reasonably large chunks to be able
2863 * to fill large memory areas with any sane speed */
2864 const unsigned chunk_size = 16384;
2865 uint8_t *target_buf = malloc(chunk_size * data_size);
2866 if (target_buf == NULL) {
2867 LOG_ERROR("Out of memory");
2868 return ERROR_FAIL;
2871 for (unsigned i = 0; i < chunk_size; i++) {
2872 switch (data_size) {
2873 case 4:
2874 target_buffer_set_u32(target, target_buf + i * data_size, b);
2875 break;
2876 case 2:
2877 target_buffer_set_u16(target, target_buf + i * data_size, b);
2878 break;
2879 case 1:
2880 target_buffer_set_u8(target, target_buf + i * data_size, b);
2881 break;
2882 default:
2883 exit(-1);
2887 int retval = ERROR_OK;
2889 for (unsigned x = 0; x < c; x += chunk_size) {
2890 unsigned current;
2891 current = c - x;
2892 if (current > chunk_size)
2893 current = chunk_size;
2894 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2895 if (retval != ERROR_OK)
2896 break;
2897 /* avoid GDB timeouts */
2898 keep_alive();
2900 free(target_buf);
2902 return retval;
2906 COMMAND_HANDLER(handle_mw_command)
2908 if (CMD_ARGC < 2)
2909 return ERROR_COMMAND_SYNTAX_ERROR;
2910 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2911 target_write_fn fn;
2912 if (physical) {
2913 CMD_ARGC--;
2914 CMD_ARGV++;
2915 fn = target_write_phys_memory;
2916 } else
2917 fn = target_write_memory;
2918 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2919 return ERROR_COMMAND_SYNTAX_ERROR;
2921 uint32_t address;
2922 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2924 uint32_t value;
2925 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2927 unsigned count = 1;
2928 if (CMD_ARGC == 3)
2929 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2931 struct target *target = get_current_target(CMD_CTX);
2932 unsigned wordsize;
2933 switch (CMD_NAME[2]) {
2934 case 'w':
2935 wordsize = 4;
2936 break;
2937 case 'h':
2938 wordsize = 2;
2939 break;
2940 case 'b':
2941 wordsize = 1;
2942 break;
2943 default:
2944 return ERROR_COMMAND_SYNTAX_ERROR;
2947 return target_fill_mem(target, address, fn, wordsize, value, count);
2950 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2951 uint32_t *min_address, uint32_t *max_address)
2953 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2954 return ERROR_COMMAND_SYNTAX_ERROR;
2956 /* a base address isn't always necessary,
2957 * default to 0x0 (i.e. don't relocate) */
2958 if (CMD_ARGC >= 2) {
2959 uint32_t addr;
2960 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2961 image->base_address = addr;
2962 image->base_address_set = 1;
2963 } else
2964 image->base_address_set = 0;
2966 image->start_address_set = 0;
2968 if (CMD_ARGC >= 4)
2969 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2970 if (CMD_ARGC == 5) {
2971 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2972 /* use size (given) to find max (required) */
2973 *max_address += *min_address;
2976 if (*min_address > *max_address)
2977 return ERROR_COMMAND_SYNTAX_ERROR;
2979 return ERROR_OK;
2982 COMMAND_HANDLER(handle_load_image_command)
2984 uint8_t *buffer;
2985 size_t buf_cnt;
2986 uint32_t image_size;
2987 uint32_t min_address = 0;
2988 uint32_t max_address = 0xffffffff;
2989 int i;
2990 struct image image;
2992 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2993 &image, &min_address, &max_address);
2994 if (ERROR_OK != retval)
2995 return retval;
2997 struct target *target = get_current_target(CMD_CTX);
2999 struct duration bench;
3000 duration_start(&bench);
3002 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3003 return ERROR_OK;
3005 image_size = 0x0;
3006 retval = ERROR_OK;
3007 for (i = 0; i < image.num_sections; i++) {
3008 buffer = malloc(image.sections[i].size);
3009 if (buffer == NULL) {
3010 command_print(CMD_CTX,
3011 "error allocating buffer for section (%d bytes)",
3012 (int)(image.sections[i].size));
3013 break;
3016 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3017 if (retval != ERROR_OK) {
3018 free(buffer);
3019 break;
3022 uint32_t offset = 0;
3023 uint32_t length = buf_cnt;
3025 /* DANGER!!! beware of unsigned comparision here!!! */
3027 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3028 (image.sections[i].base_address < max_address)) {
3030 if (image.sections[i].base_address < min_address) {
3031 /* clip addresses below */
3032 offset += min_address-image.sections[i].base_address;
3033 length -= offset;
3036 if (image.sections[i].base_address + buf_cnt > max_address)
3037 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3039 retval = target_write_buffer(target,
3040 image.sections[i].base_address + offset, length, buffer + offset);
3041 if (retval != ERROR_OK) {
3042 free(buffer);
3043 break;
3045 image_size += length;
3046 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
3047 (unsigned int)length,
3048 image.sections[i].base_address + offset);
3051 free(buffer);
3054 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3055 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
3056 "in %fs (%0.3f KiB/s)", image_size,
3057 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3060 image_close(&image);
3062 return retval;
3066 COMMAND_HANDLER(handle_dump_image_command)
3068 struct fileio fileio;
3069 uint8_t *buffer;
3070 int retval, retvaltemp;
3071 uint32_t address, size;
3072 struct duration bench;
3073 struct target *target = get_current_target(CMD_CTX);
3075 if (CMD_ARGC != 3)
3076 return ERROR_COMMAND_SYNTAX_ERROR;
3078 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
3079 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
3081 uint32_t buf_size = (size > 4096) ? 4096 : size;
3082 buffer = malloc(buf_size);
3083 if (!buffer)
3084 return ERROR_FAIL;
3086 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3087 if (retval != ERROR_OK) {
3088 free(buffer);
3089 return retval;
3092 duration_start(&bench);
3094 while (size > 0) {
3095 size_t size_written;
3096 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3097 retval = target_read_buffer(target, address, this_run_size, buffer);
3098 if (retval != ERROR_OK)
3099 break;
3101 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
3102 if (retval != ERROR_OK)
3103 break;
3105 size -= this_run_size;
3106 address += this_run_size;
3109 free(buffer);
3111 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3112 int filesize;
3113 retval = fileio_size(&fileio, &filesize);
3114 if (retval != ERROR_OK)
3115 return retval;
3116 command_print(CMD_CTX,
3117 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
3118 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3121 retvaltemp = fileio_close(&fileio);
3122 if (retvaltemp != ERROR_OK)
3123 return retvaltemp;
3125 return retval;
3128 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
3130 uint8_t *buffer;
3131 size_t buf_cnt;
3132 uint32_t image_size;
3133 int i;
3134 int retval;
3135 uint32_t checksum = 0;
3136 uint32_t mem_checksum = 0;
3138 struct image image;
3140 struct target *target = get_current_target(CMD_CTX);
3142 if (CMD_ARGC < 1)
3143 return ERROR_COMMAND_SYNTAX_ERROR;
3145 if (!target) {
3146 LOG_ERROR("no target selected");
3147 return ERROR_FAIL;
3150 struct duration bench;
3151 duration_start(&bench);
3153 if (CMD_ARGC >= 2) {
3154 uint32_t addr;
3155 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3156 image.base_address = addr;
3157 image.base_address_set = 1;
3158 } else {
3159 image.base_address_set = 0;
3160 image.base_address = 0x0;
3163 image.start_address_set = 0;
3165 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3166 if (retval != ERROR_OK)
3167 return retval;
3169 image_size = 0x0;
3170 int diffs = 0;
3171 retval = ERROR_OK;
3172 for (i = 0; i < image.num_sections; i++) {
3173 buffer = malloc(image.sections[i].size);
3174 if (buffer == NULL) {
3175 command_print(CMD_CTX,
3176 "error allocating buffer for section (%d bytes)",
3177 (int)(image.sections[i].size));
3178 break;
3180 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3181 if (retval != ERROR_OK) {
3182 free(buffer);
3183 break;
3186 if (verify) {
3187 /* calculate checksum of image */
3188 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3189 if (retval != ERROR_OK) {
3190 free(buffer);
3191 break;
3194 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3195 if (retval != ERROR_OK) {
3196 free(buffer);
3197 break;
3200 if (checksum != mem_checksum) {
3201 /* failed crc checksum, fall back to a binary compare */
3202 uint8_t *data;
3204 if (diffs == 0)
3205 LOG_ERROR("checksum mismatch - attempting binary compare");
3207 data = malloc(buf_cnt);
3209 /* Can we use 32bit word accesses? */
3210 int size = 1;
3211 int count = buf_cnt;
3212 if ((count % 4) == 0) {
3213 size *= 4;
3214 count /= 4;
3216 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3217 if (retval == ERROR_OK) {
3218 uint32_t t;
3219 for (t = 0; t < buf_cnt; t++) {
3220 if (data[t] != buffer[t]) {
3221 command_print(CMD_CTX,
3222 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3223 diffs,
3224 (unsigned)(t + image.sections[i].base_address),
3225 data[t],
3226 buffer[t]);
3227 if (diffs++ >= 127) {
3228 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3229 free(data);
3230 free(buffer);
3231 goto done;
3234 keep_alive();
3237 free(data);
3239 } else {
3240 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3241 image.sections[i].base_address,
3242 buf_cnt);
3245 free(buffer);
3246 image_size += buf_cnt;
3248 if (diffs > 0)
3249 command_print(CMD_CTX, "No more differences found.");
3250 done:
3251 if (diffs > 0)
3252 retval = ERROR_FAIL;
3253 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3254 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3255 "in %fs (%0.3f KiB/s)", image_size,
3256 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3259 image_close(&image);
3261 return retval;
3264 COMMAND_HANDLER(handle_verify_image_command)
3266 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3269 COMMAND_HANDLER(handle_test_image_command)
3271 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3274 static int handle_bp_command_list(struct command_context *cmd_ctx)
3276 struct target *target = get_current_target(cmd_ctx);
3277 struct breakpoint *breakpoint = target->breakpoints;
3278 while (breakpoint) {
3279 if (breakpoint->type == BKPT_SOFT) {
3280 char *buf = buf_to_str(breakpoint->orig_instr,
3281 breakpoint->length, 16);
3282 command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3283 breakpoint->address,
3284 breakpoint->length,
3285 breakpoint->set, buf);
3286 free(buf);
3287 } else {
3288 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3289 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3290 breakpoint->asid,
3291 breakpoint->length, breakpoint->set);
3292 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3293 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3294 breakpoint->address,
3295 breakpoint->length, breakpoint->set);
3296 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3297 breakpoint->asid);
3298 } else
3299 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3300 breakpoint->address,
3301 breakpoint->length, breakpoint->set);
3304 breakpoint = breakpoint->next;
3306 return ERROR_OK;
3309 static int handle_bp_command_set(struct command_context *cmd_ctx,
3310 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3312 struct target *target = get_current_target(cmd_ctx);
3313 int retval;
3315 if (asid == 0) {
3316 retval = breakpoint_add(target, addr, length, hw);
3317 if (ERROR_OK == retval)
3318 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3319 else {
3320 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3321 return retval;
3323 } else if (addr == 0) {
3324 if (target->type->add_context_breakpoint == NULL) {
3325 LOG_WARNING("Context breakpoint not available");
3326 return ERROR_OK;
3328 retval = context_breakpoint_add(target, asid, length, hw);
3329 if (ERROR_OK == retval)
3330 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3331 else {
3332 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3333 return retval;
3335 } else {
3336 if (target->type->add_hybrid_breakpoint == NULL) {
3337 LOG_WARNING("Hybrid breakpoint not available");
3338 return ERROR_OK;
3340 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3341 if (ERROR_OK == retval)
3342 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3343 else {
3344 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3345 return retval;
3348 return ERROR_OK;
3351 COMMAND_HANDLER(handle_bp_command)
3353 uint32_t addr;
3354 uint32_t asid;
3355 uint32_t length;
3356 int hw = BKPT_SOFT;
3358 switch (CMD_ARGC) {
3359 case 0:
3360 return handle_bp_command_list(CMD_CTX);
3362 case 2:
3363 asid = 0;
3364 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3365 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3366 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3368 case 3:
3369 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3370 hw = BKPT_HARD;
3371 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3373 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3375 asid = 0;
3376 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3377 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3378 hw = BKPT_HARD;
3379 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3380 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3381 addr = 0;
3382 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3385 case 4:
3386 hw = BKPT_HARD;
3387 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3388 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3389 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3390 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3392 default:
3393 return ERROR_COMMAND_SYNTAX_ERROR;
3397 COMMAND_HANDLER(handle_rbp_command)
3399 if (CMD_ARGC != 1)
3400 return ERROR_COMMAND_SYNTAX_ERROR;
3402 uint32_t addr;
3403 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3405 struct target *target = get_current_target(CMD_CTX);
3406 breakpoint_remove(target, addr);
3408 return ERROR_OK;
3411 COMMAND_HANDLER(handle_wp_command)
3413 struct target *target = get_current_target(CMD_CTX);
3415 if (CMD_ARGC == 0) {
3416 struct watchpoint *watchpoint = target->watchpoints;
3418 while (watchpoint) {
3419 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3420 ", len: 0x%8.8" PRIx32
3421 ", r/w/a: %i, value: 0x%8.8" PRIx32
3422 ", mask: 0x%8.8" PRIx32,
3423 watchpoint->address,
3424 watchpoint->length,
3425 (int)watchpoint->rw,
3426 watchpoint->value,
3427 watchpoint->mask);
3428 watchpoint = watchpoint->next;
3430 return ERROR_OK;
3433 enum watchpoint_rw type = WPT_ACCESS;
3434 uint32_t addr = 0;
3435 uint32_t length = 0;
3436 uint32_t data_value = 0x0;
3437 uint32_t data_mask = 0xffffffff;
3439 switch (CMD_ARGC) {
3440 case 5:
3441 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3442 /* fall through */
3443 case 4:
3444 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3445 /* fall through */
3446 case 3:
3447 switch (CMD_ARGV[2][0]) {
3448 case 'r':
3449 type = WPT_READ;
3450 break;
3451 case 'w':
3452 type = WPT_WRITE;
3453 break;
3454 case 'a':
3455 type = WPT_ACCESS;
3456 break;
3457 default:
3458 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3459 return ERROR_COMMAND_SYNTAX_ERROR;
3461 /* fall through */
3462 case 2:
3463 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3464 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3465 break;
3467 default:
3468 return ERROR_COMMAND_SYNTAX_ERROR;
3471 int retval = watchpoint_add(target, addr, length, type,
3472 data_value, data_mask);
3473 if (ERROR_OK != retval)
3474 LOG_ERROR("Failure setting watchpoints");
3476 return retval;
3479 COMMAND_HANDLER(handle_rwp_command)
3481 if (CMD_ARGC != 1)
3482 return ERROR_COMMAND_SYNTAX_ERROR;
3484 uint32_t addr;
3485 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3487 struct target *target = get_current_target(CMD_CTX);
3488 watchpoint_remove(target, addr);
3490 return ERROR_OK;
3494 * Translate a virtual address to a physical address.
3496 * The low-level target implementation must have logged a detailed error
3497 * which is forwarded to telnet/GDB session.
3499 COMMAND_HANDLER(handle_virt2phys_command)
3501 if (CMD_ARGC != 1)
3502 return ERROR_COMMAND_SYNTAX_ERROR;
3504 uint32_t va;
3505 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3506 uint32_t pa;
3508 struct target *target = get_current_target(CMD_CTX);
3509 int retval = target->type->virt2phys(target, va, &pa);
3510 if (retval == ERROR_OK)
3511 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3513 return retval;
3516 static void writeData(FILE *f, const void *data, size_t len)
3518 size_t written = fwrite(data, 1, len, f);
3519 if (written != len)
3520 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3523 static void writeLong(FILE *f, int l)
3525 int i;
3526 for (i = 0; i < 4; i++) {
3527 char c = (l >> (i*8))&0xff;
3528 writeData(f, &c, 1);
3533 static void writeString(FILE *f, char *s)
3535 writeData(f, s, strlen(s));
3538 typedef unsigned char UNIT[2]; /* unit of profiling */
3540 /* Dump a gmon.out histogram file. */
3541 static void write_gmon(uint32_t *samples, uint32_t sampleNum, const char *filename,
3542 bool with_range, uint32_t start_address, uint32_t end_address)
3544 uint32_t i;
3545 FILE *f = fopen(filename, "w");
3546 if (f == NULL)
3547 return;
3548 writeString(f, "gmon");
3549 writeLong(f, 0x00000001); /* Version */
3550 writeLong(f, 0); /* padding */
3551 writeLong(f, 0); /* padding */
3552 writeLong(f, 0); /* padding */
3554 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3555 writeData(f, &zero, 1);
3557 /* figure out bucket size */
3558 uint32_t min;
3559 uint32_t max;
3560 if (with_range) {
3561 min = start_address;
3562 max = end_address;
3563 } else {
3564 min = samples[0];
3565 max = samples[0];
3566 for (i = 0; i < sampleNum; i++) {
3567 if (min > samples[i])
3568 min = samples[i];
3569 if (max < samples[i])
3570 max = samples[i];
3573 /* max should be (largest sample + 1)
3574 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
3575 max++;
3578 int addressSpace = max - min;
3579 assert(addressSpace >= 2);
3581 /* FIXME: What is the reasonable number of buckets?
3582 * The profiling result will be more accurate if there are enough buckets. */
3583 static const uint32_t maxBuckets = 128 * 1024; /* maximum buckets. */
3584 uint32_t numBuckets = addressSpace / sizeof(UNIT);
3585 if (numBuckets > maxBuckets)
3586 numBuckets = maxBuckets;
3587 int *buckets = malloc(sizeof(int) * numBuckets);
3588 if (buckets == NULL) {
3589 fclose(f);
3590 return;
3592 memset(buckets, 0, sizeof(int) * numBuckets);
3593 for (i = 0; i < sampleNum; i++) {
3594 uint32_t address = samples[i];
3596 if ((address < min) || (max <= address))
3597 continue;
3599 long long a = address - min;
3600 long long b = numBuckets;
3601 long long c = addressSpace;
3602 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3603 buckets[index_t]++;
3606 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3607 writeLong(f, min); /* low_pc */
3608 writeLong(f, max); /* high_pc */
3609 writeLong(f, numBuckets); /* # of buckets */
3610 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3611 writeString(f, "seconds");
3612 for (i = 0; i < (15-strlen("seconds")); i++)
3613 writeData(f, &zero, 1);
3614 writeString(f, "s");
3616 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3618 char *data = malloc(2 * numBuckets);
3619 if (data != NULL) {
3620 for (i = 0; i < numBuckets; i++) {
3621 int val;
3622 val = buckets[i];
3623 if (val > 65535)
3624 val = 65535;
3625 data[i * 2] = val&0xff;
3626 data[i * 2 + 1] = (val >> 8) & 0xff;
3628 free(buckets);
3629 writeData(f, data, numBuckets * 2);
3630 free(data);
3631 } else
3632 free(buckets);
3634 fclose(f);
3637 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3638 * which will be used as a random sampling of PC */
3639 COMMAND_HANDLER(handle_profile_command)
3641 struct target *target = get_current_target(CMD_CTX);
3643 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
3644 return ERROR_COMMAND_SYNTAX_ERROR;
3646 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
3647 uint32_t offset;
3648 uint32_t num_of_samples;
3649 int retval = ERROR_OK;
3651 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
3653 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
3654 if (samples == NULL) {
3655 LOG_ERROR("No memory to store samples.");
3656 return ERROR_FAIL;
3660 * Some cores let us sample the PC without the
3661 * annoying halt/resume step; for example, ARMv7 PCSR.
3662 * Provide a way to use that more efficient mechanism.
3664 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
3665 &num_of_samples, offset);
3666 if (retval != ERROR_OK) {
3667 free(samples);
3668 return retval;
3671 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
3673 retval = target_poll(target);
3674 if (retval != ERROR_OK) {
3675 free(samples);
3676 return retval;
3678 if (target->state == TARGET_RUNNING) {
3679 retval = target_halt(target);
3680 if (retval != ERROR_OK) {
3681 free(samples);
3682 return retval;
3686 retval = target_poll(target);
3687 if (retval != ERROR_OK) {
3688 free(samples);
3689 return retval;
3692 uint32_t start_address = 0;
3693 uint32_t end_address = 0;
3694 bool with_range = false;
3695 if (CMD_ARGC == 4) {
3696 with_range = true;
3697 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
3698 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
3701 write_gmon(samples, num_of_samples, CMD_ARGV[1],
3702 with_range, start_address, end_address);
3703 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3705 free(samples);
3706 return retval;
3709 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3711 char *namebuf;
3712 Jim_Obj *nameObjPtr, *valObjPtr;
3713 int result;
3715 namebuf = alloc_printf("%s(%d)", varname, idx);
3716 if (!namebuf)
3717 return JIM_ERR;
3719 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3720 valObjPtr = Jim_NewIntObj(interp, val);
3721 if (!nameObjPtr || !valObjPtr) {
3722 free(namebuf);
3723 return JIM_ERR;
3726 Jim_IncrRefCount(nameObjPtr);
3727 Jim_IncrRefCount(valObjPtr);
3728 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3729 Jim_DecrRefCount(interp, nameObjPtr);
3730 Jim_DecrRefCount(interp, valObjPtr);
3731 free(namebuf);
3732 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3733 return result;
3736 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3738 struct command_context *context;
3739 struct target *target;
3741 context = current_command_context(interp);
3742 assert(context != NULL);
3744 target = get_current_target(context);
3745 if (target == NULL) {
3746 LOG_ERROR("mem2array: no current target");
3747 return JIM_ERR;
3750 return target_mem2array(interp, target, argc - 1, argv + 1);
3753 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3755 long l;
3756 uint32_t width;
3757 int len;
3758 uint32_t addr;
3759 uint32_t count;
3760 uint32_t v;
3761 const char *varname;
3762 int n, e, retval;
3763 uint32_t i;
3765 /* argv[1] = name of array to receive the data
3766 * argv[2] = desired width
3767 * argv[3] = memory address
3768 * argv[4] = count of times to read
3770 if (argc != 4) {
3771 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3772 return JIM_ERR;
3774 varname = Jim_GetString(argv[0], &len);
3775 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3777 e = Jim_GetLong(interp, argv[1], &l);
3778 width = l;
3779 if (e != JIM_OK)
3780 return e;
3782 e = Jim_GetLong(interp, argv[2], &l);
3783 addr = l;
3784 if (e != JIM_OK)
3785 return e;
3786 e = Jim_GetLong(interp, argv[3], &l);
3787 len = l;
3788 if (e != JIM_OK)
3789 return e;
3790 switch (width) {
3791 case 8:
3792 width = 1;
3793 break;
3794 case 16:
3795 width = 2;
3796 break;
3797 case 32:
3798 width = 4;
3799 break;
3800 default:
3801 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3802 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3803 return JIM_ERR;
3805 if (len == 0) {
3806 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3807 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3808 return JIM_ERR;
3810 if ((addr + (len * width)) < addr) {
3811 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3812 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3813 return JIM_ERR;
3815 /* absurd transfer size? */
3816 if (len > 65536) {
3817 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3818 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3819 return JIM_ERR;
3822 if ((width == 1) ||
3823 ((width == 2) && ((addr & 1) == 0)) ||
3824 ((width == 4) && ((addr & 3) == 0))) {
3825 /* all is well */
3826 } else {
3827 char buf[100];
3828 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3829 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3830 addr,
3831 width);
3832 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3833 return JIM_ERR;
3836 /* Transfer loop */
3838 /* index counter */
3839 n = 0;
3841 size_t buffersize = 4096;
3842 uint8_t *buffer = malloc(buffersize);
3843 if (buffer == NULL)
3844 return JIM_ERR;
3846 /* assume ok */
3847 e = JIM_OK;
3848 while (len) {
3849 /* Slurp... in buffer size chunks */
3851 count = len; /* in objects.. */
3852 if (count > (buffersize / width))
3853 count = (buffersize / width);
3855 retval = target_read_memory(target, addr, width, count, buffer);
3856 if (retval != ERROR_OK) {
3857 /* BOO !*/
3858 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3859 (unsigned int)addr,
3860 (int)width,
3861 (int)count);
3862 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3863 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3864 e = JIM_ERR;
3865 break;
3866 } else {
3867 v = 0; /* shut up gcc */
3868 for (i = 0; i < count ; i++, n++) {
3869 switch (width) {
3870 case 4:
3871 v = target_buffer_get_u32(target, &buffer[i*width]);
3872 break;
3873 case 2:
3874 v = target_buffer_get_u16(target, &buffer[i*width]);
3875 break;
3876 case 1:
3877 v = buffer[i] & 0x0ff;
3878 break;
3880 new_int_array_element(interp, varname, n, v);
3882 len -= count;
3883 addr += count * width;
3887 free(buffer);
3889 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3891 return e;
3894 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
3896 char *namebuf;
3897 Jim_Obj *nameObjPtr, *valObjPtr;
3898 int result;
3899 long l;
3901 namebuf = alloc_printf("%s(%d)", varname, idx);
3902 if (!namebuf)
3903 return JIM_ERR;
3905 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3906 if (!nameObjPtr) {
3907 free(namebuf);
3908 return JIM_ERR;
3911 Jim_IncrRefCount(nameObjPtr);
3912 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3913 Jim_DecrRefCount(interp, nameObjPtr);
3914 free(namebuf);
3915 if (valObjPtr == NULL)
3916 return JIM_ERR;
3918 result = Jim_GetLong(interp, valObjPtr, &l);
3919 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3920 *val = l;
3921 return result;
3924 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3926 struct command_context *context;
3927 struct target *target;
3929 context = current_command_context(interp);
3930 assert(context != NULL);
3932 target = get_current_target(context);
3933 if (target == NULL) {
3934 LOG_ERROR("array2mem: no current target");
3935 return JIM_ERR;
3938 return target_array2mem(interp, target, argc-1, argv + 1);
3941 static int target_array2mem(Jim_Interp *interp, struct target *target,
3942 int argc, Jim_Obj *const *argv)
3944 long l;
3945 uint32_t width;
3946 int len;
3947 uint32_t addr;
3948 uint32_t count;
3949 uint32_t v;
3950 const char *varname;
3951 int n, e, retval;
3952 uint32_t i;
3954 /* argv[1] = name of array to get the data
3955 * argv[2] = desired width
3956 * argv[3] = memory address
3957 * argv[4] = count to write
3959 if (argc != 4) {
3960 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3961 return JIM_ERR;
3963 varname = Jim_GetString(argv[0], &len);
3964 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3966 e = Jim_GetLong(interp, argv[1], &l);
3967 width = l;
3968 if (e != JIM_OK)
3969 return e;
3971 e = Jim_GetLong(interp, argv[2], &l);
3972 addr = l;
3973 if (e != JIM_OK)
3974 return e;
3975 e = Jim_GetLong(interp, argv[3], &l);
3976 len = l;
3977 if (e != JIM_OK)
3978 return e;
3979 switch (width) {
3980 case 8:
3981 width = 1;
3982 break;
3983 case 16:
3984 width = 2;
3985 break;
3986 case 32:
3987 width = 4;
3988 break;
3989 default:
3990 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3991 Jim_AppendStrings(interp, Jim_GetResult(interp),
3992 "Invalid width param, must be 8/16/32", NULL);
3993 return JIM_ERR;
3995 if (len == 0) {
3996 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3997 Jim_AppendStrings(interp, Jim_GetResult(interp),
3998 "array2mem: zero width read?", NULL);
3999 return JIM_ERR;
4001 if ((addr + (len * width)) < addr) {
4002 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4003 Jim_AppendStrings(interp, Jim_GetResult(interp),
4004 "array2mem: addr + len - wraps to zero?", NULL);
4005 return JIM_ERR;
4007 /* absurd transfer size? */
4008 if (len > 65536) {
4009 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4010 Jim_AppendStrings(interp, Jim_GetResult(interp),
4011 "array2mem: absurd > 64K item request", NULL);
4012 return JIM_ERR;
4015 if ((width == 1) ||
4016 ((width == 2) && ((addr & 1) == 0)) ||
4017 ((width == 4) && ((addr & 3) == 0))) {
4018 /* all is well */
4019 } else {
4020 char buf[100];
4021 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4022 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
4023 (unsigned int)addr,
4024 (int)width);
4025 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
4026 return JIM_ERR;
4029 /* Transfer loop */
4031 /* index counter */
4032 n = 0;
4033 /* assume ok */
4034 e = JIM_OK;
4036 size_t buffersize = 4096;
4037 uint8_t *buffer = malloc(buffersize);
4038 if (buffer == NULL)
4039 return JIM_ERR;
4041 while (len) {
4042 /* Slurp... in buffer size chunks */
4044 count = len; /* in objects.. */
4045 if (count > (buffersize / width))
4046 count = (buffersize / width);
4048 v = 0; /* shut up gcc */
4049 for (i = 0; i < count; i++, n++) {
4050 get_int_array_element(interp, varname, n, &v);
4051 switch (width) {
4052 case 4:
4053 target_buffer_set_u32(target, &buffer[i * width], v);
4054 break;
4055 case 2:
4056 target_buffer_set_u16(target, &buffer[i * width], v);
4057 break;
4058 case 1:
4059 buffer[i] = v & 0x0ff;
4060 break;
4063 len -= count;
4065 retval = target_write_memory(target, addr, width, count, buffer);
4066 if (retval != ERROR_OK) {
4067 /* BOO !*/
4068 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
4069 (unsigned int)addr,
4070 (int)width,
4071 (int)count);
4072 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4073 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4074 e = JIM_ERR;
4075 break;
4077 addr += count * width;
4080 free(buffer);
4082 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4084 return e;
4087 /* FIX? should we propagate errors here rather than printing them
4088 * and continuing?
4090 void target_handle_event(struct target *target, enum target_event e)
4092 struct target_event_action *teap;
4094 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4095 if (teap->event == e) {
4096 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
4097 target->target_number,
4098 target_name(target),
4099 target_type_name(target),
4101 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
4102 Jim_GetString(teap->body, NULL));
4103 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
4104 Jim_MakeErrorMessage(teap->interp);
4105 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
4112 * Returns true only if the target has a handler for the specified event.
4114 bool target_has_event_action(struct target *target, enum target_event event)
4116 struct target_event_action *teap;
4118 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4119 if (teap->event == event)
4120 return true;
4122 return false;
4125 enum target_cfg_param {
4126 TCFG_TYPE,
4127 TCFG_EVENT,
4128 TCFG_WORK_AREA_VIRT,
4129 TCFG_WORK_AREA_PHYS,
4130 TCFG_WORK_AREA_SIZE,
4131 TCFG_WORK_AREA_BACKUP,
4132 TCFG_ENDIAN,
4133 TCFG_COREID,
4134 TCFG_CHAIN_POSITION,
4135 TCFG_DBGBASE,
4136 TCFG_RTOS,
4139 static Jim_Nvp nvp_config_opts[] = {
4140 { .name = "-type", .value = TCFG_TYPE },
4141 { .name = "-event", .value = TCFG_EVENT },
4142 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4143 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4144 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4145 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4146 { .name = "-endian" , .value = TCFG_ENDIAN },
4147 { .name = "-coreid", .value = TCFG_COREID },
4148 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4149 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4150 { .name = "-rtos", .value = TCFG_RTOS },
4151 { .name = NULL, .value = -1 }
4154 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
4156 Jim_Nvp *n;
4157 Jim_Obj *o;
4158 jim_wide w;
4159 int e;
4161 /* parse config or cget options ... */
4162 while (goi->argc > 0) {
4163 Jim_SetEmptyResult(goi->interp);
4164 /* Jim_GetOpt_Debug(goi); */
4166 if (target->type->target_jim_configure) {
4167 /* target defines a configure function */
4168 /* target gets first dibs on parameters */
4169 e = (*(target->type->target_jim_configure))(target, goi);
4170 if (e == JIM_OK) {
4171 /* more? */
4172 continue;
4174 if (e == JIM_ERR) {
4175 /* An error */
4176 return e;
4178 /* otherwise we 'continue' below */
4180 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
4181 if (e != JIM_OK) {
4182 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
4183 return e;
4185 switch (n->value) {
4186 case TCFG_TYPE:
4187 /* not setable */
4188 if (goi->isconfigure) {
4189 Jim_SetResultFormatted(goi->interp,
4190 "not settable: %s", n->name);
4191 return JIM_ERR;
4192 } else {
4193 no_params:
4194 if (goi->argc != 0) {
4195 Jim_WrongNumArgs(goi->interp,
4196 goi->argc, goi->argv,
4197 "NO PARAMS");
4198 return JIM_ERR;
4201 Jim_SetResultString(goi->interp,
4202 target_type_name(target), -1);
4203 /* loop for more */
4204 break;
4205 case TCFG_EVENT:
4206 if (goi->argc == 0) {
4207 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4208 return JIM_ERR;
4211 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4212 if (e != JIM_OK) {
4213 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4214 return e;
4217 if (goi->isconfigure) {
4218 if (goi->argc != 1) {
4219 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4220 return JIM_ERR;
4222 } else {
4223 if (goi->argc != 0) {
4224 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4225 return JIM_ERR;
4230 struct target_event_action *teap;
4232 teap = target->event_action;
4233 /* replace existing? */
4234 while (teap) {
4235 if (teap->event == (enum target_event)n->value)
4236 break;
4237 teap = teap->next;
4240 if (goi->isconfigure) {
4241 bool replace = true;
4242 if (teap == NULL) {
4243 /* create new */
4244 teap = calloc(1, sizeof(*teap));
4245 replace = false;
4247 teap->event = n->value;
4248 teap->interp = goi->interp;
4249 Jim_GetOpt_Obj(goi, &o);
4250 if (teap->body)
4251 Jim_DecrRefCount(teap->interp, teap->body);
4252 teap->body = Jim_DuplicateObj(goi->interp, o);
4254 * FIXME:
4255 * Tcl/TK - "tk events" have a nice feature.
4256 * See the "BIND" command.
4257 * We should support that here.
4258 * You can specify %X and %Y in the event code.
4259 * The idea is: %T - target name.
4260 * The idea is: %N - target number
4261 * The idea is: %E - event name.
4263 Jim_IncrRefCount(teap->body);
4265 if (!replace) {
4266 /* add to head of event list */
4267 teap->next = target->event_action;
4268 target->event_action = teap;
4270 Jim_SetEmptyResult(goi->interp);
4271 } else {
4272 /* get */
4273 if (teap == NULL)
4274 Jim_SetEmptyResult(goi->interp);
4275 else
4276 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4279 /* loop for more */
4280 break;
4282 case TCFG_WORK_AREA_VIRT:
4283 if (goi->isconfigure) {
4284 target_free_all_working_areas(target);
4285 e = Jim_GetOpt_Wide(goi, &w);
4286 if (e != JIM_OK)
4287 return e;
4288 target->working_area_virt = w;
4289 target->working_area_virt_spec = true;
4290 } else {
4291 if (goi->argc != 0)
4292 goto no_params;
4294 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4295 /* loop for more */
4296 break;
4298 case TCFG_WORK_AREA_PHYS:
4299 if (goi->isconfigure) {
4300 target_free_all_working_areas(target);
4301 e = Jim_GetOpt_Wide(goi, &w);
4302 if (e != JIM_OK)
4303 return e;
4304 target->working_area_phys = w;
4305 target->working_area_phys_spec = true;
4306 } else {
4307 if (goi->argc != 0)
4308 goto no_params;
4310 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4311 /* loop for more */
4312 break;
4314 case TCFG_WORK_AREA_SIZE:
4315 if (goi->isconfigure) {
4316 target_free_all_working_areas(target);
4317 e = Jim_GetOpt_Wide(goi, &w);
4318 if (e != JIM_OK)
4319 return e;
4320 target->working_area_size = w;
4321 } else {
4322 if (goi->argc != 0)
4323 goto no_params;
4325 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4326 /* loop for more */
4327 break;
4329 case TCFG_WORK_AREA_BACKUP:
4330 if (goi->isconfigure) {
4331 target_free_all_working_areas(target);
4332 e = Jim_GetOpt_Wide(goi, &w);
4333 if (e != JIM_OK)
4334 return e;
4335 /* make this exactly 1 or 0 */
4336 target->backup_working_area = (!!w);
4337 } else {
4338 if (goi->argc != 0)
4339 goto no_params;
4341 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4342 /* loop for more e*/
4343 break;
4346 case TCFG_ENDIAN:
4347 if (goi->isconfigure) {
4348 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4349 if (e != JIM_OK) {
4350 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4351 return e;
4353 target->endianness = n->value;
4354 } else {
4355 if (goi->argc != 0)
4356 goto no_params;
4358 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4359 if (n->name == NULL) {
4360 target->endianness = TARGET_LITTLE_ENDIAN;
4361 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4363 Jim_SetResultString(goi->interp, n->name, -1);
4364 /* loop for more */
4365 break;
4367 case TCFG_COREID:
4368 if (goi->isconfigure) {
4369 e = Jim_GetOpt_Wide(goi, &w);
4370 if (e != JIM_OK)
4371 return e;
4372 target->coreid = (int32_t)w;
4373 } else {
4374 if (goi->argc != 0)
4375 goto no_params;
4377 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4378 /* loop for more */
4379 break;
4381 case TCFG_CHAIN_POSITION:
4382 if (goi->isconfigure) {
4383 Jim_Obj *o_t;
4384 struct jtag_tap *tap;
4385 target_free_all_working_areas(target);
4386 e = Jim_GetOpt_Obj(goi, &o_t);
4387 if (e != JIM_OK)
4388 return e;
4389 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4390 if (tap == NULL)
4391 return JIM_ERR;
4392 /* make this exactly 1 or 0 */
4393 target->tap = tap;
4394 } else {
4395 if (goi->argc != 0)
4396 goto no_params;
4398 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4399 /* loop for more e*/
4400 break;
4401 case TCFG_DBGBASE:
4402 if (goi->isconfigure) {
4403 e = Jim_GetOpt_Wide(goi, &w);
4404 if (e != JIM_OK)
4405 return e;
4406 target->dbgbase = (uint32_t)w;
4407 target->dbgbase_set = true;
4408 } else {
4409 if (goi->argc != 0)
4410 goto no_params;
4412 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4413 /* loop for more */
4414 break;
4416 case TCFG_RTOS:
4417 /* RTOS */
4419 int result = rtos_create(goi, target);
4420 if (result != JIM_OK)
4421 return result;
4423 /* loop for more */
4424 break;
4426 } /* while (goi->argc) */
4429 /* done - we return */
4430 return JIM_OK;
4433 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4435 Jim_GetOptInfo goi;
4437 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4438 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4439 int need_args = 1 + goi.isconfigure;
4440 if (goi.argc < need_args) {
4441 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4442 goi.isconfigure
4443 ? "missing: -option VALUE ..."
4444 : "missing: -option ...");
4445 return JIM_ERR;
4447 struct target *target = Jim_CmdPrivData(goi.interp);
4448 return target_configure(&goi, target);
4451 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4453 const char *cmd_name = Jim_GetString(argv[0], NULL);
4455 Jim_GetOptInfo goi;
4456 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4458 if (goi.argc < 2 || goi.argc > 4) {
4459 Jim_SetResultFormatted(goi.interp,
4460 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4461 return JIM_ERR;
4464 target_write_fn fn;
4465 fn = target_write_memory;
4467 int e;
4468 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4469 /* consume it */
4470 struct Jim_Obj *obj;
4471 e = Jim_GetOpt_Obj(&goi, &obj);
4472 if (e != JIM_OK)
4473 return e;
4475 fn = target_write_phys_memory;
4478 jim_wide a;
4479 e = Jim_GetOpt_Wide(&goi, &a);
4480 if (e != JIM_OK)
4481 return e;
4483 jim_wide b;
4484 e = Jim_GetOpt_Wide(&goi, &b);
4485 if (e != JIM_OK)
4486 return e;
4488 jim_wide c = 1;
4489 if (goi.argc == 1) {
4490 e = Jim_GetOpt_Wide(&goi, &c);
4491 if (e != JIM_OK)
4492 return e;
4495 /* all args must be consumed */
4496 if (goi.argc != 0)
4497 return JIM_ERR;
4499 struct target *target = Jim_CmdPrivData(goi.interp);
4500 unsigned data_size;
4501 if (strcasecmp(cmd_name, "mww") == 0)
4502 data_size = 4;
4503 else if (strcasecmp(cmd_name, "mwh") == 0)
4504 data_size = 2;
4505 else if (strcasecmp(cmd_name, "mwb") == 0)
4506 data_size = 1;
4507 else {
4508 LOG_ERROR("command '%s' unknown: ", cmd_name);
4509 return JIM_ERR;
4512 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4516 * @brief Reads an array of words/halfwords/bytes from target memory starting at specified address.
4518 * Usage: mdw [phys] <address> [<count>] - for 32 bit reads
4519 * mdh [phys] <address> [<count>] - for 16 bit reads
4520 * mdb [phys] <address> [<count>] - for 8 bit reads
4522 * Count defaults to 1.
4524 * Calls target_read_memory or target_read_phys_memory depending on
4525 * the presence of the "phys" argument
4526 * Reads the target memory in blocks of max. 32 bytes, and returns an array of ints formatted
4527 * to int representation in base16.
4528 * Also outputs read data in a human readable form using command_print
4530 * @param phys if present target_read_phys_memory will be used instead of target_read_memory
4531 * @param address address where to start the read. May be specified in decimal or hex using the standard "0x" prefix
4532 * @param count optional count parameter to read an array of values. If not specified, defaults to 1.
4533 * @returns: JIM_ERR on error or JIM_OK on success and sets the result string to an array of ascii formatted numbers
4534 * on success, with [<count>] number of elements.
4536 * In case of little endian target:
4537 * Example1: "mdw 0x00000000" returns "10123456"
4538 * Exmaple2: "mdh 0x00000000 1" returns "3456"
4539 * Example3: "mdb 0x00000000" returns "56"
4540 * Example4: "mdh 0x00000000 2" returns "3456 1012"
4541 * Example5: "mdb 0x00000000 3" returns "56 34 12"
4543 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4545 const char *cmd_name = Jim_GetString(argv[0], NULL);
4547 Jim_GetOptInfo goi;
4548 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4550 if ((goi.argc < 1) || (goi.argc > 3)) {
4551 Jim_SetResultFormatted(goi.interp,
4552 "usage: %s [phys] <address> [<count>]", cmd_name);
4553 return JIM_ERR;
4556 int (*fn)(struct target *target,
4557 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4558 fn = target_read_memory;
4560 int e;
4561 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4562 /* consume it */
4563 struct Jim_Obj *obj;
4564 e = Jim_GetOpt_Obj(&goi, &obj);
4565 if (e != JIM_OK)
4566 return e;
4568 fn = target_read_phys_memory;
4571 /* Read address parameter */
4572 jim_wide addr;
4573 e = Jim_GetOpt_Wide(&goi, &addr);
4574 if (e != JIM_OK)
4575 return JIM_ERR;
4577 /* If next parameter exists, read it out as the count parameter, if not, set it to 1 (default) */
4578 jim_wide count;
4579 if (goi.argc == 1) {
4580 e = Jim_GetOpt_Wide(&goi, &count);
4581 if (e != JIM_OK)
4582 return JIM_ERR;
4583 } else
4584 count = 1;
4586 /* all args must be consumed */
4587 if (goi.argc != 0)
4588 return JIM_ERR;
4590 jim_wide dwidth = 1; /* shut up gcc */
4591 if (strcasecmp(cmd_name, "mdw") == 0)
4592 dwidth = 4;
4593 else if (strcasecmp(cmd_name, "mdh") == 0)
4594 dwidth = 2;
4595 else if (strcasecmp(cmd_name, "mdb") == 0)
4596 dwidth = 1;
4597 else {
4598 LOG_ERROR("command '%s' unknown: ", cmd_name);
4599 return JIM_ERR;
4602 /* convert count to "bytes" */
4603 int bytes = count * dwidth;
4605 struct target *target = Jim_CmdPrivData(goi.interp);
4606 uint8_t target_buf[32];
4607 jim_wide x, y, z;
4608 while (bytes > 0) {
4609 y = (bytes < 16) ? bytes : 16; /* y = min(bytes, 16); */
4611 /* Try to read out next block */
4612 e = fn(target, addr, dwidth, y / dwidth, target_buf);
4614 if (e != ERROR_OK) {
4615 Jim_SetResultFormatted(interp, "error reading target @ 0x%08lx", (long)addr);
4616 return JIM_ERR;
4619 command_print_sameline(NULL, "0x%08x ", (int)(addr));
4620 switch (dwidth) {
4621 case 4:
4622 for (x = 0; x < 16 && x < y; x += 4) {
4623 z = target_buffer_get_u32(target, &(target_buf[x]));
4624 command_print_sameline(NULL, "%08x ", (int)(z));
4626 for (; (x < 16) ; x += 4)
4627 command_print_sameline(NULL, " ");
4628 break;
4629 case 2:
4630 for (x = 0; x < 16 && x < y; x += 2) {
4631 z = target_buffer_get_u16(target, &(target_buf[x]));
4632 command_print_sameline(NULL, "%04x ", (int)(z));
4634 for (; (x < 16) ; x += 2)
4635 command_print_sameline(NULL, " ");
4636 break;
4637 case 1:
4638 default:
4639 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4640 z = target_buffer_get_u8(target, &(target_buf[x]));
4641 command_print_sameline(NULL, "%02x ", (int)(z));
4643 for (; (x < 16) ; x += 1)
4644 command_print_sameline(NULL, " ");
4645 break;
4647 /* ascii-ify the bytes */
4648 for (x = 0 ; x < y ; x++) {
4649 if ((target_buf[x] >= 0x20) &&
4650 (target_buf[x] <= 0x7e)) {
4651 /* good */
4652 } else {
4653 /* smack it */
4654 target_buf[x] = '.';
4657 /* space pad */
4658 while (x < 16) {
4659 target_buf[x] = ' ';
4660 x++;
4662 /* terminate */
4663 target_buf[16] = 0;
4664 /* print - with a newline */
4665 command_print_sameline(NULL, "%s\n", target_buf);
4666 /* NEXT... */
4667 bytes -= 16;
4668 addr += 16;
4670 return JIM_OK;
4673 static int jim_target_mem2array(Jim_Interp *interp,
4674 int argc, Jim_Obj *const *argv)
4676 struct target *target = Jim_CmdPrivData(interp);
4677 return target_mem2array(interp, target, argc - 1, argv + 1);
4680 static int jim_target_array2mem(Jim_Interp *interp,
4681 int argc, Jim_Obj *const *argv)
4683 struct target *target = Jim_CmdPrivData(interp);
4684 return target_array2mem(interp, target, argc - 1, argv + 1);
4687 static int jim_target_tap_disabled(Jim_Interp *interp)
4689 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4690 return JIM_ERR;
4693 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4695 if (argc != 1) {
4696 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4697 return JIM_ERR;
4699 struct target *target = Jim_CmdPrivData(interp);
4700 if (!target->tap->enabled)
4701 return jim_target_tap_disabled(interp);
4703 int e = target->type->examine(target);
4704 if (e != ERROR_OK)
4705 return JIM_ERR;
4706 return JIM_OK;
4709 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4711 if (argc != 1) {
4712 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4713 return JIM_ERR;
4715 struct target *target = Jim_CmdPrivData(interp);
4717 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4718 return JIM_ERR;
4720 return JIM_OK;
4723 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4725 if (argc != 1) {
4726 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4727 return JIM_ERR;
4729 struct target *target = Jim_CmdPrivData(interp);
4730 if (!target->tap->enabled)
4731 return jim_target_tap_disabled(interp);
4733 int e;
4734 if (!(target_was_examined(target)))
4735 e = ERROR_TARGET_NOT_EXAMINED;
4736 else
4737 e = target->type->poll(target);
4738 if (e != ERROR_OK)
4739 return JIM_ERR;
4740 return JIM_OK;
4743 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4745 Jim_GetOptInfo goi;
4746 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4748 if (goi.argc != 2) {
4749 Jim_WrongNumArgs(interp, 0, argv,
4750 "([tT]|[fF]|assert|deassert) BOOL");
4751 return JIM_ERR;
4754 Jim_Nvp *n;
4755 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4756 if (e != JIM_OK) {
4757 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4758 return e;
4760 /* the halt or not param */
4761 jim_wide a;
4762 e = Jim_GetOpt_Wide(&goi, &a);
4763 if (e != JIM_OK)
4764 return e;
4766 struct target *target = Jim_CmdPrivData(goi.interp);
4767 if (!target->tap->enabled)
4768 return jim_target_tap_disabled(interp);
4769 if (!(target_was_examined(target))) {
4770 LOG_ERROR("Target not examined yet");
4771 return ERROR_TARGET_NOT_EXAMINED;
4773 if (!target->type->assert_reset || !target->type->deassert_reset) {
4774 Jim_SetResultFormatted(interp,
4775 "No target-specific reset for %s",
4776 target_name(target));
4777 return JIM_ERR;
4779 /* determine if we should halt or not. */
4780 target->reset_halt = !!a;
4781 /* When this happens - all workareas are invalid. */
4782 target_free_all_working_areas_restore(target, 0);
4784 /* do the assert */
4785 if (n->value == NVP_ASSERT)
4786 e = target->type->assert_reset(target);
4787 else
4788 e = target->type->deassert_reset(target);
4789 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4792 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4794 if (argc != 1) {
4795 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4796 return JIM_ERR;
4798 struct target *target = Jim_CmdPrivData(interp);
4799 if (!target->tap->enabled)
4800 return jim_target_tap_disabled(interp);
4801 int e = target->type->halt(target);
4802 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4805 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4807 Jim_GetOptInfo goi;
4808 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4810 /* params: <name> statename timeoutmsecs */
4811 if (goi.argc != 2) {
4812 const char *cmd_name = Jim_GetString(argv[0], NULL);
4813 Jim_SetResultFormatted(goi.interp,
4814 "%s <state_name> <timeout_in_msec>", cmd_name);
4815 return JIM_ERR;
4818 Jim_Nvp *n;
4819 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4820 if (e != JIM_OK) {
4821 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
4822 return e;
4824 jim_wide a;
4825 e = Jim_GetOpt_Wide(&goi, &a);
4826 if (e != JIM_OK)
4827 return e;
4828 struct target *target = Jim_CmdPrivData(interp);
4829 if (!target->tap->enabled)
4830 return jim_target_tap_disabled(interp);
4832 e = target_wait_state(target, n->value, a);
4833 if (e != ERROR_OK) {
4834 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4835 Jim_SetResultFormatted(goi.interp,
4836 "target: %s wait %s fails (%#s) %s",
4837 target_name(target), n->name,
4838 eObj, target_strerror_safe(e));
4839 Jim_FreeNewObj(interp, eObj);
4840 return JIM_ERR;
4842 return JIM_OK;
4844 /* List for human, Events defined for this target.
4845 * scripts/programs should use 'name cget -event NAME'
4847 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4849 struct command_context *cmd_ctx = current_command_context(interp);
4850 assert(cmd_ctx != NULL);
4852 struct target *target = Jim_CmdPrivData(interp);
4853 struct target_event_action *teap = target->event_action;
4854 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4855 target->target_number,
4856 target_name(target));
4857 command_print(cmd_ctx, "%-25s | Body", "Event");
4858 command_print(cmd_ctx, "------------------------- | "
4859 "----------------------------------------");
4860 while (teap) {
4861 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4862 command_print(cmd_ctx, "%-25s | %s",
4863 opt->name, Jim_GetString(teap->body, NULL));
4864 teap = teap->next;
4866 command_print(cmd_ctx, "***END***");
4867 return JIM_OK;
4869 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4871 if (argc != 1) {
4872 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4873 return JIM_ERR;
4875 struct target *target = Jim_CmdPrivData(interp);
4876 Jim_SetResultString(interp, target_state_name(target), -1);
4877 return JIM_OK;
4879 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4881 Jim_GetOptInfo goi;
4882 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4883 if (goi.argc != 1) {
4884 const char *cmd_name = Jim_GetString(argv[0], NULL);
4885 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4886 return JIM_ERR;
4888 Jim_Nvp *n;
4889 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4890 if (e != JIM_OK) {
4891 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4892 return e;
4894 struct target *target = Jim_CmdPrivData(interp);
4895 target_handle_event(target, n->value);
4896 return JIM_OK;
4899 static const struct command_registration target_instance_command_handlers[] = {
4901 .name = "configure",
4902 .mode = COMMAND_CONFIG,
4903 .jim_handler = jim_target_configure,
4904 .help = "configure a new target for use",
4905 .usage = "[target_attribute ...]",
4908 .name = "cget",
4909 .mode = COMMAND_ANY,
4910 .jim_handler = jim_target_configure,
4911 .help = "returns the specified target attribute",
4912 .usage = "target_attribute",
4915 .name = "mww",
4916 .mode = COMMAND_EXEC,
4917 .jim_handler = jim_target_mw,
4918 .help = "Write 32-bit word(s) to target memory",
4919 .usage = "address data [count]",
4922 .name = "mwh",
4923 .mode = COMMAND_EXEC,
4924 .jim_handler = jim_target_mw,
4925 .help = "Write 16-bit half-word(s) to target memory",
4926 .usage = "address data [count]",
4929 .name = "mwb",
4930 .mode = COMMAND_EXEC,
4931 .jim_handler = jim_target_mw,
4932 .help = "Write byte(s) to target memory",
4933 .usage = "address data [count]",
4936 .name = "mdw",
4937 .mode = COMMAND_EXEC,
4938 .jim_handler = jim_target_md,
4939 .help = "Display target memory as 32-bit words",
4940 .usage = "address [count]",
4943 .name = "mdh",
4944 .mode = COMMAND_EXEC,
4945 .jim_handler = jim_target_md,
4946 .help = "Display target memory as 16-bit half-words",
4947 .usage = "address [count]",
4950 .name = "mdb",
4951 .mode = COMMAND_EXEC,
4952 .jim_handler = jim_target_md,
4953 .help = "Display target memory as 8-bit bytes",
4954 .usage = "address [count]",
4957 .name = "array2mem",
4958 .mode = COMMAND_EXEC,
4959 .jim_handler = jim_target_array2mem,
4960 .help = "Writes Tcl array of 8/16/32 bit numbers "
4961 "to target memory",
4962 .usage = "arrayname bitwidth address count",
4965 .name = "mem2array",
4966 .mode = COMMAND_EXEC,
4967 .jim_handler = jim_target_mem2array,
4968 .help = "Loads Tcl array of 8/16/32 bit numbers "
4969 "from target memory",
4970 .usage = "arrayname bitwidth address count",
4973 .name = "eventlist",
4974 .mode = COMMAND_EXEC,
4975 .jim_handler = jim_target_event_list,
4976 .help = "displays a table of events defined for this target",
4979 .name = "curstate",
4980 .mode = COMMAND_EXEC,
4981 .jim_handler = jim_target_current_state,
4982 .help = "displays the current state of this target",
4985 .name = "arp_examine",
4986 .mode = COMMAND_EXEC,
4987 .jim_handler = jim_target_examine,
4988 .help = "used internally for reset processing",
4991 .name = "arp_halt_gdb",
4992 .mode = COMMAND_EXEC,
4993 .jim_handler = jim_target_halt_gdb,
4994 .help = "used internally for reset processing to halt GDB",
4997 .name = "arp_poll",
4998 .mode = COMMAND_EXEC,
4999 .jim_handler = jim_target_poll,
5000 .help = "used internally for reset processing",
5003 .name = "arp_reset",
5004 .mode = COMMAND_EXEC,
5005 .jim_handler = jim_target_reset,
5006 .help = "used internally for reset processing",
5009 .name = "arp_halt",
5010 .mode = COMMAND_EXEC,
5011 .jim_handler = jim_target_halt,
5012 .help = "used internally for reset processing",
5015 .name = "arp_waitstate",
5016 .mode = COMMAND_EXEC,
5017 .jim_handler = jim_target_wait_state,
5018 .help = "used internally for reset processing",
5021 .name = "invoke-event",
5022 .mode = COMMAND_EXEC,
5023 .jim_handler = jim_target_invoke_event,
5024 .help = "invoke handler for specified event",
5025 .usage = "event_name",
5027 COMMAND_REGISTRATION_DONE
5030 static int target_create(Jim_GetOptInfo *goi)
5032 Jim_Obj *new_cmd;
5033 Jim_Cmd *cmd;
5034 const char *cp;
5035 char *cp2;
5036 int e;
5037 int x;
5038 struct target *target;
5039 struct command_context *cmd_ctx;
5041 cmd_ctx = current_command_context(goi->interp);
5042 assert(cmd_ctx != NULL);
5044 if (goi->argc < 3) {
5045 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5046 return JIM_ERR;
5049 /* COMMAND */
5050 Jim_GetOpt_Obj(goi, &new_cmd);
5051 /* does this command exist? */
5052 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
5053 if (cmd) {
5054 cp = Jim_GetString(new_cmd, NULL);
5055 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5056 return JIM_ERR;
5059 /* TYPE */
5060 e = Jim_GetOpt_String(goi, &cp2, NULL);
5061 if (e != JIM_OK)
5062 return e;
5063 cp = cp2;
5064 struct transport *tr = get_current_transport();
5065 if (tr->override_target) {
5066 e = tr->override_target(&cp);
5067 if (e != ERROR_OK) {
5068 LOG_ERROR("The selected transport doesn't support this target");
5069 return JIM_ERR;
5071 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5073 /* now does target type exist */
5074 for (x = 0 ; target_types[x] ; x++) {
5075 if (0 == strcmp(cp, target_types[x]->name)) {
5076 /* found */
5077 break;
5080 /* check for deprecated name */
5081 if (target_types[x]->deprecated_name) {
5082 if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
5083 /* found */
5084 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
5085 break;
5089 if (target_types[x] == NULL) {
5090 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5091 for (x = 0 ; target_types[x] ; x++) {
5092 if (target_types[x + 1]) {
5093 Jim_AppendStrings(goi->interp,
5094 Jim_GetResult(goi->interp),
5095 target_types[x]->name,
5096 ", ", NULL);
5097 } else {
5098 Jim_AppendStrings(goi->interp,
5099 Jim_GetResult(goi->interp),
5100 " or ",
5101 target_types[x]->name, NULL);
5104 return JIM_ERR;
5107 /* Create it */
5108 target = calloc(1, sizeof(struct target));
5109 /* set target number */
5110 target->target_number = new_target_number();
5111 cmd_ctx->current_target = target->target_number;
5113 /* allocate memory for each unique target type */
5114 target->type = calloc(1, sizeof(struct target_type));
5116 memcpy(target->type, target_types[x], sizeof(struct target_type));
5118 /* will be set by "-endian" */
5119 target->endianness = TARGET_ENDIAN_UNKNOWN;
5121 /* default to first core, override with -coreid */
5122 target->coreid = 0;
5124 target->working_area = 0x0;
5125 target->working_area_size = 0x0;
5126 target->working_areas = NULL;
5127 target->backup_working_area = 0;
5129 target->state = TARGET_UNKNOWN;
5130 target->debug_reason = DBG_REASON_UNDEFINED;
5131 target->reg_cache = NULL;
5132 target->breakpoints = NULL;
5133 target->watchpoints = NULL;
5134 target->next = NULL;
5135 target->arch_info = NULL;
5137 target->display = 1;
5139 target->halt_issued = false;
5141 /* initialize trace information */
5142 target->trace_info = malloc(sizeof(struct trace));
5143 target->trace_info->num_trace_points = 0;
5144 target->trace_info->trace_points_size = 0;
5145 target->trace_info->trace_points = NULL;
5146 target->trace_info->trace_history_size = 0;
5147 target->trace_info->trace_history = NULL;
5148 target->trace_info->trace_history_pos = 0;
5149 target->trace_info->trace_history_overflowed = 0;
5151 target->dbgmsg = NULL;
5152 target->dbg_msg_enabled = 0;
5154 target->endianness = TARGET_ENDIAN_UNKNOWN;
5156 target->rtos = NULL;
5157 target->rtos_auto_detect = false;
5159 /* Do the rest as "configure" options */
5160 goi->isconfigure = 1;
5161 e = target_configure(goi, target);
5163 if (target->tap == NULL) {
5164 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
5165 e = JIM_ERR;
5168 if (e != JIM_OK) {
5169 free(target->type);
5170 free(target);
5171 return e;
5174 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5175 /* default endian to little if not specified */
5176 target->endianness = TARGET_LITTLE_ENDIAN;
5179 cp = Jim_GetString(new_cmd, NULL);
5180 target->cmd_name = strdup(cp);
5182 /* create the target specific commands */
5183 if (target->type->commands) {
5184 e = register_commands(cmd_ctx, NULL, target->type->commands);
5185 if (ERROR_OK != e)
5186 LOG_ERROR("unable to register '%s' commands", cp);
5188 if (target->type->target_create)
5189 (*(target->type->target_create))(target, goi->interp);
5191 /* append to end of list */
5193 struct target **tpp;
5194 tpp = &(all_targets);
5195 while (*tpp)
5196 tpp = &((*tpp)->next);
5197 *tpp = target;
5200 /* now - create the new target name command */
5201 const struct command_registration target_subcommands[] = {
5203 .chain = target_instance_command_handlers,
5206 .chain = target->type->commands,
5208 COMMAND_REGISTRATION_DONE
5210 const struct command_registration target_commands[] = {
5212 .name = cp,
5213 .mode = COMMAND_ANY,
5214 .help = "target command group",
5215 .usage = "",
5216 .chain = target_subcommands,
5218 COMMAND_REGISTRATION_DONE
5220 e = register_commands(cmd_ctx, NULL, target_commands);
5221 if (ERROR_OK != e)
5222 return JIM_ERR;
5224 struct command *c = command_find_in_context(cmd_ctx, cp);
5225 assert(c);
5226 command_set_handler_data(c, target);
5228 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5231 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5233 if (argc != 1) {
5234 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5235 return JIM_ERR;
5237 struct command_context *cmd_ctx = current_command_context(interp);
5238 assert(cmd_ctx != NULL);
5240 Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5241 return JIM_OK;
5244 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5246 if (argc != 1) {
5247 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5248 return JIM_ERR;
5250 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5251 for (unsigned x = 0; NULL != target_types[x]; x++) {
5252 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5253 Jim_NewStringObj(interp, target_types[x]->name, -1));
5255 return JIM_OK;
5258 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5260 if (argc != 1) {
5261 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5262 return JIM_ERR;
5264 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5265 struct target *target = all_targets;
5266 while (target) {
5267 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5268 Jim_NewStringObj(interp, target_name(target), -1));
5269 target = target->next;
5271 return JIM_OK;
5274 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5276 int i;
5277 const char *targetname;
5278 int retval, len;
5279 struct target *target = (struct target *) NULL;
5280 struct target_list *head, *curr, *new;
5281 curr = (struct target_list *) NULL;
5282 head = (struct target_list *) NULL;
5284 retval = 0;
5285 LOG_DEBUG("%d", argc);
5286 /* argv[1] = target to associate in smp
5287 * argv[2] = target to assoicate in smp
5288 * argv[3] ...
5291 for (i = 1; i < argc; i++) {
5293 targetname = Jim_GetString(argv[i], &len);
5294 target = get_target(targetname);
5295 LOG_DEBUG("%s ", targetname);
5296 if (target) {
5297 new = malloc(sizeof(struct target_list));
5298 new->target = target;
5299 new->next = (struct target_list *)NULL;
5300 if (head == (struct target_list *)NULL) {
5301 head = new;
5302 curr = head;
5303 } else {
5304 curr->next = new;
5305 curr = new;
5309 /* now parse the list of cpu and put the target in smp mode*/
5310 curr = head;
5312 while (curr != (struct target_list *)NULL) {
5313 target = curr->target;
5314 target->smp = 1;
5315 target->head = head;
5316 curr = curr->next;
5319 if (target && target->rtos)
5320 retval = rtos_smp_init(head->target);
5322 return retval;
5326 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5328 Jim_GetOptInfo goi;
5329 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5330 if (goi.argc < 3) {
5331 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5332 "<name> <target_type> [<target_options> ...]");
5333 return JIM_ERR;
5335 return target_create(&goi);
5338 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5340 Jim_GetOptInfo goi;
5341 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5343 /* It's OK to remove this mechanism sometime after August 2010 or so */
5344 LOG_WARNING("don't use numbers as target identifiers; use names");
5345 if (goi.argc != 1) {
5346 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
5347 return JIM_ERR;
5349 jim_wide w;
5350 int e = Jim_GetOpt_Wide(&goi, &w);
5351 if (e != JIM_OK)
5352 return JIM_ERR;
5354 struct target *target;
5355 for (target = all_targets; NULL != target; target = target->next) {
5356 if (target->target_number != w)
5357 continue;
5359 Jim_SetResultString(goi.interp, target_name(target), -1);
5360 return JIM_OK;
5363 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
5364 Jim_SetResultFormatted(goi.interp,
5365 "Target: number %#s does not exist", wObj);
5366 Jim_FreeNewObj(interp, wObj);
5368 return JIM_ERR;
5371 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5373 if (argc != 1) {
5374 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
5375 return JIM_ERR;
5377 unsigned count = 0;
5378 struct target *target = all_targets;
5379 while (NULL != target) {
5380 target = target->next;
5381 count++;
5383 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
5384 return JIM_OK;
5387 static const struct command_registration target_subcommand_handlers[] = {
5389 .name = "init",
5390 .mode = COMMAND_CONFIG,
5391 .handler = handle_target_init_command,
5392 .help = "initialize targets",
5395 .name = "create",
5396 /* REVISIT this should be COMMAND_CONFIG ... */
5397 .mode = COMMAND_ANY,
5398 .jim_handler = jim_target_create,
5399 .usage = "name type '-chain-position' name [options ...]",
5400 .help = "Creates and selects a new target",
5403 .name = "current",
5404 .mode = COMMAND_ANY,
5405 .jim_handler = jim_target_current,
5406 .help = "Returns the currently selected target",
5409 .name = "types",
5410 .mode = COMMAND_ANY,
5411 .jim_handler = jim_target_types,
5412 .help = "Returns the available target types as "
5413 "a list of strings",
5416 .name = "names",
5417 .mode = COMMAND_ANY,
5418 .jim_handler = jim_target_names,
5419 .help = "Returns the names of all targets as a list of strings",
5422 .name = "number",
5423 .mode = COMMAND_ANY,
5424 .jim_handler = jim_target_number,
5425 .usage = "number",
5426 .help = "Returns the name of the numbered target "
5427 "(DEPRECATED)",
5430 .name = "count",
5431 .mode = COMMAND_ANY,
5432 .jim_handler = jim_target_count,
5433 .help = "Returns the number of targets as an integer "
5434 "(DEPRECATED)",
5437 .name = "smp",
5438 .mode = COMMAND_ANY,
5439 .jim_handler = jim_target_smp,
5440 .usage = "targetname1 targetname2 ...",
5441 .help = "gather several target in a smp list"
5444 COMMAND_REGISTRATION_DONE
5447 struct FastLoad {
5448 uint32_t address;
5449 uint8_t *data;
5450 int length;
5454 static int fastload_num;
5455 static struct FastLoad *fastload;
5457 static void free_fastload(void)
5459 if (fastload != NULL) {
5460 int i;
5461 for (i = 0; i < fastload_num; i++) {
5462 if (fastload[i].data)
5463 free(fastload[i].data);
5465 free(fastload);
5466 fastload = NULL;
5470 COMMAND_HANDLER(handle_fast_load_image_command)
5472 uint8_t *buffer;
5473 size_t buf_cnt;
5474 uint32_t image_size;
5475 uint32_t min_address = 0;
5476 uint32_t max_address = 0xffffffff;
5477 int i;
5479 struct image image;
5481 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5482 &image, &min_address, &max_address);
5483 if (ERROR_OK != retval)
5484 return retval;
5486 struct duration bench;
5487 duration_start(&bench);
5489 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5490 if (retval != ERROR_OK)
5491 return retval;
5493 image_size = 0x0;
5494 retval = ERROR_OK;
5495 fastload_num = image.num_sections;
5496 fastload = malloc(sizeof(struct FastLoad)*image.num_sections);
5497 if (fastload == NULL) {
5498 command_print(CMD_CTX, "out of memory");
5499 image_close(&image);
5500 return ERROR_FAIL;
5502 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5503 for (i = 0; i < image.num_sections; i++) {
5504 buffer = malloc(image.sections[i].size);
5505 if (buffer == NULL) {
5506 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5507 (int)(image.sections[i].size));
5508 retval = ERROR_FAIL;
5509 break;
5512 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5513 if (retval != ERROR_OK) {
5514 free(buffer);
5515 break;
5518 uint32_t offset = 0;
5519 uint32_t length = buf_cnt;
5521 /* DANGER!!! beware of unsigned comparision here!!! */
5523 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5524 (image.sections[i].base_address < max_address)) {
5525 if (image.sections[i].base_address < min_address) {
5526 /* clip addresses below */
5527 offset += min_address-image.sections[i].base_address;
5528 length -= offset;
5531 if (image.sections[i].base_address + buf_cnt > max_address)
5532 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5534 fastload[i].address = image.sections[i].base_address + offset;
5535 fastload[i].data = malloc(length);
5536 if (fastload[i].data == NULL) {
5537 free(buffer);
5538 command_print(CMD_CTX, "error allocating buffer for section (%" PRIu32 " bytes)",
5539 length);
5540 retval = ERROR_FAIL;
5541 break;
5543 memcpy(fastload[i].data, buffer + offset, length);
5544 fastload[i].length = length;
5546 image_size += length;
5547 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5548 (unsigned int)length,
5549 ((unsigned int)(image.sections[i].base_address + offset)));
5552 free(buffer);
5555 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5556 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5557 "in %fs (%0.3f KiB/s)", image_size,
5558 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5560 command_print(CMD_CTX,
5561 "WARNING: image has not been loaded to target!"
5562 "You can issue a 'fast_load' to finish loading.");
5565 image_close(&image);
5567 if (retval != ERROR_OK)
5568 free_fastload();
5570 return retval;
5573 COMMAND_HANDLER(handle_fast_load_command)
5575 if (CMD_ARGC > 0)
5576 return ERROR_COMMAND_SYNTAX_ERROR;
5577 if (fastload == NULL) {
5578 LOG_ERROR("No image in memory");
5579 return ERROR_FAIL;
5581 int i;
5582 int ms = timeval_ms();
5583 int size = 0;
5584 int retval = ERROR_OK;
5585 for (i = 0; i < fastload_num; i++) {
5586 struct target *target = get_current_target(CMD_CTX);
5587 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5588 (unsigned int)(fastload[i].address),
5589 (unsigned int)(fastload[i].length));
5590 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5591 if (retval != ERROR_OK)
5592 break;
5593 size += fastload[i].length;
5595 if (retval == ERROR_OK) {
5596 int after = timeval_ms();
5597 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5599 return retval;
5602 static const struct command_registration target_command_handlers[] = {
5604 .name = "targets",
5605 .handler = handle_targets_command,
5606 .mode = COMMAND_ANY,
5607 .help = "change current default target (one parameter) "
5608 "or prints table of all targets (no parameters)",
5609 .usage = "[target]",
5612 .name = "target",
5613 .mode = COMMAND_CONFIG,
5614 .help = "configure target",
5616 .chain = target_subcommand_handlers,
5618 COMMAND_REGISTRATION_DONE
5621 int target_register_commands(struct command_context *cmd_ctx)
5623 return register_commands(cmd_ctx, NULL, target_command_handlers);
5626 static bool target_reset_nag = true;
5628 bool get_target_reset_nag(void)
5630 return target_reset_nag;
5633 COMMAND_HANDLER(handle_target_reset_nag)
5635 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5636 &target_reset_nag, "Nag after each reset about options to improve "
5637 "performance");
5640 COMMAND_HANDLER(handle_ps_command)
5642 struct target *target = get_current_target(CMD_CTX);
5643 char *display;
5644 if (target->state != TARGET_HALTED) {
5645 LOG_INFO("target not halted !!");
5646 return ERROR_OK;
5649 if ((target->rtos) && (target->rtos->type)
5650 && (target->rtos->type->ps_command)) {
5651 display = target->rtos->type->ps_command(target);
5652 command_print(CMD_CTX, "%s", display);
5653 free(display);
5654 return ERROR_OK;
5655 } else {
5656 LOG_INFO("failed");
5657 return ERROR_TARGET_FAILURE;
5661 static void binprint(struct command_context *cmd_ctx, const char *text, const uint8_t *buf, int size)
5663 if (text != NULL)
5664 command_print_sameline(cmd_ctx, "%s", text);
5665 for (int i = 0; i < size; i++)
5666 command_print_sameline(cmd_ctx, " %02x", buf[i]);
5667 command_print(cmd_ctx, " ");
5670 COMMAND_HANDLER(handle_test_mem_access_command)
5672 struct target *target = get_current_target(CMD_CTX);
5673 uint32_t test_size;
5674 int retval = ERROR_OK;
5676 if (target->state != TARGET_HALTED) {
5677 LOG_INFO("target not halted !!");
5678 return ERROR_FAIL;
5681 if (CMD_ARGC != 1)
5682 return ERROR_COMMAND_SYNTAX_ERROR;
5684 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
5686 /* Test reads */
5687 size_t num_bytes = test_size + 4;
5689 struct working_area *wa = NULL;
5690 retval = target_alloc_working_area(target, num_bytes, &wa);
5691 if (retval != ERROR_OK) {
5692 LOG_ERROR("Not enough working area");
5693 return ERROR_FAIL;
5696 uint8_t *test_pattern = malloc(num_bytes);
5698 for (size_t i = 0; i < num_bytes; i++)
5699 test_pattern[i] = rand();
5701 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
5702 if (retval != ERROR_OK) {
5703 LOG_ERROR("Test pattern write failed");
5704 goto out;
5707 for (int host_offset = 0; host_offset <= 1; host_offset++) {
5708 for (int size = 1; size <= 4; size *= 2) {
5709 for (int offset = 0; offset < 4; offset++) {
5710 uint32_t count = test_size / size;
5711 size_t host_bufsiz = (count + 2) * size + host_offset;
5712 uint8_t *read_ref = malloc(host_bufsiz);
5713 uint8_t *read_buf = malloc(host_bufsiz);
5715 for (size_t i = 0; i < host_bufsiz; i++) {
5716 read_ref[i] = rand();
5717 read_buf[i] = read_ref[i];
5719 command_print_sameline(CMD_CTX,
5720 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
5721 size, offset, host_offset ? "un" : "");
5723 struct duration bench;
5724 duration_start(&bench);
5726 retval = target_read_memory(target, wa->address + offset, size, count,
5727 read_buf + size + host_offset);
5729 duration_measure(&bench);
5731 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
5732 command_print(CMD_CTX, "Unsupported alignment");
5733 goto next;
5734 } else if (retval != ERROR_OK) {
5735 command_print(CMD_CTX, "Memory read failed");
5736 goto next;
5739 /* replay on host */
5740 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
5742 /* check result */
5743 int result = memcmp(read_ref, read_buf, host_bufsiz);
5744 if (result == 0) {
5745 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
5746 duration_elapsed(&bench),
5747 duration_kbps(&bench, count * size));
5748 } else {
5749 command_print(CMD_CTX, "Compare failed");
5750 binprint(CMD_CTX, "ref:", read_ref, host_bufsiz);
5751 binprint(CMD_CTX, "buf:", read_buf, host_bufsiz);
5753 next:
5754 free(read_ref);
5755 free(read_buf);
5760 out:
5761 free(test_pattern);
5763 if (wa != NULL)
5764 target_free_working_area(target, wa);
5766 /* Test writes */
5767 num_bytes = test_size + 4 + 4 + 4;
5769 retval = target_alloc_working_area(target, num_bytes, &wa);
5770 if (retval != ERROR_OK) {
5771 LOG_ERROR("Not enough working area");
5772 return ERROR_FAIL;
5775 test_pattern = malloc(num_bytes);
5777 for (size_t i = 0; i < num_bytes; i++)
5778 test_pattern[i] = rand();
5780 for (int host_offset = 0; host_offset <= 1; host_offset++) {
5781 for (int size = 1; size <= 4; size *= 2) {
5782 for (int offset = 0; offset < 4; offset++) {
5783 uint32_t count = test_size / size;
5784 size_t host_bufsiz = count * size + host_offset;
5785 uint8_t *read_ref = malloc(num_bytes);
5786 uint8_t *read_buf = malloc(num_bytes);
5787 uint8_t *write_buf = malloc(host_bufsiz);
5789 for (size_t i = 0; i < host_bufsiz; i++)
5790 write_buf[i] = rand();
5791 command_print_sameline(CMD_CTX,
5792 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
5793 size, offset, host_offset ? "un" : "");
5795 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
5796 if (retval != ERROR_OK) {
5797 command_print(CMD_CTX, "Test pattern write failed");
5798 goto nextw;
5801 /* replay on host */
5802 memcpy(read_ref, test_pattern, num_bytes);
5803 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
5805 struct duration bench;
5806 duration_start(&bench);
5808 retval = target_write_memory(target, wa->address + size + offset, size, count,
5809 write_buf + host_offset);
5811 duration_measure(&bench);
5813 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
5814 command_print(CMD_CTX, "Unsupported alignment");
5815 goto nextw;
5816 } else if (retval != ERROR_OK) {
5817 command_print(CMD_CTX, "Memory write failed");
5818 goto nextw;
5821 /* read back */
5822 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
5823 if (retval != ERROR_OK) {
5824 command_print(CMD_CTX, "Test pattern write failed");
5825 goto nextw;
5828 /* check result */
5829 int result = memcmp(read_ref, read_buf, num_bytes);
5830 if (result == 0) {
5831 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
5832 duration_elapsed(&bench),
5833 duration_kbps(&bench, count * size));
5834 } else {
5835 command_print(CMD_CTX, "Compare failed");
5836 binprint(CMD_CTX, "ref:", read_ref, num_bytes);
5837 binprint(CMD_CTX, "buf:", read_buf, num_bytes);
5839 nextw:
5840 free(read_ref);
5841 free(read_buf);
5846 free(test_pattern);
5848 if (wa != NULL)
5849 target_free_working_area(target, wa);
5850 return retval;
5853 static const struct command_registration target_exec_command_handlers[] = {
5855 .name = "fast_load_image",
5856 .handler = handle_fast_load_image_command,
5857 .mode = COMMAND_ANY,
5858 .help = "Load image into server memory for later use by "
5859 "fast_load; primarily for profiling",
5860 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5861 "[min_address [max_length]]",
5864 .name = "fast_load",
5865 .handler = handle_fast_load_command,
5866 .mode = COMMAND_EXEC,
5867 .help = "loads active fast load image to current target "
5868 "- mainly for profiling purposes",
5869 .usage = "",
5872 .name = "profile",
5873 .handler = handle_profile_command,
5874 .mode = COMMAND_EXEC,
5875 .usage = "seconds filename [start end]",
5876 .help = "profiling samples the CPU PC",
5878 /** @todo don't register virt2phys() unless target supports it */
5880 .name = "virt2phys",
5881 .handler = handle_virt2phys_command,
5882 .mode = COMMAND_ANY,
5883 .help = "translate a virtual address into a physical address",
5884 .usage = "virtual_address",
5887 .name = "reg",
5888 .handler = handle_reg_command,
5889 .mode = COMMAND_EXEC,
5890 .help = "display (reread from target with \"force\") or set a register; "
5891 "with no arguments, displays all registers and their values",
5892 .usage = "[(register_number|register_name) [(value|'force')]]",
5895 .name = "poll",
5896 .handler = handle_poll_command,
5897 .mode = COMMAND_EXEC,
5898 .help = "poll target state; or reconfigure background polling",
5899 .usage = "['on'|'off']",
5902 .name = "wait_halt",
5903 .handler = handle_wait_halt_command,
5904 .mode = COMMAND_EXEC,
5905 .help = "wait up to the specified number of milliseconds "
5906 "(default 5000) for a previously requested halt",
5907 .usage = "[milliseconds]",
5910 .name = "halt",
5911 .handler = handle_halt_command,
5912 .mode = COMMAND_EXEC,
5913 .help = "request target to halt, then wait up to the specified"
5914 "number of milliseconds (default 5000) for it to complete",
5915 .usage = "[milliseconds]",
5918 .name = "resume",
5919 .handler = handle_resume_command,
5920 .mode = COMMAND_EXEC,
5921 .help = "resume target execution from current PC or address",
5922 .usage = "[address]",
5925 .name = "reset",
5926 .handler = handle_reset_command,
5927 .mode = COMMAND_EXEC,
5928 .usage = "[run|halt|init]",
5929 .help = "Reset all targets into the specified mode."
5930 "Default reset mode is run, if not given.",
5933 .name = "soft_reset_halt",
5934 .handler = handle_soft_reset_halt_command,
5935 .mode = COMMAND_EXEC,
5936 .usage = "",
5937 .help = "halt the target and do a soft reset",
5940 .name = "step",
5941 .handler = handle_step_command,
5942 .mode = COMMAND_EXEC,
5943 .help = "step one instruction from current PC or address",
5944 .usage = "[address]",
5947 .name = "mdw",
5948 .handler = handle_md_command,
5949 .mode = COMMAND_EXEC,
5950 .help = "display memory words",
5951 .usage = "['phys'] address [count]",
5954 .name = "mdh",
5955 .handler = handle_md_command,
5956 .mode = COMMAND_EXEC,
5957 .help = "display memory half-words",
5958 .usage = "['phys'] address [count]",
5961 .name = "mdb",
5962 .handler = handle_md_command,
5963 .mode = COMMAND_EXEC,
5964 .help = "display memory bytes",
5965 .usage = "['phys'] address [count]",
5968 .name = "mww",
5969 .handler = handle_mw_command,
5970 .mode = COMMAND_EXEC,
5971 .help = "write memory word",
5972 .usage = "['phys'] address value [count]",
5975 .name = "mwh",
5976 .handler = handle_mw_command,
5977 .mode = COMMAND_EXEC,
5978 .help = "write memory half-word",
5979 .usage = "['phys'] address value [count]",
5982 .name = "mwb",
5983 .handler = handle_mw_command,
5984 .mode = COMMAND_EXEC,
5985 .help = "write memory byte",
5986 .usage = "['phys'] address value [count]",
5989 .name = "bp",
5990 .handler = handle_bp_command,
5991 .mode = COMMAND_EXEC,
5992 .help = "list or set hardware or software breakpoint",
5993 .usage = "<address> [<asid>]<length> ['hw'|'hw_ctx']",
5996 .name = "rbp",
5997 .handler = handle_rbp_command,
5998 .mode = COMMAND_EXEC,
5999 .help = "remove breakpoint",
6000 .usage = "address",
6003 .name = "wp",
6004 .handler = handle_wp_command,
6005 .mode = COMMAND_EXEC,
6006 .help = "list (no params) or create watchpoints",
6007 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
6010 .name = "rwp",
6011 .handler = handle_rwp_command,
6012 .mode = COMMAND_EXEC,
6013 .help = "remove watchpoint",
6014 .usage = "address",
6017 .name = "load_image",
6018 .handler = handle_load_image_command,
6019 .mode = COMMAND_EXEC,
6020 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6021 "[min_address] [max_length]",
6024 .name = "dump_image",
6025 .handler = handle_dump_image_command,
6026 .mode = COMMAND_EXEC,
6027 .usage = "filename address size",
6030 .name = "verify_image",
6031 .handler = handle_verify_image_command,
6032 .mode = COMMAND_EXEC,
6033 .usage = "filename [offset [type]]",
6036 .name = "test_image",
6037 .handler = handle_test_image_command,
6038 .mode = COMMAND_EXEC,
6039 .usage = "filename [offset [type]]",
6042 .name = "mem2array",
6043 .mode = COMMAND_EXEC,
6044 .jim_handler = jim_mem2array,
6045 .help = "read 8/16/32 bit memory and return as a TCL array "
6046 "for script processing",
6047 .usage = "arrayname bitwidth address count",
6050 .name = "array2mem",
6051 .mode = COMMAND_EXEC,
6052 .jim_handler = jim_array2mem,
6053 .help = "convert a TCL array to memory locations "
6054 "and write the 8/16/32 bit values",
6055 .usage = "arrayname bitwidth address count",
6058 .name = "reset_nag",
6059 .handler = handle_target_reset_nag,
6060 .mode = COMMAND_ANY,
6061 .help = "Nag after each reset about options that could have been "
6062 "enabled to improve performance. ",
6063 .usage = "['enable'|'disable']",
6066 .name = "ps",
6067 .handler = handle_ps_command,
6068 .mode = COMMAND_EXEC,
6069 .help = "list all tasks ",
6070 .usage = " ",
6073 .name = "test_mem_access",
6074 .handler = handle_test_mem_access_command,
6075 .mode = COMMAND_EXEC,
6076 .help = "Test the target's memory access functions",
6077 .usage = "size",
6080 COMMAND_REGISTRATION_DONE
6082 static int target_register_user_commands(struct command_context *cmd_ctx)
6084 int retval = ERROR_OK;
6085 retval = target_request_register_commands(cmd_ctx);
6086 if (retval != ERROR_OK)
6087 return retval;
6089 retval = trace_register_commands(cmd_ctx);
6090 if (retval != ERROR_OK)
6091 return retval;
6094 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);