target: add async algorithm timeout
[openocd/cmsis-dap.git] / src / target / target.c
blob6d3a99decd8adc9031124c8506a9411601ad7e86
1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
4 * *
5 * Copyright (C) 2007-2010 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
7 * *
8 * Copyright (C) 2008, Duane Ellis *
9 * openocd@duaneeellis.com *
10 * *
11 * Copyright (C) 2008 by Spencer Oliver *
12 * spen@spen-soft.co.uk *
13 * *
14 * Copyright (C) 2008 by Rick Altherr *
15 * kc8apf@kc8apf.net> *
16 * *
17 * Copyright (C) 2011 by Broadcom Corporation *
18 * Evan Hunter - ehunter@broadcom.com *
19 * *
20 * Copyright (C) ST-Ericsson SA 2011 *
21 * michel.jaouen@stericsson.com : smp minimum support *
22 * *
23 * Copyright (C) 2011 Andreas Fritiofson *
24 * andreas.fritiofson@gmail.com *
25 * *
26 * This program is free software; you can redistribute it and/or modify *
27 * it under the terms of the GNU General Public License as published by *
28 * the Free Software Foundation; either version 2 of the License, or *
29 * (at your option) any later version. *
30 * *
31 * This program is distributed in the hope that it will be useful, *
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
34 * GNU General Public License for more details. *
35 * *
36 * You should have received a copy of the GNU General Public License *
37 * along with this program; if not, write to the *
38 * Free Software Foundation, Inc., *
39 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
40 ***************************************************************************/
42 #ifdef HAVE_CONFIG_H
43 #include "config.h"
44 #endif
46 #include <helper/time_support.h>
47 #include <jtag/jtag.h>
48 #include <flash/nor/core.h>
50 #include "target.h"
51 #include "target_type.h"
52 #include "target_request.h"
53 #include "breakpoints.h"
54 #include "register.h"
55 #include "trace.h"
56 #include "image.h"
57 #include "rtos/rtos.h"
59 static int target_read_buffer_default(struct target *target, uint32_t address,
60 uint32_t size, uint8_t *buffer);
61 static int target_write_buffer_default(struct target *target, uint32_t address,
62 uint32_t size, const uint8_t *buffer);
63 static int target_array2mem(Jim_Interp *interp, struct target *target,
64 int argc, Jim_Obj * const *argv);
65 static int target_mem2array(Jim_Interp *interp, struct target *target,
66 int argc, Jim_Obj * const *argv);
67 static int target_register_user_commands(struct command_context *cmd_ctx);
69 /* targets */
70 extern struct target_type arm7tdmi_target;
71 extern struct target_type arm720t_target;
72 extern struct target_type arm9tdmi_target;
73 extern struct target_type arm920t_target;
74 extern struct target_type arm966e_target;
75 extern struct target_type arm946e_target;
76 extern struct target_type arm926ejs_target;
77 extern struct target_type fa526_target;
78 extern struct target_type feroceon_target;
79 extern struct target_type dragonite_target;
80 extern struct target_type xscale_target;
81 extern struct target_type cortexm3_target;
82 extern struct target_type cortexa8_target;
83 extern struct target_type arm11_target;
84 extern struct target_type mips_m4k_target;
85 extern struct target_type avr_target;
86 extern struct target_type dsp563xx_target;
87 extern struct target_type dsp5680xx_target;
88 extern struct target_type testee_target;
89 extern struct target_type avr32_ap7k_target;
90 extern struct target_type stm32_stlink_target;
92 static struct target_type *target_types[] = {
93 &arm7tdmi_target,
94 &arm9tdmi_target,
95 &arm920t_target,
96 &arm720t_target,
97 &arm966e_target,
98 &arm946e_target,
99 &arm926ejs_target,
100 &fa526_target,
101 &feroceon_target,
102 &dragonite_target,
103 &xscale_target,
104 &cortexm3_target,
105 &cortexa8_target,
106 &arm11_target,
107 &mips_m4k_target,
108 &avr_target,
109 &dsp563xx_target,
110 &dsp5680xx_target,
111 &testee_target,
112 &avr32_ap7k_target,
113 &stm32_stlink_target,
114 NULL,
117 struct target *all_targets;
118 static struct target_event_callback *target_event_callbacks;
119 static struct target_timer_callback *target_timer_callbacks;
120 static const int polling_interval = 100;
122 static const Jim_Nvp nvp_assert[] = {
123 { .name = "assert", NVP_ASSERT },
124 { .name = "deassert", NVP_DEASSERT },
125 { .name = "T", NVP_ASSERT },
126 { .name = "F", NVP_DEASSERT },
127 { .name = "t", NVP_ASSERT },
128 { .name = "f", NVP_DEASSERT },
129 { .name = NULL, .value = -1 }
132 static const Jim_Nvp nvp_error_target[] = {
133 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
134 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
135 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
136 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
137 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
138 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
139 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
140 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
141 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
142 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
143 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
144 { .value = -1, .name = NULL }
147 static const char *target_strerror_safe(int err)
149 const Jim_Nvp *n;
151 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
152 if (n->name == NULL)
153 return "unknown";
154 else
155 return n->name;
158 static const Jim_Nvp nvp_target_event[] = {
160 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
161 { .value = TARGET_EVENT_HALTED, .name = "halted" },
162 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
163 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
164 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
166 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
167 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
169 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
170 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
171 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
172 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
173 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
174 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
175 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
176 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
177 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
178 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
179 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
180 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
182 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
183 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
185 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
186 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
188 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
189 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
191 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
192 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
194 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
195 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
197 { .name = NULL, .value = -1 }
200 static const Jim_Nvp nvp_target_state[] = {
201 { .name = "unknown", .value = TARGET_UNKNOWN },
202 { .name = "running", .value = TARGET_RUNNING },
203 { .name = "halted", .value = TARGET_HALTED },
204 { .name = "reset", .value = TARGET_RESET },
205 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
206 { .name = NULL, .value = -1 },
209 static const Jim_Nvp nvp_target_debug_reason[] = {
210 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
211 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
212 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
213 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
214 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
215 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
216 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
217 { .name = NULL, .value = -1 },
220 static const Jim_Nvp nvp_target_endian[] = {
221 { .name = "big", .value = TARGET_BIG_ENDIAN },
222 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
223 { .name = "be", .value = TARGET_BIG_ENDIAN },
224 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
225 { .name = NULL, .value = -1 },
228 static const Jim_Nvp nvp_reset_modes[] = {
229 { .name = "unknown", .value = RESET_UNKNOWN },
230 { .name = "run" , .value = RESET_RUN },
231 { .name = "halt" , .value = RESET_HALT },
232 { .name = "init" , .value = RESET_INIT },
233 { .name = NULL , .value = -1 },
236 const char *debug_reason_name(struct target *t)
238 const char *cp;
240 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
241 t->debug_reason)->name;
242 if (!cp) {
243 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
244 cp = "(*BUG*unknown*BUG*)";
246 return cp;
249 const char *target_state_name(struct target *t)
251 const char *cp;
252 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
253 if (!cp) {
254 LOG_ERROR("Invalid target state: %d", (int)(t->state));
255 cp = "(*BUG*unknown*BUG*)";
257 return cp;
260 /* determine the number of the new target */
261 static int new_target_number(void)
263 struct target *t;
264 int x;
266 /* number is 0 based */
267 x = -1;
268 t = all_targets;
269 while (t) {
270 if (x < t->target_number)
271 x = t->target_number;
272 t = t->next;
274 return x + 1;
277 /* read a uint32_t from a buffer in target memory endianness */
278 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
280 if (target->endianness == TARGET_LITTLE_ENDIAN)
281 return le_to_h_u32(buffer);
282 else
283 return be_to_h_u32(buffer);
286 /* read a uint24_t from a buffer in target memory endianness */
287 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
289 if (target->endianness == TARGET_LITTLE_ENDIAN)
290 return le_to_h_u24(buffer);
291 else
292 return be_to_h_u24(buffer);
295 /* read a uint16_t from a buffer in target memory endianness */
296 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
298 if (target->endianness == TARGET_LITTLE_ENDIAN)
299 return le_to_h_u16(buffer);
300 else
301 return be_to_h_u16(buffer);
304 /* read a uint8_t from a buffer in target memory endianness */
305 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
307 return *buffer & 0x0ff;
310 /* write a uint32_t to a buffer in target memory endianness */
311 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
313 if (target->endianness == TARGET_LITTLE_ENDIAN)
314 h_u32_to_le(buffer, value);
315 else
316 h_u32_to_be(buffer, value);
319 /* write a uint24_t to a buffer in target memory endianness */
320 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
322 if (target->endianness == TARGET_LITTLE_ENDIAN)
323 h_u24_to_le(buffer, value);
324 else
325 h_u24_to_be(buffer, value);
328 /* write a uint16_t to a buffer in target memory endianness */
329 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
331 if (target->endianness == TARGET_LITTLE_ENDIAN)
332 h_u16_to_le(buffer, value);
333 else
334 h_u16_to_be(buffer, value);
337 /* write a uint8_t to a buffer in target memory endianness */
338 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
340 *buffer = value;
343 /* write a uint32_t array to a buffer in target memory endianness */
344 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
346 uint32_t i;
347 for (i = 0; i < count; i++)
348 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
351 /* write a uint16_t array to a buffer in target memory endianness */
352 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
354 uint32_t i;
355 for (i = 0; i < count; i++)
356 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
359 /* write a uint32_t array to a buffer in target memory endianness */
360 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, uint32_t *srcbuf)
362 uint32_t i;
363 for (i = 0; i < count; i++)
364 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
367 /* write a uint16_t array to a buffer in target memory endianness */
368 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, uint16_t *srcbuf)
370 uint32_t i;
371 for (i = 0; i < count; i++)
372 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
375 /* return a pointer to a configured target; id is name or number */
376 struct target *get_target(const char *id)
378 struct target *target;
380 /* try as tcltarget name */
381 for (target = all_targets; target; target = target->next) {
382 if (target->cmd_name == NULL)
383 continue;
384 if (strcmp(id, target->cmd_name) == 0)
385 return target;
388 /* It's OK to remove this fallback sometime after August 2010 or so */
390 /* no match, try as number */
391 unsigned num;
392 if (parse_uint(id, &num) != ERROR_OK)
393 return NULL;
395 for (target = all_targets; target; target = target->next) {
396 if (target->target_number == (int)num) {
397 LOG_WARNING("use '%s' as target identifier, not '%u'",
398 target->cmd_name, num);
399 return target;
403 return NULL;
406 /* returns a pointer to the n-th configured target */
407 static struct target *get_target_by_num(int num)
409 struct target *target = all_targets;
411 while (target) {
412 if (target->target_number == num)
413 return target;
414 target = target->next;
417 return NULL;
420 struct target *get_current_target(struct command_context *cmd_ctx)
422 struct target *target = get_target_by_num(cmd_ctx->current_target);
424 if (target == NULL) {
425 LOG_ERROR("BUG: current_target out of bounds");
426 exit(-1);
429 return target;
432 int target_poll(struct target *target)
434 int retval;
436 /* We can't poll until after examine */
437 if (!target_was_examined(target)) {
438 /* Fail silently lest we pollute the log */
439 return ERROR_FAIL;
442 retval = target->type->poll(target);
443 if (retval != ERROR_OK)
444 return retval;
446 if (target->halt_issued) {
447 if (target->state == TARGET_HALTED)
448 target->halt_issued = false;
449 else {
450 long long t = timeval_ms() - target->halt_issued_time;
451 if (t > 1000) {
452 target->halt_issued = false;
453 LOG_INFO("Halt timed out, wake up GDB.");
454 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
459 return ERROR_OK;
462 int target_halt(struct target *target)
464 int retval;
465 /* We can't poll until after examine */
466 if (!target_was_examined(target)) {
467 LOG_ERROR("Target not examined yet");
468 return ERROR_FAIL;
471 retval = target->type->halt(target);
472 if (retval != ERROR_OK)
473 return retval;
475 target->halt_issued = true;
476 target->halt_issued_time = timeval_ms();
478 return ERROR_OK;
482 * Make the target (re)start executing using its saved execution
483 * context (possibly with some modifications).
485 * @param target Which target should start executing.
486 * @param current True to use the target's saved program counter instead
487 * of the address parameter
488 * @param address Optionally used as the program counter.
489 * @param handle_breakpoints True iff breakpoints at the resumption PC
490 * should be skipped. (For example, maybe execution was stopped by
491 * such a breakpoint, in which case it would be counterprodutive to
492 * let it re-trigger.
493 * @param debug_execution False if all working areas allocated by OpenOCD
494 * should be released and/or restored to their original contents.
495 * (This would for example be true to run some downloaded "helper"
496 * algorithm code, which resides in one such working buffer and uses
497 * another for data storage.)
499 * @todo Resolve the ambiguity about what the "debug_execution" flag
500 * signifies. For example, Target implementations don't agree on how
501 * it relates to invalidation of the register cache, or to whether
502 * breakpoints and watchpoints should be enabled. (It would seem wrong
503 * to enable breakpoints when running downloaded "helper" algorithms
504 * (debug_execution true), since the breakpoints would be set to match
505 * target firmware being debugged, not the helper algorithm.... and
506 * enabling them could cause such helpers to malfunction (for example,
507 * by overwriting data with a breakpoint instruction. On the other
508 * hand the infrastructure for running such helpers might use this
509 * procedure but rely on hardware breakpoint to detect termination.)
511 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
513 int retval;
515 /* We can't poll until after examine */
516 if (!target_was_examined(target)) {
517 LOG_ERROR("Target not examined yet");
518 return ERROR_FAIL;
521 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
523 /* note that resume *must* be asynchronous. The CPU can halt before
524 * we poll. The CPU can even halt at the current PC as a result of
525 * a software breakpoint being inserted by (a bug?) the application.
527 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
528 if (retval != ERROR_OK)
529 return retval;
531 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
533 return retval;
536 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
538 char buf[100];
539 int retval;
540 Jim_Nvp *n;
541 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
542 if (n->name == NULL) {
543 LOG_ERROR("invalid reset mode");
544 return ERROR_FAIL;
547 /* disable polling during reset to make reset event scripts
548 * more predictable, i.e. dr/irscan & pathmove in events will
549 * not have JTAG operations injected into the middle of a sequence.
551 bool save_poll = jtag_poll_get_enabled();
553 jtag_poll_set_enabled(false);
555 sprintf(buf, "ocd_process_reset %s", n->name);
556 retval = Jim_Eval(cmd_ctx->interp, buf);
558 jtag_poll_set_enabled(save_poll);
560 if (retval != JIM_OK) {
561 Jim_MakeErrorMessage(cmd_ctx->interp);
562 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
563 return ERROR_FAIL;
566 /* We want any events to be processed before the prompt */
567 retval = target_call_timer_callbacks_now();
569 struct target *target;
570 for (target = all_targets; target; target = target->next)
571 target->type->check_reset(target);
573 return retval;
576 static int identity_virt2phys(struct target *target,
577 uint32_t virtual, uint32_t *physical)
579 *physical = virtual;
580 return ERROR_OK;
583 static int no_mmu(struct target *target, int *enabled)
585 *enabled = 0;
586 return ERROR_OK;
589 static int default_examine(struct target *target)
591 target_set_examined(target);
592 return ERROR_OK;
595 /* no check by default */
596 static int default_check_reset(struct target *target)
598 return ERROR_OK;
601 int target_examine_one(struct target *target)
603 return target->type->examine(target);
606 static int jtag_enable_callback(enum jtag_event event, void *priv)
608 struct target *target = priv;
610 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
611 return ERROR_OK;
613 jtag_unregister_event_callback(jtag_enable_callback, target);
615 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
617 int retval = target_examine_one(target);
618 if (retval != ERROR_OK)
619 return retval;
621 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
623 return retval;
626 /* Targets that correctly implement init + examine, i.e.
627 * no communication with target during init:
629 * XScale
631 int target_examine(void)
633 int retval = ERROR_OK;
634 struct target *target;
636 for (target = all_targets; target; target = target->next) {
637 /* defer examination, but don't skip it */
638 if (!target->tap->enabled) {
639 jtag_register_event_callback(jtag_enable_callback,
640 target);
641 continue;
644 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
646 retval = target_examine_one(target);
647 if (retval != ERROR_OK)
648 return retval;
650 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
652 return retval;
655 const char *target_type_name(struct target *target)
657 return target->type->name;
660 static int target_write_memory_imp(struct target *target, uint32_t address,
661 uint32_t size, uint32_t count, const uint8_t *buffer)
663 if (!target_was_examined(target)) {
664 LOG_ERROR("Target not examined yet");
665 return ERROR_FAIL;
667 return target->type->write_memory_imp(target, address, size, count, buffer);
670 static int target_read_memory_imp(struct target *target, uint32_t address,
671 uint32_t size, uint32_t count, uint8_t *buffer)
673 if (!target_was_examined(target)) {
674 LOG_ERROR("Target not examined yet");
675 return ERROR_FAIL;
677 return target->type->read_memory_imp(target, address, size, count, buffer);
680 static int target_soft_reset_halt_imp(struct target *target)
682 if (!target_was_examined(target)) {
683 LOG_ERROR("Target not examined yet");
684 return ERROR_FAIL;
686 if (!target->type->soft_reset_halt_imp) {
687 LOG_ERROR("Target %s does not support soft_reset_halt",
688 target_name(target));
689 return ERROR_FAIL;
691 return target->type->soft_reset_halt_imp(target);
695 * Downloads a target-specific native code algorithm to the target,
696 * and executes it. * Note that some targets may need to set up, enable,
697 * and tear down a breakpoint (hard or * soft) to detect algorithm
698 * termination, while others may support lower overhead schemes where
699 * soft breakpoints embedded in the algorithm automatically terminate the
700 * algorithm.
702 * @param target used to run the algorithm
703 * @param arch_info target-specific description of the algorithm.
705 int target_run_algorithm(struct target *target,
706 int num_mem_params, struct mem_param *mem_params,
707 int num_reg_params, struct reg_param *reg_param,
708 uint32_t entry_point, uint32_t exit_point,
709 int timeout_ms, void *arch_info)
711 int retval = ERROR_FAIL;
713 if (!target_was_examined(target)) {
714 LOG_ERROR("Target not examined yet");
715 goto done;
717 if (!target->type->run_algorithm) {
718 LOG_ERROR("Target type '%s' does not support %s",
719 target_type_name(target), __func__);
720 goto done;
723 target->running_alg = true;
724 retval = target->type->run_algorithm(target,
725 num_mem_params, mem_params,
726 num_reg_params, reg_param,
727 entry_point, exit_point, timeout_ms, arch_info);
728 target->running_alg = false;
730 done:
731 return retval;
735 * Downloads a target-specific native code algorithm to the target,
736 * executes and leaves it running.
738 * @param target used to run the algorithm
739 * @param arch_info target-specific description of the algorithm.
741 int target_start_algorithm(struct target *target,
742 int num_mem_params, struct mem_param *mem_params,
743 int num_reg_params, struct reg_param *reg_params,
744 uint32_t entry_point, uint32_t exit_point,
745 void *arch_info)
747 int retval = ERROR_FAIL;
749 if (!target_was_examined(target)) {
750 LOG_ERROR("Target not examined yet");
751 goto done;
753 if (!target->type->start_algorithm) {
754 LOG_ERROR("Target type '%s' does not support %s",
755 target_type_name(target), __func__);
756 goto done;
758 if (target->running_alg) {
759 LOG_ERROR("Target is already running an algorithm");
760 goto done;
763 target->running_alg = true;
764 retval = target->type->start_algorithm(target,
765 num_mem_params, mem_params,
766 num_reg_params, reg_params,
767 entry_point, exit_point, arch_info);
769 done:
770 return retval;
774 * Waits for an algorithm started with target_start_algorithm() to complete.
776 * @param target used to run the algorithm
777 * @param arch_info target-specific description of the algorithm.
779 int target_wait_algorithm(struct target *target,
780 int num_mem_params, struct mem_param *mem_params,
781 int num_reg_params, struct reg_param *reg_params,
782 uint32_t exit_point, int timeout_ms,
783 void *arch_info)
785 int retval = ERROR_FAIL;
787 if (!target->type->wait_algorithm) {
788 LOG_ERROR("Target type '%s' does not support %s",
789 target_type_name(target), __func__);
790 goto done;
792 if (!target->running_alg) {
793 LOG_ERROR("Target is not running an algorithm");
794 goto done;
797 retval = target->type->wait_algorithm(target,
798 num_mem_params, mem_params,
799 num_reg_params, reg_params,
800 exit_point, timeout_ms, arch_info);
801 if (retval != ERROR_TARGET_TIMEOUT)
802 target->running_alg = false;
804 done:
805 return retval;
809 * Executes a target-specific native code algorithm in the target.
810 * It differs from target_run_algorithm in that the algorithm is asynchronous.
811 * Because of this it requires an compliant algorithm:
812 * see contrib/loaders/flash/stm32f1x.S for example.
814 * @param target used to run the algorithm
817 int target_run_flash_async_algorithm(struct target *target,
818 uint8_t *buffer, uint32_t count, int block_size,
819 int num_mem_params, struct mem_param *mem_params,
820 int num_reg_params, struct reg_param *reg_params,
821 uint32_t buffer_start, uint32_t buffer_size,
822 uint32_t entry_point, uint32_t exit_point, void *arch_info)
824 int retval;
825 int timeout = 0;
827 /* Set up working area. First word is write pointer, second word is read pointer,
828 * rest is fifo data area. */
829 uint32_t wp_addr = buffer_start;
830 uint32_t rp_addr = buffer_start + 4;
831 uint32_t fifo_start_addr = buffer_start + 8;
832 uint32_t fifo_end_addr = buffer_start + buffer_size;
834 uint32_t wp = fifo_start_addr;
835 uint32_t rp = fifo_start_addr;
837 /* validate block_size is 2^n */
838 assert(!block_size || !(block_size & (block_size - 1)));
840 retval = target_write_u32(target, wp_addr, wp);
841 if (retval != ERROR_OK)
842 return retval;
843 retval = target_write_u32(target, rp_addr, rp);
844 if (retval != ERROR_OK)
845 return retval;
847 /* Start up algorithm on target and let it idle while writing the first chunk */
848 retval = target_start_algorithm(target, num_mem_params, mem_params,
849 num_reg_params, reg_params,
850 entry_point,
851 exit_point,
852 arch_info);
854 if (retval != ERROR_OK) {
855 LOG_ERROR("error starting target flash write algorithm");
856 return retval;
859 while (count > 0) {
861 retval = target_read_u32(target, rp_addr, &rp);
862 if (retval != ERROR_OK) {
863 LOG_ERROR("failed to get read pointer");
864 break;
867 LOG_DEBUG("count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32, count, wp, rp);
869 if (rp == 0) {
870 LOG_ERROR("flash write algorithm aborted by target");
871 retval = ERROR_FLASH_OPERATION_FAILED;
872 break;
875 if ((rp & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
876 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
877 break;
880 /* Count the number of bytes available in the fifo without
881 * crossing the wrap around. Make sure to not fill it completely,
882 * because that would make wp == rp and that's the empty condition. */
883 uint32_t thisrun_bytes;
884 if (rp > wp)
885 thisrun_bytes = rp - wp - block_size;
886 else if (rp > fifo_start_addr)
887 thisrun_bytes = fifo_end_addr - wp;
888 else
889 thisrun_bytes = fifo_end_addr - wp - block_size;
891 if (thisrun_bytes == 0) {
892 /* Throttle polling a bit if transfer is (much) faster than flash
893 * programming. The exact delay shouldn't matter as long as it's
894 * less than buffer size / flash speed. This is very unlikely to
895 * run when using high latency connections such as USB. */
896 alive_sleep(10);
898 /* to stop an infinite loop on some targets check and increment a timeout
899 * this issue was observed on a stellaris using the new ICDI interface */
900 if (timeout++ >= 500) {
901 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
902 return ERROR_FLASH_OPERATION_FAILED;
904 continue;
907 /* reset our timeout */
908 timeout = 0;
910 /* Limit to the amount of data we actually want to write */
911 if (thisrun_bytes > count * block_size)
912 thisrun_bytes = count * block_size;
914 /* Write data to fifo */
915 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
916 if (retval != ERROR_OK)
917 break;
919 /* Update counters and wrap write pointer */
920 buffer += thisrun_bytes;
921 count -= thisrun_bytes / block_size;
922 wp += thisrun_bytes;
923 if (wp >= fifo_end_addr)
924 wp = fifo_start_addr;
926 /* Store updated write pointer to target */
927 retval = target_write_u32(target, wp_addr, wp);
928 if (retval != ERROR_OK)
929 break;
932 if (retval != ERROR_OK) {
933 /* abort flash write algorithm on target */
934 target_write_u32(target, wp_addr, 0);
937 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
938 num_reg_params, reg_params,
939 exit_point,
940 10000,
941 arch_info);
943 if (retval2 != ERROR_OK) {
944 LOG_ERROR("error waiting for target flash write algorithm");
945 retval = retval2;
948 return retval;
951 int target_read_memory(struct target *target,
952 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
954 return target->type->read_memory(target, address, size, count, buffer);
957 static int target_read_phys_memory(struct target *target,
958 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
960 return target->type->read_phys_memory(target, address, size, count, buffer);
963 int target_write_memory(struct target *target,
964 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
966 return target->type->write_memory(target, address, size, count, buffer);
969 static int target_write_phys_memory(struct target *target,
970 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
972 return target->type->write_phys_memory(target, address, size, count, buffer);
975 int target_bulk_write_memory(struct target *target,
976 uint32_t address, uint32_t count, const uint8_t *buffer)
978 return target->type->bulk_write_memory(target, address, count, buffer);
981 int target_add_breakpoint(struct target *target,
982 struct breakpoint *breakpoint)
984 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
985 LOG_WARNING("target %s is not halted", target->cmd_name);
986 return ERROR_TARGET_NOT_HALTED;
988 return target->type->add_breakpoint(target, breakpoint);
991 int target_add_context_breakpoint(struct target *target,
992 struct breakpoint *breakpoint)
994 if (target->state != TARGET_HALTED) {
995 LOG_WARNING("target %s is not halted", target->cmd_name);
996 return ERROR_TARGET_NOT_HALTED;
998 return target->type->add_context_breakpoint(target, breakpoint);
1001 int target_add_hybrid_breakpoint(struct target *target,
1002 struct breakpoint *breakpoint)
1004 if (target->state != TARGET_HALTED) {
1005 LOG_WARNING("target %s is not halted", target->cmd_name);
1006 return ERROR_TARGET_NOT_HALTED;
1008 return target->type->add_hybrid_breakpoint(target, breakpoint);
1011 int target_remove_breakpoint(struct target *target,
1012 struct breakpoint *breakpoint)
1014 return target->type->remove_breakpoint(target, breakpoint);
1017 int target_add_watchpoint(struct target *target,
1018 struct watchpoint *watchpoint)
1020 if (target->state != TARGET_HALTED) {
1021 LOG_WARNING("target %s is not halted", target->cmd_name);
1022 return ERROR_TARGET_NOT_HALTED;
1024 return target->type->add_watchpoint(target, watchpoint);
1026 int target_remove_watchpoint(struct target *target,
1027 struct watchpoint *watchpoint)
1029 return target->type->remove_watchpoint(target, watchpoint);
1032 int target_get_gdb_reg_list(struct target *target,
1033 struct reg **reg_list[], int *reg_list_size)
1035 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
1037 int target_step(struct target *target,
1038 int current, uint32_t address, int handle_breakpoints)
1040 return target->type->step(target, current, address, handle_breakpoints);
1044 * Reset the @c examined flag for the given target.
1045 * Pure paranoia -- targets are zeroed on allocation.
1047 static void target_reset_examined(struct target *target)
1049 target->examined = false;
1052 static int err_read_phys_memory(struct target *target, uint32_t address,
1053 uint32_t size, uint32_t count, uint8_t *buffer)
1055 LOG_ERROR("Not implemented: %s", __func__);
1056 return ERROR_FAIL;
1059 static int err_write_phys_memory(struct target *target, uint32_t address,
1060 uint32_t size, uint32_t count, const uint8_t *buffer)
1062 LOG_ERROR("Not implemented: %s", __func__);
1063 return ERROR_FAIL;
1066 static int handle_target(void *priv);
1068 static int target_init_one(struct command_context *cmd_ctx,
1069 struct target *target)
1071 target_reset_examined(target);
1073 struct target_type *type = target->type;
1074 if (type->examine == NULL)
1075 type->examine = default_examine;
1077 if (type->check_reset == NULL)
1078 type->check_reset = default_check_reset;
1080 assert(type->init_target != NULL);
1082 int retval = type->init_target(cmd_ctx, target);
1083 if (ERROR_OK != retval) {
1084 LOG_ERROR("target '%s' init failed", target_name(target));
1085 return retval;
1089 * @todo get rid of those *memory_imp() methods, now that all
1090 * callers are using target_*_memory() accessors ... and make
1091 * sure the "physical" paths handle the same issues.
1093 /* a non-invasive way(in terms of patches) to add some code that
1094 * runs before the type->write/read_memory implementation
1096 type->write_memory_imp = target->type->write_memory;
1097 type->write_memory = target_write_memory_imp;
1099 type->read_memory_imp = target->type->read_memory;
1100 type->read_memory = target_read_memory_imp;
1102 type->soft_reset_halt_imp = target->type->soft_reset_halt;
1103 type->soft_reset_halt = target_soft_reset_halt_imp;
1105 /* Sanity-check MMU support ... stub in what we must, to help
1106 * implement it in stages, but warn if we need to do so.
1108 if (type->mmu) {
1109 if (type->write_phys_memory == NULL) {
1110 LOG_ERROR("type '%s' is missing write_phys_memory",
1111 type->name);
1112 type->write_phys_memory = err_write_phys_memory;
1114 if (type->read_phys_memory == NULL) {
1115 LOG_ERROR("type '%s' is missing read_phys_memory",
1116 type->name);
1117 type->read_phys_memory = err_read_phys_memory;
1119 if (type->virt2phys == NULL) {
1120 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1121 type->virt2phys = identity_virt2phys;
1123 } else {
1124 /* Make sure no-MMU targets all behave the same: make no
1125 * distinction between physical and virtual addresses, and
1126 * ensure that virt2phys() is always an identity mapping.
1128 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1129 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1131 type->mmu = no_mmu;
1132 type->write_phys_memory = type->write_memory;
1133 type->read_phys_memory = type->read_memory;
1134 type->virt2phys = identity_virt2phys;
1137 if (target->type->read_buffer == NULL)
1138 target->type->read_buffer = target_read_buffer_default;
1140 if (target->type->write_buffer == NULL)
1141 target->type->write_buffer = target_write_buffer_default;
1143 return ERROR_OK;
1146 static int target_init(struct command_context *cmd_ctx)
1148 struct target *target;
1149 int retval;
1151 for (target = all_targets; target; target = target->next) {
1152 retval = target_init_one(cmd_ctx, target);
1153 if (ERROR_OK != retval)
1154 return retval;
1157 if (!all_targets)
1158 return ERROR_OK;
1160 retval = target_register_user_commands(cmd_ctx);
1161 if (ERROR_OK != retval)
1162 return retval;
1164 retval = target_register_timer_callback(&handle_target,
1165 polling_interval, 1, cmd_ctx->interp);
1166 if (ERROR_OK != retval)
1167 return retval;
1169 return ERROR_OK;
1172 COMMAND_HANDLER(handle_target_init_command)
1174 int retval;
1176 if (CMD_ARGC != 0)
1177 return ERROR_COMMAND_SYNTAX_ERROR;
1179 static bool target_initialized;
1180 if (target_initialized) {
1181 LOG_INFO("'target init' has already been called");
1182 return ERROR_OK;
1184 target_initialized = true;
1186 retval = command_run_line(CMD_CTX, "init_targets");
1187 if (ERROR_OK != retval)
1188 return retval;
1190 retval = command_run_line(CMD_CTX, "init_board");
1191 if (ERROR_OK != retval)
1192 return retval;
1194 LOG_DEBUG("Initializing targets...");
1195 return target_init(CMD_CTX);
1198 int target_register_event_callback(int (*callback)(struct target *target,
1199 enum target_event event, void *priv), void *priv)
1201 struct target_event_callback **callbacks_p = &target_event_callbacks;
1203 if (callback == NULL)
1204 return ERROR_COMMAND_SYNTAX_ERROR;
1206 if (*callbacks_p) {
1207 while ((*callbacks_p)->next)
1208 callbacks_p = &((*callbacks_p)->next);
1209 callbacks_p = &((*callbacks_p)->next);
1212 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1213 (*callbacks_p)->callback = callback;
1214 (*callbacks_p)->priv = priv;
1215 (*callbacks_p)->next = NULL;
1217 return ERROR_OK;
1220 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1222 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1223 struct timeval now;
1225 if (callback == NULL)
1226 return ERROR_COMMAND_SYNTAX_ERROR;
1228 if (*callbacks_p) {
1229 while ((*callbacks_p)->next)
1230 callbacks_p = &((*callbacks_p)->next);
1231 callbacks_p = &((*callbacks_p)->next);
1234 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1235 (*callbacks_p)->callback = callback;
1236 (*callbacks_p)->periodic = periodic;
1237 (*callbacks_p)->time_ms = time_ms;
1239 gettimeofday(&now, NULL);
1240 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
1241 time_ms -= (time_ms % 1000);
1242 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
1243 if ((*callbacks_p)->when.tv_usec > 1000000) {
1244 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
1245 (*callbacks_p)->when.tv_sec += 1;
1248 (*callbacks_p)->priv = priv;
1249 (*callbacks_p)->next = NULL;
1251 return ERROR_OK;
1254 int target_unregister_event_callback(int (*callback)(struct target *target,
1255 enum target_event event, void *priv), void *priv)
1257 struct target_event_callback **p = &target_event_callbacks;
1258 struct target_event_callback *c = target_event_callbacks;
1260 if (callback == NULL)
1261 return ERROR_COMMAND_SYNTAX_ERROR;
1263 while (c) {
1264 struct target_event_callback *next = c->next;
1265 if ((c->callback == callback) && (c->priv == priv)) {
1266 *p = next;
1267 free(c);
1268 return ERROR_OK;
1269 } else
1270 p = &(c->next);
1271 c = next;
1274 return ERROR_OK;
1277 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1279 struct target_timer_callback **p = &target_timer_callbacks;
1280 struct target_timer_callback *c = target_timer_callbacks;
1282 if (callback == NULL)
1283 return ERROR_COMMAND_SYNTAX_ERROR;
1285 while (c) {
1286 struct target_timer_callback *next = c->next;
1287 if ((c->callback == callback) && (c->priv == priv)) {
1288 *p = next;
1289 free(c);
1290 return ERROR_OK;
1291 } else
1292 p = &(c->next);
1293 c = next;
1296 return ERROR_OK;
1299 int target_call_event_callbacks(struct target *target, enum target_event event)
1301 struct target_event_callback *callback = target_event_callbacks;
1302 struct target_event_callback *next_callback;
1304 if (event == TARGET_EVENT_HALTED) {
1305 /* execute early halted first */
1306 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1309 LOG_DEBUG("target event %i (%s)", event,
1310 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1312 target_handle_event(target, event);
1314 while (callback) {
1315 next_callback = callback->next;
1316 callback->callback(target, event, callback->priv);
1317 callback = next_callback;
1320 return ERROR_OK;
1323 static int target_timer_callback_periodic_restart(
1324 struct target_timer_callback *cb, struct timeval *now)
1326 int time_ms = cb->time_ms;
1327 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1328 time_ms -= (time_ms % 1000);
1329 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1330 if (cb->when.tv_usec > 1000000) {
1331 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1332 cb->when.tv_sec += 1;
1334 return ERROR_OK;
1337 static int target_call_timer_callback(struct target_timer_callback *cb,
1338 struct timeval *now)
1340 cb->callback(cb->priv);
1342 if (cb->periodic)
1343 return target_timer_callback_periodic_restart(cb, now);
1345 return target_unregister_timer_callback(cb->callback, cb->priv);
1348 static int target_call_timer_callbacks_check_time(int checktime)
1350 keep_alive();
1352 struct timeval now;
1353 gettimeofday(&now, NULL);
1355 struct target_timer_callback *callback = target_timer_callbacks;
1356 while (callback) {
1357 /* cleaning up may unregister and free this callback */
1358 struct target_timer_callback *next_callback = callback->next;
1360 bool call_it = callback->callback &&
1361 ((!checktime && callback->periodic) ||
1362 now.tv_sec > callback->when.tv_sec ||
1363 (now.tv_sec == callback->when.tv_sec &&
1364 now.tv_usec >= callback->when.tv_usec));
1366 if (call_it) {
1367 int retval = target_call_timer_callback(callback, &now);
1368 if (retval != ERROR_OK)
1369 return retval;
1372 callback = next_callback;
1375 return ERROR_OK;
1378 int target_call_timer_callbacks(void)
1380 return target_call_timer_callbacks_check_time(1);
1383 /* invoke periodic callbacks immediately */
1384 int target_call_timer_callbacks_now(void)
1386 return target_call_timer_callbacks_check_time(0);
1389 /* Prints the working area layout for debug purposes */
1390 static void print_wa_layout(struct target *target)
1392 struct working_area *c = target->working_areas;
1394 while (c) {
1395 LOG_DEBUG("%c%c 0x%08"PRIx32"-0x%08"PRIx32" (%"PRIu32" bytes)",
1396 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1397 c->address, c->address + c->size - 1, c->size);
1398 c = c->next;
1402 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1403 static void target_split_working_area(struct working_area *area, uint32_t size)
1405 assert(area->free); /* Shouldn't split an allocated area */
1406 assert(size <= area->size); /* Caller should guarantee this */
1408 /* Split only if not already the right size */
1409 if (size < area->size) {
1410 struct working_area *new_wa = malloc(sizeof(*new_wa));
1412 if (new_wa == NULL)
1413 return;
1415 new_wa->next = area->next;
1416 new_wa->size = area->size - size;
1417 new_wa->address = area->address + size;
1418 new_wa->backup = NULL;
1419 new_wa->user = NULL;
1420 new_wa->free = true;
1422 area->next = new_wa;
1423 area->size = size;
1425 /* If backup memory was allocated to this area, it has the wrong size
1426 * now so free it and it will be reallocated if/when needed */
1427 if (area->backup) {
1428 free(area->backup);
1429 area->backup = NULL;
1434 /* Merge all adjacent free areas into one */
1435 static void target_merge_working_areas(struct target *target)
1437 struct working_area *c = target->working_areas;
1439 while (c && c->next) {
1440 assert(c->next->address == c->address + c->size); /* This is an invariant */
1442 /* Find two adjacent free areas */
1443 if (c->free && c->next->free) {
1444 /* Merge the last into the first */
1445 c->size += c->next->size;
1447 /* Remove the last */
1448 struct working_area *to_be_freed = c->next;
1449 c->next = c->next->next;
1450 if (to_be_freed->backup)
1451 free(to_be_freed->backup);
1452 free(to_be_freed);
1454 /* If backup memory was allocated to the remaining area, it's has
1455 * the wrong size now */
1456 if (c->backup) {
1457 free(c->backup);
1458 c->backup = NULL;
1460 } else {
1461 c = c->next;
1466 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1468 /* Reevaluate working area address based on MMU state*/
1469 if (target->working_areas == NULL) {
1470 int retval;
1471 int enabled;
1473 retval = target->type->mmu(target, &enabled);
1474 if (retval != ERROR_OK)
1475 return retval;
1477 if (!enabled) {
1478 if (target->working_area_phys_spec) {
1479 LOG_DEBUG("MMU disabled, using physical "
1480 "address for working memory 0x%08"PRIx32,
1481 target->working_area_phys);
1482 target->working_area = target->working_area_phys;
1483 } else {
1484 LOG_ERROR("No working memory available. "
1485 "Specify -work-area-phys to target.");
1486 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1488 } else {
1489 if (target->working_area_virt_spec) {
1490 LOG_DEBUG("MMU enabled, using virtual "
1491 "address for working memory 0x%08"PRIx32,
1492 target->working_area_virt);
1493 target->working_area = target->working_area_virt;
1494 } else {
1495 LOG_ERROR("No working memory available. "
1496 "Specify -work-area-virt to target.");
1497 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1501 /* Set up initial working area on first call */
1502 struct working_area *new_wa = malloc(sizeof(*new_wa));
1503 if (new_wa) {
1504 new_wa->next = NULL;
1505 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1506 new_wa->address = target->working_area;
1507 new_wa->backup = NULL;
1508 new_wa->user = NULL;
1509 new_wa->free = true;
1512 target->working_areas = new_wa;
1515 /* only allocate multiples of 4 byte */
1516 if (size % 4)
1517 size = (size + 3) & (~3UL);
1519 struct working_area *c = target->working_areas;
1521 /* Find the first large enough working area */
1522 while (c) {
1523 if (c->free && c->size >= size)
1524 break;
1525 c = c->next;
1528 if (c == NULL)
1529 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1531 /* Split the working area into the requested size */
1532 target_split_working_area(c, size);
1534 LOG_DEBUG("allocated new working area of %"PRIu32" bytes at address 0x%08"PRIx32, size, c->address);
1536 if (target->backup_working_area) {
1537 if (c->backup == NULL) {
1538 c->backup = malloc(c->size);
1539 if (c->backup == NULL)
1540 return ERROR_FAIL;
1543 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1544 if (retval != ERROR_OK)
1545 return retval;
1548 /* mark as used, and return the new (reused) area */
1549 c->free = false;
1550 *area = c;
1552 /* user pointer */
1553 c->user = area;
1555 print_wa_layout(target);
1557 return ERROR_OK;
1560 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1562 int retval;
1564 retval = target_alloc_working_area_try(target, size, area);
1565 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1566 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1567 return retval;
1571 static int target_restore_working_area(struct target *target, struct working_area *area)
1573 int retval = ERROR_OK;
1575 if (target->backup_working_area && area->backup != NULL) {
1576 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1577 if (retval != ERROR_OK)
1578 LOG_ERROR("failed to restore %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1579 area->size, area->address);
1582 return retval;
1585 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1586 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1588 int retval = ERROR_OK;
1590 if (area->free)
1591 return retval;
1593 if (restore) {
1594 retval = target_restore_working_area(target, area);
1595 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1596 if (retval != ERROR_OK)
1597 return retval;
1600 area->free = true;
1602 LOG_DEBUG("freed %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1603 area->size, area->address);
1605 /* mark user pointer invalid */
1606 /* TODO: Is this really safe? It points to some previous caller's memory.
1607 * How could we know that the area pointer is still in that place and not
1608 * some other vital data? What's the purpose of this, anyway? */
1609 *area->user = NULL;
1610 area->user = NULL;
1612 target_merge_working_areas(target);
1614 print_wa_layout(target);
1616 return retval;
1619 int target_free_working_area(struct target *target, struct working_area *area)
1621 return target_free_working_area_restore(target, area, 1);
1624 /* free resources and restore memory, if restoring memory fails,
1625 * free up resources anyway
1627 static void target_free_all_working_areas_restore(struct target *target, int restore)
1629 struct working_area *c = target->working_areas;
1631 LOG_DEBUG("freeing all working areas");
1633 /* Loop through all areas, restoring the allocated ones and marking them as free */
1634 while (c) {
1635 if (!c->free) {
1636 if (restore)
1637 target_restore_working_area(target, c);
1638 c->free = true;
1639 *c->user = NULL; /* Same as above */
1640 c->user = NULL;
1642 c = c->next;
1645 /* Run a merge pass to combine all areas into one */
1646 target_merge_working_areas(target);
1648 print_wa_layout(target);
1651 void target_free_all_working_areas(struct target *target)
1653 target_free_all_working_areas_restore(target, 1);
1656 /* Find the largest number of bytes that can be allocated */
1657 uint32_t target_get_working_area_avail(struct target *target)
1659 struct working_area *c = target->working_areas;
1660 uint32_t max_size = 0;
1662 if (c == NULL)
1663 return target->working_area_size;
1665 while (c) {
1666 if (c->free && max_size < c->size)
1667 max_size = c->size;
1669 c = c->next;
1672 return max_size;
1675 int target_arch_state(struct target *target)
1677 int retval;
1678 if (target == NULL) {
1679 LOG_USER("No target has been configured");
1680 return ERROR_OK;
1683 LOG_USER("target state: %s", target_state_name(target));
1685 if (target->state != TARGET_HALTED)
1686 return ERROR_OK;
1688 retval = target->type->arch_state(target);
1689 return retval;
1692 /* Single aligned words are guaranteed to use 16 or 32 bit access
1693 * mode respectively, otherwise data is handled as quickly as
1694 * possible
1696 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1698 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1699 (int)size, (unsigned)address);
1701 if (!target_was_examined(target)) {
1702 LOG_ERROR("Target not examined yet");
1703 return ERROR_FAIL;
1706 if (size == 0)
1707 return ERROR_OK;
1709 if ((address + size - 1) < address) {
1710 /* GDB can request this when e.g. PC is 0xfffffffc*/
1711 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1712 (unsigned)address,
1713 (unsigned)size);
1714 return ERROR_FAIL;
1717 return target->type->write_buffer(target, address, size, buffer);
1720 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1722 int retval = ERROR_OK;
1724 if (((address % 2) == 0) && (size == 2))
1725 return target_write_memory(target, address, 2, 1, buffer);
1727 /* handle unaligned head bytes */
1728 if (address % 4) {
1729 uint32_t unaligned = 4 - (address % 4);
1731 if (unaligned > size)
1732 unaligned = size;
1734 retval = target_write_memory(target, address, 1, unaligned, buffer);
1735 if (retval != ERROR_OK)
1736 return retval;
1738 buffer += unaligned;
1739 address += unaligned;
1740 size -= unaligned;
1743 /* handle aligned words */
1744 if (size >= 4) {
1745 int aligned = size - (size % 4);
1747 /* use bulk writes above a certain limit. This may have to be changed */
1748 if (aligned > 128) {
1749 retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer);
1750 if (retval != ERROR_OK)
1751 return retval;
1752 } else {
1753 retval = target_write_memory(target, address, 4, aligned / 4, buffer);
1754 if (retval != ERROR_OK)
1755 return retval;
1758 buffer += aligned;
1759 address += aligned;
1760 size -= aligned;
1763 /* handle tail writes of less than 4 bytes */
1764 if (size > 0) {
1765 retval = target_write_memory(target, address, 1, size, buffer);
1766 if (retval != ERROR_OK)
1767 return retval;
1770 return retval;
1773 /* Single aligned words are guaranteed to use 16 or 32 bit access
1774 * mode respectively, otherwise data is handled as quickly as
1775 * possible
1777 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1779 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1780 (int)size, (unsigned)address);
1782 if (!target_was_examined(target)) {
1783 LOG_ERROR("Target not examined yet");
1784 return ERROR_FAIL;
1787 if (size == 0)
1788 return ERROR_OK;
1790 if ((address + size - 1) < address) {
1791 /* GDB can request this when e.g. PC is 0xfffffffc*/
1792 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1793 address,
1794 size);
1795 return ERROR_FAIL;
1798 return target->type->read_buffer(target, address, size, buffer);
1801 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1803 int retval = ERROR_OK;
1805 if (((address % 2) == 0) && (size == 2))
1806 return target_read_memory(target, address, 2, 1, buffer);
1808 /* handle unaligned head bytes */
1809 if (address % 4) {
1810 uint32_t unaligned = 4 - (address % 4);
1812 if (unaligned > size)
1813 unaligned = size;
1815 retval = target_read_memory(target, address, 1, unaligned, buffer);
1816 if (retval != ERROR_OK)
1817 return retval;
1819 buffer += unaligned;
1820 address += unaligned;
1821 size -= unaligned;
1824 /* handle aligned words */
1825 if (size >= 4) {
1826 int aligned = size - (size % 4);
1828 retval = target_read_memory(target, address, 4, aligned / 4, buffer);
1829 if (retval != ERROR_OK)
1830 return retval;
1832 buffer += aligned;
1833 address += aligned;
1834 size -= aligned;
1837 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1838 if (size >= 2) {
1839 int aligned = size - (size % 2);
1840 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1841 if (retval != ERROR_OK)
1842 return retval;
1844 buffer += aligned;
1845 address += aligned;
1846 size -= aligned;
1848 /* handle tail writes of less than 4 bytes */
1849 if (size > 0) {
1850 retval = target_read_memory(target, address, 1, size, buffer);
1851 if (retval != ERROR_OK)
1852 return retval;
1855 return ERROR_OK;
1858 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1860 uint8_t *buffer;
1861 int retval;
1862 uint32_t i;
1863 uint32_t checksum = 0;
1864 if (!target_was_examined(target)) {
1865 LOG_ERROR("Target not examined yet");
1866 return ERROR_FAIL;
1869 retval = target->type->checksum_memory(target, address, size, &checksum);
1870 if (retval != ERROR_OK) {
1871 buffer = malloc(size);
1872 if (buffer == NULL) {
1873 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1874 return ERROR_COMMAND_SYNTAX_ERROR;
1876 retval = target_read_buffer(target, address, size, buffer);
1877 if (retval != ERROR_OK) {
1878 free(buffer);
1879 return retval;
1882 /* convert to target endianness */
1883 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
1884 uint32_t target_data;
1885 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1886 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1889 retval = image_calculate_checksum(buffer, size, &checksum);
1890 free(buffer);
1893 *crc = checksum;
1895 return retval;
1898 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1900 int retval;
1901 if (!target_was_examined(target)) {
1902 LOG_ERROR("Target not examined yet");
1903 return ERROR_FAIL;
1906 if (target->type->blank_check_memory == 0)
1907 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1909 retval = target->type->blank_check_memory(target, address, size, blank);
1911 return retval;
1914 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1916 uint8_t value_buf[4];
1917 if (!target_was_examined(target)) {
1918 LOG_ERROR("Target not examined yet");
1919 return ERROR_FAIL;
1922 int retval = target_read_memory(target, address, 4, 1, value_buf);
1924 if (retval == ERROR_OK) {
1925 *value = target_buffer_get_u32(target, value_buf);
1926 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1927 address,
1928 *value);
1929 } else {
1930 *value = 0x0;
1931 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1932 address);
1935 return retval;
1938 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1940 uint8_t value_buf[2];
1941 if (!target_was_examined(target)) {
1942 LOG_ERROR("Target not examined yet");
1943 return ERROR_FAIL;
1946 int retval = target_read_memory(target, address, 2, 1, value_buf);
1948 if (retval == ERROR_OK) {
1949 *value = target_buffer_get_u16(target, value_buf);
1950 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1951 address,
1952 *value);
1953 } else {
1954 *value = 0x0;
1955 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1956 address);
1959 return retval;
1962 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1964 int retval = target_read_memory(target, address, 1, 1, value);
1965 if (!target_was_examined(target)) {
1966 LOG_ERROR("Target not examined yet");
1967 return ERROR_FAIL;
1970 if (retval == ERROR_OK) {
1971 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1972 address,
1973 *value);
1974 } else {
1975 *value = 0x0;
1976 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1977 address);
1980 return retval;
1983 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1985 int retval;
1986 uint8_t value_buf[4];
1987 if (!target_was_examined(target)) {
1988 LOG_ERROR("Target not examined yet");
1989 return ERROR_FAIL;
1992 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1993 address,
1994 value);
1996 target_buffer_set_u32(target, value_buf, value);
1997 retval = target_write_memory(target, address, 4, 1, value_buf);
1998 if (retval != ERROR_OK)
1999 LOG_DEBUG("failed: %i", retval);
2001 return retval;
2004 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
2006 int retval;
2007 uint8_t value_buf[2];
2008 if (!target_was_examined(target)) {
2009 LOG_ERROR("Target not examined yet");
2010 return ERROR_FAIL;
2013 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
2014 address,
2015 value);
2017 target_buffer_set_u16(target, value_buf, value);
2018 retval = target_write_memory(target, address, 2, 1, value_buf);
2019 if (retval != ERROR_OK)
2020 LOG_DEBUG("failed: %i", retval);
2022 return retval;
2025 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
2027 int retval;
2028 if (!target_was_examined(target)) {
2029 LOG_ERROR("Target not examined yet");
2030 return ERROR_FAIL;
2033 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2034 address, value);
2036 retval = target_write_memory(target, address, 1, 1, &value);
2037 if (retval != ERROR_OK)
2038 LOG_DEBUG("failed: %i", retval);
2040 return retval;
2043 static int find_target(struct command_context *cmd_ctx, const char *name)
2045 struct target *target = get_target(name);
2046 if (target == NULL) {
2047 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2048 return ERROR_FAIL;
2050 if (!target->tap->enabled) {
2051 LOG_USER("Target: TAP %s is disabled, "
2052 "can't be the current target\n",
2053 target->tap->dotted_name);
2054 return ERROR_FAIL;
2057 cmd_ctx->current_target = target->target_number;
2058 return ERROR_OK;
2062 COMMAND_HANDLER(handle_targets_command)
2064 int retval = ERROR_OK;
2065 if (CMD_ARGC == 1) {
2066 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2067 if (retval == ERROR_OK) {
2068 /* we're done! */
2069 return retval;
2073 struct target *target = all_targets;
2074 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2075 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2076 while (target) {
2077 const char *state;
2078 char marker = ' ';
2080 if (target->tap->enabled)
2081 state = target_state_name(target);
2082 else
2083 state = "tap-disabled";
2085 if (CMD_CTX->current_target == target->target_number)
2086 marker = '*';
2088 /* keep columns lined up to match the headers above */
2089 command_print(CMD_CTX,
2090 "%2d%c %-18s %-10s %-6s %-18s %s",
2091 target->target_number,
2092 marker,
2093 target_name(target),
2094 target_type_name(target),
2095 Jim_Nvp_value2name_simple(nvp_target_endian,
2096 target->endianness)->name,
2097 target->tap->dotted_name,
2098 state);
2099 target = target->next;
2102 return retval;
2105 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2107 static int powerDropout;
2108 static int srstAsserted;
2110 static int runPowerRestore;
2111 static int runPowerDropout;
2112 static int runSrstAsserted;
2113 static int runSrstDeasserted;
2115 static int sense_handler(void)
2117 static int prevSrstAsserted;
2118 static int prevPowerdropout;
2120 int retval = jtag_power_dropout(&powerDropout);
2121 if (retval != ERROR_OK)
2122 return retval;
2124 int powerRestored;
2125 powerRestored = prevPowerdropout && !powerDropout;
2126 if (powerRestored)
2127 runPowerRestore = 1;
2129 long long current = timeval_ms();
2130 static long long lastPower;
2131 int waitMore = lastPower + 2000 > current;
2132 if (powerDropout && !waitMore) {
2133 runPowerDropout = 1;
2134 lastPower = current;
2137 retval = jtag_srst_asserted(&srstAsserted);
2138 if (retval != ERROR_OK)
2139 return retval;
2141 int srstDeasserted;
2142 srstDeasserted = prevSrstAsserted && !srstAsserted;
2144 static long long lastSrst;
2145 waitMore = lastSrst + 2000 > current;
2146 if (srstDeasserted && !waitMore) {
2147 runSrstDeasserted = 1;
2148 lastSrst = current;
2151 if (!prevSrstAsserted && srstAsserted)
2152 runSrstAsserted = 1;
2154 prevSrstAsserted = srstAsserted;
2155 prevPowerdropout = powerDropout;
2157 if (srstDeasserted || powerRestored) {
2158 /* Other than logging the event we can't do anything here.
2159 * Issuing a reset is a particularly bad idea as we might
2160 * be inside a reset already.
2164 return ERROR_OK;
2167 static int backoff_times;
2168 static int backoff_count;
2170 /* process target state changes */
2171 static int handle_target(void *priv)
2173 Jim_Interp *interp = (Jim_Interp *)priv;
2174 int retval = ERROR_OK;
2176 if (!is_jtag_poll_safe()) {
2177 /* polling is disabled currently */
2178 return ERROR_OK;
2181 /* we do not want to recurse here... */
2182 static int recursive;
2183 if (!recursive) {
2184 recursive = 1;
2185 sense_handler();
2186 /* danger! running these procedures can trigger srst assertions and power dropouts.
2187 * We need to avoid an infinite loop/recursion here and we do that by
2188 * clearing the flags after running these events.
2190 int did_something = 0;
2191 if (runSrstAsserted) {
2192 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2193 Jim_Eval(interp, "srst_asserted");
2194 did_something = 1;
2196 if (runSrstDeasserted) {
2197 Jim_Eval(interp, "srst_deasserted");
2198 did_something = 1;
2200 if (runPowerDropout) {
2201 LOG_INFO("Power dropout detected, running power_dropout proc.");
2202 Jim_Eval(interp, "power_dropout");
2203 did_something = 1;
2205 if (runPowerRestore) {
2206 Jim_Eval(interp, "power_restore");
2207 did_something = 1;
2210 if (did_something) {
2211 /* clear detect flags */
2212 sense_handler();
2215 /* clear action flags */
2217 runSrstAsserted = 0;
2218 runSrstDeasserted = 0;
2219 runPowerRestore = 0;
2220 runPowerDropout = 0;
2222 recursive = 0;
2225 if (backoff_times > backoff_count) {
2226 /* do not poll this time as we failed previously */
2227 backoff_count++;
2228 return ERROR_OK;
2230 backoff_count = 0;
2232 /* Poll targets for state changes unless that's globally disabled.
2233 * Skip targets that are currently disabled.
2235 for (struct target *target = all_targets;
2236 is_jtag_poll_safe() && target;
2237 target = target->next) {
2238 if (!target->tap->enabled)
2239 continue;
2241 /* only poll target if we've got power and srst isn't asserted */
2242 if (!powerDropout && !srstAsserted) {
2243 /* polling may fail silently until the target has been examined */
2244 retval = target_poll(target);
2245 if (retval != ERROR_OK) {
2246 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2247 if (backoff_times * polling_interval < 5000) {
2248 backoff_times *= 2;
2249 backoff_times++;
2251 LOG_USER("Polling target failed, GDB will be halted. Polling again in %dms",
2252 backoff_times * polling_interval);
2254 /* Tell GDB to halt the debugger. This allows the user to
2255 * run monitor commands to handle the situation.
2257 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2258 return retval;
2260 /* Since we succeeded, we reset backoff count */
2261 if (backoff_times > 0)
2262 LOG_USER("Polling succeeded again");
2263 backoff_times = 0;
2267 return retval;
2270 COMMAND_HANDLER(handle_reg_command)
2272 struct target *target;
2273 struct reg *reg = NULL;
2274 unsigned count = 0;
2275 char *value;
2277 LOG_DEBUG("-");
2279 target = get_current_target(CMD_CTX);
2281 /* list all available registers for the current target */
2282 if (CMD_ARGC == 0) {
2283 struct reg_cache *cache = target->reg_cache;
2285 count = 0;
2286 while (cache) {
2287 unsigned i;
2289 command_print(CMD_CTX, "===== %s", cache->name);
2291 for (i = 0, reg = cache->reg_list;
2292 i < cache->num_regs;
2293 i++, reg++, count++) {
2294 /* only print cached values if they are valid */
2295 if (reg->valid) {
2296 value = buf_to_str(reg->value,
2297 reg->size, 16);
2298 command_print(CMD_CTX,
2299 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2300 count, reg->name,
2301 reg->size, value,
2302 reg->dirty
2303 ? " (dirty)"
2304 : "");
2305 free(value);
2306 } else {
2307 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2308 count, reg->name,
2309 reg->size) ;
2312 cache = cache->next;
2315 return ERROR_OK;
2318 /* access a single register by its ordinal number */
2319 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2320 unsigned num;
2321 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2323 struct reg_cache *cache = target->reg_cache;
2324 count = 0;
2325 while (cache) {
2326 unsigned i;
2327 for (i = 0; i < cache->num_regs; i++) {
2328 if (count++ == num) {
2329 reg = &cache->reg_list[i];
2330 break;
2333 if (reg)
2334 break;
2335 cache = cache->next;
2338 if (!reg) {
2339 command_print(CMD_CTX, "%i is out of bounds, the current target "
2340 "has only %i registers (0 - %i)", num, count, count - 1);
2341 return ERROR_OK;
2343 } else {
2344 /* access a single register by its name */
2345 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2347 if (!reg) {
2348 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2349 return ERROR_OK;
2353 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2355 /* display a register */
2356 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2357 && (CMD_ARGV[1][0] <= '9')))) {
2358 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2359 reg->valid = 0;
2361 if (reg->valid == 0)
2362 reg->type->get(reg);
2363 value = buf_to_str(reg->value, reg->size, 16);
2364 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2365 free(value);
2366 return ERROR_OK;
2369 /* set register value */
2370 if (CMD_ARGC == 2) {
2371 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2372 if (buf == NULL)
2373 return ERROR_FAIL;
2374 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2376 reg->type->set(reg, buf);
2378 value = buf_to_str(reg->value, reg->size, 16);
2379 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2380 free(value);
2382 free(buf);
2384 return ERROR_OK;
2387 return ERROR_COMMAND_SYNTAX_ERROR;
2390 COMMAND_HANDLER(handle_poll_command)
2392 int retval = ERROR_OK;
2393 struct target *target = get_current_target(CMD_CTX);
2395 if (CMD_ARGC == 0) {
2396 command_print(CMD_CTX, "background polling: %s",
2397 jtag_poll_get_enabled() ? "on" : "off");
2398 command_print(CMD_CTX, "TAP: %s (%s)",
2399 target->tap->dotted_name,
2400 target->tap->enabled ? "enabled" : "disabled");
2401 if (!target->tap->enabled)
2402 return ERROR_OK;
2403 retval = target_poll(target);
2404 if (retval != ERROR_OK)
2405 return retval;
2406 retval = target_arch_state(target);
2407 if (retval != ERROR_OK)
2408 return retval;
2409 } else if (CMD_ARGC == 1) {
2410 bool enable;
2411 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2412 jtag_poll_set_enabled(enable);
2413 } else
2414 return ERROR_COMMAND_SYNTAX_ERROR;
2416 return retval;
2419 COMMAND_HANDLER(handle_wait_halt_command)
2421 if (CMD_ARGC > 1)
2422 return ERROR_COMMAND_SYNTAX_ERROR;
2424 unsigned ms = 5000;
2425 if (1 == CMD_ARGC) {
2426 int retval = parse_uint(CMD_ARGV[0], &ms);
2427 if (ERROR_OK != retval)
2428 return ERROR_COMMAND_SYNTAX_ERROR;
2429 /* convert seconds (given) to milliseconds (needed) */
2430 ms *= 1000;
2433 struct target *target = get_current_target(CMD_CTX);
2434 return target_wait_state(target, TARGET_HALTED, ms);
2437 /* wait for target state to change. The trick here is to have a low
2438 * latency for short waits and not to suck up all the CPU time
2439 * on longer waits.
2441 * After 500ms, keep_alive() is invoked
2443 int target_wait_state(struct target *target, enum target_state state, int ms)
2445 int retval;
2446 long long then = 0, cur;
2447 int once = 1;
2449 for (;;) {
2450 retval = target_poll(target);
2451 if (retval != ERROR_OK)
2452 return retval;
2453 if (target->state == state)
2454 break;
2455 cur = timeval_ms();
2456 if (once) {
2457 once = 0;
2458 then = timeval_ms();
2459 LOG_DEBUG("waiting for target %s...",
2460 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2463 if (cur-then > 500)
2464 keep_alive();
2466 if ((cur-then) > ms) {
2467 LOG_ERROR("timed out while waiting for target %s",
2468 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2469 return ERROR_FAIL;
2473 return ERROR_OK;
2476 COMMAND_HANDLER(handle_halt_command)
2478 LOG_DEBUG("-");
2480 struct target *target = get_current_target(CMD_CTX);
2481 int retval = target_halt(target);
2482 if (ERROR_OK != retval)
2483 return retval;
2485 if (CMD_ARGC == 1) {
2486 unsigned wait_local;
2487 retval = parse_uint(CMD_ARGV[0], &wait_local);
2488 if (ERROR_OK != retval)
2489 return ERROR_COMMAND_SYNTAX_ERROR;
2490 if (!wait_local)
2491 return ERROR_OK;
2494 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2497 COMMAND_HANDLER(handle_soft_reset_halt_command)
2499 struct target *target = get_current_target(CMD_CTX);
2501 LOG_USER("requesting target halt and executing a soft reset");
2503 target->type->soft_reset_halt(target);
2505 return ERROR_OK;
2508 COMMAND_HANDLER(handle_reset_command)
2510 if (CMD_ARGC > 1)
2511 return ERROR_COMMAND_SYNTAX_ERROR;
2513 enum target_reset_mode reset_mode = RESET_RUN;
2514 if (CMD_ARGC == 1) {
2515 const Jim_Nvp *n;
2516 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2517 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2518 return ERROR_COMMAND_SYNTAX_ERROR;
2519 reset_mode = n->value;
2522 /* reset *all* targets */
2523 return target_process_reset(CMD_CTX, reset_mode);
2527 COMMAND_HANDLER(handle_resume_command)
2529 int current = 1;
2530 if (CMD_ARGC > 1)
2531 return ERROR_COMMAND_SYNTAX_ERROR;
2533 struct target *target = get_current_target(CMD_CTX);
2535 /* with no CMD_ARGV, resume from current pc, addr = 0,
2536 * with one arguments, addr = CMD_ARGV[0],
2537 * handle breakpoints, not debugging */
2538 uint32_t addr = 0;
2539 if (CMD_ARGC == 1) {
2540 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2541 current = 0;
2544 return target_resume(target, current, addr, 1, 0);
2547 COMMAND_HANDLER(handle_step_command)
2549 if (CMD_ARGC > 1)
2550 return ERROR_COMMAND_SYNTAX_ERROR;
2552 LOG_DEBUG("-");
2554 /* with no CMD_ARGV, step from current pc, addr = 0,
2555 * with one argument addr = CMD_ARGV[0],
2556 * handle breakpoints, debugging */
2557 uint32_t addr = 0;
2558 int current_pc = 1;
2559 if (CMD_ARGC == 1) {
2560 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2561 current_pc = 0;
2564 struct target *target = get_current_target(CMD_CTX);
2566 return target->type->step(target, current_pc, addr, 1);
2569 static void handle_md_output(struct command_context *cmd_ctx,
2570 struct target *target, uint32_t address, unsigned size,
2571 unsigned count, const uint8_t *buffer)
2573 const unsigned line_bytecnt = 32;
2574 unsigned line_modulo = line_bytecnt / size;
2576 char output[line_bytecnt * 4 + 1];
2577 unsigned output_len = 0;
2579 const char *value_fmt;
2580 switch (size) {
2581 case 4:
2582 value_fmt = "%8.8x ";
2583 break;
2584 case 2:
2585 value_fmt = "%4.4x ";
2586 break;
2587 case 1:
2588 value_fmt = "%2.2x ";
2589 break;
2590 default:
2591 /* "can't happen", caller checked */
2592 LOG_ERROR("invalid memory read size: %u", size);
2593 return;
2596 for (unsigned i = 0; i < count; i++) {
2597 if (i % line_modulo == 0) {
2598 output_len += snprintf(output + output_len,
2599 sizeof(output) - output_len,
2600 "0x%8.8x: ",
2601 (unsigned)(address + (i*size)));
2604 uint32_t value = 0;
2605 const uint8_t *value_ptr = buffer + i * size;
2606 switch (size) {
2607 case 4:
2608 value = target_buffer_get_u32(target, value_ptr);
2609 break;
2610 case 2:
2611 value = target_buffer_get_u16(target, value_ptr);
2612 break;
2613 case 1:
2614 value = *value_ptr;
2616 output_len += snprintf(output + output_len,
2617 sizeof(output) - output_len,
2618 value_fmt, value);
2620 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2621 command_print(cmd_ctx, "%s", output);
2622 output_len = 0;
2627 COMMAND_HANDLER(handle_md_command)
2629 if (CMD_ARGC < 1)
2630 return ERROR_COMMAND_SYNTAX_ERROR;
2632 unsigned size = 0;
2633 switch (CMD_NAME[2]) {
2634 case 'w':
2635 size = 4;
2636 break;
2637 case 'h':
2638 size = 2;
2639 break;
2640 case 'b':
2641 size = 1;
2642 break;
2643 default:
2644 return ERROR_COMMAND_SYNTAX_ERROR;
2647 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2648 int (*fn)(struct target *target,
2649 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2650 if (physical) {
2651 CMD_ARGC--;
2652 CMD_ARGV++;
2653 fn = target_read_phys_memory;
2654 } else
2655 fn = target_read_memory;
2656 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2657 return ERROR_COMMAND_SYNTAX_ERROR;
2659 uint32_t address;
2660 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2662 unsigned count = 1;
2663 if (CMD_ARGC == 2)
2664 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2666 uint8_t *buffer = calloc(count, size);
2668 struct target *target = get_current_target(CMD_CTX);
2669 int retval = fn(target, address, size, count, buffer);
2670 if (ERROR_OK == retval)
2671 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2673 free(buffer);
2675 return retval;
2678 typedef int (*target_write_fn)(struct target *target,
2679 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2681 static int target_write_memory_fast(struct target *target,
2682 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
2684 return target_write_buffer(target, address, size * count, buffer);
2687 static int target_fill_mem(struct target *target,
2688 uint32_t address,
2689 target_write_fn fn,
2690 unsigned data_size,
2691 /* value */
2692 uint32_t b,
2693 /* count */
2694 unsigned c)
2696 /* We have to write in reasonably large chunks to be able
2697 * to fill large memory areas with any sane speed */
2698 const unsigned chunk_size = 16384;
2699 uint8_t *target_buf = malloc(chunk_size * data_size);
2700 if (target_buf == NULL) {
2701 LOG_ERROR("Out of memory");
2702 return ERROR_FAIL;
2705 for (unsigned i = 0; i < chunk_size; i++) {
2706 switch (data_size) {
2707 case 4:
2708 target_buffer_set_u32(target, target_buf + i * data_size, b);
2709 break;
2710 case 2:
2711 target_buffer_set_u16(target, target_buf + i * data_size, b);
2712 break;
2713 case 1:
2714 target_buffer_set_u8(target, target_buf + i * data_size, b);
2715 break;
2716 default:
2717 exit(-1);
2721 int retval = ERROR_OK;
2723 for (unsigned x = 0; x < c; x += chunk_size) {
2724 unsigned current;
2725 current = c - x;
2726 if (current > chunk_size)
2727 current = chunk_size;
2728 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2729 if (retval != ERROR_OK)
2730 break;
2731 /* avoid GDB timeouts */
2732 keep_alive();
2734 free(target_buf);
2736 return retval;
2740 COMMAND_HANDLER(handle_mw_command)
2742 if (CMD_ARGC < 2)
2743 return ERROR_COMMAND_SYNTAX_ERROR;
2744 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2745 target_write_fn fn;
2746 if (physical) {
2747 CMD_ARGC--;
2748 CMD_ARGV++;
2749 fn = target_write_phys_memory;
2750 } else
2751 fn = target_write_memory_fast;
2752 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2753 return ERROR_COMMAND_SYNTAX_ERROR;
2755 uint32_t address;
2756 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2758 uint32_t value;
2759 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2761 unsigned count = 1;
2762 if (CMD_ARGC == 3)
2763 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2765 struct target *target = get_current_target(CMD_CTX);
2766 unsigned wordsize;
2767 switch (CMD_NAME[2]) {
2768 case 'w':
2769 wordsize = 4;
2770 break;
2771 case 'h':
2772 wordsize = 2;
2773 break;
2774 case 'b':
2775 wordsize = 1;
2776 break;
2777 default:
2778 return ERROR_COMMAND_SYNTAX_ERROR;
2781 return target_fill_mem(target, address, fn, wordsize, value, count);
2784 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2785 uint32_t *min_address, uint32_t *max_address)
2787 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2788 return ERROR_COMMAND_SYNTAX_ERROR;
2790 /* a base address isn't always necessary,
2791 * default to 0x0 (i.e. don't relocate) */
2792 if (CMD_ARGC >= 2) {
2793 uint32_t addr;
2794 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2795 image->base_address = addr;
2796 image->base_address_set = 1;
2797 } else
2798 image->base_address_set = 0;
2800 image->start_address_set = 0;
2802 if (CMD_ARGC >= 4)
2803 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2804 if (CMD_ARGC == 5) {
2805 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2806 /* use size (given) to find max (required) */
2807 *max_address += *min_address;
2810 if (*min_address > *max_address)
2811 return ERROR_COMMAND_SYNTAX_ERROR;
2813 return ERROR_OK;
2816 COMMAND_HANDLER(handle_load_image_command)
2818 uint8_t *buffer;
2819 size_t buf_cnt;
2820 uint32_t image_size;
2821 uint32_t min_address = 0;
2822 uint32_t max_address = 0xffffffff;
2823 int i;
2824 struct image image;
2826 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2827 &image, &min_address, &max_address);
2828 if (ERROR_OK != retval)
2829 return retval;
2831 struct target *target = get_current_target(CMD_CTX);
2833 struct duration bench;
2834 duration_start(&bench);
2836 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2837 return ERROR_OK;
2839 image_size = 0x0;
2840 retval = ERROR_OK;
2841 for (i = 0; i < image.num_sections; i++) {
2842 buffer = malloc(image.sections[i].size);
2843 if (buffer == NULL) {
2844 command_print(CMD_CTX,
2845 "error allocating buffer for section (%d bytes)",
2846 (int)(image.sections[i].size));
2847 break;
2850 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
2851 if (retval != ERROR_OK) {
2852 free(buffer);
2853 break;
2856 uint32_t offset = 0;
2857 uint32_t length = buf_cnt;
2859 /* DANGER!!! beware of unsigned comparision here!!! */
2861 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
2862 (image.sections[i].base_address < max_address)) {
2864 if (image.sections[i].base_address < min_address) {
2865 /* clip addresses below */
2866 offset += min_address-image.sections[i].base_address;
2867 length -= offset;
2870 if (image.sections[i].base_address + buf_cnt > max_address)
2871 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2873 retval = target_write_buffer(target,
2874 image.sections[i].base_address + offset, length, buffer + offset);
2875 if (retval != ERROR_OK) {
2876 free(buffer);
2877 break;
2879 image_size += length;
2880 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2881 (unsigned int)length,
2882 image.sections[i].base_address + offset);
2885 free(buffer);
2888 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
2889 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2890 "in %fs (%0.3f KiB/s)", image_size,
2891 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2894 image_close(&image);
2896 return retval;
2900 COMMAND_HANDLER(handle_dump_image_command)
2902 struct fileio fileio;
2903 uint8_t *buffer;
2904 int retval, retvaltemp;
2905 uint32_t address, size;
2906 struct duration bench;
2907 struct target *target = get_current_target(CMD_CTX);
2909 if (CMD_ARGC != 3)
2910 return ERROR_COMMAND_SYNTAX_ERROR;
2912 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2913 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2915 uint32_t buf_size = (size > 4096) ? 4096 : size;
2916 buffer = malloc(buf_size);
2917 if (!buffer)
2918 return ERROR_FAIL;
2920 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2921 if (retval != ERROR_OK) {
2922 free(buffer);
2923 return retval;
2926 duration_start(&bench);
2928 while (size > 0) {
2929 size_t size_written;
2930 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
2931 retval = target_read_buffer(target, address, this_run_size, buffer);
2932 if (retval != ERROR_OK)
2933 break;
2935 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2936 if (retval != ERROR_OK)
2937 break;
2939 size -= this_run_size;
2940 address += this_run_size;
2943 free(buffer);
2945 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
2946 int filesize;
2947 retval = fileio_size(&fileio, &filesize);
2948 if (retval != ERROR_OK)
2949 return retval;
2950 command_print(CMD_CTX,
2951 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
2952 duration_elapsed(&bench), duration_kbps(&bench, filesize));
2955 retvaltemp = fileio_close(&fileio);
2956 if (retvaltemp != ERROR_OK)
2957 return retvaltemp;
2959 return retval;
2962 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2964 uint8_t *buffer;
2965 size_t buf_cnt;
2966 uint32_t image_size;
2967 int i;
2968 int retval;
2969 uint32_t checksum = 0;
2970 uint32_t mem_checksum = 0;
2972 struct image image;
2974 struct target *target = get_current_target(CMD_CTX);
2976 if (CMD_ARGC < 1)
2977 return ERROR_COMMAND_SYNTAX_ERROR;
2979 if (!target) {
2980 LOG_ERROR("no target selected");
2981 return ERROR_FAIL;
2984 struct duration bench;
2985 duration_start(&bench);
2987 if (CMD_ARGC >= 2) {
2988 uint32_t addr;
2989 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2990 image.base_address = addr;
2991 image.base_address_set = 1;
2992 } else {
2993 image.base_address_set = 0;
2994 image.base_address = 0x0;
2997 image.start_address_set = 0;
2999 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3000 if (retval != ERROR_OK)
3001 return retval;
3003 image_size = 0x0;
3004 int diffs = 0;
3005 retval = ERROR_OK;
3006 for (i = 0; i < image.num_sections; i++) {
3007 buffer = malloc(image.sections[i].size);
3008 if (buffer == NULL) {
3009 command_print(CMD_CTX,
3010 "error allocating buffer for section (%d bytes)",
3011 (int)(image.sections[i].size));
3012 break;
3014 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3015 if (retval != ERROR_OK) {
3016 free(buffer);
3017 break;
3020 if (verify) {
3021 /* calculate checksum of image */
3022 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3023 if (retval != ERROR_OK) {
3024 free(buffer);
3025 break;
3028 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3029 if (retval != ERROR_OK) {
3030 free(buffer);
3031 break;
3034 if (checksum != mem_checksum) {
3035 /* failed crc checksum, fall back to a binary compare */
3036 uint8_t *data;
3038 if (diffs == 0)
3039 LOG_ERROR("checksum mismatch - attempting binary compare");
3041 data = (uint8_t *)malloc(buf_cnt);
3043 /* Can we use 32bit word accesses? */
3044 int size = 1;
3045 int count = buf_cnt;
3046 if ((count % 4) == 0) {
3047 size *= 4;
3048 count /= 4;
3050 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3051 if (retval == ERROR_OK) {
3052 uint32_t t;
3053 for (t = 0; t < buf_cnt; t++) {
3054 if (data[t] != buffer[t]) {
3055 command_print(CMD_CTX,
3056 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3057 diffs,
3058 (unsigned)(t + image.sections[i].base_address),
3059 data[t],
3060 buffer[t]);
3061 if (diffs++ >= 127) {
3062 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3063 free(data);
3064 free(buffer);
3065 goto done;
3068 keep_alive();
3071 free(data);
3073 } else {
3074 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3075 image.sections[i].base_address,
3076 buf_cnt);
3079 free(buffer);
3080 image_size += buf_cnt;
3082 if (diffs > 0)
3083 command_print(CMD_CTX, "No more differences found.");
3084 done:
3085 if (diffs > 0)
3086 retval = ERROR_FAIL;
3087 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3088 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3089 "in %fs (%0.3f KiB/s)", image_size,
3090 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3093 image_close(&image);
3095 return retval;
3098 COMMAND_HANDLER(handle_verify_image_command)
3100 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3103 COMMAND_HANDLER(handle_test_image_command)
3105 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3108 static int handle_bp_command_list(struct command_context *cmd_ctx)
3110 struct target *target = get_current_target(cmd_ctx);
3111 struct breakpoint *breakpoint = target->breakpoints;
3112 while (breakpoint) {
3113 if (breakpoint->type == BKPT_SOFT) {
3114 char *buf = buf_to_str(breakpoint->orig_instr,
3115 breakpoint->length, 16);
3116 command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3117 breakpoint->address,
3118 breakpoint->length,
3119 breakpoint->set, buf);
3120 free(buf);
3121 } else {
3122 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3123 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3124 breakpoint->asid,
3125 breakpoint->length, breakpoint->set);
3126 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3127 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3128 breakpoint->address,
3129 breakpoint->length, breakpoint->set);
3130 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3131 breakpoint->asid);
3132 } else
3133 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3134 breakpoint->address,
3135 breakpoint->length, breakpoint->set);
3138 breakpoint = breakpoint->next;
3140 return ERROR_OK;
3143 static int handle_bp_command_set(struct command_context *cmd_ctx,
3144 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3146 struct target *target = get_current_target(cmd_ctx);
3148 if (asid == 0) {
3149 int retval = breakpoint_add(target, addr, length, hw);
3150 if (ERROR_OK == retval)
3151 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3152 else {
3153 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3154 return retval;
3156 } else if (addr == 0) {
3157 int retval = context_breakpoint_add(target, asid, length, hw);
3158 if (ERROR_OK == retval)
3159 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3160 else {
3161 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3162 return retval;
3164 } else {
3165 int retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3166 if (ERROR_OK == retval)
3167 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3168 else {
3169 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3170 return retval;
3173 return ERROR_OK;
3176 COMMAND_HANDLER(handle_bp_command)
3178 uint32_t addr;
3179 uint32_t asid;
3180 uint32_t length;
3181 int hw = BKPT_SOFT;
3183 switch (CMD_ARGC) {
3184 case 0:
3185 return handle_bp_command_list(CMD_CTX);
3187 case 2:
3188 asid = 0;
3189 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3190 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3191 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3193 case 3:
3194 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3195 hw = BKPT_HARD;
3196 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3198 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3200 asid = 0;
3201 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3202 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3203 hw = BKPT_HARD;
3204 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3205 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3206 addr = 0;
3207 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3210 case 4:
3211 hw = BKPT_HARD;
3212 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3213 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3214 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3215 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3217 default:
3218 return ERROR_COMMAND_SYNTAX_ERROR;
3222 COMMAND_HANDLER(handle_rbp_command)
3224 if (CMD_ARGC != 1)
3225 return ERROR_COMMAND_SYNTAX_ERROR;
3227 uint32_t addr;
3228 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3230 struct target *target = get_current_target(CMD_CTX);
3231 breakpoint_remove(target, addr);
3233 return ERROR_OK;
3236 COMMAND_HANDLER(handle_wp_command)
3238 struct target *target = get_current_target(CMD_CTX);
3240 if (CMD_ARGC == 0) {
3241 struct watchpoint *watchpoint = target->watchpoints;
3243 while (watchpoint) {
3244 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3245 ", len: 0x%8.8" PRIx32
3246 ", r/w/a: %i, value: 0x%8.8" PRIx32
3247 ", mask: 0x%8.8" PRIx32,
3248 watchpoint->address,
3249 watchpoint->length,
3250 (int)watchpoint->rw,
3251 watchpoint->value,
3252 watchpoint->mask);
3253 watchpoint = watchpoint->next;
3255 return ERROR_OK;
3258 enum watchpoint_rw type = WPT_ACCESS;
3259 uint32_t addr = 0;
3260 uint32_t length = 0;
3261 uint32_t data_value = 0x0;
3262 uint32_t data_mask = 0xffffffff;
3264 switch (CMD_ARGC) {
3265 case 5:
3266 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3267 /* fall through */
3268 case 4:
3269 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3270 /* fall through */
3271 case 3:
3272 switch (CMD_ARGV[2][0]) {
3273 case 'r':
3274 type = WPT_READ;
3275 break;
3276 case 'w':
3277 type = WPT_WRITE;
3278 break;
3279 case 'a':
3280 type = WPT_ACCESS;
3281 break;
3282 default:
3283 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3284 return ERROR_COMMAND_SYNTAX_ERROR;
3286 /* fall through */
3287 case 2:
3288 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3289 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3290 break;
3292 default:
3293 return ERROR_COMMAND_SYNTAX_ERROR;
3296 int retval = watchpoint_add(target, addr, length, type,
3297 data_value, data_mask);
3298 if (ERROR_OK != retval)
3299 LOG_ERROR("Failure setting watchpoints");
3301 return retval;
3304 COMMAND_HANDLER(handle_rwp_command)
3306 if (CMD_ARGC != 1)
3307 return ERROR_COMMAND_SYNTAX_ERROR;
3309 uint32_t addr;
3310 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3312 struct target *target = get_current_target(CMD_CTX);
3313 watchpoint_remove(target, addr);
3315 return ERROR_OK;
3319 * Translate a virtual address to a physical address.
3321 * The low-level target implementation must have logged a detailed error
3322 * which is forwarded to telnet/GDB session.
3324 COMMAND_HANDLER(handle_virt2phys_command)
3326 if (CMD_ARGC != 1)
3327 return ERROR_COMMAND_SYNTAX_ERROR;
3329 uint32_t va;
3330 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3331 uint32_t pa;
3333 struct target *target = get_current_target(CMD_CTX);
3334 int retval = target->type->virt2phys(target, va, &pa);
3335 if (retval == ERROR_OK)
3336 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3338 return retval;
3341 static void writeData(FILE *f, const void *data, size_t len)
3343 size_t written = fwrite(data, 1, len, f);
3344 if (written != len)
3345 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3348 static void writeLong(FILE *f, int l)
3350 int i;
3351 for (i = 0; i < 4; i++) {
3352 char c = (l >> (i*8))&0xff;
3353 writeData(f, &c, 1);
3358 static void writeString(FILE *f, char *s)
3360 writeData(f, s, strlen(s));
3363 /* Dump a gmon.out histogram file. */
3364 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3366 uint32_t i;
3367 FILE *f = fopen(filename, "w");
3368 if (f == NULL)
3369 return;
3370 writeString(f, "gmon");
3371 writeLong(f, 0x00000001); /* Version */
3372 writeLong(f, 0); /* padding */
3373 writeLong(f, 0); /* padding */
3374 writeLong(f, 0); /* padding */
3376 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3377 writeData(f, &zero, 1);
3379 /* figure out bucket size */
3380 uint32_t min = samples[0];
3381 uint32_t max = samples[0];
3382 for (i = 0; i < sampleNum; i++) {
3383 if (min > samples[i])
3384 min = samples[i];
3385 if (max < samples[i])
3386 max = samples[i];
3389 int addressSpace = (max - min + 1);
3390 assert(addressSpace >= 2);
3392 static const uint32_t maxBuckets = 16 * 1024; /* maximum buckets. */
3393 uint32_t length = addressSpace;
3394 if (length > maxBuckets)
3395 length = maxBuckets;
3396 int *buckets = malloc(sizeof(int)*length);
3397 if (buckets == NULL) {
3398 fclose(f);
3399 return;
3401 memset(buckets, 0, sizeof(int) * length);
3402 for (i = 0; i < sampleNum; i++) {
3403 uint32_t address = samples[i];
3404 long long a = address - min;
3405 long long b = length - 1;
3406 long long c = addressSpace - 1;
3407 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3408 buckets[index_t]++;
3411 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3412 writeLong(f, min); /* low_pc */
3413 writeLong(f, max); /* high_pc */
3414 writeLong(f, length); /* # of samples */
3415 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3416 writeString(f, "seconds");
3417 for (i = 0; i < (15-strlen("seconds")); i++)
3418 writeData(f, &zero, 1);
3419 writeString(f, "s");
3421 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3423 char *data = malloc(2 * length);
3424 if (data != NULL) {
3425 for (i = 0; i < length; i++) {
3426 int val;
3427 val = buckets[i];
3428 if (val > 65535)
3429 val = 65535;
3430 data[i * 2] = val&0xff;
3431 data[i * 2 + 1] = (val >> 8) & 0xff;
3433 free(buckets);
3434 writeData(f, data, length * 2);
3435 free(data);
3436 } else
3437 free(buckets);
3439 fclose(f);
3442 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3443 * which will be used as a random sampling of PC */
3444 COMMAND_HANDLER(handle_profile_command)
3446 struct target *target = get_current_target(CMD_CTX);
3447 struct timeval timeout, now;
3449 gettimeofday(&timeout, NULL);
3450 if (CMD_ARGC != 2)
3451 return ERROR_COMMAND_SYNTAX_ERROR;
3452 unsigned offset;
3453 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3455 timeval_add_time(&timeout, offset, 0);
3458 * @todo: Some cores let us sample the PC without the
3459 * annoying halt/resume step; for example, ARMv7 PCSR.
3460 * Provide a way to use that more efficient mechanism.
3463 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3465 static const int maxSample = 10000;
3466 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3467 if (samples == NULL)
3468 return ERROR_OK;
3470 int numSamples = 0;
3471 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3472 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3474 int retval = ERROR_OK;
3475 for (;;) {
3476 target_poll(target);
3477 if (target->state == TARGET_HALTED) {
3478 uint32_t t = *((uint32_t *)reg->value);
3479 samples[numSamples++] = t;
3480 /* current pc, addr = 0, do not handle breakpoints, not debugging */
3481 retval = target_resume(target, 1, 0, 0, 0);
3482 target_poll(target);
3483 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3484 } else if (target->state == TARGET_RUNNING) {
3485 /* We want to quickly sample the PC. */
3486 retval = target_halt(target);
3487 if (retval != ERROR_OK) {
3488 free(samples);
3489 return retval;
3491 } else {
3492 command_print(CMD_CTX, "Target not halted or running");
3493 retval = ERROR_OK;
3494 break;
3496 if (retval != ERROR_OK)
3497 break;
3499 gettimeofday(&now, NULL);
3500 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec)
3501 && (now.tv_usec >= timeout.tv_usec))) {
3502 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3503 retval = target_poll(target);
3504 if (retval != ERROR_OK) {
3505 free(samples);
3506 return retval;
3508 if (target->state == TARGET_HALTED) {
3509 /* current pc, addr = 0, do not handle
3510 * breakpoints, not debugging */
3511 target_resume(target, 1, 0, 0, 0);
3513 retval = target_poll(target);
3514 if (retval != ERROR_OK) {
3515 free(samples);
3516 return retval;
3518 writeGmon(samples, numSamples, CMD_ARGV[1]);
3519 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3520 break;
3523 free(samples);
3525 return retval;
3528 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3530 char *namebuf;
3531 Jim_Obj *nameObjPtr, *valObjPtr;
3532 int result;
3534 namebuf = alloc_printf("%s(%d)", varname, idx);
3535 if (!namebuf)
3536 return JIM_ERR;
3538 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3539 valObjPtr = Jim_NewIntObj(interp, val);
3540 if (!nameObjPtr || !valObjPtr) {
3541 free(namebuf);
3542 return JIM_ERR;
3545 Jim_IncrRefCount(nameObjPtr);
3546 Jim_IncrRefCount(valObjPtr);
3547 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3548 Jim_DecrRefCount(interp, nameObjPtr);
3549 Jim_DecrRefCount(interp, valObjPtr);
3550 free(namebuf);
3551 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3552 return result;
3555 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3557 struct command_context *context;
3558 struct target *target;
3560 context = current_command_context(interp);
3561 assert(context != NULL);
3563 target = get_current_target(context);
3564 if (target == NULL) {
3565 LOG_ERROR("mem2array: no current target");
3566 return JIM_ERR;
3569 return target_mem2array(interp, target, argc - 1, argv + 1);
3572 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3574 long l;
3575 uint32_t width;
3576 int len;
3577 uint32_t addr;
3578 uint32_t count;
3579 uint32_t v;
3580 const char *varname;
3581 int n, e, retval;
3582 uint32_t i;
3584 /* argv[1] = name of array to receive the data
3585 * argv[2] = desired width
3586 * argv[3] = memory address
3587 * argv[4] = count of times to read
3589 if (argc != 4) {
3590 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3591 return JIM_ERR;
3593 varname = Jim_GetString(argv[0], &len);
3594 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3596 e = Jim_GetLong(interp, argv[1], &l);
3597 width = l;
3598 if (e != JIM_OK)
3599 return e;
3601 e = Jim_GetLong(interp, argv[2], &l);
3602 addr = l;
3603 if (e != JIM_OK)
3604 return e;
3605 e = Jim_GetLong(interp, argv[3], &l);
3606 len = l;
3607 if (e != JIM_OK)
3608 return e;
3609 switch (width) {
3610 case 8:
3611 width = 1;
3612 break;
3613 case 16:
3614 width = 2;
3615 break;
3616 case 32:
3617 width = 4;
3618 break;
3619 default:
3620 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3621 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3622 return JIM_ERR;
3624 if (len == 0) {
3625 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3626 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3627 return JIM_ERR;
3629 if ((addr + (len * width)) < addr) {
3630 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3631 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3632 return JIM_ERR;
3634 /* absurd transfer size? */
3635 if (len > 65536) {
3636 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3637 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3638 return JIM_ERR;
3641 if ((width == 1) ||
3642 ((width == 2) && ((addr & 1) == 0)) ||
3643 ((width == 4) && ((addr & 3) == 0))) {
3644 /* all is well */
3645 } else {
3646 char buf[100];
3647 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3648 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3649 addr,
3650 width);
3651 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3652 return JIM_ERR;
3655 /* Transfer loop */
3657 /* index counter */
3658 n = 0;
3660 size_t buffersize = 4096;
3661 uint8_t *buffer = malloc(buffersize);
3662 if (buffer == NULL)
3663 return JIM_ERR;
3665 /* assume ok */
3666 e = JIM_OK;
3667 while (len) {
3668 /* Slurp... in buffer size chunks */
3670 count = len; /* in objects.. */
3671 if (count > (buffersize / width))
3672 count = (buffersize / width);
3674 retval = target_read_memory(target, addr, width, count, buffer);
3675 if (retval != ERROR_OK) {
3676 /* BOO !*/
3677 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3678 (unsigned int)addr,
3679 (int)width,
3680 (int)count);
3681 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3682 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3683 e = JIM_ERR;
3684 break;
3685 } else {
3686 v = 0; /* shut up gcc */
3687 for (i = 0; i < count ; i++, n++) {
3688 switch (width) {
3689 case 4:
3690 v = target_buffer_get_u32(target, &buffer[i*width]);
3691 break;
3692 case 2:
3693 v = target_buffer_get_u16(target, &buffer[i*width]);
3694 break;
3695 case 1:
3696 v = buffer[i] & 0x0ff;
3697 break;
3699 new_int_array_element(interp, varname, n, v);
3701 len -= count;
3705 free(buffer);
3707 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3709 return e;
3712 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
3714 char *namebuf;
3715 Jim_Obj *nameObjPtr, *valObjPtr;
3716 int result;
3717 long l;
3719 namebuf = alloc_printf("%s(%d)", varname, idx);
3720 if (!namebuf)
3721 return JIM_ERR;
3723 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3724 if (!nameObjPtr) {
3725 free(namebuf);
3726 return JIM_ERR;
3729 Jim_IncrRefCount(nameObjPtr);
3730 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3731 Jim_DecrRefCount(interp, nameObjPtr);
3732 free(namebuf);
3733 if (valObjPtr == NULL)
3734 return JIM_ERR;
3736 result = Jim_GetLong(interp, valObjPtr, &l);
3737 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3738 *val = l;
3739 return result;
3742 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3744 struct command_context *context;
3745 struct target *target;
3747 context = current_command_context(interp);
3748 assert(context != NULL);
3750 target = get_current_target(context);
3751 if (target == NULL) {
3752 LOG_ERROR("array2mem: no current target");
3753 return JIM_ERR;
3756 return target_array2mem(interp, target, argc-1, argv + 1);
3759 static int target_array2mem(Jim_Interp *interp, struct target *target,
3760 int argc, Jim_Obj *const *argv)
3762 long l;
3763 uint32_t width;
3764 int len;
3765 uint32_t addr;
3766 uint32_t count;
3767 uint32_t v;
3768 const char *varname;
3769 int n, e, retval;
3770 uint32_t i;
3772 /* argv[1] = name of array to get the data
3773 * argv[2] = desired width
3774 * argv[3] = memory address
3775 * argv[4] = count to write
3777 if (argc != 4) {
3778 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3779 return JIM_ERR;
3781 varname = Jim_GetString(argv[0], &len);
3782 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3784 e = Jim_GetLong(interp, argv[1], &l);
3785 width = l;
3786 if (e != JIM_OK)
3787 return e;
3789 e = Jim_GetLong(interp, argv[2], &l);
3790 addr = l;
3791 if (e != JIM_OK)
3792 return e;
3793 e = Jim_GetLong(interp, argv[3], &l);
3794 len = l;
3795 if (e != JIM_OK)
3796 return e;
3797 switch (width) {
3798 case 8:
3799 width = 1;
3800 break;
3801 case 16:
3802 width = 2;
3803 break;
3804 case 32:
3805 width = 4;
3806 break;
3807 default:
3808 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3809 Jim_AppendStrings(interp, Jim_GetResult(interp),
3810 "Invalid width param, must be 8/16/32", NULL);
3811 return JIM_ERR;
3813 if (len == 0) {
3814 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3815 Jim_AppendStrings(interp, Jim_GetResult(interp),
3816 "array2mem: zero width read?", NULL);
3817 return JIM_ERR;
3819 if ((addr + (len * width)) < addr) {
3820 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3821 Jim_AppendStrings(interp, Jim_GetResult(interp),
3822 "array2mem: addr + len - wraps to zero?", NULL);
3823 return JIM_ERR;
3825 /* absurd transfer size? */
3826 if (len > 65536) {
3827 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3828 Jim_AppendStrings(interp, Jim_GetResult(interp),
3829 "array2mem: absurd > 64K item request", NULL);
3830 return JIM_ERR;
3833 if ((width == 1) ||
3834 ((width == 2) && ((addr & 1) == 0)) ||
3835 ((width == 4) && ((addr & 3) == 0))) {
3836 /* all is well */
3837 } else {
3838 char buf[100];
3839 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3840 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3841 (unsigned int)addr,
3842 (int)width);
3843 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3844 return JIM_ERR;
3847 /* Transfer loop */
3849 /* index counter */
3850 n = 0;
3851 /* assume ok */
3852 e = JIM_OK;
3854 size_t buffersize = 4096;
3855 uint8_t *buffer = malloc(buffersize);
3856 if (buffer == NULL)
3857 return JIM_ERR;
3859 while (len) {
3860 /* Slurp... in buffer size chunks */
3862 count = len; /* in objects.. */
3863 if (count > (buffersize / width))
3864 count = (buffersize / width);
3866 v = 0; /* shut up gcc */
3867 for (i = 0; i < count; i++, n++) {
3868 get_int_array_element(interp, varname, n, &v);
3869 switch (width) {
3870 case 4:
3871 target_buffer_set_u32(target, &buffer[i * width], v);
3872 break;
3873 case 2:
3874 target_buffer_set_u16(target, &buffer[i * width], v);
3875 break;
3876 case 1:
3877 buffer[i] = v & 0x0ff;
3878 break;
3881 len -= count;
3883 retval = target_write_memory(target, addr, width, count, buffer);
3884 if (retval != ERROR_OK) {
3885 /* BOO !*/
3886 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3887 (unsigned int)addr,
3888 (int)width,
3889 (int)count);
3890 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3891 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3892 e = JIM_ERR;
3893 break;
3897 free(buffer);
3899 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3901 return e;
3904 /* FIX? should we propagate errors here rather than printing them
3905 * and continuing?
3907 void target_handle_event(struct target *target, enum target_event e)
3909 struct target_event_action *teap;
3911 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3912 if (teap->event == e) {
3913 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3914 target->target_number,
3915 target_name(target),
3916 target_type_name(target),
3918 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3919 Jim_GetString(teap->body, NULL));
3920 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
3921 Jim_MakeErrorMessage(teap->interp);
3922 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
3929 * Returns true only if the target has a handler for the specified event.
3931 bool target_has_event_action(struct target *target, enum target_event event)
3933 struct target_event_action *teap;
3935 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3936 if (teap->event == event)
3937 return true;
3939 return false;
3942 enum target_cfg_param {
3943 TCFG_TYPE,
3944 TCFG_EVENT,
3945 TCFG_WORK_AREA_VIRT,
3946 TCFG_WORK_AREA_PHYS,
3947 TCFG_WORK_AREA_SIZE,
3948 TCFG_WORK_AREA_BACKUP,
3949 TCFG_ENDIAN,
3950 TCFG_VARIANT,
3951 TCFG_COREID,
3952 TCFG_CHAIN_POSITION,
3953 TCFG_DBGBASE,
3954 TCFG_RTOS,
3957 static Jim_Nvp nvp_config_opts[] = {
3958 { .name = "-type", .value = TCFG_TYPE },
3959 { .name = "-event", .value = TCFG_EVENT },
3960 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3961 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3962 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3963 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3964 { .name = "-endian" , .value = TCFG_ENDIAN },
3965 { .name = "-variant", .value = TCFG_VARIANT },
3966 { .name = "-coreid", .value = TCFG_COREID },
3967 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3968 { .name = "-dbgbase", .value = TCFG_DBGBASE },
3969 { .name = "-rtos", .value = TCFG_RTOS },
3970 { .name = NULL, .value = -1 }
3973 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3975 Jim_Nvp *n;
3976 Jim_Obj *o;
3977 jim_wide w;
3978 char *cp;
3979 int e;
3981 /* parse config or cget options ... */
3982 while (goi->argc > 0) {
3983 Jim_SetEmptyResult(goi->interp);
3984 /* Jim_GetOpt_Debug(goi); */
3986 if (target->type->target_jim_configure) {
3987 /* target defines a configure function */
3988 /* target gets first dibs on parameters */
3989 e = (*(target->type->target_jim_configure))(target, goi);
3990 if (e == JIM_OK) {
3991 /* more? */
3992 continue;
3994 if (e == JIM_ERR) {
3995 /* An error */
3996 return e;
3998 /* otherwise we 'continue' below */
4000 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
4001 if (e != JIM_OK) {
4002 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
4003 return e;
4005 switch (n->value) {
4006 case TCFG_TYPE:
4007 /* not setable */
4008 if (goi->isconfigure) {
4009 Jim_SetResultFormatted(goi->interp,
4010 "not settable: %s", n->name);
4011 return JIM_ERR;
4012 } else {
4013 no_params:
4014 if (goi->argc != 0) {
4015 Jim_WrongNumArgs(goi->interp,
4016 goi->argc, goi->argv,
4017 "NO PARAMS");
4018 return JIM_ERR;
4021 Jim_SetResultString(goi->interp,
4022 target_type_name(target), -1);
4023 /* loop for more */
4024 break;
4025 case TCFG_EVENT:
4026 if (goi->argc == 0) {
4027 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4028 return JIM_ERR;
4031 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4032 if (e != JIM_OK) {
4033 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4034 return e;
4037 if (goi->isconfigure) {
4038 if (goi->argc != 1) {
4039 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4040 return JIM_ERR;
4042 } else {
4043 if (goi->argc != 0) {
4044 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4045 return JIM_ERR;
4050 struct target_event_action *teap;
4052 teap = target->event_action;
4053 /* replace existing? */
4054 while (teap) {
4055 if (teap->event == (enum target_event)n->value)
4056 break;
4057 teap = teap->next;
4060 if (goi->isconfigure) {
4061 bool replace = true;
4062 if (teap == NULL) {
4063 /* create new */
4064 teap = calloc(1, sizeof(*teap));
4065 replace = false;
4067 teap->event = n->value;
4068 teap->interp = goi->interp;
4069 Jim_GetOpt_Obj(goi, &o);
4070 if (teap->body)
4071 Jim_DecrRefCount(teap->interp, teap->body);
4072 teap->body = Jim_DuplicateObj(goi->interp, o);
4074 * FIXME:
4075 * Tcl/TK - "tk events" have a nice feature.
4076 * See the "BIND" command.
4077 * We should support that here.
4078 * You can specify %X and %Y in the event code.
4079 * The idea is: %T - target name.
4080 * The idea is: %N - target number
4081 * The idea is: %E - event name.
4083 Jim_IncrRefCount(teap->body);
4085 if (!replace) {
4086 /* add to head of event list */
4087 teap->next = target->event_action;
4088 target->event_action = teap;
4090 Jim_SetEmptyResult(goi->interp);
4091 } else {
4092 /* get */
4093 if (teap == NULL)
4094 Jim_SetEmptyResult(goi->interp);
4095 else
4096 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4099 /* loop for more */
4100 break;
4102 case TCFG_WORK_AREA_VIRT:
4103 if (goi->isconfigure) {
4104 target_free_all_working_areas(target);
4105 e = Jim_GetOpt_Wide(goi, &w);
4106 if (e != JIM_OK)
4107 return e;
4108 target->working_area_virt = w;
4109 target->working_area_virt_spec = true;
4110 } else {
4111 if (goi->argc != 0)
4112 goto no_params;
4114 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4115 /* loop for more */
4116 break;
4118 case TCFG_WORK_AREA_PHYS:
4119 if (goi->isconfigure) {
4120 target_free_all_working_areas(target);
4121 e = Jim_GetOpt_Wide(goi, &w);
4122 if (e != JIM_OK)
4123 return e;
4124 target->working_area_phys = w;
4125 target->working_area_phys_spec = true;
4126 } else {
4127 if (goi->argc != 0)
4128 goto no_params;
4130 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4131 /* loop for more */
4132 break;
4134 case TCFG_WORK_AREA_SIZE:
4135 if (goi->isconfigure) {
4136 target_free_all_working_areas(target);
4137 e = Jim_GetOpt_Wide(goi, &w);
4138 if (e != JIM_OK)
4139 return e;
4140 target->working_area_size = w;
4141 } else {
4142 if (goi->argc != 0)
4143 goto no_params;
4145 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4146 /* loop for more */
4147 break;
4149 case TCFG_WORK_AREA_BACKUP:
4150 if (goi->isconfigure) {
4151 target_free_all_working_areas(target);
4152 e = Jim_GetOpt_Wide(goi, &w);
4153 if (e != JIM_OK)
4154 return e;
4155 /* make this exactly 1 or 0 */
4156 target->backup_working_area = (!!w);
4157 } else {
4158 if (goi->argc != 0)
4159 goto no_params;
4161 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4162 /* loop for more e*/
4163 break;
4166 case TCFG_ENDIAN:
4167 if (goi->isconfigure) {
4168 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4169 if (e != JIM_OK) {
4170 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4171 return e;
4173 target->endianness = n->value;
4174 } else {
4175 if (goi->argc != 0)
4176 goto no_params;
4178 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4179 if (n->name == NULL) {
4180 target->endianness = TARGET_LITTLE_ENDIAN;
4181 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4183 Jim_SetResultString(goi->interp, n->name, -1);
4184 /* loop for more */
4185 break;
4187 case TCFG_VARIANT:
4188 if (goi->isconfigure) {
4189 if (goi->argc < 1) {
4190 Jim_SetResultFormatted(goi->interp,
4191 "%s ?STRING?",
4192 n->name);
4193 return JIM_ERR;
4195 if (target->variant)
4196 free((void *)(target->variant));
4197 e = Jim_GetOpt_String(goi, &cp, NULL);
4198 if (e != JIM_OK)
4199 return e;
4200 target->variant = strdup(cp);
4201 } else {
4202 if (goi->argc != 0)
4203 goto no_params;
4205 Jim_SetResultString(goi->interp, target->variant, -1);
4206 /* loop for more */
4207 break;
4209 case TCFG_COREID:
4210 if (goi->isconfigure) {
4211 e = Jim_GetOpt_Wide(goi, &w);
4212 if (e != JIM_OK)
4213 return e;
4214 target->coreid = (int32_t)w;
4215 } else {
4216 if (goi->argc != 0)
4217 goto no_params;
4219 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4220 /* loop for more */
4221 break;
4223 case TCFG_CHAIN_POSITION:
4224 if (goi->isconfigure) {
4225 Jim_Obj *o_t;
4226 struct jtag_tap *tap;
4227 target_free_all_working_areas(target);
4228 e = Jim_GetOpt_Obj(goi, &o_t);
4229 if (e != JIM_OK)
4230 return e;
4231 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4232 if (tap == NULL)
4233 return JIM_ERR;
4234 /* make this exactly 1 or 0 */
4235 target->tap = tap;
4236 } else {
4237 if (goi->argc != 0)
4238 goto no_params;
4240 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4241 /* loop for more e*/
4242 break;
4243 case TCFG_DBGBASE:
4244 if (goi->isconfigure) {
4245 e = Jim_GetOpt_Wide(goi, &w);
4246 if (e != JIM_OK)
4247 return e;
4248 target->dbgbase = (uint32_t)w;
4249 target->dbgbase_set = true;
4250 } else {
4251 if (goi->argc != 0)
4252 goto no_params;
4254 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4255 /* loop for more */
4256 break;
4258 case TCFG_RTOS:
4259 /* RTOS */
4261 int result = rtos_create(goi, target);
4262 if (result != JIM_OK)
4263 return result;
4265 /* loop for more */
4266 break;
4268 } /* while (goi->argc) */
4271 /* done - we return */
4272 return JIM_OK;
4275 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4277 Jim_GetOptInfo goi;
4279 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4280 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4281 int need_args = 1 + goi.isconfigure;
4282 if (goi.argc < need_args) {
4283 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4284 goi.isconfigure
4285 ? "missing: -option VALUE ..."
4286 : "missing: -option ...");
4287 return JIM_ERR;
4289 struct target *target = Jim_CmdPrivData(goi.interp);
4290 return target_configure(&goi, target);
4293 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4295 const char *cmd_name = Jim_GetString(argv[0], NULL);
4297 Jim_GetOptInfo goi;
4298 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4300 if (goi.argc < 2 || goi.argc > 4) {
4301 Jim_SetResultFormatted(goi.interp,
4302 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4303 return JIM_ERR;
4306 target_write_fn fn;
4307 fn = target_write_memory_fast;
4309 int e;
4310 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4311 /* consume it */
4312 struct Jim_Obj *obj;
4313 e = Jim_GetOpt_Obj(&goi, &obj);
4314 if (e != JIM_OK)
4315 return e;
4317 fn = target_write_phys_memory;
4320 jim_wide a;
4321 e = Jim_GetOpt_Wide(&goi, &a);
4322 if (e != JIM_OK)
4323 return e;
4325 jim_wide b;
4326 e = Jim_GetOpt_Wide(&goi, &b);
4327 if (e != JIM_OK)
4328 return e;
4330 jim_wide c = 1;
4331 if (goi.argc == 1) {
4332 e = Jim_GetOpt_Wide(&goi, &c);
4333 if (e != JIM_OK)
4334 return e;
4337 /* all args must be consumed */
4338 if (goi.argc != 0)
4339 return JIM_ERR;
4341 struct target *target = Jim_CmdPrivData(goi.interp);
4342 unsigned data_size;
4343 if (strcasecmp(cmd_name, "mww") == 0)
4344 data_size = 4;
4345 else if (strcasecmp(cmd_name, "mwh") == 0)
4346 data_size = 2;
4347 else if (strcasecmp(cmd_name, "mwb") == 0)
4348 data_size = 1;
4349 else {
4350 LOG_ERROR("command '%s' unknown: ", cmd_name);
4351 return JIM_ERR;
4354 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4358 * @brief Reads an array of words/halfwords/bytes from target memory starting at specified address.
4360 * Usage: mdw [phys] <address> [<count>] - for 32 bit reads
4361 * mdh [phys] <address> [<count>] - for 16 bit reads
4362 * mdb [phys] <address> [<count>] - for 8 bit reads
4364 * Count defaults to 1.
4366 * Calls target_read_memory or target_read_phys_memory depending on
4367 * the presence of the "phys" argument
4368 * Reads the target memory in blocks of max. 32 bytes, and returns an array of ints formatted
4369 * to int representation in base16.
4370 * Also outputs read data in a human readable form using command_print
4372 * @param phys if present target_read_phys_memory will be used instead of target_read_memory
4373 * @param address address where to start the read. May be specified in decimal or hex using the standard "0x" prefix
4374 * @param count optional count parameter to read an array of values. If not specified, defaults to 1.
4375 * @returns: JIM_ERR on error or JIM_OK on success and sets the result string to an array of ascii formatted numbers
4376 * on success, with [<count>] number of elements.
4378 * In case of little endian target:
4379 * Example1: "mdw 0x00000000" returns "10123456"
4380 * Exmaple2: "mdh 0x00000000 1" returns "3456"
4381 * Example3: "mdb 0x00000000" returns "56"
4382 * Example4: "mdh 0x00000000 2" returns "3456 1012"
4383 * Example5: "mdb 0x00000000 3" returns "56 34 12"
4385 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4387 const char *cmd_name = Jim_GetString(argv[0], NULL);
4389 Jim_GetOptInfo goi;
4390 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4392 if ((goi.argc < 1) || (goi.argc > 3)) {
4393 Jim_SetResultFormatted(goi.interp,
4394 "usage: %s [phys] <address> [<count>]", cmd_name);
4395 return JIM_ERR;
4398 int (*fn)(struct target *target,
4399 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4400 fn = target_read_memory;
4402 int e;
4403 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4404 /* consume it */
4405 struct Jim_Obj *obj;
4406 e = Jim_GetOpt_Obj(&goi, &obj);
4407 if (e != JIM_OK)
4408 return e;
4410 fn = target_read_phys_memory;
4413 /* Read address parameter */
4414 jim_wide addr;
4415 e = Jim_GetOpt_Wide(&goi, &addr);
4416 if (e != JIM_OK)
4417 return JIM_ERR;
4419 /* If next parameter exists, read it out as the count parameter, if not, set it to 1 (default) */
4420 jim_wide count;
4421 if (goi.argc == 1) {
4422 e = Jim_GetOpt_Wide(&goi, &count);
4423 if (e != JIM_OK)
4424 return JIM_ERR;
4425 } else
4426 count = 1;
4428 /* all args must be consumed */
4429 if (goi.argc != 0)
4430 return JIM_ERR;
4432 jim_wide dwidth = 1; /* shut up gcc */
4433 if (strcasecmp(cmd_name, "mdw") == 0)
4434 dwidth = 4;
4435 else if (strcasecmp(cmd_name, "mdh") == 0)
4436 dwidth = 2;
4437 else if (strcasecmp(cmd_name, "mdb") == 0)
4438 dwidth = 1;
4439 else {
4440 LOG_ERROR("command '%s' unknown: ", cmd_name);
4441 return JIM_ERR;
4444 /* convert count to "bytes" */
4445 int bytes = count * dwidth;
4447 struct target *target = Jim_CmdPrivData(goi.interp);
4448 uint8_t target_buf[32];
4449 jim_wide x, y, z;
4450 while (bytes > 0) {
4451 y = (bytes < 16) ? bytes : 16; /* y = min(bytes, 16); */
4453 /* Try to read out next block */
4454 e = fn(target, addr, dwidth, y / dwidth, target_buf);
4456 if (e != ERROR_OK) {
4457 Jim_SetResultFormatted(interp, "error reading target @ 0x%08lx", (long)addr);
4458 return JIM_ERR;
4461 command_print_sameline(NULL, "0x%08x ", (int)(addr));
4462 switch (dwidth) {
4463 case 4:
4464 for (x = 0; x < 16 && x < y; x += 4) {
4465 z = target_buffer_get_u32(target, &(target_buf[x]));
4466 command_print_sameline(NULL, "%08x ", (int)(z));
4468 for (; (x < 16) ; x += 4)
4469 command_print_sameline(NULL, " ");
4470 break;
4471 case 2:
4472 for (x = 0; x < 16 && x < y; x += 2) {
4473 z = target_buffer_get_u16(target, &(target_buf[x]));
4474 command_print_sameline(NULL, "%04x ", (int)(z));
4476 for (; (x < 16) ; x += 2)
4477 command_print_sameline(NULL, " ");
4478 break;
4479 case 1:
4480 default:
4481 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4482 z = target_buffer_get_u8(target, &(target_buf[x]));
4483 command_print_sameline(NULL, "%02x ", (int)(z));
4485 for (; (x < 16) ; x += 1)
4486 command_print_sameline(NULL, " ");
4487 break;
4489 /* ascii-ify the bytes */
4490 for (x = 0 ; x < y ; x++) {
4491 if ((target_buf[x] >= 0x20) &&
4492 (target_buf[x] <= 0x7e)) {
4493 /* good */
4494 } else {
4495 /* smack it */
4496 target_buf[x] = '.';
4499 /* space pad */
4500 while (x < 16) {
4501 target_buf[x] = ' ';
4502 x++;
4504 /* terminate */
4505 target_buf[16] = 0;
4506 /* print - with a newline */
4507 command_print_sameline(NULL, "%s\n", target_buf);
4508 /* NEXT... */
4509 bytes -= 16;
4510 addr += 16;
4512 return JIM_OK;
4515 static int jim_target_mem2array(Jim_Interp *interp,
4516 int argc, Jim_Obj *const *argv)
4518 struct target *target = Jim_CmdPrivData(interp);
4519 return target_mem2array(interp, target, argc - 1, argv + 1);
4522 static int jim_target_array2mem(Jim_Interp *interp,
4523 int argc, Jim_Obj *const *argv)
4525 struct target *target = Jim_CmdPrivData(interp);
4526 return target_array2mem(interp, target, argc - 1, argv + 1);
4529 static int jim_target_tap_disabled(Jim_Interp *interp)
4531 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4532 return JIM_ERR;
4535 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4537 if (argc != 1) {
4538 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4539 return JIM_ERR;
4541 struct target *target = Jim_CmdPrivData(interp);
4542 if (!target->tap->enabled)
4543 return jim_target_tap_disabled(interp);
4545 int e = target->type->examine(target);
4546 if (e != ERROR_OK)
4547 return JIM_ERR;
4548 return JIM_OK;
4551 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4553 if (argc != 1) {
4554 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4555 return JIM_ERR;
4557 struct target *target = Jim_CmdPrivData(interp);
4559 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4560 return JIM_ERR;
4562 return JIM_OK;
4565 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4567 if (argc != 1) {
4568 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4569 return JIM_ERR;
4571 struct target *target = Jim_CmdPrivData(interp);
4572 if (!target->tap->enabled)
4573 return jim_target_tap_disabled(interp);
4575 int e;
4576 if (!(target_was_examined(target)))
4577 e = ERROR_TARGET_NOT_EXAMINED;
4578 else
4579 e = target->type->poll(target);
4580 if (e != ERROR_OK)
4581 return JIM_ERR;
4582 return JIM_OK;
4585 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4587 Jim_GetOptInfo goi;
4588 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4590 if (goi.argc != 2) {
4591 Jim_WrongNumArgs(interp, 0, argv,
4592 "([tT]|[fF]|assert|deassert) BOOL");
4593 return JIM_ERR;
4596 Jim_Nvp *n;
4597 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4598 if (e != JIM_OK) {
4599 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4600 return e;
4602 /* the halt or not param */
4603 jim_wide a;
4604 e = Jim_GetOpt_Wide(&goi, &a);
4605 if (e != JIM_OK)
4606 return e;
4608 struct target *target = Jim_CmdPrivData(goi.interp);
4609 if (!target->tap->enabled)
4610 return jim_target_tap_disabled(interp);
4611 if (!(target_was_examined(target))) {
4612 LOG_ERROR("Target not examined yet");
4613 return ERROR_TARGET_NOT_EXAMINED;
4615 if (!target->type->assert_reset || !target->type->deassert_reset) {
4616 Jim_SetResultFormatted(interp,
4617 "No target-specific reset for %s",
4618 target_name(target));
4619 return JIM_ERR;
4621 /* determine if we should halt or not. */
4622 target->reset_halt = !!a;
4623 /* When this happens - all workareas are invalid. */
4624 target_free_all_working_areas_restore(target, 0);
4626 /* do the assert */
4627 if (n->value == NVP_ASSERT)
4628 e = target->type->assert_reset(target);
4629 else
4630 e = target->type->deassert_reset(target);
4631 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4634 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4636 if (argc != 1) {
4637 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4638 return JIM_ERR;
4640 struct target *target = Jim_CmdPrivData(interp);
4641 if (!target->tap->enabled)
4642 return jim_target_tap_disabled(interp);
4643 int e = target->type->halt(target);
4644 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4647 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4649 Jim_GetOptInfo goi;
4650 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4652 /* params: <name> statename timeoutmsecs */
4653 if (goi.argc != 2) {
4654 const char *cmd_name = Jim_GetString(argv[0], NULL);
4655 Jim_SetResultFormatted(goi.interp,
4656 "%s <state_name> <timeout_in_msec>", cmd_name);
4657 return JIM_ERR;
4660 Jim_Nvp *n;
4661 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4662 if (e != JIM_OK) {
4663 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
4664 return e;
4666 jim_wide a;
4667 e = Jim_GetOpt_Wide(&goi, &a);
4668 if (e != JIM_OK)
4669 return e;
4670 struct target *target = Jim_CmdPrivData(interp);
4671 if (!target->tap->enabled)
4672 return jim_target_tap_disabled(interp);
4674 e = target_wait_state(target, n->value, a);
4675 if (e != ERROR_OK) {
4676 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4677 Jim_SetResultFormatted(goi.interp,
4678 "target: %s wait %s fails (%#s) %s",
4679 target_name(target), n->name,
4680 eObj, target_strerror_safe(e));
4681 Jim_FreeNewObj(interp, eObj);
4682 return JIM_ERR;
4684 return JIM_OK;
4686 /* List for human, Events defined for this target.
4687 * scripts/programs should use 'name cget -event NAME'
4689 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4691 struct command_context *cmd_ctx = current_command_context(interp);
4692 assert(cmd_ctx != NULL);
4694 struct target *target = Jim_CmdPrivData(interp);
4695 struct target_event_action *teap = target->event_action;
4696 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4697 target->target_number,
4698 target_name(target));
4699 command_print(cmd_ctx, "%-25s | Body", "Event");
4700 command_print(cmd_ctx, "------------------------- | "
4701 "----------------------------------------");
4702 while (teap) {
4703 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4704 command_print(cmd_ctx, "%-25s | %s",
4705 opt->name, Jim_GetString(teap->body, NULL));
4706 teap = teap->next;
4708 command_print(cmd_ctx, "***END***");
4709 return JIM_OK;
4711 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4713 if (argc != 1) {
4714 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4715 return JIM_ERR;
4717 struct target *target = Jim_CmdPrivData(interp);
4718 Jim_SetResultString(interp, target_state_name(target), -1);
4719 return JIM_OK;
4721 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4723 Jim_GetOptInfo goi;
4724 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4725 if (goi.argc != 1) {
4726 const char *cmd_name = Jim_GetString(argv[0], NULL);
4727 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4728 return JIM_ERR;
4730 Jim_Nvp *n;
4731 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4732 if (e != JIM_OK) {
4733 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4734 return e;
4736 struct target *target = Jim_CmdPrivData(interp);
4737 target_handle_event(target, n->value);
4738 return JIM_OK;
4741 static const struct command_registration target_instance_command_handlers[] = {
4743 .name = "configure",
4744 .mode = COMMAND_CONFIG,
4745 .jim_handler = jim_target_configure,
4746 .help = "configure a new target for use",
4747 .usage = "[target_attribute ...]",
4750 .name = "cget",
4751 .mode = COMMAND_ANY,
4752 .jim_handler = jim_target_configure,
4753 .help = "returns the specified target attribute",
4754 .usage = "target_attribute",
4757 .name = "mww",
4758 .mode = COMMAND_EXEC,
4759 .jim_handler = jim_target_mw,
4760 .help = "Write 32-bit word(s) to target memory",
4761 .usage = "address data [count]",
4764 .name = "mwh",
4765 .mode = COMMAND_EXEC,
4766 .jim_handler = jim_target_mw,
4767 .help = "Write 16-bit half-word(s) to target memory",
4768 .usage = "address data [count]",
4771 .name = "mwb",
4772 .mode = COMMAND_EXEC,
4773 .jim_handler = jim_target_mw,
4774 .help = "Write byte(s) to target memory",
4775 .usage = "address data [count]",
4778 .name = "mdw",
4779 .mode = COMMAND_EXEC,
4780 .jim_handler = jim_target_md,
4781 .help = "Display target memory as 32-bit words",
4782 .usage = "address [count]",
4785 .name = "mdh",
4786 .mode = COMMAND_EXEC,
4787 .jim_handler = jim_target_md,
4788 .help = "Display target memory as 16-bit half-words",
4789 .usage = "address [count]",
4792 .name = "mdb",
4793 .mode = COMMAND_EXEC,
4794 .jim_handler = jim_target_md,
4795 .help = "Display target memory as 8-bit bytes",
4796 .usage = "address [count]",
4799 .name = "array2mem",
4800 .mode = COMMAND_EXEC,
4801 .jim_handler = jim_target_array2mem,
4802 .help = "Writes Tcl array of 8/16/32 bit numbers "
4803 "to target memory",
4804 .usage = "arrayname bitwidth address count",
4807 .name = "mem2array",
4808 .mode = COMMAND_EXEC,
4809 .jim_handler = jim_target_mem2array,
4810 .help = "Loads Tcl array of 8/16/32 bit numbers "
4811 "from target memory",
4812 .usage = "arrayname bitwidth address count",
4815 .name = "eventlist",
4816 .mode = COMMAND_EXEC,
4817 .jim_handler = jim_target_event_list,
4818 .help = "displays a table of events defined for this target",
4821 .name = "curstate",
4822 .mode = COMMAND_EXEC,
4823 .jim_handler = jim_target_current_state,
4824 .help = "displays the current state of this target",
4827 .name = "arp_examine",
4828 .mode = COMMAND_EXEC,
4829 .jim_handler = jim_target_examine,
4830 .help = "used internally for reset processing",
4833 .name = "arp_halt_gdb",
4834 .mode = COMMAND_EXEC,
4835 .jim_handler = jim_target_halt_gdb,
4836 .help = "used internally for reset processing to halt GDB",
4839 .name = "arp_poll",
4840 .mode = COMMAND_EXEC,
4841 .jim_handler = jim_target_poll,
4842 .help = "used internally for reset processing",
4845 .name = "arp_reset",
4846 .mode = COMMAND_EXEC,
4847 .jim_handler = jim_target_reset,
4848 .help = "used internally for reset processing",
4851 .name = "arp_halt",
4852 .mode = COMMAND_EXEC,
4853 .jim_handler = jim_target_halt,
4854 .help = "used internally for reset processing",
4857 .name = "arp_waitstate",
4858 .mode = COMMAND_EXEC,
4859 .jim_handler = jim_target_wait_state,
4860 .help = "used internally for reset processing",
4863 .name = "invoke-event",
4864 .mode = COMMAND_EXEC,
4865 .jim_handler = jim_target_invoke_event,
4866 .help = "invoke handler for specified event",
4867 .usage = "event_name",
4869 COMMAND_REGISTRATION_DONE
4872 static int target_create(Jim_GetOptInfo *goi)
4874 Jim_Obj *new_cmd;
4875 Jim_Cmd *cmd;
4876 const char *cp;
4877 char *cp2;
4878 int e;
4879 int x;
4880 struct target *target;
4881 struct command_context *cmd_ctx;
4883 cmd_ctx = current_command_context(goi->interp);
4884 assert(cmd_ctx != NULL);
4886 if (goi->argc < 3) {
4887 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4888 return JIM_ERR;
4891 /* COMMAND */
4892 Jim_GetOpt_Obj(goi, &new_cmd);
4893 /* does this command exist? */
4894 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4895 if (cmd) {
4896 cp = Jim_GetString(new_cmd, NULL);
4897 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
4898 return JIM_ERR;
4901 /* TYPE */
4902 e = Jim_GetOpt_String(goi, &cp2, NULL);
4903 if (e != JIM_OK)
4904 return e;
4905 cp = cp2;
4906 /* now does target type exist */
4907 for (x = 0 ; target_types[x] ; x++) {
4908 if (0 == strcmp(cp, target_types[x]->name)) {
4909 /* found */
4910 break;
4913 if (target_types[x] == NULL) {
4914 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
4915 for (x = 0 ; target_types[x] ; x++) {
4916 if (target_types[x + 1]) {
4917 Jim_AppendStrings(goi->interp,
4918 Jim_GetResult(goi->interp),
4919 target_types[x]->name,
4920 ", ", NULL);
4921 } else {
4922 Jim_AppendStrings(goi->interp,
4923 Jim_GetResult(goi->interp),
4924 " or ",
4925 target_types[x]->name, NULL);
4928 return JIM_ERR;
4931 /* Create it */
4932 target = calloc(1, sizeof(struct target));
4933 /* set target number */
4934 target->target_number = new_target_number();
4936 /* allocate memory for each unique target type */
4937 target->type = (struct target_type *)calloc(1, sizeof(struct target_type));
4939 memcpy(target->type, target_types[x], sizeof(struct target_type));
4941 /* will be set by "-endian" */
4942 target->endianness = TARGET_ENDIAN_UNKNOWN;
4944 /* default to first core, override with -coreid */
4945 target->coreid = 0;
4947 target->working_area = 0x0;
4948 target->working_area_size = 0x0;
4949 target->working_areas = NULL;
4950 target->backup_working_area = 0;
4952 target->state = TARGET_UNKNOWN;
4953 target->debug_reason = DBG_REASON_UNDEFINED;
4954 target->reg_cache = NULL;
4955 target->breakpoints = NULL;
4956 target->watchpoints = NULL;
4957 target->next = NULL;
4958 target->arch_info = NULL;
4960 target->display = 1;
4962 target->halt_issued = false;
4964 /* initialize trace information */
4965 target->trace_info = malloc(sizeof(struct trace));
4966 target->trace_info->num_trace_points = 0;
4967 target->trace_info->trace_points_size = 0;
4968 target->trace_info->trace_points = NULL;
4969 target->trace_info->trace_history_size = 0;
4970 target->trace_info->trace_history = NULL;
4971 target->trace_info->trace_history_pos = 0;
4972 target->trace_info->trace_history_overflowed = 0;
4974 target->dbgmsg = NULL;
4975 target->dbg_msg_enabled = 0;
4977 target->endianness = TARGET_ENDIAN_UNKNOWN;
4979 target->rtos = NULL;
4980 target->rtos_auto_detect = false;
4982 /* Do the rest as "configure" options */
4983 goi->isconfigure = 1;
4984 e = target_configure(goi, target);
4986 if (target->tap == NULL) {
4987 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4988 e = JIM_ERR;
4991 if (e != JIM_OK) {
4992 free(target->type);
4993 free(target);
4994 return e;
4997 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4998 /* default endian to little if not specified */
4999 target->endianness = TARGET_LITTLE_ENDIAN;
5002 /* incase variant is not set */
5003 if (!target->variant)
5004 target->variant = strdup("");
5006 cp = Jim_GetString(new_cmd, NULL);
5007 target->cmd_name = strdup(cp);
5009 /* create the target specific commands */
5010 if (target->type->commands) {
5011 e = register_commands(cmd_ctx, NULL, target->type->commands);
5012 if (ERROR_OK != e)
5013 LOG_ERROR("unable to register '%s' commands", cp);
5015 if (target->type->target_create)
5016 (*(target->type->target_create))(target, goi->interp);
5018 /* append to end of list */
5020 struct target **tpp;
5021 tpp = &(all_targets);
5022 while (*tpp)
5023 tpp = &((*tpp)->next);
5024 *tpp = target;
5027 /* now - create the new target name command */
5028 const const struct command_registration target_subcommands[] = {
5030 .chain = target_instance_command_handlers,
5033 .chain = target->type->commands,
5035 COMMAND_REGISTRATION_DONE
5037 const const struct command_registration target_commands[] = {
5039 .name = cp,
5040 .mode = COMMAND_ANY,
5041 .help = "target command group",
5042 .usage = "",
5043 .chain = target_subcommands,
5045 COMMAND_REGISTRATION_DONE
5047 e = register_commands(cmd_ctx, NULL, target_commands);
5048 if (ERROR_OK != e)
5049 return JIM_ERR;
5051 struct command *c = command_find_in_context(cmd_ctx, cp);
5052 assert(c);
5053 command_set_handler_data(c, target);
5055 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5058 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5060 if (argc != 1) {
5061 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5062 return JIM_ERR;
5064 struct command_context *cmd_ctx = current_command_context(interp);
5065 assert(cmd_ctx != NULL);
5067 Jim_SetResultString(interp, get_current_target(cmd_ctx)->cmd_name, -1);
5068 return JIM_OK;
5071 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5073 if (argc != 1) {
5074 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5075 return JIM_ERR;
5077 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5078 for (unsigned x = 0; NULL != target_types[x]; x++) {
5079 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5080 Jim_NewStringObj(interp, target_types[x]->name, -1));
5082 return JIM_OK;
5085 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5087 if (argc != 1) {
5088 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5089 return JIM_ERR;
5091 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5092 struct target *target = all_targets;
5093 while (target) {
5094 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5095 Jim_NewStringObj(interp, target_name(target), -1));
5096 target = target->next;
5098 return JIM_OK;
5101 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5103 int i;
5104 const char *targetname;
5105 int retval, len;
5106 struct target *target = (struct target *) NULL;
5107 struct target_list *head, *curr, *new;
5108 curr = (struct target_list *) NULL;
5109 head = (struct target_list *) NULL;
5111 retval = 0;
5112 LOG_DEBUG("%d", argc);
5113 /* argv[1] = target to associate in smp
5114 * argv[2] = target to assoicate in smp
5115 * argv[3] ...
5118 for (i = 1; i < argc; i++) {
5120 targetname = Jim_GetString(argv[i], &len);
5121 target = get_target(targetname);
5122 LOG_DEBUG("%s ", targetname);
5123 if (target) {
5124 new = malloc(sizeof(struct target_list));
5125 new->target = target;
5126 new->next = (struct target_list *)NULL;
5127 if (head == (struct target_list *)NULL) {
5128 head = new;
5129 curr = head;
5130 } else {
5131 curr->next = new;
5132 curr = new;
5136 /* now parse the list of cpu and put the target in smp mode*/
5137 curr = head;
5139 while (curr != (struct target_list *)NULL) {
5140 target = curr->target;
5141 target->smp = 1;
5142 target->head = head;
5143 curr = curr->next;
5146 if (target && target->rtos)
5147 retval = rtos_smp_init(head->target);
5149 return retval;
5153 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5155 Jim_GetOptInfo goi;
5156 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5157 if (goi.argc < 3) {
5158 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5159 "<name> <target_type> [<target_options> ...]");
5160 return JIM_ERR;
5162 return target_create(&goi);
5165 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5167 Jim_GetOptInfo goi;
5168 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5170 /* It's OK to remove this mechanism sometime after August 2010 or so */
5171 LOG_WARNING("don't use numbers as target identifiers; use names");
5172 if (goi.argc != 1) {
5173 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
5174 return JIM_ERR;
5176 jim_wide w;
5177 int e = Jim_GetOpt_Wide(&goi, &w);
5178 if (e != JIM_OK)
5179 return JIM_ERR;
5181 struct target *target;
5182 for (target = all_targets; NULL != target; target = target->next) {
5183 if (target->target_number != w)
5184 continue;
5186 Jim_SetResultString(goi.interp, target_name(target), -1);
5187 return JIM_OK;
5190 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
5191 Jim_SetResultFormatted(goi.interp,
5192 "Target: number %#s does not exist", wObj);
5193 Jim_FreeNewObj(interp, wObj);
5195 return JIM_ERR;
5198 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5200 if (argc != 1) {
5201 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
5202 return JIM_ERR;
5204 unsigned count = 0;
5205 struct target *target = all_targets;
5206 while (NULL != target) {
5207 target = target->next;
5208 count++;
5210 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
5211 return JIM_OK;
5214 static const struct command_registration target_subcommand_handlers[] = {
5216 .name = "init",
5217 .mode = COMMAND_CONFIG,
5218 .handler = handle_target_init_command,
5219 .help = "initialize targets",
5222 .name = "create",
5223 /* REVISIT this should be COMMAND_CONFIG ... */
5224 .mode = COMMAND_ANY,
5225 .jim_handler = jim_target_create,
5226 .usage = "name type '-chain-position' name [options ...]",
5227 .help = "Creates and selects a new target",
5230 .name = "current",
5231 .mode = COMMAND_ANY,
5232 .jim_handler = jim_target_current,
5233 .help = "Returns the currently selected target",
5236 .name = "types",
5237 .mode = COMMAND_ANY,
5238 .jim_handler = jim_target_types,
5239 .help = "Returns the available target types as "
5240 "a list of strings",
5243 .name = "names",
5244 .mode = COMMAND_ANY,
5245 .jim_handler = jim_target_names,
5246 .help = "Returns the names of all targets as a list of strings",
5249 .name = "number",
5250 .mode = COMMAND_ANY,
5251 .jim_handler = jim_target_number,
5252 .usage = "number",
5253 .help = "Returns the name of the numbered target "
5254 "(DEPRECATED)",
5257 .name = "count",
5258 .mode = COMMAND_ANY,
5259 .jim_handler = jim_target_count,
5260 .help = "Returns the number of targets as an integer "
5261 "(DEPRECATED)",
5264 .name = "smp",
5265 .mode = COMMAND_ANY,
5266 .jim_handler = jim_target_smp,
5267 .usage = "targetname1 targetname2 ...",
5268 .help = "gather several target in a smp list"
5271 COMMAND_REGISTRATION_DONE
5274 struct FastLoad {
5275 uint32_t address;
5276 uint8_t *data;
5277 int length;
5281 static int fastload_num;
5282 static struct FastLoad *fastload;
5284 static void free_fastload(void)
5286 if (fastload != NULL) {
5287 int i;
5288 for (i = 0; i < fastload_num; i++) {
5289 if (fastload[i].data)
5290 free(fastload[i].data);
5292 free(fastload);
5293 fastload = NULL;
5297 COMMAND_HANDLER(handle_fast_load_image_command)
5299 uint8_t *buffer;
5300 size_t buf_cnt;
5301 uint32_t image_size;
5302 uint32_t min_address = 0;
5303 uint32_t max_address = 0xffffffff;
5304 int i;
5306 struct image image;
5308 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5309 &image, &min_address, &max_address);
5310 if (ERROR_OK != retval)
5311 return retval;
5313 struct duration bench;
5314 duration_start(&bench);
5316 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5317 if (retval != ERROR_OK)
5318 return retval;
5320 image_size = 0x0;
5321 retval = ERROR_OK;
5322 fastload_num = image.num_sections;
5323 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
5324 if (fastload == NULL) {
5325 command_print(CMD_CTX, "out of memory");
5326 image_close(&image);
5327 return ERROR_FAIL;
5329 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5330 for (i = 0; i < image.num_sections; i++) {
5331 buffer = malloc(image.sections[i].size);
5332 if (buffer == NULL) {
5333 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5334 (int)(image.sections[i].size));
5335 retval = ERROR_FAIL;
5336 break;
5339 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5340 if (retval != ERROR_OK) {
5341 free(buffer);
5342 break;
5345 uint32_t offset = 0;
5346 uint32_t length = buf_cnt;
5348 /* DANGER!!! beware of unsigned comparision here!!! */
5350 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5351 (image.sections[i].base_address < max_address)) {
5352 if (image.sections[i].base_address < min_address) {
5353 /* clip addresses below */
5354 offset += min_address-image.sections[i].base_address;
5355 length -= offset;
5358 if (image.sections[i].base_address + buf_cnt > max_address)
5359 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5361 fastload[i].address = image.sections[i].base_address + offset;
5362 fastload[i].data = malloc(length);
5363 if (fastload[i].data == NULL) {
5364 free(buffer);
5365 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5366 length);
5367 retval = ERROR_FAIL;
5368 break;
5370 memcpy(fastload[i].data, buffer + offset, length);
5371 fastload[i].length = length;
5373 image_size += length;
5374 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5375 (unsigned int)length,
5376 ((unsigned int)(image.sections[i].base_address + offset)));
5379 free(buffer);
5382 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5383 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5384 "in %fs (%0.3f KiB/s)", image_size,
5385 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5387 command_print(CMD_CTX,
5388 "WARNING: image has not been loaded to target!"
5389 "You can issue a 'fast_load' to finish loading.");
5392 image_close(&image);
5394 if (retval != ERROR_OK)
5395 free_fastload();
5397 return retval;
5400 COMMAND_HANDLER(handle_fast_load_command)
5402 if (CMD_ARGC > 0)
5403 return ERROR_COMMAND_SYNTAX_ERROR;
5404 if (fastload == NULL) {
5405 LOG_ERROR("No image in memory");
5406 return ERROR_FAIL;
5408 int i;
5409 int ms = timeval_ms();
5410 int size = 0;
5411 int retval = ERROR_OK;
5412 for (i = 0; i < fastload_num; i++) {
5413 struct target *target = get_current_target(CMD_CTX);
5414 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5415 (unsigned int)(fastload[i].address),
5416 (unsigned int)(fastload[i].length));
5417 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5418 if (retval != ERROR_OK)
5419 break;
5420 size += fastload[i].length;
5422 if (retval == ERROR_OK) {
5423 int after = timeval_ms();
5424 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5426 return retval;
5429 static const struct command_registration target_command_handlers[] = {
5431 .name = "targets",
5432 .handler = handle_targets_command,
5433 .mode = COMMAND_ANY,
5434 .help = "change current default target (one parameter) "
5435 "or prints table of all targets (no parameters)",
5436 .usage = "[target]",
5439 .name = "target",
5440 .mode = COMMAND_CONFIG,
5441 .help = "configure target",
5443 .chain = target_subcommand_handlers,
5445 COMMAND_REGISTRATION_DONE
5448 int target_register_commands(struct command_context *cmd_ctx)
5450 return register_commands(cmd_ctx, NULL, target_command_handlers);
5453 static bool target_reset_nag = true;
5455 bool get_target_reset_nag(void)
5457 return target_reset_nag;
5460 COMMAND_HANDLER(handle_target_reset_nag)
5462 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5463 &target_reset_nag, "Nag after each reset about options to improve "
5464 "performance");
5467 COMMAND_HANDLER(handle_ps_command)
5469 struct target *target = get_current_target(CMD_CTX);
5470 char *display;
5471 if (target->state != TARGET_HALTED) {
5472 LOG_INFO("target not halted !!");
5473 return ERROR_OK;
5476 if ((target->rtos) && (target->rtos->type)
5477 && (target->rtos->type->ps_command)) {
5478 display = target->rtos->type->ps_command(target);
5479 command_print(CMD_CTX, "%s", display);
5480 free(display);
5481 return ERROR_OK;
5482 } else {
5483 LOG_INFO("failed");
5484 return ERROR_TARGET_FAILURE;
5488 static const struct command_registration target_exec_command_handlers[] = {
5490 .name = "fast_load_image",
5491 .handler = handle_fast_load_image_command,
5492 .mode = COMMAND_ANY,
5493 .help = "Load image into server memory for later use by "
5494 "fast_load; primarily for profiling",
5495 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5496 "[min_address [max_length]]",
5499 .name = "fast_load",
5500 .handler = handle_fast_load_command,
5501 .mode = COMMAND_EXEC,
5502 .help = "loads active fast load image to current target "
5503 "- mainly for profiling purposes",
5504 .usage = "",
5507 .name = "profile",
5508 .handler = handle_profile_command,
5509 .mode = COMMAND_EXEC,
5510 .usage = "seconds filename",
5511 .help = "profiling samples the CPU PC",
5513 /** @todo don't register virt2phys() unless target supports it */
5515 .name = "virt2phys",
5516 .handler = handle_virt2phys_command,
5517 .mode = COMMAND_ANY,
5518 .help = "translate a virtual address into a physical address",
5519 .usage = "virtual_address",
5522 .name = "reg",
5523 .handler = handle_reg_command,
5524 .mode = COMMAND_EXEC,
5525 .help = "display or set a register; with no arguments, "
5526 "displays all registers and their values",
5527 .usage = "[(register_name|register_number) [value]]",
5530 .name = "poll",
5531 .handler = handle_poll_command,
5532 .mode = COMMAND_EXEC,
5533 .help = "poll target state; or reconfigure background polling",
5534 .usage = "['on'|'off']",
5537 .name = "wait_halt",
5538 .handler = handle_wait_halt_command,
5539 .mode = COMMAND_EXEC,
5540 .help = "wait up to the specified number of milliseconds "
5541 "(default 5) for a previously requested halt",
5542 .usage = "[milliseconds]",
5545 .name = "halt",
5546 .handler = handle_halt_command,
5547 .mode = COMMAND_EXEC,
5548 .help = "request target to halt, then wait up to the specified"
5549 "number of milliseconds (default 5) for it to complete",
5550 .usage = "[milliseconds]",
5553 .name = "resume",
5554 .handler = handle_resume_command,
5555 .mode = COMMAND_EXEC,
5556 .help = "resume target execution from current PC or address",
5557 .usage = "[address]",
5560 .name = "reset",
5561 .handler = handle_reset_command,
5562 .mode = COMMAND_EXEC,
5563 .usage = "[run|halt|init]",
5564 .help = "Reset all targets into the specified mode."
5565 "Default reset mode is run, if not given.",
5568 .name = "soft_reset_halt",
5569 .handler = handle_soft_reset_halt_command,
5570 .mode = COMMAND_EXEC,
5571 .usage = "",
5572 .help = "halt the target and do a soft reset",
5575 .name = "step",
5576 .handler = handle_step_command,
5577 .mode = COMMAND_EXEC,
5578 .help = "step one instruction from current PC or address",
5579 .usage = "[address]",
5582 .name = "mdw",
5583 .handler = handle_md_command,
5584 .mode = COMMAND_EXEC,
5585 .help = "display memory words",
5586 .usage = "['phys'] address [count]",
5589 .name = "mdh",
5590 .handler = handle_md_command,
5591 .mode = COMMAND_EXEC,
5592 .help = "display memory half-words",
5593 .usage = "['phys'] address [count]",
5596 .name = "mdb",
5597 .handler = handle_md_command,
5598 .mode = COMMAND_EXEC,
5599 .help = "display memory bytes",
5600 .usage = "['phys'] address [count]",
5603 .name = "mww",
5604 .handler = handle_mw_command,
5605 .mode = COMMAND_EXEC,
5606 .help = "write memory word",
5607 .usage = "['phys'] address value [count]",
5610 .name = "mwh",
5611 .handler = handle_mw_command,
5612 .mode = COMMAND_EXEC,
5613 .help = "write memory half-word",
5614 .usage = "['phys'] address value [count]",
5617 .name = "mwb",
5618 .handler = handle_mw_command,
5619 .mode = COMMAND_EXEC,
5620 .help = "write memory byte",
5621 .usage = "['phys'] address value [count]",
5624 .name = "bp",
5625 .handler = handle_bp_command,
5626 .mode = COMMAND_EXEC,
5627 .help = "list or set hardware or software breakpoint",
5628 .usage = "<address> [<asid>]<length> ['hw'|'hw_ctx']",
5631 .name = "rbp",
5632 .handler = handle_rbp_command,
5633 .mode = COMMAND_EXEC,
5634 .help = "remove breakpoint",
5635 .usage = "address",
5638 .name = "wp",
5639 .handler = handle_wp_command,
5640 .mode = COMMAND_EXEC,
5641 .help = "list (no params) or create watchpoints",
5642 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5645 .name = "rwp",
5646 .handler = handle_rwp_command,
5647 .mode = COMMAND_EXEC,
5648 .help = "remove watchpoint",
5649 .usage = "address",
5652 .name = "load_image",
5653 .handler = handle_load_image_command,
5654 .mode = COMMAND_EXEC,
5655 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5656 "[min_address] [max_length]",
5659 .name = "dump_image",
5660 .handler = handle_dump_image_command,
5661 .mode = COMMAND_EXEC,
5662 .usage = "filename address size",
5665 .name = "verify_image",
5666 .handler = handle_verify_image_command,
5667 .mode = COMMAND_EXEC,
5668 .usage = "filename [offset [type]]",
5671 .name = "test_image",
5672 .handler = handle_test_image_command,
5673 .mode = COMMAND_EXEC,
5674 .usage = "filename [offset [type]]",
5677 .name = "mem2array",
5678 .mode = COMMAND_EXEC,
5679 .jim_handler = jim_mem2array,
5680 .help = "read 8/16/32 bit memory and return as a TCL array "
5681 "for script processing",
5682 .usage = "arrayname bitwidth address count",
5685 .name = "array2mem",
5686 .mode = COMMAND_EXEC,
5687 .jim_handler = jim_array2mem,
5688 .help = "convert a TCL array to memory locations "
5689 "and write the 8/16/32 bit values",
5690 .usage = "arrayname bitwidth address count",
5693 .name = "reset_nag",
5694 .handler = handle_target_reset_nag,
5695 .mode = COMMAND_ANY,
5696 .help = "Nag after each reset about options that could have been "
5697 "enabled to improve performance. ",
5698 .usage = "['enable'|'disable']",
5701 .name = "ps",
5702 .handler = handle_ps_command,
5703 .mode = COMMAND_EXEC,
5704 .help = "list all tasks ",
5705 .usage = " ",
5708 COMMAND_REGISTRATION_DONE
5710 static int target_register_user_commands(struct command_context *cmd_ctx)
5712 int retval = ERROR_OK;
5713 retval = target_request_register_commands(cmd_ctx);
5714 if (retval != ERROR_OK)
5715 return retval;
5717 retval = trace_register_commands(cmd_ctx);
5718 if (retval != ERROR_OK)
5719 return retval;
5722 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);