target: enable TARGET_EVENT_RESUME_* events
[openocd/cederom.git] / src / target / target.c
blobccaa6e3943c95d83f7902c9e5108c745963e665c
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);
614 return target_examine_one(target);
618 /* Targets that correctly implement init + examine, i.e.
619 * no communication with target during init:
621 * XScale
623 int target_examine(void)
625 int retval = ERROR_OK;
626 struct target *target;
628 for (target = all_targets; target; target = target->next) {
629 /* defer examination, but don't skip it */
630 if (!target->tap->enabled) {
631 jtag_register_event_callback(jtag_enable_callback,
632 target);
633 continue;
635 retval = target_examine_one(target);
636 if (retval != ERROR_OK)
637 return retval;
639 return retval;
641 const char *target_type_name(struct target *target)
643 return target->type->name;
646 static int target_write_memory_imp(struct target *target, uint32_t address,
647 uint32_t size, uint32_t count, const uint8_t *buffer)
649 if (!target_was_examined(target)) {
650 LOG_ERROR("Target not examined yet");
651 return ERROR_FAIL;
653 return target->type->write_memory_imp(target, address, size, count, buffer);
656 static int target_read_memory_imp(struct target *target, uint32_t address,
657 uint32_t size, uint32_t count, uint8_t *buffer)
659 if (!target_was_examined(target)) {
660 LOG_ERROR("Target not examined yet");
661 return ERROR_FAIL;
663 return target->type->read_memory_imp(target, address, size, count, buffer);
666 static int target_soft_reset_halt_imp(struct target *target)
668 if (!target_was_examined(target)) {
669 LOG_ERROR("Target not examined yet");
670 return ERROR_FAIL;
672 if (!target->type->soft_reset_halt_imp) {
673 LOG_ERROR("Target %s does not support soft_reset_halt",
674 target_name(target));
675 return ERROR_FAIL;
677 return target->type->soft_reset_halt_imp(target);
681 * Downloads a target-specific native code algorithm to the target,
682 * and executes it. * Note that some targets may need to set up, enable,
683 * and tear down a breakpoint (hard or * soft) to detect algorithm
684 * termination, while others may support lower overhead schemes where
685 * soft breakpoints embedded in the algorithm automatically terminate the
686 * algorithm.
688 * @param target used to run the algorithm
689 * @param arch_info target-specific description of the algorithm.
691 int target_run_algorithm(struct target *target,
692 int num_mem_params, struct mem_param *mem_params,
693 int num_reg_params, struct reg_param *reg_param,
694 uint32_t entry_point, uint32_t exit_point,
695 int timeout_ms, void *arch_info)
697 int retval = ERROR_FAIL;
699 if (!target_was_examined(target)) {
700 LOG_ERROR("Target not examined yet");
701 goto done;
703 if (!target->type->run_algorithm) {
704 LOG_ERROR("Target type '%s' does not support %s",
705 target_type_name(target), __func__);
706 goto done;
709 target->running_alg = true;
710 retval = target->type->run_algorithm(target,
711 num_mem_params, mem_params,
712 num_reg_params, reg_param,
713 entry_point, exit_point, timeout_ms, arch_info);
714 target->running_alg = false;
716 done:
717 return retval;
721 * Downloads a target-specific native code algorithm to the target,
722 * executes and leaves it running.
724 * @param target used to run the algorithm
725 * @param arch_info target-specific description of the algorithm.
727 int target_start_algorithm(struct target *target,
728 int num_mem_params, struct mem_param *mem_params,
729 int num_reg_params, struct reg_param *reg_params,
730 uint32_t entry_point, uint32_t exit_point,
731 void *arch_info)
733 int retval = ERROR_FAIL;
735 if (!target_was_examined(target)) {
736 LOG_ERROR("Target not examined yet");
737 goto done;
739 if (!target->type->start_algorithm) {
740 LOG_ERROR("Target type '%s' does not support %s",
741 target_type_name(target), __func__);
742 goto done;
744 if (target->running_alg) {
745 LOG_ERROR("Target is already running an algorithm");
746 goto done;
749 target->running_alg = true;
750 retval = target->type->start_algorithm(target,
751 num_mem_params, mem_params,
752 num_reg_params, reg_params,
753 entry_point, exit_point, arch_info);
755 done:
756 return retval;
760 * Waits for an algorithm started with target_start_algorithm() to complete.
762 * @param target used to run the algorithm
763 * @param arch_info target-specific description of the algorithm.
765 int target_wait_algorithm(struct target *target,
766 int num_mem_params, struct mem_param *mem_params,
767 int num_reg_params, struct reg_param *reg_params,
768 uint32_t exit_point, int timeout_ms,
769 void *arch_info)
771 int retval = ERROR_FAIL;
773 if (!target->type->wait_algorithm) {
774 LOG_ERROR("Target type '%s' does not support %s",
775 target_type_name(target), __func__);
776 goto done;
778 if (!target->running_alg) {
779 LOG_ERROR("Target is not running an algorithm");
780 goto done;
783 retval = target->type->wait_algorithm(target,
784 num_mem_params, mem_params,
785 num_reg_params, reg_params,
786 exit_point, timeout_ms, arch_info);
787 if (retval != ERROR_TARGET_TIMEOUT)
788 target->running_alg = false;
790 done:
791 return retval;
795 * Executes a target-specific native code algorithm in the target.
796 * It differs from target_run_algorithm in that the algorithm is asynchronous.
797 * Because of this it requires an compliant algorithm:
798 * see contrib/loaders/flash/stm32f1x.S for example.
800 * @param target used to run the algorithm
803 int target_run_flash_async_algorithm(struct target *target,
804 uint8_t *buffer, uint32_t count, int block_size,
805 int num_mem_params, struct mem_param *mem_params,
806 int num_reg_params, struct reg_param *reg_params,
807 uint32_t buffer_start, uint32_t buffer_size,
808 uint32_t entry_point, uint32_t exit_point, void *arch_info)
810 int retval;
812 /* Set up working area. First word is write pointer, second word is read pointer,
813 * rest is fifo data area. */
814 uint32_t wp_addr = buffer_start;
815 uint32_t rp_addr = buffer_start + 4;
816 uint32_t fifo_start_addr = buffer_start + 8;
817 uint32_t fifo_end_addr = buffer_start + buffer_size;
819 uint32_t wp = fifo_start_addr;
820 uint32_t rp = fifo_start_addr;
822 /* validate block_size is 2^n */
823 assert(!block_size || !(block_size & (block_size - 1)));
825 retval = target_write_u32(target, wp_addr, wp);
826 if (retval != ERROR_OK)
827 return retval;
828 retval = target_write_u32(target, rp_addr, rp);
829 if (retval != ERROR_OK)
830 return retval;
832 /* Start up algorithm on target and let it idle while writing the first chunk */
833 retval = target_start_algorithm(target, num_mem_params, mem_params,
834 num_reg_params, reg_params,
835 entry_point,
836 exit_point,
837 arch_info);
839 if (retval != ERROR_OK) {
840 LOG_ERROR("error starting target flash write algorithm");
841 return retval;
844 while (count > 0) {
846 retval = target_read_u32(target, rp_addr, &rp);
847 if (retval != ERROR_OK) {
848 LOG_ERROR("failed to get read pointer");
849 break;
852 LOG_DEBUG("count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32, count, wp, rp);
854 if (rp == 0) {
855 LOG_ERROR("flash write algorithm aborted by target");
856 retval = ERROR_FLASH_OPERATION_FAILED;
857 break;
860 if ((rp & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
861 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
862 break;
865 /* Count the number of bytes available in the fifo without
866 * crossing the wrap around. Make sure to not fill it completely,
867 * because that would make wp == rp and that's the empty condition. */
868 uint32_t thisrun_bytes;
869 if (rp > wp)
870 thisrun_bytes = rp - wp - block_size;
871 else if (rp > fifo_start_addr)
872 thisrun_bytes = fifo_end_addr - wp;
873 else
874 thisrun_bytes = fifo_end_addr - wp - block_size;
876 if (thisrun_bytes == 0) {
877 /* Throttle polling a bit if transfer is (much) faster than flash
878 * programming. The exact delay shouldn't matter as long as it's
879 * less than buffer size / flash speed. This is very unlikely to
880 * run when using high latency connections such as USB. */
881 alive_sleep(10);
882 continue;
885 /* Limit to the amount of data we actually want to write */
886 if (thisrun_bytes > count * block_size)
887 thisrun_bytes = count * block_size;
889 /* Write data to fifo */
890 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
891 if (retval != ERROR_OK)
892 break;
894 /* Update counters and wrap write pointer */
895 buffer += thisrun_bytes;
896 count -= thisrun_bytes / block_size;
897 wp += thisrun_bytes;
898 if (wp >= fifo_end_addr)
899 wp = fifo_start_addr;
901 /* Store updated write pointer to target */
902 retval = target_write_u32(target, wp_addr, wp);
903 if (retval != ERROR_OK)
904 break;
907 if (retval != ERROR_OK) {
908 /* abort flash write algorithm on target */
909 target_write_u32(target, wp_addr, 0);
912 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
913 num_reg_params, reg_params,
914 exit_point,
915 10000,
916 arch_info);
918 if (retval2 != ERROR_OK) {
919 LOG_ERROR("error waiting for target flash write algorithm");
920 retval = retval2;
923 return retval;
926 int target_read_memory(struct target *target,
927 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
929 return target->type->read_memory(target, address, size, count, buffer);
932 static int target_read_phys_memory(struct target *target,
933 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
935 return target->type->read_phys_memory(target, address, size, count, buffer);
938 int target_write_memory(struct target *target,
939 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
941 return target->type->write_memory(target, address, size, count, buffer);
944 static int target_write_phys_memory(struct target *target,
945 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
947 return target->type->write_phys_memory(target, address, size, count, buffer);
950 int target_bulk_write_memory(struct target *target,
951 uint32_t address, uint32_t count, const uint8_t *buffer)
953 return target->type->bulk_write_memory(target, address, count, buffer);
956 int target_add_breakpoint(struct target *target,
957 struct breakpoint *breakpoint)
959 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
960 LOG_WARNING("target %s is not halted", target->cmd_name);
961 return ERROR_TARGET_NOT_HALTED;
963 return target->type->add_breakpoint(target, breakpoint);
966 int target_add_context_breakpoint(struct target *target,
967 struct breakpoint *breakpoint)
969 if (target->state != TARGET_HALTED) {
970 LOG_WARNING("target %s is not halted", target->cmd_name);
971 return ERROR_TARGET_NOT_HALTED;
973 return target->type->add_context_breakpoint(target, breakpoint);
976 int target_add_hybrid_breakpoint(struct target *target,
977 struct breakpoint *breakpoint)
979 if (target->state != TARGET_HALTED) {
980 LOG_WARNING("target %s is not halted", target->cmd_name);
981 return ERROR_TARGET_NOT_HALTED;
983 return target->type->add_hybrid_breakpoint(target, breakpoint);
986 int target_remove_breakpoint(struct target *target,
987 struct breakpoint *breakpoint)
989 return target->type->remove_breakpoint(target, breakpoint);
992 int target_add_watchpoint(struct target *target,
993 struct watchpoint *watchpoint)
995 if (target->state != TARGET_HALTED) {
996 LOG_WARNING("target %s is not halted", target->cmd_name);
997 return ERROR_TARGET_NOT_HALTED;
999 return target->type->add_watchpoint(target, watchpoint);
1001 int target_remove_watchpoint(struct target *target,
1002 struct watchpoint *watchpoint)
1004 return target->type->remove_watchpoint(target, watchpoint);
1007 int target_get_gdb_reg_list(struct target *target,
1008 struct reg **reg_list[], int *reg_list_size)
1010 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
1012 int target_step(struct target *target,
1013 int current, uint32_t address, int handle_breakpoints)
1015 return target->type->step(target, current, address, handle_breakpoints);
1019 * Reset the @c examined flag for the given target.
1020 * Pure paranoia -- targets are zeroed on allocation.
1022 static void target_reset_examined(struct target *target)
1024 target->examined = false;
1027 static int err_read_phys_memory(struct target *target, uint32_t address,
1028 uint32_t size, uint32_t count, uint8_t *buffer)
1030 LOG_ERROR("Not implemented: %s", __func__);
1031 return ERROR_FAIL;
1034 static int err_write_phys_memory(struct target *target, uint32_t address,
1035 uint32_t size, uint32_t count, const uint8_t *buffer)
1037 LOG_ERROR("Not implemented: %s", __func__);
1038 return ERROR_FAIL;
1041 static int handle_target(void *priv);
1043 static int target_init_one(struct command_context *cmd_ctx,
1044 struct target *target)
1046 target_reset_examined(target);
1048 struct target_type *type = target->type;
1049 if (type->examine == NULL)
1050 type->examine = default_examine;
1052 if (type->check_reset == NULL)
1053 type->check_reset = default_check_reset;
1055 assert(type->init_target != NULL);
1057 int retval = type->init_target(cmd_ctx, target);
1058 if (ERROR_OK != retval) {
1059 LOG_ERROR("target '%s' init failed", target_name(target));
1060 return retval;
1064 * @todo get rid of those *memory_imp() methods, now that all
1065 * callers are using target_*_memory() accessors ... and make
1066 * sure the "physical" paths handle the same issues.
1068 /* a non-invasive way(in terms of patches) to add some code that
1069 * runs before the type->write/read_memory implementation
1071 type->write_memory_imp = target->type->write_memory;
1072 type->write_memory = target_write_memory_imp;
1074 type->read_memory_imp = target->type->read_memory;
1075 type->read_memory = target_read_memory_imp;
1077 type->soft_reset_halt_imp = target->type->soft_reset_halt;
1078 type->soft_reset_halt = target_soft_reset_halt_imp;
1080 /* Sanity-check MMU support ... stub in what we must, to help
1081 * implement it in stages, but warn if we need to do so.
1083 if (type->mmu) {
1084 if (type->write_phys_memory == NULL) {
1085 LOG_ERROR("type '%s' is missing write_phys_memory",
1086 type->name);
1087 type->write_phys_memory = err_write_phys_memory;
1089 if (type->read_phys_memory == NULL) {
1090 LOG_ERROR("type '%s' is missing read_phys_memory",
1091 type->name);
1092 type->read_phys_memory = err_read_phys_memory;
1094 if (type->virt2phys == NULL) {
1095 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1096 type->virt2phys = identity_virt2phys;
1098 } else {
1099 /* Make sure no-MMU targets all behave the same: make no
1100 * distinction between physical and virtual addresses, and
1101 * ensure that virt2phys() is always an identity mapping.
1103 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1104 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1106 type->mmu = no_mmu;
1107 type->write_phys_memory = type->write_memory;
1108 type->read_phys_memory = type->read_memory;
1109 type->virt2phys = identity_virt2phys;
1112 if (target->type->read_buffer == NULL)
1113 target->type->read_buffer = target_read_buffer_default;
1115 if (target->type->write_buffer == NULL)
1116 target->type->write_buffer = target_write_buffer_default;
1118 return ERROR_OK;
1121 static int target_init(struct command_context *cmd_ctx)
1123 struct target *target;
1124 int retval;
1126 for (target = all_targets; target; target = target->next) {
1127 retval = target_init_one(cmd_ctx, target);
1128 if (ERROR_OK != retval)
1129 return retval;
1132 if (!all_targets)
1133 return ERROR_OK;
1135 retval = target_register_user_commands(cmd_ctx);
1136 if (ERROR_OK != retval)
1137 return retval;
1139 retval = target_register_timer_callback(&handle_target,
1140 polling_interval, 1, cmd_ctx->interp);
1141 if (ERROR_OK != retval)
1142 return retval;
1144 return ERROR_OK;
1147 COMMAND_HANDLER(handle_target_init_command)
1149 int retval;
1151 if (CMD_ARGC != 0)
1152 return ERROR_COMMAND_SYNTAX_ERROR;
1154 static bool target_initialized;
1155 if (target_initialized) {
1156 LOG_INFO("'target init' has already been called");
1157 return ERROR_OK;
1159 target_initialized = true;
1161 retval = command_run_line(CMD_CTX, "init_targets");
1162 if (ERROR_OK != retval)
1163 return retval;
1165 retval = command_run_line(CMD_CTX, "init_board");
1166 if (ERROR_OK != retval)
1167 return retval;
1169 LOG_DEBUG("Initializing targets...");
1170 return target_init(CMD_CTX);
1173 int target_register_event_callback(int (*callback)(struct target *target,
1174 enum target_event event, void *priv), void *priv)
1176 struct target_event_callback **callbacks_p = &target_event_callbacks;
1178 if (callback == NULL)
1179 return ERROR_COMMAND_SYNTAX_ERROR;
1181 if (*callbacks_p) {
1182 while ((*callbacks_p)->next)
1183 callbacks_p = &((*callbacks_p)->next);
1184 callbacks_p = &((*callbacks_p)->next);
1187 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1188 (*callbacks_p)->callback = callback;
1189 (*callbacks_p)->priv = priv;
1190 (*callbacks_p)->next = NULL;
1192 return ERROR_OK;
1195 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1197 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1198 struct timeval now;
1200 if (callback == NULL)
1201 return ERROR_COMMAND_SYNTAX_ERROR;
1203 if (*callbacks_p) {
1204 while ((*callbacks_p)->next)
1205 callbacks_p = &((*callbacks_p)->next);
1206 callbacks_p = &((*callbacks_p)->next);
1209 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1210 (*callbacks_p)->callback = callback;
1211 (*callbacks_p)->periodic = periodic;
1212 (*callbacks_p)->time_ms = time_ms;
1214 gettimeofday(&now, NULL);
1215 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
1216 time_ms -= (time_ms % 1000);
1217 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
1218 if ((*callbacks_p)->when.tv_usec > 1000000) {
1219 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
1220 (*callbacks_p)->when.tv_sec += 1;
1223 (*callbacks_p)->priv = priv;
1224 (*callbacks_p)->next = NULL;
1226 return ERROR_OK;
1229 int target_unregister_event_callback(int (*callback)(struct target *target,
1230 enum target_event event, void *priv), void *priv)
1232 struct target_event_callback **p = &target_event_callbacks;
1233 struct target_event_callback *c = target_event_callbacks;
1235 if (callback == NULL)
1236 return ERROR_COMMAND_SYNTAX_ERROR;
1238 while (c) {
1239 struct target_event_callback *next = c->next;
1240 if ((c->callback == callback) && (c->priv == priv)) {
1241 *p = next;
1242 free(c);
1243 return ERROR_OK;
1244 } else
1245 p = &(c->next);
1246 c = next;
1249 return ERROR_OK;
1252 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1254 struct target_timer_callback **p = &target_timer_callbacks;
1255 struct target_timer_callback *c = target_timer_callbacks;
1257 if (callback == NULL)
1258 return ERROR_COMMAND_SYNTAX_ERROR;
1260 while (c) {
1261 struct target_timer_callback *next = c->next;
1262 if ((c->callback == callback) && (c->priv == priv)) {
1263 *p = next;
1264 free(c);
1265 return ERROR_OK;
1266 } else
1267 p = &(c->next);
1268 c = next;
1271 return ERROR_OK;
1274 int target_call_event_callbacks(struct target *target, enum target_event event)
1276 struct target_event_callback *callback = target_event_callbacks;
1277 struct target_event_callback *next_callback;
1279 if (event == TARGET_EVENT_HALTED) {
1280 /* execute early halted first */
1281 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1284 LOG_DEBUG("target event %i (%s)", event,
1285 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1287 target_handle_event(target, event);
1289 while (callback) {
1290 next_callback = callback->next;
1291 callback->callback(target, event, callback->priv);
1292 callback = next_callback;
1295 return ERROR_OK;
1298 static int target_timer_callback_periodic_restart(
1299 struct target_timer_callback *cb, struct timeval *now)
1301 int time_ms = cb->time_ms;
1302 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1303 time_ms -= (time_ms % 1000);
1304 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1305 if (cb->when.tv_usec > 1000000) {
1306 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1307 cb->when.tv_sec += 1;
1309 return ERROR_OK;
1312 static int target_call_timer_callback(struct target_timer_callback *cb,
1313 struct timeval *now)
1315 cb->callback(cb->priv);
1317 if (cb->periodic)
1318 return target_timer_callback_periodic_restart(cb, now);
1320 return target_unregister_timer_callback(cb->callback, cb->priv);
1323 static int target_call_timer_callbacks_check_time(int checktime)
1325 keep_alive();
1327 struct timeval now;
1328 gettimeofday(&now, NULL);
1330 struct target_timer_callback *callback = target_timer_callbacks;
1331 while (callback) {
1332 /* cleaning up may unregister and free this callback */
1333 struct target_timer_callback *next_callback = callback->next;
1335 bool call_it = callback->callback &&
1336 ((!checktime && callback->periodic) ||
1337 now.tv_sec > callback->when.tv_sec ||
1338 (now.tv_sec == callback->when.tv_sec &&
1339 now.tv_usec >= callback->when.tv_usec));
1341 if (call_it) {
1342 int retval = target_call_timer_callback(callback, &now);
1343 if (retval != ERROR_OK)
1344 return retval;
1347 callback = next_callback;
1350 return ERROR_OK;
1353 int target_call_timer_callbacks(void)
1355 return target_call_timer_callbacks_check_time(1);
1358 /* invoke periodic callbacks immediately */
1359 int target_call_timer_callbacks_now(void)
1361 return target_call_timer_callbacks_check_time(0);
1364 /* Prints the working area layout for debug purposes */
1365 static void print_wa_layout(struct target *target)
1367 struct working_area *c = target->working_areas;
1369 while (c) {
1370 LOG_DEBUG("%c%c 0x%08"PRIx32"-0x%08"PRIx32" (%"PRIu32" bytes)",
1371 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1372 c->address, c->address + c->size - 1, c->size);
1373 c = c->next;
1377 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1378 static void target_split_working_area(struct working_area *area, uint32_t size)
1380 assert(area->free); /* Shouldn't split an allocated area */
1381 assert(size <= area->size); /* Caller should guarantee this */
1383 /* Split only if not already the right size */
1384 if (size < area->size) {
1385 struct working_area *new_wa = malloc(sizeof(*new_wa));
1387 if (new_wa == NULL)
1388 return;
1390 new_wa->next = area->next;
1391 new_wa->size = area->size - size;
1392 new_wa->address = area->address + size;
1393 new_wa->backup = NULL;
1394 new_wa->user = NULL;
1395 new_wa->free = true;
1397 area->next = new_wa;
1398 area->size = size;
1400 /* If backup memory was allocated to this area, it has the wrong size
1401 * now so free it and it will be reallocated if/when needed */
1402 if (area->backup) {
1403 free(area->backup);
1404 area->backup = NULL;
1409 /* Merge all adjacent free areas into one */
1410 static void target_merge_working_areas(struct target *target)
1412 struct working_area *c = target->working_areas;
1414 while (c && c->next) {
1415 assert(c->next->address == c->address + c->size); /* This is an invariant */
1417 /* Find two adjacent free areas */
1418 if (c->free && c->next->free) {
1419 /* Merge the last into the first */
1420 c->size += c->next->size;
1422 /* Remove the last */
1423 struct working_area *to_be_freed = c->next;
1424 c->next = c->next->next;
1425 if (to_be_freed->backup)
1426 free(to_be_freed->backup);
1427 free(to_be_freed);
1429 /* If backup memory was allocated to the remaining area, it's has
1430 * the wrong size now */
1431 if (c->backup) {
1432 free(c->backup);
1433 c->backup = NULL;
1435 } else {
1436 c = c->next;
1441 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1443 /* Reevaluate working area address based on MMU state*/
1444 if (target->working_areas == NULL) {
1445 int retval;
1446 int enabled;
1448 retval = target->type->mmu(target, &enabled);
1449 if (retval != ERROR_OK)
1450 return retval;
1452 if (!enabled) {
1453 if (target->working_area_phys_spec) {
1454 LOG_DEBUG("MMU disabled, using physical "
1455 "address for working memory 0x%08"PRIx32,
1456 target->working_area_phys);
1457 target->working_area = target->working_area_phys;
1458 } else {
1459 LOG_ERROR("No working memory available. "
1460 "Specify -work-area-phys to target.");
1461 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1463 } else {
1464 if (target->working_area_virt_spec) {
1465 LOG_DEBUG("MMU enabled, using virtual "
1466 "address for working memory 0x%08"PRIx32,
1467 target->working_area_virt);
1468 target->working_area = target->working_area_virt;
1469 } else {
1470 LOG_ERROR("No working memory available. "
1471 "Specify -work-area-virt to target.");
1472 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1476 /* Set up initial working area on first call */
1477 struct working_area *new_wa = malloc(sizeof(*new_wa));
1478 if (new_wa) {
1479 new_wa->next = NULL;
1480 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1481 new_wa->address = target->working_area;
1482 new_wa->backup = NULL;
1483 new_wa->user = NULL;
1484 new_wa->free = true;
1487 target->working_areas = new_wa;
1490 /* only allocate multiples of 4 byte */
1491 if (size % 4)
1492 size = (size + 3) & (~3UL);
1494 struct working_area *c = target->working_areas;
1496 /* Find the first large enough working area */
1497 while (c) {
1498 if (c->free && c->size >= size)
1499 break;
1500 c = c->next;
1503 if (c == NULL)
1504 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1506 /* Split the working area into the requested size */
1507 target_split_working_area(c, size);
1509 LOG_DEBUG("allocated new working area of %"PRIu32" bytes at address 0x%08"PRIx32, size, c->address);
1511 if (target->backup_working_area) {
1512 if (c->backup == NULL) {
1513 c->backup = malloc(c->size);
1514 if (c->backup == NULL)
1515 return ERROR_FAIL;
1518 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1519 if (retval != ERROR_OK)
1520 return retval;
1523 /* mark as used, and return the new (reused) area */
1524 c->free = false;
1525 *area = c;
1527 /* user pointer */
1528 c->user = area;
1530 print_wa_layout(target);
1532 return ERROR_OK;
1535 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1537 int retval;
1539 retval = target_alloc_working_area_try(target, size, area);
1540 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1541 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1542 return retval;
1546 static int target_restore_working_area(struct target *target, struct working_area *area)
1548 int retval = ERROR_OK;
1550 if (target->backup_working_area && area->backup != NULL) {
1551 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1552 if (retval != ERROR_OK)
1553 LOG_ERROR("failed to restore %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1554 area->size, area->address);
1557 return retval;
1560 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1561 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1563 int retval = ERROR_OK;
1565 if (area->free)
1566 return retval;
1568 if (restore) {
1569 retval = target_restore_working_area(target, area);
1570 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1571 if (retval != ERROR_OK)
1572 return retval;
1575 area->free = true;
1577 LOG_DEBUG("freed %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1578 area->size, area->address);
1580 /* mark user pointer invalid */
1581 /* TODO: Is this really safe? It points to some previous caller's memory.
1582 * How could we know that the area pointer is still in that place and not
1583 * some other vital data? What's the purpose of this, anyway? */
1584 *area->user = NULL;
1585 area->user = NULL;
1587 target_merge_working_areas(target);
1589 print_wa_layout(target);
1591 return retval;
1594 int target_free_working_area(struct target *target, struct working_area *area)
1596 return target_free_working_area_restore(target, area, 1);
1599 /* free resources and restore memory, if restoring memory fails,
1600 * free up resources anyway
1602 static void target_free_all_working_areas_restore(struct target *target, int restore)
1604 struct working_area *c = target->working_areas;
1606 LOG_DEBUG("freeing all working areas");
1608 /* Loop through all areas, restoring the allocated ones and marking them as free */
1609 while (c) {
1610 if (!c->free) {
1611 if (restore)
1612 target_restore_working_area(target, c);
1613 c->free = true;
1614 *c->user = NULL; /* Same as above */
1615 c->user = NULL;
1617 c = c->next;
1620 /* Run a merge pass to combine all areas into one */
1621 target_merge_working_areas(target);
1623 print_wa_layout(target);
1626 void target_free_all_working_areas(struct target *target)
1628 target_free_all_working_areas_restore(target, 1);
1631 /* Find the largest number of bytes that can be allocated */
1632 uint32_t target_get_working_area_avail(struct target *target)
1634 struct working_area *c = target->working_areas;
1635 uint32_t max_size = 0;
1637 if (c == NULL)
1638 return target->working_area_size;
1640 while (c) {
1641 if (c->free && max_size < c->size)
1642 max_size = c->size;
1644 c = c->next;
1647 return max_size;
1650 int target_arch_state(struct target *target)
1652 int retval;
1653 if (target == NULL) {
1654 LOG_USER("No target has been configured");
1655 return ERROR_OK;
1658 LOG_USER("target state: %s", target_state_name(target));
1660 if (target->state != TARGET_HALTED)
1661 return ERROR_OK;
1663 retval = target->type->arch_state(target);
1664 return retval;
1667 /* Single aligned words are guaranteed to use 16 or 32 bit access
1668 * mode respectively, otherwise data is handled as quickly as
1669 * possible
1671 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1673 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1674 (int)size, (unsigned)address);
1676 if (!target_was_examined(target)) {
1677 LOG_ERROR("Target not examined yet");
1678 return ERROR_FAIL;
1681 if (size == 0)
1682 return ERROR_OK;
1684 if ((address + size - 1) < address) {
1685 /* GDB can request this when e.g. PC is 0xfffffffc*/
1686 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1687 (unsigned)address,
1688 (unsigned)size);
1689 return ERROR_FAIL;
1692 return target->type->write_buffer(target, address, size, buffer);
1695 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1697 int retval = ERROR_OK;
1699 if (((address % 2) == 0) && (size == 2))
1700 return target_write_memory(target, address, 2, 1, buffer);
1702 /* handle unaligned head bytes */
1703 if (address % 4) {
1704 uint32_t unaligned = 4 - (address % 4);
1706 if (unaligned > size)
1707 unaligned = size;
1709 retval = target_write_memory(target, address, 1, unaligned, buffer);
1710 if (retval != ERROR_OK)
1711 return retval;
1713 buffer += unaligned;
1714 address += unaligned;
1715 size -= unaligned;
1718 /* handle aligned words */
1719 if (size >= 4) {
1720 int aligned = size - (size % 4);
1722 /* use bulk writes above a certain limit. This may have to be changed */
1723 if (aligned > 128) {
1724 retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer);
1725 if (retval != ERROR_OK)
1726 return retval;
1727 } else {
1728 retval = target_write_memory(target, address, 4, aligned / 4, buffer);
1729 if (retval != ERROR_OK)
1730 return retval;
1733 buffer += aligned;
1734 address += aligned;
1735 size -= aligned;
1738 /* handle tail writes of less than 4 bytes */
1739 if (size > 0) {
1740 retval = target_write_memory(target, address, 1, size, buffer);
1741 if (retval != ERROR_OK)
1742 return retval;
1745 return retval;
1748 /* Single aligned words are guaranteed to use 16 or 32 bit access
1749 * mode respectively, otherwise data is handled as quickly as
1750 * possible
1752 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1754 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1755 (int)size, (unsigned)address);
1757 if (!target_was_examined(target)) {
1758 LOG_ERROR("Target not examined yet");
1759 return ERROR_FAIL;
1762 if (size == 0)
1763 return ERROR_OK;
1765 if ((address + size - 1) < address) {
1766 /* GDB can request this when e.g. PC is 0xfffffffc*/
1767 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1768 address,
1769 size);
1770 return ERROR_FAIL;
1773 return target->type->read_buffer(target, address, size, buffer);
1776 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1778 int retval = ERROR_OK;
1780 if (((address % 2) == 0) && (size == 2))
1781 return target_read_memory(target, address, 2, 1, buffer);
1783 /* handle unaligned head bytes */
1784 if (address % 4) {
1785 uint32_t unaligned = 4 - (address % 4);
1787 if (unaligned > size)
1788 unaligned = size;
1790 retval = target_read_memory(target, address, 1, unaligned, buffer);
1791 if (retval != ERROR_OK)
1792 return retval;
1794 buffer += unaligned;
1795 address += unaligned;
1796 size -= unaligned;
1799 /* handle aligned words */
1800 if (size >= 4) {
1801 int aligned = size - (size % 4);
1803 retval = target_read_memory(target, address, 4, aligned / 4, buffer);
1804 if (retval != ERROR_OK)
1805 return retval;
1807 buffer += aligned;
1808 address += aligned;
1809 size -= aligned;
1812 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1813 if (size >= 2) {
1814 int aligned = size - (size % 2);
1815 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1816 if (retval != ERROR_OK)
1817 return retval;
1819 buffer += aligned;
1820 address += aligned;
1821 size -= aligned;
1823 /* handle tail writes of less than 4 bytes */
1824 if (size > 0) {
1825 retval = target_read_memory(target, address, 1, size, buffer);
1826 if (retval != ERROR_OK)
1827 return retval;
1830 return ERROR_OK;
1833 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1835 uint8_t *buffer;
1836 int retval;
1837 uint32_t i;
1838 uint32_t checksum = 0;
1839 if (!target_was_examined(target)) {
1840 LOG_ERROR("Target not examined yet");
1841 return ERROR_FAIL;
1844 retval = target->type->checksum_memory(target, address, size, &checksum);
1845 if (retval != ERROR_OK) {
1846 buffer = malloc(size);
1847 if (buffer == NULL) {
1848 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1849 return ERROR_COMMAND_SYNTAX_ERROR;
1851 retval = target_read_buffer(target, address, size, buffer);
1852 if (retval != ERROR_OK) {
1853 free(buffer);
1854 return retval;
1857 /* convert to target endianness */
1858 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
1859 uint32_t target_data;
1860 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1861 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1864 retval = image_calculate_checksum(buffer, size, &checksum);
1865 free(buffer);
1868 *crc = checksum;
1870 return retval;
1873 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1875 int retval;
1876 if (!target_was_examined(target)) {
1877 LOG_ERROR("Target not examined yet");
1878 return ERROR_FAIL;
1881 if (target->type->blank_check_memory == 0)
1882 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1884 retval = target->type->blank_check_memory(target, address, size, blank);
1886 return retval;
1889 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1891 uint8_t value_buf[4];
1892 if (!target_was_examined(target)) {
1893 LOG_ERROR("Target not examined yet");
1894 return ERROR_FAIL;
1897 int retval = target_read_memory(target, address, 4, 1, value_buf);
1899 if (retval == ERROR_OK) {
1900 *value = target_buffer_get_u32(target, value_buf);
1901 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1902 address,
1903 *value);
1904 } else {
1905 *value = 0x0;
1906 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1907 address);
1910 return retval;
1913 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1915 uint8_t value_buf[2];
1916 if (!target_was_examined(target)) {
1917 LOG_ERROR("Target not examined yet");
1918 return ERROR_FAIL;
1921 int retval = target_read_memory(target, address, 2, 1, value_buf);
1923 if (retval == ERROR_OK) {
1924 *value = target_buffer_get_u16(target, value_buf);
1925 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1926 address,
1927 *value);
1928 } else {
1929 *value = 0x0;
1930 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1931 address);
1934 return retval;
1937 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1939 int retval = target_read_memory(target, address, 1, 1, value);
1940 if (!target_was_examined(target)) {
1941 LOG_ERROR("Target not examined yet");
1942 return ERROR_FAIL;
1945 if (retval == ERROR_OK) {
1946 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1947 address,
1948 *value);
1949 } else {
1950 *value = 0x0;
1951 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1952 address);
1955 return retval;
1958 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1960 int retval;
1961 uint8_t value_buf[4];
1962 if (!target_was_examined(target)) {
1963 LOG_ERROR("Target not examined yet");
1964 return ERROR_FAIL;
1967 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1968 address,
1969 value);
1971 target_buffer_set_u32(target, value_buf, value);
1972 retval = target_write_memory(target, address, 4, 1, value_buf);
1973 if (retval != ERROR_OK)
1974 LOG_DEBUG("failed: %i", retval);
1976 return retval;
1979 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1981 int retval;
1982 uint8_t value_buf[2];
1983 if (!target_was_examined(target)) {
1984 LOG_ERROR("Target not examined yet");
1985 return ERROR_FAIL;
1988 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1989 address,
1990 value);
1992 target_buffer_set_u16(target, value_buf, value);
1993 retval = target_write_memory(target, address, 2, 1, value_buf);
1994 if (retval != ERROR_OK)
1995 LOG_DEBUG("failed: %i", retval);
1997 return retval;
2000 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
2002 int retval;
2003 if (!target_was_examined(target)) {
2004 LOG_ERROR("Target not examined yet");
2005 return ERROR_FAIL;
2008 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2009 address, value);
2011 retval = target_write_memory(target, address, 1, 1, &value);
2012 if (retval != ERROR_OK)
2013 LOG_DEBUG("failed: %i", retval);
2015 return retval;
2018 static int find_target(struct command_context *cmd_ctx, const char *name)
2020 struct target *target = get_target(name);
2021 if (target == NULL) {
2022 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2023 return ERROR_FAIL;
2025 if (!target->tap->enabled) {
2026 LOG_USER("Target: TAP %s is disabled, "
2027 "can't be the current target\n",
2028 target->tap->dotted_name);
2029 return ERROR_FAIL;
2032 cmd_ctx->current_target = target->target_number;
2033 return ERROR_OK;
2037 COMMAND_HANDLER(handle_targets_command)
2039 int retval = ERROR_OK;
2040 if (CMD_ARGC == 1) {
2041 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2042 if (retval == ERROR_OK) {
2043 /* we're done! */
2044 return retval;
2048 struct target *target = all_targets;
2049 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2050 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2051 while (target) {
2052 const char *state;
2053 char marker = ' ';
2055 if (target->tap->enabled)
2056 state = target_state_name(target);
2057 else
2058 state = "tap-disabled";
2060 if (CMD_CTX->current_target == target->target_number)
2061 marker = '*';
2063 /* keep columns lined up to match the headers above */
2064 command_print(CMD_CTX,
2065 "%2d%c %-18s %-10s %-6s %-18s %s",
2066 target->target_number,
2067 marker,
2068 target_name(target),
2069 target_type_name(target),
2070 Jim_Nvp_value2name_simple(nvp_target_endian,
2071 target->endianness)->name,
2072 target->tap->dotted_name,
2073 state);
2074 target = target->next;
2077 return retval;
2080 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2082 static int powerDropout;
2083 static int srstAsserted;
2085 static int runPowerRestore;
2086 static int runPowerDropout;
2087 static int runSrstAsserted;
2088 static int runSrstDeasserted;
2090 static int sense_handler(void)
2092 static int prevSrstAsserted;
2093 static int prevPowerdropout;
2095 int retval = jtag_power_dropout(&powerDropout);
2096 if (retval != ERROR_OK)
2097 return retval;
2099 int powerRestored;
2100 powerRestored = prevPowerdropout && !powerDropout;
2101 if (powerRestored)
2102 runPowerRestore = 1;
2104 long long current = timeval_ms();
2105 static long long lastPower;
2106 int waitMore = lastPower + 2000 > current;
2107 if (powerDropout && !waitMore) {
2108 runPowerDropout = 1;
2109 lastPower = current;
2112 retval = jtag_srst_asserted(&srstAsserted);
2113 if (retval != ERROR_OK)
2114 return retval;
2116 int srstDeasserted;
2117 srstDeasserted = prevSrstAsserted && !srstAsserted;
2119 static long long lastSrst;
2120 waitMore = lastSrst + 2000 > current;
2121 if (srstDeasserted && !waitMore) {
2122 runSrstDeasserted = 1;
2123 lastSrst = current;
2126 if (!prevSrstAsserted && srstAsserted)
2127 runSrstAsserted = 1;
2129 prevSrstAsserted = srstAsserted;
2130 prevPowerdropout = powerDropout;
2132 if (srstDeasserted || powerRestored) {
2133 /* Other than logging the event we can't do anything here.
2134 * Issuing a reset is a particularly bad idea as we might
2135 * be inside a reset already.
2139 return ERROR_OK;
2142 static int backoff_times;
2143 static int backoff_count;
2145 /* process target state changes */
2146 static int handle_target(void *priv)
2148 Jim_Interp *interp = (Jim_Interp *)priv;
2149 int retval = ERROR_OK;
2151 if (!is_jtag_poll_safe()) {
2152 /* polling is disabled currently */
2153 return ERROR_OK;
2156 /* we do not want to recurse here... */
2157 static int recursive;
2158 if (!recursive) {
2159 recursive = 1;
2160 sense_handler();
2161 /* danger! running these procedures can trigger srst assertions and power dropouts.
2162 * We need to avoid an infinite loop/recursion here and we do that by
2163 * clearing the flags after running these events.
2165 int did_something = 0;
2166 if (runSrstAsserted) {
2167 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2168 Jim_Eval(interp, "srst_asserted");
2169 did_something = 1;
2171 if (runSrstDeasserted) {
2172 Jim_Eval(interp, "srst_deasserted");
2173 did_something = 1;
2175 if (runPowerDropout) {
2176 LOG_INFO("Power dropout detected, running power_dropout proc.");
2177 Jim_Eval(interp, "power_dropout");
2178 did_something = 1;
2180 if (runPowerRestore) {
2181 Jim_Eval(interp, "power_restore");
2182 did_something = 1;
2185 if (did_something) {
2186 /* clear detect flags */
2187 sense_handler();
2190 /* clear action flags */
2192 runSrstAsserted = 0;
2193 runSrstDeasserted = 0;
2194 runPowerRestore = 0;
2195 runPowerDropout = 0;
2197 recursive = 0;
2200 if (backoff_times > backoff_count) {
2201 /* do not poll this time as we failed previously */
2202 backoff_count++;
2203 return ERROR_OK;
2205 backoff_count = 0;
2207 /* Poll targets for state changes unless that's globally disabled.
2208 * Skip targets that are currently disabled.
2210 for (struct target *target = all_targets;
2211 is_jtag_poll_safe() && target;
2212 target = target->next) {
2213 if (!target->tap->enabled)
2214 continue;
2216 /* only poll target if we've got power and srst isn't asserted */
2217 if (!powerDropout && !srstAsserted) {
2218 /* polling may fail silently until the target has been examined */
2219 retval = target_poll(target);
2220 if (retval != ERROR_OK) {
2221 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2222 if (backoff_times * polling_interval < 5000) {
2223 backoff_times *= 2;
2224 backoff_times++;
2226 LOG_USER("Polling target failed, GDB will be halted. Polling again in %dms",
2227 backoff_times * polling_interval);
2229 /* Tell GDB to halt the debugger. This allows the user to
2230 * run monitor commands to handle the situation.
2232 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2233 return retval;
2235 /* Since we succeeded, we reset backoff count */
2236 if (backoff_times > 0)
2237 LOG_USER("Polling succeeded again");
2238 backoff_times = 0;
2242 return retval;
2245 COMMAND_HANDLER(handle_reg_command)
2247 struct target *target;
2248 struct reg *reg = NULL;
2249 unsigned count = 0;
2250 char *value;
2252 LOG_DEBUG("-");
2254 target = get_current_target(CMD_CTX);
2256 /* list all available registers for the current target */
2257 if (CMD_ARGC == 0) {
2258 struct reg_cache *cache = target->reg_cache;
2260 count = 0;
2261 while (cache) {
2262 unsigned i;
2264 command_print(CMD_CTX, "===== %s", cache->name);
2266 for (i = 0, reg = cache->reg_list;
2267 i < cache->num_regs;
2268 i++, reg++, count++) {
2269 /* only print cached values if they are valid */
2270 if (reg->valid) {
2271 value = buf_to_str(reg->value,
2272 reg->size, 16);
2273 command_print(CMD_CTX,
2274 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2275 count, reg->name,
2276 reg->size, value,
2277 reg->dirty
2278 ? " (dirty)"
2279 : "");
2280 free(value);
2281 } else {
2282 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2283 count, reg->name,
2284 reg->size) ;
2287 cache = cache->next;
2290 return ERROR_OK;
2293 /* access a single register by its ordinal number */
2294 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2295 unsigned num;
2296 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2298 struct reg_cache *cache = target->reg_cache;
2299 count = 0;
2300 while (cache) {
2301 unsigned i;
2302 for (i = 0; i < cache->num_regs; i++) {
2303 if (count++ == num) {
2304 reg = &cache->reg_list[i];
2305 break;
2308 if (reg)
2309 break;
2310 cache = cache->next;
2313 if (!reg) {
2314 command_print(CMD_CTX, "%i is out of bounds, the current target "
2315 "has only %i registers (0 - %i)", num, count, count - 1);
2316 return ERROR_OK;
2318 } else {
2319 /* access a single register by its name */
2320 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2322 if (!reg) {
2323 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2324 return ERROR_OK;
2328 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2330 /* display a register */
2331 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2332 && (CMD_ARGV[1][0] <= '9')))) {
2333 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2334 reg->valid = 0;
2336 if (reg->valid == 0)
2337 reg->type->get(reg);
2338 value = buf_to_str(reg->value, reg->size, 16);
2339 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2340 free(value);
2341 return ERROR_OK;
2344 /* set register value */
2345 if (CMD_ARGC == 2) {
2346 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2347 if (buf == NULL)
2348 return ERROR_FAIL;
2349 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2351 reg->type->set(reg, buf);
2353 value = buf_to_str(reg->value, reg->size, 16);
2354 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2355 free(value);
2357 free(buf);
2359 return ERROR_OK;
2362 return ERROR_COMMAND_SYNTAX_ERROR;
2365 COMMAND_HANDLER(handle_poll_command)
2367 int retval = ERROR_OK;
2368 struct target *target = get_current_target(CMD_CTX);
2370 if (CMD_ARGC == 0) {
2371 command_print(CMD_CTX, "background polling: %s",
2372 jtag_poll_get_enabled() ? "on" : "off");
2373 command_print(CMD_CTX, "TAP: %s (%s)",
2374 target->tap->dotted_name,
2375 target->tap->enabled ? "enabled" : "disabled");
2376 if (!target->tap->enabled)
2377 return ERROR_OK;
2378 retval = target_poll(target);
2379 if (retval != ERROR_OK)
2380 return retval;
2381 retval = target_arch_state(target);
2382 if (retval != ERROR_OK)
2383 return retval;
2384 } else if (CMD_ARGC == 1) {
2385 bool enable;
2386 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2387 jtag_poll_set_enabled(enable);
2388 } else
2389 return ERROR_COMMAND_SYNTAX_ERROR;
2391 return retval;
2394 COMMAND_HANDLER(handle_wait_halt_command)
2396 if (CMD_ARGC > 1)
2397 return ERROR_COMMAND_SYNTAX_ERROR;
2399 unsigned ms = 5000;
2400 if (1 == CMD_ARGC) {
2401 int retval = parse_uint(CMD_ARGV[0], &ms);
2402 if (ERROR_OK != retval)
2403 return ERROR_COMMAND_SYNTAX_ERROR;
2404 /* convert seconds (given) to milliseconds (needed) */
2405 ms *= 1000;
2408 struct target *target = get_current_target(CMD_CTX);
2409 return target_wait_state(target, TARGET_HALTED, ms);
2412 /* wait for target state to change. The trick here is to have a low
2413 * latency for short waits and not to suck up all the CPU time
2414 * on longer waits.
2416 * After 500ms, keep_alive() is invoked
2418 int target_wait_state(struct target *target, enum target_state state, int ms)
2420 int retval;
2421 long long then = 0, cur;
2422 int once = 1;
2424 for (;;) {
2425 retval = target_poll(target);
2426 if (retval != ERROR_OK)
2427 return retval;
2428 if (target->state == state)
2429 break;
2430 cur = timeval_ms();
2431 if (once) {
2432 once = 0;
2433 then = timeval_ms();
2434 LOG_DEBUG("waiting for target %s...",
2435 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2438 if (cur-then > 500)
2439 keep_alive();
2441 if ((cur-then) > ms) {
2442 LOG_ERROR("timed out while waiting for target %s",
2443 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2444 return ERROR_FAIL;
2448 return ERROR_OK;
2451 COMMAND_HANDLER(handle_halt_command)
2453 LOG_DEBUG("-");
2455 struct target *target = get_current_target(CMD_CTX);
2456 int retval = target_halt(target);
2457 if (ERROR_OK != retval)
2458 return retval;
2460 if (CMD_ARGC == 1) {
2461 unsigned wait_local;
2462 retval = parse_uint(CMD_ARGV[0], &wait_local);
2463 if (ERROR_OK != retval)
2464 return ERROR_COMMAND_SYNTAX_ERROR;
2465 if (!wait_local)
2466 return ERROR_OK;
2469 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2472 COMMAND_HANDLER(handle_soft_reset_halt_command)
2474 struct target *target = get_current_target(CMD_CTX);
2476 LOG_USER("requesting target halt and executing a soft reset");
2478 target->type->soft_reset_halt(target);
2480 return ERROR_OK;
2483 COMMAND_HANDLER(handle_reset_command)
2485 if (CMD_ARGC > 1)
2486 return ERROR_COMMAND_SYNTAX_ERROR;
2488 enum target_reset_mode reset_mode = RESET_RUN;
2489 if (CMD_ARGC == 1) {
2490 const Jim_Nvp *n;
2491 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2492 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2493 return ERROR_COMMAND_SYNTAX_ERROR;
2494 reset_mode = n->value;
2497 /* reset *all* targets */
2498 return target_process_reset(CMD_CTX, reset_mode);
2502 COMMAND_HANDLER(handle_resume_command)
2504 int current = 1;
2505 if (CMD_ARGC > 1)
2506 return ERROR_COMMAND_SYNTAX_ERROR;
2508 struct target *target = get_current_target(CMD_CTX);
2510 /* with no CMD_ARGV, resume from current pc, addr = 0,
2511 * with one arguments, addr = CMD_ARGV[0],
2512 * handle breakpoints, not debugging */
2513 uint32_t addr = 0;
2514 if (CMD_ARGC == 1) {
2515 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2516 current = 0;
2519 return target_resume(target, current, addr, 1, 0);
2522 COMMAND_HANDLER(handle_step_command)
2524 if (CMD_ARGC > 1)
2525 return ERROR_COMMAND_SYNTAX_ERROR;
2527 LOG_DEBUG("-");
2529 /* with no CMD_ARGV, step from current pc, addr = 0,
2530 * with one argument addr = CMD_ARGV[0],
2531 * handle breakpoints, debugging */
2532 uint32_t addr = 0;
2533 int current_pc = 1;
2534 if (CMD_ARGC == 1) {
2535 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2536 current_pc = 0;
2539 struct target *target = get_current_target(CMD_CTX);
2541 return target->type->step(target, current_pc, addr, 1);
2544 static void handle_md_output(struct command_context *cmd_ctx,
2545 struct target *target, uint32_t address, unsigned size,
2546 unsigned count, const uint8_t *buffer)
2548 const unsigned line_bytecnt = 32;
2549 unsigned line_modulo = line_bytecnt / size;
2551 char output[line_bytecnt * 4 + 1];
2552 unsigned output_len = 0;
2554 const char *value_fmt;
2555 switch (size) {
2556 case 4:
2557 value_fmt = "%8.8x ";
2558 break;
2559 case 2:
2560 value_fmt = "%4.4x ";
2561 break;
2562 case 1:
2563 value_fmt = "%2.2x ";
2564 break;
2565 default:
2566 /* "can't happen", caller checked */
2567 LOG_ERROR("invalid memory read size: %u", size);
2568 return;
2571 for (unsigned i = 0; i < count; i++) {
2572 if (i % line_modulo == 0) {
2573 output_len += snprintf(output + output_len,
2574 sizeof(output) - output_len,
2575 "0x%8.8x: ",
2576 (unsigned)(address + (i*size)));
2579 uint32_t value = 0;
2580 const uint8_t *value_ptr = buffer + i * size;
2581 switch (size) {
2582 case 4:
2583 value = target_buffer_get_u32(target, value_ptr);
2584 break;
2585 case 2:
2586 value = target_buffer_get_u16(target, value_ptr);
2587 break;
2588 case 1:
2589 value = *value_ptr;
2591 output_len += snprintf(output + output_len,
2592 sizeof(output) - output_len,
2593 value_fmt, value);
2595 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2596 command_print(cmd_ctx, "%s", output);
2597 output_len = 0;
2602 COMMAND_HANDLER(handle_md_command)
2604 if (CMD_ARGC < 1)
2605 return ERROR_COMMAND_SYNTAX_ERROR;
2607 unsigned size = 0;
2608 switch (CMD_NAME[2]) {
2609 case 'w':
2610 size = 4;
2611 break;
2612 case 'h':
2613 size = 2;
2614 break;
2615 case 'b':
2616 size = 1;
2617 break;
2618 default:
2619 return ERROR_COMMAND_SYNTAX_ERROR;
2622 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2623 int (*fn)(struct target *target,
2624 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2625 if (physical) {
2626 CMD_ARGC--;
2627 CMD_ARGV++;
2628 fn = target_read_phys_memory;
2629 } else
2630 fn = target_read_memory;
2631 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2632 return ERROR_COMMAND_SYNTAX_ERROR;
2634 uint32_t address;
2635 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2637 unsigned count = 1;
2638 if (CMD_ARGC == 2)
2639 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2641 uint8_t *buffer = calloc(count, size);
2643 struct target *target = get_current_target(CMD_CTX);
2644 int retval = fn(target, address, size, count, buffer);
2645 if (ERROR_OK == retval)
2646 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2648 free(buffer);
2650 return retval;
2653 typedef int (*target_write_fn)(struct target *target,
2654 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2656 static int target_write_memory_fast(struct target *target,
2657 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
2659 return target_write_buffer(target, address, size * count, buffer);
2662 static int target_fill_mem(struct target *target,
2663 uint32_t address,
2664 target_write_fn fn,
2665 unsigned data_size,
2666 /* value */
2667 uint32_t b,
2668 /* count */
2669 unsigned c)
2671 /* We have to write in reasonably large chunks to be able
2672 * to fill large memory areas with any sane speed */
2673 const unsigned chunk_size = 16384;
2674 uint8_t *target_buf = malloc(chunk_size * data_size);
2675 if (target_buf == NULL) {
2676 LOG_ERROR("Out of memory");
2677 return ERROR_FAIL;
2680 for (unsigned i = 0; i < chunk_size; i++) {
2681 switch (data_size) {
2682 case 4:
2683 target_buffer_set_u32(target, target_buf + i * data_size, b);
2684 break;
2685 case 2:
2686 target_buffer_set_u16(target, target_buf + i * data_size, b);
2687 break;
2688 case 1:
2689 target_buffer_set_u8(target, target_buf + i * data_size, b);
2690 break;
2691 default:
2692 exit(-1);
2696 int retval = ERROR_OK;
2698 for (unsigned x = 0; x < c; x += chunk_size) {
2699 unsigned current;
2700 current = c - x;
2701 if (current > chunk_size)
2702 current = chunk_size;
2703 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2704 if (retval != ERROR_OK)
2705 break;
2706 /* avoid GDB timeouts */
2707 keep_alive();
2709 free(target_buf);
2711 return retval;
2715 COMMAND_HANDLER(handle_mw_command)
2717 if (CMD_ARGC < 2)
2718 return ERROR_COMMAND_SYNTAX_ERROR;
2719 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2720 target_write_fn fn;
2721 if (physical) {
2722 CMD_ARGC--;
2723 CMD_ARGV++;
2724 fn = target_write_phys_memory;
2725 } else
2726 fn = target_write_memory_fast;
2727 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2728 return ERROR_COMMAND_SYNTAX_ERROR;
2730 uint32_t address;
2731 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2733 uint32_t value;
2734 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2736 unsigned count = 1;
2737 if (CMD_ARGC == 3)
2738 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2740 struct target *target = get_current_target(CMD_CTX);
2741 unsigned wordsize;
2742 switch (CMD_NAME[2]) {
2743 case 'w':
2744 wordsize = 4;
2745 break;
2746 case 'h':
2747 wordsize = 2;
2748 break;
2749 case 'b':
2750 wordsize = 1;
2751 break;
2752 default:
2753 return ERROR_COMMAND_SYNTAX_ERROR;
2756 return target_fill_mem(target, address, fn, wordsize, value, count);
2759 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2760 uint32_t *min_address, uint32_t *max_address)
2762 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2763 return ERROR_COMMAND_SYNTAX_ERROR;
2765 /* a base address isn't always necessary,
2766 * default to 0x0 (i.e. don't relocate) */
2767 if (CMD_ARGC >= 2) {
2768 uint32_t addr;
2769 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2770 image->base_address = addr;
2771 image->base_address_set = 1;
2772 } else
2773 image->base_address_set = 0;
2775 image->start_address_set = 0;
2777 if (CMD_ARGC >= 4)
2778 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2779 if (CMD_ARGC == 5) {
2780 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2781 /* use size (given) to find max (required) */
2782 *max_address += *min_address;
2785 if (*min_address > *max_address)
2786 return ERROR_COMMAND_SYNTAX_ERROR;
2788 return ERROR_OK;
2791 COMMAND_HANDLER(handle_load_image_command)
2793 uint8_t *buffer;
2794 size_t buf_cnt;
2795 uint32_t image_size;
2796 uint32_t min_address = 0;
2797 uint32_t max_address = 0xffffffff;
2798 int i;
2799 struct image image;
2801 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2802 &image, &min_address, &max_address);
2803 if (ERROR_OK != retval)
2804 return retval;
2806 struct target *target = get_current_target(CMD_CTX);
2808 struct duration bench;
2809 duration_start(&bench);
2811 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2812 return ERROR_OK;
2814 image_size = 0x0;
2815 retval = ERROR_OK;
2816 for (i = 0; i < image.num_sections; i++) {
2817 buffer = malloc(image.sections[i].size);
2818 if (buffer == NULL) {
2819 command_print(CMD_CTX,
2820 "error allocating buffer for section (%d bytes)",
2821 (int)(image.sections[i].size));
2822 break;
2825 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
2826 if (retval != ERROR_OK) {
2827 free(buffer);
2828 break;
2831 uint32_t offset = 0;
2832 uint32_t length = buf_cnt;
2834 /* DANGER!!! beware of unsigned comparision here!!! */
2836 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
2837 (image.sections[i].base_address < max_address)) {
2839 if (image.sections[i].base_address < min_address) {
2840 /* clip addresses below */
2841 offset += min_address-image.sections[i].base_address;
2842 length -= offset;
2845 if (image.sections[i].base_address + buf_cnt > max_address)
2846 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2848 retval = target_write_buffer(target,
2849 image.sections[i].base_address + offset, length, buffer + offset);
2850 if (retval != ERROR_OK) {
2851 free(buffer);
2852 break;
2854 image_size += length;
2855 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2856 (unsigned int)length,
2857 image.sections[i].base_address + offset);
2860 free(buffer);
2863 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
2864 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2865 "in %fs (%0.3f KiB/s)", image_size,
2866 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2869 image_close(&image);
2871 return retval;
2875 COMMAND_HANDLER(handle_dump_image_command)
2877 struct fileio fileio;
2878 uint8_t *buffer;
2879 int retval, retvaltemp;
2880 uint32_t address, size;
2881 struct duration bench;
2882 struct target *target = get_current_target(CMD_CTX);
2884 if (CMD_ARGC != 3)
2885 return ERROR_COMMAND_SYNTAX_ERROR;
2887 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2888 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2890 uint32_t buf_size = (size > 4096) ? 4096 : size;
2891 buffer = malloc(buf_size);
2892 if (!buffer)
2893 return ERROR_FAIL;
2895 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2896 if (retval != ERROR_OK) {
2897 free(buffer);
2898 return retval;
2901 duration_start(&bench);
2903 while (size > 0) {
2904 size_t size_written;
2905 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
2906 retval = target_read_buffer(target, address, this_run_size, buffer);
2907 if (retval != ERROR_OK)
2908 break;
2910 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2911 if (retval != ERROR_OK)
2912 break;
2914 size -= this_run_size;
2915 address += this_run_size;
2918 free(buffer);
2920 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
2921 int filesize;
2922 retval = fileio_size(&fileio, &filesize);
2923 if (retval != ERROR_OK)
2924 return retval;
2925 command_print(CMD_CTX,
2926 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
2927 duration_elapsed(&bench), duration_kbps(&bench, filesize));
2930 retvaltemp = fileio_close(&fileio);
2931 if (retvaltemp != ERROR_OK)
2932 return retvaltemp;
2934 return retval;
2937 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2939 uint8_t *buffer;
2940 size_t buf_cnt;
2941 uint32_t image_size;
2942 int i;
2943 int retval;
2944 uint32_t checksum = 0;
2945 uint32_t mem_checksum = 0;
2947 struct image image;
2949 struct target *target = get_current_target(CMD_CTX);
2951 if (CMD_ARGC < 1)
2952 return ERROR_COMMAND_SYNTAX_ERROR;
2954 if (!target) {
2955 LOG_ERROR("no target selected");
2956 return ERROR_FAIL;
2959 struct duration bench;
2960 duration_start(&bench);
2962 if (CMD_ARGC >= 2) {
2963 uint32_t addr;
2964 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2965 image.base_address = addr;
2966 image.base_address_set = 1;
2967 } else {
2968 image.base_address_set = 0;
2969 image.base_address = 0x0;
2972 image.start_address_set = 0;
2974 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
2975 if (retval != ERROR_OK)
2976 return retval;
2978 image_size = 0x0;
2979 int diffs = 0;
2980 retval = ERROR_OK;
2981 for (i = 0; i < image.num_sections; i++) {
2982 buffer = malloc(image.sections[i].size);
2983 if (buffer == NULL) {
2984 command_print(CMD_CTX,
2985 "error allocating buffer for section (%d bytes)",
2986 (int)(image.sections[i].size));
2987 break;
2989 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
2990 if (retval != ERROR_OK) {
2991 free(buffer);
2992 break;
2995 if (verify) {
2996 /* calculate checksum of image */
2997 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
2998 if (retval != ERROR_OK) {
2999 free(buffer);
3000 break;
3003 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3004 if (retval != ERROR_OK) {
3005 free(buffer);
3006 break;
3009 if (checksum != mem_checksum) {
3010 /* failed crc checksum, fall back to a binary compare */
3011 uint8_t *data;
3013 if (diffs == 0)
3014 LOG_ERROR("checksum mismatch - attempting binary compare");
3016 data = (uint8_t *)malloc(buf_cnt);
3018 /* Can we use 32bit word accesses? */
3019 int size = 1;
3020 int count = buf_cnt;
3021 if ((count % 4) == 0) {
3022 size *= 4;
3023 count /= 4;
3025 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3026 if (retval == ERROR_OK) {
3027 uint32_t t;
3028 for (t = 0; t < buf_cnt; t++) {
3029 if (data[t] != buffer[t]) {
3030 command_print(CMD_CTX,
3031 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3032 diffs,
3033 (unsigned)(t + image.sections[i].base_address),
3034 data[t],
3035 buffer[t]);
3036 if (diffs++ >= 127) {
3037 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3038 free(data);
3039 free(buffer);
3040 goto done;
3043 keep_alive();
3046 free(data);
3048 } else {
3049 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3050 image.sections[i].base_address,
3051 buf_cnt);
3054 free(buffer);
3055 image_size += buf_cnt;
3057 if (diffs > 0)
3058 command_print(CMD_CTX, "No more differences found.");
3059 done:
3060 if (diffs > 0)
3061 retval = ERROR_FAIL;
3062 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3063 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3064 "in %fs (%0.3f KiB/s)", image_size,
3065 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3068 image_close(&image);
3070 return retval;
3073 COMMAND_HANDLER(handle_verify_image_command)
3075 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3078 COMMAND_HANDLER(handle_test_image_command)
3080 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3083 static int handle_bp_command_list(struct command_context *cmd_ctx)
3085 struct target *target = get_current_target(cmd_ctx);
3086 struct breakpoint *breakpoint = target->breakpoints;
3087 while (breakpoint) {
3088 if (breakpoint->type == BKPT_SOFT) {
3089 char *buf = buf_to_str(breakpoint->orig_instr,
3090 breakpoint->length, 16);
3091 command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3092 breakpoint->address,
3093 breakpoint->length,
3094 breakpoint->set, buf);
3095 free(buf);
3096 } else {
3097 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3098 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3099 breakpoint->asid,
3100 breakpoint->length, breakpoint->set);
3101 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3102 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3103 breakpoint->address,
3104 breakpoint->length, breakpoint->set);
3105 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3106 breakpoint->asid);
3107 } else
3108 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3109 breakpoint->address,
3110 breakpoint->length, breakpoint->set);
3113 breakpoint = breakpoint->next;
3115 return ERROR_OK;
3118 static int handle_bp_command_set(struct command_context *cmd_ctx,
3119 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3121 struct target *target = get_current_target(cmd_ctx);
3123 if (asid == 0) {
3124 int retval = breakpoint_add(target, addr, length, hw);
3125 if (ERROR_OK == retval)
3126 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3127 else {
3128 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3129 return retval;
3131 } else if (addr == 0) {
3132 int retval = context_breakpoint_add(target, asid, length, hw);
3133 if (ERROR_OK == retval)
3134 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3135 else {
3136 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3137 return retval;
3139 } else {
3140 int retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3141 if (ERROR_OK == retval)
3142 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3143 else {
3144 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3145 return retval;
3148 return ERROR_OK;
3151 COMMAND_HANDLER(handle_bp_command)
3153 uint32_t addr;
3154 uint32_t asid;
3155 uint32_t length;
3156 int hw = BKPT_SOFT;
3158 switch (CMD_ARGC) {
3159 case 0:
3160 return handle_bp_command_list(CMD_CTX);
3162 case 2:
3163 asid = 0;
3164 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3165 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3166 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3168 case 3:
3169 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3170 hw = BKPT_HARD;
3171 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3173 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3175 asid = 0;
3176 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3177 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3178 hw = BKPT_HARD;
3179 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3180 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3181 addr = 0;
3182 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3185 case 4:
3186 hw = BKPT_HARD;
3187 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3188 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3189 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3190 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3192 default:
3193 return ERROR_COMMAND_SYNTAX_ERROR;
3197 COMMAND_HANDLER(handle_rbp_command)
3199 if (CMD_ARGC != 1)
3200 return ERROR_COMMAND_SYNTAX_ERROR;
3202 uint32_t addr;
3203 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3205 struct target *target = get_current_target(CMD_CTX);
3206 breakpoint_remove(target, addr);
3208 return ERROR_OK;
3211 COMMAND_HANDLER(handle_wp_command)
3213 struct target *target = get_current_target(CMD_CTX);
3215 if (CMD_ARGC == 0) {
3216 struct watchpoint *watchpoint = target->watchpoints;
3218 while (watchpoint) {
3219 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3220 ", len: 0x%8.8" PRIx32
3221 ", r/w/a: %i, value: 0x%8.8" PRIx32
3222 ", mask: 0x%8.8" PRIx32,
3223 watchpoint->address,
3224 watchpoint->length,
3225 (int)watchpoint->rw,
3226 watchpoint->value,
3227 watchpoint->mask);
3228 watchpoint = watchpoint->next;
3230 return ERROR_OK;
3233 enum watchpoint_rw type = WPT_ACCESS;
3234 uint32_t addr = 0;
3235 uint32_t length = 0;
3236 uint32_t data_value = 0x0;
3237 uint32_t data_mask = 0xffffffff;
3239 switch (CMD_ARGC) {
3240 case 5:
3241 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3242 /* fall through */
3243 case 4:
3244 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3245 /* fall through */
3246 case 3:
3247 switch (CMD_ARGV[2][0]) {
3248 case 'r':
3249 type = WPT_READ;
3250 break;
3251 case 'w':
3252 type = WPT_WRITE;
3253 break;
3254 case 'a':
3255 type = WPT_ACCESS;
3256 break;
3257 default:
3258 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3259 return ERROR_COMMAND_SYNTAX_ERROR;
3261 /* fall through */
3262 case 2:
3263 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3264 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3265 break;
3267 default:
3268 return ERROR_COMMAND_SYNTAX_ERROR;
3271 int retval = watchpoint_add(target, addr, length, type,
3272 data_value, data_mask);
3273 if (ERROR_OK != retval)
3274 LOG_ERROR("Failure setting watchpoints");
3276 return retval;
3279 COMMAND_HANDLER(handle_rwp_command)
3281 if (CMD_ARGC != 1)
3282 return ERROR_COMMAND_SYNTAX_ERROR;
3284 uint32_t addr;
3285 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3287 struct target *target = get_current_target(CMD_CTX);
3288 watchpoint_remove(target, addr);
3290 return ERROR_OK;
3294 * Translate a virtual address to a physical address.
3296 * The low-level target implementation must have logged a detailed error
3297 * which is forwarded to telnet/GDB session.
3299 COMMAND_HANDLER(handle_virt2phys_command)
3301 if (CMD_ARGC != 1)
3302 return ERROR_COMMAND_SYNTAX_ERROR;
3304 uint32_t va;
3305 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3306 uint32_t pa;
3308 struct target *target = get_current_target(CMD_CTX);
3309 int retval = target->type->virt2phys(target, va, &pa);
3310 if (retval == ERROR_OK)
3311 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3313 return retval;
3316 static void writeData(FILE *f, const void *data, size_t len)
3318 size_t written = fwrite(data, 1, len, f);
3319 if (written != len)
3320 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3323 static void writeLong(FILE *f, int l)
3325 int i;
3326 for (i = 0; i < 4; i++) {
3327 char c = (l >> (i*8))&0xff;
3328 writeData(f, &c, 1);
3333 static void writeString(FILE *f, char *s)
3335 writeData(f, s, strlen(s));
3338 /* Dump a gmon.out histogram file. */
3339 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3341 uint32_t i;
3342 FILE *f = fopen(filename, "w");
3343 if (f == NULL)
3344 return;
3345 writeString(f, "gmon");
3346 writeLong(f, 0x00000001); /* Version */
3347 writeLong(f, 0); /* padding */
3348 writeLong(f, 0); /* padding */
3349 writeLong(f, 0); /* padding */
3351 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3352 writeData(f, &zero, 1);
3354 /* figure out bucket size */
3355 uint32_t min = samples[0];
3356 uint32_t max = samples[0];
3357 for (i = 0; i < sampleNum; i++) {
3358 if (min > samples[i])
3359 min = samples[i];
3360 if (max < samples[i])
3361 max = samples[i];
3364 int addressSpace = (max - min + 1);
3365 assert(addressSpace >= 2);
3367 static const uint32_t maxBuckets = 16 * 1024; /* maximum buckets. */
3368 uint32_t length = addressSpace;
3369 if (length > maxBuckets)
3370 length = maxBuckets;
3371 int *buckets = malloc(sizeof(int)*length);
3372 if (buckets == NULL) {
3373 fclose(f);
3374 return;
3376 memset(buckets, 0, sizeof(int) * length);
3377 for (i = 0; i < sampleNum; i++) {
3378 uint32_t address = samples[i];
3379 long long a = address - min;
3380 long long b = length - 1;
3381 long long c = addressSpace - 1;
3382 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3383 buckets[index_t]++;
3386 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3387 writeLong(f, min); /* low_pc */
3388 writeLong(f, max); /* high_pc */
3389 writeLong(f, length); /* # of samples */
3390 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3391 writeString(f, "seconds");
3392 for (i = 0; i < (15-strlen("seconds")); i++)
3393 writeData(f, &zero, 1);
3394 writeString(f, "s");
3396 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3398 char *data = malloc(2 * length);
3399 if (data != NULL) {
3400 for (i = 0; i < length; i++) {
3401 int val;
3402 val = buckets[i];
3403 if (val > 65535)
3404 val = 65535;
3405 data[i * 2] = val&0xff;
3406 data[i * 2 + 1] = (val >> 8) & 0xff;
3408 free(buckets);
3409 writeData(f, data, length * 2);
3410 free(data);
3411 } else
3412 free(buckets);
3414 fclose(f);
3417 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3418 * which will be used as a random sampling of PC */
3419 COMMAND_HANDLER(handle_profile_command)
3421 struct target *target = get_current_target(CMD_CTX);
3422 struct timeval timeout, now;
3424 gettimeofday(&timeout, NULL);
3425 if (CMD_ARGC != 2)
3426 return ERROR_COMMAND_SYNTAX_ERROR;
3427 unsigned offset;
3428 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3430 timeval_add_time(&timeout, offset, 0);
3433 * @todo: Some cores let us sample the PC without the
3434 * annoying halt/resume step; for example, ARMv7 PCSR.
3435 * Provide a way to use that more efficient mechanism.
3438 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3440 static const int maxSample = 10000;
3441 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3442 if (samples == NULL)
3443 return ERROR_OK;
3445 int numSamples = 0;
3446 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3447 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3449 int retval = ERROR_OK;
3450 for (;;) {
3451 target_poll(target);
3452 if (target->state == TARGET_HALTED) {
3453 uint32_t t = *((uint32_t *)reg->value);
3454 samples[numSamples++] = t;
3455 /* current pc, addr = 0, do not handle breakpoints, not debugging */
3456 retval = target_resume(target, 1, 0, 0, 0);
3457 target_poll(target);
3458 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3459 } else if (target->state == TARGET_RUNNING) {
3460 /* We want to quickly sample the PC. */
3461 retval = target_halt(target);
3462 if (retval != ERROR_OK) {
3463 free(samples);
3464 return retval;
3466 } else {
3467 command_print(CMD_CTX, "Target not halted or running");
3468 retval = ERROR_OK;
3469 break;
3471 if (retval != ERROR_OK)
3472 break;
3474 gettimeofday(&now, NULL);
3475 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec)
3476 && (now.tv_usec >= timeout.tv_usec))) {
3477 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3478 retval = target_poll(target);
3479 if (retval != ERROR_OK) {
3480 free(samples);
3481 return retval;
3483 if (target->state == TARGET_HALTED) {
3484 /* current pc, addr = 0, do not handle
3485 * breakpoints, not debugging */
3486 target_resume(target, 1, 0, 0, 0);
3488 retval = target_poll(target);
3489 if (retval != ERROR_OK) {
3490 free(samples);
3491 return retval;
3493 writeGmon(samples, numSamples, CMD_ARGV[1]);
3494 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3495 break;
3498 free(samples);
3500 return retval;
3503 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3505 char *namebuf;
3506 Jim_Obj *nameObjPtr, *valObjPtr;
3507 int result;
3509 namebuf = alloc_printf("%s(%d)", varname, idx);
3510 if (!namebuf)
3511 return JIM_ERR;
3513 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3514 valObjPtr = Jim_NewIntObj(interp, val);
3515 if (!nameObjPtr || !valObjPtr) {
3516 free(namebuf);
3517 return JIM_ERR;
3520 Jim_IncrRefCount(nameObjPtr);
3521 Jim_IncrRefCount(valObjPtr);
3522 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3523 Jim_DecrRefCount(interp, nameObjPtr);
3524 Jim_DecrRefCount(interp, valObjPtr);
3525 free(namebuf);
3526 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3527 return result;
3530 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3532 struct command_context *context;
3533 struct target *target;
3535 context = current_command_context(interp);
3536 assert(context != NULL);
3538 target = get_current_target(context);
3539 if (target == NULL) {
3540 LOG_ERROR("mem2array: no current target");
3541 return JIM_ERR;
3544 return target_mem2array(interp, target, argc - 1, argv + 1);
3547 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3549 long l;
3550 uint32_t width;
3551 int len;
3552 uint32_t addr;
3553 uint32_t count;
3554 uint32_t v;
3555 const char *varname;
3556 int n, e, retval;
3557 uint32_t i;
3559 /* argv[1] = name of array to receive the data
3560 * argv[2] = desired width
3561 * argv[3] = memory address
3562 * argv[4] = count of times to read
3564 if (argc != 4) {
3565 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3566 return JIM_ERR;
3568 varname = Jim_GetString(argv[0], &len);
3569 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3571 e = Jim_GetLong(interp, argv[1], &l);
3572 width = l;
3573 if (e != JIM_OK)
3574 return e;
3576 e = Jim_GetLong(interp, argv[2], &l);
3577 addr = l;
3578 if (e != JIM_OK)
3579 return e;
3580 e = Jim_GetLong(interp, argv[3], &l);
3581 len = l;
3582 if (e != JIM_OK)
3583 return e;
3584 switch (width) {
3585 case 8:
3586 width = 1;
3587 break;
3588 case 16:
3589 width = 2;
3590 break;
3591 case 32:
3592 width = 4;
3593 break;
3594 default:
3595 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3596 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3597 return JIM_ERR;
3599 if (len == 0) {
3600 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3601 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3602 return JIM_ERR;
3604 if ((addr + (len * width)) < addr) {
3605 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3606 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3607 return JIM_ERR;
3609 /* absurd transfer size? */
3610 if (len > 65536) {
3611 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3612 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3613 return JIM_ERR;
3616 if ((width == 1) ||
3617 ((width == 2) && ((addr & 1) == 0)) ||
3618 ((width == 4) && ((addr & 3) == 0))) {
3619 /* all is well */
3620 } else {
3621 char buf[100];
3622 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3623 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3624 addr,
3625 width);
3626 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3627 return JIM_ERR;
3630 /* Transfer loop */
3632 /* index counter */
3633 n = 0;
3635 size_t buffersize = 4096;
3636 uint8_t *buffer = malloc(buffersize);
3637 if (buffer == NULL)
3638 return JIM_ERR;
3640 /* assume ok */
3641 e = JIM_OK;
3642 while (len) {
3643 /* Slurp... in buffer size chunks */
3645 count = len; /* in objects.. */
3646 if (count > (buffersize / width))
3647 count = (buffersize / width);
3649 retval = target_read_memory(target, addr, width, count, buffer);
3650 if (retval != ERROR_OK) {
3651 /* BOO !*/
3652 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3653 (unsigned int)addr,
3654 (int)width,
3655 (int)count);
3656 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3657 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3658 e = JIM_ERR;
3659 break;
3660 } else {
3661 v = 0; /* shut up gcc */
3662 for (i = 0; i < count ; i++, n++) {
3663 switch (width) {
3664 case 4:
3665 v = target_buffer_get_u32(target, &buffer[i*width]);
3666 break;
3667 case 2:
3668 v = target_buffer_get_u16(target, &buffer[i*width]);
3669 break;
3670 case 1:
3671 v = buffer[i] & 0x0ff;
3672 break;
3674 new_int_array_element(interp, varname, n, v);
3676 len -= count;
3680 free(buffer);
3682 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3684 return e;
3687 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
3689 char *namebuf;
3690 Jim_Obj *nameObjPtr, *valObjPtr;
3691 int result;
3692 long l;
3694 namebuf = alloc_printf("%s(%d)", varname, idx);
3695 if (!namebuf)
3696 return JIM_ERR;
3698 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3699 if (!nameObjPtr) {
3700 free(namebuf);
3701 return JIM_ERR;
3704 Jim_IncrRefCount(nameObjPtr);
3705 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3706 Jim_DecrRefCount(interp, nameObjPtr);
3707 free(namebuf);
3708 if (valObjPtr == NULL)
3709 return JIM_ERR;
3711 result = Jim_GetLong(interp, valObjPtr, &l);
3712 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3713 *val = l;
3714 return result;
3717 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3719 struct command_context *context;
3720 struct target *target;
3722 context = current_command_context(interp);
3723 assert(context != NULL);
3725 target = get_current_target(context);
3726 if (target == NULL) {
3727 LOG_ERROR("array2mem: no current target");
3728 return JIM_ERR;
3731 return target_array2mem(interp, target, argc-1, argv + 1);
3734 static int target_array2mem(Jim_Interp *interp, struct target *target,
3735 int argc, Jim_Obj *const *argv)
3737 long l;
3738 uint32_t width;
3739 int len;
3740 uint32_t addr;
3741 uint32_t count;
3742 uint32_t v;
3743 const char *varname;
3744 int n, e, retval;
3745 uint32_t i;
3747 /* argv[1] = name of array to get the data
3748 * argv[2] = desired width
3749 * argv[3] = memory address
3750 * argv[4] = count to write
3752 if (argc != 4) {
3753 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3754 return JIM_ERR;
3756 varname = Jim_GetString(argv[0], &len);
3757 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3759 e = Jim_GetLong(interp, argv[1], &l);
3760 width = l;
3761 if (e != JIM_OK)
3762 return e;
3764 e = Jim_GetLong(interp, argv[2], &l);
3765 addr = l;
3766 if (e != JIM_OK)
3767 return e;
3768 e = Jim_GetLong(interp, argv[3], &l);
3769 len = l;
3770 if (e != JIM_OK)
3771 return e;
3772 switch (width) {
3773 case 8:
3774 width = 1;
3775 break;
3776 case 16:
3777 width = 2;
3778 break;
3779 case 32:
3780 width = 4;
3781 break;
3782 default:
3783 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3784 Jim_AppendStrings(interp, Jim_GetResult(interp),
3785 "Invalid width param, must be 8/16/32", NULL);
3786 return JIM_ERR;
3788 if (len == 0) {
3789 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3790 Jim_AppendStrings(interp, Jim_GetResult(interp),
3791 "array2mem: zero width read?", NULL);
3792 return JIM_ERR;
3794 if ((addr + (len * width)) < addr) {
3795 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3796 Jim_AppendStrings(interp, Jim_GetResult(interp),
3797 "array2mem: addr + len - wraps to zero?", NULL);
3798 return JIM_ERR;
3800 /* absurd transfer size? */
3801 if (len > 65536) {
3802 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3803 Jim_AppendStrings(interp, Jim_GetResult(interp),
3804 "array2mem: absurd > 64K item request", NULL);
3805 return JIM_ERR;
3808 if ((width == 1) ||
3809 ((width == 2) && ((addr & 1) == 0)) ||
3810 ((width == 4) && ((addr & 3) == 0))) {
3811 /* all is well */
3812 } else {
3813 char buf[100];
3814 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3815 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3816 (unsigned int)addr,
3817 (int)width);
3818 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3819 return JIM_ERR;
3822 /* Transfer loop */
3824 /* index counter */
3825 n = 0;
3826 /* assume ok */
3827 e = JIM_OK;
3829 size_t buffersize = 4096;
3830 uint8_t *buffer = malloc(buffersize);
3831 if (buffer == NULL)
3832 return JIM_ERR;
3834 while (len) {
3835 /* Slurp... in buffer size chunks */
3837 count = len; /* in objects.. */
3838 if (count > (buffersize / width))
3839 count = (buffersize / width);
3841 v = 0; /* shut up gcc */
3842 for (i = 0; i < count; i++, n++) {
3843 get_int_array_element(interp, varname, n, &v);
3844 switch (width) {
3845 case 4:
3846 target_buffer_set_u32(target, &buffer[i * width], v);
3847 break;
3848 case 2:
3849 target_buffer_set_u16(target, &buffer[i * width], v);
3850 break;
3851 case 1:
3852 buffer[i] = v & 0x0ff;
3853 break;
3856 len -= count;
3858 retval = target_write_memory(target, addr, width, count, buffer);
3859 if (retval != ERROR_OK) {
3860 /* BOO !*/
3861 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3862 (unsigned int)addr,
3863 (int)width,
3864 (int)count);
3865 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3866 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3867 e = JIM_ERR;
3868 break;
3872 free(buffer);
3874 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3876 return e;
3879 /* FIX? should we propagate errors here rather than printing them
3880 * and continuing?
3882 void target_handle_event(struct target *target, enum target_event e)
3884 struct target_event_action *teap;
3886 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3887 if (teap->event == e) {
3888 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3889 target->target_number,
3890 target_name(target),
3891 target_type_name(target),
3893 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3894 Jim_GetString(teap->body, NULL));
3895 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
3896 Jim_MakeErrorMessage(teap->interp);
3897 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
3904 * Returns true only if the target has a handler for the specified event.
3906 bool target_has_event_action(struct target *target, enum target_event event)
3908 struct target_event_action *teap;
3910 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3911 if (teap->event == event)
3912 return true;
3914 return false;
3917 enum target_cfg_param {
3918 TCFG_TYPE,
3919 TCFG_EVENT,
3920 TCFG_WORK_AREA_VIRT,
3921 TCFG_WORK_AREA_PHYS,
3922 TCFG_WORK_AREA_SIZE,
3923 TCFG_WORK_AREA_BACKUP,
3924 TCFG_ENDIAN,
3925 TCFG_VARIANT,
3926 TCFG_COREID,
3927 TCFG_CHAIN_POSITION,
3928 TCFG_DBGBASE,
3929 TCFG_RTOS,
3932 static Jim_Nvp nvp_config_opts[] = {
3933 { .name = "-type", .value = TCFG_TYPE },
3934 { .name = "-event", .value = TCFG_EVENT },
3935 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3936 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3937 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3938 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3939 { .name = "-endian" , .value = TCFG_ENDIAN },
3940 { .name = "-variant", .value = TCFG_VARIANT },
3941 { .name = "-coreid", .value = TCFG_COREID },
3942 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3943 { .name = "-dbgbase", .value = TCFG_DBGBASE },
3944 { .name = "-rtos", .value = TCFG_RTOS },
3945 { .name = NULL, .value = -1 }
3948 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3950 Jim_Nvp *n;
3951 Jim_Obj *o;
3952 jim_wide w;
3953 char *cp;
3954 int e;
3956 /* parse config or cget options ... */
3957 while (goi->argc > 0) {
3958 Jim_SetEmptyResult(goi->interp);
3959 /* Jim_GetOpt_Debug(goi); */
3961 if (target->type->target_jim_configure) {
3962 /* target defines a configure function */
3963 /* target gets first dibs on parameters */
3964 e = (*(target->type->target_jim_configure))(target, goi);
3965 if (e == JIM_OK) {
3966 /* more? */
3967 continue;
3969 if (e == JIM_ERR) {
3970 /* An error */
3971 return e;
3973 /* otherwise we 'continue' below */
3975 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3976 if (e != JIM_OK) {
3977 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3978 return e;
3980 switch (n->value) {
3981 case TCFG_TYPE:
3982 /* not setable */
3983 if (goi->isconfigure) {
3984 Jim_SetResultFormatted(goi->interp,
3985 "not settable: %s", n->name);
3986 return JIM_ERR;
3987 } else {
3988 no_params:
3989 if (goi->argc != 0) {
3990 Jim_WrongNumArgs(goi->interp,
3991 goi->argc, goi->argv,
3992 "NO PARAMS");
3993 return JIM_ERR;
3996 Jim_SetResultString(goi->interp,
3997 target_type_name(target), -1);
3998 /* loop for more */
3999 break;
4000 case TCFG_EVENT:
4001 if (goi->argc == 0) {
4002 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4003 return JIM_ERR;
4006 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4007 if (e != JIM_OK) {
4008 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4009 return e;
4012 if (goi->isconfigure) {
4013 if (goi->argc != 1) {
4014 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4015 return JIM_ERR;
4017 } else {
4018 if (goi->argc != 0) {
4019 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4020 return JIM_ERR;
4025 struct target_event_action *teap;
4027 teap = target->event_action;
4028 /* replace existing? */
4029 while (teap) {
4030 if (teap->event == (enum target_event)n->value)
4031 break;
4032 teap = teap->next;
4035 if (goi->isconfigure) {
4036 bool replace = true;
4037 if (teap == NULL) {
4038 /* create new */
4039 teap = calloc(1, sizeof(*teap));
4040 replace = false;
4042 teap->event = n->value;
4043 teap->interp = goi->interp;
4044 Jim_GetOpt_Obj(goi, &o);
4045 if (teap->body)
4046 Jim_DecrRefCount(teap->interp, teap->body);
4047 teap->body = Jim_DuplicateObj(goi->interp, o);
4049 * FIXME:
4050 * Tcl/TK - "tk events" have a nice feature.
4051 * See the "BIND" command.
4052 * We should support that here.
4053 * You can specify %X and %Y in the event code.
4054 * The idea is: %T - target name.
4055 * The idea is: %N - target number
4056 * The idea is: %E - event name.
4058 Jim_IncrRefCount(teap->body);
4060 if (!replace) {
4061 /* add to head of event list */
4062 teap->next = target->event_action;
4063 target->event_action = teap;
4065 Jim_SetEmptyResult(goi->interp);
4066 } else {
4067 /* get */
4068 if (teap == NULL)
4069 Jim_SetEmptyResult(goi->interp);
4070 else
4071 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4074 /* loop for more */
4075 break;
4077 case TCFG_WORK_AREA_VIRT:
4078 if (goi->isconfigure) {
4079 target_free_all_working_areas(target);
4080 e = Jim_GetOpt_Wide(goi, &w);
4081 if (e != JIM_OK)
4082 return e;
4083 target->working_area_virt = w;
4084 target->working_area_virt_spec = true;
4085 } else {
4086 if (goi->argc != 0)
4087 goto no_params;
4089 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4090 /* loop for more */
4091 break;
4093 case TCFG_WORK_AREA_PHYS:
4094 if (goi->isconfigure) {
4095 target_free_all_working_areas(target);
4096 e = Jim_GetOpt_Wide(goi, &w);
4097 if (e != JIM_OK)
4098 return e;
4099 target->working_area_phys = w;
4100 target->working_area_phys_spec = true;
4101 } else {
4102 if (goi->argc != 0)
4103 goto no_params;
4105 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4106 /* loop for more */
4107 break;
4109 case TCFG_WORK_AREA_SIZE:
4110 if (goi->isconfigure) {
4111 target_free_all_working_areas(target);
4112 e = Jim_GetOpt_Wide(goi, &w);
4113 if (e != JIM_OK)
4114 return e;
4115 target->working_area_size = w;
4116 } else {
4117 if (goi->argc != 0)
4118 goto no_params;
4120 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4121 /* loop for more */
4122 break;
4124 case TCFG_WORK_AREA_BACKUP:
4125 if (goi->isconfigure) {
4126 target_free_all_working_areas(target);
4127 e = Jim_GetOpt_Wide(goi, &w);
4128 if (e != JIM_OK)
4129 return e;
4130 /* make this exactly 1 or 0 */
4131 target->backup_working_area = (!!w);
4132 } else {
4133 if (goi->argc != 0)
4134 goto no_params;
4136 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4137 /* loop for more e*/
4138 break;
4141 case TCFG_ENDIAN:
4142 if (goi->isconfigure) {
4143 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4144 if (e != JIM_OK) {
4145 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4146 return e;
4148 target->endianness = n->value;
4149 } else {
4150 if (goi->argc != 0)
4151 goto no_params;
4153 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4154 if (n->name == NULL) {
4155 target->endianness = TARGET_LITTLE_ENDIAN;
4156 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4158 Jim_SetResultString(goi->interp, n->name, -1);
4159 /* loop for more */
4160 break;
4162 case TCFG_VARIANT:
4163 if (goi->isconfigure) {
4164 if (goi->argc < 1) {
4165 Jim_SetResultFormatted(goi->interp,
4166 "%s ?STRING?",
4167 n->name);
4168 return JIM_ERR;
4170 if (target->variant)
4171 free((void *)(target->variant));
4172 e = Jim_GetOpt_String(goi, &cp, NULL);
4173 if (e != JIM_OK)
4174 return e;
4175 target->variant = strdup(cp);
4176 } else {
4177 if (goi->argc != 0)
4178 goto no_params;
4180 Jim_SetResultString(goi->interp, target->variant, -1);
4181 /* loop for more */
4182 break;
4184 case TCFG_COREID:
4185 if (goi->isconfigure) {
4186 e = Jim_GetOpt_Wide(goi, &w);
4187 if (e != JIM_OK)
4188 return e;
4189 target->coreid = (int32_t)w;
4190 } else {
4191 if (goi->argc != 0)
4192 goto no_params;
4194 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4195 /* loop for more */
4196 break;
4198 case TCFG_CHAIN_POSITION:
4199 if (goi->isconfigure) {
4200 Jim_Obj *o_t;
4201 struct jtag_tap *tap;
4202 target_free_all_working_areas(target);
4203 e = Jim_GetOpt_Obj(goi, &o_t);
4204 if (e != JIM_OK)
4205 return e;
4206 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4207 if (tap == NULL)
4208 return JIM_ERR;
4209 /* make this exactly 1 or 0 */
4210 target->tap = tap;
4211 } else {
4212 if (goi->argc != 0)
4213 goto no_params;
4215 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4216 /* loop for more e*/
4217 break;
4218 case TCFG_DBGBASE:
4219 if (goi->isconfigure) {
4220 e = Jim_GetOpt_Wide(goi, &w);
4221 if (e != JIM_OK)
4222 return e;
4223 target->dbgbase = (uint32_t)w;
4224 target->dbgbase_set = true;
4225 } else {
4226 if (goi->argc != 0)
4227 goto no_params;
4229 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4230 /* loop for more */
4231 break;
4233 case TCFG_RTOS:
4234 /* RTOS */
4236 int result = rtos_create(goi, target);
4237 if (result != JIM_OK)
4238 return result;
4240 /* loop for more */
4241 break;
4243 } /* while (goi->argc) */
4246 /* done - we return */
4247 return JIM_OK;
4250 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4252 Jim_GetOptInfo goi;
4254 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4255 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4256 int need_args = 1 + goi.isconfigure;
4257 if (goi.argc < need_args) {
4258 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4259 goi.isconfigure
4260 ? "missing: -option VALUE ..."
4261 : "missing: -option ...");
4262 return JIM_ERR;
4264 struct target *target = Jim_CmdPrivData(goi.interp);
4265 return target_configure(&goi, target);
4268 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4270 const char *cmd_name = Jim_GetString(argv[0], NULL);
4272 Jim_GetOptInfo goi;
4273 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4275 if (goi.argc < 2 || goi.argc > 4) {
4276 Jim_SetResultFormatted(goi.interp,
4277 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4278 return JIM_ERR;
4281 target_write_fn fn;
4282 fn = target_write_memory_fast;
4284 int e;
4285 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4286 /* consume it */
4287 struct Jim_Obj *obj;
4288 e = Jim_GetOpt_Obj(&goi, &obj);
4289 if (e != JIM_OK)
4290 return e;
4292 fn = target_write_phys_memory;
4295 jim_wide a;
4296 e = Jim_GetOpt_Wide(&goi, &a);
4297 if (e != JIM_OK)
4298 return e;
4300 jim_wide b;
4301 e = Jim_GetOpt_Wide(&goi, &b);
4302 if (e != JIM_OK)
4303 return e;
4305 jim_wide c = 1;
4306 if (goi.argc == 1) {
4307 e = Jim_GetOpt_Wide(&goi, &c);
4308 if (e != JIM_OK)
4309 return e;
4312 /* all args must be consumed */
4313 if (goi.argc != 0)
4314 return JIM_ERR;
4316 struct target *target = Jim_CmdPrivData(goi.interp);
4317 unsigned data_size;
4318 if (strcasecmp(cmd_name, "mww") == 0)
4319 data_size = 4;
4320 else if (strcasecmp(cmd_name, "mwh") == 0)
4321 data_size = 2;
4322 else if (strcasecmp(cmd_name, "mwb") == 0)
4323 data_size = 1;
4324 else {
4325 LOG_ERROR("command '%s' unknown: ", cmd_name);
4326 return JIM_ERR;
4329 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4332 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4334 const char *cmd_name = Jim_GetString(argv[0], NULL);
4336 Jim_GetOptInfo goi;
4337 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4339 if ((goi.argc < 1) || (goi.argc > 3)) {
4340 Jim_SetResultFormatted(goi.interp,
4341 "usage: %s [phys] <address> [<count>]", cmd_name);
4342 return JIM_ERR;
4345 int (*fn)(struct target *target,
4346 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4347 fn = target_read_memory;
4349 int e;
4350 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4351 /* consume it */
4352 struct Jim_Obj *obj;
4353 e = Jim_GetOpt_Obj(&goi, &obj);
4354 if (e != JIM_OK)
4355 return e;
4357 fn = target_read_phys_memory;
4360 jim_wide a;
4361 e = Jim_GetOpt_Wide(&goi, &a);
4362 if (e != JIM_OK)
4363 return JIM_ERR;
4364 jim_wide c;
4365 if (goi.argc == 1) {
4366 e = Jim_GetOpt_Wide(&goi, &c);
4367 if (e != JIM_OK)
4368 return JIM_ERR;
4369 } else
4370 c = 1;
4372 /* all args must be consumed */
4373 if (goi.argc != 0)
4374 return JIM_ERR;
4376 jim_wide b = 1; /* shut up gcc */
4377 if (strcasecmp(cmd_name, "mdw") == 0)
4378 b = 4;
4379 else if (strcasecmp(cmd_name, "mdh") == 0)
4380 b = 2;
4381 else if (strcasecmp(cmd_name, "mdb") == 0)
4382 b = 1;
4383 else {
4384 LOG_ERROR("command '%s' unknown: ", cmd_name);
4385 return JIM_ERR;
4388 /* convert count to "bytes" */
4389 c = c * b;
4391 struct target *target = Jim_CmdPrivData(goi.interp);
4392 uint8_t target_buf[32];
4393 jim_wide x, y, z;
4394 while (c > 0) {
4395 y = c;
4396 if (y > 16)
4397 y = 16;
4398 e = fn(target, a, b, y / b, target_buf);
4399 if (e != ERROR_OK) {
4400 char tmp[10];
4401 snprintf(tmp, sizeof(tmp), "%08lx", (long)a);
4402 Jim_SetResultFormatted(interp, "error reading target @ 0x%s", tmp);
4403 return JIM_ERR;
4406 command_print(NULL, "0x%08x ", (int)(a));
4407 switch (b) {
4408 case 4:
4409 for (x = 0; x < 16 && x < y; x += 4) {
4410 z = target_buffer_get_u32(target, &(target_buf[x]));
4411 command_print(NULL, "%08x ", (int)(z));
4413 for (; (x < 16) ; x += 4)
4414 command_print(NULL, " ");
4415 break;
4416 case 2:
4417 for (x = 0; x < 16 && x < y; x += 2) {
4418 z = target_buffer_get_u16(target, &(target_buf[x]));
4419 command_print(NULL, "%04x ", (int)(z));
4421 for (; (x < 16) ; x += 2)
4422 command_print(NULL, " ");
4423 break;
4424 case 1:
4425 default:
4426 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4427 z = target_buffer_get_u8(target, &(target_buf[x]));
4428 command_print(NULL, "%02x ", (int)(z));
4430 for (; (x < 16) ; x += 1)
4431 command_print(NULL, " ");
4432 break;
4434 /* ascii-ify the bytes */
4435 for (x = 0 ; x < y ; x++) {
4436 if ((target_buf[x] >= 0x20) &&
4437 (target_buf[x] <= 0x7e)) {
4438 /* good */
4439 } else {
4440 /* smack it */
4441 target_buf[x] = '.';
4444 /* space pad */
4445 while (x < 16) {
4446 target_buf[x] = ' ';
4447 x++;
4449 /* terminate */
4450 target_buf[16] = 0;
4451 /* print - with a newline */
4452 command_print(NULL, "%s\n", target_buf);
4453 /* NEXT... */
4454 c -= 16;
4455 a += 16;
4457 return JIM_OK;
4460 static int jim_target_mem2array(Jim_Interp *interp,
4461 int argc, Jim_Obj *const *argv)
4463 struct target *target = Jim_CmdPrivData(interp);
4464 return target_mem2array(interp, target, argc - 1, argv + 1);
4467 static int jim_target_array2mem(Jim_Interp *interp,
4468 int argc, Jim_Obj *const *argv)
4470 struct target *target = Jim_CmdPrivData(interp);
4471 return target_array2mem(interp, target, argc - 1, argv + 1);
4474 static int jim_target_tap_disabled(Jim_Interp *interp)
4476 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4477 return JIM_ERR;
4480 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4482 if (argc != 1) {
4483 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4484 return JIM_ERR;
4486 struct target *target = Jim_CmdPrivData(interp);
4487 if (!target->tap->enabled)
4488 return jim_target_tap_disabled(interp);
4490 int e = target->type->examine(target);
4491 if (e != ERROR_OK)
4492 return JIM_ERR;
4493 return JIM_OK;
4496 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4498 if (argc != 1) {
4499 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4500 return JIM_ERR;
4502 struct target *target = Jim_CmdPrivData(interp);
4504 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4505 return JIM_ERR;
4507 return JIM_OK;
4510 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4512 if (argc != 1) {
4513 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4514 return JIM_ERR;
4516 struct target *target = Jim_CmdPrivData(interp);
4517 if (!target->tap->enabled)
4518 return jim_target_tap_disabled(interp);
4520 int e;
4521 if (!(target_was_examined(target)))
4522 e = ERROR_TARGET_NOT_EXAMINED;
4523 else
4524 e = target->type->poll(target);
4525 if (e != ERROR_OK)
4526 return JIM_ERR;
4527 return JIM_OK;
4530 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4532 Jim_GetOptInfo goi;
4533 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4535 if (goi.argc != 2) {
4536 Jim_WrongNumArgs(interp, 0, argv,
4537 "([tT]|[fF]|assert|deassert) BOOL");
4538 return JIM_ERR;
4541 Jim_Nvp *n;
4542 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4543 if (e != JIM_OK) {
4544 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4545 return e;
4547 /* the halt or not param */
4548 jim_wide a;
4549 e = Jim_GetOpt_Wide(&goi, &a);
4550 if (e != JIM_OK)
4551 return e;
4553 struct target *target = Jim_CmdPrivData(goi.interp);
4554 if (!target->tap->enabled)
4555 return jim_target_tap_disabled(interp);
4556 if (!(target_was_examined(target))) {
4557 LOG_ERROR("Target not examined yet");
4558 return ERROR_TARGET_NOT_EXAMINED;
4560 if (!target->type->assert_reset || !target->type->deassert_reset) {
4561 Jim_SetResultFormatted(interp,
4562 "No target-specific reset for %s",
4563 target_name(target));
4564 return JIM_ERR;
4566 /* determine if we should halt or not. */
4567 target->reset_halt = !!a;
4568 /* When this happens - all workareas are invalid. */
4569 target_free_all_working_areas_restore(target, 0);
4571 /* do the assert */
4572 if (n->value == NVP_ASSERT)
4573 e = target->type->assert_reset(target);
4574 else
4575 e = target->type->deassert_reset(target);
4576 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4579 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4581 if (argc != 1) {
4582 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4583 return JIM_ERR;
4585 struct target *target = Jim_CmdPrivData(interp);
4586 if (!target->tap->enabled)
4587 return jim_target_tap_disabled(interp);
4588 int e = target->type->halt(target);
4589 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4592 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4594 Jim_GetOptInfo goi;
4595 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4597 /* params: <name> statename timeoutmsecs */
4598 if (goi.argc != 2) {
4599 const char *cmd_name = Jim_GetString(argv[0], NULL);
4600 Jim_SetResultFormatted(goi.interp,
4601 "%s <state_name> <timeout_in_msec>", cmd_name);
4602 return JIM_ERR;
4605 Jim_Nvp *n;
4606 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4607 if (e != JIM_OK) {
4608 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
4609 return e;
4611 jim_wide a;
4612 e = Jim_GetOpt_Wide(&goi, &a);
4613 if (e != JIM_OK)
4614 return e;
4615 struct target *target = Jim_CmdPrivData(interp);
4616 if (!target->tap->enabled)
4617 return jim_target_tap_disabled(interp);
4619 e = target_wait_state(target, n->value, a);
4620 if (e != ERROR_OK) {
4621 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4622 Jim_SetResultFormatted(goi.interp,
4623 "target: %s wait %s fails (%#s) %s",
4624 target_name(target), n->name,
4625 eObj, target_strerror_safe(e));
4626 Jim_FreeNewObj(interp, eObj);
4627 return JIM_ERR;
4629 return JIM_OK;
4631 /* List for human, Events defined for this target.
4632 * scripts/programs should use 'name cget -event NAME'
4634 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4636 struct command_context *cmd_ctx = current_command_context(interp);
4637 assert(cmd_ctx != NULL);
4639 struct target *target = Jim_CmdPrivData(interp);
4640 struct target_event_action *teap = target->event_action;
4641 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4642 target->target_number,
4643 target_name(target));
4644 command_print(cmd_ctx, "%-25s | Body", "Event");
4645 command_print(cmd_ctx, "------------------------- | "
4646 "----------------------------------------");
4647 while (teap) {
4648 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4649 command_print(cmd_ctx, "%-25s | %s",
4650 opt->name, Jim_GetString(teap->body, NULL));
4651 teap = teap->next;
4653 command_print(cmd_ctx, "***END***");
4654 return JIM_OK;
4656 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4658 if (argc != 1) {
4659 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4660 return JIM_ERR;
4662 struct target *target = Jim_CmdPrivData(interp);
4663 Jim_SetResultString(interp, target_state_name(target), -1);
4664 return JIM_OK;
4666 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4668 Jim_GetOptInfo goi;
4669 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4670 if (goi.argc != 1) {
4671 const char *cmd_name = Jim_GetString(argv[0], NULL);
4672 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4673 return JIM_ERR;
4675 Jim_Nvp *n;
4676 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4677 if (e != JIM_OK) {
4678 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4679 return e;
4681 struct target *target = Jim_CmdPrivData(interp);
4682 target_handle_event(target, n->value);
4683 return JIM_OK;
4686 static const struct command_registration target_instance_command_handlers[] = {
4688 .name = "configure",
4689 .mode = COMMAND_CONFIG,
4690 .jim_handler = jim_target_configure,
4691 .help = "configure a new target for use",
4692 .usage = "[target_attribute ...]",
4695 .name = "cget",
4696 .mode = COMMAND_ANY,
4697 .jim_handler = jim_target_configure,
4698 .help = "returns the specified target attribute",
4699 .usage = "target_attribute",
4702 .name = "mww",
4703 .mode = COMMAND_EXEC,
4704 .jim_handler = jim_target_mw,
4705 .help = "Write 32-bit word(s) to target memory",
4706 .usage = "address data [count]",
4709 .name = "mwh",
4710 .mode = COMMAND_EXEC,
4711 .jim_handler = jim_target_mw,
4712 .help = "Write 16-bit half-word(s) to target memory",
4713 .usage = "address data [count]",
4716 .name = "mwb",
4717 .mode = COMMAND_EXEC,
4718 .jim_handler = jim_target_mw,
4719 .help = "Write byte(s) to target memory",
4720 .usage = "address data [count]",
4723 .name = "mdw",
4724 .mode = COMMAND_EXEC,
4725 .jim_handler = jim_target_md,
4726 .help = "Display target memory as 32-bit words",
4727 .usage = "address [count]",
4730 .name = "mdh",
4731 .mode = COMMAND_EXEC,
4732 .jim_handler = jim_target_md,
4733 .help = "Display target memory as 16-bit half-words",
4734 .usage = "address [count]",
4737 .name = "mdb",
4738 .mode = COMMAND_EXEC,
4739 .jim_handler = jim_target_md,
4740 .help = "Display target memory as 8-bit bytes",
4741 .usage = "address [count]",
4744 .name = "array2mem",
4745 .mode = COMMAND_EXEC,
4746 .jim_handler = jim_target_array2mem,
4747 .help = "Writes Tcl array of 8/16/32 bit numbers "
4748 "to target memory",
4749 .usage = "arrayname bitwidth address count",
4752 .name = "mem2array",
4753 .mode = COMMAND_EXEC,
4754 .jim_handler = jim_target_mem2array,
4755 .help = "Loads Tcl array of 8/16/32 bit numbers "
4756 "from target memory",
4757 .usage = "arrayname bitwidth address count",
4760 .name = "eventlist",
4761 .mode = COMMAND_EXEC,
4762 .jim_handler = jim_target_event_list,
4763 .help = "displays a table of events defined for this target",
4766 .name = "curstate",
4767 .mode = COMMAND_EXEC,
4768 .jim_handler = jim_target_current_state,
4769 .help = "displays the current state of this target",
4772 .name = "arp_examine",
4773 .mode = COMMAND_EXEC,
4774 .jim_handler = jim_target_examine,
4775 .help = "used internally for reset processing",
4778 .name = "arp_halt_gdb",
4779 .mode = COMMAND_EXEC,
4780 .jim_handler = jim_target_halt_gdb,
4781 .help = "used internally for reset processing to halt GDB",
4784 .name = "arp_poll",
4785 .mode = COMMAND_EXEC,
4786 .jim_handler = jim_target_poll,
4787 .help = "used internally for reset processing",
4790 .name = "arp_reset",
4791 .mode = COMMAND_EXEC,
4792 .jim_handler = jim_target_reset,
4793 .help = "used internally for reset processing",
4796 .name = "arp_halt",
4797 .mode = COMMAND_EXEC,
4798 .jim_handler = jim_target_halt,
4799 .help = "used internally for reset processing",
4802 .name = "arp_waitstate",
4803 .mode = COMMAND_EXEC,
4804 .jim_handler = jim_target_wait_state,
4805 .help = "used internally for reset processing",
4808 .name = "invoke-event",
4809 .mode = COMMAND_EXEC,
4810 .jim_handler = jim_target_invoke_event,
4811 .help = "invoke handler for specified event",
4812 .usage = "event_name",
4814 COMMAND_REGISTRATION_DONE
4817 static int target_create(Jim_GetOptInfo *goi)
4819 Jim_Obj *new_cmd;
4820 Jim_Cmd *cmd;
4821 const char *cp;
4822 char *cp2;
4823 int e;
4824 int x;
4825 struct target *target;
4826 struct command_context *cmd_ctx;
4828 cmd_ctx = current_command_context(goi->interp);
4829 assert(cmd_ctx != NULL);
4831 if (goi->argc < 3) {
4832 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4833 return JIM_ERR;
4836 /* COMMAND */
4837 Jim_GetOpt_Obj(goi, &new_cmd);
4838 /* does this command exist? */
4839 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4840 if (cmd) {
4841 cp = Jim_GetString(new_cmd, NULL);
4842 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
4843 return JIM_ERR;
4846 /* TYPE */
4847 e = Jim_GetOpt_String(goi, &cp2, NULL);
4848 if (e != JIM_OK)
4849 return e;
4850 cp = cp2;
4851 /* now does target type exist */
4852 for (x = 0 ; target_types[x] ; x++) {
4853 if (0 == strcmp(cp, target_types[x]->name)) {
4854 /* found */
4855 break;
4858 if (target_types[x] == NULL) {
4859 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
4860 for (x = 0 ; target_types[x] ; x++) {
4861 if (target_types[x + 1]) {
4862 Jim_AppendStrings(goi->interp,
4863 Jim_GetResult(goi->interp),
4864 target_types[x]->name,
4865 ", ", NULL);
4866 } else {
4867 Jim_AppendStrings(goi->interp,
4868 Jim_GetResult(goi->interp),
4869 " or ",
4870 target_types[x]->name, NULL);
4873 return JIM_ERR;
4876 /* Create it */
4877 target = calloc(1, sizeof(struct target));
4878 /* set target number */
4879 target->target_number = new_target_number();
4881 /* allocate memory for each unique target type */
4882 target->type = (struct target_type *)calloc(1, sizeof(struct target_type));
4884 memcpy(target->type, target_types[x], sizeof(struct target_type));
4886 /* will be set by "-endian" */
4887 target->endianness = TARGET_ENDIAN_UNKNOWN;
4889 /* default to first core, override with -coreid */
4890 target->coreid = 0;
4892 target->working_area = 0x0;
4893 target->working_area_size = 0x0;
4894 target->working_areas = NULL;
4895 target->backup_working_area = 0;
4897 target->state = TARGET_UNKNOWN;
4898 target->debug_reason = DBG_REASON_UNDEFINED;
4899 target->reg_cache = NULL;
4900 target->breakpoints = NULL;
4901 target->watchpoints = NULL;
4902 target->next = NULL;
4903 target->arch_info = NULL;
4905 target->display = 1;
4907 target->halt_issued = false;
4909 /* initialize trace information */
4910 target->trace_info = malloc(sizeof(struct trace));
4911 target->trace_info->num_trace_points = 0;
4912 target->trace_info->trace_points_size = 0;
4913 target->trace_info->trace_points = NULL;
4914 target->trace_info->trace_history_size = 0;
4915 target->trace_info->trace_history = NULL;
4916 target->trace_info->trace_history_pos = 0;
4917 target->trace_info->trace_history_overflowed = 0;
4919 target->dbgmsg = NULL;
4920 target->dbg_msg_enabled = 0;
4922 target->endianness = TARGET_ENDIAN_UNKNOWN;
4924 target->rtos = NULL;
4925 target->rtos_auto_detect = false;
4927 /* Do the rest as "configure" options */
4928 goi->isconfigure = 1;
4929 e = target_configure(goi, target);
4931 if (target->tap == NULL) {
4932 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4933 e = JIM_ERR;
4936 if (e != JIM_OK) {
4937 free(target->type);
4938 free(target);
4939 return e;
4942 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4943 /* default endian to little if not specified */
4944 target->endianness = TARGET_LITTLE_ENDIAN;
4947 /* incase variant is not set */
4948 if (!target->variant)
4949 target->variant = strdup("");
4951 cp = Jim_GetString(new_cmd, NULL);
4952 target->cmd_name = strdup(cp);
4954 /* create the target specific commands */
4955 if (target->type->commands) {
4956 e = register_commands(cmd_ctx, NULL, target->type->commands);
4957 if (ERROR_OK != e)
4958 LOG_ERROR("unable to register '%s' commands", cp);
4960 if (target->type->target_create)
4961 (*(target->type->target_create))(target, goi->interp);
4963 /* append to end of list */
4965 struct target **tpp;
4966 tpp = &(all_targets);
4967 while (*tpp)
4968 tpp = &((*tpp)->next);
4969 *tpp = target;
4972 /* now - create the new target name command */
4973 const const struct command_registration target_subcommands[] = {
4975 .chain = target_instance_command_handlers,
4978 .chain = target->type->commands,
4980 COMMAND_REGISTRATION_DONE
4982 const const struct command_registration target_commands[] = {
4984 .name = cp,
4985 .mode = COMMAND_ANY,
4986 .help = "target command group",
4987 .usage = "",
4988 .chain = target_subcommands,
4990 COMMAND_REGISTRATION_DONE
4992 e = register_commands(cmd_ctx, NULL, target_commands);
4993 if (ERROR_OK != e)
4994 return JIM_ERR;
4996 struct command *c = command_find_in_context(cmd_ctx, cp);
4997 assert(c);
4998 command_set_handler_data(c, target);
5000 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5003 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5005 if (argc != 1) {
5006 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5007 return JIM_ERR;
5009 struct command_context *cmd_ctx = current_command_context(interp);
5010 assert(cmd_ctx != NULL);
5012 Jim_SetResultString(interp, get_current_target(cmd_ctx)->cmd_name, -1);
5013 return JIM_OK;
5016 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5018 if (argc != 1) {
5019 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5020 return JIM_ERR;
5022 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5023 for (unsigned x = 0; NULL != target_types[x]; x++) {
5024 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5025 Jim_NewStringObj(interp, target_types[x]->name, -1));
5027 return JIM_OK;
5030 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5032 if (argc != 1) {
5033 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5034 return JIM_ERR;
5036 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5037 struct target *target = all_targets;
5038 while (target) {
5039 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5040 Jim_NewStringObj(interp, target_name(target), -1));
5041 target = target->next;
5043 return JIM_OK;
5046 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5048 int i;
5049 const char *targetname;
5050 int retval, len;
5051 struct target *target = (struct target *) NULL;
5052 struct target_list *head, *curr, *new;
5053 curr = (struct target_list *) NULL;
5054 head = (struct target_list *) NULL;
5056 retval = 0;
5057 LOG_DEBUG("%d", argc);
5058 /* argv[1] = target to associate in smp
5059 * argv[2] = target to assoicate in smp
5060 * argv[3] ...
5063 for (i = 1; i < argc; i++) {
5065 targetname = Jim_GetString(argv[i], &len);
5066 target = get_target(targetname);
5067 LOG_DEBUG("%s ", targetname);
5068 if (target) {
5069 new = malloc(sizeof(struct target_list));
5070 new->target = target;
5071 new->next = (struct target_list *)NULL;
5072 if (head == (struct target_list *)NULL) {
5073 head = new;
5074 curr = head;
5075 } else {
5076 curr->next = new;
5077 curr = new;
5081 /* now parse the list of cpu and put the target in smp mode*/
5082 curr = head;
5084 while (curr != (struct target_list *)NULL) {
5085 target = curr->target;
5086 target->smp = 1;
5087 target->head = head;
5088 curr = curr->next;
5090 if (target->rtos)
5091 retval = rtos_smp_init(head->target);
5092 return retval;
5096 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5098 Jim_GetOptInfo goi;
5099 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5100 if (goi.argc < 3) {
5101 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5102 "<name> <target_type> [<target_options> ...]");
5103 return JIM_ERR;
5105 return target_create(&goi);
5108 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5110 Jim_GetOptInfo goi;
5111 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5113 /* It's OK to remove this mechanism sometime after August 2010 or so */
5114 LOG_WARNING("don't use numbers as target identifiers; use names");
5115 if (goi.argc != 1) {
5116 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
5117 return JIM_ERR;
5119 jim_wide w;
5120 int e = Jim_GetOpt_Wide(&goi, &w);
5121 if (e != JIM_OK)
5122 return JIM_ERR;
5124 struct target *target;
5125 for (target = all_targets; NULL != target; target = target->next) {
5126 if (target->target_number != w)
5127 continue;
5129 Jim_SetResultString(goi.interp, target_name(target), -1);
5130 return JIM_OK;
5133 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
5134 Jim_SetResultFormatted(goi.interp,
5135 "Target: number %#s does not exist", wObj);
5136 Jim_FreeNewObj(interp, wObj);
5138 return JIM_ERR;
5141 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5143 if (argc != 1) {
5144 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
5145 return JIM_ERR;
5147 unsigned count = 0;
5148 struct target *target = all_targets;
5149 while (NULL != target) {
5150 target = target->next;
5151 count++;
5153 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
5154 return JIM_OK;
5157 static const struct command_registration target_subcommand_handlers[] = {
5159 .name = "init",
5160 .mode = COMMAND_CONFIG,
5161 .handler = handle_target_init_command,
5162 .help = "initialize targets",
5165 .name = "create",
5166 /* REVISIT this should be COMMAND_CONFIG ... */
5167 .mode = COMMAND_ANY,
5168 .jim_handler = jim_target_create,
5169 .usage = "name type '-chain-position' name [options ...]",
5170 .help = "Creates and selects a new target",
5173 .name = "current",
5174 .mode = COMMAND_ANY,
5175 .jim_handler = jim_target_current,
5176 .help = "Returns the currently selected target",
5179 .name = "types",
5180 .mode = COMMAND_ANY,
5181 .jim_handler = jim_target_types,
5182 .help = "Returns the available target types as "
5183 "a list of strings",
5186 .name = "names",
5187 .mode = COMMAND_ANY,
5188 .jim_handler = jim_target_names,
5189 .help = "Returns the names of all targets as a list of strings",
5192 .name = "number",
5193 .mode = COMMAND_ANY,
5194 .jim_handler = jim_target_number,
5195 .usage = "number",
5196 .help = "Returns the name of the numbered target "
5197 "(DEPRECATED)",
5200 .name = "count",
5201 .mode = COMMAND_ANY,
5202 .jim_handler = jim_target_count,
5203 .help = "Returns the number of targets as an integer "
5204 "(DEPRECATED)",
5207 .name = "smp",
5208 .mode = COMMAND_ANY,
5209 .jim_handler = jim_target_smp,
5210 .usage = "targetname1 targetname2 ...",
5211 .help = "gather several target in a smp list"
5214 COMMAND_REGISTRATION_DONE
5217 struct FastLoad {
5218 uint32_t address;
5219 uint8_t *data;
5220 int length;
5224 static int fastload_num;
5225 static struct FastLoad *fastload;
5227 static void free_fastload(void)
5229 if (fastload != NULL) {
5230 int i;
5231 for (i = 0; i < fastload_num; i++) {
5232 if (fastload[i].data)
5233 free(fastload[i].data);
5235 free(fastload);
5236 fastload = NULL;
5240 COMMAND_HANDLER(handle_fast_load_image_command)
5242 uint8_t *buffer;
5243 size_t buf_cnt;
5244 uint32_t image_size;
5245 uint32_t min_address = 0;
5246 uint32_t max_address = 0xffffffff;
5247 int i;
5249 struct image image;
5251 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5252 &image, &min_address, &max_address);
5253 if (ERROR_OK != retval)
5254 return retval;
5256 struct duration bench;
5257 duration_start(&bench);
5259 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5260 if (retval != ERROR_OK)
5261 return retval;
5263 image_size = 0x0;
5264 retval = ERROR_OK;
5265 fastload_num = image.num_sections;
5266 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
5267 if (fastload == NULL) {
5268 command_print(CMD_CTX, "out of memory");
5269 image_close(&image);
5270 return ERROR_FAIL;
5272 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5273 for (i = 0; i < image.num_sections; i++) {
5274 buffer = malloc(image.sections[i].size);
5275 if (buffer == NULL) {
5276 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5277 (int)(image.sections[i].size));
5278 retval = ERROR_FAIL;
5279 break;
5282 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5283 if (retval != ERROR_OK) {
5284 free(buffer);
5285 break;
5288 uint32_t offset = 0;
5289 uint32_t length = buf_cnt;
5291 /* DANGER!!! beware of unsigned comparision here!!! */
5293 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5294 (image.sections[i].base_address < max_address)) {
5295 if (image.sections[i].base_address < min_address) {
5296 /* clip addresses below */
5297 offset += min_address-image.sections[i].base_address;
5298 length -= offset;
5301 if (image.sections[i].base_address + buf_cnt > max_address)
5302 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5304 fastload[i].address = image.sections[i].base_address + offset;
5305 fastload[i].data = malloc(length);
5306 if (fastload[i].data == NULL) {
5307 free(buffer);
5308 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5309 length);
5310 retval = ERROR_FAIL;
5311 break;
5313 memcpy(fastload[i].data, buffer + offset, length);
5314 fastload[i].length = length;
5316 image_size += length;
5317 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5318 (unsigned int)length,
5319 ((unsigned int)(image.sections[i].base_address + offset)));
5322 free(buffer);
5325 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5326 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5327 "in %fs (%0.3f KiB/s)", image_size,
5328 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5330 command_print(CMD_CTX,
5331 "WARNING: image has not been loaded to target!"
5332 "You can issue a 'fast_load' to finish loading.");
5335 image_close(&image);
5337 if (retval != ERROR_OK)
5338 free_fastload();
5340 return retval;
5343 COMMAND_HANDLER(handle_fast_load_command)
5345 if (CMD_ARGC > 0)
5346 return ERROR_COMMAND_SYNTAX_ERROR;
5347 if (fastload == NULL) {
5348 LOG_ERROR("No image in memory");
5349 return ERROR_FAIL;
5351 int i;
5352 int ms = timeval_ms();
5353 int size = 0;
5354 int retval = ERROR_OK;
5355 for (i = 0; i < fastload_num; i++) {
5356 struct target *target = get_current_target(CMD_CTX);
5357 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5358 (unsigned int)(fastload[i].address),
5359 (unsigned int)(fastload[i].length));
5360 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5361 if (retval != ERROR_OK)
5362 break;
5363 size += fastload[i].length;
5365 if (retval == ERROR_OK) {
5366 int after = timeval_ms();
5367 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5369 return retval;
5372 static const struct command_registration target_command_handlers[] = {
5374 .name = "targets",
5375 .handler = handle_targets_command,
5376 .mode = COMMAND_ANY,
5377 .help = "change current default target (one parameter) "
5378 "or prints table of all targets (no parameters)",
5379 .usage = "[target]",
5382 .name = "target",
5383 .mode = COMMAND_CONFIG,
5384 .help = "configure target",
5386 .chain = target_subcommand_handlers,
5388 COMMAND_REGISTRATION_DONE
5391 int target_register_commands(struct command_context *cmd_ctx)
5393 return register_commands(cmd_ctx, NULL, target_command_handlers);
5396 static bool target_reset_nag = true;
5398 bool get_target_reset_nag(void)
5400 return target_reset_nag;
5403 COMMAND_HANDLER(handle_target_reset_nag)
5405 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5406 &target_reset_nag, "Nag after each reset about options to improve "
5407 "performance");
5410 COMMAND_HANDLER(handle_ps_command)
5412 struct target *target = get_current_target(CMD_CTX);
5413 char *display;
5414 if (target->state != TARGET_HALTED) {
5415 LOG_INFO("target not halted !!");
5416 return ERROR_OK;
5419 if ((target->rtos) && (target->rtos->type)
5420 && (target->rtos->type->ps_command)) {
5421 display = target->rtos->type->ps_command(target);
5422 command_print(CMD_CTX, "%s", display);
5423 free(display);
5424 return ERROR_OK;
5425 } else {
5426 LOG_INFO("failed");
5427 return ERROR_TARGET_FAILURE;
5431 static const struct command_registration target_exec_command_handlers[] = {
5433 .name = "fast_load_image",
5434 .handler = handle_fast_load_image_command,
5435 .mode = COMMAND_ANY,
5436 .help = "Load image into server memory for later use by "
5437 "fast_load; primarily for profiling",
5438 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5439 "[min_address [max_length]]",
5442 .name = "fast_load",
5443 .handler = handle_fast_load_command,
5444 .mode = COMMAND_EXEC,
5445 .help = "loads active fast load image to current target "
5446 "- mainly for profiling purposes",
5447 .usage = "",
5450 .name = "profile",
5451 .handler = handle_profile_command,
5452 .mode = COMMAND_EXEC,
5453 .usage = "seconds filename",
5454 .help = "profiling samples the CPU PC",
5456 /** @todo don't register virt2phys() unless target supports it */
5458 .name = "virt2phys",
5459 .handler = handle_virt2phys_command,
5460 .mode = COMMAND_ANY,
5461 .help = "translate a virtual address into a physical address",
5462 .usage = "virtual_address",
5465 .name = "reg",
5466 .handler = handle_reg_command,
5467 .mode = COMMAND_EXEC,
5468 .help = "display or set a register; with no arguments, "
5469 "displays all registers and their values",
5470 .usage = "[(register_name|register_number) [value]]",
5473 .name = "poll",
5474 .handler = handle_poll_command,
5475 .mode = COMMAND_EXEC,
5476 .help = "poll target state; or reconfigure background polling",
5477 .usage = "['on'|'off']",
5480 .name = "wait_halt",
5481 .handler = handle_wait_halt_command,
5482 .mode = COMMAND_EXEC,
5483 .help = "wait up to the specified number of milliseconds "
5484 "(default 5) for a previously requested halt",
5485 .usage = "[milliseconds]",
5488 .name = "halt",
5489 .handler = handle_halt_command,
5490 .mode = COMMAND_EXEC,
5491 .help = "request target to halt, then wait up to the specified"
5492 "number of milliseconds (default 5) for it to complete",
5493 .usage = "[milliseconds]",
5496 .name = "resume",
5497 .handler = handle_resume_command,
5498 .mode = COMMAND_EXEC,
5499 .help = "resume target execution from current PC or address",
5500 .usage = "[address]",
5503 .name = "reset",
5504 .handler = handle_reset_command,
5505 .mode = COMMAND_EXEC,
5506 .usage = "[run|halt|init]",
5507 .help = "Reset all targets into the specified mode."
5508 "Default reset mode is run, if not given.",
5511 .name = "soft_reset_halt",
5512 .handler = handle_soft_reset_halt_command,
5513 .mode = COMMAND_EXEC,
5514 .usage = "",
5515 .help = "halt the target and do a soft reset",
5518 .name = "step",
5519 .handler = handle_step_command,
5520 .mode = COMMAND_EXEC,
5521 .help = "step one instruction from current PC or address",
5522 .usage = "[address]",
5525 .name = "mdw",
5526 .handler = handle_md_command,
5527 .mode = COMMAND_EXEC,
5528 .help = "display memory words",
5529 .usage = "['phys'] address [count]",
5532 .name = "mdh",
5533 .handler = handle_md_command,
5534 .mode = COMMAND_EXEC,
5535 .help = "display memory half-words",
5536 .usage = "['phys'] address [count]",
5539 .name = "mdb",
5540 .handler = handle_md_command,
5541 .mode = COMMAND_EXEC,
5542 .help = "display memory bytes",
5543 .usage = "['phys'] address [count]",
5546 .name = "mww",
5547 .handler = handle_mw_command,
5548 .mode = COMMAND_EXEC,
5549 .help = "write memory word",
5550 .usage = "['phys'] address value [count]",
5553 .name = "mwh",
5554 .handler = handle_mw_command,
5555 .mode = COMMAND_EXEC,
5556 .help = "write memory half-word",
5557 .usage = "['phys'] address value [count]",
5560 .name = "mwb",
5561 .handler = handle_mw_command,
5562 .mode = COMMAND_EXEC,
5563 .help = "write memory byte",
5564 .usage = "['phys'] address value [count]",
5567 .name = "bp",
5568 .handler = handle_bp_command,
5569 .mode = COMMAND_EXEC,
5570 .help = "list or set hardware or software breakpoint",
5571 .usage = "<address> [<asid>]<length> ['hw'|'hw_ctx']",
5574 .name = "rbp",
5575 .handler = handle_rbp_command,
5576 .mode = COMMAND_EXEC,
5577 .help = "remove breakpoint",
5578 .usage = "address",
5581 .name = "wp",
5582 .handler = handle_wp_command,
5583 .mode = COMMAND_EXEC,
5584 .help = "list (no params) or create watchpoints",
5585 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5588 .name = "rwp",
5589 .handler = handle_rwp_command,
5590 .mode = COMMAND_EXEC,
5591 .help = "remove watchpoint",
5592 .usage = "address",
5595 .name = "load_image",
5596 .handler = handle_load_image_command,
5597 .mode = COMMAND_EXEC,
5598 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5599 "[min_address] [max_length]",
5602 .name = "dump_image",
5603 .handler = handle_dump_image_command,
5604 .mode = COMMAND_EXEC,
5605 .usage = "filename address size",
5608 .name = "verify_image",
5609 .handler = handle_verify_image_command,
5610 .mode = COMMAND_EXEC,
5611 .usage = "filename [offset [type]]",
5614 .name = "test_image",
5615 .handler = handle_test_image_command,
5616 .mode = COMMAND_EXEC,
5617 .usage = "filename [offset [type]]",
5620 .name = "mem2array",
5621 .mode = COMMAND_EXEC,
5622 .jim_handler = jim_mem2array,
5623 .help = "read 8/16/32 bit memory and return as a TCL array "
5624 "for script processing",
5625 .usage = "arrayname bitwidth address count",
5628 .name = "array2mem",
5629 .mode = COMMAND_EXEC,
5630 .jim_handler = jim_array2mem,
5631 .help = "convert a TCL array to memory locations "
5632 "and write the 8/16/32 bit values",
5633 .usage = "arrayname bitwidth address count",
5636 .name = "reset_nag",
5637 .handler = handle_target_reset_nag,
5638 .mode = COMMAND_ANY,
5639 .help = "Nag after each reset about options that could have been "
5640 "enabled to improve performance. ",
5641 .usage = "['enable'|'disable']",
5644 .name = "ps",
5645 .handler = handle_ps_command,
5646 .mode = COMMAND_EXEC,
5647 .help = "list all tasks ",
5648 .usage = " ",
5651 COMMAND_REGISTRATION_DONE
5653 static int target_register_user_commands(struct command_context *cmd_ctx)
5655 int retval = ERROR_OK;
5656 retval = target_request_register_commands(cmd_ctx);
5657 if (retval != ERROR_OK)
5658 return retval;
5660 retval = trace_register_commands(cmd_ctx);
5661 if (retval != ERROR_OK)
5662 return retval;
5665 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);