target: clear running_alg flag after reset
[openocd.git] / src / target / target.c
blobe4235ed26ab5d2e4c52f55e488826be24a52b519
1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
4 * *
5 * Copyright (C) 2007-2010 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
7 * *
8 * Copyright (C) 2008, Duane Ellis *
9 * openocd@duaneeellis.com *
10 * *
11 * Copyright (C) 2008 by Spencer Oliver *
12 * spen@spen-soft.co.uk *
13 * *
14 * Copyright (C) 2008 by Rick Altherr *
15 * kc8apf@kc8apf.net> *
16 * *
17 * Copyright (C) 2011 by Broadcom Corporation *
18 * Evan Hunter - ehunter@broadcom.com *
19 * *
20 * Copyright (C) ST-Ericsson SA 2011 *
21 * michel.jaouen@stericsson.com : smp minimum support *
22 * *
23 * Copyright (C) 2011 Andreas Fritiofson *
24 * andreas.fritiofson@gmail.com *
25 * *
26 * This program is free software; you can redistribute it and/or modify *
27 * it under the terms of the GNU General Public License as published by *
28 * the Free Software Foundation; either version 2 of the License, or *
29 * (at your option) any later version. *
30 * *
31 * This program is distributed in the hope that it will be useful, *
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
34 * GNU General Public License for more details. *
35 * *
36 * You should have received a copy of the GNU General Public License *
37 * along with this program; if not, write to the *
38 * Free Software Foundation, Inc., *
39 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
40 ***************************************************************************/
42 #ifdef HAVE_CONFIG_H
43 #include "config.h"
44 #endif
46 #include <helper/time_support.h>
47 #include <jtag/jtag.h>
48 #include <flash/nor/core.h>
50 #include "target.h"
51 #include "target_type.h"
52 #include "target_request.h"
53 #include "breakpoints.h"
54 #include "register.h"
55 #include "trace.h"
56 #include "image.h"
57 #include "rtos/rtos.h"
59 /* default halt wait timeout (ms) */
60 #define DEFAULT_HALT_TIMEOUT 5000
62 static int target_read_buffer_default(struct target *target, uint32_t address,
63 uint32_t size, uint8_t *buffer);
64 static int target_write_buffer_default(struct target *target, uint32_t address,
65 uint32_t size, const uint8_t *buffer);
66 static int target_array2mem(Jim_Interp *interp, struct target *target,
67 int argc, Jim_Obj * const *argv);
68 static int target_mem2array(Jim_Interp *interp, struct target *target,
69 int argc, Jim_Obj * const *argv);
70 static int target_register_user_commands(struct command_context *cmd_ctx);
71 static int target_get_gdb_fileio_info_default(struct target *target,
72 struct gdb_fileio_info *fileio_info);
73 static int target_gdb_fileio_end_default(struct target *target, int retcode,
74 int fileio_errno, bool ctrl_c);
76 /* targets */
77 extern struct target_type arm7tdmi_target;
78 extern struct target_type arm720t_target;
79 extern struct target_type arm9tdmi_target;
80 extern struct target_type arm920t_target;
81 extern struct target_type arm966e_target;
82 extern struct target_type arm946e_target;
83 extern struct target_type arm926ejs_target;
84 extern struct target_type fa526_target;
85 extern struct target_type feroceon_target;
86 extern struct target_type dragonite_target;
87 extern struct target_type xscale_target;
88 extern struct target_type cortexm3_target;
89 extern struct target_type cortexa8_target;
90 extern struct target_type cortexr4_target;
91 extern struct target_type arm11_target;
92 extern struct target_type mips_m4k_target;
93 extern struct target_type avr_target;
94 extern struct target_type dsp563xx_target;
95 extern struct target_type dsp5680xx_target;
96 extern struct target_type testee_target;
97 extern struct target_type avr32_ap7k_target;
98 extern struct target_type hla_target;
99 extern struct target_type nds32_v2_target;
100 extern struct target_type nds32_v3_target;
101 extern struct target_type nds32_v3m_target;
103 static struct target_type *target_types[] = {
104 &arm7tdmi_target,
105 &arm9tdmi_target,
106 &arm920t_target,
107 &arm720t_target,
108 &arm966e_target,
109 &arm946e_target,
110 &arm926ejs_target,
111 &fa526_target,
112 &feroceon_target,
113 &dragonite_target,
114 &xscale_target,
115 &cortexm3_target,
116 &cortexa8_target,
117 &cortexr4_target,
118 &arm11_target,
119 &mips_m4k_target,
120 &avr_target,
121 &dsp563xx_target,
122 &dsp5680xx_target,
123 &testee_target,
124 &avr32_ap7k_target,
125 &hla_target,
126 &nds32_v2_target,
127 &nds32_v3_target,
128 &nds32_v3m_target,
129 NULL,
132 struct target *all_targets;
133 static struct target_event_callback *target_event_callbacks;
134 static struct target_timer_callback *target_timer_callbacks;
135 static const int polling_interval = 100;
137 static const Jim_Nvp nvp_assert[] = {
138 { .name = "assert", NVP_ASSERT },
139 { .name = "deassert", NVP_DEASSERT },
140 { .name = "T", NVP_ASSERT },
141 { .name = "F", NVP_DEASSERT },
142 { .name = "t", NVP_ASSERT },
143 { .name = "f", NVP_DEASSERT },
144 { .name = NULL, .value = -1 }
147 static const Jim_Nvp nvp_error_target[] = {
148 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
149 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
150 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
151 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
152 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
153 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
154 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
155 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
156 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
157 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
158 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
159 { .value = -1, .name = NULL }
162 static const char *target_strerror_safe(int err)
164 const Jim_Nvp *n;
166 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
167 if (n->name == NULL)
168 return "unknown";
169 else
170 return n->name;
173 static const Jim_Nvp nvp_target_event[] = {
175 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
176 { .value = TARGET_EVENT_HALTED, .name = "halted" },
177 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
178 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
179 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
181 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
182 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
184 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
185 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
186 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
187 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
188 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
189 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
190 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
191 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
192 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
193 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
194 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
195 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
197 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
198 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
200 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
201 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
203 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
204 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
206 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
207 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
209 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
210 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
212 { .name = NULL, .value = -1 }
215 static const Jim_Nvp nvp_target_state[] = {
216 { .name = "unknown", .value = TARGET_UNKNOWN },
217 { .name = "running", .value = TARGET_RUNNING },
218 { .name = "halted", .value = TARGET_HALTED },
219 { .name = "reset", .value = TARGET_RESET },
220 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
221 { .name = NULL, .value = -1 },
224 static const Jim_Nvp nvp_target_debug_reason[] = {
225 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
226 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
227 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
228 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
229 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
230 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
231 { .name = "program-exit" , .value = DBG_REASON_EXIT },
232 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
233 { .name = NULL, .value = -1 },
236 static const Jim_Nvp nvp_target_endian[] = {
237 { .name = "big", .value = TARGET_BIG_ENDIAN },
238 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
239 { .name = "be", .value = TARGET_BIG_ENDIAN },
240 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
241 { .name = NULL, .value = -1 },
244 static const Jim_Nvp nvp_reset_modes[] = {
245 { .name = "unknown", .value = RESET_UNKNOWN },
246 { .name = "run" , .value = RESET_RUN },
247 { .name = "halt" , .value = RESET_HALT },
248 { .name = "init" , .value = RESET_INIT },
249 { .name = NULL , .value = -1 },
252 const char *debug_reason_name(struct target *t)
254 const char *cp;
256 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
257 t->debug_reason)->name;
258 if (!cp) {
259 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
260 cp = "(*BUG*unknown*BUG*)";
262 return cp;
265 const char *target_state_name(struct target *t)
267 const char *cp;
268 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
269 if (!cp) {
270 LOG_ERROR("Invalid target state: %d", (int)(t->state));
271 cp = "(*BUG*unknown*BUG*)";
273 return cp;
276 /* determine the number of the new target */
277 static int new_target_number(void)
279 struct target *t;
280 int x;
282 /* number is 0 based */
283 x = -1;
284 t = all_targets;
285 while (t) {
286 if (x < t->target_number)
287 x = t->target_number;
288 t = t->next;
290 return x + 1;
293 /* read a uint32_t from a buffer in target memory endianness */
294 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
296 if (target->endianness == TARGET_LITTLE_ENDIAN)
297 return le_to_h_u32(buffer);
298 else
299 return be_to_h_u32(buffer);
302 /* read a uint24_t from a buffer in target memory endianness */
303 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
305 if (target->endianness == TARGET_LITTLE_ENDIAN)
306 return le_to_h_u24(buffer);
307 else
308 return be_to_h_u24(buffer);
311 /* read a uint16_t from a buffer in target memory endianness */
312 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
314 if (target->endianness == TARGET_LITTLE_ENDIAN)
315 return le_to_h_u16(buffer);
316 else
317 return be_to_h_u16(buffer);
320 /* read a uint8_t from a buffer in target memory endianness */
321 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
323 return *buffer & 0x0ff;
326 /* write a uint32_t to a buffer in target memory endianness */
327 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
329 if (target->endianness == TARGET_LITTLE_ENDIAN)
330 h_u32_to_le(buffer, value);
331 else
332 h_u32_to_be(buffer, value);
335 /* write a uint24_t to a buffer in target memory endianness */
336 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
338 if (target->endianness == TARGET_LITTLE_ENDIAN)
339 h_u24_to_le(buffer, value);
340 else
341 h_u24_to_be(buffer, value);
344 /* write a uint16_t to a buffer in target memory endianness */
345 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
347 if (target->endianness == TARGET_LITTLE_ENDIAN)
348 h_u16_to_le(buffer, value);
349 else
350 h_u16_to_be(buffer, value);
353 /* write a uint8_t to a buffer in target memory endianness */
354 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
356 *buffer = value;
359 /* write a uint32_t array to a buffer in target memory endianness */
360 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
362 uint32_t i;
363 for (i = 0; i < count; i++)
364 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
367 /* write a uint16_t array to a buffer in target memory endianness */
368 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
370 uint32_t i;
371 for (i = 0; i < count; i++)
372 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
375 /* write a uint32_t array to a buffer in target memory endianness */
376 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, uint32_t *srcbuf)
378 uint32_t i;
379 for (i = 0; i < count; i++)
380 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
383 /* write a uint16_t array to a buffer in target memory endianness */
384 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, uint16_t *srcbuf)
386 uint32_t i;
387 for (i = 0; i < count; i++)
388 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
391 /* return a pointer to a configured target; id is name or number */
392 struct target *get_target(const char *id)
394 struct target *target;
396 /* try as tcltarget name */
397 for (target = all_targets; target; target = target->next) {
398 if (target_name(target) == NULL)
399 continue;
400 if (strcmp(id, target_name(target)) == 0)
401 return target;
404 /* It's OK to remove this fallback sometime after August 2010 or so */
406 /* no match, try as number */
407 unsigned num;
408 if (parse_uint(id, &num) != ERROR_OK)
409 return NULL;
411 for (target = all_targets; target; target = target->next) {
412 if (target->target_number == (int)num) {
413 LOG_WARNING("use '%s' as target identifier, not '%u'",
414 target_name(target), num);
415 return target;
419 return NULL;
422 /* returns a pointer to the n-th configured target */
423 static struct target *get_target_by_num(int num)
425 struct target *target = all_targets;
427 while (target) {
428 if (target->target_number == num)
429 return target;
430 target = target->next;
433 return NULL;
436 struct target *get_current_target(struct command_context *cmd_ctx)
438 struct target *target = get_target_by_num(cmd_ctx->current_target);
440 if (target == NULL) {
441 LOG_ERROR("BUG: current_target out of bounds");
442 exit(-1);
445 return target;
448 int target_poll(struct target *target)
450 int retval;
452 /* We can't poll until after examine */
453 if (!target_was_examined(target)) {
454 /* Fail silently lest we pollute the log */
455 return ERROR_FAIL;
458 retval = target->type->poll(target);
459 if (retval != ERROR_OK)
460 return retval;
462 if (target->halt_issued) {
463 if (target->state == TARGET_HALTED)
464 target->halt_issued = false;
465 else {
466 long long t = timeval_ms() - target->halt_issued_time;
467 if (t > DEFAULT_HALT_TIMEOUT) {
468 target->halt_issued = false;
469 LOG_INFO("Halt timed out, wake up GDB.");
470 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
475 return ERROR_OK;
478 int target_halt(struct target *target)
480 int retval;
481 /* We can't poll until after examine */
482 if (!target_was_examined(target)) {
483 LOG_ERROR("Target not examined yet");
484 return ERROR_FAIL;
487 retval = target->type->halt(target);
488 if (retval != ERROR_OK)
489 return retval;
491 target->halt_issued = true;
492 target->halt_issued_time = timeval_ms();
494 return ERROR_OK;
498 * Make the target (re)start executing using its saved execution
499 * context (possibly with some modifications).
501 * @param target Which target should start executing.
502 * @param current True to use the target's saved program counter instead
503 * of the address parameter
504 * @param address Optionally used as the program counter.
505 * @param handle_breakpoints True iff breakpoints at the resumption PC
506 * should be skipped. (For example, maybe execution was stopped by
507 * such a breakpoint, in which case it would be counterprodutive to
508 * let it re-trigger.
509 * @param debug_execution False if all working areas allocated by OpenOCD
510 * should be released and/or restored to their original contents.
511 * (This would for example be true to run some downloaded "helper"
512 * algorithm code, which resides in one such working buffer and uses
513 * another for data storage.)
515 * @todo Resolve the ambiguity about what the "debug_execution" flag
516 * signifies. For example, Target implementations don't agree on how
517 * it relates to invalidation of the register cache, or to whether
518 * breakpoints and watchpoints should be enabled. (It would seem wrong
519 * to enable breakpoints when running downloaded "helper" algorithms
520 * (debug_execution true), since the breakpoints would be set to match
521 * target firmware being debugged, not the helper algorithm.... and
522 * enabling them could cause such helpers to malfunction (for example,
523 * by overwriting data with a breakpoint instruction. On the other
524 * hand the infrastructure for running such helpers might use this
525 * procedure but rely on hardware breakpoint to detect termination.)
527 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
529 int retval;
531 /* We can't poll until after examine */
532 if (!target_was_examined(target)) {
533 LOG_ERROR("Target not examined yet");
534 return ERROR_FAIL;
537 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
539 /* note that resume *must* be asynchronous. The CPU can halt before
540 * we poll. The CPU can even halt at the current PC as a result of
541 * a software breakpoint being inserted by (a bug?) the application.
543 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
544 if (retval != ERROR_OK)
545 return retval;
547 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
549 return retval;
552 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
554 char buf[100];
555 int retval;
556 Jim_Nvp *n;
557 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
558 if (n->name == NULL) {
559 LOG_ERROR("invalid reset mode");
560 return ERROR_FAIL;
563 /* disable polling during reset to make reset event scripts
564 * more predictable, i.e. dr/irscan & pathmove in events will
565 * not have JTAG operations injected into the middle of a sequence.
567 bool save_poll = jtag_poll_get_enabled();
569 jtag_poll_set_enabled(false);
571 sprintf(buf, "ocd_process_reset %s", n->name);
572 retval = Jim_Eval(cmd_ctx->interp, buf);
574 jtag_poll_set_enabled(save_poll);
576 if (retval != JIM_OK) {
577 Jim_MakeErrorMessage(cmd_ctx->interp);
578 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
579 return ERROR_FAIL;
582 /* We want any events to be processed before the prompt */
583 retval = target_call_timer_callbacks_now();
585 struct target *target;
586 for (target = all_targets; target; target = target->next) {
587 target->type->check_reset(target);
588 target->running_alg = false;
591 return retval;
594 static int identity_virt2phys(struct target *target,
595 uint32_t virtual, uint32_t *physical)
597 *physical = virtual;
598 return ERROR_OK;
601 static int no_mmu(struct target *target, int *enabled)
603 *enabled = 0;
604 return ERROR_OK;
607 static int default_examine(struct target *target)
609 target_set_examined(target);
610 return ERROR_OK;
613 /* no check by default */
614 static int default_check_reset(struct target *target)
616 return ERROR_OK;
619 int target_examine_one(struct target *target)
621 return target->type->examine(target);
624 static int jtag_enable_callback(enum jtag_event event, void *priv)
626 struct target *target = priv;
628 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
629 return ERROR_OK;
631 jtag_unregister_event_callback(jtag_enable_callback, target);
633 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
635 int retval = target_examine_one(target);
636 if (retval != ERROR_OK)
637 return retval;
639 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
641 return retval;
644 /* Targets that correctly implement init + examine, i.e.
645 * no communication with target during init:
647 * XScale
649 int target_examine(void)
651 int retval = ERROR_OK;
652 struct target *target;
654 for (target = all_targets; target; target = target->next) {
655 /* defer examination, but don't skip it */
656 if (!target->tap->enabled) {
657 jtag_register_event_callback(jtag_enable_callback,
658 target);
659 continue;
662 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
664 retval = target_examine_one(target);
665 if (retval != ERROR_OK)
666 return retval;
668 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
670 return retval;
673 const char *target_type_name(struct target *target)
675 return target->type->name;
678 static int target_soft_reset_halt(struct target *target)
680 if (!target_was_examined(target)) {
681 LOG_ERROR("Target not examined yet");
682 return ERROR_FAIL;
684 if (!target->type->soft_reset_halt) {
685 LOG_ERROR("Target %s does not support soft_reset_halt",
686 target_name(target));
687 return ERROR_FAIL;
689 return target->type->soft_reset_halt(target);
693 * Downloads a target-specific native code algorithm to the target,
694 * and executes it. * Note that some targets may need to set up, enable,
695 * and tear down a breakpoint (hard or * soft) to detect algorithm
696 * termination, while others may support lower overhead schemes where
697 * soft breakpoints embedded in the algorithm automatically terminate the
698 * algorithm.
700 * @param target used to run the algorithm
701 * @param arch_info target-specific description of the algorithm.
703 int target_run_algorithm(struct target *target,
704 int num_mem_params, struct mem_param *mem_params,
705 int num_reg_params, struct reg_param *reg_param,
706 uint32_t entry_point, uint32_t exit_point,
707 int timeout_ms, void *arch_info)
709 int retval = ERROR_FAIL;
711 if (!target_was_examined(target)) {
712 LOG_ERROR("Target not examined yet");
713 goto done;
715 if (!target->type->run_algorithm) {
716 LOG_ERROR("Target type '%s' does not support %s",
717 target_type_name(target), __func__);
718 goto done;
721 target->running_alg = true;
722 retval = target->type->run_algorithm(target,
723 num_mem_params, mem_params,
724 num_reg_params, reg_param,
725 entry_point, exit_point, timeout_ms, arch_info);
726 target->running_alg = false;
728 done:
729 return retval;
733 * Downloads a target-specific native code algorithm to the target,
734 * executes and leaves it running.
736 * @param target used to run the algorithm
737 * @param arch_info target-specific description of the algorithm.
739 int target_start_algorithm(struct target *target,
740 int num_mem_params, struct mem_param *mem_params,
741 int num_reg_params, struct reg_param *reg_params,
742 uint32_t entry_point, uint32_t exit_point,
743 void *arch_info)
745 int retval = ERROR_FAIL;
747 if (!target_was_examined(target)) {
748 LOG_ERROR("Target not examined yet");
749 goto done;
751 if (!target->type->start_algorithm) {
752 LOG_ERROR("Target type '%s' does not support %s",
753 target_type_name(target), __func__);
754 goto done;
756 if (target->running_alg) {
757 LOG_ERROR("Target is already running an algorithm");
758 goto done;
761 target->running_alg = true;
762 retval = target->type->start_algorithm(target,
763 num_mem_params, mem_params,
764 num_reg_params, reg_params,
765 entry_point, exit_point, arch_info);
767 done:
768 return retval;
772 * Waits for an algorithm started with target_start_algorithm() to complete.
774 * @param target used to run the algorithm
775 * @param arch_info target-specific description of the algorithm.
777 int target_wait_algorithm(struct target *target,
778 int num_mem_params, struct mem_param *mem_params,
779 int num_reg_params, struct reg_param *reg_params,
780 uint32_t exit_point, int timeout_ms,
781 void *arch_info)
783 int retval = ERROR_FAIL;
785 if (!target->type->wait_algorithm) {
786 LOG_ERROR("Target type '%s' does not support %s",
787 target_type_name(target), __func__);
788 goto done;
790 if (!target->running_alg) {
791 LOG_ERROR("Target is not running an algorithm");
792 goto done;
795 retval = target->type->wait_algorithm(target,
796 num_mem_params, mem_params,
797 num_reg_params, reg_params,
798 exit_point, timeout_ms, arch_info);
799 if (retval != ERROR_TARGET_TIMEOUT)
800 target->running_alg = false;
802 done:
803 return retval;
807 * Executes a target-specific native code algorithm in the target.
808 * It differs from target_run_algorithm in that the algorithm is asynchronous.
809 * Because of this it requires an compliant algorithm:
810 * see contrib/loaders/flash/stm32f1x.S for example.
812 * @param target used to run the algorithm
815 int target_run_flash_async_algorithm(struct target *target,
816 uint8_t *buffer, uint32_t count, int block_size,
817 int num_mem_params, struct mem_param *mem_params,
818 int num_reg_params, struct reg_param *reg_params,
819 uint32_t buffer_start, uint32_t buffer_size,
820 uint32_t entry_point, uint32_t exit_point, void *arch_info)
822 int retval;
823 int timeout = 0;
825 /* Set up working area. First word is write pointer, second word is read pointer,
826 * rest is fifo data area. */
827 uint32_t wp_addr = buffer_start;
828 uint32_t rp_addr = buffer_start + 4;
829 uint32_t fifo_start_addr = buffer_start + 8;
830 uint32_t fifo_end_addr = buffer_start + buffer_size;
832 uint32_t wp = fifo_start_addr;
833 uint32_t rp = fifo_start_addr;
835 /* validate block_size is 2^n */
836 assert(!block_size || !(block_size & (block_size - 1)));
838 retval = target_write_u32(target, wp_addr, wp);
839 if (retval != ERROR_OK)
840 return retval;
841 retval = target_write_u32(target, rp_addr, rp);
842 if (retval != ERROR_OK)
843 return retval;
845 /* Start up algorithm on target and let it idle while writing the first chunk */
846 retval = target_start_algorithm(target, num_mem_params, mem_params,
847 num_reg_params, reg_params,
848 entry_point,
849 exit_point,
850 arch_info);
852 if (retval != ERROR_OK) {
853 LOG_ERROR("error starting target flash write algorithm");
854 return retval;
857 while (count > 0) {
859 retval = target_read_u32(target, rp_addr, &rp);
860 if (retval != ERROR_OK) {
861 LOG_ERROR("failed to get read pointer");
862 break;
865 LOG_DEBUG("count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32, count, wp, rp);
867 if (rp == 0) {
868 LOG_ERROR("flash write algorithm aborted by target");
869 retval = ERROR_FLASH_OPERATION_FAILED;
870 break;
873 if ((rp & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
874 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
875 break;
878 /* Count the number of bytes available in the fifo without
879 * crossing the wrap around. Make sure to not fill it completely,
880 * because that would make wp == rp and that's the empty condition. */
881 uint32_t thisrun_bytes;
882 if (rp > wp)
883 thisrun_bytes = rp - wp - block_size;
884 else if (rp > fifo_start_addr)
885 thisrun_bytes = fifo_end_addr - wp;
886 else
887 thisrun_bytes = fifo_end_addr - wp - block_size;
889 if (thisrun_bytes == 0) {
890 /* Throttle polling a bit if transfer is (much) faster than flash
891 * programming. The exact delay shouldn't matter as long as it's
892 * less than buffer size / flash speed. This is very unlikely to
893 * run when using high latency connections such as USB. */
894 alive_sleep(10);
896 /* to stop an infinite loop on some targets check and increment a timeout
897 * this issue was observed on a stellaris using the new ICDI interface */
898 if (timeout++ >= 500) {
899 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
900 return ERROR_FLASH_OPERATION_FAILED;
902 continue;
905 /* reset our timeout */
906 timeout = 0;
908 /* Limit to the amount of data we actually want to write */
909 if (thisrun_bytes > count * block_size)
910 thisrun_bytes = count * block_size;
912 /* Write data to fifo */
913 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
914 if (retval != ERROR_OK)
915 break;
917 /* Update counters and wrap write pointer */
918 buffer += thisrun_bytes;
919 count -= thisrun_bytes / block_size;
920 wp += thisrun_bytes;
921 if (wp >= fifo_end_addr)
922 wp = fifo_start_addr;
924 /* Store updated write pointer to target */
925 retval = target_write_u32(target, wp_addr, wp);
926 if (retval != ERROR_OK)
927 break;
930 if (retval != ERROR_OK) {
931 /* abort flash write algorithm on target */
932 target_write_u32(target, wp_addr, 0);
935 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
936 num_reg_params, reg_params,
937 exit_point,
938 10000,
939 arch_info);
941 if (retval2 != ERROR_OK) {
942 LOG_ERROR("error waiting for target flash write algorithm");
943 retval = retval2;
946 return retval;
949 int target_read_memory(struct target *target,
950 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
952 if (!target_was_examined(target)) {
953 LOG_ERROR("Target not examined yet");
954 return ERROR_FAIL;
956 return target->type->read_memory(target, address, size, count, buffer);
959 int target_read_phys_memory(struct target *target,
960 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
962 if (!target_was_examined(target)) {
963 LOG_ERROR("Target not examined yet");
964 return ERROR_FAIL;
966 return target->type->read_phys_memory(target, address, size, count, buffer);
969 int target_write_memory(struct target *target,
970 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
972 if (!target_was_examined(target)) {
973 LOG_ERROR("Target not examined yet");
974 return ERROR_FAIL;
976 return target->type->write_memory(target, address, size, count, buffer);
979 int target_write_phys_memory(struct target *target,
980 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
982 if (!target_was_examined(target)) {
983 LOG_ERROR("Target not examined yet");
984 return ERROR_FAIL;
986 return target->type->write_phys_memory(target, address, size, count, buffer);
989 static int target_bulk_write_memory_default(struct target *target,
990 uint32_t address, uint32_t count, const uint8_t *buffer)
992 return target_write_memory(target, address, 4, count, buffer);
995 int target_add_breakpoint(struct target *target,
996 struct breakpoint *breakpoint)
998 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
999 LOG_WARNING("target %s is not halted", target_name(target));
1000 return ERROR_TARGET_NOT_HALTED;
1002 return target->type->add_breakpoint(target, breakpoint);
1005 int target_add_context_breakpoint(struct target *target,
1006 struct breakpoint *breakpoint)
1008 if (target->state != TARGET_HALTED) {
1009 LOG_WARNING("target %s is not halted", target_name(target));
1010 return ERROR_TARGET_NOT_HALTED;
1012 return target->type->add_context_breakpoint(target, breakpoint);
1015 int target_add_hybrid_breakpoint(struct target *target,
1016 struct breakpoint *breakpoint)
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_hybrid_breakpoint(target, breakpoint);
1025 int target_remove_breakpoint(struct target *target,
1026 struct breakpoint *breakpoint)
1028 return target->type->remove_breakpoint(target, breakpoint);
1031 int target_add_watchpoint(struct target *target,
1032 struct watchpoint *watchpoint)
1034 if (target->state != TARGET_HALTED) {
1035 LOG_WARNING("target %s is not halted", target_name(target));
1036 return ERROR_TARGET_NOT_HALTED;
1038 return target->type->add_watchpoint(target, watchpoint);
1040 int target_remove_watchpoint(struct target *target,
1041 struct watchpoint *watchpoint)
1043 return target->type->remove_watchpoint(target, watchpoint);
1045 int target_hit_watchpoint(struct target *target,
1046 struct watchpoint **hit_watchpoint)
1048 if (target->state != TARGET_HALTED) {
1049 LOG_WARNING("target %s is not halted", target->cmd_name);
1050 return ERROR_TARGET_NOT_HALTED;
1053 if (target->type->hit_watchpoint == NULL) {
1054 /* For backward compatible, if hit_watchpoint is not implemented,
1055 * return ERROR_FAIL such that gdb_server will not take the nonsense
1056 * information. */
1057 return ERROR_FAIL;
1060 return target->type->hit_watchpoint(target, hit_watchpoint);
1063 int target_get_gdb_reg_list(struct target *target,
1064 struct reg **reg_list[], int *reg_list_size,
1065 enum target_register_class reg_class)
1067 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1069 int target_step(struct target *target,
1070 int current, uint32_t address, int handle_breakpoints)
1072 return target->type->step(target, current, address, handle_breakpoints);
1075 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1077 if (target->state != TARGET_HALTED) {
1078 LOG_WARNING("target %s is not halted", target->cmd_name);
1079 return ERROR_TARGET_NOT_HALTED;
1081 return target->type->get_gdb_fileio_info(target, fileio_info);
1084 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1086 if (target->state != TARGET_HALTED) {
1087 LOG_WARNING("target %s is not halted", target->cmd_name);
1088 return ERROR_TARGET_NOT_HALTED;
1090 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1094 * Reset the @c examined flag for the given target.
1095 * Pure paranoia -- targets are zeroed on allocation.
1097 static void target_reset_examined(struct target *target)
1099 target->examined = false;
1102 static int err_read_phys_memory(struct target *target, uint32_t address,
1103 uint32_t size, uint32_t count, uint8_t *buffer)
1105 LOG_ERROR("Not implemented: %s", __func__);
1106 return ERROR_FAIL;
1109 static int err_write_phys_memory(struct target *target, uint32_t address,
1110 uint32_t size, uint32_t count, const uint8_t *buffer)
1112 LOG_ERROR("Not implemented: %s", __func__);
1113 return ERROR_FAIL;
1116 static int handle_target(void *priv);
1118 static int target_init_one(struct command_context *cmd_ctx,
1119 struct target *target)
1121 target_reset_examined(target);
1123 struct target_type *type = target->type;
1124 if (type->examine == NULL)
1125 type->examine = default_examine;
1127 if (type->check_reset == NULL)
1128 type->check_reset = default_check_reset;
1130 assert(type->init_target != NULL);
1132 int retval = type->init_target(cmd_ctx, target);
1133 if (ERROR_OK != retval) {
1134 LOG_ERROR("target '%s' init failed", target_name(target));
1135 return retval;
1138 /* Sanity-check MMU support ... stub in what we must, to help
1139 * implement it in stages, but warn if we need to do so.
1141 if (type->mmu) {
1142 if (type->write_phys_memory == NULL) {
1143 LOG_ERROR("type '%s' is missing write_phys_memory",
1144 type->name);
1145 type->write_phys_memory = err_write_phys_memory;
1147 if (type->read_phys_memory == NULL) {
1148 LOG_ERROR("type '%s' is missing read_phys_memory",
1149 type->name);
1150 type->read_phys_memory = err_read_phys_memory;
1152 if (type->virt2phys == NULL) {
1153 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1154 type->virt2phys = identity_virt2phys;
1156 } else {
1157 /* Make sure no-MMU targets all behave the same: make no
1158 * distinction between physical and virtual addresses, and
1159 * ensure that virt2phys() is always an identity mapping.
1161 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1162 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1164 type->mmu = no_mmu;
1165 type->write_phys_memory = type->write_memory;
1166 type->read_phys_memory = type->read_memory;
1167 type->virt2phys = identity_virt2phys;
1170 if (target->type->read_buffer == NULL)
1171 target->type->read_buffer = target_read_buffer_default;
1173 if (target->type->write_buffer == NULL)
1174 target->type->write_buffer = target_write_buffer_default;
1176 if (target->type->bulk_write_memory == NULL)
1177 target->type->bulk_write_memory = target_bulk_write_memory_default;
1179 if (target->type->get_gdb_fileio_info == NULL)
1180 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1182 if (target->type->gdb_fileio_end == NULL)
1183 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1185 return ERROR_OK;
1188 static int target_init(struct command_context *cmd_ctx)
1190 struct target *target;
1191 int retval;
1193 for (target = all_targets; target; target = target->next) {
1194 retval = target_init_one(cmd_ctx, target);
1195 if (ERROR_OK != retval)
1196 return retval;
1199 if (!all_targets)
1200 return ERROR_OK;
1202 retval = target_register_user_commands(cmd_ctx);
1203 if (ERROR_OK != retval)
1204 return retval;
1206 retval = target_register_timer_callback(&handle_target,
1207 polling_interval, 1, cmd_ctx->interp);
1208 if (ERROR_OK != retval)
1209 return retval;
1211 return ERROR_OK;
1214 COMMAND_HANDLER(handle_target_init_command)
1216 int retval;
1218 if (CMD_ARGC != 0)
1219 return ERROR_COMMAND_SYNTAX_ERROR;
1221 static bool target_initialized;
1222 if (target_initialized) {
1223 LOG_INFO("'target init' has already been called");
1224 return ERROR_OK;
1226 target_initialized = true;
1228 retval = command_run_line(CMD_CTX, "init_targets");
1229 if (ERROR_OK != retval)
1230 return retval;
1232 retval = command_run_line(CMD_CTX, "init_board");
1233 if (ERROR_OK != retval)
1234 return retval;
1236 LOG_DEBUG("Initializing targets...");
1237 return target_init(CMD_CTX);
1240 int target_register_event_callback(int (*callback)(struct target *target,
1241 enum target_event event, void *priv), void *priv)
1243 struct target_event_callback **callbacks_p = &target_event_callbacks;
1245 if (callback == NULL)
1246 return ERROR_COMMAND_SYNTAX_ERROR;
1248 if (*callbacks_p) {
1249 while ((*callbacks_p)->next)
1250 callbacks_p = &((*callbacks_p)->next);
1251 callbacks_p = &((*callbacks_p)->next);
1254 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1255 (*callbacks_p)->callback = callback;
1256 (*callbacks_p)->priv = priv;
1257 (*callbacks_p)->next = NULL;
1259 return ERROR_OK;
1262 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1264 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1265 struct timeval now;
1267 if (callback == NULL)
1268 return ERROR_COMMAND_SYNTAX_ERROR;
1270 if (*callbacks_p) {
1271 while ((*callbacks_p)->next)
1272 callbacks_p = &((*callbacks_p)->next);
1273 callbacks_p = &((*callbacks_p)->next);
1276 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1277 (*callbacks_p)->callback = callback;
1278 (*callbacks_p)->periodic = periodic;
1279 (*callbacks_p)->time_ms = time_ms;
1281 gettimeofday(&now, NULL);
1282 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
1283 time_ms -= (time_ms % 1000);
1284 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
1285 if ((*callbacks_p)->when.tv_usec > 1000000) {
1286 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
1287 (*callbacks_p)->when.tv_sec += 1;
1290 (*callbacks_p)->priv = priv;
1291 (*callbacks_p)->next = NULL;
1293 return ERROR_OK;
1296 int target_unregister_event_callback(int (*callback)(struct target *target,
1297 enum target_event event, void *priv), void *priv)
1299 struct target_event_callback **p = &target_event_callbacks;
1300 struct target_event_callback *c = target_event_callbacks;
1302 if (callback == NULL)
1303 return ERROR_COMMAND_SYNTAX_ERROR;
1305 while (c) {
1306 struct target_event_callback *next = c->next;
1307 if ((c->callback == callback) && (c->priv == priv)) {
1308 *p = next;
1309 free(c);
1310 return ERROR_OK;
1311 } else
1312 p = &(c->next);
1313 c = next;
1316 return ERROR_OK;
1319 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1321 struct target_timer_callback **p = &target_timer_callbacks;
1322 struct target_timer_callback *c = target_timer_callbacks;
1324 if (callback == NULL)
1325 return ERROR_COMMAND_SYNTAX_ERROR;
1327 while (c) {
1328 struct target_timer_callback *next = c->next;
1329 if ((c->callback == callback) && (c->priv == priv)) {
1330 *p = next;
1331 free(c);
1332 return ERROR_OK;
1333 } else
1334 p = &(c->next);
1335 c = next;
1338 return ERROR_OK;
1341 int target_call_event_callbacks(struct target *target, enum target_event event)
1343 struct target_event_callback *callback = target_event_callbacks;
1344 struct target_event_callback *next_callback;
1346 if (event == TARGET_EVENT_HALTED) {
1347 /* execute early halted first */
1348 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1351 LOG_DEBUG("target event %i (%s)", event,
1352 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1354 target_handle_event(target, event);
1356 while (callback) {
1357 next_callback = callback->next;
1358 callback->callback(target, event, callback->priv);
1359 callback = next_callback;
1362 return ERROR_OK;
1365 static int target_timer_callback_periodic_restart(
1366 struct target_timer_callback *cb, struct timeval *now)
1368 int time_ms = cb->time_ms;
1369 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1370 time_ms -= (time_ms % 1000);
1371 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1372 if (cb->when.tv_usec > 1000000) {
1373 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1374 cb->when.tv_sec += 1;
1376 return ERROR_OK;
1379 static int target_call_timer_callback(struct target_timer_callback *cb,
1380 struct timeval *now)
1382 cb->callback(cb->priv);
1384 if (cb->periodic)
1385 return target_timer_callback_periodic_restart(cb, now);
1387 return target_unregister_timer_callback(cb->callback, cb->priv);
1390 static int target_call_timer_callbacks_check_time(int checktime)
1392 keep_alive();
1394 struct timeval now;
1395 gettimeofday(&now, NULL);
1397 struct target_timer_callback *callback = target_timer_callbacks;
1398 while (callback) {
1399 /* cleaning up may unregister and free this callback */
1400 struct target_timer_callback *next_callback = callback->next;
1402 bool call_it = callback->callback &&
1403 ((!checktime && callback->periodic) ||
1404 now.tv_sec > callback->when.tv_sec ||
1405 (now.tv_sec == callback->when.tv_sec &&
1406 now.tv_usec >= callback->when.tv_usec));
1408 if (call_it) {
1409 int retval = target_call_timer_callback(callback, &now);
1410 if (retval != ERROR_OK)
1411 return retval;
1414 callback = next_callback;
1417 return ERROR_OK;
1420 int target_call_timer_callbacks(void)
1422 return target_call_timer_callbacks_check_time(1);
1425 /* invoke periodic callbacks immediately */
1426 int target_call_timer_callbacks_now(void)
1428 return target_call_timer_callbacks_check_time(0);
1431 /* Prints the working area layout for debug purposes */
1432 static void print_wa_layout(struct target *target)
1434 struct working_area *c = target->working_areas;
1436 while (c) {
1437 LOG_DEBUG("%c%c 0x%08"PRIx32"-0x%08"PRIx32" (%"PRIu32" bytes)",
1438 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1439 c->address, c->address + c->size - 1, c->size);
1440 c = c->next;
1444 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1445 static void target_split_working_area(struct working_area *area, uint32_t size)
1447 assert(area->free); /* Shouldn't split an allocated area */
1448 assert(size <= area->size); /* Caller should guarantee this */
1450 /* Split only if not already the right size */
1451 if (size < area->size) {
1452 struct working_area *new_wa = malloc(sizeof(*new_wa));
1454 if (new_wa == NULL)
1455 return;
1457 new_wa->next = area->next;
1458 new_wa->size = area->size - size;
1459 new_wa->address = area->address + size;
1460 new_wa->backup = NULL;
1461 new_wa->user = NULL;
1462 new_wa->free = true;
1464 area->next = new_wa;
1465 area->size = size;
1467 /* If backup memory was allocated to this area, it has the wrong size
1468 * now so free it and it will be reallocated if/when needed */
1469 if (area->backup) {
1470 free(area->backup);
1471 area->backup = NULL;
1476 /* Merge all adjacent free areas into one */
1477 static void target_merge_working_areas(struct target *target)
1479 struct working_area *c = target->working_areas;
1481 while (c && c->next) {
1482 assert(c->next->address == c->address + c->size); /* This is an invariant */
1484 /* Find two adjacent free areas */
1485 if (c->free && c->next->free) {
1486 /* Merge the last into the first */
1487 c->size += c->next->size;
1489 /* Remove the last */
1490 struct working_area *to_be_freed = c->next;
1491 c->next = c->next->next;
1492 if (to_be_freed->backup)
1493 free(to_be_freed->backup);
1494 free(to_be_freed);
1496 /* If backup memory was allocated to the remaining area, it's has
1497 * the wrong size now */
1498 if (c->backup) {
1499 free(c->backup);
1500 c->backup = NULL;
1502 } else {
1503 c = c->next;
1508 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1510 /* Reevaluate working area address based on MMU state*/
1511 if (target->working_areas == NULL) {
1512 int retval;
1513 int enabled;
1515 retval = target->type->mmu(target, &enabled);
1516 if (retval != ERROR_OK)
1517 return retval;
1519 if (!enabled) {
1520 if (target->working_area_phys_spec) {
1521 LOG_DEBUG("MMU disabled, using physical "
1522 "address for working memory 0x%08"PRIx32,
1523 target->working_area_phys);
1524 target->working_area = target->working_area_phys;
1525 } else {
1526 LOG_ERROR("No working memory available. "
1527 "Specify -work-area-phys to target.");
1528 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1530 } else {
1531 if (target->working_area_virt_spec) {
1532 LOG_DEBUG("MMU enabled, using virtual "
1533 "address for working memory 0x%08"PRIx32,
1534 target->working_area_virt);
1535 target->working_area = target->working_area_virt;
1536 } else {
1537 LOG_ERROR("No working memory available. "
1538 "Specify -work-area-virt to target.");
1539 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1543 /* Set up initial working area on first call */
1544 struct working_area *new_wa = malloc(sizeof(*new_wa));
1545 if (new_wa) {
1546 new_wa->next = NULL;
1547 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1548 new_wa->address = target->working_area;
1549 new_wa->backup = NULL;
1550 new_wa->user = NULL;
1551 new_wa->free = true;
1554 target->working_areas = new_wa;
1557 /* only allocate multiples of 4 byte */
1558 if (size % 4)
1559 size = (size + 3) & (~3UL);
1561 struct working_area *c = target->working_areas;
1563 /* Find the first large enough working area */
1564 while (c) {
1565 if (c->free && c->size >= size)
1566 break;
1567 c = c->next;
1570 if (c == NULL)
1571 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1573 /* Split the working area into the requested size */
1574 target_split_working_area(c, size);
1576 LOG_DEBUG("allocated new working area of %"PRIu32" bytes at address 0x%08"PRIx32, size, c->address);
1578 if (target->backup_working_area) {
1579 if (c->backup == NULL) {
1580 c->backup = malloc(c->size);
1581 if (c->backup == NULL)
1582 return ERROR_FAIL;
1585 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1586 if (retval != ERROR_OK)
1587 return retval;
1590 /* mark as used, and return the new (reused) area */
1591 c->free = false;
1592 *area = c;
1594 /* user pointer */
1595 c->user = area;
1597 print_wa_layout(target);
1599 return ERROR_OK;
1602 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1604 int retval;
1606 retval = target_alloc_working_area_try(target, size, area);
1607 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1608 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1609 return retval;
1613 static int target_restore_working_area(struct target *target, struct working_area *area)
1615 int retval = ERROR_OK;
1617 if (target->backup_working_area && area->backup != NULL) {
1618 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1619 if (retval != ERROR_OK)
1620 LOG_ERROR("failed to restore %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1621 area->size, area->address);
1624 return retval;
1627 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1628 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1630 int retval = ERROR_OK;
1632 if (area->free)
1633 return retval;
1635 if (restore) {
1636 retval = target_restore_working_area(target, area);
1637 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1638 if (retval != ERROR_OK)
1639 return retval;
1642 area->free = true;
1644 LOG_DEBUG("freed %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1645 area->size, area->address);
1647 /* mark user pointer invalid */
1648 /* TODO: Is this really safe? It points to some previous caller's memory.
1649 * How could we know that the area pointer is still in that place and not
1650 * some other vital data? What's the purpose of this, anyway? */
1651 *area->user = NULL;
1652 area->user = NULL;
1654 target_merge_working_areas(target);
1656 print_wa_layout(target);
1658 return retval;
1661 int target_free_working_area(struct target *target, struct working_area *area)
1663 return target_free_working_area_restore(target, area, 1);
1666 /* free resources and restore memory, if restoring memory fails,
1667 * free up resources anyway
1669 static void target_free_all_working_areas_restore(struct target *target, int restore)
1671 struct working_area *c = target->working_areas;
1673 LOG_DEBUG("freeing all working areas");
1675 /* Loop through all areas, restoring the allocated ones and marking them as free */
1676 while (c) {
1677 if (!c->free) {
1678 if (restore)
1679 target_restore_working_area(target, c);
1680 c->free = true;
1681 *c->user = NULL; /* Same as above */
1682 c->user = NULL;
1684 c = c->next;
1687 /* Run a merge pass to combine all areas into one */
1688 target_merge_working_areas(target);
1690 print_wa_layout(target);
1693 void target_free_all_working_areas(struct target *target)
1695 target_free_all_working_areas_restore(target, 1);
1698 /* Find the largest number of bytes that can be allocated */
1699 uint32_t target_get_working_area_avail(struct target *target)
1701 struct working_area *c = target->working_areas;
1702 uint32_t max_size = 0;
1704 if (c == NULL)
1705 return target->working_area_size;
1707 while (c) {
1708 if (c->free && max_size < c->size)
1709 max_size = c->size;
1711 c = c->next;
1714 return max_size;
1717 int target_arch_state(struct target *target)
1719 int retval;
1720 if (target == NULL) {
1721 LOG_USER("No target has been configured");
1722 return ERROR_OK;
1725 LOG_USER("target state: %s", target_state_name(target));
1727 if (target->state != TARGET_HALTED)
1728 return ERROR_OK;
1730 retval = target->type->arch_state(target);
1731 return retval;
1734 static int target_get_gdb_fileio_info_default(struct target *target,
1735 struct gdb_fileio_info *fileio_info)
1737 LOG_ERROR("Not implemented: %s", __func__);
1738 return ERROR_FAIL;
1741 static int target_gdb_fileio_end_default(struct target *target,
1742 int retcode, int fileio_errno, bool ctrl_c)
1744 LOG_ERROR("Not implemented: %s", __func__);
1745 return ERROR_OK;
1748 /* Single aligned words are guaranteed to use 16 or 32 bit access
1749 * mode respectively, otherwise data is handled as quickly as
1750 * possible
1752 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1754 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1755 (int)size, (unsigned)address);
1757 if (!target_was_examined(target)) {
1758 LOG_ERROR("Target not examined yet");
1759 return ERROR_FAIL;
1762 if (size == 0)
1763 return ERROR_OK;
1765 if ((address + size - 1) < address) {
1766 /* GDB can request this when e.g. PC is 0xfffffffc*/
1767 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1768 (unsigned)address,
1769 (unsigned)size);
1770 return ERROR_FAIL;
1773 return target->type->write_buffer(target, address, size, buffer);
1776 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1778 int retval = ERROR_OK;
1780 if (((address % 2) == 0) && (size == 2))
1781 return target_write_memory(target, address, 2, 1, buffer);
1783 /* handle unaligned head bytes */
1784 if (address % 4) {
1785 uint32_t unaligned = 4 - (address % 4);
1787 if (unaligned > size)
1788 unaligned = size;
1790 retval = target_write_memory(target, address, 1, unaligned, buffer);
1791 if (retval != ERROR_OK)
1792 return retval;
1794 buffer += unaligned;
1795 address += unaligned;
1796 size -= unaligned;
1799 /* handle aligned words */
1800 if (size >= 4) {
1801 int aligned = size - (size % 4);
1803 /* use bulk writes above a certain limit. This may have to be changed */
1804 if (aligned > 128) {
1805 retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer);
1806 if (retval != ERROR_OK)
1807 return retval;
1808 } else {
1809 retval = target_write_memory(target, address, 4, aligned / 4, buffer);
1810 if (retval != ERROR_OK)
1811 return retval;
1814 buffer += aligned;
1815 address += aligned;
1816 size -= aligned;
1819 /* handle tail writes of less than 4 bytes */
1820 if (size > 0) {
1821 retval = target_write_memory(target, address, 1, size, buffer);
1822 if (retval != ERROR_OK)
1823 return retval;
1826 return retval;
1829 /* Single aligned words are guaranteed to use 16 or 32 bit access
1830 * mode respectively, otherwise data is handled as quickly as
1831 * possible
1833 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1835 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1836 (int)size, (unsigned)address);
1838 if (!target_was_examined(target)) {
1839 LOG_ERROR("Target not examined yet");
1840 return ERROR_FAIL;
1843 if (size == 0)
1844 return ERROR_OK;
1846 if ((address + size - 1) < address) {
1847 /* GDB can request this when e.g. PC is 0xfffffffc*/
1848 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1849 address,
1850 size);
1851 return ERROR_FAIL;
1854 return target->type->read_buffer(target, address, size, buffer);
1857 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1859 int retval = ERROR_OK;
1861 if (((address % 2) == 0) && (size == 2))
1862 return target_read_memory(target, address, 2, 1, buffer);
1864 /* handle unaligned head bytes */
1865 if (address % 4) {
1866 uint32_t unaligned = 4 - (address % 4);
1868 if (unaligned > size)
1869 unaligned = size;
1871 retval = target_read_memory(target, address, 1, unaligned, buffer);
1872 if (retval != ERROR_OK)
1873 return retval;
1875 buffer += unaligned;
1876 address += unaligned;
1877 size -= unaligned;
1880 /* handle aligned words */
1881 if (size >= 4) {
1882 int aligned = size - (size % 4);
1884 retval = target_read_memory(target, address, 4, aligned / 4, buffer);
1885 if (retval != ERROR_OK)
1886 return retval;
1888 buffer += aligned;
1889 address += aligned;
1890 size -= aligned;
1893 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1894 if (size >= 2) {
1895 int aligned = size - (size % 2);
1896 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1897 if (retval != ERROR_OK)
1898 return retval;
1900 buffer += aligned;
1901 address += aligned;
1902 size -= aligned;
1904 /* handle tail writes of less than 4 bytes */
1905 if (size > 0) {
1906 retval = target_read_memory(target, address, 1, size, buffer);
1907 if (retval != ERROR_OK)
1908 return retval;
1911 return ERROR_OK;
1914 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1916 uint8_t *buffer;
1917 int retval;
1918 uint32_t i;
1919 uint32_t checksum = 0;
1920 if (!target_was_examined(target)) {
1921 LOG_ERROR("Target not examined yet");
1922 return ERROR_FAIL;
1925 retval = target->type->checksum_memory(target, address, size, &checksum);
1926 if (retval != ERROR_OK) {
1927 buffer = malloc(size);
1928 if (buffer == NULL) {
1929 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1930 return ERROR_COMMAND_SYNTAX_ERROR;
1932 retval = target_read_buffer(target, address, size, buffer);
1933 if (retval != ERROR_OK) {
1934 free(buffer);
1935 return retval;
1938 /* convert to target endianness */
1939 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
1940 uint32_t target_data;
1941 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1942 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1945 retval = image_calculate_checksum(buffer, size, &checksum);
1946 free(buffer);
1949 *crc = checksum;
1951 return retval;
1954 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1956 int retval;
1957 if (!target_was_examined(target)) {
1958 LOG_ERROR("Target not examined yet");
1959 return ERROR_FAIL;
1962 if (target->type->blank_check_memory == 0)
1963 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1965 retval = target->type->blank_check_memory(target, address, size, blank);
1967 return retval;
1970 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1972 uint8_t value_buf[4];
1973 if (!target_was_examined(target)) {
1974 LOG_ERROR("Target not examined yet");
1975 return ERROR_FAIL;
1978 int retval = target_read_memory(target, address, 4, 1, value_buf);
1980 if (retval == ERROR_OK) {
1981 *value = target_buffer_get_u32(target, value_buf);
1982 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1983 address,
1984 *value);
1985 } else {
1986 *value = 0x0;
1987 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1988 address);
1991 return retval;
1994 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1996 uint8_t value_buf[2];
1997 if (!target_was_examined(target)) {
1998 LOG_ERROR("Target not examined yet");
1999 return ERROR_FAIL;
2002 int retval = target_read_memory(target, address, 2, 1, value_buf);
2004 if (retval == ERROR_OK) {
2005 *value = target_buffer_get_u16(target, value_buf);
2006 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
2007 address,
2008 *value);
2009 } else {
2010 *value = 0x0;
2011 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2012 address);
2015 return retval;
2018 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
2020 int retval = target_read_memory(target, address, 1, 1, value);
2021 if (!target_was_examined(target)) {
2022 LOG_ERROR("Target not examined yet");
2023 return ERROR_FAIL;
2026 if (retval == ERROR_OK) {
2027 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2028 address,
2029 *value);
2030 } else {
2031 *value = 0x0;
2032 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2033 address);
2036 return retval;
2039 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
2041 int retval;
2042 uint8_t value_buf[4];
2043 if (!target_was_examined(target)) {
2044 LOG_ERROR("Target not examined yet");
2045 return ERROR_FAIL;
2048 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2049 address,
2050 value);
2052 target_buffer_set_u32(target, value_buf, value);
2053 retval = target_write_memory(target, address, 4, 1, value_buf);
2054 if (retval != ERROR_OK)
2055 LOG_DEBUG("failed: %i", retval);
2057 return retval;
2060 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
2062 int retval;
2063 uint8_t value_buf[2];
2064 if (!target_was_examined(target)) {
2065 LOG_ERROR("Target not examined yet");
2066 return ERROR_FAIL;
2069 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
2070 address,
2071 value);
2073 target_buffer_set_u16(target, value_buf, value);
2074 retval = target_write_memory(target, address, 2, 1, value_buf);
2075 if (retval != ERROR_OK)
2076 LOG_DEBUG("failed: %i", retval);
2078 return retval;
2081 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
2083 int retval;
2084 if (!target_was_examined(target)) {
2085 LOG_ERROR("Target not examined yet");
2086 return ERROR_FAIL;
2089 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2090 address, value);
2092 retval = target_write_memory(target, address, 1, 1, &value);
2093 if (retval != ERROR_OK)
2094 LOG_DEBUG("failed: %i", retval);
2096 return retval;
2099 static int find_target(struct command_context *cmd_ctx, const char *name)
2101 struct target *target = get_target(name);
2102 if (target == NULL) {
2103 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2104 return ERROR_FAIL;
2106 if (!target->tap->enabled) {
2107 LOG_USER("Target: TAP %s is disabled, "
2108 "can't be the current target\n",
2109 target->tap->dotted_name);
2110 return ERROR_FAIL;
2113 cmd_ctx->current_target = target->target_number;
2114 return ERROR_OK;
2118 COMMAND_HANDLER(handle_targets_command)
2120 int retval = ERROR_OK;
2121 if (CMD_ARGC == 1) {
2122 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2123 if (retval == ERROR_OK) {
2124 /* we're done! */
2125 return retval;
2129 struct target *target = all_targets;
2130 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2131 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2132 while (target) {
2133 const char *state;
2134 char marker = ' ';
2136 if (target->tap->enabled)
2137 state = target_state_name(target);
2138 else
2139 state = "tap-disabled";
2141 if (CMD_CTX->current_target == target->target_number)
2142 marker = '*';
2144 /* keep columns lined up to match the headers above */
2145 command_print(CMD_CTX,
2146 "%2d%c %-18s %-10s %-6s %-18s %s",
2147 target->target_number,
2148 marker,
2149 target_name(target),
2150 target_type_name(target),
2151 Jim_Nvp_value2name_simple(nvp_target_endian,
2152 target->endianness)->name,
2153 target->tap->dotted_name,
2154 state);
2155 target = target->next;
2158 return retval;
2161 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2163 static int powerDropout;
2164 static int srstAsserted;
2166 static int runPowerRestore;
2167 static int runPowerDropout;
2168 static int runSrstAsserted;
2169 static int runSrstDeasserted;
2171 static int sense_handler(void)
2173 static int prevSrstAsserted;
2174 static int prevPowerdropout;
2176 int retval = jtag_power_dropout(&powerDropout);
2177 if (retval != ERROR_OK)
2178 return retval;
2180 int powerRestored;
2181 powerRestored = prevPowerdropout && !powerDropout;
2182 if (powerRestored)
2183 runPowerRestore = 1;
2185 long long current = timeval_ms();
2186 static long long lastPower;
2187 int waitMore = lastPower + 2000 > current;
2188 if (powerDropout && !waitMore) {
2189 runPowerDropout = 1;
2190 lastPower = current;
2193 retval = jtag_srst_asserted(&srstAsserted);
2194 if (retval != ERROR_OK)
2195 return retval;
2197 int srstDeasserted;
2198 srstDeasserted = prevSrstAsserted && !srstAsserted;
2200 static long long lastSrst;
2201 waitMore = lastSrst + 2000 > current;
2202 if (srstDeasserted && !waitMore) {
2203 runSrstDeasserted = 1;
2204 lastSrst = current;
2207 if (!prevSrstAsserted && srstAsserted)
2208 runSrstAsserted = 1;
2210 prevSrstAsserted = srstAsserted;
2211 prevPowerdropout = powerDropout;
2213 if (srstDeasserted || powerRestored) {
2214 /* Other than logging the event we can't do anything here.
2215 * Issuing a reset is a particularly bad idea as we might
2216 * be inside a reset already.
2220 return ERROR_OK;
2223 /* process target state changes */
2224 static int handle_target(void *priv)
2226 Jim_Interp *interp = (Jim_Interp *)priv;
2227 int retval = ERROR_OK;
2229 if (!is_jtag_poll_safe()) {
2230 /* polling is disabled currently */
2231 return ERROR_OK;
2234 /* we do not want to recurse here... */
2235 static int recursive;
2236 if (!recursive) {
2237 recursive = 1;
2238 sense_handler();
2239 /* danger! running these procedures can trigger srst assertions and power dropouts.
2240 * We need to avoid an infinite loop/recursion here and we do that by
2241 * clearing the flags after running these events.
2243 int did_something = 0;
2244 if (runSrstAsserted) {
2245 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2246 Jim_Eval(interp, "srst_asserted");
2247 did_something = 1;
2249 if (runSrstDeasserted) {
2250 Jim_Eval(interp, "srst_deasserted");
2251 did_something = 1;
2253 if (runPowerDropout) {
2254 LOG_INFO("Power dropout detected, running power_dropout proc.");
2255 Jim_Eval(interp, "power_dropout");
2256 did_something = 1;
2258 if (runPowerRestore) {
2259 Jim_Eval(interp, "power_restore");
2260 did_something = 1;
2263 if (did_something) {
2264 /* clear detect flags */
2265 sense_handler();
2268 /* clear action flags */
2270 runSrstAsserted = 0;
2271 runSrstDeasserted = 0;
2272 runPowerRestore = 0;
2273 runPowerDropout = 0;
2275 recursive = 0;
2278 /* Poll targets for state changes unless that's globally disabled.
2279 * Skip targets that are currently disabled.
2281 for (struct target *target = all_targets;
2282 is_jtag_poll_safe() && target;
2283 target = target->next) {
2284 if (!target->tap->enabled)
2285 continue;
2287 if (target->backoff.times > target->backoff.count) {
2288 /* do not poll this time as we failed previously */
2289 target->backoff.count++;
2290 continue;
2292 target->backoff.count = 0;
2294 /* only poll target if we've got power and srst isn't asserted */
2295 if (!powerDropout && !srstAsserted) {
2296 /* polling may fail silently until the target has been examined */
2297 retval = target_poll(target);
2298 if (retval != ERROR_OK) {
2299 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2300 if (target->backoff.times * polling_interval < 5000) {
2301 target->backoff.times *= 2;
2302 target->backoff.times++;
2304 LOG_USER("Polling target %s failed, GDB will be halted. Polling again in %dms",
2305 target_name(target),
2306 target->backoff.times * polling_interval);
2308 /* Tell GDB to halt the debugger. This allows the user to
2309 * run monitor commands to handle the situation.
2311 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2312 return retval;
2314 /* Since we succeeded, we reset backoff count */
2315 if (target->backoff.times > 0)
2316 LOG_USER("Polling target %s succeeded again", target_name(target));
2317 target->backoff.times = 0;
2321 return retval;
2324 COMMAND_HANDLER(handle_reg_command)
2326 struct target *target;
2327 struct reg *reg = NULL;
2328 unsigned count = 0;
2329 char *value;
2331 LOG_DEBUG("-");
2333 target = get_current_target(CMD_CTX);
2335 /* list all available registers for the current target */
2336 if (CMD_ARGC == 0) {
2337 struct reg_cache *cache = target->reg_cache;
2339 count = 0;
2340 while (cache) {
2341 unsigned i;
2343 command_print(CMD_CTX, "===== %s", cache->name);
2345 for (i = 0, reg = cache->reg_list;
2346 i < cache->num_regs;
2347 i++, reg++, count++) {
2348 /* only print cached values if they are valid */
2349 if (reg->valid) {
2350 value = buf_to_str(reg->value,
2351 reg->size, 16);
2352 command_print(CMD_CTX,
2353 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2354 count, reg->name,
2355 reg->size, value,
2356 reg->dirty
2357 ? " (dirty)"
2358 : "");
2359 free(value);
2360 } else {
2361 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2362 count, reg->name,
2363 reg->size) ;
2366 cache = cache->next;
2369 return ERROR_OK;
2372 /* access a single register by its ordinal number */
2373 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2374 unsigned num;
2375 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2377 struct reg_cache *cache = target->reg_cache;
2378 count = 0;
2379 while (cache) {
2380 unsigned i;
2381 for (i = 0; i < cache->num_regs; i++) {
2382 if (count++ == num) {
2383 reg = &cache->reg_list[i];
2384 break;
2387 if (reg)
2388 break;
2389 cache = cache->next;
2392 if (!reg) {
2393 command_print(CMD_CTX, "%i is out of bounds, the current target "
2394 "has only %i registers (0 - %i)", num, count, count - 1);
2395 return ERROR_OK;
2397 } else {
2398 /* access a single register by its name */
2399 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2401 if (!reg) {
2402 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2403 return ERROR_OK;
2407 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2409 /* display a register */
2410 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2411 && (CMD_ARGV[1][0] <= '9')))) {
2412 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2413 reg->valid = 0;
2415 if (reg->valid == 0)
2416 reg->type->get(reg);
2417 value = buf_to_str(reg->value, reg->size, 16);
2418 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2419 free(value);
2420 return ERROR_OK;
2423 /* set register value */
2424 if (CMD_ARGC == 2) {
2425 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2426 if (buf == NULL)
2427 return ERROR_FAIL;
2428 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2430 reg->type->set(reg, buf);
2432 value = buf_to_str(reg->value, reg->size, 16);
2433 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2434 free(value);
2436 free(buf);
2438 return ERROR_OK;
2441 return ERROR_COMMAND_SYNTAX_ERROR;
2444 COMMAND_HANDLER(handle_poll_command)
2446 int retval = ERROR_OK;
2447 struct target *target = get_current_target(CMD_CTX);
2449 if (CMD_ARGC == 0) {
2450 command_print(CMD_CTX, "background polling: %s",
2451 jtag_poll_get_enabled() ? "on" : "off");
2452 command_print(CMD_CTX, "TAP: %s (%s)",
2453 target->tap->dotted_name,
2454 target->tap->enabled ? "enabled" : "disabled");
2455 if (!target->tap->enabled)
2456 return ERROR_OK;
2457 retval = target_poll(target);
2458 if (retval != ERROR_OK)
2459 return retval;
2460 retval = target_arch_state(target);
2461 if (retval != ERROR_OK)
2462 return retval;
2463 } else if (CMD_ARGC == 1) {
2464 bool enable;
2465 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2466 jtag_poll_set_enabled(enable);
2467 } else
2468 return ERROR_COMMAND_SYNTAX_ERROR;
2470 return retval;
2473 COMMAND_HANDLER(handle_wait_halt_command)
2475 if (CMD_ARGC > 1)
2476 return ERROR_COMMAND_SYNTAX_ERROR;
2478 unsigned ms = DEFAULT_HALT_TIMEOUT;
2479 if (1 == CMD_ARGC) {
2480 int retval = parse_uint(CMD_ARGV[0], &ms);
2481 if (ERROR_OK != retval)
2482 return ERROR_COMMAND_SYNTAX_ERROR;
2485 struct target *target = get_current_target(CMD_CTX);
2486 return target_wait_state(target, TARGET_HALTED, ms);
2489 /* wait for target state to change. The trick here is to have a low
2490 * latency for short waits and not to suck up all the CPU time
2491 * on longer waits.
2493 * After 500ms, keep_alive() is invoked
2495 int target_wait_state(struct target *target, enum target_state state, int ms)
2497 int retval;
2498 long long then = 0, cur;
2499 int once = 1;
2501 for (;;) {
2502 retval = target_poll(target);
2503 if (retval != ERROR_OK)
2504 return retval;
2505 if (target->state == state)
2506 break;
2507 cur = timeval_ms();
2508 if (once) {
2509 once = 0;
2510 then = timeval_ms();
2511 LOG_DEBUG("waiting for target %s...",
2512 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2515 if (cur-then > 500)
2516 keep_alive();
2518 if ((cur-then) > ms) {
2519 LOG_ERROR("timed out while waiting for target %s",
2520 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2521 return ERROR_FAIL;
2525 return ERROR_OK;
2528 COMMAND_HANDLER(handle_halt_command)
2530 LOG_DEBUG("-");
2532 struct target *target = get_current_target(CMD_CTX);
2533 int retval = target_halt(target);
2534 if (ERROR_OK != retval)
2535 return retval;
2537 if (CMD_ARGC == 1) {
2538 unsigned wait_local;
2539 retval = parse_uint(CMD_ARGV[0], &wait_local);
2540 if (ERROR_OK != retval)
2541 return ERROR_COMMAND_SYNTAX_ERROR;
2542 if (!wait_local)
2543 return ERROR_OK;
2546 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2549 COMMAND_HANDLER(handle_soft_reset_halt_command)
2551 struct target *target = get_current_target(CMD_CTX);
2553 LOG_USER("requesting target halt and executing a soft reset");
2555 target_soft_reset_halt(target);
2557 return ERROR_OK;
2560 COMMAND_HANDLER(handle_reset_command)
2562 if (CMD_ARGC > 1)
2563 return ERROR_COMMAND_SYNTAX_ERROR;
2565 enum target_reset_mode reset_mode = RESET_RUN;
2566 if (CMD_ARGC == 1) {
2567 const Jim_Nvp *n;
2568 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2569 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2570 return ERROR_COMMAND_SYNTAX_ERROR;
2571 reset_mode = n->value;
2574 /* reset *all* targets */
2575 return target_process_reset(CMD_CTX, reset_mode);
2579 COMMAND_HANDLER(handle_resume_command)
2581 int current = 1;
2582 if (CMD_ARGC > 1)
2583 return ERROR_COMMAND_SYNTAX_ERROR;
2585 struct target *target = get_current_target(CMD_CTX);
2587 /* with no CMD_ARGV, resume from current pc, addr = 0,
2588 * with one arguments, addr = CMD_ARGV[0],
2589 * handle breakpoints, not debugging */
2590 uint32_t addr = 0;
2591 if (CMD_ARGC == 1) {
2592 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2593 current = 0;
2596 return target_resume(target, current, addr, 1, 0);
2599 COMMAND_HANDLER(handle_step_command)
2601 if (CMD_ARGC > 1)
2602 return ERROR_COMMAND_SYNTAX_ERROR;
2604 LOG_DEBUG("-");
2606 /* with no CMD_ARGV, step from current pc, addr = 0,
2607 * with one argument addr = CMD_ARGV[0],
2608 * handle breakpoints, debugging */
2609 uint32_t addr = 0;
2610 int current_pc = 1;
2611 if (CMD_ARGC == 1) {
2612 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2613 current_pc = 0;
2616 struct target *target = get_current_target(CMD_CTX);
2618 return target->type->step(target, current_pc, addr, 1);
2621 static void handle_md_output(struct command_context *cmd_ctx,
2622 struct target *target, uint32_t address, unsigned size,
2623 unsigned count, const uint8_t *buffer)
2625 const unsigned line_bytecnt = 32;
2626 unsigned line_modulo = line_bytecnt / size;
2628 char output[line_bytecnt * 4 + 1];
2629 unsigned output_len = 0;
2631 const char *value_fmt;
2632 switch (size) {
2633 case 4:
2634 value_fmt = "%8.8x ";
2635 break;
2636 case 2:
2637 value_fmt = "%4.4x ";
2638 break;
2639 case 1:
2640 value_fmt = "%2.2x ";
2641 break;
2642 default:
2643 /* "can't happen", caller checked */
2644 LOG_ERROR("invalid memory read size: %u", size);
2645 return;
2648 for (unsigned i = 0; i < count; i++) {
2649 if (i % line_modulo == 0) {
2650 output_len += snprintf(output + output_len,
2651 sizeof(output) - output_len,
2652 "0x%8.8x: ",
2653 (unsigned)(address + (i*size)));
2656 uint32_t value = 0;
2657 const uint8_t *value_ptr = buffer + i * size;
2658 switch (size) {
2659 case 4:
2660 value = target_buffer_get_u32(target, value_ptr);
2661 break;
2662 case 2:
2663 value = target_buffer_get_u16(target, value_ptr);
2664 break;
2665 case 1:
2666 value = *value_ptr;
2668 output_len += snprintf(output + output_len,
2669 sizeof(output) - output_len,
2670 value_fmt, value);
2672 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2673 command_print(cmd_ctx, "%s", output);
2674 output_len = 0;
2679 COMMAND_HANDLER(handle_md_command)
2681 if (CMD_ARGC < 1)
2682 return ERROR_COMMAND_SYNTAX_ERROR;
2684 unsigned size = 0;
2685 switch (CMD_NAME[2]) {
2686 case 'w':
2687 size = 4;
2688 break;
2689 case 'h':
2690 size = 2;
2691 break;
2692 case 'b':
2693 size = 1;
2694 break;
2695 default:
2696 return ERROR_COMMAND_SYNTAX_ERROR;
2699 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2700 int (*fn)(struct target *target,
2701 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2702 if (physical) {
2703 CMD_ARGC--;
2704 CMD_ARGV++;
2705 fn = target_read_phys_memory;
2706 } else
2707 fn = target_read_memory;
2708 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2709 return ERROR_COMMAND_SYNTAX_ERROR;
2711 uint32_t address;
2712 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2714 unsigned count = 1;
2715 if (CMD_ARGC == 2)
2716 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2718 uint8_t *buffer = calloc(count, size);
2720 struct target *target = get_current_target(CMD_CTX);
2721 int retval = fn(target, address, size, count, buffer);
2722 if (ERROR_OK == retval)
2723 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2725 free(buffer);
2727 return retval;
2730 typedef int (*target_write_fn)(struct target *target,
2731 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2733 static int target_write_memory_fast(struct target *target,
2734 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
2736 return target_write_buffer(target, address, size * count, buffer);
2739 static int target_fill_mem(struct target *target,
2740 uint32_t address,
2741 target_write_fn fn,
2742 unsigned data_size,
2743 /* value */
2744 uint32_t b,
2745 /* count */
2746 unsigned c)
2748 /* We have to write in reasonably large chunks to be able
2749 * to fill large memory areas with any sane speed */
2750 const unsigned chunk_size = 16384;
2751 uint8_t *target_buf = malloc(chunk_size * data_size);
2752 if (target_buf == NULL) {
2753 LOG_ERROR("Out of memory");
2754 return ERROR_FAIL;
2757 for (unsigned i = 0; i < chunk_size; i++) {
2758 switch (data_size) {
2759 case 4:
2760 target_buffer_set_u32(target, target_buf + i * data_size, b);
2761 break;
2762 case 2:
2763 target_buffer_set_u16(target, target_buf + i * data_size, b);
2764 break;
2765 case 1:
2766 target_buffer_set_u8(target, target_buf + i * data_size, b);
2767 break;
2768 default:
2769 exit(-1);
2773 int retval = ERROR_OK;
2775 for (unsigned x = 0; x < c; x += chunk_size) {
2776 unsigned current;
2777 current = c - x;
2778 if (current > chunk_size)
2779 current = chunk_size;
2780 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2781 if (retval != ERROR_OK)
2782 break;
2783 /* avoid GDB timeouts */
2784 keep_alive();
2786 free(target_buf);
2788 return retval;
2792 COMMAND_HANDLER(handle_mw_command)
2794 if (CMD_ARGC < 2)
2795 return ERROR_COMMAND_SYNTAX_ERROR;
2796 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2797 target_write_fn fn;
2798 if (physical) {
2799 CMD_ARGC--;
2800 CMD_ARGV++;
2801 fn = target_write_phys_memory;
2802 } else
2803 fn = target_write_memory_fast;
2804 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2805 return ERROR_COMMAND_SYNTAX_ERROR;
2807 uint32_t address;
2808 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2810 uint32_t value;
2811 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2813 unsigned count = 1;
2814 if (CMD_ARGC == 3)
2815 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2817 struct target *target = get_current_target(CMD_CTX);
2818 unsigned wordsize;
2819 switch (CMD_NAME[2]) {
2820 case 'w':
2821 wordsize = 4;
2822 break;
2823 case 'h':
2824 wordsize = 2;
2825 break;
2826 case 'b':
2827 wordsize = 1;
2828 break;
2829 default:
2830 return ERROR_COMMAND_SYNTAX_ERROR;
2833 return target_fill_mem(target, address, fn, wordsize, value, count);
2836 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2837 uint32_t *min_address, uint32_t *max_address)
2839 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2840 return ERROR_COMMAND_SYNTAX_ERROR;
2842 /* a base address isn't always necessary,
2843 * default to 0x0 (i.e. don't relocate) */
2844 if (CMD_ARGC >= 2) {
2845 uint32_t addr;
2846 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2847 image->base_address = addr;
2848 image->base_address_set = 1;
2849 } else
2850 image->base_address_set = 0;
2852 image->start_address_set = 0;
2854 if (CMD_ARGC >= 4)
2855 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2856 if (CMD_ARGC == 5) {
2857 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2858 /* use size (given) to find max (required) */
2859 *max_address += *min_address;
2862 if (*min_address > *max_address)
2863 return ERROR_COMMAND_SYNTAX_ERROR;
2865 return ERROR_OK;
2868 COMMAND_HANDLER(handle_load_image_command)
2870 uint8_t *buffer;
2871 size_t buf_cnt;
2872 uint32_t image_size;
2873 uint32_t min_address = 0;
2874 uint32_t max_address = 0xffffffff;
2875 int i;
2876 struct image image;
2878 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2879 &image, &min_address, &max_address);
2880 if (ERROR_OK != retval)
2881 return retval;
2883 struct target *target = get_current_target(CMD_CTX);
2885 struct duration bench;
2886 duration_start(&bench);
2888 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2889 return ERROR_OK;
2891 image_size = 0x0;
2892 retval = ERROR_OK;
2893 for (i = 0; i < image.num_sections; i++) {
2894 buffer = malloc(image.sections[i].size);
2895 if (buffer == NULL) {
2896 command_print(CMD_CTX,
2897 "error allocating buffer for section (%d bytes)",
2898 (int)(image.sections[i].size));
2899 break;
2902 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
2903 if (retval != ERROR_OK) {
2904 free(buffer);
2905 break;
2908 uint32_t offset = 0;
2909 uint32_t length = buf_cnt;
2911 /* DANGER!!! beware of unsigned comparision here!!! */
2913 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
2914 (image.sections[i].base_address < max_address)) {
2916 if (image.sections[i].base_address < min_address) {
2917 /* clip addresses below */
2918 offset += min_address-image.sections[i].base_address;
2919 length -= offset;
2922 if (image.sections[i].base_address + buf_cnt > max_address)
2923 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2925 retval = target_write_buffer(target,
2926 image.sections[i].base_address + offset, length, buffer + offset);
2927 if (retval != ERROR_OK) {
2928 free(buffer);
2929 break;
2931 image_size += length;
2932 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2933 (unsigned int)length,
2934 image.sections[i].base_address + offset);
2937 free(buffer);
2940 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
2941 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2942 "in %fs (%0.3f KiB/s)", image_size,
2943 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2946 image_close(&image);
2948 return retval;
2952 COMMAND_HANDLER(handle_dump_image_command)
2954 struct fileio fileio;
2955 uint8_t *buffer;
2956 int retval, retvaltemp;
2957 uint32_t address, size;
2958 struct duration bench;
2959 struct target *target = get_current_target(CMD_CTX);
2961 if (CMD_ARGC != 3)
2962 return ERROR_COMMAND_SYNTAX_ERROR;
2964 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2965 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2967 uint32_t buf_size = (size > 4096) ? 4096 : size;
2968 buffer = malloc(buf_size);
2969 if (!buffer)
2970 return ERROR_FAIL;
2972 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2973 if (retval != ERROR_OK) {
2974 free(buffer);
2975 return retval;
2978 duration_start(&bench);
2980 while (size > 0) {
2981 size_t size_written;
2982 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
2983 retval = target_read_buffer(target, address, this_run_size, buffer);
2984 if (retval != ERROR_OK)
2985 break;
2987 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2988 if (retval != ERROR_OK)
2989 break;
2991 size -= this_run_size;
2992 address += this_run_size;
2995 free(buffer);
2997 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
2998 int filesize;
2999 retval = fileio_size(&fileio, &filesize);
3000 if (retval != ERROR_OK)
3001 return retval;
3002 command_print(CMD_CTX,
3003 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
3004 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3007 retvaltemp = fileio_close(&fileio);
3008 if (retvaltemp != ERROR_OK)
3009 return retvaltemp;
3011 return retval;
3014 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
3016 uint8_t *buffer;
3017 size_t buf_cnt;
3018 uint32_t image_size;
3019 int i;
3020 int retval;
3021 uint32_t checksum = 0;
3022 uint32_t mem_checksum = 0;
3024 struct image image;
3026 struct target *target = get_current_target(CMD_CTX);
3028 if (CMD_ARGC < 1)
3029 return ERROR_COMMAND_SYNTAX_ERROR;
3031 if (!target) {
3032 LOG_ERROR("no target selected");
3033 return ERROR_FAIL;
3036 struct duration bench;
3037 duration_start(&bench);
3039 if (CMD_ARGC >= 2) {
3040 uint32_t addr;
3041 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3042 image.base_address = addr;
3043 image.base_address_set = 1;
3044 } else {
3045 image.base_address_set = 0;
3046 image.base_address = 0x0;
3049 image.start_address_set = 0;
3051 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3052 if (retval != ERROR_OK)
3053 return retval;
3055 image_size = 0x0;
3056 int diffs = 0;
3057 retval = ERROR_OK;
3058 for (i = 0; i < image.num_sections; i++) {
3059 buffer = malloc(image.sections[i].size);
3060 if (buffer == NULL) {
3061 command_print(CMD_CTX,
3062 "error allocating buffer for section (%d bytes)",
3063 (int)(image.sections[i].size));
3064 break;
3066 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3067 if (retval != ERROR_OK) {
3068 free(buffer);
3069 break;
3072 if (verify) {
3073 /* calculate checksum of image */
3074 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3075 if (retval != ERROR_OK) {
3076 free(buffer);
3077 break;
3080 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3081 if (retval != ERROR_OK) {
3082 free(buffer);
3083 break;
3086 if (checksum != mem_checksum) {
3087 /* failed crc checksum, fall back to a binary compare */
3088 uint8_t *data;
3090 if (diffs == 0)
3091 LOG_ERROR("checksum mismatch - attempting binary compare");
3093 data = (uint8_t *)malloc(buf_cnt);
3095 /* Can we use 32bit word accesses? */
3096 int size = 1;
3097 int count = buf_cnt;
3098 if ((count % 4) == 0) {
3099 size *= 4;
3100 count /= 4;
3102 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3103 if (retval == ERROR_OK) {
3104 uint32_t t;
3105 for (t = 0; t < buf_cnt; t++) {
3106 if (data[t] != buffer[t]) {
3107 command_print(CMD_CTX,
3108 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3109 diffs,
3110 (unsigned)(t + image.sections[i].base_address),
3111 data[t],
3112 buffer[t]);
3113 if (diffs++ >= 127) {
3114 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3115 free(data);
3116 free(buffer);
3117 goto done;
3120 keep_alive();
3123 free(data);
3125 } else {
3126 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3127 image.sections[i].base_address,
3128 buf_cnt);
3131 free(buffer);
3132 image_size += buf_cnt;
3134 if (diffs > 0)
3135 command_print(CMD_CTX, "No more differences found.");
3136 done:
3137 if (diffs > 0)
3138 retval = ERROR_FAIL;
3139 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3140 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3141 "in %fs (%0.3f KiB/s)", image_size,
3142 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3145 image_close(&image);
3147 return retval;
3150 COMMAND_HANDLER(handle_verify_image_command)
3152 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3155 COMMAND_HANDLER(handle_test_image_command)
3157 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3160 static int handle_bp_command_list(struct command_context *cmd_ctx)
3162 struct target *target = get_current_target(cmd_ctx);
3163 struct breakpoint *breakpoint = target->breakpoints;
3164 while (breakpoint) {
3165 if (breakpoint->type == BKPT_SOFT) {
3166 char *buf = buf_to_str(breakpoint->orig_instr,
3167 breakpoint->length, 16);
3168 command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3169 breakpoint->address,
3170 breakpoint->length,
3171 breakpoint->set, buf);
3172 free(buf);
3173 } else {
3174 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3175 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3176 breakpoint->asid,
3177 breakpoint->length, breakpoint->set);
3178 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3179 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3180 breakpoint->address,
3181 breakpoint->length, breakpoint->set);
3182 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3183 breakpoint->asid);
3184 } else
3185 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3186 breakpoint->address,
3187 breakpoint->length, breakpoint->set);
3190 breakpoint = breakpoint->next;
3192 return ERROR_OK;
3195 static int handle_bp_command_set(struct command_context *cmd_ctx,
3196 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3198 struct target *target = get_current_target(cmd_ctx);
3200 if (asid == 0) {
3201 int retval = breakpoint_add(target, addr, length, hw);
3202 if (ERROR_OK == retval)
3203 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3204 else {
3205 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3206 return retval;
3208 } else if (addr == 0) {
3209 int retval = context_breakpoint_add(target, asid, length, hw);
3210 if (ERROR_OK == retval)
3211 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3212 else {
3213 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3214 return retval;
3216 } else {
3217 int retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3218 if (ERROR_OK == retval)
3219 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3220 else {
3221 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3222 return retval;
3225 return ERROR_OK;
3228 COMMAND_HANDLER(handle_bp_command)
3230 uint32_t addr;
3231 uint32_t asid;
3232 uint32_t length;
3233 int hw = BKPT_SOFT;
3235 switch (CMD_ARGC) {
3236 case 0:
3237 return handle_bp_command_list(CMD_CTX);
3239 case 2:
3240 asid = 0;
3241 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3242 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3243 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3245 case 3:
3246 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3247 hw = BKPT_HARD;
3248 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3250 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3252 asid = 0;
3253 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3254 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3255 hw = BKPT_HARD;
3256 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3257 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3258 addr = 0;
3259 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3262 case 4:
3263 hw = BKPT_HARD;
3264 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3265 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3266 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3267 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3269 default:
3270 return ERROR_COMMAND_SYNTAX_ERROR;
3274 COMMAND_HANDLER(handle_rbp_command)
3276 if (CMD_ARGC != 1)
3277 return ERROR_COMMAND_SYNTAX_ERROR;
3279 uint32_t addr;
3280 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3282 struct target *target = get_current_target(CMD_CTX);
3283 breakpoint_remove(target, addr);
3285 return ERROR_OK;
3288 COMMAND_HANDLER(handle_wp_command)
3290 struct target *target = get_current_target(CMD_CTX);
3292 if (CMD_ARGC == 0) {
3293 struct watchpoint *watchpoint = target->watchpoints;
3295 while (watchpoint) {
3296 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3297 ", len: 0x%8.8" PRIx32
3298 ", r/w/a: %i, value: 0x%8.8" PRIx32
3299 ", mask: 0x%8.8" PRIx32,
3300 watchpoint->address,
3301 watchpoint->length,
3302 (int)watchpoint->rw,
3303 watchpoint->value,
3304 watchpoint->mask);
3305 watchpoint = watchpoint->next;
3307 return ERROR_OK;
3310 enum watchpoint_rw type = WPT_ACCESS;
3311 uint32_t addr = 0;
3312 uint32_t length = 0;
3313 uint32_t data_value = 0x0;
3314 uint32_t data_mask = 0xffffffff;
3316 switch (CMD_ARGC) {
3317 case 5:
3318 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3319 /* fall through */
3320 case 4:
3321 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3322 /* fall through */
3323 case 3:
3324 switch (CMD_ARGV[2][0]) {
3325 case 'r':
3326 type = WPT_READ;
3327 break;
3328 case 'w':
3329 type = WPT_WRITE;
3330 break;
3331 case 'a':
3332 type = WPT_ACCESS;
3333 break;
3334 default:
3335 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3336 return ERROR_COMMAND_SYNTAX_ERROR;
3338 /* fall through */
3339 case 2:
3340 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3341 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3342 break;
3344 default:
3345 return ERROR_COMMAND_SYNTAX_ERROR;
3348 int retval = watchpoint_add(target, addr, length, type,
3349 data_value, data_mask);
3350 if (ERROR_OK != retval)
3351 LOG_ERROR("Failure setting watchpoints");
3353 return retval;
3356 COMMAND_HANDLER(handle_rwp_command)
3358 if (CMD_ARGC != 1)
3359 return ERROR_COMMAND_SYNTAX_ERROR;
3361 uint32_t addr;
3362 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3364 struct target *target = get_current_target(CMD_CTX);
3365 watchpoint_remove(target, addr);
3367 return ERROR_OK;
3371 * Translate a virtual address to a physical address.
3373 * The low-level target implementation must have logged a detailed error
3374 * which is forwarded to telnet/GDB session.
3376 COMMAND_HANDLER(handle_virt2phys_command)
3378 if (CMD_ARGC != 1)
3379 return ERROR_COMMAND_SYNTAX_ERROR;
3381 uint32_t va;
3382 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3383 uint32_t pa;
3385 struct target *target = get_current_target(CMD_CTX);
3386 int retval = target->type->virt2phys(target, va, &pa);
3387 if (retval == ERROR_OK)
3388 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3390 return retval;
3393 static void writeData(FILE *f, const void *data, size_t len)
3395 size_t written = fwrite(data, 1, len, f);
3396 if (written != len)
3397 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3400 static void writeLong(FILE *f, int l)
3402 int i;
3403 for (i = 0; i < 4; i++) {
3404 char c = (l >> (i*8))&0xff;
3405 writeData(f, &c, 1);
3410 static void writeString(FILE *f, char *s)
3412 writeData(f, s, strlen(s));
3415 /* Dump a gmon.out histogram file. */
3416 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3418 uint32_t i;
3419 FILE *f = fopen(filename, "w");
3420 if (f == NULL)
3421 return;
3422 writeString(f, "gmon");
3423 writeLong(f, 0x00000001); /* Version */
3424 writeLong(f, 0); /* padding */
3425 writeLong(f, 0); /* padding */
3426 writeLong(f, 0); /* padding */
3428 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3429 writeData(f, &zero, 1);
3431 /* figure out bucket size */
3432 uint32_t min = samples[0];
3433 uint32_t max = samples[0];
3434 for (i = 0; i < sampleNum; i++) {
3435 if (min > samples[i])
3436 min = samples[i];
3437 if (max < samples[i])
3438 max = samples[i];
3441 int addressSpace = (max - min + 1);
3442 assert(addressSpace >= 2);
3444 static const uint32_t maxBuckets = 16 * 1024; /* maximum buckets. */
3445 uint32_t length = addressSpace;
3446 if (length > maxBuckets)
3447 length = maxBuckets;
3448 int *buckets = malloc(sizeof(int)*length);
3449 if (buckets == NULL) {
3450 fclose(f);
3451 return;
3453 memset(buckets, 0, sizeof(int) * length);
3454 for (i = 0; i < sampleNum; i++) {
3455 uint32_t address = samples[i];
3456 long long a = address - min;
3457 long long b = length - 1;
3458 long long c = addressSpace - 1;
3459 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3460 buckets[index_t]++;
3463 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3464 writeLong(f, min); /* low_pc */
3465 writeLong(f, max); /* high_pc */
3466 writeLong(f, length); /* # of samples */
3467 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3468 writeString(f, "seconds");
3469 for (i = 0; i < (15-strlen("seconds")); i++)
3470 writeData(f, &zero, 1);
3471 writeString(f, "s");
3473 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3475 char *data = malloc(2 * length);
3476 if (data != NULL) {
3477 for (i = 0; i < length; i++) {
3478 int val;
3479 val = buckets[i];
3480 if (val > 65535)
3481 val = 65535;
3482 data[i * 2] = val&0xff;
3483 data[i * 2 + 1] = (val >> 8) & 0xff;
3485 free(buckets);
3486 writeData(f, data, length * 2);
3487 free(data);
3488 } else
3489 free(buckets);
3491 fclose(f);
3494 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3495 * which will be used as a random sampling of PC */
3496 COMMAND_HANDLER(handle_profile_command)
3498 struct target *target = get_current_target(CMD_CTX);
3499 struct timeval timeout, now;
3501 gettimeofday(&timeout, NULL);
3502 if (CMD_ARGC != 2)
3503 return ERROR_COMMAND_SYNTAX_ERROR;
3504 unsigned offset;
3505 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3507 timeval_add_time(&timeout, offset, 0);
3510 * @todo: Some cores let us sample the PC without the
3511 * annoying halt/resume step; for example, ARMv7 PCSR.
3512 * Provide a way to use that more efficient mechanism.
3515 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3517 static const int maxSample = 10000;
3518 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3519 if (samples == NULL)
3520 return ERROR_OK;
3522 int numSamples = 0;
3523 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3524 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3526 int retval = ERROR_OK;
3527 for (;;) {
3528 target_poll(target);
3529 if (target->state == TARGET_HALTED) {
3530 uint32_t t = *((uint32_t *)reg->value);
3531 samples[numSamples++] = t;
3532 /* current pc, addr = 0, do not handle breakpoints, not debugging */
3533 retval = target_resume(target, 1, 0, 0, 0);
3534 target_poll(target);
3535 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3536 } else if (target->state == TARGET_RUNNING) {
3537 /* We want to quickly sample the PC. */
3538 retval = target_halt(target);
3539 if (retval != ERROR_OK) {
3540 free(samples);
3541 return retval;
3543 } else {
3544 command_print(CMD_CTX, "Target not halted or running");
3545 retval = ERROR_OK;
3546 break;
3548 if (retval != ERROR_OK)
3549 break;
3551 gettimeofday(&now, NULL);
3552 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec)
3553 && (now.tv_usec >= timeout.tv_usec))) {
3554 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3555 retval = target_poll(target);
3556 if (retval != ERROR_OK) {
3557 free(samples);
3558 return retval;
3560 if (target->state == TARGET_HALTED) {
3561 /* current pc, addr = 0, do not handle
3562 * breakpoints, not debugging */
3563 target_resume(target, 1, 0, 0, 0);
3565 retval = target_poll(target);
3566 if (retval != ERROR_OK) {
3567 free(samples);
3568 return retval;
3570 writeGmon(samples, numSamples, CMD_ARGV[1]);
3571 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3572 break;
3575 free(samples);
3577 return retval;
3580 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3582 char *namebuf;
3583 Jim_Obj *nameObjPtr, *valObjPtr;
3584 int result;
3586 namebuf = alloc_printf("%s(%d)", varname, idx);
3587 if (!namebuf)
3588 return JIM_ERR;
3590 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3591 valObjPtr = Jim_NewIntObj(interp, val);
3592 if (!nameObjPtr || !valObjPtr) {
3593 free(namebuf);
3594 return JIM_ERR;
3597 Jim_IncrRefCount(nameObjPtr);
3598 Jim_IncrRefCount(valObjPtr);
3599 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3600 Jim_DecrRefCount(interp, nameObjPtr);
3601 Jim_DecrRefCount(interp, valObjPtr);
3602 free(namebuf);
3603 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3604 return result;
3607 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3609 struct command_context *context;
3610 struct target *target;
3612 context = current_command_context(interp);
3613 assert(context != NULL);
3615 target = get_current_target(context);
3616 if (target == NULL) {
3617 LOG_ERROR("mem2array: no current target");
3618 return JIM_ERR;
3621 return target_mem2array(interp, target, argc - 1, argv + 1);
3624 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3626 long l;
3627 uint32_t width;
3628 int len;
3629 uint32_t addr;
3630 uint32_t count;
3631 uint32_t v;
3632 const char *varname;
3633 int n, e, retval;
3634 uint32_t i;
3636 /* argv[1] = name of array to receive the data
3637 * argv[2] = desired width
3638 * argv[3] = memory address
3639 * argv[4] = count of times to read
3641 if (argc != 4) {
3642 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3643 return JIM_ERR;
3645 varname = Jim_GetString(argv[0], &len);
3646 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3648 e = Jim_GetLong(interp, argv[1], &l);
3649 width = l;
3650 if (e != JIM_OK)
3651 return e;
3653 e = Jim_GetLong(interp, argv[2], &l);
3654 addr = l;
3655 if (e != JIM_OK)
3656 return e;
3657 e = Jim_GetLong(interp, argv[3], &l);
3658 len = l;
3659 if (e != JIM_OK)
3660 return e;
3661 switch (width) {
3662 case 8:
3663 width = 1;
3664 break;
3665 case 16:
3666 width = 2;
3667 break;
3668 case 32:
3669 width = 4;
3670 break;
3671 default:
3672 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3673 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3674 return JIM_ERR;
3676 if (len == 0) {
3677 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3678 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3679 return JIM_ERR;
3681 if ((addr + (len * width)) < addr) {
3682 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3683 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3684 return JIM_ERR;
3686 /* absurd transfer size? */
3687 if (len > 65536) {
3688 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3689 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3690 return JIM_ERR;
3693 if ((width == 1) ||
3694 ((width == 2) && ((addr & 1) == 0)) ||
3695 ((width == 4) && ((addr & 3) == 0))) {
3696 /* all is well */
3697 } else {
3698 char buf[100];
3699 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3700 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3701 addr,
3702 width);
3703 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3704 return JIM_ERR;
3707 /* Transfer loop */
3709 /* index counter */
3710 n = 0;
3712 size_t buffersize = 4096;
3713 uint8_t *buffer = malloc(buffersize);
3714 if (buffer == NULL)
3715 return JIM_ERR;
3717 /* assume ok */
3718 e = JIM_OK;
3719 while (len) {
3720 /* Slurp... in buffer size chunks */
3722 count = len; /* in objects.. */
3723 if (count > (buffersize / width))
3724 count = (buffersize / width);
3726 retval = target_read_memory(target, addr, width, count, buffer);
3727 if (retval != ERROR_OK) {
3728 /* BOO !*/
3729 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3730 (unsigned int)addr,
3731 (int)width,
3732 (int)count);
3733 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3734 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3735 e = JIM_ERR;
3736 break;
3737 } else {
3738 v = 0; /* shut up gcc */
3739 for (i = 0; i < count ; i++, n++) {
3740 switch (width) {
3741 case 4:
3742 v = target_buffer_get_u32(target, &buffer[i*width]);
3743 break;
3744 case 2:
3745 v = target_buffer_get_u16(target, &buffer[i*width]);
3746 break;
3747 case 1:
3748 v = buffer[i] & 0x0ff;
3749 break;
3751 new_int_array_element(interp, varname, n, v);
3753 len -= count;
3757 free(buffer);
3759 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3761 return e;
3764 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
3766 char *namebuf;
3767 Jim_Obj *nameObjPtr, *valObjPtr;
3768 int result;
3769 long l;
3771 namebuf = alloc_printf("%s(%d)", varname, idx);
3772 if (!namebuf)
3773 return JIM_ERR;
3775 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3776 if (!nameObjPtr) {
3777 free(namebuf);
3778 return JIM_ERR;
3781 Jim_IncrRefCount(nameObjPtr);
3782 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3783 Jim_DecrRefCount(interp, nameObjPtr);
3784 free(namebuf);
3785 if (valObjPtr == NULL)
3786 return JIM_ERR;
3788 result = Jim_GetLong(interp, valObjPtr, &l);
3789 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3790 *val = l;
3791 return result;
3794 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3796 struct command_context *context;
3797 struct target *target;
3799 context = current_command_context(interp);
3800 assert(context != NULL);
3802 target = get_current_target(context);
3803 if (target == NULL) {
3804 LOG_ERROR("array2mem: no current target");
3805 return JIM_ERR;
3808 return target_array2mem(interp, target, argc-1, argv + 1);
3811 static int target_array2mem(Jim_Interp *interp, struct target *target,
3812 int argc, Jim_Obj *const *argv)
3814 long l;
3815 uint32_t width;
3816 int len;
3817 uint32_t addr;
3818 uint32_t count;
3819 uint32_t v;
3820 const char *varname;
3821 int n, e, retval;
3822 uint32_t i;
3824 /* argv[1] = name of array to get the data
3825 * argv[2] = desired width
3826 * argv[3] = memory address
3827 * argv[4] = count to write
3829 if (argc != 4) {
3830 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3831 return JIM_ERR;
3833 varname = Jim_GetString(argv[0], &len);
3834 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3836 e = Jim_GetLong(interp, argv[1], &l);
3837 width = l;
3838 if (e != JIM_OK)
3839 return e;
3841 e = Jim_GetLong(interp, argv[2], &l);
3842 addr = l;
3843 if (e != JIM_OK)
3844 return e;
3845 e = Jim_GetLong(interp, argv[3], &l);
3846 len = l;
3847 if (e != JIM_OK)
3848 return e;
3849 switch (width) {
3850 case 8:
3851 width = 1;
3852 break;
3853 case 16:
3854 width = 2;
3855 break;
3856 case 32:
3857 width = 4;
3858 break;
3859 default:
3860 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3861 Jim_AppendStrings(interp, Jim_GetResult(interp),
3862 "Invalid width param, must be 8/16/32", NULL);
3863 return JIM_ERR;
3865 if (len == 0) {
3866 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3867 Jim_AppendStrings(interp, Jim_GetResult(interp),
3868 "array2mem: zero width read?", NULL);
3869 return JIM_ERR;
3871 if ((addr + (len * width)) < addr) {
3872 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3873 Jim_AppendStrings(interp, Jim_GetResult(interp),
3874 "array2mem: addr + len - wraps to zero?", NULL);
3875 return JIM_ERR;
3877 /* absurd transfer size? */
3878 if (len > 65536) {
3879 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3880 Jim_AppendStrings(interp, Jim_GetResult(interp),
3881 "array2mem: absurd > 64K item request", NULL);
3882 return JIM_ERR;
3885 if ((width == 1) ||
3886 ((width == 2) && ((addr & 1) == 0)) ||
3887 ((width == 4) && ((addr & 3) == 0))) {
3888 /* all is well */
3889 } else {
3890 char buf[100];
3891 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3892 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3893 (unsigned int)addr,
3894 (int)width);
3895 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3896 return JIM_ERR;
3899 /* Transfer loop */
3901 /* index counter */
3902 n = 0;
3903 /* assume ok */
3904 e = JIM_OK;
3906 size_t buffersize = 4096;
3907 uint8_t *buffer = malloc(buffersize);
3908 if (buffer == NULL)
3909 return JIM_ERR;
3911 while (len) {
3912 /* Slurp... in buffer size chunks */
3914 count = len; /* in objects.. */
3915 if (count > (buffersize / width))
3916 count = (buffersize / width);
3918 v = 0; /* shut up gcc */
3919 for (i = 0; i < count; i++, n++) {
3920 get_int_array_element(interp, varname, n, &v);
3921 switch (width) {
3922 case 4:
3923 target_buffer_set_u32(target, &buffer[i * width], v);
3924 break;
3925 case 2:
3926 target_buffer_set_u16(target, &buffer[i * width], v);
3927 break;
3928 case 1:
3929 buffer[i] = v & 0x0ff;
3930 break;
3933 len -= count;
3935 retval = target_write_memory(target, addr, width, count, buffer);
3936 if (retval != ERROR_OK) {
3937 /* BOO !*/
3938 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3939 (unsigned int)addr,
3940 (int)width,
3941 (int)count);
3942 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3943 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3944 e = JIM_ERR;
3945 break;
3949 free(buffer);
3951 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3953 return e;
3956 /* FIX? should we propagate errors here rather than printing them
3957 * and continuing?
3959 void target_handle_event(struct target *target, enum target_event e)
3961 struct target_event_action *teap;
3963 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3964 if (teap->event == e) {
3965 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3966 target->target_number,
3967 target_name(target),
3968 target_type_name(target),
3970 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3971 Jim_GetString(teap->body, NULL));
3972 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
3973 Jim_MakeErrorMessage(teap->interp);
3974 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
3981 * Returns true only if the target has a handler for the specified event.
3983 bool target_has_event_action(struct target *target, enum target_event event)
3985 struct target_event_action *teap;
3987 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3988 if (teap->event == event)
3989 return true;
3991 return false;
3994 enum target_cfg_param {
3995 TCFG_TYPE,
3996 TCFG_EVENT,
3997 TCFG_WORK_AREA_VIRT,
3998 TCFG_WORK_AREA_PHYS,
3999 TCFG_WORK_AREA_SIZE,
4000 TCFG_WORK_AREA_BACKUP,
4001 TCFG_ENDIAN,
4002 TCFG_VARIANT,
4003 TCFG_COREID,
4004 TCFG_CHAIN_POSITION,
4005 TCFG_DBGBASE,
4006 TCFG_RTOS,
4009 static Jim_Nvp nvp_config_opts[] = {
4010 { .name = "-type", .value = TCFG_TYPE },
4011 { .name = "-event", .value = TCFG_EVENT },
4012 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4013 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4014 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4015 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4016 { .name = "-endian" , .value = TCFG_ENDIAN },
4017 { .name = "-variant", .value = TCFG_VARIANT },
4018 { .name = "-coreid", .value = TCFG_COREID },
4019 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4020 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4021 { .name = "-rtos", .value = TCFG_RTOS },
4022 { .name = NULL, .value = -1 }
4025 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
4027 Jim_Nvp *n;
4028 Jim_Obj *o;
4029 jim_wide w;
4030 char *cp;
4031 int e;
4033 /* parse config or cget options ... */
4034 while (goi->argc > 0) {
4035 Jim_SetEmptyResult(goi->interp);
4036 /* Jim_GetOpt_Debug(goi); */
4038 if (target->type->target_jim_configure) {
4039 /* target defines a configure function */
4040 /* target gets first dibs on parameters */
4041 e = (*(target->type->target_jim_configure))(target, goi);
4042 if (e == JIM_OK) {
4043 /* more? */
4044 continue;
4046 if (e == JIM_ERR) {
4047 /* An error */
4048 return e;
4050 /* otherwise we 'continue' below */
4052 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
4053 if (e != JIM_OK) {
4054 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
4055 return e;
4057 switch (n->value) {
4058 case TCFG_TYPE:
4059 /* not setable */
4060 if (goi->isconfigure) {
4061 Jim_SetResultFormatted(goi->interp,
4062 "not settable: %s", n->name);
4063 return JIM_ERR;
4064 } else {
4065 no_params:
4066 if (goi->argc != 0) {
4067 Jim_WrongNumArgs(goi->interp,
4068 goi->argc, goi->argv,
4069 "NO PARAMS");
4070 return JIM_ERR;
4073 Jim_SetResultString(goi->interp,
4074 target_type_name(target), -1);
4075 /* loop for more */
4076 break;
4077 case TCFG_EVENT:
4078 if (goi->argc == 0) {
4079 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4080 return JIM_ERR;
4083 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4084 if (e != JIM_OK) {
4085 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4086 return e;
4089 if (goi->isconfigure) {
4090 if (goi->argc != 1) {
4091 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4092 return JIM_ERR;
4094 } else {
4095 if (goi->argc != 0) {
4096 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4097 return JIM_ERR;
4102 struct target_event_action *teap;
4104 teap = target->event_action;
4105 /* replace existing? */
4106 while (teap) {
4107 if (teap->event == (enum target_event)n->value)
4108 break;
4109 teap = teap->next;
4112 if (goi->isconfigure) {
4113 bool replace = true;
4114 if (teap == NULL) {
4115 /* create new */
4116 teap = calloc(1, sizeof(*teap));
4117 replace = false;
4119 teap->event = n->value;
4120 teap->interp = goi->interp;
4121 Jim_GetOpt_Obj(goi, &o);
4122 if (teap->body)
4123 Jim_DecrRefCount(teap->interp, teap->body);
4124 teap->body = Jim_DuplicateObj(goi->interp, o);
4126 * FIXME:
4127 * Tcl/TK - "tk events" have a nice feature.
4128 * See the "BIND" command.
4129 * We should support that here.
4130 * You can specify %X and %Y in the event code.
4131 * The idea is: %T - target name.
4132 * The idea is: %N - target number
4133 * The idea is: %E - event name.
4135 Jim_IncrRefCount(teap->body);
4137 if (!replace) {
4138 /* add to head of event list */
4139 teap->next = target->event_action;
4140 target->event_action = teap;
4142 Jim_SetEmptyResult(goi->interp);
4143 } else {
4144 /* get */
4145 if (teap == NULL)
4146 Jim_SetEmptyResult(goi->interp);
4147 else
4148 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4151 /* loop for more */
4152 break;
4154 case TCFG_WORK_AREA_VIRT:
4155 if (goi->isconfigure) {
4156 target_free_all_working_areas(target);
4157 e = Jim_GetOpt_Wide(goi, &w);
4158 if (e != JIM_OK)
4159 return e;
4160 target->working_area_virt = w;
4161 target->working_area_virt_spec = true;
4162 } else {
4163 if (goi->argc != 0)
4164 goto no_params;
4166 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4167 /* loop for more */
4168 break;
4170 case TCFG_WORK_AREA_PHYS:
4171 if (goi->isconfigure) {
4172 target_free_all_working_areas(target);
4173 e = Jim_GetOpt_Wide(goi, &w);
4174 if (e != JIM_OK)
4175 return e;
4176 target->working_area_phys = w;
4177 target->working_area_phys_spec = true;
4178 } else {
4179 if (goi->argc != 0)
4180 goto no_params;
4182 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4183 /* loop for more */
4184 break;
4186 case TCFG_WORK_AREA_SIZE:
4187 if (goi->isconfigure) {
4188 target_free_all_working_areas(target);
4189 e = Jim_GetOpt_Wide(goi, &w);
4190 if (e != JIM_OK)
4191 return e;
4192 target->working_area_size = w;
4193 } else {
4194 if (goi->argc != 0)
4195 goto no_params;
4197 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4198 /* loop for more */
4199 break;
4201 case TCFG_WORK_AREA_BACKUP:
4202 if (goi->isconfigure) {
4203 target_free_all_working_areas(target);
4204 e = Jim_GetOpt_Wide(goi, &w);
4205 if (e != JIM_OK)
4206 return e;
4207 /* make this exactly 1 or 0 */
4208 target->backup_working_area = (!!w);
4209 } else {
4210 if (goi->argc != 0)
4211 goto no_params;
4213 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4214 /* loop for more e*/
4215 break;
4218 case TCFG_ENDIAN:
4219 if (goi->isconfigure) {
4220 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4221 if (e != JIM_OK) {
4222 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4223 return e;
4225 target->endianness = n->value;
4226 } else {
4227 if (goi->argc != 0)
4228 goto no_params;
4230 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4231 if (n->name == NULL) {
4232 target->endianness = TARGET_LITTLE_ENDIAN;
4233 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4235 Jim_SetResultString(goi->interp, n->name, -1);
4236 /* loop for more */
4237 break;
4239 case TCFG_VARIANT:
4240 if (goi->isconfigure) {
4241 if (goi->argc < 1) {
4242 Jim_SetResultFormatted(goi->interp,
4243 "%s ?STRING?",
4244 n->name);
4245 return JIM_ERR;
4247 if (target->variant)
4248 free((void *)(target->variant));
4249 e = Jim_GetOpt_String(goi, &cp, NULL);
4250 if (e != JIM_OK)
4251 return e;
4252 target->variant = strdup(cp);
4253 } else {
4254 if (goi->argc != 0)
4255 goto no_params;
4257 Jim_SetResultString(goi->interp, target->variant, -1);
4258 /* loop for more */
4259 break;
4261 case TCFG_COREID:
4262 if (goi->isconfigure) {
4263 e = Jim_GetOpt_Wide(goi, &w);
4264 if (e != JIM_OK)
4265 return e;
4266 target->coreid = (int32_t)w;
4267 } else {
4268 if (goi->argc != 0)
4269 goto no_params;
4271 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4272 /* loop for more */
4273 break;
4275 case TCFG_CHAIN_POSITION:
4276 if (goi->isconfigure) {
4277 Jim_Obj *o_t;
4278 struct jtag_tap *tap;
4279 target_free_all_working_areas(target);
4280 e = Jim_GetOpt_Obj(goi, &o_t);
4281 if (e != JIM_OK)
4282 return e;
4283 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4284 if (tap == NULL)
4285 return JIM_ERR;
4286 /* make this exactly 1 or 0 */
4287 target->tap = tap;
4288 } else {
4289 if (goi->argc != 0)
4290 goto no_params;
4292 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4293 /* loop for more e*/
4294 break;
4295 case TCFG_DBGBASE:
4296 if (goi->isconfigure) {
4297 e = Jim_GetOpt_Wide(goi, &w);
4298 if (e != JIM_OK)
4299 return e;
4300 target->dbgbase = (uint32_t)w;
4301 target->dbgbase_set = true;
4302 } else {
4303 if (goi->argc != 0)
4304 goto no_params;
4306 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4307 /* loop for more */
4308 break;
4310 case TCFG_RTOS:
4311 /* RTOS */
4313 int result = rtos_create(goi, target);
4314 if (result != JIM_OK)
4315 return result;
4317 /* loop for more */
4318 break;
4320 } /* while (goi->argc) */
4323 /* done - we return */
4324 return JIM_OK;
4327 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4329 Jim_GetOptInfo goi;
4331 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4332 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4333 int need_args = 1 + goi.isconfigure;
4334 if (goi.argc < need_args) {
4335 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4336 goi.isconfigure
4337 ? "missing: -option VALUE ..."
4338 : "missing: -option ...");
4339 return JIM_ERR;
4341 struct target *target = Jim_CmdPrivData(goi.interp);
4342 return target_configure(&goi, target);
4345 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4347 const char *cmd_name = Jim_GetString(argv[0], NULL);
4349 Jim_GetOptInfo goi;
4350 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4352 if (goi.argc < 2 || goi.argc > 4) {
4353 Jim_SetResultFormatted(goi.interp,
4354 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4355 return JIM_ERR;
4358 target_write_fn fn;
4359 fn = target_write_memory_fast;
4361 int e;
4362 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4363 /* consume it */
4364 struct Jim_Obj *obj;
4365 e = Jim_GetOpt_Obj(&goi, &obj);
4366 if (e != JIM_OK)
4367 return e;
4369 fn = target_write_phys_memory;
4372 jim_wide a;
4373 e = Jim_GetOpt_Wide(&goi, &a);
4374 if (e != JIM_OK)
4375 return e;
4377 jim_wide b;
4378 e = Jim_GetOpt_Wide(&goi, &b);
4379 if (e != JIM_OK)
4380 return e;
4382 jim_wide c = 1;
4383 if (goi.argc == 1) {
4384 e = Jim_GetOpt_Wide(&goi, &c);
4385 if (e != JIM_OK)
4386 return e;
4389 /* all args must be consumed */
4390 if (goi.argc != 0)
4391 return JIM_ERR;
4393 struct target *target = Jim_CmdPrivData(goi.interp);
4394 unsigned data_size;
4395 if (strcasecmp(cmd_name, "mww") == 0)
4396 data_size = 4;
4397 else if (strcasecmp(cmd_name, "mwh") == 0)
4398 data_size = 2;
4399 else if (strcasecmp(cmd_name, "mwb") == 0)
4400 data_size = 1;
4401 else {
4402 LOG_ERROR("command '%s' unknown: ", cmd_name);
4403 return JIM_ERR;
4406 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4410 * @brief Reads an array of words/halfwords/bytes from target memory starting at specified address.
4412 * Usage: mdw [phys] <address> [<count>] - for 32 bit reads
4413 * mdh [phys] <address> [<count>] - for 16 bit reads
4414 * mdb [phys] <address> [<count>] - for 8 bit reads
4416 * Count defaults to 1.
4418 * Calls target_read_memory or target_read_phys_memory depending on
4419 * the presence of the "phys" argument
4420 * Reads the target memory in blocks of max. 32 bytes, and returns an array of ints formatted
4421 * to int representation in base16.
4422 * Also outputs read data in a human readable form using command_print
4424 * @param phys if present target_read_phys_memory will be used instead of target_read_memory
4425 * @param address address where to start the read. May be specified in decimal or hex using the standard "0x" prefix
4426 * @param count optional count parameter to read an array of values. If not specified, defaults to 1.
4427 * @returns: JIM_ERR on error or JIM_OK on success and sets the result string to an array of ascii formatted numbers
4428 * on success, with [<count>] number of elements.
4430 * In case of little endian target:
4431 * Example1: "mdw 0x00000000" returns "10123456"
4432 * Exmaple2: "mdh 0x00000000 1" returns "3456"
4433 * Example3: "mdb 0x00000000" returns "56"
4434 * Example4: "mdh 0x00000000 2" returns "3456 1012"
4435 * Example5: "mdb 0x00000000 3" returns "56 34 12"
4437 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4439 const char *cmd_name = Jim_GetString(argv[0], NULL);
4441 Jim_GetOptInfo goi;
4442 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4444 if ((goi.argc < 1) || (goi.argc > 3)) {
4445 Jim_SetResultFormatted(goi.interp,
4446 "usage: %s [phys] <address> [<count>]", cmd_name);
4447 return JIM_ERR;
4450 int (*fn)(struct target *target,
4451 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4452 fn = target_read_memory;
4454 int e;
4455 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4456 /* consume it */
4457 struct Jim_Obj *obj;
4458 e = Jim_GetOpt_Obj(&goi, &obj);
4459 if (e != JIM_OK)
4460 return e;
4462 fn = target_read_phys_memory;
4465 /* Read address parameter */
4466 jim_wide addr;
4467 e = Jim_GetOpt_Wide(&goi, &addr);
4468 if (e != JIM_OK)
4469 return JIM_ERR;
4471 /* If next parameter exists, read it out as the count parameter, if not, set it to 1 (default) */
4472 jim_wide count;
4473 if (goi.argc == 1) {
4474 e = Jim_GetOpt_Wide(&goi, &count);
4475 if (e != JIM_OK)
4476 return JIM_ERR;
4477 } else
4478 count = 1;
4480 /* all args must be consumed */
4481 if (goi.argc != 0)
4482 return JIM_ERR;
4484 jim_wide dwidth = 1; /* shut up gcc */
4485 if (strcasecmp(cmd_name, "mdw") == 0)
4486 dwidth = 4;
4487 else if (strcasecmp(cmd_name, "mdh") == 0)
4488 dwidth = 2;
4489 else if (strcasecmp(cmd_name, "mdb") == 0)
4490 dwidth = 1;
4491 else {
4492 LOG_ERROR("command '%s' unknown: ", cmd_name);
4493 return JIM_ERR;
4496 /* convert count to "bytes" */
4497 int bytes = count * dwidth;
4499 struct target *target = Jim_CmdPrivData(goi.interp);
4500 uint8_t target_buf[32];
4501 jim_wide x, y, z;
4502 while (bytes > 0) {
4503 y = (bytes < 16) ? bytes : 16; /* y = min(bytes, 16); */
4505 /* Try to read out next block */
4506 e = fn(target, addr, dwidth, y / dwidth, target_buf);
4508 if (e != ERROR_OK) {
4509 Jim_SetResultFormatted(interp, "error reading target @ 0x%08lx", (long)addr);
4510 return JIM_ERR;
4513 command_print_sameline(NULL, "0x%08x ", (int)(addr));
4514 switch (dwidth) {
4515 case 4:
4516 for (x = 0; x < 16 && x < y; x += 4) {
4517 z = target_buffer_get_u32(target, &(target_buf[x]));
4518 command_print_sameline(NULL, "%08x ", (int)(z));
4520 for (; (x < 16) ; x += 4)
4521 command_print_sameline(NULL, " ");
4522 break;
4523 case 2:
4524 for (x = 0; x < 16 && x < y; x += 2) {
4525 z = target_buffer_get_u16(target, &(target_buf[x]));
4526 command_print_sameline(NULL, "%04x ", (int)(z));
4528 for (; (x < 16) ; x += 2)
4529 command_print_sameline(NULL, " ");
4530 break;
4531 case 1:
4532 default:
4533 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4534 z = target_buffer_get_u8(target, &(target_buf[x]));
4535 command_print_sameline(NULL, "%02x ", (int)(z));
4537 for (; (x < 16) ; x += 1)
4538 command_print_sameline(NULL, " ");
4539 break;
4541 /* ascii-ify the bytes */
4542 for (x = 0 ; x < y ; x++) {
4543 if ((target_buf[x] >= 0x20) &&
4544 (target_buf[x] <= 0x7e)) {
4545 /* good */
4546 } else {
4547 /* smack it */
4548 target_buf[x] = '.';
4551 /* space pad */
4552 while (x < 16) {
4553 target_buf[x] = ' ';
4554 x++;
4556 /* terminate */
4557 target_buf[16] = 0;
4558 /* print - with a newline */
4559 command_print_sameline(NULL, "%s\n", target_buf);
4560 /* NEXT... */
4561 bytes -= 16;
4562 addr += 16;
4564 return JIM_OK;
4567 static int jim_target_mem2array(Jim_Interp *interp,
4568 int argc, Jim_Obj *const *argv)
4570 struct target *target = Jim_CmdPrivData(interp);
4571 return target_mem2array(interp, target, argc - 1, argv + 1);
4574 static int jim_target_array2mem(Jim_Interp *interp,
4575 int argc, Jim_Obj *const *argv)
4577 struct target *target = Jim_CmdPrivData(interp);
4578 return target_array2mem(interp, target, argc - 1, argv + 1);
4581 static int jim_target_tap_disabled(Jim_Interp *interp)
4583 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4584 return JIM_ERR;
4587 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4589 if (argc != 1) {
4590 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4591 return JIM_ERR;
4593 struct target *target = Jim_CmdPrivData(interp);
4594 if (!target->tap->enabled)
4595 return jim_target_tap_disabled(interp);
4597 int e = target->type->examine(target);
4598 if (e != ERROR_OK)
4599 return JIM_ERR;
4600 return JIM_OK;
4603 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4605 if (argc != 1) {
4606 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4607 return JIM_ERR;
4609 struct target *target = Jim_CmdPrivData(interp);
4611 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4612 return JIM_ERR;
4614 return JIM_OK;
4617 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4619 if (argc != 1) {
4620 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4621 return JIM_ERR;
4623 struct target *target = Jim_CmdPrivData(interp);
4624 if (!target->tap->enabled)
4625 return jim_target_tap_disabled(interp);
4627 int e;
4628 if (!(target_was_examined(target)))
4629 e = ERROR_TARGET_NOT_EXAMINED;
4630 else
4631 e = target->type->poll(target);
4632 if (e != ERROR_OK)
4633 return JIM_ERR;
4634 return JIM_OK;
4637 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4639 Jim_GetOptInfo goi;
4640 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4642 if (goi.argc != 2) {
4643 Jim_WrongNumArgs(interp, 0, argv,
4644 "([tT]|[fF]|assert|deassert) BOOL");
4645 return JIM_ERR;
4648 Jim_Nvp *n;
4649 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4650 if (e != JIM_OK) {
4651 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4652 return e;
4654 /* the halt or not param */
4655 jim_wide a;
4656 e = Jim_GetOpt_Wide(&goi, &a);
4657 if (e != JIM_OK)
4658 return e;
4660 struct target *target = Jim_CmdPrivData(goi.interp);
4661 if (!target->tap->enabled)
4662 return jim_target_tap_disabled(interp);
4663 if (!(target_was_examined(target))) {
4664 LOG_ERROR("Target not examined yet");
4665 return ERROR_TARGET_NOT_EXAMINED;
4667 if (!target->type->assert_reset || !target->type->deassert_reset) {
4668 Jim_SetResultFormatted(interp,
4669 "No target-specific reset for %s",
4670 target_name(target));
4671 return JIM_ERR;
4673 /* determine if we should halt or not. */
4674 target->reset_halt = !!a;
4675 /* When this happens - all workareas are invalid. */
4676 target_free_all_working_areas_restore(target, 0);
4678 /* do the assert */
4679 if (n->value == NVP_ASSERT)
4680 e = target->type->assert_reset(target);
4681 else
4682 e = target->type->deassert_reset(target);
4683 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4686 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4688 if (argc != 1) {
4689 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4690 return JIM_ERR;
4692 struct target *target = Jim_CmdPrivData(interp);
4693 if (!target->tap->enabled)
4694 return jim_target_tap_disabled(interp);
4695 int e = target->type->halt(target);
4696 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4699 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4701 Jim_GetOptInfo goi;
4702 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4704 /* params: <name> statename timeoutmsecs */
4705 if (goi.argc != 2) {
4706 const char *cmd_name = Jim_GetString(argv[0], NULL);
4707 Jim_SetResultFormatted(goi.interp,
4708 "%s <state_name> <timeout_in_msec>", cmd_name);
4709 return JIM_ERR;
4712 Jim_Nvp *n;
4713 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4714 if (e != JIM_OK) {
4715 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
4716 return e;
4718 jim_wide a;
4719 e = Jim_GetOpt_Wide(&goi, &a);
4720 if (e != JIM_OK)
4721 return e;
4722 struct target *target = Jim_CmdPrivData(interp);
4723 if (!target->tap->enabled)
4724 return jim_target_tap_disabled(interp);
4726 e = target_wait_state(target, n->value, a);
4727 if (e != ERROR_OK) {
4728 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4729 Jim_SetResultFormatted(goi.interp,
4730 "target: %s wait %s fails (%#s) %s",
4731 target_name(target), n->name,
4732 eObj, target_strerror_safe(e));
4733 Jim_FreeNewObj(interp, eObj);
4734 return JIM_ERR;
4736 return JIM_OK;
4738 /* List for human, Events defined for this target.
4739 * scripts/programs should use 'name cget -event NAME'
4741 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4743 struct command_context *cmd_ctx = current_command_context(interp);
4744 assert(cmd_ctx != NULL);
4746 struct target *target = Jim_CmdPrivData(interp);
4747 struct target_event_action *teap = target->event_action;
4748 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4749 target->target_number,
4750 target_name(target));
4751 command_print(cmd_ctx, "%-25s | Body", "Event");
4752 command_print(cmd_ctx, "------------------------- | "
4753 "----------------------------------------");
4754 while (teap) {
4755 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4756 command_print(cmd_ctx, "%-25s | %s",
4757 opt->name, Jim_GetString(teap->body, NULL));
4758 teap = teap->next;
4760 command_print(cmd_ctx, "***END***");
4761 return JIM_OK;
4763 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4765 if (argc != 1) {
4766 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4767 return JIM_ERR;
4769 struct target *target = Jim_CmdPrivData(interp);
4770 Jim_SetResultString(interp, target_state_name(target), -1);
4771 return JIM_OK;
4773 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4775 Jim_GetOptInfo goi;
4776 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4777 if (goi.argc != 1) {
4778 const char *cmd_name = Jim_GetString(argv[0], NULL);
4779 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4780 return JIM_ERR;
4782 Jim_Nvp *n;
4783 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4784 if (e != JIM_OK) {
4785 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4786 return e;
4788 struct target *target = Jim_CmdPrivData(interp);
4789 target_handle_event(target, n->value);
4790 return JIM_OK;
4793 static const struct command_registration target_instance_command_handlers[] = {
4795 .name = "configure",
4796 .mode = COMMAND_CONFIG,
4797 .jim_handler = jim_target_configure,
4798 .help = "configure a new target for use",
4799 .usage = "[target_attribute ...]",
4802 .name = "cget",
4803 .mode = COMMAND_ANY,
4804 .jim_handler = jim_target_configure,
4805 .help = "returns the specified target attribute",
4806 .usage = "target_attribute",
4809 .name = "mww",
4810 .mode = COMMAND_EXEC,
4811 .jim_handler = jim_target_mw,
4812 .help = "Write 32-bit word(s) to target memory",
4813 .usage = "address data [count]",
4816 .name = "mwh",
4817 .mode = COMMAND_EXEC,
4818 .jim_handler = jim_target_mw,
4819 .help = "Write 16-bit half-word(s) to target memory",
4820 .usage = "address data [count]",
4823 .name = "mwb",
4824 .mode = COMMAND_EXEC,
4825 .jim_handler = jim_target_mw,
4826 .help = "Write byte(s) to target memory",
4827 .usage = "address data [count]",
4830 .name = "mdw",
4831 .mode = COMMAND_EXEC,
4832 .jim_handler = jim_target_md,
4833 .help = "Display target memory as 32-bit words",
4834 .usage = "address [count]",
4837 .name = "mdh",
4838 .mode = COMMAND_EXEC,
4839 .jim_handler = jim_target_md,
4840 .help = "Display target memory as 16-bit half-words",
4841 .usage = "address [count]",
4844 .name = "mdb",
4845 .mode = COMMAND_EXEC,
4846 .jim_handler = jim_target_md,
4847 .help = "Display target memory as 8-bit bytes",
4848 .usage = "address [count]",
4851 .name = "array2mem",
4852 .mode = COMMAND_EXEC,
4853 .jim_handler = jim_target_array2mem,
4854 .help = "Writes Tcl array of 8/16/32 bit numbers "
4855 "to target memory",
4856 .usage = "arrayname bitwidth address count",
4859 .name = "mem2array",
4860 .mode = COMMAND_EXEC,
4861 .jim_handler = jim_target_mem2array,
4862 .help = "Loads Tcl array of 8/16/32 bit numbers "
4863 "from target memory",
4864 .usage = "arrayname bitwidth address count",
4867 .name = "eventlist",
4868 .mode = COMMAND_EXEC,
4869 .jim_handler = jim_target_event_list,
4870 .help = "displays a table of events defined for this target",
4873 .name = "curstate",
4874 .mode = COMMAND_EXEC,
4875 .jim_handler = jim_target_current_state,
4876 .help = "displays the current state of this target",
4879 .name = "arp_examine",
4880 .mode = COMMAND_EXEC,
4881 .jim_handler = jim_target_examine,
4882 .help = "used internally for reset processing",
4885 .name = "arp_halt_gdb",
4886 .mode = COMMAND_EXEC,
4887 .jim_handler = jim_target_halt_gdb,
4888 .help = "used internally for reset processing to halt GDB",
4891 .name = "arp_poll",
4892 .mode = COMMAND_EXEC,
4893 .jim_handler = jim_target_poll,
4894 .help = "used internally for reset processing",
4897 .name = "arp_reset",
4898 .mode = COMMAND_EXEC,
4899 .jim_handler = jim_target_reset,
4900 .help = "used internally for reset processing",
4903 .name = "arp_halt",
4904 .mode = COMMAND_EXEC,
4905 .jim_handler = jim_target_halt,
4906 .help = "used internally for reset processing",
4909 .name = "arp_waitstate",
4910 .mode = COMMAND_EXEC,
4911 .jim_handler = jim_target_wait_state,
4912 .help = "used internally for reset processing",
4915 .name = "invoke-event",
4916 .mode = COMMAND_EXEC,
4917 .jim_handler = jim_target_invoke_event,
4918 .help = "invoke handler for specified event",
4919 .usage = "event_name",
4921 COMMAND_REGISTRATION_DONE
4924 static int target_create(Jim_GetOptInfo *goi)
4926 Jim_Obj *new_cmd;
4927 Jim_Cmd *cmd;
4928 const char *cp;
4929 char *cp2;
4930 int e;
4931 int x;
4932 struct target *target;
4933 struct command_context *cmd_ctx;
4935 cmd_ctx = current_command_context(goi->interp);
4936 assert(cmd_ctx != NULL);
4938 if (goi->argc < 3) {
4939 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4940 return JIM_ERR;
4943 /* COMMAND */
4944 Jim_GetOpt_Obj(goi, &new_cmd);
4945 /* does this command exist? */
4946 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4947 if (cmd) {
4948 cp = Jim_GetString(new_cmd, NULL);
4949 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
4950 return JIM_ERR;
4953 /* TYPE */
4954 e = Jim_GetOpt_String(goi, &cp2, NULL);
4955 if (e != JIM_OK)
4956 return e;
4957 cp = cp2;
4958 /* now does target type exist */
4959 for (x = 0 ; target_types[x] ; x++) {
4960 if (0 == strcmp(cp, target_types[x]->name)) {
4961 /* found */
4962 break;
4965 /* check for deprecated name */
4966 if (target_types[x]->deprecated_name) {
4967 if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
4968 /* found */
4969 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
4970 break;
4974 if (target_types[x] == NULL) {
4975 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
4976 for (x = 0 ; target_types[x] ; x++) {
4977 if (target_types[x + 1]) {
4978 Jim_AppendStrings(goi->interp,
4979 Jim_GetResult(goi->interp),
4980 target_types[x]->name,
4981 ", ", NULL);
4982 } else {
4983 Jim_AppendStrings(goi->interp,
4984 Jim_GetResult(goi->interp),
4985 " or ",
4986 target_types[x]->name, NULL);
4989 return JIM_ERR;
4992 /* Create it */
4993 target = calloc(1, sizeof(struct target));
4994 /* set target number */
4995 target->target_number = new_target_number();
4997 /* allocate memory for each unique target type */
4998 target->type = (struct target_type *)calloc(1, sizeof(struct target_type));
5000 memcpy(target->type, target_types[x], sizeof(struct target_type));
5002 /* will be set by "-endian" */
5003 target->endianness = TARGET_ENDIAN_UNKNOWN;
5005 /* default to first core, override with -coreid */
5006 target->coreid = 0;
5008 target->working_area = 0x0;
5009 target->working_area_size = 0x0;
5010 target->working_areas = NULL;
5011 target->backup_working_area = 0;
5013 target->state = TARGET_UNKNOWN;
5014 target->debug_reason = DBG_REASON_UNDEFINED;
5015 target->reg_cache = NULL;
5016 target->breakpoints = NULL;
5017 target->watchpoints = NULL;
5018 target->next = NULL;
5019 target->arch_info = NULL;
5021 target->display = 1;
5023 target->halt_issued = false;
5025 /* initialize trace information */
5026 target->trace_info = malloc(sizeof(struct trace));
5027 target->trace_info->num_trace_points = 0;
5028 target->trace_info->trace_points_size = 0;
5029 target->trace_info->trace_points = NULL;
5030 target->trace_info->trace_history_size = 0;
5031 target->trace_info->trace_history = NULL;
5032 target->trace_info->trace_history_pos = 0;
5033 target->trace_info->trace_history_overflowed = 0;
5035 target->dbgmsg = NULL;
5036 target->dbg_msg_enabled = 0;
5038 target->endianness = TARGET_ENDIAN_UNKNOWN;
5040 target->rtos = NULL;
5041 target->rtos_auto_detect = false;
5043 /* Do the rest as "configure" options */
5044 goi->isconfigure = 1;
5045 e = target_configure(goi, target);
5047 if (target->tap == NULL) {
5048 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
5049 e = JIM_ERR;
5052 if (e != JIM_OK) {
5053 free(target->type);
5054 free(target);
5055 return e;
5058 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5059 /* default endian to little if not specified */
5060 target->endianness = TARGET_LITTLE_ENDIAN;
5063 /* incase variant is not set */
5064 if (!target->variant)
5065 target->variant = strdup("");
5067 cp = Jim_GetString(new_cmd, NULL);
5068 target->cmd_name = strdup(cp);
5070 /* create the target specific commands */
5071 if (target->type->commands) {
5072 e = register_commands(cmd_ctx, NULL, target->type->commands);
5073 if (ERROR_OK != e)
5074 LOG_ERROR("unable to register '%s' commands", cp);
5076 if (target->type->target_create)
5077 (*(target->type->target_create))(target, goi->interp);
5079 /* append to end of list */
5081 struct target **tpp;
5082 tpp = &(all_targets);
5083 while (*tpp)
5084 tpp = &((*tpp)->next);
5085 *tpp = target;
5088 /* now - create the new target name command */
5089 const struct command_registration target_subcommands[] = {
5091 .chain = target_instance_command_handlers,
5094 .chain = target->type->commands,
5096 COMMAND_REGISTRATION_DONE
5098 const struct command_registration target_commands[] = {
5100 .name = cp,
5101 .mode = COMMAND_ANY,
5102 .help = "target command group",
5103 .usage = "",
5104 .chain = target_subcommands,
5106 COMMAND_REGISTRATION_DONE
5108 e = register_commands(cmd_ctx, NULL, target_commands);
5109 if (ERROR_OK != e)
5110 return JIM_ERR;
5112 struct command *c = command_find_in_context(cmd_ctx, cp);
5113 assert(c);
5114 command_set_handler_data(c, target);
5116 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5119 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5121 if (argc != 1) {
5122 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5123 return JIM_ERR;
5125 struct command_context *cmd_ctx = current_command_context(interp);
5126 assert(cmd_ctx != NULL);
5128 Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5129 return JIM_OK;
5132 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5134 if (argc != 1) {
5135 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5136 return JIM_ERR;
5138 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5139 for (unsigned x = 0; NULL != target_types[x]; x++) {
5140 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5141 Jim_NewStringObj(interp, target_types[x]->name, -1));
5143 return JIM_OK;
5146 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5148 if (argc != 1) {
5149 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5150 return JIM_ERR;
5152 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5153 struct target *target = all_targets;
5154 while (target) {
5155 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5156 Jim_NewStringObj(interp, target_name(target), -1));
5157 target = target->next;
5159 return JIM_OK;
5162 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5164 int i;
5165 const char *targetname;
5166 int retval, len;
5167 struct target *target = (struct target *) NULL;
5168 struct target_list *head, *curr, *new;
5169 curr = (struct target_list *) NULL;
5170 head = (struct target_list *) NULL;
5172 retval = 0;
5173 LOG_DEBUG("%d", argc);
5174 /* argv[1] = target to associate in smp
5175 * argv[2] = target to assoicate in smp
5176 * argv[3] ...
5179 for (i = 1; i < argc; i++) {
5181 targetname = Jim_GetString(argv[i], &len);
5182 target = get_target(targetname);
5183 LOG_DEBUG("%s ", targetname);
5184 if (target) {
5185 new = malloc(sizeof(struct target_list));
5186 new->target = target;
5187 new->next = (struct target_list *)NULL;
5188 if (head == (struct target_list *)NULL) {
5189 head = new;
5190 curr = head;
5191 } else {
5192 curr->next = new;
5193 curr = new;
5197 /* now parse the list of cpu and put the target in smp mode*/
5198 curr = head;
5200 while (curr != (struct target_list *)NULL) {
5201 target = curr->target;
5202 target->smp = 1;
5203 target->head = head;
5204 curr = curr->next;
5207 if (target && target->rtos)
5208 retval = rtos_smp_init(head->target);
5210 return retval;
5214 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5216 Jim_GetOptInfo goi;
5217 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5218 if (goi.argc < 3) {
5219 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5220 "<name> <target_type> [<target_options> ...]");
5221 return JIM_ERR;
5223 return target_create(&goi);
5226 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5228 Jim_GetOptInfo goi;
5229 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5231 /* It's OK to remove this mechanism sometime after August 2010 or so */
5232 LOG_WARNING("don't use numbers as target identifiers; use names");
5233 if (goi.argc != 1) {
5234 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
5235 return JIM_ERR;
5237 jim_wide w;
5238 int e = Jim_GetOpt_Wide(&goi, &w);
5239 if (e != JIM_OK)
5240 return JIM_ERR;
5242 struct target *target;
5243 for (target = all_targets; NULL != target; target = target->next) {
5244 if (target->target_number != w)
5245 continue;
5247 Jim_SetResultString(goi.interp, target_name(target), -1);
5248 return JIM_OK;
5251 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
5252 Jim_SetResultFormatted(goi.interp,
5253 "Target: number %#s does not exist", wObj);
5254 Jim_FreeNewObj(interp, wObj);
5256 return JIM_ERR;
5259 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5261 if (argc != 1) {
5262 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
5263 return JIM_ERR;
5265 unsigned count = 0;
5266 struct target *target = all_targets;
5267 while (NULL != target) {
5268 target = target->next;
5269 count++;
5271 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
5272 return JIM_OK;
5275 static const struct command_registration target_subcommand_handlers[] = {
5277 .name = "init",
5278 .mode = COMMAND_CONFIG,
5279 .handler = handle_target_init_command,
5280 .help = "initialize targets",
5283 .name = "create",
5284 /* REVISIT this should be COMMAND_CONFIG ... */
5285 .mode = COMMAND_ANY,
5286 .jim_handler = jim_target_create,
5287 .usage = "name type '-chain-position' name [options ...]",
5288 .help = "Creates and selects a new target",
5291 .name = "current",
5292 .mode = COMMAND_ANY,
5293 .jim_handler = jim_target_current,
5294 .help = "Returns the currently selected target",
5297 .name = "types",
5298 .mode = COMMAND_ANY,
5299 .jim_handler = jim_target_types,
5300 .help = "Returns the available target types as "
5301 "a list of strings",
5304 .name = "names",
5305 .mode = COMMAND_ANY,
5306 .jim_handler = jim_target_names,
5307 .help = "Returns the names of all targets as a list of strings",
5310 .name = "number",
5311 .mode = COMMAND_ANY,
5312 .jim_handler = jim_target_number,
5313 .usage = "number",
5314 .help = "Returns the name of the numbered target "
5315 "(DEPRECATED)",
5318 .name = "count",
5319 .mode = COMMAND_ANY,
5320 .jim_handler = jim_target_count,
5321 .help = "Returns the number of targets as an integer "
5322 "(DEPRECATED)",
5325 .name = "smp",
5326 .mode = COMMAND_ANY,
5327 .jim_handler = jim_target_smp,
5328 .usage = "targetname1 targetname2 ...",
5329 .help = "gather several target in a smp list"
5332 COMMAND_REGISTRATION_DONE
5335 struct FastLoad {
5336 uint32_t address;
5337 uint8_t *data;
5338 int length;
5342 static int fastload_num;
5343 static struct FastLoad *fastload;
5345 static void free_fastload(void)
5347 if (fastload != NULL) {
5348 int i;
5349 for (i = 0; i < fastload_num; i++) {
5350 if (fastload[i].data)
5351 free(fastload[i].data);
5353 free(fastload);
5354 fastload = NULL;
5358 COMMAND_HANDLER(handle_fast_load_image_command)
5360 uint8_t *buffer;
5361 size_t buf_cnt;
5362 uint32_t image_size;
5363 uint32_t min_address = 0;
5364 uint32_t max_address = 0xffffffff;
5365 int i;
5367 struct image image;
5369 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5370 &image, &min_address, &max_address);
5371 if (ERROR_OK != retval)
5372 return retval;
5374 struct duration bench;
5375 duration_start(&bench);
5377 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5378 if (retval != ERROR_OK)
5379 return retval;
5381 image_size = 0x0;
5382 retval = ERROR_OK;
5383 fastload_num = image.num_sections;
5384 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
5385 if (fastload == NULL) {
5386 command_print(CMD_CTX, "out of memory");
5387 image_close(&image);
5388 return ERROR_FAIL;
5390 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5391 for (i = 0; i < image.num_sections; i++) {
5392 buffer = malloc(image.sections[i].size);
5393 if (buffer == NULL) {
5394 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5395 (int)(image.sections[i].size));
5396 retval = ERROR_FAIL;
5397 break;
5400 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5401 if (retval != ERROR_OK) {
5402 free(buffer);
5403 break;
5406 uint32_t offset = 0;
5407 uint32_t length = buf_cnt;
5409 /* DANGER!!! beware of unsigned comparision here!!! */
5411 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5412 (image.sections[i].base_address < max_address)) {
5413 if (image.sections[i].base_address < min_address) {
5414 /* clip addresses below */
5415 offset += min_address-image.sections[i].base_address;
5416 length -= offset;
5419 if (image.sections[i].base_address + buf_cnt > max_address)
5420 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5422 fastload[i].address = image.sections[i].base_address + offset;
5423 fastload[i].data = malloc(length);
5424 if (fastload[i].data == NULL) {
5425 free(buffer);
5426 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5427 length);
5428 retval = ERROR_FAIL;
5429 break;
5431 memcpy(fastload[i].data, buffer + offset, length);
5432 fastload[i].length = length;
5434 image_size += length;
5435 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5436 (unsigned int)length,
5437 ((unsigned int)(image.sections[i].base_address + offset)));
5440 free(buffer);
5443 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5444 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5445 "in %fs (%0.3f KiB/s)", image_size,
5446 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5448 command_print(CMD_CTX,
5449 "WARNING: image has not been loaded to target!"
5450 "You can issue a 'fast_load' to finish loading.");
5453 image_close(&image);
5455 if (retval != ERROR_OK)
5456 free_fastload();
5458 return retval;
5461 COMMAND_HANDLER(handle_fast_load_command)
5463 if (CMD_ARGC > 0)
5464 return ERROR_COMMAND_SYNTAX_ERROR;
5465 if (fastload == NULL) {
5466 LOG_ERROR("No image in memory");
5467 return ERROR_FAIL;
5469 int i;
5470 int ms = timeval_ms();
5471 int size = 0;
5472 int retval = ERROR_OK;
5473 for (i = 0; i < fastload_num; i++) {
5474 struct target *target = get_current_target(CMD_CTX);
5475 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5476 (unsigned int)(fastload[i].address),
5477 (unsigned int)(fastload[i].length));
5478 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5479 if (retval != ERROR_OK)
5480 break;
5481 size += fastload[i].length;
5483 if (retval == ERROR_OK) {
5484 int after = timeval_ms();
5485 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5487 return retval;
5490 static const struct command_registration target_command_handlers[] = {
5492 .name = "targets",
5493 .handler = handle_targets_command,
5494 .mode = COMMAND_ANY,
5495 .help = "change current default target (one parameter) "
5496 "or prints table of all targets (no parameters)",
5497 .usage = "[target]",
5500 .name = "target",
5501 .mode = COMMAND_CONFIG,
5502 .help = "configure target",
5504 .chain = target_subcommand_handlers,
5506 COMMAND_REGISTRATION_DONE
5509 int target_register_commands(struct command_context *cmd_ctx)
5511 return register_commands(cmd_ctx, NULL, target_command_handlers);
5514 static bool target_reset_nag = true;
5516 bool get_target_reset_nag(void)
5518 return target_reset_nag;
5521 COMMAND_HANDLER(handle_target_reset_nag)
5523 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5524 &target_reset_nag, "Nag after each reset about options to improve "
5525 "performance");
5528 COMMAND_HANDLER(handle_ps_command)
5530 struct target *target = get_current_target(CMD_CTX);
5531 char *display;
5532 if (target->state != TARGET_HALTED) {
5533 LOG_INFO("target not halted !!");
5534 return ERROR_OK;
5537 if ((target->rtos) && (target->rtos->type)
5538 && (target->rtos->type->ps_command)) {
5539 display = target->rtos->type->ps_command(target);
5540 command_print(CMD_CTX, "%s", display);
5541 free(display);
5542 return ERROR_OK;
5543 } else {
5544 LOG_INFO("failed");
5545 return ERROR_TARGET_FAILURE;
5549 static const struct command_registration target_exec_command_handlers[] = {
5551 .name = "fast_load_image",
5552 .handler = handle_fast_load_image_command,
5553 .mode = COMMAND_ANY,
5554 .help = "Load image into server memory for later use by "
5555 "fast_load; primarily for profiling",
5556 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5557 "[min_address [max_length]]",
5560 .name = "fast_load",
5561 .handler = handle_fast_load_command,
5562 .mode = COMMAND_EXEC,
5563 .help = "loads active fast load image to current target "
5564 "- mainly for profiling purposes",
5565 .usage = "",
5568 .name = "profile",
5569 .handler = handle_profile_command,
5570 .mode = COMMAND_EXEC,
5571 .usage = "seconds filename",
5572 .help = "profiling samples the CPU PC",
5574 /** @todo don't register virt2phys() unless target supports it */
5576 .name = "virt2phys",
5577 .handler = handle_virt2phys_command,
5578 .mode = COMMAND_ANY,
5579 .help = "translate a virtual address into a physical address",
5580 .usage = "virtual_address",
5583 .name = "reg",
5584 .handler = handle_reg_command,
5585 .mode = COMMAND_EXEC,
5586 .help = "display or set a register; with no arguments, "
5587 "displays all registers and their values",
5588 .usage = "[(register_name|register_number) [value]]",
5591 .name = "poll",
5592 .handler = handle_poll_command,
5593 .mode = COMMAND_EXEC,
5594 .help = "poll target state; or reconfigure background polling",
5595 .usage = "['on'|'off']",
5598 .name = "wait_halt",
5599 .handler = handle_wait_halt_command,
5600 .mode = COMMAND_EXEC,
5601 .help = "wait up to the specified number of milliseconds "
5602 "(default 5000) for a previously requested halt",
5603 .usage = "[milliseconds]",
5606 .name = "halt",
5607 .handler = handle_halt_command,
5608 .mode = COMMAND_EXEC,
5609 .help = "request target to halt, then wait up to the specified"
5610 "number of milliseconds (default 5000) for it to complete",
5611 .usage = "[milliseconds]",
5614 .name = "resume",
5615 .handler = handle_resume_command,
5616 .mode = COMMAND_EXEC,
5617 .help = "resume target execution from current PC or address",
5618 .usage = "[address]",
5621 .name = "reset",
5622 .handler = handle_reset_command,
5623 .mode = COMMAND_EXEC,
5624 .usage = "[run|halt|init]",
5625 .help = "Reset all targets into the specified mode."
5626 "Default reset mode is run, if not given.",
5629 .name = "soft_reset_halt",
5630 .handler = handle_soft_reset_halt_command,
5631 .mode = COMMAND_EXEC,
5632 .usage = "",
5633 .help = "halt the target and do a soft reset",
5636 .name = "step",
5637 .handler = handle_step_command,
5638 .mode = COMMAND_EXEC,
5639 .help = "step one instruction from current PC or address",
5640 .usage = "[address]",
5643 .name = "mdw",
5644 .handler = handle_md_command,
5645 .mode = COMMAND_EXEC,
5646 .help = "display memory words",
5647 .usage = "['phys'] address [count]",
5650 .name = "mdh",
5651 .handler = handle_md_command,
5652 .mode = COMMAND_EXEC,
5653 .help = "display memory half-words",
5654 .usage = "['phys'] address [count]",
5657 .name = "mdb",
5658 .handler = handle_md_command,
5659 .mode = COMMAND_EXEC,
5660 .help = "display memory bytes",
5661 .usage = "['phys'] address [count]",
5664 .name = "mww",
5665 .handler = handle_mw_command,
5666 .mode = COMMAND_EXEC,
5667 .help = "write memory word",
5668 .usage = "['phys'] address value [count]",
5671 .name = "mwh",
5672 .handler = handle_mw_command,
5673 .mode = COMMAND_EXEC,
5674 .help = "write memory half-word",
5675 .usage = "['phys'] address value [count]",
5678 .name = "mwb",
5679 .handler = handle_mw_command,
5680 .mode = COMMAND_EXEC,
5681 .help = "write memory byte",
5682 .usage = "['phys'] address value [count]",
5685 .name = "bp",
5686 .handler = handle_bp_command,
5687 .mode = COMMAND_EXEC,
5688 .help = "list or set hardware or software breakpoint",
5689 .usage = "<address> [<asid>]<length> ['hw'|'hw_ctx']",
5692 .name = "rbp",
5693 .handler = handle_rbp_command,
5694 .mode = COMMAND_EXEC,
5695 .help = "remove breakpoint",
5696 .usage = "address",
5699 .name = "wp",
5700 .handler = handle_wp_command,
5701 .mode = COMMAND_EXEC,
5702 .help = "list (no params) or create watchpoints",
5703 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5706 .name = "rwp",
5707 .handler = handle_rwp_command,
5708 .mode = COMMAND_EXEC,
5709 .help = "remove watchpoint",
5710 .usage = "address",
5713 .name = "load_image",
5714 .handler = handle_load_image_command,
5715 .mode = COMMAND_EXEC,
5716 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5717 "[min_address] [max_length]",
5720 .name = "dump_image",
5721 .handler = handle_dump_image_command,
5722 .mode = COMMAND_EXEC,
5723 .usage = "filename address size",
5726 .name = "verify_image",
5727 .handler = handle_verify_image_command,
5728 .mode = COMMAND_EXEC,
5729 .usage = "filename [offset [type]]",
5732 .name = "test_image",
5733 .handler = handle_test_image_command,
5734 .mode = COMMAND_EXEC,
5735 .usage = "filename [offset [type]]",
5738 .name = "mem2array",
5739 .mode = COMMAND_EXEC,
5740 .jim_handler = jim_mem2array,
5741 .help = "read 8/16/32 bit memory and return as a TCL array "
5742 "for script processing",
5743 .usage = "arrayname bitwidth address count",
5746 .name = "array2mem",
5747 .mode = COMMAND_EXEC,
5748 .jim_handler = jim_array2mem,
5749 .help = "convert a TCL array to memory locations "
5750 "and write the 8/16/32 bit values",
5751 .usage = "arrayname bitwidth address count",
5754 .name = "reset_nag",
5755 .handler = handle_target_reset_nag,
5756 .mode = COMMAND_ANY,
5757 .help = "Nag after each reset about options that could have been "
5758 "enabled to improve performance. ",
5759 .usage = "['enable'|'disable']",
5762 .name = "ps",
5763 .handler = handle_ps_command,
5764 .mode = COMMAND_EXEC,
5765 .help = "list all tasks ",
5766 .usage = " ",
5769 COMMAND_REGISTRATION_DONE
5771 static int target_register_user_commands(struct command_context *cmd_ctx)
5773 int retval = ERROR_OK;
5774 retval = target_request_register_commands(cmd_ctx);
5775 if (retval != ERROR_OK)
5776 return retval;
5778 retval = trace_register_commands(cmd_ctx);
5779 if (retval != ERROR_OK)
5780 return retval;
5783 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);