target: Add missing spaces in error messages
[openocd.git] / src / target / target.c
blobfefaa0e1e38366331b3e613a35c24d25f300804e
1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
4 * *
5 * Copyright (C) 2007-2010 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
7 * *
8 * Copyright (C) 2008, Duane Ellis *
9 * openocd@duaneeellis.com *
10 * *
11 * Copyright (C) 2008 by Spencer Oliver *
12 * spen@spen-soft.co.uk *
13 * *
14 * Copyright (C) 2008 by Rick Altherr *
15 * kc8apf@kc8apf.net> *
16 * *
17 * Copyright (C) 2011 by Broadcom Corporation *
18 * Evan Hunter - ehunter@broadcom.com *
19 * *
20 * Copyright (C) ST-Ericsson SA 2011 *
21 * michel.jaouen@stericsson.com : smp minimum support *
22 * *
23 * Copyright (C) 2011 Andreas Fritiofson *
24 * andreas.fritiofson@gmail.com *
25 * *
26 * This program is free software; you can redistribute it and/or modify *
27 * it under the terms of the GNU General Public License as published by *
28 * the Free Software Foundation; either version 2 of the License, or *
29 * (at your option) any later version. *
30 * *
31 * This program is distributed in the hope that it will be useful, *
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
34 * GNU General Public License for more details. *
35 * *
36 * You should have received a copy of the GNU General Public License *
37 * along with this program. If not, see <http://www.gnu.org/licenses/>. *
38 ***************************************************************************/
40 #ifdef HAVE_CONFIG_H
41 #include "config.h"
42 #endif
44 #include <helper/time_support.h>
45 #include <jtag/jtag.h>
46 #include <flash/nor/core.h>
48 #include "target.h"
49 #include "target_type.h"
50 #include "target_request.h"
51 #include "breakpoints.h"
52 #include "register.h"
53 #include "trace.h"
54 #include "image.h"
55 #include "rtos/rtos.h"
56 #include "transport/transport.h"
58 /* default halt wait timeout (ms) */
59 #define DEFAULT_HALT_TIMEOUT 5000
61 static int target_read_buffer_default(struct target *target, uint32_t address,
62 uint32_t count, uint8_t *buffer);
63 static int target_write_buffer_default(struct target *target, uint32_t address,
64 uint32_t count, const uint8_t *buffer);
65 static int target_array2mem(Jim_Interp *interp, struct target *target,
66 int argc, Jim_Obj * const *argv);
67 static int target_mem2array(Jim_Interp *interp, struct target *target,
68 int argc, Jim_Obj * const *argv);
69 static int target_register_user_commands(struct command_context *cmd_ctx);
70 static int target_get_gdb_fileio_info_default(struct target *target,
71 struct gdb_fileio_info *fileio_info);
72 static int target_gdb_fileio_end_default(struct target *target, int retcode,
73 int fileio_errno, bool ctrl_c);
74 static int target_profiling_default(struct target *target, uint32_t *samples,
75 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds);
77 /* targets */
78 extern struct target_type arm7tdmi_target;
79 extern struct target_type arm720t_target;
80 extern struct target_type arm9tdmi_target;
81 extern struct target_type arm920t_target;
82 extern struct target_type arm966e_target;
83 extern struct target_type arm946e_target;
84 extern struct target_type arm926ejs_target;
85 extern struct target_type fa526_target;
86 extern struct target_type feroceon_target;
87 extern struct target_type dragonite_target;
88 extern struct target_type xscale_target;
89 extern struct target_type cortexm_target;
90 extern struct target_type cortexa_target;
91 extern struct target_type cortexr4_target;
92 extern struct target_type arm11_target;
93 extern struct target_type ls1_sap_target;
94 extern struct target_type mips_m4k_target;
95 extern struct target_type avr_target;
96 extern struct target_type dsp563xx_target;
97 extern struct target_type dsp5680xx_target;
98 extern struct target_type testee_target;
99 extern struct target_type avr32_ap7k_target;
100 extern struct target_type hla_target;
101 extern struct target_type nds32_v2_target;
102 extern struct target_type nds32_v3_target;
103 extern struct target_type nds32_v3m_target;
104 extern struct target_type or1k_target;
105 extern struct target_type quark_x10xx_target;
106 extern struct target_type quark_d20xx_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 &ls1_sap_target,
125 &mips_m4k_target,
126 &avr_target,
127 &dsp563xx_target,
128 &dsp5680xx_target,
129 &testee_target,
130 &avr32_ap7k_target,
131 &hla_target,
132 &nds32_v2_target,
133 &nds32_v3_target,
134 &nds32_v3m_target,
135 &or1k_target,
136 &quark_x10xx_target,
137 &quark_d20xx_target,
138 NULL,
141 struct target *all_targets;
142 static struct target_event_callback *target_event_callbacks;
143 static struct target_timer_callback *target_timer_callbacks;
144 LIST_HEAD(target_reset_callback_list);
145 LIST_HEAD(target_trace_callback_list);
146 static const int polling_interval = 100;
148 static const Jim_Nvp nvp_assert[] = {
149 { .name = "assert", NVP_ASSERT },
150 { .name = "deassert", NVP_DEASSERT },
151 { .name = "T", NVP_ASSERT },
152 { .name = "F", NVP_DEASSERT },
153 { .name = "t", NVP_ASSERT },
154 { .name = "f", NVP_DEASSERT },
155 { .name = NULL, .value = -1 }
158 static const Jim_Nvp nvp_error_target[] = {
159 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
160 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
161 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
162 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
163 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
164 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
165 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
166 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
167 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
168 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
169 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
170 { .value = -1, .name = NULL }
173 static const char *target_strerror_safe(int err)
175 const Jim_Nvp *n;
177 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
178 if (n->name == NULL)
179 return "unknown";
180 else
181 return n->name;
184 static const Jim_Nvp nvp_target_event[] = {
186 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
187 { .value = TARGET_EVENT_HALTED, .name = "halted" },
188 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
189 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
190 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
192 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
193 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
195 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
196 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
197 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
198 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
199 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
200 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
201 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
202 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
203 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
204 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
205 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
206 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
208 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
209 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
211 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
212 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
214 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
215 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
217 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
218 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
220 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
221 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
223 { .value = TARGET_EVENT_TRACE_CONFIG, .name = "trace-config" },
225 { .name = NULL, .value = -1 }
228 static const Jim_Nvp nvp_target_state[] = {
229 { .name = "unknown", .value = TARGET_UNKNOWN },
230 { .name = "running", .value = TARGET_RUNNING },
231 { .name = "halted", .value = TARGET_HALTED },
232 { .name = "reset", .value = TARGET_RESET },
233 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
234 { .name = NULL, .value = -1 },
237 static const Jim_Nvp nvp_target_debug_reason[] = {
238 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
239 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
240 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
241 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
242 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
243 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
244 { .name = "program-exit" , .value = DBG_REASON_EXIT },
245 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
246 { .name = NULL, .value = -1 },
249 static const Jim_Nvp nvp_target_endian[] = {
250 { .name = "big", .value = TARGET_BIG_ENDIAN },
251 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
252 { .name = "be", .value = TARGET_BIG_ENDIAN },
253 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
254 { .name = NULL, .value = -1 },
257 static const Jim_Nvp nvp_reset_modes[] = {
258 { .name = "unknown", .value = RESET_UNKNOWN },
259 { .name = "run" , .value = RESET_RUN },
260 { .name = "halt" , .value = RESET_HALT },
261 { .name = "init" , .value = RESET_INIT },
262 { .name = NULL , .value = -1 },
265 const char *debug_reason_name(struct target *t)
267 const char *cp;
269 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
270 t->debug_reason)->name;
271 if (!cp) {
272 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
273 cp = "(*BUG*unknown*BUG*)";
275 return cp;
278 const char *target_state_name(struct target *t)
280 const char *cp;
281 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
282 if (!cp) {
283 LOG_ERROR("Invalid target state: %d", (int)(t->state));
284 cp = "(*BUG*unknown*BUG*)";
286 return cp;
289 const char *target_event_name(enum target_event event)
291 const char *cp;
292 cp = Jim_Nvp_value2name_simple(nvp_target_event, event)->name;
293 if (!cp) {
294 LOG_ERROR("Invalid target event: %d", (int)(event));
295 cp = "(*BUG*unknown*BUG*)";
297 return cp;
300 const char *target_reset_mode_name(enum target_reset_mode reset_mode)
302 const char *cp;
303 cp = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name;
304 if (!cp) {
305 LOG_ERROR("Invalid target reset mode: %d", (int)(reset_mode));
306 cp = "(*BUG*unknown*BUG*)";
308 return cp;
311 /* determine the number of the new target */
312 static int new_target_number(void)
314 struct target *t;
315 int x;
317 /* number is 0 based */
318 x = -1;
319 t = all_targets;
320 while (t) {
321 if (x < t->target_number)
322 x = t->target_number;
323 t = t->next;
325 return x + 1;
328 /* read a uint64_t from a buffer in target memory endianness */
329 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
331 if (target->endianness == TARGET_LITTLE_ENDIAN)
332 return le_to_h_u64(buffer);
333 else
334 return be_to_h_u64(buffer);
337 /* read a uint32_t from a buffer in target memory endianness */
338 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
340 if (target->endianness == TARGET_LITTLE_ENDIAN)
341 return le_to_h_u32(buffer);
342 else
343 return be_to_h_u32(buffer);
346 /* read a uint24_t from a buffer in target memory endianness */
347 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
349 if (target->endianness == TARGET_LITTLE_ENDIAN)
350 return le_to_h_u24(buffer);
351 else
352 return be_to_h_u24(buffer);
355 /* read a uint16_t from a buffer in target memory endianness */
356 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
358 if (target->endianness == TARGET_LITTLE_ENDIAN)
359 return le_to_h_u16(buffer);
360 else
361 return be_to_h_u16(buffer);
364 /* read a uint8_t from a buffer in target memory endianness */
365 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
367 return *buffer & 0x0ff;
370 /* write a uint64_t to a buffer in target memory endianness */
371 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
373 if (target->endianness == TARGET_LITTLE_ENDIAN)
374 h_u64_to_le(buffer, value);
375 else
376 h_u64_to_be(buffer, value);
379 /* write a uint32_t to a buffer in target memory endianness */
380 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
382 if (target->endianness == TARGET_LITTLE_ENDIAN)
383 h_u32_to_le(buffer, value);
384 else
385 h_u32_to_be(buffer, value);
388 /* write a uint24_t to a buffer in target memory endianness */
389 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
391 if (target->endianness == TARGET_LITTLE_ENDIAN)
392 h_u24_to_le(buffer, value);
393 else
394 h_u24_to_be(buffer, value);
397 /* write a uint16_t to a buffer in target memory endianness */
398 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
400 if (target->endianness == TARGET_LITTLE_ENDIAN)
401 h_u16_to_le(buffer, value);
402 else
403 h_u16_to_be(buffer, value);
406 /* write a uint8_t to a buffer in target memory endianness */
407 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
409 *buffer = value;
412 /* write a uint64_t array to a buffer in target memory endianness */
413 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
415 uint32_t i;
416 for (i = 0; i < count; i++)
417 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
420 /* write a uint32_t array to a buffer in target memory endianness */
421 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
423 uint32_t i;
424 for (i = 0; i < count; i++)
425 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
428 /* write a uint16_t array to a buffer in target memory endianness */
429 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
431 uint32_t i;
432 for (i = 0; i < count; i++)
433 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
436 /* write a uint64_t array to a buffer in target memory endianness */
437 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
439 uint32_t i;
440 for (i = 0; i < count; i++)
441 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
444 /* write a uint32_t array to a buffer in target memory endianness */
445 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
447 uint32_t i;
448 for (i = 0; i < count; i++)
449 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
452 /* write a uint16_t array to a buffer in target memory endianness */
453 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
455 uint32_t i;
456 for (i = 0; i < count; i++)
457 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
460 /* return a pointer to a configured target; id is name or number */
461 struct target *get_target(const char *id)
463 struct target *target;
465 /* try as tcltarget name */
466 for (target = all_targets; target; target = target->next) {
467 if (target_name(target) == NULL)
468 continue;
469 if (strcmp(id, target_name(target)) == 0)
470 return target;
473 /* It's OK to remove this fallback sometime after August 2010 or so */
475 /* no match, try as number */
476 unsigned num;
477 if (parse_uint(id, &num) != ERROR_OK)
478 return NULL;
480 for (target = all_targets; target; target = target->next) {
481 if (target->target_number == (int)num) {
482 LOG_WARNING("use '%s' as target identifier, not '%u'",
483 target_name(target), num);
484 return target;
488 return NULL;
491 /* returns a pointer to the n-th configured target */
492 struct target *get_target_by_num(int num)
494 struct target *target = all_targets;
496 while (target) {
497 if (target->target_number == num)
498 return target;
499 target = target->next;
502 return NULL;
505 struct target *get_current_target(struct command_context *cmd_ctx)
507 struct target *target = get_target_by_num(cmd_ctx->current_target);
509 if (target == NULL) {
510 LOG_ERROR("BUG: current_target out of bounds");
511 exit(-1);
514 return target;
517 int target_poll(struct target *target)
519 int retval;
521 /* We can't poll until after examine */
522 if (!target_was_examined(target)) {
523 /* Fail silently lest we pollute the log */
524 return ERROR_FAIL;
527 retval = target->type->poll(target);
528 if (retval != ERROR_OK)
529 return retval;
531 if (target->halt_issued) {
532 if (target->state == TARGET_HALTED)
533 target->halt_issued = false;
534 else {
535 int64_t t = timeval_ms() - target->halt_issued_time;
536 if (t > DEFAULT_HALT_TIMEOUT) {
537 target->halt_issued = false;
538 LOG_INFO("Halt timed out, wake up GDB.");
539 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
544 return ERROR_OK;
547 int target_halt(struct target *target)
549 int retval;
550 /* We can't poll until after examine */
551 if (!target_was_examined(target)) {
552 LOG_ERROR("Target not examined yet");
553 return ERROR_FAIL;
556 retval = target->type->halt(target);
557 if (retval != ERROR_OK)
558 return retval;
560 target->halt_issued = true;
561 target->halt_issued_time = timeval_ms();
563 return ERROR_OK;
567 * Make the target (re)start executing using its saved execution
568 * context (possibly with some modifications).
570 * @param target Which target should start executing.
571 * @param current True to use the target's saved program counter instead
572 * of the address parameter
573 * @param address Optionally used as the program counter.
574 * @param handle_breakpoints True iff breakpoints at the resumption PC
575 * should be skipped. (For example, maybe execution was stopped by
576 * such a breakpoint, in which case it would be counterprodutive to
577 * let it re-trigger.
578 * @param debug_execution False if all working areas allocated by OpenOCD
579 * should be released and/or restored to their original contents.
580 * (This would for example be true to run some downloaded "helper"
581 * algorithm code, which resides in one such working buffer and uses
582 * another for data storage.)
584 * @todo Resolve the ambiguity about what the "debug_execution" flag
585 * signifies. For example, Target implementations don't agree on how
586 * it relates to invalidation of the register cache, or to whether
587 * breakpoints and watchpoints should be enabled. (It would seem wrong
588 * to enable breakpoints when running downloaded "helper" algorithms
589 * (debug_execution true), since the breakpoints would be set to match
590 * target firmware being debugged, not the helper algorithm.... and
591 * enabling them could cause such helpers to malfunction (for example,
592 * by overwriting data with a breakpoint instruction. On the other
593 * hand the infrastructure for running such helpers might use this
594 * procedure but rely on hardware breakpoint to detect termination.)
596 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
598 int retval;
600 /* We can't poll until after examine */
601 if (!target_was_examined(target)) {
602 LOG_ERROR("Target not examined yet");
603 return ERROR_FAIL;
606 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
608 /* note that resume *must* be asynchronous. The CPU can halt before
609 * we poll. The CPU can even halt at the current PC as a result of
610 * a software breakpoint being inserted by (a bug?) the application.
612 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
613 if (retval != ERROR_OK)
614 return retval;
616 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
618 return retval;
621 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
623 char buf[100];
624 int retval;
625 Jim_Nvp *n;
626 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
627 if (n->name == NULL) {
628 LOG_ERROR("invalid reset mode");
629 return ERROR_FAIL;
632 struct target *target;
633 for (target = all_targets; target; target = target->next)
634 target_call_reset_callbacks(target, reset_mode);
636 /* disable polling during reset to make reset event scripts
637 * more predictable, i.e. dr/irscan & pathmove in events will
638 * not have JTAG operations injected into the middle of a sequence.
640 bool save_poll = jtag_poll_get_enabled();
642 jtag_poll_set_enabled(false);
644 sprintf(buf, "ocd_process_reset %s", n->name);
645 retval = Jim_Eval(cmd_ctx->interp, buf);
647 jtag_poll_set_enabled(save_poll);
649 if (retval != JIM_OK) {
650 Jim_MakeErrorMessage(cmd_ctx->interp);
651 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
652 return ERROR_FAIL;
655 /* We want any events to be processed before the prompt */
656 retval = target_call_timer_callbacks_now();
658 for (target = all_targets; target; target = target->next) {
659 target->type->check_reset(target);
660 target->running_alg = false;
663 return retval;
666 static int identity_virt2phys(struct target *target,
667 uint32_t virtual, uint32_t *physical)
669 *physical = virtual;
670 return ERROR_OK;
673 static int no_mmu(struct target *target, int *enabled)
675 *enabled = 0;
676 return ERROR_OK;
679 static int default_examine(struct target *target)
681 target_set_examined(target);
682 return ERROR_OK;
685 /* no check by default */
686 static int default_check_reset(struct target *target)
688 return ERROR_OK;
691 int target_examine_one(struct target *target)
693 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
695 int retval = target->type->examine(target);
696 if (retval != ERROR_OK)
697 return retval;
699 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
701 return ERROR_OK;
704 static int jtag_enable_callback(enum jtag_event event, void *priv)
706 struct target *target = priv;
708 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
709 return ERROR_OK;
711 jtag_unregister_event_callback(jtag_enable_callback, target);
713 return target_examine_one(target);
716 /* Targets that correctly implement init + examine, i.e.
717 * no communication with target during init:
719 * XScale
721 int target_examine(void)
723 int retval = ERROR_OK;
724 struct target *target;
726 for (target = all_targets; target; target = target->next) {
727 /* defer examination, but don't skip it */
728 if (!target->tap->enabled) {
729 jtag_register_event_callback(jtag_enable_callback,
730 target);
731 continue;
734 retval = target_examine_one(target);
735 if (retval != ERROR_OK)
736 return retval;
738 return retval;
741 const char *target_type_name(struct target *target)
743 return target->type->name;
746 static int target_soft_reset_halt(struct target *target)
748 if (!target_was_examined(target)) {
749 LOG_ERROR("Target not examined yet");
750 return ERROR_FAIL;
752 if (!target->type->soft_reset_halt) {
753 LOG_ERROR("Target %s does not support soft_reset_halt",
754 target_name(target));
755 return ERROR_FAIL;
757 return target->type->soft_reset_halt(target);
761 * Downloads a target-specific native code algorithm to the target,
762 * and executes it. * Note that some targets may need to set up, enable,
763 * and tear down a breakpoint (hard or * soft) to detect algorithm
764 * termination, while others may support lower overhead schemes where
765 * soft breakpoints embedded in the algorithm automatically terminate the
766 * algorithm.
768 * @param target used to run the algorithm
769 * @param arch_info target-specific description of the algorithm.
771 int target_run_algorithm(struct target *target,
772 int num_mem_params, struct mem_param *mem_params,
773 int num_reg_params, struct reg_param *reg_param,
774 uint32_t entry_point, uint32_t exit_point,
775 int timeout_ms, void *arch_info)
777 int retval = ERROR_FAIL;
779 if (!target_was_examined(target)) {
780 LOG_ERROR("Target not examined yet");
781 goto done;
783 if (!target->type->run_algorithm) {
784 LOG_ERROR("Target type '%s' does not support %s",
785 target_type_name(target), __func__);
786 goto done;
789 target->running_alg = true;
790 retval = target->type->run_algorithm(target,
791 num_mem_params, mem_params,
792 num_reg_params, reg_param,
793 entry_point, exit_point, timeout_ms, arch_info);
794 target->running_alg = false;
796 done:
797 return retval;
801 * Downloads a target-specific native code algorithm to the target,
802 * executes and leaves it running.
804 * @param target used to run the algorithm
805 * @param arch_info target-specific description of the algorithm.
807 int target_start_algorithm(struct target *target,
808 int num_mem_params, struct mem_param *mem_params,
809 int num_reg_params, struct reg_param *reg_params,
810 uint32_t entry_point, uint32_t exit_point,
811 void *arch_info)
813 int retval = ERROR_FAIL;
815 if (!target_was_examined(target)) {
816 LOG_ERROR("Target not examined yet");
817 goto done;
819 if (!target->type->start_algorithm) {
820 LOG_ERROR("Target type '%s' does not support %s",
821 target_type_name(target), __func__);
822 goto done;
824 if (target->running_alg) {
825 LOG_ERROR("Target is already running an algorithm");
826 goto done;
829 target->running_alg = true;
830 retval = target->type->start_algorithm(target,
831 num_mem_params, mem_params,
832 num_reg_params, reg_params,
833 entry_point, exit_point, arch_info);
835 done:
836 return retval;
840 * Waits for an algorithm started with target_start_algorithm() to complete.
842 * @param target used to run the algorithm
843 * @param arch_info target-specific description of the algorithm.
845 int target_wait_algorithm(struct target *target,
846 int num_mem_params, struct mem_param *mem_params,
847 int num_reg_params, struct reg_param *reg_params,
848 uint32_t exit_point, int timeout_ms,
849 void *arch_info)
851 int retval = ERROR_FAIL;
853 if (!target->type->wait_algorithm) {
854 LOG_ERROR("Target type '%s' does not support %s",
855 target_type_name(target), __func__);
856 goto done;
858 if (!target->running_alg) {
859 LOG_ERROR("Target is not running an algorithm");
860 goto done;
863 retval = target->type->wait_algorithm(target,
864 num_mem_params, mem_params,
865 num_reg_params, reg_params,
866 exit_point, timeout_ms, arch_info);
867 if (retval != ERROR_TARGET_TIMEOUT)
868 target->running_alg = false;
870 done:
871 return retval;
875 * Executes a target-specific native code algorithm in the target.
876 * It differs from target_run_algorithm in that the algorithm is asynchronous.
877 * Because of this it requires an compliant algorithm:
878 * see contrib/loaders/flash/stm32f1x.S for example.
880 * @param target used to run the algorithm
883 int target_run_flash_async_algorithm(struct target *target,
884 const uint8_t *buffer, uint32_t count, int block_size,
885 int num_mem_params, struct mem_param *mem_params,
886 int num_reg_params, struct reg_param *reg_params,
887 uint32_t buffer_start, uint32_t buffer_size,
888 uint32_t entry_point, uint32_t exit_point, void *arch_info)
890 int retval;
891 int timeout = 0;
893 const uint8_t *buffer_orig = buffer;
895 /* Set up working area. First word is write pointer, second word is read pointer,
896 * rest is fifo data area. */
897 uint32_t wp_addr = buffer_start;
898 uint32_t rp_addr = buffer_start + 4;
899 uint32_t fifo_start_addr = buffer_start + 8;
900 uint32_t fifo_end_addr = buffer_start + buffer_size;
902 uint32_t wp = fifo_start_addr;
903 uint32_t rp = fifo_start_addr;
905 /* validate block_size is 2^n */
906 assert(!block_size || !(block_size & (block_size - 1)));
908 retval = target_write_u32(target, wp_addr, wp);
909 if (retval != ERROR_OK)
910 return retval;
911 retval = target_write_u32(target, rp_addr, rp);
912 if (retval != ERROR_OK)
913 return retval;
915 /* Start up algorithm on target and let it idle while writing the first chunk */
916 retval = target_start_algorithm(target, num_mem_params, mem_params,
917 num_reg_params, reg_params,
918 entry_point,
919 exit_point,
920 arch_info);
922 if (retval != ERROR_OK) {
923 LOG_ERROR("error starting target flash write algorithm");
924 return retval;
927 while (count > 0) {
929 retval = target_read_u32(target, rp_addr, &rp);
930 if (retval != ERROR_OK) {
931 LOG_ERROR("failed to get read pointer");
932 break;
935 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
936 (size_t) (buffer - buffer_orig), count, wp, rp);
938 if (rp == 0) {
939 LOG_ERROR("flash write algorithm aborted by target");
940 retval = ERROR_FLASH_OPERATION_FAILED;
941 break;
944 if (((rp - fifo_start_addr) & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
945 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
946 break;
949 /* Count the number of bytes available in the fifo without
950 * crossing the wrap around. Make sure to not fill it completely,
951 * because that would make wp == rp and that's the empty condition. */
952 uint32_t thisrun_bytes;
953 if (rp > wp)
954 thisrun_bytes = rp - wp - block_size;
955 else if (rp > fifo_start_addr)
956 thisrun_bytes = fifo_end_addr - wp;
957 else
958 thisrun_bytes = fifo_end_addr - wp - block_size;
960 if (thisrun_bytes == 0) {
961 /* Throttle polling a bit if transfer is (much) faster than flash
962 * programming. The exact delay shouldn't matter as long as it's
963 * less than buffer size / flash speed. This is very unlikely to
964 * run when using high latency connections such as USB. */
965 alive_sleep(10);
967 /* to stop an infinite loop on some targets check and increment a timeout
968 * this issue was observed on a stellaris using the new ICDI interface */
969 if (timeout++ >= 500) {
970 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
971 return ERROR_FLASH_OPERATION_FAILED;
973 continue;
976 /* reset our timeout */
977 timeout = 0;
979 /* Limit to the amount of data we actually want to write */
980 if (thisrun_bytes > count * block_size)
981 thisrun_bytes = count * block_size;
983 /* Write data to fifo */
984 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
985 if (retval != ERROR_OK)
986 break;
988 /* Update counters and wrap write pointer */
989 buffer += thisrun_bytes;
990 count -= thisrun_bytes / block_size;
991 wp += thisrun_bytes;
992 if (wp >= fifo_end_addr)
993 wp = fifo_start_addr;
995 /* Store updated write pointer to target */
996 retval = target_write_u32(target, wp_addr, wp);
997 if (retval != ERROR_OK)
998 break;
1001 if (retval != ERROR_OK) {
1002 /* abort flash write algorithm on target */
1003 target_write_u32(target, wp_addr, 0);
1006 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1007 num_reg_params, reg_params,
1008 exit_point,
1009 10000,
1010 arch_info);
1012 if (retval2 != ERROR_OK) {
1013 LOG_ERROR("error waiting for target flash write algorithm");
1014 retval = retval2;
1017 if (retval == ERROR_OK) {
1018 /* check if algorithm set rp = 0 after fifo writer loop finished */
1019 retval = target_read_u32(target, rp_addr, &rp);
1020 if (retval == ERROR_OK && rp == 0) {
1021 LOG_ERROR("flash write algorithm aborted by target");
1022 retval = ERROR_FLASH_OPERATION_FAILED;
1026 return retval;
1029 int target_read_memory(struct target *target,
1030 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1032 if (!target_was_examined(target)) {
1033 LOG_ERROR("Target not examined yet");
1034 return ERROR_FAIL;
1036 if (!target->type->read_memory) {
1037 LOG_ERROR("Target %s doesn't support read_memory", target_name(target));
1038 return ERROR_FAIL;
1040 return target->type->read_memory(target, address, size, count, buffer);
1043 int target_read_phys_memory(struct target *target,
1044 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1046 if (!target_was_examined(target)) {
1047 LOG_ERROR("Target not examined yet");
1048 return ERROR_FAIL;
1050 if (!target->type->read_phys_memory) {
1051 LOG_ERROR("Target %s doesn't support read_phys_memory", target_name(target));
1052 return ERROR_FAIL;
1054 return target->type->read_phys_memory(target, address, size, count, buffer);
1057 int target_write_memory(struct target *target,
1058 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1060 if (!target_was_examined(target)) {
1061 LOG_ERROR("Target not examined yet");
1062 return ERROR_FAIL;
1064 if (!target->type->write_memory) {
1065 LOG_ERROR("Target %s doesn't support write_memory", target_name(target));
1066 return ERROR_FAIL;
1068 return target->type->write_memory(target, address, size, count, buffer);
1071 int target_write_phys_memory(struct target *target,
1072 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1074 if (!target_was_examined(target)) {
1075 LOG_ERROR("Target not examined yet");
1076 return ERROR_FAIL;
1078 if (!target->type->write_phys_memory) {
1079 LOG_ERROR("Target %s doesn't support write_phys_memory", target_name(target));
1080 return ERROR_FAIL;
1082 return target->type->write_phys_memory(target, address, size, count, buffer);
1085 int target_add_breakpoint(struct target *target,
1086 struct breakpoint *breakpoint)
1088 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1089 LOG_WARNING("target %s is not halted", target_name(target));
1090 return ERROR_TARGET_NOT_HALTED;
1092 return target->type->add_breakpoint(target, breakpoint);
1095 int target_add_context_breakpoint(struct target *target,
1096 struct breakpoint *breakpoint)
1098 if (target->state != TARGET_HALTED) {
1099 LOG_WARNING("target %s is not halted", target_name(target));
1100 return ERROR_TARGET_NOT_HALTED;
1102 return target->type->add_context_breakpoint(target, breakpoint);
1105 int target_add_hybrid_breakpoint(struct target *target,
1106 struct breakpoint *breakpoint)
1108 if (target->state != TARGET_HALTED) {
1109 LOG_WARNING("target %s is not halted", target_name(target));
1110 return ERROR_TARGET_NOT_HALTED;
1112 return target->type->add_hybrid_breakpoint(target, breakpoint);
1115 int target_remove_breakpoint(struct target *target,
1116 struct breakpoint *breakpoint)
1118 return target->type->remove_breakpoint(target, breakpoint);
1121 int target_add_watchpoint(struct target *target,
1122 struct watchpoint *watchpoint)
1124 if (target->state != TARGET_HALTED) {
1125 LOG_WARNING("target %s is not halted", target_name(target));
1126 return ERROR_TARGET_NOT_HALTED;
1128 return target->type->add_watchpoint(target, watchpoint);
1130 int target_remove_watchpoint(struct target *target,
1131 struct watchpoint *watchpoint)
1133 return target->type->remove_watchpoint(target, watchpoint);
1135 int target_hit_watchpoint(struct target *target,
1136 struct watchpoint **hit_watchpoint)
1138 if (target->state != TARGET_HALTED) {
1139 LOG_WARNING("target %s is not halted", target->cmd_name);
1140 return ERROR_TARGET_NOT_HALTED;
1143 if (target->type->hit_watchpoint == NULL) {
1144 /* For backward compatible, if hit_watchpoint is not implemented,
1145 * return ERROR_FAIL such that gdb_server will not take the nonsense
1146 * information. */
1147 return ERROR_FAIL;
1150 return target->type->hit_watchpoint(target, hit_watchpoint);
1153 int target_get_gdb_reg_list(struct target *target,
1154 struct reg **reg_list[], int *reg_list_size,
1155 enum target_register_class reg_class)
1157 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1159 int target_step(struct target *target,
1160 int current, uint32_t address, int handle_breakpoints)
1162 return target->type->step(target, current, address, handle_breakpoints);
1165 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1167 if (target->state != TARGET_HALTED) {
1168 LOG_WARNING("target %s is not halted", target->cmd_name);
1169 return ERROR_TARGET_NOT_HALTED;
1171 return target->type->get_gdb_fileio_info(target, fileio_info);
1174 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1176 if (target->state != TARGET_HALTED) {
1177 LOG_WARNING("target %s is not halted", target->cmd_name);
1178 return ERROR_TARGET_NOT_HALTED;
1180 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1183 int target_profiling(struct target *target, uint32_t *samples,
1184 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1186 if (target->state != TARGET_HALTED) {
1187 LOG_WARNING("target %s is not halted", target->cmd_name);
1188 return ERROR_TARGET_NOT_HALTED;
1190 return target->type->profiling(target, samples, max_num_samples,
1191 num_samples, seconds);
1195 * Reset the @c examined flag for the given target.
1196 * Pure paranoia -- targets are zeroed on allocation.
1198 static void target_reset_examined(struct target *target)
1200 target->examined = false;
1203 static int handle_target(void *priv);
1205 static int target_init_one(struct command_context *cmd_ctx,
1206 struct target *target)
1208 target_reset_examined(target);
1210 struct target_type *type = target->type;
1211 if (type->examine == NULL)
1212 type->examine = default_examine;
1214 if (type->check_reset == NULL)
1215 type->check_reset = default_check_reset;
1217 assert(type->init_target != NULL);
1219 int retval = type->init_target(cmd_ctx, target);
1220 if (ERROR_OK != retval) {
1221 LOG_ERROR("target '%s' init failed", target_name(target));
1222 return retval;
1225 /* Sanity-check MMU support ... stub in what we must, to help
1226 * implement it in stages, but warn if we need to do so.
1228 if (type->mmu) {
1229 if (type->virt2phys == NULL) {
1230 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1231 type->virt2phys = identity_virt2phys;
1233 } else {
1234 /* Make sure no-MMU targets all behave the same: make no
1235 * distinction between physical and virtual addresses, and
1236 * ensure that virt2phys() is always an identity mapping.
1238 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1239 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1241 type->mmu = no_mmu;
1242 type->write_phys_memory = type->write_memory;
1243 type->read_phys_memory = type->read_memory;
1244 type->virt2phys = identity_virt2phys;
1247 if (target->type->read_buffer == NULL)
1248 target->type->read_buffer = target_read_buffer_default;
1250 if (target->type->write_buffer == NULL)
1251 target->type->write_buffer = target_write_buffer_default;
1253 if (target->type->get_gdb_fileio_info == NULL)
1254 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1256 if (target->type->gdb_fileio_end == NULL)
1257 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1259 if (target->type->profiling == NULL)
1260 target->type->profiling = target_profiling_default;
1262 return ERROR_OK;
1265 static int target_init(struct command_context *cmd_ctx)
1267 struct target *target;
1268 int retval;
1270 for (target = all_targets; target; target = target->next) {
1271 retval = target_init_one(cmd_ctx, target);
1272 if (ERROR_OK != retval)
1273 return retval;
1276 if (!all_targets)
1277 return ERROR_OK;
1279 retval = target_register_user_commands(cmd_ctx);
1280 if (ERROR_OK != retval)
1281 return retval;
1283 retval = target_register_timer_callback(&handle_target,
1284 polling_interval, 1, cmd_ctx->interp);
1285 if (ERROR_OK != retval)
1286 return retval;
1288 return ERROR_OK;
1291 COMMAND_HANDLER(handle_target_init_command)
1293 int retval;
1295 if (CMD_ARGC != 0)
1296 return ERROR_COMMAND_SYNTAX_ERROR;
1298 static bool target_initialized;
1299 if (target_initialized) {
1300 LOG_INFO("'target init' has already been called");
1301 return ERROR_OK;
1303 target_initialized = true;
1305 retval = command_run_line(CMD_CTX, "init_targets");
1306 if (ERROR_OK != retval)
1307 return retval;
1309 retval = command_run_line(CMD_CTX, "init_target_events");
1310 if (ERROR_OK != retval)
1311 return retval;
1313 retval = command_run_line(CMD_CTX, "init_board");
1314 if (ERROR_OK != retval)
1315 return retval;
1317 LOG_DEBUG("Initializing targets...");
1318 return target_init(CMD_CTX);
1321 int target_register_event_callback(int (*callback)(struct target *target,
1322 enum target_event event, void *priv), void *priv)
1324 struct target_event_callback **callbacks_p = &target_event_callbacks;
1326 if (callback == NULL)
1327 return ERROR_COMMAND_SYNTAX_ERROR;
1329 if (*callbacks_p) {
1330 while ((*callbacks_p)->next)
1331 callbacks_p = &((*callbacks_p)->next);
1332 callbacks_p = &((*callbacks_p)->next);
1335 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1336 (*callbacks_p)->callback = callback;
1337 (*callbacks_p)->priv = priv;
1338 (*callbacks_p)->next = NULL;
1340 return ERROR_OK;
1343 int target_register_reset_callback(int (*callback)(struct target *target,
1344 enum target_reset_mode reset_mode, void *priv), void *priv)
1346 struct target_reset_callback *entry;
1348 if (callback == NULL)
1349 return ERROR_COMMAND_SYNTAX_ERROR;
1351 entry = malloc(sizeof(struct target_reset_callback));
1352 if (entry == NULL) {
1353 LOG_ERROR("error allocating buffer for reset callback entry");
1354 return ERROR_COMMAND_SYNTAX_ERROR;
1357 entry->callback = callback;
1358 entry->priv = priv;
1359 list_add(&entry->list, &target_reset_callback_list);
1362 return ERROR_OK;
1365 int target_register_trace_callback(int (*callback)(struct target *target,
1366 size_t len, uint8_t *data, void *priv), void *priv)
1368 struct target_trace_callback *entry;
1370 if (callback == NULL)
1371 return ERROR_COMMAND_SYNTAX_ERROR;
1373 entry = malloc(sizeof(struct target_trace_callback));
1374 if (entry == NULL) {
1375 LOG_ERROR("error allocating buffer for trace callback entry");
1376 return ERROR_COMMAND_SYNTAX_ERROR;
1379 entry->callback = callback;
1380 entry->priv = priv;
1381 list_add(&entry->list, &target_trace_callback_list);
1384 return ERROR_OK;
1387 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1389 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1390 struct timeval now;
1392 if (callback == NULL)
1393 return ERROR_COMMAND_SYNTAX_ERROR;
1395 if (*callbacks_p) {
1396 while ((*callbacks_p)->next)
1397 callbacks_p = &((*callbacks_p)->next);
1398 callbacks_p = &((*callbacks_p)->next);
1401 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1402 (*callbacks_p)->callback = callback;
1403 (*callbacks_p)->periodic = periodic;
1404 (*callbacks_p)->time_ms = time_ms;
1405 (*callbacks_p)->removed = false;
1407 gettimeofday(&now, NULL);
1408 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
1409 time_ms -= (time_ms % 1000);
1410 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
1411 if ((*callbacks_p)->when.tv_usec > 1000000) {
1412 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
1413 (*callbacks_p)->when.tv_sec += 1;
1416 (*callbacks_p)->priv = priv;
1417 (*callbacks_p)->next = NULL;
1419 return ERROR_OK;
1422 int target_unregister_event_callback(int (*callback)(struct target *target,
1423 enum target_event event, void *priv), void *priv)
1425 struct target_event_callback **p = &target_event_callbacks;
1426 struct target_event_callback *c = target_event_callbacks;
1428 if (callback == NULL)
1429 return ERROR_COMMAND_SYNTAX_ERROR;
1431 while (c) {
1432 struct target_event_callback *next = c->next;
1433 if ((c->callback == callback) && (c->priv == priv)) {
1434 *p = next;
1435 free(c);
1436 return ERROR_OK;
1437 } else
1438 p = &(c->next);
1439 c = next;
1442 return ERROR_OK;
1445 int target_unregister_reset_callback(int (*callback)(struct target *target,
1446 enum target_reset_mode reset_mode, void *priv), void *priv)
1448 struct target_reset_callback *entry;
1450 if (callback == NULL)
1451 return ERROR_COMMAND_SYNTAX_ERROR;
1453 list_for_each_entry(entry, &target_reset_callback_list, list) {
1454 if (entry->callback == callback && entry->priv == priv) {
1455 list_del(&entry->list);
1456 free(entry);
1457 break;
1461 return ERROR_OK;
1464 int target_unregister_trace_callback(int (*callback)(struct target *target,
1465 size_t len, uint8_t *data, void *priv), void *priv)
1467 struct target_trace_callback *entry;
1469 if (callback == NULL)
1470 return ERROR_COMMAND_SYNTAX_ERROR;
1472 list_for_each_entry(entry, &target_trace_callback_list, list) {
1473 if (entry->callback == callback && entry->priv == priv) {
1474 list_del(&entry->list);
1475 free(entry);
1476 break;
1480 return ERROR_OK;
1483 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1485 if (callback == NULL)
1486 return ERROR_COMMAND_SYNTAX_ERROR;
1488 for (struct target_timer_callback *c = target_timer_callbacks;
1489 c; c = c->next) {
1490 if ((c->callback == callback) && (c->priv == priv)) {
1491 c->removed = true;
1492 return ERROR_OK;
1496 return ERROR_FAIL;
1499 int target_call_event_callbacks(struct target *target, enum target_event event)
1501 struct target_event_callback *callback = target_event_callbacks;
1502 struct target_event_callback *next_callback;
1504 if (event == TARGET_EVENT_HALTED) {
1505 /* execute early halted first */
1506 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1509 LOG_DEBUG("target event %i (%s)", event,
1510 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1512 target_handle_event(target, event);
1514 while (callback) {
1515 next_callback = callback->next;
1516 callback->callback(target, event, callback->priv);
1517 callback = next_callback;
1520 return ERROR_OK;
1523 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1525 struct target_reset_callback *callback;
1527 LOG_DEBUG("target reset %i (%s)", reset_mode,
1528 Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name);
1530 list_for_each_entry(callback, &target_reset_callback_list, list)
1531 callback->callback(target, reset_mode, callback->priv);
1533 return ERROR_OK;
1536 int target_call_trace_callbacks(struct target *target, size_t len, uint8_t *data)
1538 struct target_trace_callback *callback;
1540 list_for_each_entry(callback, &target_trace_callback_list, list)
1541 callback->callback(target, len, data, callback->priv);
1543 return ERROR_OK;
1546 static int target_timer_callback_periodic_restart(
1547 struct target_timer_callback *cb, struct timeval *now)
1549 int time_ms = cb->time_ms;
1550 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1551 time_ms -= (time_ms % 1000);
1552 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1553 if (cb->when.tv_usec > 1000000) {
1554 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1555 cb->when.tv_sec += 1;
1557 return ERROR_OK;
1560 static int target_call_timer_callback(struct target_timer_callback *cb,
1561 struct timeval *now)
1563 cb->callback(cb->priv);
1565 if (cb->periodic)
1566 return target_timer_callback_periodic_restart(cb, now);
1568 return target_unregister_timer_callback(cb->callback, cb->priv);
1571 static int target_call_timer_callbacks_check_time(int checktime)
1573 static bool callback_processing;
1575 /* Do not allow nesting */
1576 if (callback_processing)
1577 return ERROR_OK;
1579 callback_processing = true;
1581 keep_alive();
1583 struct timeval now;
1584 gettimeofday(&now, NULL);
1586 /* Store an address of the place containing a pointer to the
1587 * next item; initially, that's a standalone "root of the
1588 * list" variable. */
1589 struct target_timer_callback **callback = &target_timer_callbacks;
1590 while (*callback) {
1591 if ((*callback)->removed) {
1592 struct target_timer_callback *p = *callback;
1593 *callback = (*callback)->next;
1594 free(p);
1595 continue;
1598 bool call_it = (*callback)->callback &&
1599 ((!checktime && (*callback)->periodic) ||
1600 now.tv_sec > (*callback)->when.tv_sec ||
1601 (now.tv_sec == (*callback)->when.tv_sec &&
1602 now.tv_usec >= (*callback)->when.tv_usec));
1604 if (call_it)
1605 target_call_timer_callback(*callback, &now);
1607 callback = &(*callback)->next;
1610 callback_processing = false;
1611 return ERROR_OK;
1614 int target_call_timer_callbacks(void)
1616 return target_call_timer_callbacks_check_time(1);
1619 /* invoke periodic callbacks immediately */
1620 int target_call_timer_callbacks_now(void)
1622 return target_call_timer_callbacks_check_time(0);
1625 /* Prints the working area layout for debug purposes */
1626 static void print_wa_layout(struct target *target)
1628 struct working_area *c = target->working_areas;
1630 while (c) {
1631 LOG_DEBUG("%c%c 0x%08"PRIx32"-0x%08"PRIx32" (%"PRIu32" bytes)",
1632 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1633 c->address, c->address + c->size - 1, c->size);
1634 c = c->next;
1638 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1639 static void target_split_working_area(struct working_area *area, uint32_t size)
1641 assert(area->free); /* Shouldn't split an allocated area */
1642 assert(size <= area->size); /* Caller should guarantee this */
1644 /* Split only if not already the right size */
1645 if (size < area->size) {
1646 struct working_area *new_wa = malloc(sizeof(*new_wa));
1648 if (new_wa == NULL)
1649 return;
1651 new_wa->next = area->next;
1652 new_wa->size = area->size - size;
1653 new_wa->address = area->address + size;
1654 new_wa->backup = NULL;
1655 new_wa->user = NULL;
1656 new_wa->free = true;
1658 area->next = new_wa;
1659 area->size = size;
1661 /* If backup memory was allocated to this area, it has the wrong size
1662 * now so free it and it will be reallocated if/when needed */
1663 if (area->backup) {
1664 free(area->backup);
1665 area->backup = NULL;
1670 /* Merge all adjacent free areas into one */
1671 static void target_merge_working_areas(struct target *target)
1673 struct working_area *c = target->working_areas;
1675 while (c && c->next) {
1676 assert(c->next->address == c->address + c->size); /* This is an invariant */
1678 /* Find two adjacent free areas */
1679 if (c->free && c->next->free) {
1680 /* Merge the last into the first */
1681 c->size += c->next->size;
1683 /* Remove the last */
1684 struct working_area *to_be_freed = c->next;
1685 c->next = c->next->next;
1686 if (to_be_freed->backup)
1687 free(to_be_freed->backup);
1688 free(to_be_freed);
1690 /* If backup memory was allocated to the remaining area, it's has
1691 * the wrong size now */
1692 if (c->backup) {
1693 free(c->backup);
1694 c->backup = NULL;
1696 } else {
1697 c = c->next;
1702 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1704 /* Reevaluate working area address based on MMU state*/
1705 if (target->working_areas == NULL) {
1706 int retval;
1707 int enabled;
1709 retval = target->type->mmu(target, &enabled);
1710 if (retval != ERROR_OK)
1711 return retval;
1713 if (!enabled) {
1714 if (target->working_area_phys_spec) {
1715 LOG_DEBUG("MMU disabled, using physical "
1716 "address for working memory 0x%08"PRIx32,
1717 target->working_area_phys);
1718 target->working_area = target->working_area_phys;
1719 } else {
1720 LOG_ERROR("No working memory available. "
1721 "Specify -work-area-phys to target.");
1722 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1724 } else {
1725 if (target->working_area_virt_spec) {
1726 LOG_DEBUG("MMU enabled, using virtual "
1727 "address for working memory 0x%08"PRIx32,
1728 target->working_area_virt);
1729 target->working_area = target->working_area_virt;
1730 } else {
1731 LOG_ERROR("No working memory available. "
1732 "Specify -work-area-virt to target.");
1733 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1737 /* Set up initial working area on first call */
1738 struct working_area *new_wa = malloc(sizeof(*new_wa));
1739 if (new_wa) {
1740 new_wa->next = NULL;
1741 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1742 new_wa->address = target->working_area;
1743 new_wa->backup = NULL;
1744 new_wa->user = NULL;
1745 new_wa->free = true;
1748 target->working_areas = new_wa;
1751 /* only allocate multiples of 4 byte */
1752 if (size % 4)
1753 size = (size + 3) & (~3UL);
1755 struct working_area *c = target->working_areas;
1757 /* Find the first large enough working area */
1758 while (c) {
1759 if (c->free && c->size >= size)
1760 break;
1761 c = c->next;
1764 if (c == NULL)
1765 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1767 /* Split the working area into the requested size */
1768 target_split_working_area(c, size);
1770 LOG_DEBUG("allocated new working area of %"PRIu32" bytes at address 0x%08"PRIx32, size, c->address);
1772 if (target->backup_working_area) {
1773 if (c->backup == NULL) {
1774 c->backup = malloc(c->size);
1775 if (c->backup == NULL)
1776 return ERROR_FAIL;
1779 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1780 if (retval != ERROR_OK)
1781 return retval;
1784 /* mark as used, and return the new (reused) area */
1785 c->free = false;
1786 *area = c;
1788 /* user pointer */
1789 c->user = area;
1791 print_wa_layout(target);
1793 return ERROR_OK;
1796 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1798 int retval;
1800 retval = target_alloc_working_area_try(target, size, area);
1801 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1802 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1803 return retval;
1807 static int target_restore_working_area(struct target *target, struct working_area *area)
1809 int retval = ERROR_OK;
1811 if (target->backup_working_area && area->backup != NULL) {
1812 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1813 if (retval != ERROR_OK)
1814 LOG_ERROR("failed to restore %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1815 area->size, area->address);
1818 return retval;
1821 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1822 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1824 int retval = ERROR_OK;
1826 if (area->free)
1827 return retval;
1829 if (restore) {
1830 retval = target_restore_working_area(target, area);
1831 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1832 if (retval != ERROR_OK)
1833 return retval;
1836 area->free = true;
1838 LOG_DEBUG("freed %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1839 area->size, area->address);
1841 /* mark user pointer invalid */
1842 /* TODO: Is this really safe? It points to some previous caller's memory.
1843 * How could we know that the area pointer is still in that place and not
1844 * some other vital data? What's the purpose of this, anyway? */
1845 *area->user = NULL;
1846 area->user = NULL;
1848 target_merge_working_areas(target);
1850 print_wa_layout(target);
1852 return retval;
1855 int target_free_working_area(struct target *target, struct working_area *area)
1857 return target_free_working_area_restore(target, area, 1);
1860 void target_quit(void)
1862 struct target_event_callback *pe = target_event_callbacks;
1863 while (pe) {
1864 struct target_event_callback *t = pe->next;
1865 free(pe);
1866 pe = t;
1868 target_event_callbacks = NULL;
1870 struct target_timer_callback *pt = target_timer_callbacks;
1871 while (pt) {
1872 struct target_timer_callback *t = pt->next;
1873 free(pt);
1874 pt = t;
1876 target_timer_callbacks = NULL;
1878 for (struct target *target = all_targets;
1879 target; target = target->next) {
1880 if (target->type->deinit_target)
1881 target->type->deinit_target(target);
1885 /* free resources and restore memory, if restoring memory fails,
1886 * free up resources anyway
1888 static void target_free_all_working_areas_restore(struct target *target, int restore)
1890 struct working_area *c = target->working_areas;
1892 LOG_DEBUG("freeing all working areas");
1894 /* Loop through all areas, restoring the allocated ones and marking them as free */
1895 while (c) {
1896 if (!c->free) {
1897 if (restore)
1898 target_restore_working_area(target, c);
1899 c->free = true;
1900 *c->user = NULL; /* Same as above */
1901 c->user = NULL;
1903 c = c->next;
1906 /* Run a merge pass to combine all areas into one */
1907 target_merge_working_areas(target);
1909 print_wa_layout(target);
1912 void target_free_all_working_areas(struct target *target)
1914 target_free_all_working_areas_restore(target, 1);
1917 /* Find the largest number of bytes that can be allocated */
1918 uint32_t target_get_working_area_avail(struct target *target)
1920 struct working_area *c = target->working_areas;
1921 uint32_t max_size = 0;
1923 if (c == NULL)
1924 return target->working_area_size;
1926 while (c) {
1927 if (c->free && max_size < c->size)
1928 max_size = c->size;
1930 c = c->next;
1933 return max_size;
1936 int target_arch_state(struct target *target)
1938 int retval;
1939 if (target == NULL) {
1940 LOG_USER("No target has been configured");
1941 return ERROR_OK;
1944 LOG_USER("%s: target state: %s", target_name(target),
1945 target_state_name(target));
1947 if (target->state != TARGET_HALTED)
1948 return ERROR_OK;
1950 retval = target->type->arch_state(target);
1951 return retval;
1954 static int target_get_gdb_fileio_info_default(struct target *target,
1955 struct gdb_fileio_info *fileio_info)
1957 /* If target does not support semi-hosting function, target
1958 has no need to provide .get_gdb_fileio_info callback.
1959 It just return ERROR_FAIL and gdb_server will return "Txx"
1960 as target halted every time. */
1961 return ERROR_FAIL;
1964 static int target_gdb_fileio_end_default(struct target *target,
1965 int retcode, int fileio_errno, bool ctrl_c)
1967 return ERROR_OK;
1970 static int target_profiling_default(struct target *target, uint32_t *samples,
1971 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1973 struct timeval timeout, now;
1975 gettimeofday(&timeout, NULL);
1976 timeval_add_time(&timeout, seconds, 0);
1978 LOG_INFO("Starting profiling. Halting and resuming the"
1979 " target as often as we can...");
1981 uint32_t sample_count = 0;
1982 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
1983 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
1985 int retval = ERROR_OK;
1986 for (;;) {
1987 target_poll(target);
1988 if (target->state == TARGET_HALTED) {
1989 uint32_t t = buf_get_u32(reg->value, 0, 32);
1990 samples[sample_count++] = t;
1991 /* current pc, addr = 0, do not handle breakpoints, not debugging */
1992 retval = target_resume(target, 1, 0, 0, 0);
1993 target_poll(target);
1994 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
1995 } else if (target->state == TARGET_RUNNING) {
1996 /* We want to quickly sample the PC. */
1997 retval = target_halt(target);
1998 } else {
1999 LOG_INFO("Target not halted or running");
2000 retval = ERROR_OK;
2001 break;
2004 if (retval != ERROR_OK)
2005 break;
2007 gettimeofday(&now, NULL);
2008 if ((sample_count >= max_num_samples) ||
2009 ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec))) {
2010 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2011 break;
2015 *num_samples = sample_count;
2016 return retval;
2019 /* Single aligned words are guaranteed to use 16 or 32 bit access
2020 * mode respectively, otherwise data is handled as quickly as
2021 * possible
2023 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
2025 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
2026 (int)size, (unsigned)address);
2028 if (!target_was_examined(target)) {
2029 LOG_ERROR("Target not examined yet");
2030 return ERROR_FAIL;
2033 if (size == 0)
2034 return ERROR_OK;
2036 if ((address + size - 1) < address) {
2037 /* GDB can request this when e.g. PC is 0xfffffffc */
2038 LOG_ERROR("address + size wrapped (0x%08x, 0x%08x)",
2039 (unsigned)address,
2040 (unsigned)size);
2041 return ERROR_FAIL;
2044 return target->type->write_buffer(target, address, size, buffer);
2047 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t count, const uint8_t *buffer)
2049 uint32_t size;
2051 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2052 * will have something to do with the size we leave to it. */
2053 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2054 if (address & size) {
2055 int retval = target_write_memory(target, address, size, 1, buffer);
2056 if (retval != ERROR_OK)
2057 return retval;
2058 address += size;
2059 count -= size;
2060 buffer += size;
2064 /* Write the data with as large access size as possible. */
2065 for (; size > 0; size /= 2) {
2066 uint32_t aligned = count - count % size;
2067 if (aligned > 0) {
2068 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2069 if (retval != ERROR_OK)
2070 return retval;
2071 address += aligned;
2072 count -= aligned;
2073 buffer += aligned;
2077 return ERROR_OK;
2080 /* Single aligned words are guaranteed to use 16 or 32 bit access
2081 * mode respectively, otherwise data is handled as quickly as
2082 * possible
2084 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
2086 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
2087 (int)size, (unsigned)address);
2089 if (!target_was_examined(target)) {
2090 LOG_ERROR("Target not examined yet");
2091 return ERROR_FAIL;
2094 if (size == 0)
2095 return ERROR_OK;
2097 if ((address + size - 1) < address) {
2098 /* GDB can request this when e.g. PC is 0xfffffffc */
2099 LOG_ERROR("address + size wrapped (0x%08" PRIx32 ", 0x%08" PRIx32 ")",
2100 address,
2101 size);
2102 return ERROR_FAIL;
2105 return target->type->read_buffer(target, address, size, buffer);
2108 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t count, uint8_t *buffer)
2110 uint32_t size;
2112 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2113 * will have something to do with the size we leave to it. */
2114 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2115 if (address & size) {
2116 int retval = target_read_memory(target, address, size, 1, buffer);
2117 if (retval != ERROR_OK)
2118 return retval;
2119 address += size;
2120 count -= size;
2121 buffer += size;
2125 /* Read the data with as large access size as possible. */
2126 for (; size > 0; size /= 2) {
2127 uint32_t aligned = count - count % size;
2128 if (aligned > 0) {
2129 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2130 if (retval != ERROR_OK)
2131 return retval;
2132 address += aligned;
2133 count -= aligned;
2134 buffer += aligned;
2138 return ERROR_OK;
2141 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
2143 uint8_t *buffer;
2144 int retval;
2145 uint32_t i;
2146 uint32_t checksum = 0;
2147 if (!target_was_examined(target)) {
2148 LOG_ERROR("Target not examined yet");
2149 return ERROR_FAIL;
2152 retval = target->type->checksum_memory(target, address, size, &checksum);
2153 if (retval != ERROR_OK) {
2154 buffer = malloc(size);
2155 if (buffer == NULL) {
2156 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
2157 return ERROR_COMMAND_SYNTAX_ERROR;
2159 retval = target_read_buffer(target, address, size, buffer);
2160 if (retval != ERROR_OK) {
2161 free(buffer);
2162 return retval;
2165 /* convert to target endianness */
2166 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2167 uint32_t target_data;
2168 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2169 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2172 retval = image_calculate_checksum(buffer, size, &checksum);
2173 free(buffer);
2176 *crc = checksum;
2178 return retval;
2181 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
2183 int retval;
2184 if (!target_was_examined(target)) {
2185 LOG_ERROR("Target not examined yet");
2186 return ERROR_FAIL;
2189 if (target->type->blank_check_memory == 0)
2190 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2192 retval = target->type->blank_check_memory(target, address, size, blank);
2194 return retval;
2197 int target_read_u64(struct target *target, uint64_t address, uint64_t *value)
2199 uint8_t value_buf[8];
2200 if (!target_was_examined(target)) {
2201 LOG_ERROR("Target not examined yet");
2202 return ERROR_FAIL;
2205 int retval = target_read_memory(target, address, 8, 1, value_buf);
2207 if (retval == ERROR_OK) {
2208 *value = target_buffer_get_u64(target, value_buf);
2209 LOG_DEBUG("address: 0x%" PRIx64 ", value: 0x%16.16" PRIx64 "",
2210 address,
2211 *value);
2212 } else {
2213 *value = 0x0;
2214 LOG_DEBUG("address: 0x%" PRIx64 " failed",
2215 address);
2218 return retval;
2221 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
2223 uint8_t value_buf[4];
2224 if (!target_was_examined(target)) {
2225 LOG_ERROR("Target not examined yet");
2226 return ERROR_FAIL;
2229 int retval = target_read_memory(target, address, 4, 1, value_buf);
2231 if (retval == ERROR_OK) {
2232 *value = target_buffer_get_u32(target, value_buf);
2233 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2234 address,
2235 *value);
2236 } else {
2237 *value = 0x0;
2238 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2239 address);
2242 return retval;
2245 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
2247 uint8_t value_buf[2];
2248 if (!target_was_examined(target)) {
2249 LOG_ERROR("Target not examined yet");
2250 return ERROR_FAIL;
2253 int retval = target_read_memory(target, address, 2, 1, value_buf);
2255 if (retval == ERROR_OK) {
2256 *value = target_buffer_get_u16(target, value_buf);
2257 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
2258 address,
2259 *value);
2260 } else {
2261 *value = 0x0;
2262 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2263 address);
2266 return retval;
2269 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
2271 if (!target_was_examined(target)) {
2272 LOG_ERROR("Target not examined yet");
2273 return ERROR_FAIL;
2276 int retval = target_read_memory(target, address, 1, 1, value);
2278 if (retval == ERROR_OK) {
2279 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2280 address,
2281 *value);
2282 } else {
2283 *value = 0x0;
2284 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2285 address);
2288 return retval;
2291 int target_write_u64(struct target *target, uint64_t address, uint64_t value)
2293 int retval;
2294 uint8_t value_buf[8];
2295 if (!target_was_examined(target)) {
2296 LOG_ERROR("Target not examined yet");
2297 return ERROR_FAIL;
2300 LOG_DEBUG("address: 0x%" PRIx64 ", value: 0x%16.16" PRIx64 "",
2301 address,
2302 value);
2304 target_buffer_set_u64(target, value_buf, value);
2305 retval = target_write_memory(target, address, 8, 1, value_buf);
2306 if (retval != ERROR_OK)
2307 LOG_DEBUG("failed: %i", retval);
2309 return retval;
2312 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
2314 int retval;
2315 uint8_t value_buf[4];
2316 if (!target_was_examined(target)) {
2317 LOG_ERROR("Target not examined yet");
2318 return ERROR_FAIL;
2321 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2322 address,
2323 value);
2325 target_buffer_set_u32(target, value_buf, value);
2326 retval = target_write_memory(target, address, 4, 1, value_buf);
2327 if (retval != ERROR_OK)
2328 LOG_DEBUG("failed: %i", retval);
2330 return retval;
2333 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
2335 int retval;
2336 uint8_t value_buf[2];
2337 if (!target_was_examined(target)) {
2338 LOG_ERROR("Target not examined yet");
2339 return ERROR_FAIL;
2342 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
2343 address,
2344 value);
2346 target_buffer_set_u16(target, value_buf, value);
2347 retval = target_write_memory(target, address, 2, 1, value_buf);
2348 if (retval != ERROR_OK)
2349 LOG_DEBUG("failed: %i", retval);
2351 return retval;
2354 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
2356 int retval;
2357 if (!target_was_examined(target)) {
2358 LOG_ERROR("Target not examined yet");
2359 return ERROR_FAIL;
2362 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2363 address, value);
2365 retval = target_write_memory(target, address, 1, 1, &value);
2366 if (retval != ERROR_OK)
2367 LOG_DEBUG("failed: %i", retval);
2369 return retval;
2372 static int find_target(struct command_context *cmd_ctx, const char *name)
2374 struct target *target = get_target(name);
2375 if (target == NULL) {
2376 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2377 return ERROR_FAIL;
2379 if (!target->tap->enabled) {
2380 LOG_USER("Target: TAP %s is disabled, "
2381 "can't be the current target\n",
2382 target->tap->dotted_name);
2383 return ERROR_FAIL;
2386 cmd_ctx->current_target = target->target_number;
2387 return ERROR_OK;
2391 COMMAND_HANDLER(handle_targets_command)
2393 int retval = ERROR_OK;
2394 if (CMD_ARGC == 1) {
2395 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2396 if (retval == ERROR_OK) {
2397 /* we're done! */
2398 return retval;
2402 struct target *target = all_targets;
2403 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2404 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2405 while (target) {
2406 const char *state;
2407 char marker = ' ';
2409 if (target->tap->enabled)
2410 state = target_state_name(target);
2411 else
2412 state = "tap-disabled";
2414 if (CMD_CTX->current_target == target->target_number)
2415 marker = '*';
2417 /* keep columns lined up to match the headers above */
2418 command_print(CMD_CTX,
2419 "%2d%c %-18s %-10s %-6s %-18s %s",
2420 target->target_number,
2421 marker,
2422 target_name(target),
2423 target_type_name(target),
2424 Jim_Nvp_value2name_simple(nvp_target_endian,
2425 target->endianness)->name,
2426 target->tap->dotted_name,
2427 state);
2428 target = target->next;
2431 return retval;
2434 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2436 static int powerDropout;
2437 static int srstAsserted;
2439 static int runPowerRestore;
2440 static int runPowerDropout;
2441 static int runSrstAsserted;
2442 static int runSrstDeasserted;
2444 static int sense_handler(void)
2446 static int prevSrstAsserted;
2447 static int prevPowerdropout;
2449 int retval = jtag_power_dropout(&powerDropout);
2450 if (retval != ERROR_OK)
2451 return retval;
2453 int powerRestored;
2454 powerRestored = prevPowerdropout && !powerDropout;
2455 if (powerRestored)
2456 runPowerRestore = 1;
2458 int64_t current = timeval_ms();
2459 static int64_t lastPower;
2460 bool waitMore = lastPower + 2000 > current;
2461 if (powerDropout && !waitMore) {
2462 runPowerDropout = 1;
2463 lastPower = current;
2466 retval = jtag_srst_asserted(&srstAsserted);
2467 if (retval != ERROR_OK)
2468 return retval;
2470 int srstDeasserted;
2471 srstDeasserted = prevSrstAsserted && !srstAsserted;
2473 static int64_t lastSrst;
2474 waitMore = lastSrst + 2000 > current;
2475 if (srstDeasserted && !waitMore) {
2476 runSrstDeasserted = 1;
2477 lastSrst = current;
2480 if (!prevSrstAsserted && srstAsserted)
2481 runSrstAsserted = 1;
2483 prevSrstAsserted = srstAsserted;
2484 prevPowerdropout = powerDropout;
2486 if (srstDeasserted || powerRestored) {
2487 /* Other than logging the event we can't do anything here.
2488 * Issuing a reset is a particularly bad idea as we might
2489 * be inside a reset already.
2493 return ERROR_OK;
2496 /* process target state changes */
2497 static int handle_target(void *priv)
2499 Jim_Interp *interp = (Jim_Interp *)priv;
2500 int retval = ERROR_OK;
2502 if (!is_jtag_poll_safe()) {
2503 /* polling is disabled currently */
2504 return ERROR_OK;
2507 /* we do not want to recurse here... */
2508 static int recursive;
2509 if (!recursive) {
2510 recursive = 1;
2511 sense_handler();
2512 /* danger! running these procedures can trigger srst assertions and power dropouts.
2513 * We need to avoid an infinite loop/recursion here and we do that by
2514 * clearing the flags after running these events.
2516 int did_something = 0;
2517 if (runSrstAsserted) {
2518 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2519 Jim_Eval(interp, "srst_asserted");
2520 did_something = 1;
2522 if (runSrstDeasserted) {
2523 Jim_Eval(interp, "srst_deasserted");
2524 did_something = 1;
2526 if (runPowerDropout) {
2527 LOG_INFO("Power dropout detected, running power_dropout proc.");
2528 Jim_Eval(interp, "power_dropout");
2529 did_something = 1;
2531 if (runPowerRestore) {
2532 Jim_Eval(interp, "power_restore");
2533 did_something = 1;
2536 if (did_something) {
2537 /* clear detect flags */
2538 sense_handler();
2541 /* clear action flags */
2543 runSrstAsserted = 0;
2544 runSrstDeasserted = 0;
2545 runPowerRestore = 0;
2546 runPowerDropout = 0;
2548 recursive = 0;
2551 /* Poll targets for state changes unless that's globally disabled.
2552 * Skip targets that are currently disabled.
2554 for (struct target *target = all_targets;
2555 is_jtag_poll_safe() && target;
2556 target = target->next) {
2558 if (!target_was_examined(target))
2559 continue;
2561 if (!target->tap->enabled)
2562 continue;
2564 if (target->backoff.times > target->backoff.count) {
2565 /* do not poll this time as we failed previously */
2566 target->backoff.count++;
2567 continue;
2569 target->backoff.count = 0;
2571 /* only poll target if we've got power and srst isn't asserted */
2572 if (!powerDropout && !srstAsserted) {
2573 /* polling may fail silently until the target has been examined */
2574 retval = target_poll(target);
2575 if (retval != ERROR_OK) {
2576 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2577 if (target->backoff.times * polling_interval < 5000) {
2578 target->backoff.times *= 2;
2579 target->backoff.times++;
2582 /* Tell GDB to halt the debugger. This allows the user to
2583 * run monitor commands to handle the situation.
2585 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2587 if (target->backoff.times > 0) {
2588 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
2589 target_reset_examined(target);
2590 retval = target_examine_one(target);
2591 /* Target examination could have failed due to unstable connection,
2592 * but we set the examined flag anyway to repoll it later */
2593 if (retval != ERROR_OK) {
2594 target->examined = true;
2595 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
2596 target->backoff.times * polling_interval);
2597 return retval;
2601 /* Since we succeeded, we reset backoff count */
2602 target->backoff.times = 0;
2606 return retval;
2609 COMMAND_HANDLER(handle_reg_command)
2611 struct target *target;
2612 struct reg *reg = NULL;
2613 unsigned count = 0;
2614 char *value;
2616 LOG_DEBUG("-");
2618 target = get_current_target(CMD_CTX);
2620 /* list all available registers for the current target */
2621 if (CMD_ARGC == 0) {
2622 struct reg_cache *cache = target->reg_cache;
2624 count = 0;
2625 while (cache) {
2626 unsigned i;
2628 command_print(CMD_CTX, "===== %s", cache->name);
2630 for (i = 0, reg = cache->reg_list;
2631 i < cache->num_regs;
2632 i++, reg++, count++) {
2633 /* only print cached values if they are valid */
2634 if (reg->valid) {
2635 value = buf_to_str(reg->value,
2636 reg->size, 16);
2637 command_print(CMD_CTX,
2638 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2639 count, reg->name,
2640 reg->size, value,
2641 reg->dirty
2642 ? " (dirty)"
2643 : "");
2644 free(value);
2645 } else {
2646 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2647 count, reg->name,
2648 reg->size) ;
2651 cache = cache->next;
2654 return ERROR_OK;
2657 /* access a single register by its ordinal number */
2658 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2659 unsigned num;
2660 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2662 struct reg_cache *cache = target->reg_cache;
2663 count = 0;
2664 while (cache) {
2665 unsigned i;
2666 for (i = 0; i < cache->num_regs; i++) {
2667 if (count++ == num) {
2668 reg = &cache->reg_list[i];
2669 break;
2672 if (reg)
2673 break;
2674 cache = cache->next;
2677 if (!reg) {
2678 command_print(CMD_CTX, "%i is out of bounds, the current target "
2679 "has only %i registers (0 - %i)", num, count, count - 1);
2680 return ERROR_OK;
2682 } else {
2683 /* access a single register by its name */
2684 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2686 if (!reg) {
2687 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2688 return ERROR_OK;
2692 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2694 /* display a register */
2695 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2696 && (CMD_ARGV[1][0] <= '9')))) {
2697 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2698 reg->valid = 0;
2700 if (reg->valid == 0)
2701 reg->type->get(reg);
2702 value = buf_to_str(reg->value, reg->size, 16);
2703 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2704 free(value);
2705 return ERROR_OK;
2708 /* set register value */
2709 if (CMD_ARGC == 2) {
2710 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2711 if (buf == NULL)
2712 return ERROR_FAIL;
2713 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2715 reg->type->set(reg, buf);
2717 value = buf_to_str(reg->value, reg->size, 16);
2718 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2719 free(value);
2721 free(buf);
2723 return ERROR_OK;
2726 return ERROR_COMMAND_SYNTAX_ERROR;
2729 COMMAND_HANDLER(handle_poll_command)
2731 int retval = ERROR_OK;
2732 struct target *target = get_current_target(CMD_CTX);
2734 if (CMD_ARGC == 0) {
2735 command_print(CMD_CTX, "background polling: %s",
2736 jtag_poll_get_enabled() ? "on" : "off");
2737 command_print(CMD_CTX, "TAP: %s (%s)",
2738 target->tap->dotted_name,
2739 target->tap->enabled ? "enabled" : "disabled");
2740 if (!target->tap->enabled)
2741 return ERROR_OK;
2742 retval = target_poll(target);
2743 if (retval != ERROR_OK)
2744 return retval;
2745 retval = target_arch_state(target);
2746 if (retval != ERROR_OK)
2747 return retval;
2748 } else if (CMD_ARGC == 1) {
2749 bool enable;
2750 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2751 jtag_poll_set_enabled(enable);
2752 } else
2753 return ERROR_COMMAND_SYNTAX_ERROR;
2755 return retval;
2758 COMMAND_HANDLER(handle_wait_halt_command)
2760 if (CMD_ARGC > 1)
2761 return ERROR_COMMAND_SYNTAX_ERROR;
2763 unsigned ms = DEFAULT_HALT_TIMEOUT;
2764 if (1 == CMD_ARGC) {
2765 int retval = parse_uint(CMD_ARGV[0], &ms);
2766 if (ERROR_OK != retval)
2767 return ERROR_COMMAND_SYNTAX_ERROR;
2770 struct target *target = get_current_target(CMD_CTX);
2771 return target_wait_state(target, TARGET_HALTED, ms);
2774 /* wait for target state to change. The trick here is to have a low
2775 * latency for short waits and not to suck up all the CPU time
2776 * on longer waits.
2778 * After 500ms, keep_alive() is invoked
2780 int target_wait_state(struct target *target, enum target_state state, int ms)
2782 int retval;
2783 int64_t then = 0, cur;
2784 bool once = true;
2786 for (;;) {
2787 retval = target_poll(target);
2788 if (retval != ERROR_OK)
2789 return retval;
2790 if (target->state == state)
2791 break;
2792 cur = timeval_ms();
2793 if (once) {
2794 once = false;
2795 then = timeval_ms();
2796 LOG_DEBUG("waiting for target %s...",
2797 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2800 if (cur-then > 500)
2801 keep_alive();
2803 if ((cur-then) > ms) {
2804 LOG_ERROR("timed out while waiting for target %s",
2805 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2806 return ERROR_FAIL;
2810 return ERROR_OK;
2813 COMMAND_HANDLER(handle_halt_command)
2815 LOG_DEBUG("-");
2817 struct target *target = get_current_target(CMD_CTX);
2818 int retval = target_halt(target);
2819 if (ERROR_OK != retval)
2820 return retval;
2822 if (CMD_ARGC == 1) {
2823 unsigned wait_local;
2824 retval = parse_uint(CMD_ARGV[0], &wait_local);
2825 if (ERROR_OK != retval)
2826 return ERROR_COMMAND_SYNTAX_ERROR;
2827 if (!wait_local)
2828 return ERROR_OK;
2831 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2834 COMMAND_HANDLER(handle_soft_reset_halt_command)
2836 struct target *target = get_current_target(CMD_CTX);
2838 LOG_USER("requesting target halt and executing a soft reset");
2840 target_soft_reset_halt(target);
2842 return ERROR_OK;
2845 COMMAND_HANDLER(handle_reset_command)
2847 if (CMD_ARGC > 1)
2848 return ERROR_COMMAND_SYNTAX_ERROR;
2850 enum target_reset_mode reset_mode = RESET_RUN;
2851 if (CMD_ARGC == 1) {
2852 const Jim_Nvp *n;
2853 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2854 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2855 return ERROR_COMMAND_SYNTAX_ERROR;
2856 reset_mode = n->value;
2859 /* reset *all* targets */
2860 return target_process_reset(CMD_CTX, reset_mode);
2864 COMMAND_HANDLER(handle_resume_command)
2866 int current = 1;
2867 if (CMD_ARGC > 1)
2868 return ERROR_COMMAND_SYNTAX_ERROR;
2870 struct target *target = get_current_target(CMD_CTX);
2872 /* with no CMD_ARGV, resume from current pc, addr = 0,
2873 * with one arguments, addr = CMD_ARGV[0],
2874 * handle breakpoints, not debugging */
2875 uint32_t addr = 0;
2876 if (CMD_ARGC == 1) {
2877 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2878 current = 0;
2881 return target_resume(target, current, addr, 1, 0);
2884 COMMAND_HANDLER(handle_step_command)
2886 if (CMD_ARGC > 1)
2887 return ERROR_COMMAND_SYNTAX_ERROR;
2889 LOG_DEBUG("-");
2891 /* with no CMD_ARGV, step from current pc, addr = 0,
2892 * with one argument addr = CMD_ARGV[0],
2893 * handle breakpoints, debugging */
2894 uint32_t addr = 0;
2895 int current_pc = 1;
2896 if (CMD_ARGC == 1) {
2897 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2898 current_pc = 0;
2901 struct target *target = get_current_target(CMD_CTX);
2903 return target->type->step(target, current_pc, addr, 1);
2906 static void handle_md_output(struct command_context *cmd_ctx,
2907 struct target *target, uint32_t address, unsigned size,
2908 unsigned count, const uint8_t *buffer)
2910 const unsigned line_bytecnt = 32;
2911 unsigned line_modulo = line_bytecnt / size;
2913 char output[line_bytecnt * 4 + 1];
2914 unsigned output_len = 0;
2916 const char *value_fmt;
2917 switch (size) {
2918 case 4:
2919 value_fmt = "%8.8x ";
2920 break;
2921 case 2:
2922 value_fmt = "%4.4x ";
2923 break;
2924 case 1:
2925 value_fmt = "%2.2x ";
2926 break;
2927 default:
2928 /* "can't happen", caller checked */
2929 LOG_ERROR("invalid memory read size: %u", size);
2930 return;
2933 for (unsigned i = 0; i < count; i++) {
2934 if (i % line_modulo == 0) {
2935 output_len += snprintf(output + output_len,
2936 sizeof(output) - output_len,
2937 "0x%8.8x: ",
2938 (unsigned)(address + (i*size)));
2941 uint32_t value = 0;
2942 const uint8_t *value_ptr = buffer + i * size;
2943 switch (size) {
2944 case 4:
2945 value = target_buffer_get_u32(target, value_ptr);
2946 break;
2947 case 2:
2948 value = target_buffer_get_u16(target, value_ptr);
2949 break;
2950 case 1:
2951 value = *value_ptr;
2953 output_len += snprintf(output + output_len,
2954 sizeof(output) - output_len,
2955 value_fmt, value);
2957 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2958 command_print(cmd_ctx, "%s", output);
2959 output_len = 0;
2964 COMMAND_HANDLER(handle_md_command)
2966 if (CMD_ARGC < 1)
2967 return ERROR_COMMAND_SYNTAX_ERROR;
2969 unsigned size = 0;
2970 switch (CMD_NAME[2]) {
2971 case 'w':
2972 size = 4;
2973 break;
2974 case 'h':
2975 size = 2;
2976 break;
2977 case 'b':
2978 size = 1;
2979 break;
2980 default:
2981 return ERROR_COMMAND_SYNTAX_ERROR;
2984 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2985 int (*fn)(struct target *target,
2986 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2987 if (physical) {
2988 CMD_ARGC--;
2989 CMD_ARGV++;
2990 fn = target_read_phys_memory;
2991 } else
2992 fn = target_read_memory;
2993 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2994 return ERROR_COMMAND_SYNTAX_ERROR;
2996 uint32_t address;
2997 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2999 unsigned count = 1;
3000 if (CMD_ARGC == 2)
3001 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3003 uint8_t *buffer = calloc(count, size);
3005 struct target *target = get_current_target(CMD_CTX);
3006 int retval = fn(target, address, size, count, buffer);
3007 if (ERROR_OK == retval)
3008 handle_md_output(CMD_CTX, target, address, size, count, buffer);
3010 free(buffer);
3012 return retval;
3015 typedef int (*target_write_fn)(struct target *target,
3016 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3018 static int target_fill_mem(struct target *target,
3019 uint32_t address,
3020 target_write_fn fn,
3021 unsigned data_size,
3022 /* value */
3023 uint32_t b,
3024 /* count */
3025 unsigned c)
3027 /* We have to write in reasonably large chunks to be able
3028 * to fill large memory areas with any sane speed */
3029 const unsigned chunk_size = 16384;
3030 uint8_t *target_buf = malloc(chunk_size * data_size);
3031 if (target_buf == NULL) {
3032 LOG_ERROR("Out of memory");
3033 return ERROR_FAIL;
3036 for (unsigned i = 0; i < chunk_size; i++) {
3037 switch (data_size) {
3038 case 4:
3039 target_buffer_set_u32(target, target_buf + i * data_size, b);
3040 break;
3041 case 2:
3042 target_buffer_set_u16(target, target_buf + i * data_size, b);
3043 break;
3044 case 1:
3045 target_buffer_set_u8(target, target_buf + i * data_size, b);
3046 break;
3047 default:
3048 exit(-1);
3052 int retval = ERROR_OK;
3054 for (unsigned x = 0; x < c; x += chunk_size) {
3055 unsigned current;
3056 current = c - x;
3057 if (current > chunk_size)
3058 current = chunk_size;
3059 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3060 if (retval != ERROR_OK)
3061 break;
3062 /* avoid GDB timeouts */
3063 keep_alive();
3065 free(target_buf);
3067 return retval;
3071 COMMAND_HANDLER(handle_mw_command)
3073 if (CMD_ARGC < 2)
3074 return ERROR_COMMAND_SYNTAX_ERROR;
3075 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3076 target_write_fn fn;
3077 if (physical) {
3078 CMD_ARGC--;
3079 CMD_ARGV++;
3080 fn = target_write_phys_memory;
3081 } else
3082 fn = target_write_memory;
3083 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3084 return ERROR_COMMAND_SYNTAX_ERROR;
3086 uint32_t address;
3087 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
3089 uint32_t value;
3090 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
3092 unsigned count = 1;
3093 if (CMD_ARGC == 3)
3094 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3096 struct target *target = get_current_target(CMD_CTX);
3097 unsigned wordsize;
3098 switch (CMD_NAME[2]) {
3099 case 'w':
3100 wordsize = 4;
3101 break;
3102 case 'h':
3103 wordsize = 2;
3104 break;
3105 case 'b':
3106 wordsize = 1;
3107 break;
3108 default:
3109 return ERROR_COMMAND_SYNTAX_ERROR;
3112 return target_fill_mem(target, address, fn, wordsize, value, count);
3115 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
3116 uint32_t *min_address, uint32_t *max_address)
3118 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3119 return ERROR_COMMAND_SYNTAX_ERROR;
3121 /* a base address isn't always necessary,
3122 * default to 0x0 (i.e. don't relocate) */
3123 if (CMD_ARGC >= 2) {
3124 uint32_t addr;
3125 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3126 image->base_address = addr;
3127 image->base_address_set = 1;
3128 } else
3129 image->base_address_set = 0;
3131 image->start_address_set = 0;
3133 if (CMD_ARGC >= 4)
3134 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
3135 if (CMD_ARGC == 5) {
3136 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
3137 /* use size (given) to find max (required) */
3138 *max_address += *min_address;
3141 if (*min_address > *max_address)
3142 return ERROR_COMMAND_SYNTAX_ERROR;
3144 return ERROR_OK;
3147 COMMAND_HANDLER(handle_load_image_command)
3149 uint8_t *buffer;
3150 size_t buf_cnt;
3151 uint32_t image_size;
3152 uint32_t min_address = 0;
3153 uint32_t max_address = 0xffffffff;
3154 int i;
3155 struct image image;
3157 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
3158 &image, &min_address, &max_address);
3159 if (ERROR_OK != retval)
3160 return retval;
3162 struct target *target = get_current_target(CMD_CTX);
3164 struct duration bench;
3165 duration_start(&bench);
3167 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3168 return ERROR_OK;
3170 image_size = 0x0;
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;
3181 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3182 if (retval != ERROR_OK) {
3183 free(buffer);
3184 break;
3187 uint32_t offset = 0;
3188 uint32_t length = buf_cnt;
3190 /* DANGER!!! beware of unsigned comparision here!!! */
3192 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3193 (image.sections[i].base_address < max_address)) {
3195 if (image.sections[i].base_address < min_address) {
3196 /* clip addresses below */
3197 offset += min_address-image.sections[i].base_address;
3198 length -= offset;
3201 if (image.sections[i].base_address + buf_cnt > max_address)
3202 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3204 retval = target_write_buffer(target,
3205 image.sections[i].base_address + offset, length, buffer + offset);
3206 if (retval != ERROR_OK) {
3207 free(buffer);
3208 break;
3210 image_size += length;
3211 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
3212 (unsigned int)length,
3213 image.sections[i].base_address + offset);
3216 free(buffer);
3219 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3220 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
3221 "in %fs (%0.3f KiB/s)", image_size,
3222 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3225 image_close(&image);
3227 return retval;
3231 COMMAND_HANDLER(handle_dump_image_command)
3233 struct fileio *fileio;
3234 uint8_t *buffer;
3235 int retval, retvaltemp;
3236 uint32_t address, size;
3237 struct duration bench;
3238 struct target *target = get_current_target(CMD_CTX);
3240 if (CMD_ARGC != 3)
3241 return ERROR_COMMAND_SYNTAX_ERROR;
3243 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
3244 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
3246 uint32_t buf_size = (size > 4096) ? 4096 : size;
3247 buffer = malloc(buf_size);
3248 if (!buffer)
3249 return ERROR_FAIL;
3251 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3252 if (retval != ERROR_OK) {
3253 free(buffer);
3254 return retval;
3257 duration_start(&bench);
3259 while (size > 0) {
3260 size_t size_written;
3261 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3262 retval = target_read_buffer(target, address, this_run_size, buffer);
3263 if (retval != ERROR_OK)
3264 break;
3266 retval = fileio_write(fileio, this_run_size, buffer, &size_written);
3267 if (retval != ERROR_OK)
3268 break;
3270 size -= this_run_size;
3271 address += this_run_size;
3274 free(buffer);
3276 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3277 size_t filesize;
3278 retval = fileio_size(fileio, &filesize);
3279 if (retval != ERROR_OK)
3280 return retval;
3281 command_print(CMD_CTX,
3282 "dumped %zu bytes in %fs (%0.3f KiB/s)", filesize,
3283 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3286 retvaltemp = fileio_close(fileio);
3287 if (retvaltemp != ERROR_OK)
3288 return retvaltemp;
3290 return retval;
3293 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
3295 uint8_t *buffer;
3296 size_t buf_cnt;
3297 uint32_t image_size;
3298 int i;
3299 int retval;
3300 uint32_t checksum = 0;
3301 uint32_t mem_checksum = 0;
3303 struct image image;
3305 struct target *target = get_current_target(CMD_CTX);
3307 if (CMD_ARGC < 1)
3308 return ERROR_COMMAND_SYNTAX_ERROR;
3310 if (!target) {
3311 LOG_ERROR("no target selected");
3312 return ERROR_FAIL;
3315 struct duration bench;
3316 duration_start(&bench);
3318 if (CMD_ARGC >= 2) {
3319 uint32_t addr;
3320 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3321 image.base_address = addr;
3322 image.base_address_set = 1;
3323 } else {
3324 image.base_address_set = 0;
3325 image.base_address = 0x0;
3328 image.start_address_set = 0;
3330 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3331 if (retval != ERROR_OK)
3332 return retval;
3334 image_size = 0x0;
3335 int diffs = 0;
3336 retval = ERROR_OK;
3337 for (i = 0; i < image.num_sections; i++) {
3338 buffer = malloc(image.sections[i].size);
3339 if (buffer == NULL) {
3340 command_print(CMD_CTX,
3341 "error allocating buffer for section (%d bytes)",
3342 (int)(image.sections[i].size));
3343 break;
3345 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3346 if (retval != ERROR_OK) {
3347 free(buffer);
3348 break;
3351 if (verify) {
3352 /* calculate checksum of image */
3353 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3354 if (retval != ERROR_OK) {
3355 free(buffer);
3356 break;
3359 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3360 if (retval != ERROR_OK) {
3361 free(buffer);
3362 break;
3365 if (checksum != mem_checksum) {
3366 /* failed crc checksum, fall back to a binary compare */
3367 uint8_t *data;
3369 if (diffs == 0)
3370 LOG_ERROR("checksum mismatch - attempting binary compare");
3372 data = malloc(buf_cnt);
3374 /* Can we use 32bit word accesses? */
3375 int size = 1;
3376 int count = buf_cnt;
3377 if ((count % 4) == 0) {
3378 size *= 4;
3379 count /= 4;
3381 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3382 if (retval == ERROR_OK) {
3383 uint32_t t;
3384 for (t = 0; t < buf_cnt; t++) {
3385 if (data[t] != buffer[t]) {
3386 command_print(CMD_CTX,
3387 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3388 diffs,
3389 (unsigned)(t + image.sections[i].base_address),
3390 data[t],
3391 buffer[t]);
3392 if (diffs++ >= 127) {
3393 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3394 free(data);
3395 free(buffer);
3396 goto done;
3399 keep_alive();
3402 free(data);
3404 } else {
3405 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3406 image.sections[i].base_address,
3407 buf_cnt);
3410 free(buffer);
3411 image_size += buf_cnt;
3413 if (diffs > 0)
3414 command_print(CMD_CTX, "No more differences found.");
3415 done:
3416 if (diffs > 0)
3417 retval = ERROR_FAIL;
3418 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3419 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3420 "in %fs (%0.3f KiB/s)", image_size,
3421 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3424 image_close(&image);
3426 return retval;
3429 COMMAND_HANDLER(handle_verify_image_command)
3431 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3434 COMMAND_HANDLER(handle_test_image_command)
3436 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3439 static int handle_bp_command_list(struct command_context *cmd_ctx)
3441 struct target *target = get_current_target(cmd_ctx);
3442 struct breakpoint *breakpoint = target->breakpoints;
3443 while (breakpoint) {
3444 if (breakpoint->type == BKPT_SOFT) {
3445 char *buf = buf_to_str(breakpoint->orig_instr,
3446 breakpoint->length, 16);
3447 command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3448 breakpoint->address,
3449 breakpoint->length,
3450 breakpoint->set, buf);
3451 free(buf);
3452 } else {
3453 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3454 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3455 breakpoint->asid,
3456 breakpoint->length, breakpoint->set);
3457 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3458 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3459 breakpoint->address,
3460 breakpoint->length, breakpoint->set);
3461 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3462 breakpoint->asid);
3463 } else
3464 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3465 breakpoint->address,
3466 breakpoint->length, breakpoint->set);
3469 breakpoint = breakpoint->next;
3471 return ERROR_OK;
3474 static int handle_bp_command_set(struct command_context *cmd_ctx,
3475 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3477 struct target *target = get_current_target(cmd_ctx);
3478 int retval;
3480 if (asid == 0) {
3481 retval = breakpoint_add(target, addr, length, hw);
3482 if (ERROR_OK == retval)
3483 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3484 else {
3485 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3486 return retval;
3488 } else if (addr == 0) {
3489 if (target->type->add_context_breakpoint == NULL) {
3490 LOG_WARNING("Context breakpoint not available");
3491 return ERROR_OK;
3493 retval = context_breakpoint_add(target, asid, length, hw);
3494 if (ERROR_OK == retval)
3495 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3496 else {
3497 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3498 return retval;
3500 } else {
3501 if (target->type->add_hybrid_breakpoint == NULL) {
3502 LOG_WARNING("Hybrid breakpoint not available");
3503 return ERROR_OK;
3505 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3506 if (ERROR_OK == retval)
3507 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3508 else {
3509 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3510 return retval;
3513 return ERROR_OK;
3516 COMMAND_HANDLER(handle_bp_command)
3518 uint32_t addr;
3519 uint32_t asid;
3520 uint32_t length;
3521 int hw = BKPT_SOFT;
3523 switch (CMD_ARGC) {
3524 case 0:
3525 return handle_bp_command_list(CMD_CTX);
3527 case 2:
3528 asid = 0;
3529 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3530 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3531 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3533 case 3:
3534 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3535 hw = BKPT_HARD;
3536 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3538 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3540 asid = 0;
3541 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3542 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3543 hw = BKPT_HARD;
3544 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3545 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3546 addr = 0;
3547 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3550 case 4:
3551 hw = BKPT_HARD;
3552 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3553 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3554 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3555 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3557 default:
3558 return ERROR_COMMAND_SYNTAX_ERROR;
3562 COMMAND_HANDLER(handle_rbp_command)
3564 if (CMD_ARGC != 1)
3565 return ERROR_COMMAND_SYNTAX_ERROR;
3567 uint32_t addr;
3568 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3570 struct target *target = get_current_target(CMD_CTX);
3571 breakpoint_remove(target, addr);
3573 return ERROR_OK;
3576 COMMAND_HANDLER(handle_wp_command)
3578 struct target *target = get_current_target(CMD_CTX);
3580 if (CMD_ARGC == 0) {
3581 struct watchpoint *watchpoint = target->watchpoints;
3583 while (watchpoint) {
3584 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3585 ", len: 0x%8.8" PRIx32
3586 ", r/w/a: %i, value: 0x%8.8" PRIx32
3587 ", mask: 0x%8.8" PRIx32,
3588 watchpoint->address,
3589 watchpoint->length,
3590 (int)watchpoint->rw,
3591 watchpoint->value,
3592 watchpoint->mask);
3593 watchpoint = watchpoint->next;
3595 return ERROR_OK;
3598 enum watchpoint_rw type = WPT_ACCESS;
3599 uint32_t addr = 0;
3600 uint32_t length = 0;
3601 uint32_t data_value = 0x0;
3602 uint32_t data_mask = 0xffffffff;
3604 switch (CMD_ARGC) {
3605 case 5:
3606 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3607 /* fall through */
3608 case 4:
3609 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3610 /* fall through */
3611 case 3:
3612 switch (CMD_ARGV[2][0]) {
3613 case 'r':
3614 type = WPT_READ;
3615 break;
3616 case 'w':
3617 type = WPT_WRITE;
3618 break;
3619 case 'a':
3620 type = WPT_ACCESS;
3621 break;
3622 default:
3623 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3624 return ERROR_COMMAND_SYNTAX_ERROR;
3626 /* fall through */
3627 case 2:
3628 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3629 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3630 break;
3632 default:
3633 return ERROR_COMMAND_SYNTAX_ERROR;
3636 int retval = watchpoint_add(target, addr, length, type,
3637 data_value, data_mask);
3638 if (ERROR_OK != retval)
3639 LOG_ERROR("Failure setting watchpoints");
3641 return retval;
3644 COMMAND_HANDLER(handle_rwp_command)
3646 if (CMD_ARGC != 1)
3647 return ERROR_COMMAND_SYNTAX_ERROR;
3649 uint32_t addr;
3650 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3652 struct target *target = get_current_target(CMD_CTX);
3653 watchpoint_remove(target, addr);
3655 return ERROR_OK;
3659 * Translate a virtual address to a physical address.
3661 * The low-level target implementation must have logged a detailed error
3662 * which is forwarded to telnet/GDB session.
3664 COMMAND_HANDLER(handle_virt2phys_command)
3666 if (CMD_ARGC != 1)
3667 return ERROR_COMMAND_SYNTAX_ERROR;
3669 uint32_t va;
3670 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3671 uint32_t pa;
3673 struct target *target = get_current_target(CMD_CTX);
3674 int retval = target->type->virt2phys(target, va, &pa);
3675 if (retval == ERROR_OK)
3676 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3678 return retval;
3681 static void writeData(FILE *f, const void *data, size_t len)
3683 size_t written = fwrite(data, 1, len, f);
3684 if (written != len)
3685 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3688 static void writeLong(FILE *f, int l, struct target *target)
3690 uint8_t val[4];
3692 target_buffer_set_u32(target, val, l);
3693 writeData(f, val, 4);
3696 static void writeString(FILE *f, char *s)
3698 writeData(f, s, strlen(s));
3701 typedef unsigned char UNIT[2]; /* unit of profiling */
3703 /* Dump a gmon.out histogram file. */
3704 static void write_gmon(uint32_t *samples, uint32_t sampleNum, const char *filename, bool with_range,
3705 uint32_t start_address, uint32_t end_address, struct target *target)
3707 uint32_t i;
3708 FILE *f = fopen(filename, "w");
3709 if (f == NULL)
3710 return;
3711 writeString(f, "gmon");
3712 writeLong(f, 0x00000001, target); /* Version */
3713 writeLong(f, 0, target); /* padding */
3714 writeLong(f, 0, target); /* padding */
3715 writeLong(f, 0, target); /* padding */
3717 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3718 writeData(f, &zero, 1);
3720 /* figure out bucket size */
3721 uint32_t min;
3722 uint32_t max;
3723 if (with_range) {
3724 min = start_address;
3725 max = end_address;
3726 } else {
3727 min = samples[0];
3728 max = samples[0];
3729 for (i = 0; i < sampleNum; i++) {
3730 if (min > samples[i])
3731 min = samples[i];
3732 if (max < samples[i])
3733 max = samples[i];
3736 /* max should be (largest sample + 1)
3737 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
3738 max++;
3741 int addressSpace = max - min;
3742 assert(addressSpace >= 2);
3744 /* FIXME: What is the reasonable number of buckets?
3745 * The profiling result will be more accurate if there are enough buckets. */
3746 static const uint32_t maxBuckets = 128 * 1024; /* maximum buckets. */
3747 uint32_t numBuckets = addressSpace / sizeof(UNIT);
3748 if (numBuckets > maxBuckets)
3749 numBuckets = maxBuckets;
3750 int *buckets = malloc(sizeof(int) * numBuckets);
3751 if (buckets == NULL) {
3752 fclose(f);
3753 return;
3755 memset(buckets, 0, sizeof(int) * numBuckets);
3756 for (i = 0; i < sampleNum; i++) {
3757 uint32_t address = samples[i];
3759 if ((address < min) || (max <= address))
3760 continue;
3762 long long a = address - min;
3763 long long b = numBuckets;
3764 long long c = addressSpace;
3765 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3766 buckets[index_t]++;
3769 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3770 writeLong(f, min, target); /* low_pc */
3771 writeLong(f, max, target); /* high_pc */
3772 writeLong(f, numBuckets, target); /* # of buckets */
3773 writeLong(f, 100, target); /* KLUDGE! We lie, ca. 100Hz best case. */
3774 writeString(f, "seconds");
3775 for (i = 0; i < (15-strlen("seconds")); i++)
3776 writeData(f, &zero, 1);
3777 writeString(f, "s");
3779 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3781 char *data = malloc(2 * numBuckets);
3782 if (data != NULL) {
3783 for (i = 0; i < numBuckets; i++) {
3784 int val;
3785 val = buckets[i];
3786 if (val > 65535)
3787 val = 65535;
3788 data[i * 2] = val&0xff;
3789 data[i * 2 + 1] = (val >> 8) & 0xff;
3791 free(buckets);
3792 writeData(f, data, numBuckets * 2);
3793 free(data);
3794 } else
3795 free(buckets);
3797 fclose(f);
3800 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3801 * which will be used as a random sampling of PC */
3802 COMMAND_HANDLER(handle_profile_command)
3804 struct target *target = get_current_target(CMD_CTX);
3806 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
3807 return ERROR_COMMAND_SYNTAX_ERROR;
3809 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
3810 uint32_t offset;
3811 uint32_t num_of_samples;
3812 int retval = ERROR_OK;
3814 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
3816 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
3817 if (samples == NULL) {
3818 LOG_ERROR("No memory to store samples.");
3819 return ERROR_FAIL;
3823 * Some cores let us sample the PC without the
3824 * annoying halt/resume step; for example, ARMv7 PCSR.
3825 * Provide a way to use that more efficient mechanism.
3827 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
3828 &num_of_samples, offset);
3829 if (retval != ERROR_OK) {
3830 free(samples);
3831 return retval;
3834 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
3836 retval = target_poll(target);
3837 if (retval != ERROR_OK) {
3838 free(samples);
3839 return retval;
3841 if (target->state == TARGET_RUNNING) {
3842 retval = target_halt(target);
3843 if (retval != ERROR_OK) {
3844 free(samples);
3845 return retval;
3849 retval = target_poll(target);
3850 if (retval != ERROR_OK) {
3851 free(samples);
3852 return retval;
3855 uint32_t start_address = 0;
3856 uint32_t end_address = 0;
3857 bool with_range = false;
3858 if (CMD_ARGC == 4) {
3859 with_range = true;
3860 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
3861 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
3864 write_gmon(samples, num_of_samples, CMD_ARGV[1],
3865 with_range, start_address, end_address, target);
3866 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3868 free(samples);
3869 return retval;
3872 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3874 char *namebuf;
3875 Jim_Obj *nameObjPtr, *valObjPtr;
3876 int result;
3878 namebuf = alloc_printf("%s(%d)", varname, idx);
3879 if (!namebuf)
3880 return JIM_ERR;
3882 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3883 valObjPtr = Jim_NewIntObj(interp, val);
3884 if (!nameObjPtr || !valObjPtr) {
3885 free(namebuf);
3886 return JIM_ERR;
3889 Jim_IncrRefCount(nameObjPtr);
3890 Jim_IncrRefCount(valObjPtr);
3891 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3892 Jim_DecrRefCount(interp, nameObjPtr);
3893 Jim_DecrRefCount(interp, valObjPtr);
3894 free(namebuf);
3895 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3896 return result;
3899 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3901 struct command_context *context;
3902 struct target *target;
3904 context = current_command_context(interp);
3905 assert(context != NULL);
3907 target = get_current_target(context);
3908 if (target == NULL) {
3909 LOG_ERROR("mem2array: no current target");
3910 return JIM_ERR;
3913 return target_mem2array(interp, target, argc - 1, argv + 1);
3916 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3918 long l;
3919 uint32_t width;
3920 int len;
3921 uint32_t addr;
3922 uint32_t count;
3923 uint32_t v;
3924 const char *varname;
3925 const char *phys;
3926 bool is_phys;
3927 int n, e, retval;
3928 uint32_t i;
3930 /* argv[1] = name of array to receive the data
3931 * argv[2] = desired width
3932 * argv[3] = memory address
3933 * argv[4] = count of times to read
3935 if (argc < 4 || argc > 5) {
3936 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems [phys]");
3937 return JIM_ERR;
3939 varname = Jim_GetString(argv[0], &len);
3940 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3942 e = Jim_GetLong(interp, argv[1], &l);
3943 width = l;
3944 if (e != JIM_OK)
3945 return e;
3947 e = Jim_GetLong(interp, argv[2], &l);
3948 addr = l;
3949 if (e != JIM_OK)
3950 return e;
3951 e = Jim_GetLong(interp, argv[3], &l);
3952 len = l;
3953 if (e != JIM_OK)
3954 return e;
3955 is_phys = false;
3956 if (argc > 4) {
3957 phys = Jim_GetString(argv[4], &n);
3958 if (!strncmp(phys, "phys", n))
3959 is_phys = true;
3960 else
3961 return JIM_ERR;
3963 switch (width) {
3964 case 8:
3965 width = 1;
3966 break;
3967 case 16:
3968 width = 2;
3969 break;
3970 case 32:
3971 width = 4;
3972 break;
3973 default:
3974 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3975 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3976 return JIM_ERR;
3978 if (len == 0) {
3979 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3980 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3981 return JIM_ERR;
3983 if ((addr + (len * width)) < addr) {
3984 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3985 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3986 return JIM_ERR;
3988 /* absurd transfer size? */
3989 if (len > 65536) {
3990 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3991 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3992 return JIM_ERR;
3995 if ((width == 1) ||
3996 ((width == 2) && ((addr & 1) == 0)) ||
3997 ((width == 4) && ((addr & 3) == 0))) {
3998 /* all is well */
3999 } else {
4000 char buf[100];
4001 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4002 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
4003 addr,
4004 width);
4005 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4006 return JIM_ERR;
4009 /* Transfer loop */
4011 /* index counter */
4012 n = 0;
4014 size_t buffersize = 4096;
4015 uint8_t *buffer = malloc(buffersize);
4016 if (buffer == NULL)
4017 return JIM_ERR;
4019 /* assume ok */
4020 e = JIM_OK;
4021 while (len) {
4022 /* Slurp... in buffer size chunks */
4024 count = len; /* in objects.. */
4025 if (count > (buffersize / width))
4026 count = (buffersize / width);
4028 if (is_phys)
4029 retval = target_read_phys_memory(target, addr, width, count, buffer);
4030 else
4031 retval = target_read_memory(target, addr, width, count, buffer);
4032 if (retval != ERROR_OK) {
4033 /* BOO !*/
4034 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
4035 (unsigned int)addr,
4036 (int)width,
4037 (int)count);
4038 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4039 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
4040 e = JIM_ERR;
4041 break;
4042 } else {
4043 v = 0; /* shut up gcc */
4044 for (i = 0; i < count ; i++, n++) {
4045 switch (width) {
4046 case 4:
4047 v = target_buffer_get_u32(target, &buffer[i*width]);
4048 break;
4049 case 2:
4050 v = target_buffer_get_u16(target, &buffer[i*width]);
4051 break;
4052 case 1:
4053 v = buffer[i] & 0x0ff;
4054 break;
4056 new_int_array_element(interp, varname, n, v);
4058 len -= count;
4059 addr += count * width;
4063 free(buffer);
4065 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4067 return e;
4070 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
4072 char *namebuf;
4073 Jim_Obj *nameObjPtr, *valObjPtr;
4074 int result;
4075 long l;
4077 namebuf = alloc_printf("%s(%d)", varname, idx);
4078 if (!namebuf)
4079 return JIM_ERR;
4081 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
4082 if (!nameObjPtr) {
4083 free(namebuf);
4084 return JIM_ERR;
4087 Jim_IncrRefCount(nameObjPtr);
4088 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
4089 Jim_DecrRefCount(interp, nameObjPtr);
4090 free(namebuf);
4091 if (valObjPtr == NULL)
4092 return JIM_ERR;
4094 result = Jim_GetLong(interp, valObjPtr, &l);
4095 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
4096 *val = l;
4097 return result;
4100 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4102 struct command_context *context;
4103 struct target *target;
4105 context = current_command_context(interp);
4106 assert(context != NULL);
4108 target = get_current_target(context);
4109 if (target == NULL) {
4110 LOG_ERROR("array2mem: no current target");
4111 return JIM_ERR;
4114 return target_array2mem(interp, target, argc-1, argv + 1);
4117 static int target_array2mem(Jim_Interp *interp, struct target *target,
4118 int argc, Jim_Obj *const *argv)
4120 long l;
4121 uint32_t width;
4122 int len;
4123 uint32_t addr;
4124 uint32_t count;
4125 uint32_t v;
4126 const char *varname;
4127 const char *phys;
4128 bool is_phys;
4129 int n, e, retval;
4130 uint32_t i;
4132 /* argv[1] = name of array to get the data
4133 * argv[2] = desired width
4134 * argv[3] = memory address
4135 * argv[4] = count to write
4137 if (argc < 4 || argc > 5) {
4138 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4139 return JIM_ERR;
4141 varname = Jim_GetString(argv[0], &len);
4142 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
4144 e = Jim_GetLong(interp, argv[1], &l);
4145 width = l;
4146 if (e != JIM_OK)
4147 return e;
4149 e = Jim_GetLong(interp, argv[2], &l);
4150 addr = l;
4151 if (e != JIM_OK)
4152 return e;
4153 e = Jim_GetLong(interp, argv[3], &l);
4154 len = l;
4155 if (e != JIM_OK)
4156 return e;
4157 is_phys = false;
4158 if (argc > 4) {
4159 phys = Jim_GetString(argv[4], &n);
4160 if (!strncmp(phys, "phys", n))
4161 is_phys = true;
4162 else
4163 return JIM_ERR;
4165 switch (width) {
4166 case 8:
4167 width = 1;
4168 break;
4169 case 16:
4170 width = 2;
4171 break;
4172 case 32:
4173 width = 4;
4174 break;
4175 default:
4176 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4177 Jim_AppendStrings(interp, Jim_GetResult(interp),
4178 "Invalid width param, must be 8/16/32", NULL);
4179 return JIM_ERR;
4181 if (len == 0) {
4182 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4183 Jim_AppendStrings(interp, Jim_GetResult(interp),
4184 "array2mem: zero width read?", NULL);
4185 return JIM_ERR;
4187 if ((addr + (len * width)) < addr) {
4188 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4189 Jim_AppendStrings(interp, Jim_GetResult(interp),
4190 "array2mem: addr + len - wraps to zero?", NULL);
4191 return JIM_ERR;
4193 /* absurd transfer size? */
4194 if (len > 65536) {
4195 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4196 Jim_AppendStrings(interp, Jim_GetResult(interp),
4197 "array2mem: absurd > 64K item request", NULL);
4198 return JIM_ERR;
4201 if ((width == 1) ||
4202 ((width == 2) && ((addr & 1) == 0)) ||
4203 ((width == 4) && ((addr & 3) == 0))) {
4204 /* all is well */
4205 } else {
4206 char buf[100];
4207 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4208 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
4209 (unsigned int)addr,
4210 (int)width);
4211 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4212 return JIM_ERR;
4215 /* Transfer loop */
4217 /* index counter */
4218 n = 0;
4219 /* assume ok */
4220 e = JIM_OK;
4222 size_t buffersize = 4096;
4223 uint8_t *buffer = malloc(buffersize);
4224 if (buffer == NULL)
4225 return JIM_ERR;
4227 while (len) {
4228 /* Slurp... in buffer size chunks */
4230 count = len; /* in objects.. */
4231 if (count > (buffersize / width))
4232 count = (buffersize / width);
4234 v = 0; /* shut up gcc */
4235 for (i = 0; i < count; i++, n++) {
4236 get_int_array_element(interp, varname, n, &v);
4237 switch (width) {
4238 case 4:
4239 target_buffer_set_u32(target, &buffer[i * width], v);
4240 break;
4241 case 2:
4242 target_buffer_set_u16(target, &buffer[i * width], v);
4243 break;
4244 case 1:
4245 buffer[i] = v & 0x0ff;
4246 break;
4249 len -= count;
4251 if (is_phys)
4252 retval = target_write_phys_memory(target, addr, width, count, buffer);
4253 else
4254 retval = target_write_memory(target, addr, width, count, buffer);
4255 if (retval != ERROR_OK) {
4256 /* BOO !*/
4257 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
4258 (unsigned int)addr,
4259 (int)width,
4260 (int)count);
4261 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4262 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4263 e = JIM_ERR;
4264 break;
4266 addr += count * width;
4269 free(buffer);
4271 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4273 return e;
4276 /* FIX? should we propagate errors here rather than printing them
4277 * and continuing?
4279 void target_handle_event(struct target *target, enum target_event e)
4281 struct target_event_action *teap;
4283 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4284 if (teap->event == e) {
4285 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
4286 target->target_number,
4287 target_name(target),
4288 target_type_name(target),
4290 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
4291 Jim_GetString(teap->body, NULL));
4292 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
4293 Jim_MakeErrorMessage(teap->interp);
4294 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
4301 * Returns true only if the target has a handler for the specified event.
4303 bool target_has_event_action(struct target *target, enum target_event event)
4305 struct target_event_action *teap;
4307 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4308 if (teap->event == event)
4309 return true;
4311 return false;
4314 enum target_cfg_param {
4315 TCFG_TYPE,
4316 TCFG_EVENT,
4317 TCFG_WORK_AREA_VIRT,
4318 TCFG_WORK_AREA_PHYS,
4319 TCFG_WORK_AREA_SIZE,
4320 TCFG_WORK_AREA_BACKUP,
4321 TCFG_ENDIAN,
4322 TCFG_COREID,
4323 TCFG_CHAIN_POSITION,
4324 TCFG_DBGBASE,
4325 TCFG_RTOS,
4328 static Jim_Nvp nvp_config_opts[] = {
4329 { .name = "-type", .value = TCFG_TYPE },
4330 { .name = "-event", .value = TCFG_EVENT },
4331 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4332 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4333 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4334 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4335 { .name = "-endian" , .value = TCFG_ENDIAN },
4336 { .name = "-coreid", .value = TCFG_COREID },
4337 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4338 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4339 { .name = "-rtos", .value = TCFG_RTOS },
4340 { .name = NULL, .value = -1 }
4343 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
4345 Jim_Nvp *n;
4346 Jim_Obj *o;
4347 jim_wide w;
4348 int e;
4350 /* parse config or cget options ... */
4351 while (goi->argc > 0) {
4352 Jim_SetEmptyResult(goi->interp);
4353 /* Jim_GetOpt_Debug(goi); */
4355 if (target->type->target_jim_configure) {
4356 /* target defines a configure function */
4357 /* target gets first dibs on parameters */
4358 e = (*(target->type->target_jim_configure))(target, goi);
4359 if (e == JIM_OK) {
4360 /* more? */
4361 continue;
4363 if (e == JIM_ERR) {
4364 /* An error */
4365 return e;
4367 /* otherwise we 'continue' below */
4369 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
4370 if (e != JIM_OK) {
4371 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
4372 return e;
4374 switch (n->value) {
4375 case TCFG_TYPE:
4376 /* not setable */
4377 if (goi->isconfigure) {
4378 Jim_SetResultFormatted(goi->interp,
4379 "not settable: %s", n->name);
4380 return JIM_ERR;
4381 } else {
4382 no_params:
4383 if (goi->argc != 0) {
4384 Jim_WrongNumArgs(goi->interp,
4385 goi->argc, goi->argv,
4386 "NO PARAMS");
4387 return JIM_ERR;
4390 Jim_SetResultString(goi->interp,
4391 target_type_name(target), -1);
4392 /* loop for more */
4393 break;
4394 case TCFG_EVENT:
4395 if (goi->argc == 0) {
4396 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4397 return JIM_ERR;
4400 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4401 if (e != JIM_OK) {
4402 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4403 return e;
4406 if (goi->isconfigure) {
4407 if (goi->argc != 1) {
4408 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4409 return JIM_ERR;
4411 } else {
4412 if (goi->argc != 0) {
4413 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4414 return JIM_ERR;
4419 struct target_event_action *teap;
4421 teap = target->event_action;
4422 /* replace existing? */
4423 while (teap) {
4424 if (teap->event == (enum target_event)n->value)
4425 break;
4426 teap = teap->next;
4429 if (goi->isconfigure) {
4430 bool replace = true;
4431 if (teap == NULL) {
4432 /* create new */
4433 teap = calloc(1, sizeof(*teap));
4434 replace = false;
4436 teap->event = n->value;
4437 teap->interp = goi->interp;
4438 Jim_GetOpt_Obj(goi, &o);
4439 if (teap->body)
4440 Jim_DecrRefCount(teap->interp, teap->body);
4441 teap->body = Jim_DuplicateObj(goi->interp, o);
4443 * FIXME:
4444 * Tcl/TK - "tk events" have a nice feature.
4445 * See the "BIND" command.
4446 * We should support that here.
4447 * You can specify %X and %Y in the event code.
4448 * The idea is: %T - target name.
4449 * The idea is: %N - target number
4450 * The idea is: %E - event name.
4452 Jim_IncrRefCount(teap->body);
4454 if (!replace) {
4455 /* add to head of event list */
4456 teap->next = target->event_action;
4457 target->event_action = teap;
4459 Jim_SetEmptyResult(goi->interp);
4460 } else {
4461 /* get */
4462 if (teap == NULL)
4463 Jim_SetEmptyResult(goi->interp);
4464 else
4465 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4468 /* loop for more */
4469 break;
4471 case TCFG_WORK_AREA_VIRT:
4472 if (goi->isconfigure) {
4473 target_free_all_working_areas(target);
4474 e = Jim_GetOpt_Wide(goi, &w);
4475 if (e != JIM_OK)
4476 return e;
4477 target->working_area_virt = w;
4478 target->working_area_virt_spec = true;
4479 } else {
4480 if (goi->argc != 0)
4481 goto no_params;
4483 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4484 /* loop for more */
4485 break;
4487 case TCFG_WORK_AREA_PHYS:
4488 if (goi->isconfigure) {
4489 target_free_all_working_areas(target);
4490 e = Jim_GetOpt_Wide(goi, &w);
4491 if (e != JIM_OK)
4492 return e;
4493 target->working_area_phys = w;
4494 target->working_area_phys_spec = true;
4495 } else {
4496 if (goi->argc != 0)
4497 goto no_params;
4499 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4500 /* loop for more */
4501 break;
4503 case TCFG_WORK_AREA_SIZE:
4504 if (goi->isconfigure) {
4505 target_free_all_working_areas(target);
4506 e = Jim_GetOpt_Wide(goi, &w);
4507 if (e != JIM_OK)
4508 return e;
4509 target->working_area_size = w;
4510 } else {
4511 if (goi->argc != 0)
4512 goto no_params;
4514 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4515 /* loop for more */
4516 break;
4518 case TCFG_WORK_AREA_BACKUP:
4519 if (goi->isconfigure) {
4520 target_free_all_working_areas(target);
4521 e = Jim_GetOpt_Wide(goi, &w);
4522 if (e != JIM_OK)
4523 return e;
4524 /* make this exactly 1 or 0 */
4525 target->backup_working_area = (!!w);
4526 } else {
4527 if (goi->argc != 0)
4528 goto no_params;
4530 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4531 /* loop for more e*/
4532 break;
4535 case TCFG_ENDIAN:
4536 if (goi->isconfigure) {
4537 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4538 if (e != JIM_OK) {
4539 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4540 return e;
4542 target->endianness = n->value;
4543 } else {
4544 if (goi->argc != 0)
4545 goto no_params;
4547 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4548 if (n->name == NULL) {
4549 target->endianness = TARGET_LITTLE_ENDIAN;
4550 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4552 Jim_SetResultString(goi->interp, n->name, -1);
4553 /* loop for more */
4554 break;
4556 case TCFG_COREID:
4557 if (goi->isconfigure) {
4558 e = Jim_GetOpt_Wide(goi, &w);
4559 if (e != JIM_OK)
4560 return e;
4561 target->coreid = (int32_t)w;
4562 } else {
4563 if (goi->argc != 0)
4564 goto no_params;
4566 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4567 /* loop for more */
4568 break;
4570 case TCFG_CHAIN_POSITION:
4571 if (goi->isconfigure) {
4572 Jim_Obj *o_t;
4573 struct jtag_tap *tap;
4574 target_free_all_working_areas(target);
4575 e = Jim_GetOpt_Obj(goi, &o_t);
4576 if (e != JIM_OK)
4577 return e;
4578 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4579 if (tap == NULL)
4580 return JIM_ERR;
4581 /* make this exactly 1 or 0 */
4582 target->tap = tap;
4583 } else {
4584 if (goi->argc != 0)
4585 goto no_params;
4587 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4588 /* loop for more e*/
4589 break;
4590 case TCFG_DBGBASE:
4591 if (goi->isconfigure) {
4592 e = Jim_GetOpt_Wide(goi, &w);
4593 if (e != JIM_OK)
4594 return e;
4595 target->dbgbase = (uint32_t)w;
4596 target->dbgbase_set = true;
4597 } else {
4598 if (goi->argc != 0)
4599 goto no_params;
4601 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4602 /* loop for more */
4603 break;
4605 case TCFG_RTOS:
4606 /* RTOS */
4608 int result = rtos_create(goi, target);
4609 if (result != JIM_OK)
4610 return result;
4612 /* loop for more */
4613 break;
4615 } /* while (goi->argc) */
4618 /* done - we return */
4619 return JIM_OK;
4622 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4624 Jim_GetOptInfo goi;
4626 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4627 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4628 int need_args = 1 + goi.isconfigure;
4629 if (goi.argc < need_args) {
4630 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4631 goi.isconfigure
4632 ? "missing: -option VALUE ..."
4633 : "missing: -option ...");
4634 return JIM_ERR;
4636 struct target *target = Jim_CmdPrivData(goi.interp);
4637 return target_configure(&goi, target);
4640 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4642 const char *cmd_name = Jim_GetString(argv[0], NULL);
4644 Jim_GetOptInfo goi;
4645 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4647 if (goi.argc < 2 || goi.argc > 4) {
4648 Jim_SetResultFormatted(goi.interp,
4649 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4650 return JIM_ERR;
4653 target_write_fn fn;
4654 fn = target_write_memory;
4656 int e;
4657 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4658 /* consume it */
4659 struct Jim_Obj *obj;
4660 e = Jim_GetOpt_Obj(&goi, &obj);
4661 if (e != JIM_OK)
4662 return e;
4664 fn = target_write_phys_memory;
4667 jim_wide a;
4668 e = Jim_GetOpt_Wide(&goi, &a);
4669 if (e != JIM_OK)
4670 return e;
4672 jim_wide b;
4673 e = Jim_GetOpt_Wide(&goi, &b);
4674 if (e != JIM_OK)
4675 return e;
4677 jim_wide c = 1;
4678 if (goi.argc == 1) {
4679 e = Jim_GetOpt_Wide(&goi, &c);
4680 if (e != JIM_OK)
4681 return e;
4684 /* all args must be consumed */
4685 if (goi.argc != 0)
4686 return JIM_ERR;
4688 struct target *target = Jim_CmdPrivData(goi.interp);
4689 unsigned data_size;
4690 if (strcasecmp(cmd_name, "mww") == 0)
4691 data_size = 4;
4692 else if (strcasecmp(cmd_name, "mwh") == 0)
4693 data_size = 2;
4694 else if (strcasecmp(cmd_name, "mwb") == 0)
4695 data_size = 1;
4696 else {
4697 LOG_ERROR("command '%s' unknown: ", cmd_name);
4698 return JIM_ERR;
4701 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4705 * @brief Reads an array of words/halfwords/bytes from target memory starting at specified address.
4707 * Usage: mdw [phys] <address> [<count>] - for 32 bit reads
4708 * mdh [phys] <address> [<count>] - for 16 bit reads
4709 * mdb [phys] <address> [<count>] - for 8 bit reads
4711 * Count defaults to 1.
4713 * Calls target_read_memory or target_read_phys_memory depending on
4714 * the presence of the "phys" argument
4715 * Reads the target memory in blocks of max. 32 bytes, and returns an array of ints formatted
4716 * to int representation in base16.
4717 * Also outputs read data in a human readable form using command_print
4719 * @param phys if present target_read_phys_memory will be used instead of target_read_memory
4720 * @param address address where to start the read. May be specified in decimal or hex using the standard "0x" prefix
4721 * @param count optional count parameter to read an array of values. If not specified, defaults to 1.
4722 * @returns: JIM_ERR on error or JIM_OK on success and sets the result string to an array of ascii formatted numbers
4723 * on success, with [<count>] number of elements.
4725 * In case of little endian target:
4726 * Example1: "mdw 0x00000000" returns "10123456"
4727 * Exmaple2: "mdh 0x00000000 1" returns "3456"
4728 * Example3: "mdb 0x00000000" returns "56"
4729 * Example4: "mdh 0x00000000 2" returns "3456 1012"
4730 * Example5: "mdb 0x00000000 3" returns "56 34 12"
4732 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4734 const char *cmd_name = Jim_GetString(argv[0], NULL);
4736 Jim_GetOptInfo goi;
4737 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4739 if ((goi.argc < 1) || (goi.argc > 3)) {
4740 Jim_SetResultFormatted(goi.interp,
4741 "usage: %s [phys] <address> [<count>]", cmd_name);
4742 return JIM_ERR;
4745 int (*fn)(struct target *target,
4746 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4747 fn = target_read_memory;
4749 int e;
4750 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4751 /* consume it */
4752 struct Jim_Obj *obj;
4753 e = Jim_GetOpt_Obj(&goi, &obj);
4754 if (e != JIM_OK)
4755 return e;
4757 fn = target_read_phys_memory;
4760 /* Read address parameter */
4761 jim_wide addr;
4762 e = Jim_GetOpt_Wide(&goi, &addr);
4763 if (e != JIM_OK)
4764 return JIM_ERR;
4766 /* If next parameter exists, read it out as the count parameter, if not, set it to 1 (default) */
4767 jim_wide count;
4768 if (goi.argc == 1) {
4769 e = Jim_GetOpt_Wide(&goi, &count);
4770 if (e != JIM_OK)
4771 return JIM_ERR;
4772 } else
4773 count = 1;
4775 /* all args must be consumed */
4776 if (goi.argc != 0)
4777 return JIM_ERR;
4779 jim_wide dwidth = 1; /* shut up gcc */
4780 if (strcasecmp(cmd_name, "mdw") == 0)
4781 dwidth = 4;
4782 else if (strcasecmp(cmd_name, "mdh") == 0)
4783 dwidth = 2;
4784 else if (strcasecmp(cmd_name, "mdb") == 0)
4785 dwidth = 1;
4786 else {
4787 LOG_ERROR("command '%s' unknown: ", cmd_name);
4788 return JIM_ERR;
4791 /* convert count to "bytes" */
4792 int bytes = count * dwidth;
4794 struct target *target = Jim_CmdPrivData(goi.interp);
4795 uint8_t target_buf[32];
4796 jim_wide x, y, z;
4797 while (bytes > 0) {
4798 y = (bytes < 16) ? bytes : 16; /* y = min(bytes, 16); */
4800 /* Try to read out next block */
4801 e = fn(target, addr, dwidth, y / dwidth, target_buf);
4803 if (e != ERROR_OK) {
4804 Jim_SetResultFormatted(interp, "error reading target @ 0x%08lx", (long)addr);
4805 return JIM_ERR;
4808 command_print_sameline(NULL, "0x%08x ", (int)(addr));
4809 switch (dwidth) {
4810 case 4:
4811 for (x = 0; x < 16 && x < y; x += 4) {
4812 z = target_buffer_get_u32(target, &(target_buf[x]));
4813 command_print_sameline(NULL, "%08x ", (int)(z));
4815 for (; (x < 16) ; x += 4)
4816 command_print_sameline(NULL, " ");
4817 break;
4818 case 2:
4819 for (x = 0; x < 16 && x < y; x += 2) {
4820 z = target_buffer_get_u16(target, &(target_buf[x]));
4821 command_print_sameline(NULL, "%04x ", (int)(z));
4823 for (; (x < 16) ; x += 2)
4824 command_print_sameline(NULL, " ");
4825 break;
4826 case 1:
4827 default:
4828 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4829 z = target_buffer_get_u8(target, &(target_buf[x]));
4830 command_print_sameline(NULL, "%02x ", (int)(z));
4832 for (; (x < 16) ; x += 1)
4833 command_print_sameline(NULL, " ");
4834 break;
4836 /* ascii-ify the bytes */
4837 for (x = 0 ; x < y ; x++) {
4838 if ((target_buf[x] >= 0x20) &&
4839 (target_buf[x] <= 0x7e)) {
4840 /* good */
4841 } else {
4842 /* smack it */
4843 target_buf[x] = '.';
4846 /* space pad */
4847 while (x < 16) {
4848 target_buf[x] = ' ';
4849 x++;
4851 /* terminate */
4852 target_buf[16] = 0;
4853 /* print - with a newline */
4854 command_print_sameline(NULL, "%s\n", target_buf);
4855 /* NEXT... */
4856 bytes -= 16;
4857 addr += 16;
4859 return JIM_OK;
4862 static int jim_target_mem2array(Jim_Interp *interp,
4863 int argc, Jim_Obj *const *argv)
4865 struct target *target = Jim_CmdPrivData(interp);
4866 return target_mem2array(interp, target, argc - 1, argv + 1);
4869 static int jim_target_array2mem(Jim_Interp *interp,
4870 int argc, Jim_Obj *const *argv)
4872 struct target *target = Jim_CmdPrivData(interp);
4873 return target_array2mem(interp, target, argc - 1, argv + 1);
4876 static int jim_target_tap_disabled(Jim_Interp *interp)
4878 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4879 return JIM_ERR;
4882 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4884 if (argc != 1) {
4885 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4886 return JIM_ERR;
4888 struct target *target = Jim_CmdPrivData(interp);
4889 if (!target->tap->enabled)
4890 return jim_target_tap_disabled(interp);
4892 int e = target->type->examine(target);
4893 if (e != ERROR_OK)
4894 return JIM_ERR;
4895 return JIM_OK;
4898 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4900 if (argc != 1) {
4901 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4902 return JIM_ERR;
4904 struct target *target = Jim_CmdPrivData(interp);
4906 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4907 return JIM_ERR;
4909 return JIM_OK;
4912 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4914 if (argc != 1) {
4915 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4916 return JIM_ERR;
4918 struct target *target = Jim_CmdPrivData(interp);
4919 if (!target->tap->enabled)
4920 return jim_target_tap_disabled(interp);
4922 int e;
4923 if (!(target_was_examined(target)))
4924 e = ERROR_TARGET_NOT_EXAMINED;
4925 else
4926 e = target->type->poll(target);
4927 if (e != ERROR_OK)
4928 return JIM_ERR;
4929 return JIM_OK;
4932 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4934 Jim_GetOptInfo goi;
4935 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4937 if (goi.argc != 2) {
4938 Jim_WrongNumArgs(interp, 0, argv,
4939 "([tT]|[fF]|assert|deassert) BOOL");
4940 return JIM_ERR;
4943 Jim_Nvp *n;
4944 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4945 if (e != JIM_OK) {
4946 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4947 return e;
4949 /* the halt or not param */
4950 jim_wide a;
4951 e = Jim_GetOpt_Wide(&goi, &a);
4952 if (e != JIM_OK)
4953 return e;
4955 struct target *target = Jim_CmdPrivData(goi.interp);
4956 if (!target->tap->enabled)
4957 return jim_target_tap_disabled(interp);
4959 if (!target->type->assert_reset || !target->type->deassert_reset) {
4960 Jim_SetResultFormatted(interp,
4961 "No target-specific reset for %s",
4962 target_name(target));
4963 return JIM_ERR;
4965 /* determine if we should halt or not. */
4966 target->reset_halt = !!a;
4967 /* When this happens - all workareas are invalid. */
4968 target_free_all_working_areas_restore(target, 0);
4970 /* do the assert */
4971 if (n->value == NVP_ASSERT)
4972 e = target->type->assert_reset(target);
4973 else
4974 e = target->type->deassert_reset(target);
4975 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4978 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4980 if (argc != 1) {
4981 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4982 return JIM_ERR;
4984 struct target *target = Jim_CmdPrivData(interp);
4985 if (!target->tap->enabled)
4986 return jim_target_tap_disabled(interp);
4987 int e = target->type->halt(target);
4988 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4991 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4993 Jim_GetOptInfo goi;
4994 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4996 /* params: <name> statename timeoutmsecs */
4997 if (goi.argc != 2) {
4998 const char *cmd_name = Jim_GetString(argv[0], NULL);
4999 Jim_SetResultFormatted(goi.interp,
5000 "%s <state_name> <timeout_in_msec>", cmd_name);
5001 return JIM_ERR;
5004 Jim_Nvp *n;
5005 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
5006 if (e != JIM_OK) {
5007 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
5008 return e;
5010 jim_wide a;
5011 e = Jim_GetOpt_Wide(&goi, &a);
5012 if (e != JIM_OK)
5013 return e;
5014 struct target *target = Jim_CmdPrivData(interp);
5015 if (!target->tap->enabled)
5016 return jim_target_tap_disabled(interp);
5018 e = target_wait_state(target, n->value, a);
5019 if (e != ERROR_OK) {
5020 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
5021 Jim_SetResultFormatted(goi.interp,
5022 "target: %s wait %s fails (%#s) %s",
5023 target_name(target), n->name,
5024 eObj, target_strerror_safe(e));
5025 Jim_FreeNewObj(interp, eObj);
5026 return JIM_ERR;
5028 return JIM_OK;
5030 /* List for human, Events defined for this target.
5031 * scripts/programs should use 'name cget -event NAME'
5033 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5035 struct command_context *cmd_ctx = current_command_context(interp);
5036 assert(cmd_ctx != NULL);
5038 struct target *target = Jim_CmdPrivData(interp);
5039 struct target_event_action *teap = target->event_action;
5040 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
5041 target->target_number,
5042 target_name(target));
5043 command_print(cmd_ctx, "%-25s | Body", "Event");
5044 command_print(cmd_ctx, "------------------------- | "
5045 "----------------------------------------");
5046 while (teap) {
5047 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
5048 command_print(cmd_ctx, "%-25s | %s",
5049 opt->name, Jim_GetString(teap->body, NULL));
5050 teap = teap->next;
5052 command_print(cmd_ctx, "***END***");
5053 return JIM_OK;
5055 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5057 if (argc != 1) {
5058 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5059 return JIM_ERR;
5061 struct target *target = Jim_CmdPrivData(interp);
5062 Jim_SetResultString(interp, target_state_name(target), -1);
5063 return JIM_OK;
5065 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5067 Jim_GetOptInfo goi;
5068 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5069 if (goi.argc != 1) {
5070 const char *cmd_name = Jim_GetString(argv[0], NULL);
5071 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5072 return JIM_ERR;
5074 Jim_Nvp *n;
5075 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
5076 if (e != JIM_OK) {
5077 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
5078 return e;
5080 struct target *target = Jim_CmdPrivData(interp);
5081 target_handle_event(target, n->value);
5082 return JIM_OK;
5085 static const struct command_registration target_instance_command_handlers[] = {
5087 .name = "configure",
5088 .mode = COMMAND_CONFIG,
5089 .jim_handler = jim_target_configure,
5090 .help = "configure a new target for use",
5091 .usage = "[target_attribute ...]",
5094 .name = "cget",
5095 .mode = COMMAND_ANY,
5096 .jim_handler = jim_target_configure,
5097 .help = "returns the specified target attribute",
5098 .usage = "target_attribute",
5101 .name = "mww",
5102 .mode = COMMAND_EXEC,
5103 .jim_handler = jim_target_mw,
5104 .help = "Write 32-bit word(s) to target memory",
5105 .usage = "address data [count]",
5108 .name = "mwh",
5109 .mode = COMMAND_EXEC,
5110 .jim_handler = jim_target_mw,
5111 .help = "Write 16-bit half-word(s) to target memory",
5112 .usage = "address data [count]",
5115 .name = "mwb",
5116 .mode = COMMAND_EXEC,
5117 .jim_handler = jim_target_mw,
5118 .help = "Write byte(s) to target memory",
5119 .usage = "address data [count]",
5122 .name = "mdw",
5123 .mode = COMMAND_EXEC,
5124 .jim_handler = jim_target_md,
5125 .help = "Display target memory as 32-bit words",
5126 .usage = "address [count]",
5129 .name = "mdh",
5130 .mode = COMMAND_EXEC,
5131 .jim_handler = jim_target_md,
5132 .help = "Display target memory as 16-bit half-words",
5133 .usage = "address [count]",
5136 .name = "mdb",
5137 .mode = COMMAND_EXEC,
5138 .jim_handler = jim_target_md,
5139 .help = "Display target memory as 8-bit bytes",
5140 .usage = "address [count]",
5143 .name = "array2mem",
5144 .mode = COMMAND_EXEC,
5145 .jim_handler = jim_target_array2mem,
5146 .help = "Writes Tcl array of 8/16/32 bit numbers "
5147 "to target memory",
5148 .usage = "arrayname bitwidth address count",
5151 .name = "mem2array",
5152 .mode = COMMAND_EXEC,
5153 .jim_handler = jim_target_mem2array,
5154 .help = "Loads Tcl array of 8/16/32 bit numbers "
5155 "from target memory",
5156 .usage = "arrayname bitwidth address count",
5159 .name = "eventlist",
5160 .mode = COMMAND_EXEC,
5161 .jim_handler = jim_target_event_list,
5162 .help = "displays a table of events defined for this target",
5165 .name = "curstate",
5166 .mode = COMMAND_EXEC,
5167 .jim_handler = jim_target_current_state,
5168 .help = "displays the current state of this target",
5171 .name = "arp_examine",
5172 .mode = COMMAND_EXEC,
5173 .jim_handler = jim_target_examine,
5174 .help = "used internally for reset processing",
5177 .name = "arp_halt_gdb",
5178 .mode = COMMAND_EXEC,
5179 .jim_handler = jim_target_halt_gdb,
5180 .help = "used internally for reset processing to halt GDB",
5183 .name = "arp_poll",
5184 .mode = COMMAND_EXEC,
5185 .jim_handler = jim_target_poll,
5186 .help = "used internally for reset processing",
5189 .name = "arp_reset",
5190 .mode = COMMAND_EXEC,
5191 .jim_handler = jim_target_reset,
5192 .help = "used internally for reset processing",
5195 .name = "arp_halt",
5196 .mode = COMMAND_EXEC,
5197 .jim_handler = jim_target_halt,
5198 .help = "used internally for reset processing",
5201 .name = "arp_waitstate",
5202 .mode = COMMAND_EXEC,
5203 .jim_handler = jim_target_wait_state,
5204 .help = "used internally for reset processing",
5207 .name = "invoke-event",
5208 .mode = COMMAND_EXEC,
5209 .jim_handler = jim_target_invoke_event,
5210 .help = "invoke handler for specified event",
5211 .usage = "event_name",
5213 COMMAND_REGISTRATION_DONE
5216 static int target_create(Jim_GetOptInfo *goi)
5218 Jim_Obj *new_cmd;
5219 Jim_Cmd *cmd;
5220 const char *cp;
5221 int e;
5222 int x;
5223 struct target *target;
5224 struct command_context *cmd_ctx;
5226 cmd_ctx = current_command_context(goi->interp);
5227 assert(cmd_ctx != NULL);
5229 if (goi->argc < 3) {
5230 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5231 return JIM_ERR;
5234 /* COMMAND */
5235 Jim_GetOpt_Obj(goi, &new_cmd);
5236 /* does this command exist? */
5237 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
5238 if (cmd) {
5239 cp = Jim_GetString(new_cmd, NULL);
5240 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5241 return JIM_ERR;
5244 /* TYPE */
5245 e = Jim_GetOpt_String(goi, &cp, NULL);
5246 if (e != JIM_OK)
5247 return e;
5248 struct transport *tr = get_current_transport();
5249 if (tr->override_target) {
5250 e = tr->override_target(&cp);
5251 if (e != ERROR_OK) {
5252 LOG_ERROR("The selected transport doesn't support this target");
5253 return JIM_ERR;
5255 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5257 /* now does target type exist */
5258 for (x = 0 ; target_types[x] ; x++) {
5259 if (0 == strcmp(cp, target_types[x]->name)) {
5260 /* found */
5261 break;
5264 /* check for deprecated name */
5265 if (target_types[x]->deprecated_name) {
5266 if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
5267 /* found */
5268 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
5269 break;
5273 if (target_types[x] == NULL) {
5274 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5275 for (x = 0 ; target_types[x] ; x++) {
5276 if (target_types[x + 1]) {
5277 Jim_AppendStrings(goi->interp,
5278 Jim_GetResult(goi->interp),
5279 target_types[x]->name,
5280 ", ", NULL);
5281 } else {
5282 Jim_AppendStrings(goi->interp,
5283 Jim_GetResult(goi->interp),
5284 " or ",
5285 target_types[x]->name, NULL);
5288 return JIM_ERR;
5291 /* Create it */
5292 target = calloc(1, sizeof(struct target));
5293 /* set target number */
5294 target->target_number = new_target_number();
5295 cmd_ctx->current_target = target->target_number;
5297 /* allocate memory for each unique target type */
5298 target->type = calloc(1, sizeof(struct target_type));
5300 memcpy(target->type, target_types[x], sizeof(struct target_type));
5302 /* will be set by "-endian" */
5303 target->endianness = TARGET_ENDIAN_UNKNOWN;
5305 /* default to first core, override with -coreid */
5306 target->coreid = 0;
5308 target->working_area = 0x0;
5309 target->working_area_size = 0x0;
5310 target->working_areas = NULL;
5311 target->backup_working_area = 0;
5313 target->state = TARGET_UNKNOWN;
5314 target->debug_reason = DBG_REASON_UNDEFINED;
5315 target->reg_cache = NULL;
5316 target->breakpoints = NULL;
5317 target->watchpoints = NULL;
5318 target->next = NULL;
5319 target->arch_info = NULL;
5321 target->display = 1;
5323 target->halt_issued = false;
5325 /* initialize trace information */
5326 target->trace_info = malloc(sizeof(struct trace));
5327 target->trace_info->num_trace_points = 0;
5328 target->trace_info->trace_points_size = 0;
5329 target->trace_info->trace_points = NULL;
5330 target->trace_info->trace_history_size = 0;
5331 target->trace_info->trace_history = NULL;
5332 target->trace_info->trace_history_pos = 0;
5333 target->trace_info->trace_history_overflowed = 0;
5335 target->dbgmsg = NULL;
5336 target->dbg_msg_enabled = 0;
5338 target->endianness = TARGET_ENDIAN_UNKNOWN;
5340 target->rtos = NULL;
5341 target->rtos_auto_detect = false;
5343 /* Do the rest as "configure" options */
5344 goi->isconfigure = 1;
5345 e = target_configure(goi, target);
5347 if (target->tap == NULL) {
5348 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
5349 e = JIM_ERR;
5352 if (e != JIM_OK) {
5353 free(target->type);
5354 free(target);
5355 return e;
5358 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5359 /* default endian to little if not specified */
5360 target->endianness = TARGET_LITTLE_ENDIAN;
5363 cp = Jim_GetString(new_cmd, NULL);
5364 target->cmd_name = strdup(cp);
5366 /* create the target specific commands */
5367 if (target->type->commands) {
5368 e = register_commands(cmd_ctx, NULL, target->type->commands);
5369 if (ERROR_OK != e)
5370 LOG_ERROR("unable to register '%s' commands", cp);
5372 if (target->type->target_create)
5373 (*(target->type->target_create))(target, goi->interp);
5375 /* append to end of list */
5377 struct target **tpp;
5378 tpp = &(all_targets);
5379 while (*tpp)
5380 tpp = &((*tpp)->next);
5381 *tpp = target;
5384 /* now - create the new target name command */
5385 const struct command_registration target_subcommands[] = {
5387 .chain = target_instance_command_handlers,
5390 .chain = target->type->commands,
5392 COMMAND_REGISTRATION_DONE
5394 const struct command_registration target_commands[] = {
5396 .name = cp,
5397 .mode = COMMAND_ANY,
5398 .help = "target command group",
5399 .usage = "",
5400 .chain = target_subcommands,
5402 COMMAND_REGISTRATION_DONE
5404 e = register_commands(cmd_ctx, NULL, target_commands);
5405 if (ERROR_OK != e)
5406 return JIM_ERR;
5408 struct command *c = command_find_in_context(cmd_ctx, cp);
5409 assert(c);
5410 command_set_handler_data(c, target);
5412 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5415 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5417 if (argc != 1) {
5418 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5419 return JIM_ERR;
5421 struct command_context *cmd_ctx = current_command_context(interp);
5422 assert(cmd_ctx != NULL);
5424 Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5425 return JIM_OK;
5428 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5430 if (argc != 1) {
5431 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5432 return JIM_ERR;
5434 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5435 for (unsigned x = 0; NULL != target_types[x]; x++) {
5436 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5437 Jim_NewStringObj(interp, target_types[x]->name, -1));
5439 return JIM_OK;
5442 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5444 if (argc != 1) {
5445 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5446 return JIM_ERR;
5448 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5449 struct target *target = all_targets;
5450 while (target) {
5451 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5452 Jim_NewStringObj(interp, target_name(target), -1));
5453 target = target->next;
5455 return JIM_OK;
5458 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5460 int i;
5461 const char *targetname;
5462 int retval, len;
5463 struct target *target = (struct target *) NULL;
5464 struct target_list *head, *curr, *new;
5465 curr = (struct target_list *) NULL;
5466 head = (struct target_list *) NULL;
5468 retval = 0;
5469 LOG_DEBUG("%d", argc);
5470 /* argv[1] = target to associate in smp
5471 * argv[2] = target to assoicate in smp
5472 * argv[3] ...
5475 for (i = 1; i < argc; i++) {
5477 targetname = Jim_GetString(argv[i], &len);
5478 target = get_target(targetname);
5479 LOG_DEBUG("%s ", targetname);
5480 if (target) {
5481 new = malloc(sizeof(struct target_list));
5482 new->target = target;
5483 new->next = (struct target_list *)NULL;
5484 if (head == (struct target_list *)NULL) {
5485 head = new;
5486 curr = head;
5487 } else {
5488 curr->next = new;
5489 curr = new;
5493 /* now parse the list of cpu and put the target in smp mode*/
5494 curr = head;
5496 while (curr != (struct target_list *)NULL) {
5497 target = curr->target;
5498 target->smp = 1;
5499 target->head = head;
5500 curr = curr->next;
5503 if (target && target->rtos)
5504 retval = rtos_smp_init(head->target);
5506 return retval;
5510 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5512 Jim_GetOptInfo goi;
5513 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5514 if (goi.argc < 3) {
5515 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5516 "<name> <target_type> [<target_options> ...]");
5517 return JIM_ERR;
5519 return target_create(&goi);
5522 static const struct command_registration target_subcommand_handlers[] = {
5524 .name = "init",
5525 .mode = COMMAND_CONFIG,
5526 .handler = handle_target_init_command,
5527 .help = "initialize targets",
5530 .name = "create",
5531 /* REVISIT this should be COMMAND_CONFIG ... */
5532 .mode = COMMAND_ANY,
5533 .jim_handler = jim_target_create,
5534 .usage = "name type '-chain-position' name [options ...]",
5535 .help = "Creates and selects a new target",
5538 .name = "current",
5539 .mode = COMMAND_ANY,
5540 .jim_handler = jim_target_current,
5541 .help = "Returns the currently selected target",
5544 .name = "types",
5545 .mode = COMMAND_ANY,
5546 .jim_handler = jim_target_types,
5547 .help = "Returns the available target types as "
5548 "a list of strings",
5551 .name = "names",
5552 .mode = COMMAND_ANY,
5553 .jim_handler = jim_target_names,
5554 .help = "Returns the names of all targets as a list of strings",
5557 .name = "smp",
5558 .mode = COMMAND_ANY,
5559 .jim_handler = jim_target_smp,
5560 .usage = "targetname1 targetname2 ...",
5561 .help = "gather several target in a smp list"
5564 COMMAND_REGISTRATION_DONE
5567 struct FastLoad {
5568 uint32_t address;
5569 uint8_t *data;
5570 int length;
5574 static int fastload_num;
5575 static struct FastLoad *fastload;
5577 static void free_fastload(void)
5579 if (fastload != NULL) {
5580 int i;
5581 for (i = 0; i < fastload_num; i++) {
5582 if (fastload[i].data)
5583 free(fastload[i].data);
5585 free(fastload);
5586 fastload = NULL;
5590 COMMAND_HANDLER(handle_fast_load_image_command)
5592 uint8_t *buffer;
5593 size_t buf_cnt;
5594 uint32_t image_size;
5595 uint32_t min_address = 0;
5596 uint32_t max_address = 0xffffffff;
5597 int i;
5599 struct image image;
5601 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5602 &image, &min_address, &max_address);
5603 if (ERROR_OK != retval)
5604 return retval;
5606 struct duration bench;
5607 duration_start(&bench);
5609 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5610 if (retval != ERROR_OK)
5611 return retval;
5613 image_size = 0x0;
5614 retval = ERROR_OK;
5615 fastload_num = image.num_sections;
5616 fastload = malloc(sizeof(struct FastLoad)*image.num_sections);
5617 if (fastload == NULL) {
5618 command_print(CMD_CTX, "out of memory");
5619 image_close(&image);
5620 return ERROR_FAIL;
5622 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5623 for (i = 0; i < image.num_sections; i++) {
5624 buffer = malloc(image.sections[i].size);
5625 if (buffer == NULL) {
5626 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5627 (int)(image.sections[i].size));
5628 retval = ERROR_FAIL;
5629 break;
5632 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5633 if (retval != ERROR_OK) {
5634 free(buffer);
5635 break;
5638 uint32_t offset = 0;
5639 uint32_t length = buf_cnt;
5641 /* DANGER!!! beware of unsigned comparision here!!! */
5643 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5644 (image.sections[i].base_address < max_address)) {
5645 if (image.sections[i].base_address < min_address) {
5646 /* clip addresses below */
5647 offset += min_address-image.sections[i].base_address;
5648 length -= offset;
5651 if (image.sections[i].base_address + buf_cnt > max_address)
5652 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5654 fastload[i].address = image.sections[i].base_address + offset;
5655 fastload[i].data = malloc(length);
5656 if (fastload[i].data == NULL) {
5657 free(buffer);
5658 command_print(CMD_CTX, "error allocating buffer for section (%" PRIu32 " bytes)",
5659 length);
5660 retval = ERROR_FAIL;
5661 break;
5663 memcpy(fastload[i].data, buffer + offset, length);
5664 fastload[i].length = length;
5666 image_size += length;
5667 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5668 (unsigned int)length,
5669 ((unsigned int)(image.sections[i].base_address + offset)));
5672 free(buffer);
5675 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5676 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5677 "in %fs (%0.3f KiB/s)", image_size,
5678 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5680 command_print(CMD_CTX,
5681 "WARNING: image has not been loaded to target!"
5682 "You can issue a 'fast_load' to finish loading.");
5685 image_close(&image);
5687 if (retval != ERROR_OK)
5688 free_fastload();
5690 return retval;
5693 COMMAND_HANDLER(handle_fast_load_command)
5695 if (CMD_ARGC > 0)
5696 return ERROR_COMMAND_SYNTAX_ERROR;
5697 if (fastload == NULL) {
5698 LOG_ERROR("No image in memory");
5699 return ERROR_FAIL;
5701 int i;
5702 int64_t ms = timeval_ms();
5703 int size = 0;
5704 int retval = ERROR_OK;
5705 for (i = 0; i < fastload_num; i++) {
5706 struct target *target = get_current_target(CMD_CTX);
5707 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5708 (unsigned int)(fastload[i].address),
5709 (unsigned int)(fastload[i].length));
5710 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5711 if (retval != ERROR_OK)
5712 break;
5713 size += fastload[i].length;
5715 if (retval == ERROR_OK) {
5716 int64_t after = timeval_ms();
5717 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5719 return retval;
5722 static const struct command_registration target_command_handlers[] = {
5724 .name = "targets",
5725 .handler = handle_targets_command,
5726 .mode = COMMAND_ANY,
5727 .help = "change current default target (one parameter) "
5728 "or prints table of all targets (no parameters)",
5729 .usage = "[target]",
5732 .name = "target",
5733 .mode = COMMAND_CONFIG,
5734 .help = "configure target",
5736 .chain = target_subcommand_handlers,
5738 COMMAND_REGISTRATION_DONE
5741 int target_register_commands(struct command_context *cmd_ctx)
5743 return register_commands(cmd_ctx, NULL, target_command_handlers);
5746 static bool target_reset_nag = true;
5748 bool get_target_reset_nag(void)
5750 return target_reset_nag;
5753 COMMAND_HANDLER(handle_target_reset_nag)
5755 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5756 &target_reset_nag, "Nag after each reset about options to improve "
5757 "performance");
5760 COMMAND_HANDLER(handle_ps_command)
5762 struct target *target = get_current_target(CMD_CTX);
5763 char *display;
5764 if (target->state != TARGET_HALTED) {
5765 LOG_INFO("target not halted !!");
5766 return ERROR_OK;
5769 if ((target->rtos) && (target->rtos->type)
5770 && (target->rtos->type->ps_command)) {
5771 display = target->rtos->type->ps_command(target);
5772 command_print(CMD_CTX, "%s", display);
5773 free(display);
5774 return ERROR_OK;
5775 } else {
5776 LOG_INFO("failed");
5777 return ERROR_TARGET_FAILURE;
5781 static void binprint(struct command_context *cmd_ctx, const char *text, const uint8_t *buf, int size)
5783 if (text != NULL)
5784 command_print_sameline(cmd_ctx, "%s", text);
5785 for (int i = 0; i < size; i++)
5786 command_print_sameline(cmd_ctx, " %02x", buf[i]);
5787 command_print(cmd_ctx, " ");
5790 COMMAND_HANDLER(handle_test_mem_access_command)
5792 struct target *target = get_current_target(CMD_CTX);
5793 uint32_t test_size;
5794 int retval = ERROR_OK;
5796 if (target->state != TARGET_HALTED) {
5797 LOG_INFO("target not halted !!");
5798 return ERROR_FAIL;
5801 if (CMD_ARGC != 1)
5802 return ERROR_COMMAND_SYNTAX_ERROR;
5804 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
5806 /* Test reads */
5807 size_t num_bytes = test_size + 4;
5809 struct working_area *wa = NULL;
5810 retval = target_alloc_working_area(target, num_bytes, &wa);
5811 if (retval != ERROR_OK) {
5812 LOG_ERROR("Not enough working area");
5813 return ERROR_FAIL;
5816 uint8_t *test_pattern = malloc(num_bytes);
5818 for (size_t i = 0; i < num_bytes; i++)
5819 test_pattern[i] = rand();
5821 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
5822 if (retval != ERROR_OK) {
5823 LOG_ERROR("Test pattern write failed");
5824 goto out;
5827 for (int host_offset = 0; host_offset <= 1; host_offset++) {
5828 for (int size = 1; size <= 4; size *= 2) {
5829 for (int offset = 0; offset < 4; offset++) {
5830 uint32_t count = test_size / size;
5831 size_t host_bufsiz = (count + 2) * size + host_offset;
5832 uint8_t *read_ref = malloc(host_bufsiz);
5833 uint8_t *read_buf = malloc(host_bufsiz);
5835 for (size_t i = 0; i < host_bufsiz; i++) {
5836 read_ref[i] = rand();
5837 read_buf[i] = read_ref[i];
5839 command_print_sameline(CMD_CTX,
5840 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
5841 size, offset, host_offset ? "un" : "");
5843 struct duration bench;
5844 duration_start(&bench);
5846 retval = target_read_memory(target, wa->address + offset, size, count,
5847 read_buf + size + host_offset);
5849 duration_measure(&bench);
5851 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
5852 command_print(CMD_CTX, "Unsupported alignment");
5853 goto next;
5854 } else if (retval != ERROR_OK) {
5855 command_print(CMD_CTX, "Memory read failed");
5856 goto next;
5859 /* replay on host */
5860 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
5862 /* check result */
5863 int result = memcmp(read_ref, read_buf, host_bufsiz);
5864 if (result == 0) {
5865 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
5866 duration_elapsed(&bench),
5867 duration_kbps(&bench, count * size));
5868 } else {
5869 command_print(CMD_CTX, "Compare failed");
5870 binprint(CMD_CTX, "ref:", read_ref, host_bufsiz);
5871 binprint(CMD_CTX, "buf:", read_buf, host_bufsiz);
5873 next:
5874 free(read_ref);
5875 free(read_buf);
5880 out:
5881 free(test_pattern);
5883 if (wa != NULL)
5884 target_free_working_area(target, wa);
5886 /* Test writes */
5887 num_bytes = test_size + 4 + 4 + 4;
5889 retval = target_alloc_working_area(target, num_bytes, &wa);
5890 if (retval != ERROR_OK) {
5891 LOG_ERROR("Not enough working area");
5892 return ERROR_FAIL;
5895 test_pattern = malloc(num_bytes);
5897 for (size_t i = 0; i < num_bytes; i++)
5898 test_pattern[i] = rand();
5900 for (int host_offset = 0; host_offset <= 1; host_offset++) {
5901 for (int size = 1; size <= 4; size *= 2) {
5902 for (int offset = 0; offset < 4; offset++) {
5903 uint32_t count = test_size / size;
5904 size_t host_bufsiz = count * size + host_offset;
5905 uint8_t *read_ref = malloc(num_bytes);
5906 uint8_t *read_buf = malloc(num_bytes);
5907 uint8_t *write_buf = malloc(host_bufsiz);
5909 for (size_t i = 0; i < host_bufsiz; i++)
5910 write_buf[i] = rand();
5911 command_print_sameline(CMD_CTX,
5912 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
5913 size, offset, host_offset ? "un" : "");
5915 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
5916 if (retval != ERROR_OK) {
5917 command_print(CMD_CTX, "Test pattern write failed");
5918 goto nextw;
5921 /* replay on host */
5922 memcpy(read_ref, test_pattern, num_bytes);
5923 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
5925 struct duration bench;
5926 duration_start(&bench);
5928 retval = target_write_memory(target, wa->address + size + offset, size, count,
5929 write_buf + host_offset);
5931 duration_measure(&bench);
5933 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
5934 command_print(CMD_CTX, "Unsupported alignment");
5935 goto nextw;
5936 } else if (retval != ERROR_OK) {
5937 command_print(CMD_CTX, "Memory write failed");
5938 goto nextw;
5941 /* read back */
5942 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
5943 if (retval != ERROR_OK) {
5944 command_print(CMD_CTX, "Test pattern write failed");
5945 goto nextw;
5948 /* check result */
5949 int result = memcmp(read_ref, read_buf, num_bytes);
5950 if (result == 0) {
5951 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
5952 duration_elapsed(&bench),
5953 duration_kbps(&bench, count * size));
5954 } else {
5955 command_print(CMD_CTX, "Compare failed");
5956 binprint(CMD_CTX, "ref:", read_ref, num_bytes);
5957 binprint(CMD_CTX, "buf:", read_buf, num_bytes);
5959 nextw:
5960 free(read_ref);
5961 free(read_buf);
5966 free(test_pattern);
5968 if (wa != NULL)
5969 target_free_working_area(target, wa);
5970 return retval;
5973 static const struct command_registration target_exec_command_handlers[] = {
5975 .name = "fast_load_image",
5976 .handler = handle_fast_load_image_command,
5977 .mode = COMMAND_ANY,
5978 .help = "Load image into server memory for later use by "
5979 "fast_load; primarily for profiling",
5980 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5981 "[min_address [max_length]]",
5984 .name = "fast_load",
5985 .handler = handle_fast_load_command,
5986 .mode = COMMAND_EXEC,
5987 .help = "loads active fast load image to current target "
5988 "- mainly for profiling purposes",
5989 .usage = "",
5992 .name = "profile",
5993 .handler = handle_profile_command,
5994 .mode = COMMAND_EXEC,
5995 .usage = "seconds filename [start end]",
5996 .help = "profiling samples the CPU PC",
5998 /** @todo don't register virt2phys() unless target supports it */
6000 .name = "virt2phys",
6001 .handler = handle_virt2phys_command,
6002 .mode = COMMAND_ANY,
6003 .help = "translate a virtual address into a physical address",
6004 .usage = "virtual_address",
6007 .name = "reg",
6008 .handler = handle_reg_command,
6009 .mode = COMMAND_EXEC,
6010 .help = "display (reread from target with \"force\") or set a register; "
6011 "with no arguments, displays all registers and their values",
6012 .usage = "[(register_number|register_name) [(value|'force')]]",
6015 .name = "poll",
6016 .handler = handle_poll_command,
6017 .mode = COMMAND_EXEC,
6018 .help = "poll target state; or reconfigure background polling",
6019 .usage = "['on'|'off']",
6022 .name = "wait_halt",
6023 .handler = handle_wait_halt_command,
6024 .mode = COMMAND_EXEC,
6025 .help = "wait up to the specified number of milliseconds "
6026 "(default 5000) for a previously requested halt",
6027 .usage = "[milliseconds]",
6030 .name = "halt",
6031 .handler = handle_halt_command,
6032 .mode = COMMAND_EXEC,
6033 .help = "request target to halt, then wait up to the specified"
6034 "number of milliseconds (default 5000) for it to complete",
6035 .usage = "[milliseconds]",
6038 .name = "resume",
6039 .handler = handle_resume_command,
6040 .mode = COMMAND_EXEC,
6041 .help = "resume target execution from current PC or address",
6042 .usage = "[address]",
6045 .name = "reset",
6046 .handler = handle_reset_command,
6047 .mode = COMMAND_EXEC,
6048 .usage = "[run|halt|init]",
6049 .help = "Reset all targets into the specified mode."
6050 "Default reset mode is run, if not given.",
6053 .name = "soft_reset_halt",
6054 .handler = handle_soft_reset_halt_command,
6055 .mode = COMMAND_EXEC,
6056 .usage = "",
6057 .help = "halt the target and do a soft reset",
6060 .name = "step",
6061 .handler = handle_step_command,
6062 .mode = COMMAND_EXEC,
6063 .help = "step one instruction from current PC or address",
6064 .usage = "[address]",
6067 .name = "mdw",
6068 .handler = handle_md_command,
6069 .mode = COMMAND_EXEC,
6070 .help = "display memory words",
6071 .usage = "['phys'] address [count]",
6074 .name = "mdh",
6075 .handler = handle_md_command,
6076 .mode = COMMAND_EXEC,
6077 .help = "display memory half-words",
6078 .usage = "['phys'] address [count]",
6081 .name = "mdb",
6082 .handler = handle_md_command,
6083 .mode = COMMAND_EXEC,
6084 .help = "display memory bytes",
6085 .usage = "['phys'] address [count]",
6088 .name = "mww",
6089 .handler = handle_mw_command,
6090 .mode = COMMAND_EXEC,
6091 .help = "write memory word",
6092 .usage = "['phys'] address value [count]",
6095 .name = "mwh",
6096 .handler = handle_mw_command,
6097 .mode = COMMAND_EXEC,
6098 .help = "write memory half-word",
6099 .usage = "['phys'] address value [count]",
6102 .name = "mwb",
6103 .handler = handle_mw_command,
6104 .mode = COMMAND_EXEC,
6105 .help = "write memory byte",
6106 .usage = "['phys'] address value [count]",
6109 .name = "bp",
6110 .handler = handle_bp_command,
6111 .mode = COMMAND_EXEC,
6112 .help = "list or set hardware or software breakpoint",
6113 .usage = "<address> [<asid>]<length> ['hw'|'hw_ctx']",
6116 .name = "rbp",
6117 .handler = handle_rbp_command,
6118 .mode = COMMAND_EXEC,
6119 .help = "remove breakpoint",
6120 .usage = "address",
6123 .name = "wp",
6124 .handler = handle_wp_command,
6125 .mode = COMMAND_EXEC,
6126 .help = "list (no params) or create watchpoints",
6127 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
6130 .name = "rwp",
6131 .handler = handle_rwp_command,
6132 .mode = COMMAND_EXEC,
6133 .help = "remove watchpoint",
6134 .usage = "address",
6137 .name = "load_image",
6138 .handler = handle_load_image_command,
6139 .mode = COMMAND_EXEC,
6140 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6141 "[min_address] [max_length]",
6144 .name = "dump_image",
6145 .handler = handle_dump_image_command,
6146 .mode = COMMAND_EXEC,
6147 .usage = "filename address size",
6150 .name = "verify_image",
6151 .handler = handle_verify_image_command,
6152 .mode = COMMAND_EXEC,
6153 .usage = "filename [offset [type]]",
6156 .name = "test_image",
6157 .handler = handle_test_image_command,
6158 .mode = COMMAND_EXEC,
6159 .usage = "filename [offset [type]]",
6162 .name = "mem2array",
6163 .mode = COMMAND_EXEC,
6164 .jim_handler = jim_mem2array,
6165 .help = "read 8/16/32 bit memory and return as a TCL array "
6166 "for script processing",
6167 .usage = "arrayname bitwidth address count",
6170 .name = "array2mem",
6171 .mode = COMMAND_EXEC,
6172 .jim_handler = jim_array2mem,
6173 .help = "convert a TCL array to memory locations "
6174 "and write the 8/16/32 bit values",
6175 .usage = "arrayname bitwidth address count",
6178 .name = "reset_nag",
6179 .handler = handle_target_reset_nag,
6180 .mode = COMMAND_ANY,
6181 .help = "Nag after each reset about options that could have been "
6182 "enabled to improve performance. ",
6183 .usage = "['enable'|'disable']",
6186 .name = "ps",
6187 .handler = handle_ps_command,
6188 .mode = COMMAND_EXEC,
6189 .help = "list all tasks ",
6190 .usage = " ",
6193 .name = "test_mem_access",
6194 .handler = handle_test_mem_access_command,
6195 .mode = COMMAND_EXEC,
6196 .help = "Test the target's memory access functions",
6197 .usage = "size",
6200 COMMAND_REGISTRATION_DONE
6202 static int target_register_user_commands(struct command_context *cmd_ctx)
6204 int retval = ERROR_OK;
6205 retval = target_request_register_commands(cmd_ctx);
6206 if (retval != ERROR_OK)
6207 return retval;
6209 retval = trace_register_commands(cmd_ctx);
6210 if (retval != ERROR_OK)
6211 return retval;
6214 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);