kinetis: fix "SF1" parts to limit FlexRAM usage
[openocd.git] / src / target / target.c
blobed1a2cc4c4400c48c9607ff02f58c027bbbcf250
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 cortexr4_target;
84 extern struct target_type arm11_target;
85 extern struct target_type mips_m4k_target;
86 extern struct target_type avr_target;
87 extern struct target_type dsp563xx_target;
88 extern struct target_type dsp5680xx_target;
89 extern struct target_type testee_target;
90 extern struct target_type avr32_ap7k_target;
91 extern struct target_type hla_target;
93 static struct target_type *target_types[] = {
94 &arm7tdmi_target,
95 &arm9tdmi_target,
96 &arm920t_target,
97 &arm720t_target,
98 &arm966e_target,
99 &arm946e_target,
100 &arm926ejs_target,
101 &fa526_target,
102 &feroceon_target,
103 &dragonite_target,
104 &xscale_target,
105 &cortexm3_target,
106 &cortexa8_target,
107 &cortexr4_target,
108 &arm11_target,
109 &mips_m4k_target,
110 &avr_target,
111 &dsp563xx_target,
112 &dsp5680xx_target,
113 &testee_target,
114 &avr32_ap7k_target,
115 &hla_target,
116 NULL,
119 struct target *all_targets;
120 static struct target_event_callback *target_event_callbacks;
121 static struct target_timer_callback *target_timer_callbacks;
122 static const int polling_interval = 100;
124 static const Jim_Nvp nvp_assert[] = {
125 { .name = "assert", NVP_ASSERT },
126 { .name = "deassert", NVP_DEASSERT },
127 { .name = "T", NVP_ASSERT },
128 { .name = "F", NVP_DEASSERT },
129 { .name = "t", NVP_ASSERT },
130 { .name = "f", NVP_DEASSERT },
131 { .name = NULL, .value = -1 }
134 static const Jim_Nvp nvp_error_target[] = {
135 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
136 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
137 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
138 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
139 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
140 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
141 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
142 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
143 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
144 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
145 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
146 { .value = -1, .name = NULL }
149 static const char *target_strerror_safe(int err)
151 const Jim_Nvp *n;
153 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
154 if (n->name == NULL)
155 return "unknown";
156 else
157 return n->name;
160 static const Jim_Nvp nvp_target_event[] = {
162 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
163 { .value = TARGET_EVENT_HALTED, .name = "halted" },
164 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
165 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
166 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
168 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
169 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
171 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
172 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
173 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
174 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
175 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
176 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
177 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
178 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
179 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
180 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
181 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
182 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
184 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
185 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
187 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
188 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
190 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
191 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
193 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
194 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
196 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
197 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
199 { .name = NULL, .value = -1 }
202 static const Jim_Nvp nvp_target_state[] = {
203 { .name = "unknown", .value = TARGET_UNKNOWN },
204 { .name = "running", .value = TARGET_RUNNING },
205 { .name = "halted", .value = TARGET_HALTED },
206 { .name = "reset", .value = TARGET_RESET },
207 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
208 { .name = NULL, .value = -1 },
211 static const Jim_Nvp nvp_target_debug_reason[] = {
212 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
213 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
214 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
215 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
216 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
217 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
218 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
219 { .name = NULL, .value = -1 },
222 static const Jim_Nvp nvp_target_endian[] = {
223 { .name = "big", .value = TARGET_BIG_ENDIAN },
224 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
225 { .name = "be", .value = TARGET_BIG_ENDIAN },
226 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
227 { .name = NULL, .value = -1 },
230 static const Jim_Nvp nvp_reset_modes[] = {
231 { .name = "unknown", .value = RESET_UNKNOWN },
232 { .name = "run" , .value = RESET_RUN },
233 { .name = "halt" , .value = RESET_HALT },
234 { .name = "init" , .value = RESET_INIT },
235 { .name = NULL , .value = -1 },
238 const char *debug_reason_name(struct target *t)
240 const char *cp;
242 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
243 t->debug_reason)->name;
244 if (!cp) {
245 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
246 cp = "(*BUG*unknown*BUG*)";
248 return cp;
251 const char *target_state_name(struct target *t)
253 const char *cp;
254 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
255 if (!cp) {
256 LOG_ERROR("Invalid target state: %d", (int)(t->state));
257 cp = "(*BUG*unknown*BUG*)";
259 return cp;
262 /* determine the number of the new target */
263 static int new_target_number(void)
265 struct target *t;
266 int x;
268 /* number is 0 based */
269 x = -1;
270 t = all_targets;
271 while (t) {
272 if (x < t->target_number)
273 x = t->target_number;
274 t = t->next;
276 return x + 1;
279 /* read a uint32_t from a buffer in target memory endianness */
280 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
282 if (target->endianness == TARGET_LITTLE_ENDIAN)
283 return le_to_h_u32(buffer);
284 else
285 return be_to_h_u32(buffer);
288 /* read a uint24_t from a buffer in target memory endianness */
289 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
291 if (target->endianness == TARGET_LITTLE_ENDIAN)
292 return le_to_h_u24(buffer);
293 else
294 return be_to_h_u24(buffer);
297 /* read a uint16_t from a buffer in target memory endianness */
298 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
300 if (target->endianness == TARGET_LITTLE_ENDIAN)
301 return le_to_h_u16(buffer);
302 else
303 return be_to_h_u16(buffer);
306 /* read a uint8_t from a buffer in target memory endianness */
307 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
309 return *buffer & 0x0ff;
312 /* write a uint32_t to a buffer in target memory endianness */
313 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
315 if (target->endianness == TARGET_LITTLE_ENDIAN)
316 h_u32_to_le(buffer, value);
317 else
318 h_u32_to_be(buffer, value);
321 /* write a uint24_t to a buffer in target memory endianness */
322 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
324 if (target->endianness == TARGET_LITTLE_ENDIAN)
325 h_u24_to_le(buffer, value);
326 else
327 h_u24_to_be(buffer, value);
330 /* write a uint16_t to a buffer in target memory endianness */
331 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
333 if (target->endianness == TARGET_LITTLE_ENDIAN)
334 h_u16_to_le(buffer, value);
335 else
336 h_u16_to_be(buffer, value);
339 /* write a uint8_t to a buffer in target memory endianness */
340 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
342 *buffer = value;
345 /* write a uint32_t array to a buffer in target memory endianness */
346 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
348 uint32_t i;
349 for (i = 0; i < count; i++)
350 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
353 /* write a uint16_t array to a buffer in target memory endianness */
354 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
356 uint32_t i;
357 for (i = 0; i < count; i++)
358 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
361 /* write a uint32_t array to a buffer in target memory endianness */
362 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, uint32_t *srcbuf)
364 uint32_t i;
365 for (i = 0; i < count; i++)
366 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
369 /* write a uint16_t array to a buffer in target memory endianness */
370 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, uint16_t *srcbuf)
372 uint32_t i;
373 for (i = 0; i < count; i++)
374 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
377 /* return a pointer to a configured target; id is name or number */
378 struct target *get_target(const char *id)
380 struct target *target;
382 /* try as tcltarget name */
383 for (target = all_targets; target; target = target->next) {
384 if (target_name(target) == NULL)
385 continue;
386 if (strcmp(id, target_name(target)) == 0)
387 return target;
390 /* It's OK to remove this fallback sometime after August 2010 or so */
392 /* no match, try as number */
393 unsigned num;
394 if (parse_uint(id, &num) != ERROR_OK)
395 return NULL;
397 for (target = all_targets; target; target = target->next) {
398 if (target->target_number == (int)num) {
399 LOG_WARNING("use '%s' as target identifier, not '%u'",
400 target_name(target), num);
401 return target;
405 return NULL;
408 /* returns a pointer to the n-th configured target */
409 static struct target *get_target_by_num(int num)
411 struct target *target = all_targets;
413 while (target) {
414 if (target->target_number == num)
415 return target;
416 target = target->next;
419 return NULL;
422 struct target *get_current_target(struct command_context *cmd_ctx)
424 struct target *target = get_target_by_num(cmd_ctx->current_target);
426 if (target == NULL) {
427 LOG_ERROR("BUG: current_target out of bounds");
428 exit(-1);
431 return target;
434 int target_poll(struct target *target)
436 int retval;
438 /* We can't poll until after examine */
439 if (!target_was_examined(target)) {
440 /* Fail silently lest we pollute the log */
441 return ERROR_FAIL;
444 retval = target->type->poll(target);
445 if (retval != ERROR_OK)
446 return retval;
448 if (target->halt_issued) {
449 if (target->state == TARGET_HALTED)
450 target->halt_issued = false;
451 else {
452 long long t = timeval_ms() - target->halt_issued_time;
453 if (t > 1000) {
454 target->halt_issued = false;
455 LOG_INFO("Halt timed out, wake up GDB.");
456 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
461 return ERROR_OK;
464 int target_halt(struct target *target)
466 int retval;
467 /* We can't poll until after examine */
468 if (!target_was_examined(target)) {
469 LOG_ERROR("Target not examined yet");
470 return ERROR_FAIL;
473 retval = target->type->halt(target);
474 if (retval != ERROR_OK)
475 return retval;
477 target->halt_issued = true;
478 target->halt_issued_time = timeval_ms();
480 return ERROR_OK;
484 * Make the target (re)start executing using its saved execution
485 * context (possibly with some modifications).
487 * @param target Which target should start executing.
488 * @param current True to use the target's saved program counter instead
489 * of the address parameter
490 * @param address Optionally used as the program counter.
491 * @param handle_breakpoints True iff breakpoints at the resumption PC
492 * should be skipped. (For example, maybe execution was stopped by
493 * such a breakpoint, in which case it would be counterprodutive to
494 * let it re-trigger.
495 * @param debug_execution False if all working areas allocated by OpenOCD
496 * should be released and/or restored to their original contents.
497 * (This would for example be true to run some downloaded "helper"
498 * algorithm code, which resides in one such working buffer and uses
499 * another for data storage.)
501 * @todo Resolve the ambiguity about what the "debug_execution" flag
502 * signifies. For example, Target implementations don't agree on how
503 * it relates to invalidation of the register cache, or to whether
504 * breakpoints and watchpoints should be enabled. (It would seem wrong
505 * to enable breakpoints when running downloaded "helper" algorithms
506 * (debug_execution true), since the breakpoints would be set to match
507 * target firmware being debugged, not the helper algorithm.... and
508 * enabling them could cause such helpers to malfunction (for example,
509 * by overwriting data with a breakpoint instruction. On the other
510 * hand the infrastructure for running such helpers might use this
511 * procedure but rely on hardware breakpoint to detect termination.)
513 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
515 int retval;
517 /* We can't poll until after examine */
518 if (!target_was_examined(target)) {
519 LOG_ERROR("Target not examined yet");
520 return ERROR_FAIL;
523 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
525 /* note that resume *must* be asynchronous. The CPU can halt before
526 * we poll. The CPU can even halt at the current PC as a result of
527 * a software breakpoint being inserted by (a bug?) the application.
529 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
530 if (retval != ERROR_OK)
531 return retval;
533 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
535 return retval;
538 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
540 char buf[100];
541 int retval;
542 Jim_Nvp *n;
543 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
544 if (n->name == NULL) {
545 LOG_ERROR("invalid reset mode");
546 return ERROR_FAIL;
549 /* disable polling during reset to make reset event scripts
550 * more predictable, i.e. dr/irscan & pathmove in events will
551 * not have JTAG operations injected into the middle of a sequence.
553 bool save_poll = jtag_poll_get_enabled();
555 jtag_poll_set_enabled(false);
557 sprintf(buf, "ocd_process_reset %s", n->name);
558 retval = Jim_Eval(cmd_ctx->interp, buf);
560 jtag_poll_set_enabled(save_poll);
562 if (retval != JIM_OK) {
563 Jim_MakeErrorMessage(cmd_ctx->interp);
564 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
565 return ERROR_FAIL;
568 /* We want any events to be processed before the prompt */
569 retval = target_call_timer_callbacks_now();
571 struct target *target;
572 for (target = all_targets; target; target = target->next)
573 target->type->check_reset(target);
575 return retval;
578 static int identity_virt2phys(struct target *target,
579 uint32_t virtual, uint32_t *physical)
581 *physical = virtual;
582 return ERROR_OK;
585 static int no_mmu(struct target *target, int *enabled)
587 *enabled = 0;
588 return ERROR_OK;
591 static int default_examine(struct target *target)
593 target_set_examined(target);
594 return ERROR_OK;
597 /* no check by default */
598 static int default_check_reset(struct target *target)
600 return ERROR_OK;
603 int target_examine_one(struct target *target)
605 return target->type->examine(target);
608 static int jtag_enable_callback(enum jtag_event event, void *priv)
610 struct target *target = priv;
612 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
613 return ERROR_OK;
615 jtag_unregister_event_callback(jtag_enable_callback, target);
617 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
619 int retval = target_examine_one(target);
620 if (retval != ERROR_OK)
621 return retval;
623 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
625 return retval;
628 /* Targets that correctly implement init + examine, i.e.
629 * no communication with target during init:
631 * XScale
633 int target_examine(void)
635 int retval = ERROR_OK;
636 struct target *target;
638 for (target = all_targets; target; target = target->next) {
639 /* defer examination, but don't skip it */
640 if (!target->tap->enabled) {
641 jtag_register_event_callback(jtag_enable_callback,
642 target);
643 continue;
646 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
648 retval = target_examine_one(target);
649 if (retval != ERROR_OK)
650 return retval;
652 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
654 return retval;
657 const char *target_type_name(struct target *target)
659 return target->type->name;
662 static int target_soft_reset_halt(struct target *target)
664 if (!target_was_examined(target)) {
665 LOG_ERROR("Target not examined yet");
666 return ERROR_FAIL;
668 if (!target->type->soft_reset_halt) {
669 LOG_ERROR("Target %s does not support soft_reset_halt",
670 target_name(target));
671 return ERROR_FAIL;
673 return target->type->soft_reset_halt(target);
677 * Downloads a target-specific native code algorithm to the target,
678 * and executes it. * Note that some targets may need to set up, enable,
679 * and tear down a breakpoint (hard or * soft) to detect algorithm
680 * termination, while others may support lower overhead schemes where
681 * soft breakpoints embedded in the algorithm automatically terminate the
682 * algorithm.
684 * @param target used to run the algorithm
685 * @param arch_info target-specific description of the algorithm.
687 int target_run_algorithm(struct target *target,
688 int num_mem_params, struct mem_param *mem_params,
689 int num_reg_params, struct reg_param *reg_param,
690 uint32_t entry_point, uint32_t exit_point,
691 int timeout_ms, void *arch_info)
693 int retval = ERROR_FAIL;
695 if (!target_was_examined(target)) {
696 LOG_ERROR("Target not examined yet");
697 goto done;
699 if (!target->type->run_algorithm) {
700 LOG_ERROR("Target type '%s' does not support %s",
701 target_type_name(target), __func__);
702 goto done;
705 target->running_alg = true;
706 retval = target->type->run_algorithm(target,
707 num_mem_params, mem_params,
708 num_reg_params, reg_param,
709 entry_point, exit_point, timeout_ms, arch_info);
710 target->running_alg = false;
712 done:
713 return retval;
717 * Downloads a target-specific native code algorithm to the target,
718 * executes and leaves it running.
720 * @param target used to run the algorithm
721 * @param arch_info target-specific description of the algorithm.
723 int target_start_algorithm(struct target *target,
724 int num_mem_params, struct mem_param *mem_params,
725 int num_reg_params, struct reg_param *reg_params,
726 uint32_t entry_point, uint32_t exit_point,
727 void *arch_info)
729 int retval = ERROR_FAIL;
731 if (!target_was_examined(target)) {
732 LOG_ERROR("Target not examined yet");
733 goto done;
735 if (!target->type->start_algorithm) {
736 LOG_ERROR("Target type '%s' does not support %s",
737 target_type_name(target), __func__);
738 goto done;
740 if (target->running_alg) {
741 LOG_ERROR("Target is already running an algorithm");
742 goto done;
745 target->running_alg = true;
746 retval = target->type->start_algorithm(target,
747 num_mem_params, mem_params,
748 num_reg_params, reg_params,
749 entry_point, exit_point, arch_info);
751 done:
752 return retval;
756 * Waits for an algorithm started with target_start_algorithm() to complete.
758 * @param target used to run the algorithm
759 * @param arch_info target-specific description of the algorithm.
761 int target_wait_algorithm(struct target *target,
762 int num_mem_params, struct mem_param *mem_params,
763 int num_reg_params, struct reg_param *reg_params,
764 uint32_t exit_point, int timeout_ms,
765 void *arch_info)
767 int retval = ERROR_FAIL;
769 if (!target->type->wait_algorithm) {
770 LOG_ERROR("Target type '%s' does not support %s",
771 target_type_name(target), __func__);
772 goto done;
774 if (!target->running_alg) {
775 LOG_ERROR("Target is not running an algorithm");
776 goto done;
779 retval = target->type->wait_algorithm(target,
780 num_mem_params, mem_params,
781 num_reg_params, reg_params,
782 exit_point, timeout_ms, arch_info);
783 if (retval != ERROR_TARGET_TIMEOUT)
784 target->running_alg = false;
786 done:
787 return retval;
791 * Executes a target-specific native code algorithm in the target.
792 * It differs from target_run_algorithm in that the algorithm is asynchronous.
793 * Because of this it requires an compliant algorithm:
794 * see contrib/loaders/flash/stm32f1x.S for example.
796 * @param target used to run the algorithm
799 int target_run_flash_async_algorithm(struct target *target,
800 uint8_t *buffer, uint32_t count, int block_size,
801 int num_mem_params, struct mem_param *mem_params,
802 int num_reg_params, struct reg_param *reg_params,
803 uint32_t buffer_start, uint32_t buffer_size,
804 uint32_t entry_point, uint32_t exit_point, void *arch_info)
806 int retval;
807 int timeout = 0;
809 /* Set up working area. First word is write pointer, second word is read pointer,
810 * rest is fifo data area. */
811 uint32_t wp_addr = buffer_start;
812 uint32_t rp_addr = buffer_start + 4;
813 uint32_t fifo_start_addr = buffer_start + 8;
814 uint32_t fifo_end_addr = buffer_start + buffer_size;
816 uint32_t wp = fifo_start_addr;
817 uint32_t rp = fifo_start_addr;
819 /* validate block_size is 2^n */
820 assert(!block_size || !(block_size & (block_size - 1)));
822 retval = target_write_u32(target, wp_addr, wp);
823 if (retval != ERROR_OK)
824 return retval;
825 retval = target_write_u32(target, rp_addr, rp);
826 if (retval != ERROR_OK)
827 return retval;
829 /* Start up algorithm on target and let it idle while writing the first chunk */
830 retval = target_start_algorithm(target, num_mem_params, mem_params,
831 num_reg_params, reg_params,
832 entry_point,
833 exit_point,
834 arch_info);
836 if (retval != ERROR_OK) {
837 LOG_ERROR("error starting target flash write algorithm");
838 return retval;
841 while (count > 0) {
843 retval = target_read_u32(target, rp_addr, &rp);
844 if (retval != ERROR_OK) {
845 LOG_ERROR("failed to get read pointer");
846 break;
849 LOG_DEBUG("count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32, count, wp, rp);
851 if (rp == 0) {
852 LOG_ERROR("flash write algorithm aborted by target");
853 retval = ERROR_FLASH_OPERATION_FAILED;
854 break;
857 if ((rp & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
858 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
859 break;
862 /* Count the number of bytes available in the fifo without
863 * crossing the wrap around. Make sure to not fill it completely,
864 * because that would make wp == rp and that's the empty condition. */
865 uint32_t thisrun_bytes;
866 if (rp > wp)
867 thisrun_bytes = rp - wp - block_size;
868 else if (rp > fifo_start_addr)
869 thisrun_bytes = fifo_end_addr - wp;
870 else
871 thisrun_bytes = fifo_end_addr - wp - block_size;
873 if (thisrun_bytes == 0) {
874 /* Throttle polling a bit if transfer is (much) faster than flash
875 * programming. The exact delay shouldn't matter as long as it's
876 * less than buffer size / flash speed. This is very unlikely to
877 * run when using high latency connections such as USB. */
878 alive_sleep(10);
880 /* to stop an infinite loop on some targets check and increment a timeout
881 * this issue was observed on a stellaris using the new ICDI interface */
882 if (timeout++ >= 500) {
883 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
884 return ERROR_FLASH_OPERATION_FAILED;
886 continue;
889 /* reset our timeout */
890 timeout = 0;
892 /* Limit to the amount of data we actually want to write */
893 if (thisrun_bytes > count * block_size)
894 thisrun_bytes = count * block_size;
896 /* Write data to fifo */
897 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
898 if (retval != ERROR_OK)
899 break;
901 /* Update counters and wrap write pointer */
902 buffer += thisrun_bytes;
903 count -= thisrun_bytes / block_size;
904 wp += thisrun_bytes;
905 if (wp >= fifo_end_addr)
906 wp = fifo_start_addr;
908 /* Store updated write pointer to target */
909 retval = target_write_u32(target, wp_addr, wp);
910 if (retval != ERROR_OK)
911 break;
914 if (retval != ERROR_OK) {
915 /* abort flash write algorithm on target */
916 target_write_u32(target, wp_addr, 0);
919 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
920 num_reg_params, reg_params,
921 exit_point,
922 10000,
923 arch_info);
925 if (retval2 != ERROR_OK) {
926 LOG_ERROR("error waiting for target flash write algorithm");
927 retval = retval2;
930 return retval;
933 int target_read_memory(struct target *target,
934 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
936 if (!target_was_examined(target)) {
937 LOG_ERROR("Target not examined yet");
938 return ERROR_FAIL;
940 return target->type->read_memory(target, address, size, count, buffer);
943 int target_read_phys_memory(struct target *target,
944 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
946 if (!target_was_examined(target)) {
947 LOG_ERROR("Target not examined yet");
948 return ERROR_FAIL;
950 return target->type->read_phys_memory(target, address, size, count, buffer);
953 int target_write_memory(struct target *target,
954 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
956 if (!target_was_examined(target)) {
957 LOG_ERROR("Target not examined yet");
958 return ERROR_FAIL;
960 return target->type->write_memory(target, address, size, count, buffer);
963 int target_write_phys_memory(struct target *target,
964 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
966 if (!target_was_examined(target)) {
967 LOG_ERROR("Target not examined yet");
968 return ERROR_FAIL;
970 return target->type->write_phys_memory(target, address, size, count, buffer);
973 static int target_bulk_write_memory_default(struct target *target,
974 uint32_t address, uint32_t count, const uint8_t *buffer)
976 return target_write_memory(target, address, 4, count, buffer);
979 int target_add_breakpoint(struct target *target,
980 struct breakpoint *breakpoint)
982 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
983 LOG_WARNING("target %s is not halted", target_name(target));
984 return ERROR_TARGET_NOT_HALTED;
986 return target->type->add_breakpoint(target, breakpoint);
989 int target_add_context_breakpoint(struct target *target,
990 struct breakpoint *breakpoint)
992 if (target->state != TARGET_HALTED) {
993 LOG_WARNING("target %s is not halted", target_name(target));
994 return ERROR_TARGET_NOT_HALTED;
996 return target->type->add_context_breakpoint(target, breakpoint);
999 int target_add_hybrid_breakpoint(struct target *target,
1000 struct breakpoint *breakpoint)
1002 if (target->state != TARGET_HALTED) {
1003 LOG_WARNING("target %s is not halted", target_name(target));
1004 return ERROR_TARGET_NOT_HALTED;
1006 return target->type->add_hybrid_breakpoint(target, breakpoint);
1009 int target_remove_breakpoint(struct target *target,
1010 struct breakpoint *breakpoint)
1012 return target->type->remove_breakpoint(target, breakpoint);
1015 int target_add_watchpoint(struct target *target,
1016 struct watchpoint *watchpoint)
1018 if (target->state != TARGET_HALTED) {
1019 LOG_WARNING("target %s is not halted", target_name(target));
1020 return ERROR_TARGET_NOT_HALTED;
1022 return target->type->add_watchpoint(target, watchpoint);
1024 int target_remove_watchpoint(struct target *target,
1025 struct watchpoint *watchpoint)
1027 return target->type->remove_watchpoint(target, watchpoint);
1030 int target_get_gdb_reg_list(struct target *target,
1031 struct reg **reg_list[], int *reg_list_size)
1033 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
1035 int target_step(struct target *target,
1036 int current, uint32_t address, int handle_breakpoints)
1038 return target->type->step(target, current, address, handle_breakpoints);
1042 * Reset the @c examined flag for the given target.
1043 * Pure paranoia -- targets are zeroed on allocation.
1045 static void target_reset_examined(struct target *target)
1047 target->examined = false;
1050 static int err_read_phys_memory(struct target *target, uint32_t address,
1051 uint32_t size, uint32_t count, uint8_t *buffer)
1053 LOG_ERROR("Not implemented: %s", __func__);
1054 return ERROR_FAIL;
1057 static int err_write_phys_memory(struct target *target, uint32_t address,
1058 uint32_t size, uint32_t count, const uint8_t *buffer)
1060 LOG_ERROR("Not implemented: %s", __func__);
1061 return ERROR_FAIL;
1064 static int handle_target(void *priv);
1066 static int target_init_one(struct command_context *cmd_ctx,
1067 struct target *target)
1069 target_reset_examined(target);
1071 struct target_type *type = target->type;
1072 if (type->examine == NULL)
1073 type->examine = default_examine;
1075 if (type->check_reset == NULL)
1076 type->check_reset = default_check_reset;
1078 assert(type->init_target != NULL);
1080 int retval = type->init_target(cmd_ctx, target);
1081 if (ERROR_OK != retval) {
1082 LOG_ERROR("target '%s' init failed", target_name(target));
1083 return retval;
1086 /* Sanity-check MMU support ... stub in what we must, to help
1087 * implement it in stages, but warn if we need to do so.
1089 if (type->mmu) {
1090 if (type->write_phys_memory == NULL) {
1091 LOG_ERROR("type '%s' is missing write_phys_memory",
1092 type->name);
1093 type->write_phys_memory = err_write_phys_memory;
1095 if (type->read_phys_memory == NULL) {
1096 LOG_ERROR("type '%s' is missing read_phys_memory",
1097 type->name);
1098 type->read_phys_memory = err_read_phys_memory;
1100 if (type->virt2phys == NULL) {
1101 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1102 type->virt2phys = identity_virt2phys;
1104 } else {
1105 /* Make sure no-MMU targets all behave the same: make no
1106 * distinction between physical and virtual addresses, and
1107 * ensure that virt2phys() is always an identity mapping.
1109 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1110 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1112 type->mmu = no_mmu;
1113 type->write_phys_memory = type->write_memory;
1114 type->read_phys_memory = type->read_memory;
1115 type->virt2phys = identity_virt2phys;
1118 if (target->type->read_buffer == NULL)
1119 target->type->read_buffer = target_read_buffer_default;
1121 if (target->type->write_buffer == NULL)
1122 target->type->write_buffer = target_write_buffer_default;
1124 if (target->type->bulk_write_memory == NULL)
1125 target->type->bulk_write_memory = target_bulk_write_memory_default;
1127 return ERROR_OK;
1130 static int target_init(struct command_context *cmd_ctx)
1132 struct target *target;
1133 int retval;
1135 for (target = all_targets; target; target = target->next) {
1136 retval = target_init_one(cmd_ctx, target);
1137 if (ERROR_OK != retval)
1138 return retval;
1141 if (!all_targets)
1142 return ERROR_OK;
1144 retval = target_register_user_commands(cmd_ctx);
1145 if (ERROR_OK != retval)
1146 return retval;
1148 retval = target_register_timer_callback(&handle_target,
1149 polling_interval, 1, cmd_ctx->interp);
1150 if (ERROR_OK != retval)
1151 return retval;
1153 return ERROR_OK;
1156 COMMAND_HANDLER(handle_target_init_command)
1158 int retval;
1160 if (CMD_ARGC != 0)
1161 return ERROR_COMMAND_SYNTAX_ERROR;
1163 static bool target_initialized;
1164 if (target_initialized) {
1165 LOG_INFO("'target init' has already been called");
1166 return ERROR_OK;
1168 target_initialized = true;
1170 retval = command_run_line(CMD_CTX, "init_targets");
1171 if (ERROR_OK != retval)
1172 return retval;
1174 retval = command_run_line(CMD_CTX, "init_board");
1175 if (ERROR_OK != retval)
1176 return retval;
1178 LOG_DEBUG("Initializing targets...");
1179 return target_init(CMD_CTX);
1182 int target_register_event_callback(int (*callback)(struct target *target,
1183 enum target_event event, void *priv), void *priv)
1185 struct target_event_callback **callbacks_p = &target_event_callbacks;
1187 if (callback == NULL)
1188 return ERROR_COMMAND_SYNTAX_ERROR;
1190 if (*callbacks_p) {
1191 while ((*callbacks_p)->next)
1192 callbacks_p = &((*callbacks_p)->next);
1193 callbacks_p = &((*callbacks_p)->next);
1196 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1197 (*callbacks_p)->callback = callback;
1198 (*callbacks_p)->priv = priv;
1199 (*callbacks_p)->next = NULL;
1201 return ERROR_OK;
1204 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1206 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1207 struct timeval now;
1209 if (callback == NULL)
1210 return ERROR_COMMAND_SYNTAX_ERROR;
1212 if (*callbacks_p) {
1213 while ((*callbacks_p)->next)
1214 callbacks_p = &((*callbacks_p)->next);
1215 callbacks_p = &((*callbacks_p)->next);
1218 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1219 (*callbacks_p)->callback = callback;
1220 (*callbacks_p)->periodic = periodic;
1221 (*callbacks_p)->time_ms = time_ms;
1223 gettimeofday(&now, NULL);
1224 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
1225 time_ms -= (time_ms % 1000);
1226 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
1227 if ((*callbacks_p)->when.tv_usec > 1000000) {
1228 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
1229 (*callbacks_p)->when.tv_sec += 1;
1232 (*callbacks_p)->priv = priv;
1233 (*callbacks_p)->next = NULL;
1235 return ERROR_OK;
1238 int target_unregister_event_callback(int (*callback)(struct target *target,
1239 enum target_event event, void *priv), void *priv)
1241 struct target_event_callback **p = &target_event_callbacks;
1242 struct target_event_callback *c = target_event_callbacks;
1244 if (callback == NULL)
1245 return ERROR_COMMAND_SYNTAX_ERROR;
1247 while (c) {
1248 struct target_event_callback *next = c->next;
1249 if ((c->callback == callback) && (c->priv == priv)) {
1250 *p = next;
1251 free(c);
1252 return ERROR_OK;
1253 } else
1254 p = &(c->next);
1255 c = next;
1258 return ERROR_OK;
1261 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1263 struct target_timer_callback **p = &target_timer_callbacks;
1264 struct target_timer_callback *c = target_timer_callbacks;
1266 if (callback == NULL)
1267 return ERROR_COMMAND_SYNTAX_ERROR;
1269 while (c) {
1270 struct target_timer_callback *next = c->next;
1271 if ((c->callback == callback) && (c->priv == priv)) {
1272 *p = next;
1273 free(c);
1274 return ERROR_OK;
1275 } else
1276 p = &(c->next);
1277 c = next;
1280 return ERROR_OK;
1283 int target_call_event_callbacks(struct target *target, enum target_event event)
1285 struct target_event_callback *callback = target_event_callbacks;
1286 struct target_event_callback *next_callback;
1288 if (event == TARGET_EVENT_HALTED) {
1289 /* execute early halted first */
1290 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1293 LOG_DEBUG("target event %i (%s)", event,
1294 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1296 target_handle_event(target, event);
1298 while (callback) {
1299 next_callback = callback->next;
1300 callback->callback(target, event, callback->priv);
1301 callback = next_callback;
1304 return ERROR_OK;
1307 static int target_timer_callback_periodic_restart(
1308 struct target_timer_callback *cb, struct timeval *now)
1310 int time_ms = cb->time_ms;
1311 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1312 time_ms -= (time_ms % 1000);
1313 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1314 if (cb->when.tv_usec > 1000000) {
1315 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1316 cb->when.tv_sec += 1;
1318 return ERROR_OK;
1321 static int target_call_timer_callback(struct target_timer_callback *cb,
1322 struct timeval *now)
1324 cb->callback(cb->priv);
1326 if (cb->periodic)
1327 return target_timer_callback_periodic_restart(cb, now);
1329 return target_unregister_timer_callback(cb->callback, cb->priv);
1332 static int target_call_timer_callbacks_check_time(int checktime)
1334 keep_alive();
1336 struct timeval now;
1337 gettimeofday(&now, NULL);
1339 struct target_timer_callback *callback = target_timer_callbacks;
1340 while (callback) {
1341 /* cleaning up may unregister and free this callback */
1342 struct target_timer_callback *next_callback = callback->next;
1344 bool call_it = callback->callback &&
1345 ((!checktime && callback->periodic) ||
1346 now.tv_sec > callback->when.tv_sec ||
1347 (now.tv_sec == callback->when.tv_sec &&
1348 now.tv_usec >= callback->when.tv_usec));
1350 if (call_it) {
1351 int retval = target_call_timer_callback(callback, &now);
1352 if (retval != ERROR_OK)
1353 return retval;
1356 callback = next_callback;
1359 return ERROR_OK;
1362 int target_call_timer_callbacks(void)
1364 return target_call_timer_callbacks_check_time(1);
1367 /* invoke periodic callbacks immediately */
1368 int target_call_timer_callbacks_now(void)
1370 return target_call_timer_callbacks_check_time(0);
1373 /* Prints the working area layout for debug purposes */
1374 static void print_wa_layout(struct target *target)
1376 struct working_area *c = target->working_areas;
1378 while (c) {
1379 LOG_DEBUG("%c%c 0x%08"PRIx32"-0x%08"PRIx32" (%"PRIu32" bytes)",
1380 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1381 c->address, c->address + c->size - 1, c->size);
1382 c = c->next;
1386 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1387 static void target_split_working_area(struct working_area *area, uint32_t size)
1389 assert(area->free); /* Shouldn't split an allocated area */
1390 assert(size <= area->size); /* Caller should guarantee this */
1392 /* Split only if not already the right size */
1393 if (size < area->size) {
1394 struct working_area *new_wa = malloc(sizeof(*new_wa));
1396 if (new_wa == NULL)
1397 return;
1399 new_wa->next = area->next;
1400 new_wa->size = area->size - size;
1401 new_wa->address = area->address + size;
1402 new_wa->backup = NULL;
1403 new_wa->user = NULL;
1404 new_wa->free = true;
1406 area->next = new_wa;
1407 area->size = size;
1409 /* If backup memory was allocated to this area, it has the wrong size
1410 * now so free it and it will be reallocated if/when needed */
1411 if (area->backup) {
1412 free(area->backup);
1413 area->backup = NULL;
1418 /* Merge all adjacent free areas into one */
1419 static void target_merge_working_areas(struct target *target)
1421 struct working_area *c = target->working_areas;
1423 while (c && c->next) {
1424 assert(c->next->address == c->address + c->size); /* This is an invariant */
1426 /* Find two adjacent free areas */
1427 if (c->free && c->next->free) {
1428 /* Merge the last into the first */
1429 c->size += c->next->size;
1431 /* Remove the last */
1432 struct working_area *to_be_freed = c->next;
1433 c->next = c->next->next;
1434 if (to_be_freed->backup)
1435 free(to_be_freed->backup);
1436 free(to_be_freed);
1438 /* If backup memory was allocated to the remaining area, it's has
1439 * the wrong size now */
1440 if (c->backup) {
1441 free(c->backup);
1442 c->backup = NULL;
1444 } else {
1445 c = c->next;
1450 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1452 /* Reevaluate working area address based on MMU state*/
1453 if (target->working_areas == NULL) {
1454 int retval;
1455 int enabled;
1457 retval = target->type->mmu(target, &enabled);
1458 if (retval != ERROR_OK)
1459 return retval;
1461 if (!enabled) {
1462 if (target->working_area_phys_spec) {
1463 LOG_DEBUG("MMU disabled, using physical "
1464 "address for working memory 0x%08"PRIx32,
1465 target->working_area_phys);
1466 target->working_area = target->working_area_phys;
1467 } else {
1468 LOG_ERROR("No working memory available. "
1469 "Specify -work-area-phys to target.");
1470 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1472 } else {
1473 if (target->working_area_virt_spec) {
1474 LOG_DEBUG("MMU enabled, using virtual "
1475 "address for working memory 0x%08"PRIx32,
1476 target->working_area_virt);
1477 target->working_area = target->working_area_virt;
1478 } else {
1479 LOG_ERROR("No working memory available. "
1480 "Specify -work-area-virt to target.");
1481 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1485 /* Set up initial working area on first call */
1486 struct working_area *new_wa = malloc(sizeof(*new_wa));
1487 if (new_wa) {
1488 new_wa->next = NULL;
1489 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1490 new_wa->address = target->working_area;
1491 new_wa->backup = NULL;
1492 new_wa->user = NULL;
1493 new_wa->free = true;
1496 target->working_areas = new_wa;
1499 /* only allocate multiples of 4 byte */
1500 if (size % 4)
1501 size = (size + 3) & (~3UL);
1503 struct working_area *c = target->working_areas;
1505 /* Find the first large enough working area */
1506 while (c) {
1507 if (c->free && c->size >= size)
1508 break;
1509 c = c->next;
1512 if (c == NULL)
1513 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1515 /* Split the working area into the requested size */
1516 target_split_working_area(c, size);
1518 LOG_DEBUG("allocated new working area of %"PRIu32" bytes at address 0x%08"PRIx32, size, c->address);
1520 if (target->backup_working_area) {
1521 if (c->backup == NULL) {
1522 c->backup = malloc(c->size);
1523 if (c->backup == NULL)
1524 return ERROR_FAIL;
1527 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1528 if (retval != ERROR_OK)
1529 return retval;
1532 /* mark as used, and return the new (reused) area */
1533 c->free = false;
1534 *area = c;
1536 /* user pointer */
1537 c->user = area;
1539 print_wa_layout(target);
1541 return ERROR_OK;
1544 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1546 int retval;
1548 retval = target_alloc_working_area_try(target, size, area);
1549 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1550 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1551 return retval;
1555 static int target_restore_working_area(struct target *target, struct working_area *area)
1557 int retval = ERROR_OK;
1559 if (target->backup_working_area && area->backup != NULL) {
1560 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1561 if (retval != ERROR_OK)
1562 LOG_ERROR("failed to restore %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1563 area->size, area->address);
1566 return retval;
1569 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1570 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1572 int retval = ERROR_OK;
1574 if (area->free)
1575 return retval;
1577 if (restore) {
1578 retval = target_restore_working_area(target, area);
1579 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1580 if (retval != ERROR_OK)
1581 return retval;
1584 area->free = true;
1586 LOG_DEBUG("freed %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1587 area->size, area->address);
1589 /* mark user pointer invalid */
1590 /* TODO: Is this really safe? It points to some previous caller's memory.
1591 * How could we know that the area pointer is still in that place and not
1592 * some other vital data? What's the purpose of this, anyway? */
1593 *area->user = NULL;
1594 area->user = NULL;
1596 target_merge_working_areas(target);
1598 print_wa_layout(target);
1600 return retval;
1603 int target_free_working_area(struct target *target, struct working_area *area)
1605 return target_free_working_area_restore(target, area, 1);
1608 /* free resources and restore memory, if restoring memory fails,
1609 * free up resources anyway
1611 static void target_free_all_working_areas_restore(struct target *target, int restore)
1613 struct working_area *c = target->working_areas;
1615 LOG_DEBUG("freeing all working areas");
1617 /* Loop through all areas, restoring the allocated ones and marking them as free */
1618 while (c) {
1619 if (!c->free) {
1620 if (restore)
1621 target_restore_working_area(target, c);
1622 c->free = true;
1623 *c->user = NULL; /* Same as above */
1624 c->user = NULL;
1626 c = c->next;
1629 /* Run a merge pass to combine all areas into one */
1630 target_merge_working_areas(target);
1632 print_wa_layout(target);
1635 void target_free_all_working_areas(struct target *target)
1637 target_free_all_working_areas_restore(target, 1);
1640 /* Find the largest number of bytes that can be allocated */
1641 uint32_t target_get_working_area_avail(struct target *target)
1643 struct working_area *c = target->working_areas;
1644 uint32_t max_size = 0;
1646 if (c == NULL)
1647 return target->working_area_size;
1649 while (c) {
1650 if (c->free && max_size < c->size)
1651 max_size = c->size;
1653 c = c->next;
1656 return max_size;
1659 int target_arch_state(struct target *target)
1661 int retval;
1662 if (target == NULL) {
1663 LOG_USER("No target has been configured");
1664 return ERROR_OK;
1667 LOG_USER("target state: %s", target_state_name(target));
1669 if (target->state != TARGET_HALTED)
1670 return ERROR_OK;
1672 retval = target->type->arch_state(target);
1673 return retval;
1676 /* Single aligned words are guaranteed to use 16 or 32 bit access
1677 * mode respectively, otherwise data is handled as quickly as
1678 * possible
1680 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1682 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1683 (int)size, (unsigned)address);
1685 if (!target_was_examined(target)) {
1686 LOG_ERROR("Target not examined yet");
1687 return ERROR_FAIL;
1690 if (size == 0)
1691 return ERROR_OK;
1693 if ((address + size - 1) < address) {
1694 /* GDB can request this when e.g. PC is 0xfffffffc*/
1695 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1696 (unsigned)address,
1697 (unsigned)size);
1698 return ERROR_FAIL;
1701 return target->type->write_buffer(target, address, size, buffer);
1704 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1706 int retval = ERROR_OK;
1708 if (((address % 2) == 0) && (size == 2))
1709 return target_write_memory(target, address, 2, 1, buffer);
1711 /* handle unaligned head bytes */
1712 if (address % 4) {
1713 uint32_t unaligned = 4 - (address % 4);
1715 if (unaligned > size)
1716 unaligned = size;
1718 retval = target_write_memory(target, address, 1, unaligned, buffer);
1719 if (retval != ERROR_OK)
1720 return retval;
1722 buffer += unaligned;
1723 address += unaligned;
1724 size -= unaligned;
1727 /* handle aligned words */
1728 if (size >= 4) {
1729 int aligned = size - (size % 4);
1731 /* use bulk writes above a certain limit. This may have to be changed */
1732 if (aligned > 128) {
1733 retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer);
1734 if (retval != ERROR_OK)
1735 return retval;
1736 } else {
1737 retval = target_write_memory(target, address, 4, aligned / 4, buffer);
1738 if (retval != ERROR_OK)
1739 return retval;
1742 buffer += aligned;
1743 address += aligned;
1744 size -= aligned;
1747 /* handle tail writes of less than 4 bytes */
1748 if (size > 0) {
1749 retval = target_write_memory(target, address, 1, size, buffer);
1750 if (retval != ERROR_OK)
1751 return retval;
1754 return retval;
1757 /* Single aligned words are guaranteed to use 16 or 32 bit access
1758 * mode respectively, otherwise data is handled as quickly as
1759 * possible
1761 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1763 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1764 (int)size, (unsigned)address);
1766 if (!target_was_examined(target)) {
1767 LOG_ERROR("Target not examined yet");
1768 return ERROR_FAIL;
1771 if (size == 0)
1772 return ERROR_OK;
1774 if ((address + size - 1) < address) {
1775 /* GDB can request this when e.g. PC is 0xfffffffc*/
1776 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1777 address,
1778 size);
1779 return ERROR_FAIL;
1782 return target->type->read_buffer(target, address, size, buffer);
1785 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1787 int retval = ERROR_OK;
1789 if (((address % 2) == 0) && (size == 2))
1790 return target_read_memory(target, address, 2, 1, buffer);
1792 /* handle unaligned head bytes */
1793 if (address % 4) {
1794 uint32_t unaligned = 4 - (address % 4);
1796 if (unaligned > size)
1797 unaligned = size;
1799 retval = target_read_memory(target, address, 1, unaligned, buffer);
1800 if (retval != ERROR_OK)
1801 return retval;
1803 buffer += unaligned;
1804 address += unaligned;
1805 size -= unaligned;
1808 /* handle aligned words */
1809 if (size >= 4) {
1810 int aligned = size - (size % 4);
1812 retval = target_read_memory(target, address, 4, aligned / 4, buffer);
1813 if (retval != ERROR_OK)
1814 return retval;
1816 buffer += aligned;
1817 address += aligned;
1818 size -= aligned;
1821 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1822 if (size >= 2) {
1823 int aligned = size - (size % 2);
1824 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1825 if (retval != ERROR_OK)
1826 return retval;
1828 buffer += aligned;
1829 address += aligned;
1830 size -= aligned;
1832 /* handle tail writes of less than 4 bytes */
1833 if (size > 0) {
1834 retval = target_read_memory(target, address, 1, size, buffer);
1835 if (retval != ERROR_OK)
1836 return retval;
1839 return ERROR_OK;
1842 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1844 uint8_t *buffer;
1845 int retval;
1846 uint32_t i;
1847 uint32_t checksum = 0;
1848 if (!target_was_examined(target)) {
1849 LOG_ERROR("Target not examined yet");
1850 return ERROR_FAIL;
1853 retval = target->type->checksum_memory(target, address, size, &checksum);
1854 if (retval != ERROR_OK) {
1855 buffer = malloc(size);
1856 if (buffer == NULL) {
1857 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1858 return ERROR_COMMAND_SYNTAX_ERROR;
1860 retval = target_read_buffer(target, address, size, buffer);
1861 if (retval != ERROR_OK) {
1862 free(buffer);
1863 return retval;
1866 /* convert to target endianness */
1867 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
1868 uint32_t target_data;
1869 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1870 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1873 retval = image_calculate_checksum(buffer, size, &checksum);
1874 free(buffer);
1877 *crc = checksum;
1879 return retval;
1882 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1884 int retval;
1885 if (!target_was_examined(target)) {
1886 LOG_ERROR("Target not examined yet");
1887 return ERROR_FAIL;
1890 if (target->type->blank_check_memory == 0)
1891 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1893 retval = target->type->blank_check_memory(target, address, size, blank);
1895 return retval;
1898 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1900 uint8_t value_buf[4];
1901 if (!target_was_examined(target)) {
1902 LOG_ERROR("Target not examined yet");
1903 return ERROR_FAIL;
1906 int retval = target_read_memory(target, address, 4, 1, value_buf);
1908 if (retval == ERROR_OK) {
1909 *value = target_buffer_get_u32(target, value_buf);
1910 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1911 address,
1912 *value);
1913 } else {
1914 *value = 0x0;
1915 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1916 address);
1919 return retval;
1922 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1924 uint8_t value_buf[2];
1925 if (!target_was_examined(target)) {
1926 LOG_ERROR("Target not examined yet");
1927 return ERROR_FAIL;
1930 int retval = target_read_memory(target, address, 2, 1, value_buf);
1932 if (retval == ERROR_OK) {
1933 *value = target_buffer_get_u16(target, value_buf);
1934 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1935 address,
1936 *value);
1937 } else {
1938 *value = 0x0;
1939 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1940 address);
1943 return retval;
1946 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1948 int retval = target_read_memory(target, address, 1, 1, value);
1949 if (!target_was_examined(target)) {
1950 LOG_ERROR("Target not examined yet");
1951 return ERROR_FAIL;
1954 if (retval == ERROR_OK) {
1955 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1956 address,
1957 *value);
1958 } else {
1959 *value = 0x0;
1960 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1961 address);
1964 return retval;
1967 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1969 int retval;
1970 uint8_t value_buf[4];
1971 if (!target_was_examined(target)) {
1972 LOG_ERROR("Target not examined yet");
1973 return ERROR_FAIL;
1976 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1977 address,
1978 value);
1980 target_buffer_set_u32(target, value_buf, value);
1981 retval = target_write_memory(target, address, 4, 1, value_buf);
1982 if (retval != ERROR_OK)
1983 LOG_DEBUG("failed: %i", retval);
1985 return retval;
1988 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1990 int retval;
1991 uint8_t value_buf[2];
1992 if (!target_was_examined(target)) {
1993 LOG_ERROR("Target not examined yet");
1994 return ERROR_FAIL;
1997 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1998 address,
1999 value);
2001 target_buffer_set_u16(target, value_buf, value);
2002 retval = target_write_memory(target, address, 2, 1, value_buf);
2003 if (retval != ERROR_OK)
2004 LOG_DEBUG("failed: %i", retval);
2006 return retval;
2009 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
2011 int retval;
2012 if (!target_was_examined(target)) {
2013 LOG_ERROR("Target not examined yet");
2014 return ERROR_FAIL;
2017 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2018 address, value);
2020 retval = target_write_memory(target, address, 1, 1, &value);
2021 if (retval != ERROR_OK)
2022 LOG_DEBUG("failed: %i", retval);
2024 return retval;
2027 static int find_target(struct command_context *cmd_ctx, const char *name)
2029 struct target *target = get_target(name);
2030 if (target == NULL) {
2031 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2032 return ERROR_FAIL;
2034 if (!target->tap->enabled) {
2035 LOG_USER("Target: TAP %s is disabled, "
2036 "can't be the current target\n",
2037 target->tap->dotted_name);
2038 return ERROR_FAIL;
2041 cmd_ctx->current_target = target->target_number;
2042 return ERROR_OK;
2046 COMMAND_HANDLER(handle_targets_command)
2048 int retval = ERROR_OK;
2049 if (CMD_ARGC == 1) {
2050 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2051 if (retval == ERROR_OK) {
2052 /* we're done! */
2053 return retval;
2057 struct target *target = all_targets;
2058 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2059 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2060 while (target) {
2061 const char *state;
2062 char marker = ' ';
2064 if (target->tap->enabled)
2065 state = target_state_name(target);
2066 else
2067 state = "tap-disabled";
2069 if (CMD_CTX->current_target == target->target_number)
2070 marker = '*';
2072 /* keep columns lined up to match the headers above */
2073 command_print(CMD_CTX,
2074 "%2d%c %-18s %-10s %-6s %-18s %s",
2075 target->target_number,
2076 marker,
2077 target_name(target),
2078 target_type_name(target),
2079 Jim_Nvp_value2name_simple(nvp_target_endian,
2080 target->endianness)->name,
2081 target->tap->dotted_name,
2082 state);
2083 target = target->next;
2086 return retval;
2089 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2091 static int powerDropout;
2092 static int srstAsserted;
2094 static int runPowerRestore;
2095 static int runPowerDropout;
2096 static int runSrstAsserted;
2097 static int runSrstDeasserted;
2099 static int sense_handler(void)
2101 static int prevSrstAsserted;
2102 static int prevPowerdropout;
2104 int retval = jtag_power_dropout(&powerDropout);
2105 if (retval != ERROR_OK)
2106 return retval;
2108 int powerRestored;
2109 powerRestored = prevPowerdropout && !powerDropout;
2110 if (powerRestored)
2111 runPowerRestore = 1;
2113 long long current = timeval_ms();
2114 static long long lastPower;
2115 int waitMore = lastPower + 2000 > current;
2116 if (powerDropout && !waitMore) {
2117 runPowerDropout = 1;
2118 lastPower = current;
2121 retval = jtag_srst_asserted(&srstAsserted);
2122 if (retval != ERROR_OK)
2123 return retval;
2125 int srstDeasserted;
2126 srstDeasserted = prevSrstAsserted && !srstAsserted;
2128 static long long lastSrst;
2129 waitMore = lastSrst + 2000 > current;
2130 if (srstDeasserted && !waitMore) {
2131 runSrstDeasserted = 1;
2132 lastSrst = current;
2135 if (!prevSrstAsserted && srstAsserted)
2136 runSrstAsserted = 1;
2138 prevSrstAsserted = srstAsserted;
2139 prevPowerdropout = powerDropout;
2141 if (srstDeasserted || powerRestored) {
2142 /* Other than logging the event we can't do anything here.
2143 * Issuing a reset is a particularly bad idea as we might
2144 * be inside a reset already.
2148 return ERROR_OK;
2151 /* process target state changes */
2152 static int handle_target(void *priv)
2154 Jim_Interp *interp = (Jim_Interp *)priv;
2155 int retval = ERROR_OK;
2157 if (!is_jtag_poll_safe()) {
2158 /* polling is disabled currently */
2159 return ERROR_OK;
2162 /* we do not want to recurse here... */
2163 static int recursive;
2164 if (!recursive) {
2165 recursive = 1;
2166 sense_handler();
2167 /* danger! running these procedures can trigger srst assertions and power dropouts.
2168 * We need to avoid an infinite loop/recursion here and we do that by
2169 * clearing the flags after running these events.
2171 int did_something = 0;
2172 if (runSrstAsserted) {
2173 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2174 Jim_Eval(interp, "srst_asserted");
2175 did_something = 1;
2177 if (runSrstDeasserted) {
2178 Jim_Eval(interp, "srst_deasserted");
2179 did_something = 1;
2181 if (runPowerDropout) {
2182 LOG_INFO("Power dropout detected, running power_dropout proc.");
2183 Jim_Eval(interp, "power_dropout");
2184 did_something = 1;
2186 if (runPowerRestore) {
2187 Jim_Eval(interp, "power_restore");
2188 did_something = 1;
2191 if (did_something) {
2192 /* clear detect flags */
2193 sense_handler();
2196 /* clear action flags */
2198 runSrstAsserted = 0;
2199 runSrstDeasserted = 0;
2200 runPowerRestore = 0;
2201 runPowerDropout = 0;
2203 recursive = 0;
2206 /* Poll targets for state changes unless that's globally disabled.
2207 * Skip targets that are currently disabled.
2209 for (struct target *target = all_targets;
2210 is_jtag_poll_safe() && target;
2211 target = target->next) {
2212 if (!target->tap->enabled)
2213 continue;
2215 if (target->backoff.times > target->backoff.count) {
2216 /* do not poll this time as we failed previously */
2217 target->backoff.count++;
2218 continue;
2220 target->backoff.count = 0;
2222 /* only poll target if we've got power and srst isn't asserted */
2223 if (!powerDropout && !srstAsserted) {
2224 /* polling may fail silently until the target has been examined */
2225 retval = target_poll(target);
2226 if (retval != ERROR_OK) {
2227 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2228 if (target->backoff.times * polling_interval < 5000) {
2229 target->backoff.times *= 2;
2230 target->backoff.times++;
2232 LOG_USER("Polling target %s failed, GDB will be halted. Polling again in %dms",
2233 target_name(target),
2234 target->backoff.times * polling_interval);
2236 /* Tell GDB to halt the debugger. This allows the user to
2237 * run monitor commands to handle the situation.
2239 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2240 return retval;
2242 /* Since we succeeded, we reset backoff count */
2243 if (target->backoff.times > 0)
2244 LOG_USER("Polling target %s succeeded again", target_name(target));
2245 target->backoff.times = 0;
2249 return retval;
2252 COMMAND_HANDLER(handle_reg_command)
2254 struct target *target;
2255 struct reg *reg = NULL;
2256 unsigned count = 0;
2257 char *value;
2259 LOG_DEBUG("-");
2261 target = get_current_target(CMD_CTX);
2263 /* list all available registers for the current target */
2264 if (CMD_ARGC == 0) {
2265 struct reg_cache *cache = target->reg_cache;
2267 count = 0;
2268 while (cache) {
2269 unsigned i;
2271 command_print(CMD_CTX, "===== %s", cache->name);
2273 for (i = 0, reg = cache->reg_list;
2274 i < cache->num_regs;
2275 i++, reg++, count++) {
2276 /* only print cached values if they are valid */
2277 if (reg->valid) {
2278 value = buf_to_str(reg->value,
2279 reg->size, 16);
2280 command_print(CMD_CTX,
2281 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2282 count, reg->name,
2283 reg->size, value,
2284 reg->dirty
2285 ? " (dirty)"
2286 : "");
2287 free(value);
2288 } else {
2289 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2290 count, reg->name,
2291 reg->size) ;
2294 cache = cache->next;
2297 return ERROR_OK;
2300 /* access a single register by its ordinal number */
2301 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2302 unsigned num;
2303 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2305 struct reg_cache *cache = target->reg_cache;
2306 count = 0;
2307 while (cache) {
2308 unsigned i;
2309 for (i = 0; i < cache->num_regs; i++) {
2310 if (count++ == num) {
2311 reg = &cache->reg_list[i];
2312 break;
2315 if (reg)
2316 break;
2317 cache = cache->next;
2320 if (!reg) {
2321 command_print(CMD_CTX, "%i is out of bounds, the current target "
2322 "has only %i registers (0 - %i)", num, count, count - 1);
2323 return ERROR_OK;
2325 } else {
2326 /* access a single register by its name */
2327 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2329 if (!reg) {
2330 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2331 return ERROR_OK;
2335 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2337 /* display a register */
2338 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2339 && (CMD_ARGV[1][0] <= '9')))) {
2340 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2341 reg->valid = 0;
2343 if (reg->valid == 0)
2344 reg->type->get(reg);
2345 value = buf_to_str(reg->value, reg->size, 16);
2346 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2347 free(value);
2348 return ERROR_OK;
2351 /* set register value */
2352 if (CMD_ARGC == 2) {
2353 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2354 if (buf == NULL)
2355 return ERROR_FAIL;
2356 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2358 reg->type->set(reg, buf);
2360 value = buf_to_str(reg->value, reg->size, 16);
2361 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2362 free(value);
2364 free(buf);
2366 return ERROR_OK;
2369 return ERROR_COMMAND_SYNTAX_ERROR;
2372 COMMAND_HANDLER(handle_poll_command)
2374 int retval = ERROR_OK;
2375 struct target *target = get_current_target(CMD_CTX);
2377 if (CMD_ARGC == 0) {
2378 command_print(CMD_CTX, "background polling: %s",
2379 jtag_poll_get_enabled() ? "on" : "off");
2380 command_print(CMD_CTX, "TAP: %s (%s)",
2381 target->tap->dotted_name,
2382 target->tap->enabled ? "enabled" : "disabled");
2383 if (!target->tap->enabled)
2384 return ERROR_OK;
2385 retval = target_poll(target);
2386 if (retval != ERROR_OK)
2387 return retval;
2388 retval = target_arch_state(target);
2389 if (retval != ERROR_OK)
2390 return retval;
2391 } else if (CMD_ARGC == 1) {
2392 bool enable;
2393 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2394 jtag_poll_set_enabled(enable);
2395 } else
2396 return ERROR_COMMAND_SYNTAX_ERROR;
2398 return retval;
2401 COMMAND_HANDLER(handle_wait_halt_command)
2403 if (CMD_ARGC > 1)
2404 return ERROR_COMMAND_SYNTAX_ERROR;
2406 unsigned ms = 5000;
2407 if (1 == CMD_ARGC) {
2408 int retval = parse_uint(CMD_ARGV[0], &ms);
2409 if (ERROR_OK != retval)
2410 return ERROR_COMMAND_SYNTAX_ERROR;
2411 /* convert seconds (given) to milliseconds (needed) */
2412 ms *= 1000;
2415 struct target *target = get_current_target(CMD_CTX);
2416 return target_wait_state(target, TARGET_HALTED, ms);
2419 /* wait for target state to change. The trick here is to have a low
2420 * latency for short waits and not to suck up all the CPU time
2421 * on longer waits.
2423 * After 500ms, keep_alive() is invoked
2425 int target_wait_state(struct target *target, enum target_state state, int ms)
2427 int retval;
2428 long long then = 0, cur;
2429 int once = 1;
2431 for (;;) {
2432 retval = target_poll(target);
2433 if (retval != ERROR_OK)
2434 return retval;
2435 if (target->state == state)
2436 break;
2437 cur = timeval_ms();
2438 if (once) {
2439 once = 0;
2440 then = timeval_ms();
2441 LOG_DEBUG("waiting for target %s...",
2442 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2445 if (cur-then > 500)
2446 keep_alive();
2448 if ((cur-then) > ms) {
2449 LOG_ERROR("timed out while waiting for target %s",
2450 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2451 return ERROR_FAIL;
2455 return ERROR_OK;
2458 COMMAND_HANDLER(handle_halt_command)
2460 LOG_DEBUG("-");
2462 struct target *target = get_current_target(CMD_CTX);
2463 int retval = target_halt(target);
2464 if (ERROR_OK != retval)
2465 return retval;
2467 if (CMD_ARGC == 1) {
2468 unsigned wait_local;
2469 retval = parse_uint(CMD_ARGV[0], &wait_local);
2470 if (ERROR_OK != retval)
2471 return ERROR_COMMAND_SYNTAX_ERROR;
2472 if (!wait_local)
2473 return ERROR_OK;
2476 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2479 COMMAND_HANDLER(handle_soft_reset_halt_command)
2481 struct target *target = get_current_target(CMD_CTX);
2483 LOG_USER("requesting target halt and executing a soft reset");
2485 target_soft_reset_halt(target);
2487 return ERROR_OK;
2490 COMMAND_HANDLER(handle_reset_command)
2492 if (CMD_ARGC > 1)
2493 return ERROR_COMMAND_SYNTAX_ERROR;
2495 enum target_reset_mode reset_mode = RESET_RUN;
2496 if (CMD_ARGC == 1) {
2497 const Jim_Nvp *n;
2498 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2499 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2500 return ERROR_COMMAND_SYNTAX_ERROR;
2501 reset_mode = n->value;
2504 /* reset *all* targets */
2505 return target_process_reset(CMD_CTX, reset_mode);
2509 COMMAND_HANDLER(handle_resume_command)
2511 int current = 1;
2512 if (CMD_ARGC > 1)
2513 return ERROR_COMMAND_SYNTAX_ERROR;
2515 struct target *target = get_current_target(CMD_CTX);
2517 /* with no CMD_ARGV, resume from current pc, addr = 0,
2518 * with one arguments, addr = CMD_ARGV[0],
2519 * handle breakpoints, not debugging */
2520 uint32_t addr = 0;
2521 if (CMD_ARGC == 1) {
2522 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2523 current = 0;
2526 return target_resume(target, current, addr, 1, 0);
2529 COMMAND_HANDLER(handle_step_command)
2531 if (CMD_ARGC > 1)
2532 return ERROR_COMMAND_SYNTAX_ERROR;
2534 LOG_DEBUG("-");
2536 /* with no CMD_ARGV, step from current pc, addr = 0,
2537 * with one argument addr = CMD_ARGV[0],
2538 * handle breakpoints, debugging */
2539 uint32_t addr = 0;
2540 int current_pc = 1;
2541 if (CMD_ARGC == 1) {
2542 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2543 current_pc = 0;
2546 struct target *target = get_current_target(CMD_CTX);
2548 return target->type->step(target, current_pc, addr, 1);
2551 static void handle_md_output(struct command_context *cmd_ctx,
2552 struct target *target, uint32_t address, unsigned size,
2553 unsigned count, const uint8_t *buffer)
2555 const unsigned line_bytecnt = 32;
2556 unsigned line_modulo = line_bytecnt / size;
2558 char output[line_bytecnt * 4 + 1];
2559 unsigned output_len = 0;
2561 const char *value_fmt;
2562 switch (size) {
2563 case 4:
2564 value_fmt = "%8.8x ";
2565 break;
2566 case 2:
2567 value_fmt = "%4.4x ";
2568 break;
2569 case 1:
2570 value_fmt = "%2.2x ";
2571 break;
2572 default:
2573 /* "can't happen", caller checked */
2574 LOG_ERROR("invalid memory read size: %u", size);
2575 return;
2578 for (unsigned i = 0; i < count; i++) {
2579 if (i % line_modulo == 0) {
2580 output_len += snprintf(output + output_len,
2581 sizeof(output) - output_len,
2582 "0x%8.8x: ",
2583 (unsigned)(address + (i*size)));
2586 uint32_t value = 0;
2587 const uint8_t *value_ptr = buffer + i * size;
2588 switch (size) {
2589 case 4:
2590 value = target_buffer_get_u32(target, value_ptr);
2591 break;
2592 case 2:
2593 value = target_buffer_get_u16(target, value_ptr);
2594 break;
2595 case 1:
2596 value = *value_ptr;
2598 output_len += snprintf(output + output_len,
2599 sizeof(output) - output_len,
2600 value_fmt, value);
2602 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2603 command_print(cmd_ctx, "%s", output);
2604 output_len = 0;
2609 COMMAND_HANDLER(handle_md_command)
2611 if (CMD_ARGC < 1)
2612 return ERROR_COMMAND_SYNTAX_ERROR;
2614 unsigned size = 0;
2615 switch (CMD_NAME[2]) {
2616 case 'w':
2617 size = 4;
2618 break;
2619 case 'h':
2620 size = 2;
2621 break;
2622 case 'b':
2623 size = 1;
2624 break;
2625 default:
2626 return ERROR_COMMAND_SYNTAX_ERROR;
2629 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2630 int (*fn)(struct target *target,
2631 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2632 if (physical) {
2633 CMD_ARGC--;
2634 CMD_ARGV++;
2635 fn = target_read_phys_memory;
2636 } else
2637 fn = target_read_memory;
2638 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2639 return ERROR_COMMAND_SYNTAX_ERROR;
2641 uint32_t address;
2642 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2644 unsigned count = 1;
2645 if (CMD_ARGC == 2)
2646 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2648 uint8_t *buffer = calloc(count, size);
2650 struct target *target = get_current_target(CMD_CTX);
2651 int retval = fn(target, address, size, count, buffer);
2652 if (ERROR_OK == retval)
2653 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2655 free(buffer);
2657 return retval;
2660 typedef int (*target_write_fn)(struct target *target,
2661 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2663 static int target_write_memory_fast(struct target *target,
2664 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
2666 return target_write_buffer(target, address, size * count, buffer);
2669 static int target_fill_mem(struct target *target,
2670 uint32_t address,
2671 target_write_fn fn,
2672 unsigned data_size,
2673 /* value */
2674 uint32_t b,
2675 /* count */
2676 unsigned c)
2678 /* We have to write in reasonably large chunks to be able
2679 * to fill large memory areas with any sane speed */
2680 const unsigned chunk_size = 16384;
2681 uint8_t *target_buf = malloc(chunk_size * data_size);
2682 if (target_buf == NULL) {
2683 LOG_ERROR("Out of memory");
2684 return ERROR_FAIL;
2687 for (unsigned i = 0; i < chunk_size; i++) {
2688 switch (data_size) {
2689 case 4:
2690 target_buffer_set_u32(target, target_buf + i * data_size, b);
2691 break;
2692 case 2:
2693 target_buffer_set_u16(target, target_buf + i * data_size, b);
2694 break;
2695 case 1:
2696 target_buffer_set_u8(target, target_buf + i * data_size, b);
2697 break;
2698 default:
2699 exit(-1);
2703 int retval = ERROR_OK;
2705 for (unsigned x = 0; x < c; x += chunk_size) {
2706 unsigned current;
2707 current = c - x;
2708 if (current > chunk_size)
2709 current = chunk_size;
2710 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2711 if (retval != ERROR_OK)
2712 break;
2713 /* avoid GDB timeouts */
2714 keep_alive();
2716 free(target_buf);
2718 return retval;
2722 COMMAND_HANDLER(handle_mw_command)
2724 if (CMD_ARGC < 2)
2725 return ERROR_COMMAND_SYNTAX_ERROR;
2726 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2727 target_write_fn fn;
2728 if (physical) {
2729 CMD_ARGC--;
2730 CMD_ARGV++;
2731 fn = target_write_phys_memory;
2732 } else
2733 fn = target_write_memory_fast;
2734 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2735 return ERROR_COMMAND_SYNTAX_ERROR;
2737 uint32_t address;
2738 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2740 uint32_t value;
2741 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2743 unsigned count = 1;
2744 if (CMD_ARGC == 3)
2745 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2747 struct target *target = get_current_target(CMD_CTX);
2748 unsigned wordsize;
2749 switch (CMD_NAME[2]) {
2750 case 'w':
2751 wordsize = 4;
2752 break;
2753 case 'h':
2754 wordsize = 2;
2755 break;
2756 case 'b':
2757 wordsize = 1;
2758 break;
2759 default:
2760 return ERROR_COMMAND_SYNTAX_ERROR;
2763 return target_fill_mem(target, address, fn, wordsize, value, count);
2766 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2767 uint32_t *min_address, uint32_t *max_address)
2769 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2770 return ERROR_COMMAND_SYNTAX_ERROR;
2772 /* a base address isn't always necessary,
2773 * default to 0x0 (i.e. don't relocate) */
2774 if (CMD_ARGC >= 2) {
2775 uint32_t addr;
2776 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2777 image->base_address = addr;
2778 image->base_address_set = 1;
2779 } else
2780 image->base_address_set = 0;
2782 image->start_address_set = 0;
2784 if (CMD_ARGC >= 4)
2785 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2786 if (CMD_ARGC == 5) {
2787 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2788 /* use size (given) to find max (required) */
2789 *max_address += *min_address;
2792 if (*min_address > *max_address)
2793 return ERROR_COMMAND_SYNTAX_ERROR;
2795 return ERROR_OK;
2798 COMMAND_HANDLER(handle_load_image_command)
2800 uint8_t *buffer;
2801 size_t buf_cnt;
2802 uint32_t image_size;
2803 uint32_t min_address = 0;
2804 uint32_t max_address = 0xffffffff;
2805 int i;
2806 struct image image;
2808 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2809 &image, &min_address, &max_address);
2810 if (ERROR_OK != retval)
2811 return retval;
2813 struct target *target = get_current_target(CMD_CTX);
2815 struct duration bench;
2816 duration_start(&bench);
2818 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2819 return ERROR_OK;
2821 image_size = 0x0;
2822 retval = ERROR_OK;
2823 for (i = 0; i < image.num_sections; i++) {
2824 buffer = malloc(image.sections[i].size);
2825 if (buffer == NULL) {
2826 command_print(CMD_CTX,
2827 "error allocating buffer for section (%d bytes)",
2828 (int)(image.sections[i].size));
2829 break;
2832 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
2833 if (retval != ERROR_OK) {
2834 free(buffer);
2835 break;
2838 uint32_t offset = 0;
2839 uint32_t length = buf_cnt;
2841 /* DANGER!!! beware of unsigned comparision here!!! */
2843 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
2844 (image.sections[i].base_address < max_address)) {
2846 if (image.sections[i].base_address < min_address) {
2847 /* clip addresses below */
2848 offset += min_address-image.sections[i].base_address;
2849 length -= offset;
2852 if (image.sections[i].base_address + buf_cnt > max_address)
2853 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2855 retval = target_write_buffer(target,
2856 image.sections[i].base_address + offset, length, buffer + offset);
2857 if (retval != ERROR_OK) {
2858 free(buffer);
2859 break;
2861 image_size += length;
2862 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2863 (unsigned int)length,
2864 image.sections[i].base_address + offset);
2867 free(buffer);
2870 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
2871 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2872 "in %fs (%0.3f KiB/s)", image_size,
2873 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2876 image_close(&image);
2878 return retval;
2882 COMMAND_HANDLER(handle_dump_image_command)
2884 struct fileio fileio;
2885 uint8_t *buffer;
2886 int retval, retvaltemp;
2887 uint32_t address, size;
2888 struct duration bench;
2889 struct target *target = get_current_target(CMD_CTX);
2891 if (CMD_ARGC != 3)
2892 return ERROR_COMMAND_SYNTAX_ERROR;
2894 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2895 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2897 uint32_t buf_size = (size > 4096) ? 4096 : size;
2898 buffer = malloc(buf_size);
2899 if (!buffer)
2900 return ERROR_FAIL;
2902 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2903 if (retval != ERROR_OK) {
2904 free(buffer);
2905 return retval;
2908 duration_start(&bench);
2910 while (size > 0) {
2911 size_t size_written;
2912 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
2913 retval = target_read_buffer(target, address, this_run_size, buffer);
2914 if (retval != ERROR_OK)
2915 break;
2917 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2918 if (retval != ERROR_OK)
2919 break;
2921 size -= this_run_size;
2922 address += this_run_size;
2925 free(buffer);
2927 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
2928 int filesize;
2929 retval = fileio_size(&fileio, &filesize);
2930 if (retval != ERROR_OK)
2931 return retval;
2932 command_print(CMD_CTX,
2933 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
2934 duration_elapsed(&bench), duration_kbps(&bench, filesize));
2937 retvaltemp = fileio_close(&fileio);
2938 if (retvaltemp != ERROR_OK)
2939 return retvaltemp;
2941 return retval;
2944 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2946 uint8_t *buffer;
2947 size_t buf_cnt;
2948 uint32_t image_size;
2949 int i;
2950 int retval;
2951 uint32_t checksum = 0;
2952 uint32_t mem_checksum = 0;
2954 struct image image;
2956 struct target *target = get_current_target(CMD_CTX);
2958 if (CMD_ARGC < 1)
2959 return ERROR_COMMAND_SYNTAX_ERROR;
2961 if (!target) {
2962 LOG_ERROR("no target selected");
2963 return ERROR_FAIL;
2966 struct duration bench;
2967 duration_start(&bench);
2969 if (CMD_ARGC >= 2) {
2970 uint32_t addr;
2971 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2972 image.base_address = addr;
2973 image.base_address_set = 1;
2974 } else {
2975 image.base_address_set = 0;
2976 image.base_address = 0x0;
2979 image.start_address_set = 0;
2981 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
2982 if (retval != ERROR_OK)
2983 return retval;
2985 image_size = 0x0;
2986 int diffs = 0;
2987 retval = ERROR_OK;
2988 for (i = 0; i < image.num_sections; i++) {
2989 buffer = malloc(image.sections[i].size);
2990 if (buffer == NULL) {
2991 command_print(CMD_CTX,
2992 "error allocating buffer for section (%d bytes)",
2993 (int)(image.sections[i].size));
2994 break;
2996 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
2997 if (retval != ERROR_OK) {
2998 free(buffer);
2999 break;
3002 if (verify) {
3003 /* calculate checksum of image */
3004 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3005 if (retval != ERROR_OK) {
3006 free(buffer);
3007 break;
3010 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3011 if (retval != ERROR_OK) {
3012 free(buffer);
3013 break;
3016 if (checksum != mem_checksum) {
3017 /* failed crc checksum, fall back to a binary compare */
3018 uint8_t *data;
3020 if (diffs == 0)
3021 LOG_ERROR("checksum mismatch - attempting binary compare");
3023 data = (uint8_t *)malloc(buf_cnt);
3025 /* Can we use 32bit word accesses? */
3026 int size = 1;
3027 int count = buf_cnt;
3028 if ((count % 4) == 0) {
3029 size *= 4;
3030 count /= 4;
3032 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3033 if (retval == ERROR_OK) {
3034 uint32_t t;
3035 for (t = 0; t < buf_cnt; t++) {
3036 if (data[t] != buffer[t]) {
3037 command_print(CMD_CTX,
3038 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3039 diffs,
3040 (unsigned)(t + image.sections[i].base_address),
3041 data[t],
3042 buffer[t]);
3043 if (diffs++ >= 127) {
3044 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3045 free(data);
3046 free(buffer);
3047 goto done;
3050 keep_alive();
3053 free(data);
3055 } else {
3056 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3057 image.sections[i].base_address,
3058 buf_cnt);
3061 free(buffer);
3062 image_size += buf_cnt;
3064 if (diffs > 0)
3065 command_print(CMD_CTX, "No more differences found.");
3066 done:
3067 if (diffs > 0)
3068 retval = ERROR_FAIL;
3069 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3070 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3071 "in %fs (%0.3f KiB/s)", image_size,
3072 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3075 image_close(&image);
3077 return retval;
3080 COMMAND_HANDLER(handle_verify_image_command)
3082 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3085 COMMAND_HANDLER(handle_test_image_command)
3087 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3090 static int handle_bp_command_list(struct command_context *cmd_ctx)
3092 struct target *target = get_current_target(cmd_ctx);
3093 struct breakpoint *breakpoint = target->breakpoints;
3094 while (breakpoint) {
3095 if (breakpoint->type == BKPT_SOFT) {
3096 char *buf = buf_to_str(breakpoint->orig_instr,
3097 breakpoint->length, 16);
3098 command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3099 breakpoint->address,
3100 breakpoint->length,
3101 breakpoint->set, buf);
3102 free(buf);
3103 } else {
3104 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3105 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3106 breakpoint->asid,
3107 breakpoint->length, breakpoint->set);
3108 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3109 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3110 breakpoint->address,
3111 breakpoint->length, breakpoint->set);
3112 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3113 breakpoint->asid);
3114 } else
3115 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3116 breakpoint->address,
3117 breakpoint->length, breakpoint->set);
3120 breakpoint = breakpoint->next;
3122 return ERROR_OK;
3125 static int handle_bp_command_set(struct command_context *cmd_ctx,
3126 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3128 struct target *target = get_current_target(cmd_ctx);
3130 if (asid == 0) {
3131 int retval = breakpoint_add(target, addr, length, hw);
3132 if (ERROR_OK == retval)
3133 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3134 else {
3135 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3136 return retval;
3138 } else if (addr == 0) {
3139 int retval = context_breakpoint_add(target, asid, length, hw);
3140 if (ERROR_OK == retval)
3141 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3142 else {
3143 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3144 return retval;
3146 } else {
3147 int retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3148 if (ERROR_OK == retval)
3149 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3150 else {
3151 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3152 return retval;
3155 return ERROR_OK;
3158 COMMAND_HANDLER(handle_bp_command)
3160 uint32_t addr;
3161 uint32_t asid;
3162 uint32_t length;
3163 int hw = BKPT_SOFT;
3165 switch (CMD_ARGC) {
3166 case 0:
3167 return handle_bp_command_list(CMD_CTX);
3169 case 2:
3170 asid = 0;
3171 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3172 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3173 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3175 case 3:
3176 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3177 hw = BKPT_HARD;
3178 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3180 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3182 asid = 0;
3183 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3184 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3185 hw = BKPT_HARD;
3186 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3187 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3188 addr = 0;
3189 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3192 case 4:
3193 hw = BKPT_HARD;
3194 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3195 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3196 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3197 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3199 default:
3200 return ERROR_COMMAND_SYNTAX_ERROR;
3204 COMMAND_HANDLER(handle_rbp_command)
3206 if (CMD_ARGC != 1)
3207 return ERROR_COMMAND_SYNTAX_ERROR;
3209 uint32_t addr;
3210 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3212 struct target *target = get_current_target(CMD_CTX);
3213 breakpoint_remove(target, addr);
3215 return ERROR_OK;
3218 COMMAND_HANDLER(handle_wp_command)
3220 struct target *target = get_current_target(CMD_CTX);
3222 if (CMD_ARGC == 0) {
3223 struct watchpoint *watchpoint = target->watchpoints;
3225 while (watchpoint) {
3226 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3227 ", len: 0x%8.8" PRIx32
3228 ", r/w/a: %i, value: 0x%8.8" PRIx32
3229 ", mask: 0x%8.8" PRIx32,
3230 watchpoint->address,
3231 watchpoint->length,
3232 (int)watchpoint->rw,
3233 watchpoint->value,
3234 watchpoint->mask);
3235 watchpoint = watchpoint->next;
3237 return ERROR_OK;
3240 enum watchpoint_rw type = WPT_ACCESS;
3241 uint32_t addr = 0;
3242 uint32_t length = 0;
3243 uint32_t data_value = 0x0;
3244 uint32_t data_mask = 0xffffffff;
3246 switch (CMD_ARGC) {
3247 case 5:
3248 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3249 /* fall through */
3250 case 4:
3251 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3252 /* fall through */
3253 case 3:
3254 switch (CMD_ARGV[2][0]) {
3255 case 'r':
3256 type = WPT_READ;
3257 break;
3258 case 'w':
3259 type = WPT_WRITE;
3260 break;
3261 case 'a':
3262 type = WPT_ACCESS;
3263 break;
3264 default:
3265 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3266 return ERROR_COMMAND_SYNTAX_ERROR;
3268 /* fall through */
3269 case 2:
3270 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3271 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3272 break;
3274 default:
3275 return ERROR_COMMAND_SYNTAX_ERROR;
3278 int retval = watchpoint_add(target, addr, length, type,
3279 data_value, data_mask);
3280 if (ERROR_OK != retval)
3281 LOG_ERROR("Failure setting watchpoints");
3283 return retval;
3286 COMMAND_HANDLER(handle_rwp_command)
3288 if (CMD_ARGC != 1)
3289 return ERROR_COMMAND_SYNTAX_ERROR;
3291 uint32_t addr;
3292 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3294 struct target *target = get_current_target(CMD_CTX);
3295 watchpoint_remove(target, addr);
3297 return ERROR_OK;
3301 * Translate a virtual address to a physical address.
3303 * The low-level target implementation must have logged a detailed error
3304 * which is forwarded to telnet/GDB session.
3306 COMMAND_HANDLER(handle_virt2phys_command)
3308 if (CMD_ARGC != 1)
3309 return ERROR_COMMAND_SYNTAX_ERROR;
3311 uint32_t va;
3312 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3313 uint32_t pa;
3315 struct target *target = get_current_target(CMD_CTX);
3316 int retval = target->type->virt2phys(target, va, &pa);
3317 if (retval == ERROR_OK)
3318 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3320 return retval;
3323 static void writeData(FILE *f, const void *data, size_t len)
3325 size_t written = fwrite(data, 1, len, f);
3326 if (written != len)
3327 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3330 static void writeLong(FILE *f, int l)
3332 int i;
3333 for (i = 0; i < 4; i++) {
3334 char c = (l >> (i*8))&0xff;
3335 writeData(f, &c, 1);
3340 static void writeString(FILE *f, char *s)
3342 writeData(f, s, strlen(s));
3345 /* Dump a gmon.out histogram file. */
3346 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3348 uint32_t i;
3349 FILE *f = fopen(filename, "w");
3350 if (f == NULL)
3351 return;
3352 writeString(f, "gmon");
3353 writeLong(f, 0x00000001); /* Version */
3354 writeLong(f, 0); /* padding */
3355 writeLong(f, 0); /* padding */
3356 writeLong(f, 0); /* padding */
3358 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3359 writeData(f, &zero, 1);
3361 /* figure out bucket size */
3362 uint32_t min = samples[0];
3363 uint32_t max = samples[0];
3364 for (i = 0; i < sampleNum; i++) {
3365 if (min > samples[i])
3366 min = samples[i];
3367 if (max < samples[i])
3368 max = samples[i];
3371 int addressSpace = (max - min + 1);
3372 assert(addressSpace >= 2);
3374 static const uint32_t maxBuckets = 16 * 1024; /* maximum buckets. */
3375 uint32_t length = addressSpace;
3376 if (length > maxBuckets)
3377 length = maxBuckets;
3378 int *buckets = malloc(sizeof(int)*length);
3379 if (buckets == NULL) {
3380 fclose(f);
3381 return;
3383 memset(buckets, 0, sizeof(int) * length);
3384 for (i = 0; i < sampleNum; i++) {
3385 uint32_t address = samples[i];
3386 long long a = address - min;
3387 long long b = length - 1;
3388 long long c = addressSpace - 1;
3389 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3390 buckets[index_t]++;
3393 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3394 writeLong(f, min); /* low_pc */
3395 writeLong(f, max); /* high_pc */
3396 writeLong(f, length); /* # of samples */
3397 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3398 writeString(f, "seconds");
3399 for (i = 0; i < (15-strlen("seconds")); i++)
3400 writeData(f, &zero, 1);
3401 writeString(f, "s");
3403 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3405 char *data = malloc(2 * length);
3406 if (data != NULL) {
3407 for (i = 0; i < length; i++) {
3408 int val;
3409 val = buckets[i];
3410 if (val > 65535)
3411 val = 65535;
3412 data[i * 2] = val&0xff;
3413 data[i * 2 + 1] = (val >> 8) & 0xff;
3415 free(buckets);
3416 writeData(f, data, length * 2);
3417 free(data);
3418 } else
3419 free(buckets);
3421 fclose(f);
3424 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3425 * which will be used as a random sampling of PC */
3426 COMMAND_HANDLER(handle_profile_command)
3428 struct target *target = get_current_target(CMD_CTX);
3429 struct timeval timeout, now;
3431 gettimeofday(&timeout, NULL);
3432 if (CMD_ARGC != 2)
3433 return ERROR_COMMAND_SYNTAX_ERROR;
3434 unsigned offset;
3435 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3437 timeval_add_time(&timeout, offset, 0);
3440 * @todo: Some cores let us sample the PC without the
3441 * annoying halt/resume step; for example, ARMv7 PCSR.
3442 * Provide a way to use that more efficient mechanism.
3445 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3447 static const int maxSample = 10000;
3448 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3449 if (samples == NULL)
3450 return ERROR_OK;
3452 int numSamples = 0;
3453 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3454 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3456 int retval = ERROR_OK;
3457 for (;;) {
3458 target_poll(target);
3459 if (target->state == TARGET_HALTED) {
3460 uint32_t t = *((uint32_t *)reg->value);
3461 samples[numSamples++] = t;
3462 /* current pc, addr = 0, do not handle breakpoints, not debugging */
3463 retval = target_resume(target, 1, 0, 0, 0);
3464 target_poll(target);
3465 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3466 } else if (target->state == TARGET_RUNNING) {
3467 /* We want to quickly sample the PC. */
3468 retval = target_halt(target);
3469 if (retval != ERROR_OK) {
3470 free(samples);
3471 return retval;
3473 } else {
3474 command_print(CMD_CTX, "Target not halted or running");
3475 retval = ERROR_OK;
3476 break;
3478 if (retval != ERROR_OK)
3479 break;
3481 gettimeofday(&now, NULL);
3482 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec)
3483 && (now.tv_usec >= timeout.tv_usec))) {
3484 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3485 retval = target_poll(target);
3486 if (retval != ERROR_OK) {
3487 free(samples);
3488 return retval;
3490 if (target->state == TARGET_HALTED) {
3491 /* current pc, addr = 0, do not handle
3492 * breakpoints, not debugging */
3493 target_resume(target, 1, 0, 0, 0);
3495 retval = target_poll(target);
3496 if (retval != ERROR_OK) {
3497 free(samples);
3498 return retval;
3500 writeGmon(samples, numSamples, CMD_ARGV[1]);
3501 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3502 break;
3505 free(samples);
3507 return retval;
3510 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3512 char *namebuf;
3513 Jim_Obj *nameObjPtr, *valObjPtr;
3514 int result;
3516 namebuf = alloc_printf("%s(%d)", varname, idx);
3517 if (!namebuf)
3518 return JIM_ERR;
3520 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3521 valObjPtr = Jim_NewIntObj(interp, val);
3522 if (!nameObjPtr || !valObjPtr) {
3523 free(namebuf);
3524 return JIM_ERR;
3527 Jim_IncrRefCount(nameObjPtr);
3528 Jim_IncrRefCount(valObjPtr);
3529 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3530 Jim_DecrRefCount(interp, nameObjPtr);
3531 Jim_DecrRefCount(interp, valObjPtr);
3532 free(namebuf);
3533 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3534 return result;
3537 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3539 struct command_context *context;
3540 struct target *target;
3542 context = current_command_context(interp);
3543 assert(context != NULL);
3545 target = get_current_target(context);
3546 if (target == NULL) {
3547 LOG_ERROR("mem2array: no current target");
3548 return JIM_ERR;
3551 return target_mem2array(interp, target, argc - 1, argv + 1);
3554 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3556 long l;
3557 uint32_t width;
3558 int len;
3559 uint32_t addr;
3560 uint32_t count;
3561 uint32_t v;
3562 const char *varname;
3563 int n, e, retval;
3564 uint32_t i;
3566 /* argv[1] = name of array to receive the data
3567 * argv[2] = desired width
3568 * argv[3] = memory address
3569 * argv[4] = count of times to read
3571 if (argc != 4) {
3572 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3573 return JIM_ERR;
3575 varname = Jim_GetString(argv[0], &len);
3576 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3578 e = Jim_GetLong(interp, argv[1], &l);
3579 width = l;
3580 if (e != JIM_OK)
3581 return e;
3583 e = Jim_GetLong(interp, argv[2], &l);
3584 addr = l;
3585 if (e != JIM_OK)
3586 return e;
3587 e = Jim_GetLong(interp, argv[3], &l);
3588 len = l;
3589 if (e != JIM_OK)
3590 return e;
3591 switch (width) {
3592 case 8:
3593 width = 1;
3594 break;
3595 case 16:
3596 width = 2;
3597 break;
3598 case 32:
3599 width = 4;
3600 break;
3601 default:
3602 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3603 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3604 return JIM_ERR;
3606 if (len == 0) {
3607 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3608 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3609 return JIM_ERR;
3611 if ((addr + (len * width)) < addr) {
3612 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3613 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3614 return JIM_ERR;
3616 /* absurd transfer size? */
3617 if (len > 65536) {
3618 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3619 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3620 return JIM_ERR;
3623 if ((width == 1) ||
3624 ((width == 2) && ((addr & 1) == 0)) ||
3625 ((width == 4) && ((addr & 3) == 0))) {
3626 /* all is well */
3627 } else {
3628 char buf[100];
3629 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3630 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3631 addr,
3632 width);
3633 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3634 return JIM_ERR;
3637 /* Transfer loop */
3639 /* index counter */
3640 n = 0;
3642 size_t buffersize = 4096;
3643 uint8_t *buffer = malloc(buffersize);
3644 if (buffer == NULL)
3645 return JIM_ERR;
3647 /* assume ok */
3648 e = JIM_OK;
3649 while (len) {
3650 /* Slurp... in buffer size chunks */
3652 count = len; /* in objects.. */
3653 if (count > (buffersize / width))
3654 count = (buffersize / width);
3656 retval = target_read_memory(target, addr, width, count, buffer);
3657 if (retval != ERROR_OK) {
3658 /* BOO !*/
3659 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3660 (unsigned int)addr,
3661 (int)width,
3662 (int)count);
3663 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3664 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3665 e = JIM_ERR;
3666 break;
3667 } else {
3668 v = 0; /* shut up gcc */
3669 for (i = 0; i < count ; i++, n++) {
3670 switch (width) {
3671 case 4:
3672 v = target_buffer_get_u32(target, &buffer[i*width]);
3673 break;
3674 case 2:
3675 v = target_buffer_get_u16(target, &buffer[i*width]);
3676 break;
3677 case 1:
3678 v = buffer[i] & 0x0ff;
3679 break;
3681 new_int_array_element(interp, varname, n, v);
3683 len -= count;
3687 free(buffer);
3689 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3691 return e;
3694 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
3696 char *namebuf;
3697 Jim_Obj *nameObjPtr, *valObjPtr;
3698 int result;
3699 long l;
3701 namebuf = alloc_printf("%s(%d)", varname, idx);
3702 if (!namebuf)
3703 return JIM_ERR;
3705 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3706 if (!nameObjPtr) {
3707 free(namebuf);
3708 return JIM_ERR;
3711 Jim_IncrRefCount(nameObjPtr);
3712 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3713 Jim_DecrRefCount(interp, nameObjPtr);
3714 free(namebuf);
3715 if (valObjPtr == NULL)
3716 return JIM_ERR;
3718 result = Jim_GetLong(interp, valObjPtr, &l);
3719 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3720 *val = l;
3721 return result;
3724 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3726 struct command_context *context;
3727 struct target *target;
3729 context = current_command_context(interp);
3730 assert(context != NULL);
3732 target = get_current_target(context);
3733 if (target == NULL) {
3734 LOG_ERROR("array2mem: no current target");
3735 return JIM_ERR;
3738 return target_array2mem(interp, target, argc-1, argv + 1);
3741 static int target_array2mem(Jim_Interp *interp, struct target *target,
3742 int argc, Jim_Obj *const *argv)
3744 long l;
3745 uint32_t width;
3746 int len;
3747 uint32_t addr;
3748 uint32_t count;
3749 uint32_t v;
3750 const char *varname;
3751 int n, e, retval;
3752 uint32_t i;
3754 /* argv[1] = name of array to get the data
3755 * argv[2] = desired width
3756 * argv[3] = memory address
3757 * argv[4] = count to write
3759 if (argc != 4) {
3760 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3761 return JIM_ERR;
3763 varname = Jim_GetString(argv[0], &len);
3764 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3766 e = Jim_GetLong(interp, argv[1], &l);
3767 width = l;
3768 if (e != JIM_OK)
3769 return e;
3771 e = Jim_GetLong(interp, argv[2], &l);
3772 addr = l;
3773 if (e != JIM_OK)
3774 return e;
3775 e = Jim_GetLong(interp, argv[3], &l);
3776 len = l;
3777 if (e != JIM_OK)
3778 return e;
3779 switch (width) {
3780 case 8:
3781 width = 1;
3782 break;
3783 case 16:
3784 width = 2;
3785 break;
3786 case 32:
3787 width = 4;
3788 break;
3789 default:
3790 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3791 Jim_AppendStrings(interp, Jim_GetResult(interp),
3792 "Invalid width param, must be 8/16/32", NULL);
3793 return JIM_ERR;
3795 if (len == 0) {
3796 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3797 Jim_AppendStrings(interp, Jim_GetResult(interp),
3798 "array2mem: zero width read?", NULL);
3799 return JIM_ERR;
3801 if ((addr + (len * width)) < addr) {
3802 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3803 Jim_AppendStrings(interp, Jim_GetResult(interp),
3804 "array2mem: addr + len - wraps to zero?", NULL);
3805 return JIM_ERR;
3807 /* absurd transfer size? */
3808 if (len > 65536) {
3809 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3810 Jim_AppendStrings(interp, Jim_GetResult(interp),
3811 "array2mem: absurd > 64K item request", NULL);
3812 return JIM_ERR;
3815 if ((width == 1) ||
3816 ((width == 2) && ((addr & 1) == 0)) ||
3817 ((width == 4) && ((addr & 3) == 0))) {
3818 /* all is well */
3819 } else {
3820 char buf[100];
3821 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3822 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3823 (unsigned int)addr,
3824 (int)width);
3825 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3826 return JIM_ERR;
3829 /* Transfer loop */
3831 /* index counter */
3832 n = 0;
3833 /* assume ok */
3834 e = JIM_OK;
3836 size_t buffersize = 4096;
3837 uint8_t *buffer = malloc(buffersize);
3838 if (buffer == NULL)
3839 return JIM_ERR;
3841 while (len) {
3842 /* Slurp... in buffer size chunks */
3844 count = len; /* in objects.. */
3845 if (count > (buffersize / width))
3846 count = (buffersize / width);
3848 v = 0; /* shut up gcc */
3849 for (i = 0; i < count; i++, n++) {
3850 get_int_array_element(interp, varname, n, &v);
3851 switch (width) {
3852 case 4:
3853 target_buffer_set_u32(target, &buffer[i * width], v);
3854 break;
3855 case 2:
3856 target_buffer_set_u16(target, &buffer[i * width], v);
3857 break;
3858 case 1:
3859 buffer[i] = v & 0x0ff;
3860 break;
3863 len -= count;
3865 retval = target_write_memory(target, addr, width, count, buffer);
3866 if (retval != ERROR_OK) {
3867 /* BOO !*/
3868 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3869 (unsigned int)addr,
3870 (int)width,
3871 (int)count);
3872 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3873 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3874 e = JIM_ERR;
3875 break;
3879 free(buffer);
3881 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3883 return e;
3886 /* FIX? should we propagate errors here rather than printing them
3887 * and continuing?
3889 void target_handle_event(struct target *target, enum target_event e)
3891 struct target_event_action *teap;
3893 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3894 if (teap->event == e) {
3895 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3896 target->target_number,
3897 target_name(target),
3898 target_type_name(target),
3900 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3901 Jim_GetString(teap->body, NULL));
3902 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
3903 Jim_MakeErrorMessage(teap->interp);
3904 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
3911 * Returns true only if the target has a handler for the specified event.
3913 bool target_has_event_action(struct target *target, enum target_event event)
3915 struct target_event_action *teap;
3917 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3918 if (teap->event == event)
3919 return true;
3921 return false;
3924 enum target_cfg_param {
3925 TCFG_TYPE,
3926 TCFG_EVENT,
3927 TCFG_WORK_AREA_VIRT,
3928 TCFG_WORK_AREA_PHYS,
3929 TCFG_WORK_AREA_SIZE,
3930 TCFG_WORK_AREA_BACKUP,
3931 TCFG_ENDIAN,
3932 TCFG_VARIANT,
3933 TCFG_COREID,
3934 TCFG_CHAIN_POSITION,
3935 TCFG_DBGBASE,
3936 TCFG_RTOS,
3939 static Jim_Nvp nvp_config_opts[] = {
3940 { .name = "-type", .value = TCFG_TYPE },
3941 { .name = "-event", .value = TCFG_EVENT },
3942 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3943 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3944 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3945 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3946 { .name = "-endian" , .value = TCFG_ENDIAN },
3947 { .name = "-variant", .value = TCFG_VARIANT },
3948 { .name = "-coreid", .value = TCFG_COREID },
3949 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3950 { .name = "-dbgbase", .value = TCFG_DBGBASE },
3951 { .name = "-rtos", .value = TCFG_RTOS },
3952 { .name = NULL, .value = -1 }
3955 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3957 Jim_Nvp *n;
3958 Jim_Obj *o;
3959 jim_wide w;
3960 char *cp;
3961 int e;
3963 /* parse config or cget options ... */
3964 while (goi->argc > 0) {
3965 Jim_SetEmptyResult(goi->interp);
3966 /* Jim_GetOpt_Debug(goi); */
3968 if (target->type->target_jim_configure) {
3969 /* target defines a configure function */
3970 /* target gets first dibs on parameters */
3971 e = (*(target->type->target_jim_configure))(target, goi);
3972 if (e == JIM_OK) {
3973 /* more? */
3974 continue;
3976 if (e == JIM_ERR) {
3977 /* An error */
3978 return e;
3980 /* otherwise we 'continue' below */
3982 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3983 if (e != JIM_OK) {
3984 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3985 return e;
3987 switch (n->value) {
3988 case TCFG_TYPE:
3989 /* not setable */
3990 if (goi->isconfigure) {
3991 Jim_SetResultFormatted(goi->interp,
3992 "not settable: %s", n->name);
3993 return JIM_ERR;
3994 } else {
3995 no_params:
3996 if (goi->argc != 0) {
3997 Jim_WrongNumArgs(goi->interp,
3998 goi->argc, goi->argv,
3999 "NO PARAMS");
4000 return JIM_ERR;
4003 Jim_SetResultString(goi->interp,
4004 target_type_name(target), -1);
4005 /* loop for more */
4006 break;
4007 case TCFG_EVENT:
4008 if (goi->argc == 0) {
4009 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4010 return JIM_ERR;
4013 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4014 if (e != JIM_OK) {
4015 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4016 return e;
4019 if (goi->isconfigure) {
4020 if (goi->argc != 1) {
4021 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4022 return JIM_ERR;
4024 } else {
4025 if (goi->argc != 0) {
4026 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4027 return JIM_ERR;
4032 struct target_event_action *teap;
4034 teap = target->event_action;
4035 /* replace existing? */
4036 while (teap) {
4037 if (teap->event == (enum target_event)n->value)
4038 break;
4039 teap = teap->next;
4042 if (goi->isconfigure) {
4043 bool replace = true;
4044 if (teap == NULL) {
4045 /* create new */
4046 teap = calloc(1, sizeof(*teap));
4047 replace = false;
4049 teap->event = n->value;
4050 teap->interp = goi->interp;
4051 Jim_GetOpt_Obj(goi, &o);
4052 if (teap->body)
4053 Jim_DecrRefCount(teap->interp, teap->body);
4054 teap->body = Jim_DuplicateObj(goi->interp, o);
4056 * FIXME:
4057 * Tcl/TK - "tk events" have a nice feature.
4058 * See the "BIND" command.
4059 * We should support that here.
4060 * You can specify %X and %Y in the event code.
4061 * The idea is: %T - target name.
4062 * The idea is: %N - target number
4063 * The idea is: %E - event name.
4065 Jim_IncrRefCount(teap->body);
4067 if (!replace) {
4068 /* add to head of event list */
4069 teap->next = target->event_action;
4070 target->event_action = teap;
4072 Jim_SetEmptyResult(goi->interp);
4073 } else {
4074 /* get */
4075 if (teap == NULL)
4076 Jim_SetEmptyResult(goi->interp);
4077 else
4078 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4081 /* loop for more */
4082 break;
4084 case TCFG_WORK_AREA_VIRT:
4085 if (goi->isconfigure) {
4086 target_free_all_working_areas(target);
4087 e = Jim_GetOpt_Wide(goi, &w);
4088 if (e != JIM_OK)
4089 return e;
4090 target->working_area_virt = w;
4091 target->working_area_virt_spec = true;
4092 } else {
4093 if (goi->argc != 0)
4094 goto no_params;
4096 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4097 /* loop for more */
4098 break;
4100 case TCFG_WORK_AREA_PHYS:
4101 if (goi->isconfigure) {
4102 target_free_all_working_areas(target);
4103 e = Jim_GetOpt_Wide(goi, &w);
4104 if (e != JIM_OK)
4105 return e;
4106 target->working_area_phys = w;
4107 target->working_area_phys_spec = true;
4108 } else {
4109 if (goi->argc != 0)
4110 goto no_params;
4112 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4113 /* loop for more */
4114 break;
4116 case TCFG_WORK_AREA_SIZE:
4117 if (goi->isconfigure) {
4118 target_free_all_working_areas(target);
4119 e = Jim_GetOpt_Wide(goi, &w);
4120 if (e != JIM_OK)
4121 return e;
4122 target->working_area_size = w;
4123 } else {
4124 if (goi->argc != 0)
4125 goto no_params;
4127 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4128 /* loop for more */
4129 break;
4131 case TCFG_WORK_AREA_BACKUP:
4132 if (goi->isconfigure) {
4133 target_free_all_working_areas(target);
4134 e = Jim_GetOpt_Wide(goi, &w);
4135 if (e != JIM_OK)
4136 return e;
4137 /* make this exactly 1 or 0 */
4138 target->backup_working_area = (!!w);
4139 } else {
4140 if (goi->argc != 0)
4141 goto no_params;
4143 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4144 /* loop for more e*/
4145 break;
4148 case TCFG_ENDIAN:
4149 if (goi->isconfigure) {
4150 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4151 if (e != JIM_OK) {
4152 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4153 return e;
4155 target->endianness = n->value;
4156 } else {
4157 if (goi->argc != 0)
4158 goto no_params;
4160 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4161 if (n->name == NULL) {
4162 target->endianness = TARGET_LITTLE_ENDIAN;
4163 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4165 Jim_SetResultString(goi->interp, n->name, -1);
4166 /* loop for more */
4167 break;
4169 case TCFG_VARIANT:
4170 if (goi->isconfigure) {
4171 if (goi->argc < 1) {
4172 Jim_SetResultFormatted(goi->interp,
4173 "%s ?STRING?",
4174 n->name);
4175 return JIM_ERR;
4177 if (target->variant)
4178 free((void *)(target->variant));
4179 e = Jim_GetOpt_String(goi, &cp, NULL);
4180 if (e != JIM_OK)
4181 return e;
4182 target->variant = strdup(cp);
4183 } else {
4184 if (goi->argc != 0)
4185 goto no_params;
4187 Jim_SetResultString(goi->interp, target->variant, -1);
4188 /* loop for more */
4189 break;
4191 case TCFG_COREID:
4192 if (goi->isconfigure) {
4193 e = Jim_GetOpt_Wide(goi, &w);
4194 if (e != JIM_OK)
4195 return e;
4196 target->coreid = (int32_t)w;
4197 } else {
4198 if (goi->argc != 0)
4199 goto no_params;
4201 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4202 /* loop for more */
4203 break;
4205 case TCFG_CHAIN_POSITION:
4206 if (goi->isconfigure) {
4207 Jim_Obj *o_t;
4208 struct jtag_tap *tap;
4209 target_free_all_working_areas(target);
4210 e = Jim_GetOpt_Obj(goi, &o_t);
4211 if (e != JIM_OK)
4212 return e;
4213 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4214 if (tap == NULL)
4215 return JIM_ERR;
4216 /* make this exactly 1 or 0 */
4217 target->tap = tap;
4218 } else {
4219 if (goi->argc != 0)
4220 goto no_params;
4222 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4223 /* loop for more e*/
4224 break;
4225 case TCFG_DBGBASE:
4226 if (goi->isconfigure) {
4227 e = Jim_GetOpt_Wide(goi, &w);
4228 if (e != JIM_OK)
4229 return e;
4230 target->dbgbase = (uint32_t)w;
4231 target->dbgbase_set = true;
4232 } else {
4233 if (goi->argc != 0)
4234 goto no_params;
4236 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4237 /* loop for more */
4238 break;
4240 case TCFG_RTOS:
4241 /* RTOS */
4243 int result = rtos_create(goi, target);
4244 if (result != JIM_OK)
4245 return result;
4247 /* loop for more */
4248 break;
4250 } /* while (goi->argc) */
4253 /* done - we return */
4254 return JIM_OK;
4257 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4259 Jim_GetOptInfo goi;
4261 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4262 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4263 int need_args = 1 + goi.isconfigure;
4264 if (goi.argc < need_args) {
4265 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4266 goi.isconfigure
4267 ? "missing: -option VALUE ..."
4268 : "missing: -option ...");
4269 return JIM_ERR;
4271 struct target *target = Jim_CmdPrivData(goi.interp);
4272 return target_configure(&goi, target);
4275 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4277 const char *cmd_name = Jim_GetString(argv[0], NULL);
4279 Jim_GetOptInfo goi;
4280 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4282 if (goi.argc < 2 || goi.argc > 4) {
4283 Jim_SetResultFormatted(goi.interp,
4284 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4285 return JIM_ERR;
4288 target_write_fn fn;
4289 fn = target_write_memory_fast;
4291 int e;
4292 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4293 /* consume it */
4294 struct Jim_Obj *obj;
4295 e = Jim_GetOpt_Obj(&goi, &obj);
4296 if (e != JIM_OK)
4297 return e;
4299 fn = target_write_phys_memory;
4302 jim_wide a;
4303 e = Jim_GetOpt_Wide(&goi, &a);
4304 if (e != JIM_OK)
4305 return e;
4307 jim_wide b;
4308 e = Jim_GetOpt_Wide(&goi, &b);
4309 if (e != JIM_OK)
4310 return e;
4312 jim_wide c = 1;
4313 if (goi.argc == 1) {
4314 e = Jim_GetOpt_Wide(&goi, &c);
4315 if (e != JIM_OK)
4316 return e;
4319 /* all args must be consumed */
4320 if (goi.argc != 0)
4321 return JIM_ERR;
4323 struct target *target = Jim_CmdPrivData(goi.interp);
4324 unsigned data_size;
4325 if (strcasecmp(cmd_name, "mww") == 0)
4326 data_size = 4;
4327 else if (strcasecmp(cmd_name, "mwh") == 0)
4328 data_size = 2;
4329 else if (strcasecmp(cmd_name, "mwb") == 0)
4330 data_size = 1;
4331 else {
4332 LOG_ERROR("command '%s' unknown: ", cmd_name);
4333 return JIM_ERR;
4336 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4340 * @brief Reads an array of words/halfwords/bytes from target memory starting at specified address.
4342 * Usage: mdw [phys] <address> [<count>] - for 32 bit reads
4343 * mdh [phys] <address> [<count>] - for 16 bit reads
4344 * mdb [phys] <address> [<count>] - for 8 bit reads
4346 * Count defaults to 1.
4348 * Calls target_read_memory or target_read_phys_memory depending on
4349 * the presence of the "phys" argument
4350 * Reads the target memory in blocks of max. 32 bytes, and returns an array of ints formatted
4351 * to int representation in base16.
4352 * Also outputs read data in a human readable form using command_print
4354 * @param phys if present target_read_phys_memory will be used instead of target_read_memory
4355 * @param address address where to start the read. May be specified in decimal or hex using the standard "0x" prefix
4356 * @param count optional count parameter to read an array of values. If not specified, defaults to 1.
4357 * @returns: JIM_ERR on error or JIM_OK on success and sets the result string to an array of ascii formatted numbers
4358 * on success, with [<count>] number of elements.
4360 * In case of little endian target:
4361 * Example1: "mdw 0x00000000" returns "10123456"
4362 * Exmaple2: "mdh 0x00000000 1" returns "3456"
4363 * Example3: "mdb 0x00000000" returns "56"
4364 * Example4: "mdh 0x00000000 2" returns "3456 1012"
4365 * Example5: "mdb 0x00000000 3" returns "56 34 12"
4367 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4369 const char *cmd_name = Jim_GetString(argv[0], NULL);
4371 Jim_GetOptInfo goi;
4372 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4374 if ((goi.argc < 1) || (goi.argc > 3)) {
4375 Jim_SetResultFormatted(goi.interp,
4376 "usage: %s [phys] <address> [<count>]", cmd_name);
4377 return JIM_ERR;
4380 int (*fn)(struct target *target,
4381 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4382 fn = target_read_memory;
4384 int e;
4385 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4386 /* consume it */
4387 struct Jim_Obj *obj;
4388 e = Jim_GetOpt_Obj(&goi, &obj);
4389 if (e != JIM_OK)
4390 return e;
4392 fn = target_read_phys_memory;
4395 /* Read address parameter */
4396 jim_wide addr;
4397 e = Jim_GetOpt_Wide(&goi, &addr);
4398 if (e != JIM_OK)
4399 return JIM_ERR;
4401 /* If next parameter exists, read it out as the count parameter, if not, set it to 1 (default) */
4402 jim_wide count;
4403 if (goi.argc == 1) {
4404 e = Jim_GetOpt_Wide(&goi, &count);
4405 if (e != JIM_OK)
4406 return JIM_ERR;
4407 } else
4408 count = 1;
4410 /* all args must be consumed */
4411 if (goi.argc != 0)
4412 return JIM_ERR;
4414 jim_wide dwidth = 1; /* shut up gcc */
4415 if (strcasecmp(cmd_name, "mdw") == 0)
4416 dwidth = 4;
4417 else if (strcasecmp(cmd_name, "mdh") == 0)
4418 dwidth = 2;
4419 else if (strcasecmp(cmd_name, "mdb") == 0)
4420 dwidth = 1;
4421 else {
4422 LOG_ERROR("command '%s' unknown: ", cmd_name);
4423 return JIM_ERR;
4426 /* convert count to "bytes" */
4427 int bytes = count * dwidth;
4429 struct target *target = Jim_CmdPrivData(goi.interp);
4430 uint8_t target_buf[32];
4431 jim_wide x, y, z;
4432 while (bytes > 0) {
4433 y = (bytes < 16) ? bytes : 16; /* y = min(bytes, 16); */
4435 /* Try to read out next block */
4436 e = fn(target, addr, dwidth, y / dwidth, target_buf);
4438 if (e != ERROR_OK) {
4439 Jim_SetResultFormatted(interp, "error reading target @ 0x%08lx", (long)addr);
4440 return JIM_ERR;
4443 command_print_sameline(NULL, "0x%08x ", (int)(addr));
4444 switch (dwidth) {
4445 case 4:
4446 for (x = 0; x < 16 && x < y; x += 4) {
4447 z = target_buffer_get_u32(target, &(target_buf[x]));
4448 command_print_sameline(NULL, "%08x ", (int)(z));
4450 for (; (x < 16) ; x += 4)
4451 command_print_sameline(NULL, " ");
4452 break;
4453 case 2:
4454 for (x = 0; x < 16 && x < y; x += 2) {
4455 z = target_buffer_get_u16(target, &(target_buf[x]));
4456 command_print_sameline(NULL, "%04x ", (int)(z));
4458 for (; (x < 16) ; x += 2)
4459 command_print_sameline(NULL, " ");
4460 break;
4461 case 1:
4462 default:
4463 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4464 z = target_buffer_get_u8(target, &(target_buf[x]));
4465 command_print_sameline(NULL, "%02x ", (int)(z));
4467 for (; (x < 16) ; x += 1)
4468 command_print_sameline(NULL, " ");
4469 break;
4471 /* ascii-ify the bytes */
4472 for (x = 0 ; x < y ; x++) {
4473 if ((target_buf[x] >= 0x20) &&
4474 (target_buf[x] <= 0x7e)) {
4475 /* good */
4476 } else {
4477 /* smack it */
4478 target_buf[x] = '.';
4481 /* space pad */
4482 while (x < 16) {
4483 target_buf[x] = ' ';
4484 x++;
4486 /* terminate */
4487 target_buf[16] = 0;
4488 /* print - with a newline */
4489 command_print_sameline(NULL, "%s\n", target_buf);
4490 /* NEXT... */
4491 bytes -= 16;
4492 addr += 16;
4494 return JIM_OK;
4497 static int jim_target_mem2array(Jim_Interp *interp,
4498 int argc, Jim_Obj *const *argv)
4500 struct target *target = Jim_CmdPrivData(interp);
4501 return target_mem2array(interp, target, argc - 1, argv + 1);
4504 static int jim_target_array2mem(Jim_Interp *interp,
4505 int argc, Jim_Obj *const *argv)
4507 struct target *target = Jim_CmdPrivData(interp);
4508 return target_array2mem(interp, target, argc - 1, argv + 1);
4511 static int jim_target_tap_disabled(Jim_Interp *interp)
4513 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4514 return JIM_ERR;
4517 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4519 if (argc != 1) {
4520 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4521 return JIM_ERR;
4523 struct target *target = Jim_CmdPrivData(interp);
4524 if (!target->tap->enabled)
4525 return jim_target_tap_disabled(interp);
4527 int e = target->type->examine(target);
4528 if (e != ERROR_OK)
4529 return JIM_ERR;
4530 return JIM_OK;
4533 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4535 if (argc != 1) {
4536 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4537 return JIM_ERR;
4539 struct target *target = Jim_CmdPrivData(interp);
4541 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4542 return JIM_ERR;
4544 return JIM_OK;
4547 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4549 if (argc != 1) {
4550 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4551 return JIM_ERR;
4553 struct target *target = Jim_CmdPrivData(interp);
4554 if (!target->tap->enabled)
4555 return jim_target_tap_disabled(interp);
4557 int e;
4558 if (!(target_was_examined(target)))
4559 e = ERROR_TARGET_NOT_EXAMINED;
4560 else
4561 e = target->type->poll(target);
4562 if (e != ERROR_OK)
4563 return JIM_ERR;
4564 return JIM_OK;
4567 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4569 Jim_GetOptInfo goi;
4570 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4572 if (goi.argc != 2) {
4573 Jim_WrongNumArgs(interp, 0, argv,
4574 "([tT]|[fF]|assert|deassert) BOOL");
4575 return JIM_ERR;
4578 Jim_Nvp *n;
4579 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4580 if (e != JIM_OK) {
4581 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4582 return e;
4584 /* the halt or not param */
4585 jim_wide a;
4586 e = Jim_GetOpt_Wide(&goi, &a);
4587 if (e != JIM_OK)
4588 return e;
4590 struct target *target = Jim_CmdPrivData(goi.interp);
4591 if (!target->tap->enabled)
4592 return jim_target_tap_disabled(interp);
4593 if (!(target_was_examined(target))) {
4594 LOG_ERROR("Target not examined yet");
4595 return ERROR_TARGET_NOT_EXAMINED;
4597 if (!target->type->assert_reset || !target->type->deassert_reset) {
4598 Jim_SetResultFormatted(interp,
4599 "No target-specific reset for %s",
4600 target_name(target));
4601 return JIM_ERR;
4603 /* determine if we should halt or not. */
4604 target->reset_halt = !!a;
4605 /* When this happens - all workareas are invalid. */
4606 target_free_all_working_areas_restore(target, 0);
4608 /* do the assert */
4609 if (n->value == NVP_ASSERT)
4610 e = target->type->assert_reset(target);
4611 else
4612 e = target->type->deassert_reset(target);
4613 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4616 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4618 if (argc != 1) {
4619 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4620 return JIM_ERR;
4622 struct target *target = Jim_CmdPrivData(interp);
4623 if (!target->tap->enabled)
4624 return jim_target_tap_disabled(interp);
4625 int e = target->type->halt(target);
4626 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4629 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4631 Jim_GetOptInfo goi;
4632 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4634 /* params: <name> statename timeoutmsecs */
4635 if (goi.argc != 2) {
4636 const char *cmd_name = Jim_GetString(argv[0], NULL);
4637 Jim_SetResultFormatted(goi.interp,
4638 "%s <state_name> <timeout_in_msec>", cmd_name);
4639 return JIM_ERR;
4642 Jim_Nvp *n;
4643 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4644 if (e != JIM_OK) {
4645 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
4646 return e;
4648 jim_wide a;
4649 e = Jim_GetOpt_Wide(&goi, &a);
4650 if (e != JIM_OK)
4651 return e;
4652 struct target *target = Jim_CmdPrivData(interp);
4653 if (!target->tap->enabled)
4654 return jim_target_tap_disabled(interp);
4656 e = target_wait_state(target, n->value, a);
4657 if (e != ERROR_OK) {
4658 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4659 Jim_SetResultFormatted(goi.interp,
4660 "target: %s wait %s fails (%#s) %s",
4661 target_name(target), n->name,
4662 eObj, target_strerror_safe(e));
4663 Jim_FreeNewObj(interp, eObj);
4664 return JIM_ERR;
4666 return JIM_OK;
4668 /* List for human, Events defined for this target.
4669 * scripts/programs should use 'name cget -event NAME'
4671 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4673 struct command_context *cmd_ctx = current_command_context(interp);
4674 assert(cmd_ctx != NULL);
4676 struct target *target = Jim_CmdPrivData(interp);
4677 struct target_event_action *teap = target->event_action;
4678 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4679 target->target_number,
4680 target_name(target));
4681 command_print(cmd_ctx, "%-25s | Body", "Event");
4682 command_print(cmd_ctx, "------------------------- | "
4683 "----------------------------------------");
4684 while (teap) {
4685 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4686 command_print(cmd_ctx, "%-25s | %s",
4687 opt->name, Jim_GetString(teap->body, NULL));
4688 teap = teap->next;
4690 command_print(cmd_ctx, "***END***");
4691 return JIM_OK;
4693 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4695 if (argc != 1) {
4696 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4697 return JIM_ERR;
4699 struct target *target = Jim_CmdPrivData(interp);
4700 Jim_SetResultString(interp, target_state_name(target), -1);
4701 return JIM_OK;
4703 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4705 Jim_GetOptInfo goi;
4706 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4707 if (goi.argc != 1) {
4708 const char *cmd_name = Jim_GetString(argv[0], NULL);
4709 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4710 return JIM_ERR;
4712 Jim_Nvp *n;
4713 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4714 if (e != JIM_OK) {
4715 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4716 return e;
4718 struct target *target = Jim_CmdPrivData(interp);
4719 target_handle_event(target, n->value);
4720 return JIM_OK;
4723 static const struct command_registration target_instance_command_handlers[] = {
4725 .name = "configure",
4726 .mode = COMMAND_CONFIG,
4727 .jim_handler = jim_target_configure,
4728 .help = "configure a new target for use",
4729 .usage = "[target_attribute ...]",
4732 .name = "cget",
4733 .mode = COMMAND_ANY,
4734 .jim_handler = jim_target_configure,
4735 .help = "returns the specified target attribute",
4736 .usage = "target_attribute",
4739 .name = "mww",
4740 .mode = COMMAND_EXEC,
4741 .jim_handler = jim_target_mw,
4742 .help = "Write 32-bit word(s) to target memory",
4743 .usage = "address data [count]",
4746 .name = "mwh",
4747 .mode = COMMAND_EXEC,
4748 .jim_handler = jim_target_mw,
4749 .help = "Write 16-bit half-word(s) to target memory",
4750 .usage = "address data [count]",
4753 .name = "mwb",
4754 .mode = COMMAND_EXEC,
4755 .jim_handler = jim_target_mw,
4756 .help = "Write byte(s) to target memory",
4757 .usage = "address data [count]",
4760 .name = "mdw",
4761 .mode = COMMAND_EXEC,
4762 .jim_handler = jim_target_md,
4763 .help = "Display target memory as 32-bit words",
4764 .usage = "address [count]",
4767 .name = "mdh",
4768 .mode = COMMAND_EXEC,
4769 .jim_handler = jim_target_md,
4770 .help = "Display target memory as 16-bit half-words",
4771 .usage = "address [count]",
4774 .name = "mdb",
4775 .mode = COMMAND_EXEC,
4776 .jim_handler = jim_target_md,
4777 .help = "Display target memory as 8-bit bytes",
4778 .usage = "address [count]",
4781 .name = "array2mem",
4782 .mode = COMMAND_EXEC,
4783 .jim_handler = jim_target_array2mem,
4784 .help = "Writes Tcl array of 8/16/32 bit numbers "
4785 "to target memory",
4786 .usage = "arrayname bitwidth address count",
4789 .name = "mem2array",
4790 .mode = COMMAND_EXEC,
4791 .jim_handler = jim_target_mem2array,
4792 .help = "Loads Tcl array of 8/16/32 bit numbers "
4793 "from target memory",
4794 .usage = "arrayname bitwidth address count",
4797 .name = "eventlist",
4798 .mode = COMMAND_EXEC,
4799 .jim_handler = jim_target_event_list,
4800 .help = "displays a table of events defined for this target",
4803 .name = "curstate",
4804 .mode = COMMAND_EXEC,
4805 .jim_handler = jim_target_current_state,
4806 .help = "displays the current state of this target",
4809 .name = "arp_examine",
4810 .mode = COMMAND_EXEC,
4811 .jim_handler = jim_target_examine,
4812 .help = "used internally for reset processing",
4815 .name = "arp_halt_gdb",
4816 .mode = COMMAND_EXEC,
4817 .jim_handler = jim_target_halt_gdb,
4818 .help = "used internally for reset processing to halt GDB",
4821 .name = "arp_poll",
4822 .mode = COMMAND_EXEC,
4823 .jim_handler = jim_target_poll,
4824 .help = "used internally for reset processing",
4827 .name = "arp_reset",
4828 .mode = COMMAND_EXEC,
4829 .jim_handler = jim_target_reset,
4830 .help = "used internally for reset processing",
4833 .name = "arp_halt",
4834 .mode = COMMAND_EXEC,
4835 .jim_handler = jim_target_halt,
4836 .help = "used internally for reset processing",
4839 .name = "arp_waitstate",
4840 .mode = COMMAND_EXEC,
4841 .jim_handler = jim_target_wait_state,
4842 .help = "used internally for reset processing",
4845 .name = "invoke-event",
4846 .mode = COMMAND_EXEC,
4847 .jim_handler = jim_target_invoke_event,
4848 .help = "invoke handler for specified event",
4849 .usage = "event_name",
4851 COMMAND_REGISTRATION_DONE
4854 static int target_create(Jim_GetOptInfo *goi)
4856 Jim_Obj *new_cmd;
4857 Jim_Cmd *cmd;
4858 const char *cp;
4859 char *cp2;
4860 int e;
4861 int x;
4862 struct target *target;
4863 struct command_context *cmd_ctx;
4865 cmd_ctx = current_command_context(goi->interp);
4866 assert(cmd_ctx != NULL);
4868 if (goi->argc < 3) {
4869 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4870 return JIM_ERR;
4873 /* COMMAND */
4874 Jim_GetOpt_Obj(goi, &new_cmd);
4875 /* does this command exist? */
4876 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4877 if (cmd) {
4878 cp = Jim_GetString(new_cmd, NULL);
4879 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
4880 return JIM_ERR;
4883 /* TYPE */
4884 e = Jim_GetOpt_String(goi, &cp2, NULL);
4885 if (e != JIM_OK)
4886 return e;
4887 cp = cp2;
4888 /* now does target type exist */
4889 for (x = 0 ; target_types[x] ; x++) {
4890 if (0 == strcmp(cp, target_types[x]->name)) {
4891 /* found */
4892 break;
4895 /* check for deprecated name */
4896 if (target_types[x]->deprecated_name) {
4897 if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
4898 /* found */
4899 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
4900 break;
4904 if (target_types[x] == NULL) {
4905 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
4906 for (x = 0 ; target_types[x] ; x++) {
4907 if (target_types[x + 1]) {
4908 Jim_AppendStrings(goi->interp,
4909 Jim_GetResult(goi->interp),
4910 target_types[x]->name,
4911 ", ", NULL);
4912 } else {
4913 Jim_AppendStrings(goi->interp,
4914 Jim_GetResult(goi->interp),
4915 " or ",
4916 target_types[x]->name, NULL);
4919 return JIM_ERR;
4922 /* Create it */
4923 target = calloc(1, sizeof(struct target));
4924 /* set target number */
4925 target->target_number = new_target_number();
4927 /* allocate memory for each unique target type */
4928 target->type = (struct target_type *)calloc(1, sizeof(struct target_type));
4930 memcpy(target->type, target_types[x], sizeof(struct target_type));
4932 /* will be set by "-endian" */
4933 target->endianness = TARGET_ENDIAN_UNKNOWN;
4935 /* default to first core, override with -coreid */
4936 target->coreid = 0;
4938 target->working_area = 0x0;
4939 target->working_area_size = 0x0;
4940 target->working_areas = NULL;
4941 target->backup_working_area = 0;
4943 target->state = TARGET_UNKNOWN;
4944 target->debug_reason = DBG_REASON_UNDEFINED;
4945 target->reg_cache = NULL;
4946 target->breakpoints = NULL;
4947 target->watchpoints = NULL;
4948 target->next = NULL;
4949 target->arch_info = NULL;
4951 target->display = 1;
4953 target->halt_issued = false;
4955 /* initialize trace information */
4956 target->trace_info = malloc(sizeof(struct trace));
4957 target->trace_info->num_trace_points = 0;
4958 target->trace_info->trace_points_size = 0;
4959 target->trace_info->trace_points = NULL;
4960 target->trace_info->trace_history_size = 0;
4961 target->trace_info->trace_history = NULL;
4962 target->trace_info->trace_history_pos = 0;
4963 target->trace_info->trace_history_overflowed = 0;
4965 target->dbgmsg = NULL;
4966 target->dbg_msg_enabled = 0;
4968 target->endianness = TARGET_ENDIAN_UNKNOWN;
4970 target->rtos = NULL;
4971 target->rtos_auto_detect = false;
4973 /* Do the rest as "configure" options */
4974 goi->isconfigure = 1;
4975 e = target_configure(goi, target);
4977 if (target->tap == NULL) {
4978 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4979 e = JIM_ERR;
4982 if (e != JIM_OK) {
4983 free(target->type);
4984 free(target);
4985 return e;
4988 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4989 /* default endian to little if not specified */
4990 target->endianness = TARGET_LITTLE_ENDIAN;
4993 /* incase variant is not set */
4994 if (!target->variant)
4995 target->variant = strdup("");
4997 cp = Jim_GetString(new_cmd, NULL);
4998 target->cmd_name = strdup(cp);
5000 /* create the target specific commands */
5001 if (target->type->commands) {
5002 e = register_commands(cmd_ctx, NULL, target->type->commands);
5003 if (ERROR_OK != e)
5004 LOG_ERROR("unable to register '%s' commands", cp);
5006 if (target->type->target_create)
5007 (*(target->type->target_create))(target, goi->interp);
5009 /* append to end of list */
5011 struct target **tpp;
5012 tpp = &(all_targets);
5013 while (*tpp)
5014 tpp = &((*tpp)->next);
5015 *tpp = target;
5018 /* now - create the new target name command */
5019 const const struct command_registration target_subcommands[] = {
5021 .chain = target_instance_command_handlers,
5024 .chain = target->type->commands,
5026 COMMAND_REGISTRATION_DONE
5028 const const struct command_registration target_commands[] = {
5030 .name = cp,
5031 .mode = COMMAND_ANY,
5032 .help = "target command group",
5033 .usage = "",
5034 .chain = target_subcommands,
5036 COMMAND_REGISTRATION_DONE
5038 e = register_commands(cmd_ctx, NULL, target_commands);
5039 if (ERROR_OK != e)
5040 return JIM_ERR;
5042 struct command *c = command_find_in_context(cmd_ctx, cp);
5043 assert(c);
5044 command_set_handler_data(c, target);
5046 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5049 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5051 if (argc != 1) {
5052 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5053 return JIM_ERR;
5055 struct command_context *cmd_ctx = current_command_context(interp);
5056 assert(cmd_ctx != NULL);
5058 Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5059 return JIM_OK;
5062 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5064 if (argc != 1) {
5065 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5066 return JIM_ERR;
5068 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5069 for (unsigned x = 0; NULL != target_types[x]; x++) {
5070 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5071 Jim_NewStringObj(interp, target_types[x]->name, -1));
5073 return JIM_OK;
5076 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5078 if (argc != 1) {
5079 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5080 return JIM_ERR;
5082 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5083 struct target *target = all_targets;
5084 while (target) {
5085 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5086 Jim_NewStringObj(interp, target_name(target), -1));
5087 target = target->next;
5089 return JIM_OK;
5092 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5094 int i;
5095 const char *targetname;
5096 int retval, len;
5097 struct target *target = (struct target *) NULL;
5098 struct target_list *head, *curr, *new;
5099 curr = (struct target_list *) NULL;
5100 head = (struct target_list *) NULL;
5102 retval = 0;
5103 LOG_DEBUG("%d", argc);
5104 /* argv[1] = target to associate in smp
5105 * argv[2] = target to assoicate in smp
5106 * argv[3] ...
5109 for (i = 1; i < argc; i++) {
5111 targetname = Jim_GetString(argv[i], &len);
5112 target = get_target(targetname);
5113 LOG_DEBUG("%s ", targetname);
5114 if (target) {
5115 new = malloc(sizeof(struct target_list));
5116 new->target = target;
5117 new->next = (struct target_list *)NULL;
5118 if (head == (struct target_list *)NULL) {
5119 head = new;
5120 curr = head;
5121 } else {
5122 curr->next = new;
5123 curr = new;
5127 /* now parse the list of cpu and put the target in smp mode*/
5128 curr = head;
5130 while (curr != (struct target_list *)NULL) {
5131 target = curr->target;
5132 target->smp = 1;
5133 target->head = head;
5134 curr = curr->next;
5137 if (target && target->rtos)
5138 retval = rtos_smp_init(head->target);
5140 return retval;
5144 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5146 Jim_GetOptInfo goi;
5147 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5148 if (goi.argc < 3) {
5149 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5150 "<name> <target_type> [<target_options> ...]");
5151 return JIM_ERR;
5153 return target_create(&goi);
5156 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5158 Jim_GetOptInfo goi;
5159 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5161 /* It's OK to remove this mechanism sometime after August 2010 or so */
5162 LOG_WARNING("don't use numbers as target identifiers; use names");
5163 if (goi.argc != 1) {
5164 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
5165 return JIM_ERR;
5167 jim_wide w;
5168 int e = Jim_GetOpt_Wide(&goi, &w);
5169 if (e != JIM_OK)
5170 return JIM_ERR;
5172 struct target *target;
5173 for (target = all_targets; NULL != target; target = target->next) {
5174 if (target->target_number != w)
5175 continue;
5177 Jim_SetResultString(goi.interp, target_name(target), -1);
5178 return JIM_OK;
5181 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
5182 Jim_SetResultFormatted(goi.interp,
5183 "Target: number %#s does not exist", wObj);
5184 Jim_FreeNewObj(interp, wObj);
5186 return JIM_ERR;
5189 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5191 if (argc != 1) {
5192 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
5193 return JIM_ERR;
5195 unsigned count = 0;
5196 struct target *target = all_targets;
5197 while (NULL != target) {
5198 target = target->next;
5199 count++;
5201 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
5202 return JIM_OK;
5205 static const struct command_registration target_subcommand_handlers[] = {
5207 .name = "init",
5208 .mode = COMMAND_CONFIG,
5209 .handler = handle_target_init_command,
5210 .help = "initialize targets",
5213 .name = "create",
5214 /* REVISIT this should be COMMAND_CONFIG ... */
5215 .mode = COMMAND_ANY,
5216 .jim_handler = jim_target_create,
5217 .usage = "name type '-chain-position' name [options ...]",
5218 .help = "Creates and selects a new target",
5221 .name = "current",
5222 .mode = COMMAND_ANY,
5223 .jim_handler = jim_target_current,
5224 .help = "Returns the currently selected target",
5227 .name = "types",
5228 .mode = COMMAND_ANY,
5229 .jim_handler = jim_target_types,
5230 .help = "Returns the available target types as "
5231 "a list of strings",
5234 .name = "names",
5235 .mode = COMMAND_ANY,
5236 .jim_handler = jim_target_names,
5237 .help = "Returns the names of all targets as a list of strings",
5240 .name = "number",
5241 .mode = COMMAND_ANY,
5242 .jim_handler = jim_target_number,
5243 .usage = "number",
5244 .help = "Returns the name of the numbered target "
5245 "(DEPRECATED)",
5248 .name = "count",
5249 .mode = COMMAND_ANY,
5250 .jim_handler = jim_target_count,
5251 .help = "Returns the number of targets as an integer "
5252 "(DEPRECATED)",
5255 .name = "smp",
5256 .mode = COMMAND_ANY,
5257 .jim_handler = jim_target_smp,
5258 .usage = "targetname1 targetname2 ...",
5259 .help = "gather several target in a smp list"
5262 COMMAND_REGISTRATION_DONE
5265 struct FastLoad {
5266 uint32_t address;
5267 uint8_t *data;
5268 int length;
5272 static int fastload_num;
5273 static struct FastLoad *fastload;
5275 static void free_fastload(void)
5277 if (fastload != NULL) {
5278 int i;
5279 for (i = 0; i < fastload_num; i++) {
5280 if (fastload[i].data)
5281 free(fastload[i].data);
5283 free(fastload);
5284 fastload = NULL;
5288 COMMAND_HANDLER(handle_fast_load_image_command)
5290 uint8_t *buffer;
5291 size_t buf_cnt;
5292 uint32_t image_size;
5293 uint32_t min_address = 0;
5294 uint32_t max_address = 0xffffffff;
5295 int i;
5297 struct image image;
5299 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5300 &image, &min_address, &max_address);
5301 if (ERROR_OK != retval)
5302 return retval;
5304 struct duration bench;
5305 duration_start(&bench);
5307 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5308 if (retval != ERROR_OK)
5309 return retval;
5311 image_size = 0x0;
5312 retval = ERROR_OK;
5313 fastload_num = image.num_sections;
5314 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
5315 if (fastload == NULL) {
5316 command_print(CMD_CTX, "out of memory");
5317 image_close(&image);
5318 return ERROR_FAIL;
5320 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5321 for (i = 0; i < image.num_sections; i++) {
5322 buffer = malloc(image.sections[i].size);
5323 if (buffer == NULL) {
5324 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5325 (int)(image.sections[i].size));
5326 retval = ERROR_FAIL;
5327 break;
5330 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5331 if (retval != ERROR_OK) {
5332 free(buffer);
5333 break;
5336 uint32_t offset = 0;
5337 uint32_t length = buf_cnt;
5339 /* DANGER!!! beware of unsigned comparision here!!! */
5341 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5342 (image.sections[i].base_address < max_address)) {
5343 if (image.sections[i].base_address < min_address) {
5344 /* clip addresses below */
5345 offset += min_address-image.sections[i].base_address;
5346 length -= offset;
5349 if (image.sections[i].base_address + buf_cnt > max_address)
5350 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5352 fastload[i].address = image.sections[i].base_address + offset;
5353 fastload[i].data = malloc(length);
5354 if (fastload[i].data == NULL) {
5355 free(buffer);
5356 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5357 length);
5358 retval = ERROR_FAIL;
5359 break;
5361 memcpy(fastload[i].data, buffer + offset, length);
5362 fastload[i].length = length;
5364 image_size += length;
5365 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5366 (unsigned int)length,
5367 ((unsigned int)(image.sections[i].base_address + offset)));
5370 free(buffer);
5373 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5374 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5375 "in %fs (%0.3f KiB/s)", image_size,
5376 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5378 command_print(CMD_CTX,
5379 "WARNING: image has not been loaded to target!"
5380 "You can issue a 'fast_load' to finish loading.");
5383 image_close(&image);
5385 if (retval != ERROR_OK)
5386 free_fastload();
5388 return retval;
5391 COMMAND_HANDLER(handle_fast_load_command)
5393 if (CMD_ARGC > 0)
5394 return ERROR_COMMAND_SYNTAX_ERROR;
5395 if (fastload == NULL) {
5396 LOG_ERROR("No image in memory");
5397 return ERROR_FAIL;
5399 int i;
5400 int ms = timeval_ms();
5401 int size = 0;
5402 int retval = ERROR_OK;
5403 for (i = 0; i < fastload_num; i++) {
5404 struct target *target = get_current_target(CMD_CTX);
5405 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5406 (unsigned int)(fastload[i].address),
5407 (unsigned int)(fastload[i].length));
5408 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5409 if (retval != ERROR_OK)
5410 break;
5411 size += fastload[i].length;
5413 if (retval == ERROR_OK) {
5414 int after = timeval_ms();
5415 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5417 return retval;
5420 static const struct command_registration target_command_handlers[] = {
5422 .name = "targets",
5423 .handler = handle_targets_command,
5424 .mode = COMMAND_ANY,
5425 .help = "change current default target (one parameter) "
5426 "or prints table of all targets (no parameters)",
5427 .usage = "[target]",
5430 .name = "target",
5431 .mode = COMMAND_CONFIG,
5432 .help = "configure target",
5434 .chain = target_subcommand_handlers,
5436 COMMAND_REGISTRATION_DONE
5439 int target_register_commands(struct command_context *cmd_ctx)
5441 return register_commands(cmd_ctx, NULL, target_command_handlers);
5444 static bool target_reset_nag = true;
5446 bool get_target_reset_nag(void)
5448 return target_reset_nag;
5451 COMMAND_HANDLER(handle_target_reset_nag)
5453 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5454 &target_reset_nag, "Nag after each reset about options to improve "
5455 "performance");
5458 COMMAND_HANDLER(handle_ps_command)
5460 struct target *target = get_current_target(CMD_CTX);
5461 char *display;
5462 if (target->state != TARGET_HALTED) {
5463 LOG_INFO("target not halted !!");
5464 return ERROR_OK;
5467 if ((target->rtos) && (target->rtos->type)
5468 && (target->rtos->type->ps_command)) {
5469 display = target->rtos->type->ps_command(target);
5470 command_print(CMD_CTX, "%s", display);
5471 free(display);
5472 return ERROR_OK;
5473 } else {
5474 LOG_INFO("failed");
5475 return ERROR_TARGET_FAILURE;
5479 static const struct command_registration target_exec_command_handlers[] = {
5481 .name = "fast_load_image",
5482 .handler = handle_fast_load_image_command,
5483 .mode = COMMAND_ANY,
5484 .help = "Load image into server memory for later use by "
5485 "fast_load; primarily for profiling",
5486 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5487 "[min_address [max_length]]",
5490 .name = "fast_load",
5491 .handler = handle_fast_load_command,
5492 .mode = COMMAND_EXEC,
5493 .help = "loads active fast load image to current target "
5494 "- mainly for profiling purposes",
5495 .usage = "",
5498 .name = "profile",
5499 .handler = handle_profile_command,
5500 .mode = COMMAND_EXEC,
5501 .usage = "seconds filename",
5502 .help = "profiling samples the CPU PC",
5504 /** @todo don't register virt2phys() unless target supports it */
5506 .name = "virt2phys",
5507 .handler = handle_virt2phys_command,
5508 .mode = COMMAND_ANY,
5509 .help = "translate a virtual address into a physical address",
5510 .usage = "virtual_address",
5513 .name = "reg",
5514 .handler = handle_reg_command,
5515 .mode = COMMAND_EXEC,
5516 .help = "display or set a register; with no arguments, "
5517 "displays all registers and their values",
5518 .usage = "[(register_name|register_number) [value]]",
5521 .name = "poll",
5522 .handler = handle_poll_command,
5523 .mode = COMMAND_EXEC,
5524 .help = "poll target state; or reconfigure background polling",
5525 .usage = "['on'|'off']",
5528 .name = "wait_halt",
5529 .handler = handle_wait_halt_command,
5530 .mode = COMMAND_EXEC,
5531 .help = "wait up to the specified number of milliseconds "
5532 "(default 5) for a previously requested halt",
5533 .usage = "[milliseconds]",
5536 .name = "halt",
5537 .handler = handle_halt_command,
5538 .mode = COMMAND_EXEC,
5539 .help = "request target to halt, then wait up to the specified"
5540 "number of milliseconds (default 5) for it to complete",
5541 .usage = "[milliseconds]",
5544 .name = "resume",
5545 .handler = handle_resume_command,
5546 .mode = COMMAND_EXEC,
5547 .help = "resume target execution from current PC or address",
5548 .usage = "[address]",
5551 .name = "reset",
5552 .handler = handle_reset_command,
5553 .mode = COMMAND_EXEC,
5554 .usage = "[run|halt|init]",
5555 .help = "Reset all targets into the specified mode."
5556 "Default reset mode is run, if not given.",
5559 .name = "soft_reset_halt",
5560 .handler = handle_soft_reset_halt_command,
5561 .mode = COMMAND_EXEC,
5562 .usage = "",
5563 .help = "halt the target and do a soft reset",
5566 .name = "step",
5567 .handler = handle_step_command,
5568 .mode = COMMAND_EXEC,
5569 .help = "step one instruction from current PC or address",
5570 .usage = "[address]",
5573 .name = "mdw",
5574 .handler = handle_md_command,
5575 .mode = COMMAND_EXEC,
5576 .help = "display memory words",
5577 .usage = "['phys'] address [count]",
5580 .name = "mdh",
5581 .handler = handle_md_command,
5582 .mode = COMMAND_EXEC,
5583 .help = "display memory half-words",
5584 .usage = "['phys'] address [count]",
5587 .name = "mdb",
5588 .handler = handle_md_command,
5589 .mode = COMMAND_EXEC,
5590 .help = "display memory bytes",
5591 .usage = "['phys'] address [count]",
5594 .name = "mww",
5595 .handler = handle_mw_command,
5596 .mode = COMMAND_EXEC,
5597 .help = "write memory word",
5598 .usage = "['phys'] address value [count]",
5601 .name = "mwh",
5602 .handler = handle_mw_command,
5603 .mode = COMMAND_EXEC,
5604 .help = "write memory half-word",
5605 .usage = "['phys'] address value [count]",
5608 .name = "mwb",
5609 .handler = handle_mw_command,
5610 .mode = COMMAND_EXEC,
5611 .help = "write memory byte",
5612 .usage = "['phys'] address value [count]",
5615 .name = "bp",
5616 .handler = handle_bp_command,
5617 .mode = COMMAND_EXEC,
5618 .help = "list or set hardware or software breakpoint",
5619 .usage = "<address> [<asid>]<length> ['hw'|'hw_ctx']",
5622 .name = "rbp",
5623 .handler = handle_rbp_command,
5624 .mode = COMMAND_EXEC,
5625 .help = "remove breakpoint",
5626 .usage = "address",
5629 .name = "wp",
5630 .handler = handle_wp_command,
5631 .mode = COMMAND_EXEC,
5632 .help = "list (no params) or create watchpoints",
5633 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5636 .name = "rwp",
5637 .handler = handle_rwp_command,
5638 .mode = COMMAND_EXEC,
5639 .help = "remove watchpoint",
5640 .usage = "address",
5643 .name = "load_image",
5644 .handler = handle_load_image_command,
5645 .mode = COMMAND_EXEC,
5646 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5647 "[min_address] [max_length]",
5650 .name = "dump_image",
5651 .handler = handle_dump_image_command,
5652 .mode = COMMAND_EXEC,
5653 .usage = "filename address size",
5656 .name = "verify_image",
5657 .handler = handle_verify_image_command,
5658 .mode = COMMAND_EXEC,
5659 .usage = "filename [offset [type]]",
5662 .name = "test_image",
5663 .handler = handle_test_image_command,
5664 .mode = COMMAND_EXEC,
5665 .usage = "filename [offset [type]]",
5668 .name = "mem2array",
5669 .mode = COMMAND_EXEC,
5670 .jim_handler = jim_mem2array,
5671 .help = "read 8/16/32 bit memory and return as a TCL array "
5672 "for script processing",
5673 .usage = "arrayname bitwidth address count",
5676 .name = "array2mem",
5677 .mode = COMMAND_EXEC,
5678 .jim_handler = jim_array2mem,
5679 .help = "convert a TCL array to memory locations "
5680 "and write the 8/16/32 bit values",
5681 .usage = "arrayname bitwidth address count",
5684 .name = "reset_nag",
5685 .handler = handle_target_reset_nag,
5686 .mode = COMMAND_ANY,
5687 .help = "Nag after each reset about options that could have been "
5688 "enabled to improve performance. ",
5689 .usage = "['enable'|'disable']",
5692 .name = "ps",
5693 .handler = handle_ps_command,
5694 .mode = COMMAND_EXEC,
5695 .help = "list all tasks ",
5696 .usage = " ",
5699 COMMAND_REGISTRATION_DONE
5701 static int target_register_user_commands(struct command_context *cmd_ctx)
5703 int retval = ERROR_OK;
5704 retval = target_request_register_commands(cmd_ctx);
5705 if (retval != ERROR_OK)
5706 return retval;
5708 retval = trace_register_commands(cmd_ctx);
5709 if (retval != ERROR_OK)
5710 return retval;
5713 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);