stlink: remove stlink_api command
[openocd.git] / src / target / target.c
blobcb54ced5e5733ac42044b37371f498d4a55103c9
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 count, uint8_t *buffer);
64 static int target_write_buffer_default(struct target *target, uint32_t address,
65 uint32_t count, 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);
75 static int target_profiling_default(struct target *target, uint32_t *samples,
76 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds);
78 /* targets */
79 extern struct target_type arm7tdmi_target;
80 extern struct target_type arm720t_target;
81 extern struct target_type arm9tdmi_target;
82 extern struct target_type arm920t_target;
83 extern struct target_type arm966e_target;
84 extern struct target_type arm946e_target;
85 extern struct target_type arm926ejs_target;
86 extern struct target_type fa526_target;
87 extern struct target_type feroceon_target;
88 extern struct target_type dragonite_target;
89 extern struct target_type xscale_target;
90 extern struct target_type cortexm_target;
91 extern struct target_type cortexa8_target;
92 extern struct target_type cortexr4_target;
93 extern struct target_type arm11_target;
94 extern struct target_type mips_m4k_target;
95 extern struct target_type avr_target;
96 extern struct target_type dsp563xx_target;
97 extern struct target_type dsp5680xx_target;
98 extern struct target_type testee_target;
99 extern struct target_type avr32_ap7k_target;
100 extern struct target_type hla_target;
101 extern struct target_type nds32_v2_target;
102 extern struct target_type nds32_v3_target;
103 extern struct target_type nds32_v3m_target;
104 extern struct target_type or1k_target;
106 static struct target_type *target_types[] = {
107 &arm7tdmi_target,
108 &arm9tdmi_target,
109 &arm920t_target,
110 &arm720t_target,
111 &arm966e_target,
112 &arm946e_target,
113 &arm926ejs_target,
114 &fa526_target,
115 &feroceon_target,
116 &dragonite_target,
117 &xscale_target,
118 &cortexm_target,
119 &cortexa8_target,
120 &cortexr4_target,
121 &arm11_target,
122 &mips_m4k_target,
123 &avr_target,
124 &dsp563xx_target,
125 &dsp5680xx_target,
126 &testee_target,
127 &avr32_ap7k_target,
128 &hla_target,
129 &nds32_v2_target,
130 &nds32_v3_target,
131 &nds32_v3m_target,
132 &or1k_target,
133 NULL,
136 struct target *all_targets;
137 static struct target_event_callback *target_event_callbacks;
138 static struct target_timer_callback *target_timer_callbacks;
139 static const int polling_interval = 100;
141 static const Jim_Nvp nvp_assert[] = {
142 { .name = "assert", NVP_ASSERT },
143 { .name = "deassert", NVP_DEASSERT },
144 { .name = "T", NVP_ASSERT },
145 { .name = "F", NVP_DEASSERT },
146 { .name = "t", NVP_ASSERT },
147 { .name = "f", NVP_DEASSERT },
148 { .name = NULL, .value = -1 }
151 static const Jim_Nvp nvp_error_target[] = {
152 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
153 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
154 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
155 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
156 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
157 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
158 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
159 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
160 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
161 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
162 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
163 { .value = -1, .name = NULL }
166 static const char *target_strerror_safe(int err)
168 const Jim_Nvp *n;
170 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
171 if (n->name == NULL)
172 return "unknown";
173 else
174 return n->name;
177 static const Jim_Nvp nvp_target_event[] = {
179 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
180 { .value = TARGET_EVENT_HALTED, .name = "halted" },
181 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
182 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
183 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
185 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
186 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
188 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
189 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
190 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
191 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
192 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
193 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
194 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
195 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
196 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
197 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
198 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
199 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
201 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
202 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
204 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
205 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
207 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
208 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
210 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
211 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
213 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
214 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
216 { .name = NULL, .value = -1 }
219 static const Jim_Nvp nvp_target_state[] = {
220 { .name = "unknown", .value = TARGET_UNKNOWN },
221 { .name = "running", .value = TARGET_RUNNING },
222 { .name = "halted", .value = TARGET_HALTED },
223 { .name = "reset", .value = TARGET_RESET },
224 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
225 { .name = NULL, .value = -1 },
228 static const Jim_Nvp nvp_target_debug_reason[] = {
229 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
230 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
231 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
232 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
233 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
234 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
235 { .name = "program-exit" , .value = DBG_REASON_EXIT },
236 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
237 { .name = NULL, .value = -1 },
240 static const Jim_Nvp nvp_target_endian[] = {
241 { .name = "big", .value = TARGET_BIG_ENDIAN },
242 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
243 { .name = "be", .value = TARGET_BIG_ENDIAN },
244 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
245 { .name = NULL, .value = -1 },
248 static const Jim_Nvp nvp_reset_modes[] = {
249 { .name = "unknown", .value = RESET_UNKNOWN },
250 { .name = "run" , .value = RESET_RUN },
251 { .name = "halt" , .value = RESET_HALT },
252 { .name = "init" , .value = RESET_INIT },
253 { .name = NULL , .value = -1 },
256 const char *debug_reason_name(struct target *t)
258 const char *cp;
260 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
261 t->debug_reason)->name;
262 if (!cp) {
263 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
264 cp = "(*BUG*unknown*BUG*)";
266 return cp;
269 const char *target_state_name(struct target *t)
271 const char *cp;
272 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
273 if (!cp) {
274 LOG_ERROR("Invalid target state: %d", (int)(t->state));
275 cp = "(*BUG*unknown*BUG*)";
277 return cp;
280 /* determine the number of the new target */
281 static int new_target_number(void)
283 struct target *t;
284 int x;
286 /* number is 0 based */
287 x = -1;
288 t = all_targets;
289 while (t) {
290 if (x < t->target_number)
291 x = t->target_number;
292 t = t->next;
294 return x + 1;
297 /* read a uint64_t from a buffer in target memory endianness */
298 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
300 if (target->endianness == TARGET_LITTLE_ENDIAN)
301 return le_to_h_u64(buffer);
302 else
303 return be_to_h_u64(buffer);
306 /* read a uint32_t from a buffer in target memory endianness */
307 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
309 if (target->endianness == TARGET_LITTLE_ENDIAN)
310 return le_to_h_u32(buffer);
311 else
312 return be_to_h_u32(buffer);
315 /* read a uint24_t from a buffer in target memory endianness */
316 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
318 if (target->endianness == TARGET_LITTLE_ENDIAN)
319 return le_to_h_u24(buffer);
320 else
321 return be_to_h_u24(buffer);
324 /* read a uint16_t from a buffer in target memory endianness */
325 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
327 if (target->endianness == TARGET_LITTLE_ENDIAN)
328 return le_to_h_u16(buffer);
329 else
330 return be_to_h_u16(buffer);
333 /* read a uint8_t from a buffer in target memory endianness */
334 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
336 return *buffer & 0x0ff;
339 /* write a uint64_t to a buffer in target memory endianness */
340 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
342 if (target->endianness == TARGET_LITTLE_ENDIAN)
343 h_u64_to_le(buffer, value);
344 else
345 h_u64_to_be(buffer, value);
348 /* write a uint32_t to a buffer in target memory endianness */
349 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
351 if (target->endianness == TARGET_LITTLE_ENDIAN)
352 h_u32_to_le(buffer, value);
353 else
354 h_u32_to_be(buffer, value);
357 /* write a uint24_t to a buffer in target memory endianness */
358 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
360 if (target->endianness == TARGET_LITTLE_ENDIAN)
361 h_u24_to_le(buffer, value);
362 else
363 h_u24_to_be(buffer, value);
366 /* write a uint16_t to a buffer in target memory endianness */
367 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
369 if (target->endianness == TARGET_LITTLE_ENDIAN)
370 h_u16_to_le(buffer, value);
371 else
372 h_u16_to_be(buffer, value);
375 /* write a uint8_t to a buffer in target memory endianness */
376 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
378 *buffer = value;
381 /* write a uint64_t array to a buffer in target memory endianness */
382 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
384 uint32_t i;
385 for (i = 0; i < count; i++)
386 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
389 /* write a uint32_t array to a buffer in target memory endianness */
390 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
392 uint32_t i;
393 for (i = 0; i < count; i++)
394 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
397 /* write a uint16_t array to a buffer in target memory endianness */
398 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
400 uint32_t i;
401 for (i = 0; i < count; i++)
402 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
405 /* write a uint64_t array to a buffer in target memory endianness */
406 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
408 uint32_t i;
409 for (i = 0; i < count; i++)
410 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
413 /* write a uint32_t array to a buffer in target memory endianness */
414 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
416 uint32_t i;
417 for (i = 0; i < count; i++)
418 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
421 /* write a uint16_t array to a buffer in target memory endianness */
422 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
424 uint32_t i;
425 for (i = 0; i < count; i++)
426 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
429 /* return a pointer to a configured target; id is name or number */
430 struct target *get_target(const char *id)
432 struct target *target;
434 /* try as tcltarget name */
435 for (target = all_targets; target; target = target->next) {
436 if (target_name(target) == NULL)
437 continue;
438 if (strcmp(id, target_name(target)) == 0)
439 return target;
442 /* It's OK to remove this fallback sometime after August 2010 or so */
444 /* no match, try as number */
445 unsigned num;
446 if (parse_uint(id, &num) != ERROR_OK)
447 return NULL;
449 for (target = all_targets; target; target = target->next) {
450 if (target->target_number == (int)num) {
451 LOG_WARNING("use '%s' as target identifier, not '%u'",
452 target_name(target), num);
453 return target;
457 return NULL;
460 /* returns a pointer to the n-th configured target */
461 static struct target *get_target_by_num(int num)
463 struct target *target = all_targets;
465 while (target) {
466 if (target->target_number == num)
467 return target;
468 target = target->next;
471 return NULL;
474 struct target *get_current_target(struct command_context *cmd_ctx)
476 struct target *target = get_target_by_num(cmd_ctx->current_target);
478 if (target == NULL) {
479 LOG_ERROR("BUG: current_target out of bounds");
480 exit(-1);
483 return target;
486 int target_poll(struct target *target)
488 int retval;
490 /* We can't poll until after examine */
491 if (!target_was_examined(target)) {
492 /* Fail silently lest we pollute the log */
493 return ERROR_FAIL;
496 retval = target->type->poll(target);
497 if (retval != ERROR_OK)
498 return retval;
500 if (target->halt_issued) {
501 if (target->state == TARGET_HALTED)
502 target->halt_issued = false;
503 else {
504 long long t = timeval_ms() - target->halt_issued_time;
505 if (t > DEFAULT_HALT_TIMEOUT) {
506 target->halt_issued = false;
507 LOG_INFO("Halt timed out, wake up GDB.");
508 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
513 return ERROR_OK;
516 int target_halt(struct target *target)
518 int retval;
519 /* We can't poll until after examine */
520 if (!target_was_examined(target)) {
521 LOG_ERROR("Target not examined yet");
522 return ERROR_FAIL;
525 retval = target->type->halt(target);
526 if (retval != ERROR_OK)
527 return retval;
529 target->halt_issued = true;
530 target->halt_issued_time = timeval_ms();
532 return ERROR_OK;
536 * Make the target (re)start executing using its saved execution
537 * context (possibly with some modifications).
539 * @param target Which target should start executing.
540 * @param current True to use the target's saved program counter instead
541 * of the address parameter
542 * @param address Optionally used as the program counter.
543 * @param handle_breakpoints True iff breakpoints at the resumption PC
544 * should be skipped. (For example, maybe execution was stopped by
545 * such a breakpoint, in which case it would be counterprodutive to
546 * let it re-trigger.
547 * @param debug_execution False if all working areas allocated by OpenOCD
548 * should be released and/or restored to their original contents.
549 * (This would for example be true to run some downloaded "helper"
550 * algorithm code, which resides in one such working buffer and uses
551 * another for data storage.)
553 * @todo Resolve the ambiguity about what the "debug_execution" flag
554 * signifies. For example, Target implementations don't agree on how
555 * it relates to invalidation of the register cache, or to whether
556 * breakpoints and watchpoints should be enabled. (It would seem wrong
557 * to enable breakpoints when running downloaded "helper" algorithms
558 * (debug_execution true), since the breakpoints would be set to match
559 * target firmware being debugged, not the helper algorithm.... and
560 * enabling them could cause such helpers to malfunction (for example,
561 * by overwriting data with a breakpoint instruction. On the other
562 * hand the infrastructure for running such helpers might use this
563 * procedure but rely on hardware breakpoint to detect termination.)
565 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
567 int retval;
569 /* We can't poll until after examine */
570 if (!target_was_examined(target)) {
571 LOG_ERROR("Target not examined yet");
572 return ERROR_FAIL;
575 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
577 /* note that resume *must* be asynchronous. The CPU can halt before
578 * we poll. The CPU can even halt at the current PC as a result of
579 * a software breakpoint being inserted by (a bug?) the application.
581 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
582 if (retval != ERROR_OK)
583 return retval;
585 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
587 return retval;
590 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
592 char buf[100];
593 int retval;
594 Jim_Nvp *n;
595 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
596 if (n->name == NULL) {
597 LOG_ERROR("invalid reset mode");
598 return ERROR_FAIL;
601 /* disable polling during reset to make reset event scripts
602 * more predictable, i.e. dr/irscan & pathmove in events will
603 * not have JTAG operations injected into the middle of a sequence.
605 bool save_poll = jtag_poll_get_enabled();
607 jtag_poll_set_enabled(false);
609 sprintf(buf, "ocd_process_reset %s", n->name);
610 retval = Jim_Eval(cmd_ctx->interp, buf);
612 jtag_poll_set_enabled(save_poll);
614 if (retval != JIM_OK) {
615 Jim_MakeErrorMessage(cmd_ctx->interp);
616 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
617 return ERROR_FAIL;
620 /* We want any events to be processed before the prompt */
621 retval = target_call_timer_callbacks_now();
623 struct target *target;
624 for (target = all_targets; target; target = target->next) {
625 target->type->check_reset(target);
626 target->running_alg = false;
629 return retval;
632 static int identity_virt2phys(struct target *target,
633 uint32_t virtual, uint32_t *physical)
635 *physical = virtual;
636 return ERROR_OK;
639 static int no_mmu(struct target *target, int *enabled)
641 *enabled = 0;
642 return ERROR_OK;
645 static int default_examine(struct target *target)
647 target_set_examined(target);
648 return ERROR_OK;
651 /* no check by default */
652 static int default_check_reset(struct target *target)
654 return ERROR_OK;
657 int target_examine_one(struct target *target)
659 return target->type->examine(target);
662 static int jtag_enable_callback(enum jtag_event event, void *priv)
664 struct target *target = priv;
666 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
667 return ERROR_OK;
669 jtag_unregister_event_callback(jtag_enable_callback, target);
671 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
673 int retval = target_examine_one(target);
674 if (retval != ERROR_OK)
675 return retval;
677 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
679 return retval;
682 /* Targets that correctly implement init + examine, i.e.
683 * no communication with target during init:
685 * XScale
687 int target_examine(void)
689 int retval = ERROR_OK;
690 struct target *target;
692 for (target = all_targets; target; target = target->next) {
693 /* defer examination, but don't skip it */
694 if (!target->tap->enabled) {
695 jtag_register_event_callback(jtag_enable_callback,
696 target);
697 continue;
700 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
702 retval = target_examine_one(target);
703 if (retval != ERROR_OK)
704 return retval;
706 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
708 return retval;
711 const char *target_type_name(struct target *target)
713 return target->type->name;
716 static int target_soft_reset_halt(struct target *target)
718 if (!target_was_examined(target)) {
719 LOG_ERROR("Target not examined yet");
720 return ERROR_FAIL;
722 if (!target->type->soft_reset_halt) {
723 LOG_ERROR("Target %s does not support soft_reset_halt",
724 target_name(target));
725 return ERROR_FAIL;
727 return target->type->soft_reset_halt(target);
731 * Downloads a target-specific native code algorithm to the target,
732 * and executes it. * Note that some targets may need to set up, enable,
733 * and tear down a breakpoint (hard or * soft) to detect algorithm
734 * termination, while others may support lower overhead schemes where
735 * soft breakpoints embedded in the algorithm automatically terminate the
736 * algorithm.
738 * @param target used to run the algorithm
739 * @param arch_info target-specific description of the algorithm.
741 int target_run_algorithm(struct target *target,
742 int num_mem_params, struct mem_param *mem_params,
743 int num_reg_params, struct reg_param *reg_param,
744 uint32_t entry_point, uint32_t exit_point,
745 int timeout_ms, void *arch_info)
747 int retval = ERROR_FAIL;
749 if (!target_was_examined(target)) {
750 LOG_ERROR("Target not examined yet");
751 goto done;
753 if (!target->type->run_algorithm) {
754 LOG_ERROR("Target type '%s' does not support %s",
755 target_type_name(target), __func__);
756 goto done;
759 target->running_alg = true;
760 retval = target->type->run_algorithm(target,
761 num_mem_params, mem_params,
762 num_reg_params, reg_param,
763 entry_point, exit_point, timeout_ms, arch_info);
764 target->running_alg = false;
766 done:
767 return retval;
771 * Downloads a target-specific native code algorithm to the target,
772 * executes and leaves it running.
774 * @param target used to run the algorithm
775 * @param arch_info target-specific description of the algorithm.
777 int target_start_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 entry_point, uint32_t exit_point,
781 void *arch_info)
783 int retval = ERROR_FAIL;
785 if (!target_was_examined(target)) {
786 LOG_ERROR("Target not examined yet");
787 goto done;
789 if (!target->type->start_algorithm) {
790 LOG_ERROR("Target type '%s' does not support %s",
791 target_type_name(target), __func__);
792 goto done;
794 if (target->running_alg) {
795 LOG_ERROR("Target is already running an algorithm");
796 goto done;
799 target->running_alg = true;
800 retval = target->type->start_algorithm(target,
801 num_mem_params, mem_params,
802 num_reg_params, reg_params,
803 entry_point, exit_point, arch_info);
805 done:
806 return retval;
810 * Waits for an algorithm started with target_start_algorithm() to complete.
812 * @param target used to run the algorithm
813 * @param arch_info target-specific description of the algorithm.
815 int target_wait_algorithm(struct target *target,
816 int num_mem_params, struct mem_param *mem_params,
817 int num_reg_params, struct reg_param *reg_params,
818 uint32_t exit_point, int timeout_ms,
819 void *arch_info)
821 int retval = ERROR_FAIL;
823 if (!target->type->wait_algorithm) {
824 LOG_ERROR("Target type '%s' does not support %s",
825 target_type_name(target), __func__);
826 goto done;
828 if (!target->running_alg) {
829 LOG_ERROR("Target is not running an algorithm");
830 goto done;
833 retval = target->type->wait_algorithm(target,
834 num_mem_params, mem_params,
835 num_reg_params, reg_params,
836 exit_point, timeout_ms, arch_info);
837 if (retval != ERROR_TARGET_TIMEOUT)
838 target->running_alg = false;
840 done:
841 return retval;
845 * Executes a target-specific native code algorithm in the target.
846 * It differs from target_run_algorithm in that the algorithm is asynchronous.
847 * Because of this it requires an compliant algorithm:
848 * see contrib/loaders/flash/stm32f1x.S for example.
850 * @param target used to run the algorithm
853 int target_run_flash_async_algorithm(struct target *target,
854 uint8_t *buffer, uint32_t count, int block_size,
855 int num_mem_params, struct mem_param *mem_params,
856 int num_reg_params, struct reg_param *reg_params,
857 uint32_t buffer_start, uint32_t buffer_size,
858 uint32_t entry_point, uint32_t exit_point, void *arch_info)
860 int retval;
861 int timeout = 0;
863 /* Set up working area. First word is write pointer, second word is read pointer,
864 * rest is fifo data area. */
865 uint32_t wp_addr = buffer_start;
866 uint32_t rp_addr = buffer_start + 4;
867 uint32_t fifo_start_addr = buffer_start + 8;
868 uint32_t fifo_end_addr = buffer_start + buffer_size;
870 uint32_t wp = fifo_start_addr;
871 uint32_t rp = fifo_start_addr;
873 /* validate block_size is 2^n */
874 assert(!block_size || !(block_size & (block_size - 1)));
876 retval = target_write_u32(target, wp_addr, wp);
877 if (retval != ERROR_OK)
878 return retval;
879 retval = target_write_u32(target, rp_addr, rp);
880 if (retval != ERROR_OK)
881 return retval;
883 /* Start up algorithm on target and let it idle while writing the first chunk */
884 retval = target_start_algorithm(target, num_mem_params, mem_params,
885 num_reg_params, reg_params,
886 entry_point,
887 exit_point,
888 arch_info);
890 if (retval != ERROR_OK) {
891 LOG_ERROR("error starting target flash write algorithm");
892 return retval;
895 while (count > 0) {
897 retval = target_read_u32(target, rp_addr, &rp);
898 if (retval != ERROR_OK) {
899 LOG_ERROR("failed to get read pointer");
900 break;
903 LOG_DEBUG("count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32, count, wp, rp);
905 if (rp == 0) {
906 LOG_ERROR("flash write algorithm aborted by target");
907 retval = ERROR_FLASH_OPERATION_FAILED;
908 break;
911 if ((rp & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
912 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
913 break;
916 /* Count the number of bytes available in the fifo without
917 * crossing the wrap around. Make sure to not fill it completely,
918 * because that would make wp == rp and that's the empty condition. */
919 uint32_t thisrun_bytes;
920 if (rp > wp)
921 thisrun_bytes = rp - wp - block_size;
922 else if (rp > fifo_start_addr)
923 thisrun_bytes = fifo_end_addr - wp;
924 else
925 thisrun_bytes = fifo_end_addr - wp - block_size;
927 if (thisrun_bytes == 0) {
928 /* Throttle polling a bit if transfer is (much) faster than flash
929 * programming. The exact delay shouldn't matter as long as it's
930 * less than buffer size / flash speed. This is very unlikely to
931 * run when using high latency connections such as USB. */
932 alive_sleep(10);
934 /* to stop an infinite loop on some targets check and increment a timeout
935 * this issue was observed on a stellaris using the new ICDI interface */
936 if (timeout++ >= 500) {
937 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
938 return ERROR_FLASH_OPERATION_FAILED;
940 continue;
943 /* reset our timeout */
944 timeout = 0;
946 /* Limit to the amount of data we actually want to write */
947 if (thisrun_bytes > count * block_size)
948 thisrun_bytes = count * block_size;
950 /* Write data to fifo */
951 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
952 if (retval != ERROR_OK)
953 break;
955 /* Update counters and wrap write pointer */
956 buffer += thisrun_bytes;
957 count -= thisrun_bytes / block_size;
958 wp += thisrun_bytes;
959 if (wp >= fifo_end_addr)
960 wp = fifo_start_addr;
962 /* Store updated write pointer to target */
963 retval = target_write_u32(target, wp_addr, wp);
964 if (retval != ERROR_OK)
965 break;
968 if (retval != ERROR_OK) {
969 /* abort flash write algorithm on target */
970 target_write_u32(target, wp_addr, 0);
973 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
974 num_reg_params, reg_params,
975 exit_point,
976 10000,
977 arch_info);
979 if (retval2 != ERROR_OK) {
980 LOG_ERROR("error waiting for target flash write algorithm");
981 retval = retval2;
984 return retval;
987 int target_read_memory(struct target *target,
988 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
990 if (!target_was_examined(target)) {
991 LOG_ERROR("Target not examined yet");
992 return ERROR_FAIL;
994 return target->type->read_memory(target, address, size, count, buffer);
997 int target_read_phys_memory(struct target *target,
998 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1000 if (!target_was_examined(target)) {
1001 LOG_ERROR("Target not examined yet");
1002 return ERROR_FAIL;
1004 return target->type->read_phys_memory(target, address, size, count, buffer);
1007 int target_write_memory(struct target *target,
1008 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1010 if (!target_was_examined(target)) {
1011 LOG_ERROR("Target not examined yet");
1012 return ERROR_FAIL;
1014 return target->type->write_memory(target, address, size, count, buffer);
1017 int target_write_phys_memory(struct target *target,
1018 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1020 if (!target_was_examined(target)) {
1021 LOG_ERROR("Target not examined yet");
1022 return ERROR_FAIL;
1024 return target->type->write_phys_memory(target, address, size, count, buffer);
1027 int target_add_breakpoint(struct target *target,
1028 struct breakpoint *breakpoint)
1030 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1031 LOG_WARNING("target %s is not halted", target_name(target));
1032 return ERROR_TARGET_NOT_HALTED;
1034 return target->type->add_breakpoint(target, breakpoint);
1037 int target_add_context_breakpoint(struct target *target,
1038 struct breakpoint *breakpoint)
1040 if (target->state != TARGET_HALTED) {
1041 LOG_WARNING("target %s is not halted", target_name(target));
1042 return ERROR_TARGET_NOT_HALTED;
1044 return target->type->add_context_breakpoint(target, breakpoint);
1047 int target_add_hybrid_breakpoint(struct target *target,
1048 struct breakpoint *breakpoint)
1050 if (target->state != TARGET_HALTED) {
1051 LOG_WARNING("target %s is not halted", target_name(target));
1052 return ERROR_TARGET_NOT_HALTED;
1054 return target->type->add_hybrid_breakpoint(target, breakpoint);
1057 int target_remove_breakpoint(struct target *target,
1058 struct breakpoint *breakpoint)
1060 return target->type->remove_breakpoint(target, breakpoint);
1063 int target_add_watchpoint(struct target *target,
1064 struct watchpoint *watchpoint)
1066 if (target->state != TARGET_HALTED) {
1067 LOG_WARNING("target %s is not halted", target_name(target));
1068 return ERROR_TARGET_NOT_HALTED;
1070 return target->type->add_watchpoint(target, watchpoint);
1072 int target_remove_watchpoint(struct target *target,
1073 struct watchpoint *watchpoint)
1075 return target->type->remove_watchpoint(target, watchpoint);
1077 int target_hit_watchpoint(struct target *target,
1078 struct watchpoint **hit_watchpoint)
1080 if (target->state != TARGET_HALTED) {
1081 LOG_WARNING("target %s is not halted", target->cmd_name);
1082 return ERROR_TARGET_NOT_HALTED;
1085 if (target->type->hit_watchpoint == NULL) {
1086 /* For backward compatible, if hit_watchpoint is not implemented,
1087 * return ERROR_FAIL such that gdb_server will not take the nonsense
1088 * information. */
1089 return ERROR_FAIL;
1092 return target->type->hit_watchpoint(target, hit_watchpoint);
1095 int target_get_gdb_reg_list(struct target *target,
1096 struct reg **reg_list[], int *reg_list_size,
1097 enum target_register_class reg_class)
1099 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1101 int target_step(struct target *target,
1102 int current, uint32_t address, int handle_breakpoints)
1104 return target->type->step(target, current, address, handle_breakpoints);
1107 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1109 if (target->state != TARGET_HALTED) {
1110 LOG_WARNING("target %s is not halted", target->cmd_name);
1111 return ERROR_TARGET_NOT_HALTED;
1113 return target->type->get_gdb_fileio_info(target, fileio_info);
1116 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1118 if (target->state != TARGET_HALTED) {
1119 LOG_WARNING("target %s is not halted", target->cmd_name);
1120 return ERROR_TARGET_NOT_HALTED;
1122 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1125 int target_profiling(struct target *target, uint32_t *samples,
1126 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1128 if (target->state != TARGET_HALTED) {
1129 LOG_WARNING("target %s is not halted", target->cmd_name);
1130 return ERROR_TARGET_NOT_HALTED;
1132 return target->type->profiling(target, samples, max_num_samples,
1133 num_samples, seconds);
1137 * Reset the @c examined flag for the given target.
1138 * Pure paranoia -- targets are zeroed on allocation.
1140 static void target_reset_examined(struct target *target)
1142 target->examined = false;
1145 static int err_read_phys_memory(struct target *target, uint32_t address,
1146 uint32_t size, uint32_t count, uint8_t *buffer)
1148 LOG_ERROR("Not implemented: %s", __func__);
1149 return ERROR_FAIL;
1152 static int err_write_phys_memory(struct target *target, uint32_t address,
1153 uint32_t size, uint32_t count, const uint8_t *buffer)
1155 LOG_ERROR("Not implemented: %s", __func__);
1156 return ERROR_FAIL;
1159 static int handle_target(void *priv);
1161 static int target_init_one(struct command_context *cmd_ctx,
1162 struct target *target)
1164 target_reset_examined(target);
1166 struct target_type *type = target->type;
1167 if (type->examine == NULL)
1168 type->examine = default_examine;
1170 if (type->check_reset == NULL)
1171 type->check_reset = default_check_reset;
1173 assert(type->init_target != NULL);
1175 int retval = type->init_target(cmd_ctx, target);
1176 if (ERROR_OK != retval) {
1177 LOG_ERROR("target '%s' init failed", target_name(target));
1178 return retval;
1181 /* Sanity-check MMU support ... stub in what we must, to help
1182 * implement it in stages, but warn if we need to do so.
1184 if (type->mmu) {
1185 if (type->write_phys_memory == NULL) {
1186 LOG_ERROR("type '%s' is missing write_phys_memory",
1187 type->name);
1188 type->write_phys_memory = err_write_phys_memory;
1190 if (type->read_phys_memory == NULL) {
1191 LOG_ERROR("type '%s' is missing read_phys_memory",
1192 type->name);
1193 type->read_phys_memory = err_read_phys_memory;
1195 if (type->virt2phys == NULL) {
1196 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1197 type->virt2phys = identity_virt2phys;
1199 } else {
1200 /* Make sure no-MMU targets all behave the same: make no
1201 * distinction between physical and virtual addresses, and
1202 * ensure that virt2phys() is always an identity mapping.
1204 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1205 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1207 type->mmu = no_mmu;
1208 type->write_phys_memory = type->write_memory;
1209 type->read_phys_memory = type->read_memory;
1210 type->virt2phys = identity_virt2phys;
1213 if (target->type->read_buffer == NULL)
1214 target->type->read_buffer = target_read_buffer_default;
1216 if (target->type->write_buffer == NULL)
1217 target->type->write_buffer = target_write_buffer_default;
1219 if (target->type->get_gdb_fileio_info == NULL)
1220 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1222 if (target->type->gdb_fileio_end == NULL)
1223 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1225 if (target->type->profiling == NULL)
1226 target->type->profiling = target_profiling_default;
1228 return ERROR_OK;
1231 static int target_init(struct command_context *cmd_ctx)
1233 struct target *target;
1234 int retval;
1236 for (target = all_targets; target; target = target->next) {
1237 retval = target_init_one(cmd_ctx, target);
1238 if (ERROR_OK != retval)
1239 return retval;
1242 if (!all_targets)
1243 return ERROR_OK;
1245 retval = target_register_user_commands(cmd_ctx);
1246 if (ERROR_OK != retval)
1247 return retval;
1249 retval = target_register_timer_callback(&handle_target,
1250 polling_interval, 1, cmd_ctx->interp);
1251 if (ERROR_OK != retval)
1252 return retval;
1254 return ERROR_OK;
1257 COMMAND_HANDLER(handle_target_init_command)
1259 int retval;
1261 if (CMD_ARGC != 0)
1262 return ERROR_COMMAND_SYNTAX_ERROR;
1264 static bool target_initialized;
1265 if (target_initialized) {
1266 LOG_INFO("'target init' has already been called");
1267 return ERROR_OK;
1269 target_initialized = true;
1271 retval = command_run_line(CMD_CTX, "init_targets");
1272 if (ERROR_OK != retval)
1273 return retval;
1275 retval = command_run_line(CMD_CTX, "init_board");
1276 if (ERROR_OK != retval)
1277 return retval;
1279 LOG_DEBUG("Initializing targets...");
1280 return target_init(CMD_CTX);
1283 int target_register_event_callback(int (*callback)(struct target *target,
1284 enum target_event event, void *priv), void *priv)
1286 struct target_event_callback **callbacks_p = &target_event_callbacks;
1288 if (callback == NULL)
1289 return ERROR_COMMAND_SYNTAX_ERROR;
1291 if (*callbacks_p) {
1292 while ((*callbacks_p)->next)
1293 callbacks_p = &((*callbacks_p)->next);
1294 callbacks_p = &((*callbacks_p)->next);
1297 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1298 (*callbacks_p)->callback = callback;
1299 (*callbacks_p)->priv = priv;
1300 (*callbacks_p)->next = NULL;
1302 return ERROR_OK;
1305 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1307 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1308 struct timeval now;
1310 if (callback == NULL)
1311 return ERROR_COMMAND_SYNTAX_ERROR;
1313 if (*callbacks_p) {
1314 while ((*callbacks_p)->next)
1315 callbacks_p = &((*callbacks_p)->next);
1316 callbacks_p = &((*callbacks_p)->next);
1319 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1320 (*callbacks_p)->callback = callback;
1321 (*callbacks_p)->periodic = periodic;
1322 (*callbacks_p)->time_ms = time_ms;
1324 gettimeofday(&now, NULL);
1325 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
1326 time_ms -= (time_ms % 1000);
1327 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
1328 if ((*callbacks_p)->when.tv_usec > 1000000) {
1329 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
1330 (*callbacks_p)->when.tv_sec += 1;
1333 (*callbacks_p)->priv = priv;
1334 (*callbacks_p)->next = NULL;
1336 return ERROR_OK;
1339 int target_unregister_event_callback(int (*callback)(struct target *target,
1340 enum target_event event, void *priv), void *priv)
1342 struct target_event_callback **p = &target_event_callbacks;
1343 struct target_event_callback *c = target_event_callbacks;
1345 if (callback == NULL)
1346 return ERROR_COMMAND_SYNTAX_ERROR;
1348 while (c) {
1349 struct target_event_callback *next = c->next;
1350 if ((c->callback == callback) && (c->priv == priv)) {
1351 *p = next;
1352 free(c);
1353 return ERROR_OK;
1354 } else
1355 p = &(c->next);
1356 c = next;
1359 return ERROR_OK;
1362 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1364 struct target_timer_callback **p = &target_timer_callbacks;
1365 struct target_timer_callback *c = target_timer_callbacks;
1367 if (callback == NULL)
1368 return ERROR_COMMAND_SYNTAX_ERROR;
1370 while (c) {
1371 struct target_timer_callback *next = c->next;
1372 if ((c->callback == callback) && (c->priv == priv)) {
1373 *p = next;
1374 free(c);
1375 return ERROR_OK;
1376 } else
1377 p = &(c->next);
1378 c = next;
1381 return ERROR_OK;
1384 int target_call_event_callbacks(struct target *target, enum target_event event)
1386 struct target_event_callback *callback = target_event_callbacks;
1387 struct target_event_callback *next_callback;
1389 if (event == TARGET_EVENT_HALTED) {
1390 /* execute early halted first */
1391 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1394 LOG_DEBUG("target event %i (%s)", event,
1395 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1397 target_handle_event(target, event);
1399 while (callback) {
1400 next_callback = callback->next;
1401 callback->callback(target, event, callback->priv);
1402 callback = next_callback;
1405 return ERROR_OK;
1408 static int target_timer_callback_periodic_restart(
1409 struct target_timer_callback *cb, struct timeval *now)
1411 int time_ms = cb->time_ms;
1412 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1413 time_ms -= (time_ms % 1000);
1414 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1415 if (cb->when.tv_usec > 1000000) {
1416 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1417 cb->when.tv_sec += 1;
1419 return ERROR_OK;
1422 static int target_call_timer_callback(struct target_timer_callback *cb,
1423 struct timeval *now)
1425 cb->callback(cb->priv);
1427 if (cb->periodic)
1428 return target_timer_callback_periodic_restart(cb, now);
1430 return target_unregister_timer_callback(cb->callback, cb->priv);
1433 static int target_call_timer_callbacks_check_time(int checktime)
1435 keep_alive();
1437 struct timeval now;
1438 gettimeofday(&now, NULL);
1440 struct target_timer_callback *callback = target_timer_callbacks;
1441 while (callback) {
1442 /* cleaning up may unregister and free this callback */
1443 struct target_timer_callback *next_callback = callback->next;
1445 bool call_it = callback->callback &&
1446 ((!checktime && callback->periodic) ||
1447 now.tv_sec > callback->when.tv_sec ||
1448 (now.tv_sec == callback->when.tv_sec &&
1449 now.tv_usec >= callback->when.tv_usec));
1451 if (call_it) {
1452 int retval = target_call_timer_callback(callback, &now);
1453 if (retval != ERROR_OK)
1454 return retval;
1457 callback = next_callback;
1460 return ERROR_OK;
1463 int target_call_timer_callbacks(void)
1465 return target_call_timer_callbacks_check_time(1);
1468 /* invoke periodic callbacks immediately */
1469 int target_call_timer_callbacks_now(void)
1471 return target_call_timer_callbacks_check_time(0);
1474 /* Prints the working area layout for debug purposes */
1475 static void print_wa_layout(struct target *target)
1477 struct working_area *c = target->working_areas;
1479 while (c) {
1480 LOG_DEBUG("%c%c 0x%08"PRIx32"-0x%08"PRIx32" (%"PRIu32" bytes)",
1481 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1482 c->address, c->address + c->size - 1, c->size);
1483 c = c->next;
1487 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1488 static void target_split_working_area(struct working_area *area, uint32_t size)
1490 assert(area->free); /* Shouldn't split an allocated area */
1491 assert(size <= area->size); /* Caller should guarantee this */
1493 /* Split only if not already the right size */
1494 if (size < area->size) {
1495 struct working_area *new_wa = malloc(sizeof(*new_wa));
1497 if (new_wa == NULL)
1498 return;
1500 new_wa->next = area->next;
1501 new_wa->size = area->size - size;
1502 new_wa->address = area->address + size;
1503 new_wa->backup = NULL;
1504 new_wa->user = NULL;
1505 new_wa->free = true;
1507 area->next = new_wa;
1508 area->size = size;
1510 /* If backup memory was allocated to this area, it has the wrong size
1511 * now so free it and it will be reallocated if/when needed */
1512 if (area->backup) {
1513 free(area->backup);
1514 area->backup = NULL;
1519 /* Merge all adjacent free areas into one */
1520 static void target_merge_working_areas(struct target *target)
1522 struct working_area *c = target->working_areas;
1524 while (c && c->next) {
1525 assert(c->next->address == c->address + c->size); /* This is an invariant */
1527 /* Find two adjacent free areas */
1528 if (c->free && c->next->free) {
1529 /* Merge the last into the first */
1530 c->size += c->next->size;
1532 /* Remove the last */
1533 struct working_area *to_be_freed = c->next;
1534 c->next = c->next->next;
1535 if (to_be_freed->backup)
1536 free(to_be_freed->backup);
1537 free(to_be_freed);
1539 /* If backup memory was allocated to the remaining area, it's has
1540 * the wrong size now */
1541 if (c->backup) {
1542 free(c->backup);
1543 c->backup = NULL;
1545 } else {
1546 c = c->next;
1551 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1553 /* Reevaluate working area address based on MMU state*/
1554 if (target->working_areas == NULL) {
1555 int retval;
1556 int enabled;
1558 retval = target->type->mmu(target, &enabled);
1559 if (retval != ERROR_OK)
1560 return retval;
1562 if (!enabled) {
1563 if (target->working_area_phys_spec) {
1564 LOG_DEBUG("MMU disabled, using physical "
1565 "address for working memory 0x%08"PRIx32,
1566 target->working_area_phys);
1567 target->working_area = target->working_area_phys;
1568 } else {
1569 LOG_ERROR("No working memory available. "
1570 "Specify -work-area-phys to target.");
1571 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1573 } else {
1574 if (target->working_area_virt_spec) {
1575 LOG_DEBUG("MMU enabled, using virtual "
1576 "address for working memory 0x%08"PRIx32,
1577 target->working_area_virt);
1578 target->working_area = target->working_area_virt;
1579 } else {
1580 LOG_ERROR("No working memory available. "
1581 "Specify -work-area-virt to target.");
1582 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1586 /* Set up initial working area on first call */
1587 struct working_area *new_wa = malloc(sizeof(*new_wa));
1588 if (new_wa) {
1589 new_wa->next = NULL;
1590 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1591 new_wa->address = target->working_area;
1592 new_wa->backup = NULL;
1593 new_wa->user = NULL;
1594 new_wa->free = true;
1597 target->working_areas = new_wa;
1600 /* only allocate multiples of 4 byte */
1601 if (size % 4)
1602 size = (size + 3) & (~3UL);
1604 struct working_area *c = target->working_areas;
1606 /* Find the first large enough working area */
1607 while (c) {
1608 if (c->free && c->size >= size)
1609 break;
1610 c = c->next;
1613 if (c == NULL)
1614 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1616 /* Split the working area into the requested size */
1617 target_split_working_area(c, size);
1619 LOG_DEBUG("allocated new working area of %"PRIu32" bytes at address 0x%08"PRIx32, size, c->address);
1621 if (target->backup_working_area) {
1622 if (c->backup == NULL) {
1623 c->backup = malloc(c->size);
1624 if (c->backup == NULL)
1625 return ERROR_FAIL;
1628 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1629 if (retval != ERROR_OK)
1630 return retval;
1633 /* mark as used, and return the new (reused) area */
1634 c->free = false;
1635 *area = c;
1637 /* user pointer */
1638 c->user = area;
1640 print_wa_layout(target);
1642 return ERROR_OK;
1645 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1647 int retval;
1649 retval = target_alloc_working_area_try(target, size, area);
1650 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1651 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1652 return retval;
1656 static int target_restore_working_area(struct target *target, struct working_area *area)
1658 int retval = ERROR_OK;
1660 if (target->backup_working_area && area->backup != NULL) {
1661 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1662 if (retval != ERROR_OK)
1663 LOG_ERROR("failed to restore %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1664 area->size, area->address);
1667 return retval;
1670 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1671 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1673 int retval = ERROR_OK;
1675 if (area->free)
1676 return retval;
1678 if (restore) {
1679 retval = target_restore_working_area(target, area);
1680 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1681 if (retval != ERROR_OK)
1682 return retval;
1685 area->free = true;
1687 LOG_DEBUG("freed %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1688 area->size, area->address);
1690 /* mark user pointer invalid */
1691 /* TODO: Is this really safe? It points to some previous caller's memory.
1692 * How could we know that the area pointer is still in that place and not
1693 * some other vital data? What's the purpose of this, anyway? */
1694 *area->user = NULL;
1695 area->user = NULL;
1697 target_merge_working_areas(target);
1699 print_wa_layout(target);
1701 return retval;
1704 int target_free_working_area(struct target *target, struct working_area *area)
1706 return target_free_working_area_restore(target, area, 1);
1709 /* free resources and restore memory, if restoring memory fails,
1710 * free up resources anyway
1712 static void target_free_all_working_areas_restore(struct target *target, int restore)
1714 struct working_area *c = target->working_areas;
1716 LOG_DEBUG("freeing all working areas");
1718 /* Loop through all areas, restoring the allocated ones and marking them as free */
1719 while (c) {
1720 if (!c->free) {
1721 if (restore)
1722 target_restore_working_area(target, c);
1723 c->free = true;
1724 *c->user = NULL; /* Same as above */
1725 c->user = NULL;
1727 c = c->next;
1730 /* Run a merge pass to combine all areas into one */
1731 target_merge_working_areas(target);
1733 print_wa_layout(target);
1736 void target_free_all_working_areas(struct target *target)
1738 target_free_all_working_areas_restore(target, 1);
1741 /* Find the largest number of bytes that can be allocated */
1742 uint32_t target_get_working_area_avail(struct target *target)
1744 struct working_area *c = target->working_areas;
1745 uint32_t max_size = 0;
1747 if (c == NULL)
1748 return target->working_area_size;
1750 while (c) {
1751 if (c->free && max_size < c->size)
1752 max_size = c->size;
1754 c = c->next;
1757 return max_size;
1760 int target_arch_state(struct target *target)
1762 int retval;
1763 if (target == NULL) {
1764 LOG_USER("No target has been configured");
1765 return ERROR_OK;
1768 LOG_USER("target state: %s", target_state_name(target));
1770 if (target->state != TARGET_HALTED)
1771 return ERROR_OK;
1773 retval = target->type->arch_state(target);
1774 return retval;
1777 static int target_get_gdb_fileio_info_default(struct target *target,
1778 struct gdb_fileio_info *fileio_info)
1780 /* If target does not support semi-hosting function, target
1781 has no need to provide .get_gdb_fileio_info callback.
1782 It just return ERROR_FAIL and gdb_server will return "Txx"
1783 as target halted every time. */
1784 return ERROR_FAIL;
1787 static int target_gdb_fileio_end_default(struct target *target,
1788 int retcode, int fileio_errno, bool ctrl_c)
1790 return ERROR_OK;
1793 static int target_profiling_default(struct target *target, uint32_t *samples,
1794 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1796 struct timeval timeout, now;
1798 gettimeofday(&timeout, NULL);
1799 timeval_add_time(&timeout, seconds, 0);
1801 LOG_INFO("Starting profiling. Halting and resuming the"
1802 " target as often as we can...");
1804 uint32_t sample_count = 0;
1805 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
1806 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
1808 int retval = ERROR_OK;
1809 for (;;) {
1810 target_poll(target);
1811 if (target->state == TARGET_HALTED) {
1812 uint32_t t = *((uint32_t *)reg->value);
1813 samples[sample_count++] = t;
1814 /* current pc, addr = 0, do not handle breakpoints, not debugging */
1815 retval = target_resume(target, 1, 0, 0, 0);
1816 target_poll(target);
1817 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
1818 } else if (target->state == TARGET_RUNNING) {
1819 /* We want to quickly sample the PC. */
1820 retval = target_halt(target);
1821 } else {
1822 LOG_INFO("Target not halted or running");
1823 retval = ERROR_OK;
1824 break;
1827 if (retval != ERROR_OK)
1828 break;
1830 gettimeofday(&now, NULL);
1831 if ((sample_count >= max_num_samples) ||
1832 ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec))) {
1833 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
1834 break;
1838 *num_samples = sample_count;
1839 return retval;
1842 /* Single aligned words are guaranteed to use 16 or 32 bit access
1843 * mode respectively, otherwise data is handled as quickly as
1844 * possible
1846 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1848 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1849 (int)size, (unsigned)address);
1851 if (!target_was_examined(target)) {
1852 LOG_ERROR("Target not examined yet");
1853 return ERROR_FAIL;
1856 if (size == 0)
1857 return ERROR_OK;
1859 if ((address + size - 1) < address) {
1860 /* GDB can request this when e.g. PC is 0xfffffffc*/
1861 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1862 (unsigned)address,
1863 (unsigned)size);
1864 return ERROR_FAIL;
1867 return target->type->write_buffer(target, address, size, buffer);
1870 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t count, const uint8_t *buffer)
1872 uint32_t size;
1874 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
1875 * will have something to do with the size we leave to it. */
1876 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
1877 if (address & size) {
1878 int retval = target_write_memory(target, address, size, 1, buffer);
1879 if (retval != ERROR_OK)
1880 return retval;
1881 address += size;
1882 count -= size;
1883 buffer += size;
1887 /* Write the data with as large access size as possible. */
1888 for (; size > 0; size /= 2) {
1889 uint32_t aligned = count - count % size;
1890 if (aligned > 0) {
1891 int retval = target_write_memory(target, address, size, aligned / size, buffer);
1892 if (retval != ERROR_OK)
1893 return retval;
1894 address += aligned;
1895 count -= aligned;
1896 buffer += aligned;
1900 return ERROR_OK;
1903 /* Single aligned words are guaranteed to use 16 or 32 bit access
1904 * mode respectively, otherwise data is handled as quickly as
1905 * possible
1907 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1909 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1910 (int)size, (unsigned)address);
1912 if (!target_was_examined(target)) {
1913 LOG_ERROR("Target not examined yet");
1914 return ERROR_FAIL;
1917 if (size == 0)
1918 return ERROR_OK;
1920 if ((address + size - 1) < address) {
1921 /* GDB can request this when e.g. PC is 0xfffffffc*/
1922 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1923 address,
1924 size);
1925 return ERROR_FAIL;
1928 return target->type->read_buffer(target, address, size, buffer);
1931 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t count, uint8_t *buffer)
1933 uint32_t size;
1935 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
1936 * will have something to do with the size we leave to it. */
1937 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
1938 if (address & size) {
1939 int retval = target_read_memory(target, address, size, 1, buffer);
1940 if (retval != ERROR_OK)
1941 return retval;
1942 address += size;
1943 count -= size;
1944 buffer += size;
1948 /* Read the data with as large access size as possible. */
1949 for (; size > 0; size /= 2) {
1950 uint32_t aligned = count - count % size;
1951 if (aligned > 0) {
1952 int retval = target_read_memory(target, address, size, aligned / size, buffer);
1953 if (retval != ERROR_OK)
1954 return retval;
1955 address += aligned;
1956 count -= aligned;
1957 buffer += aligned;
1961 return ERROR_OK;
1964 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1966 uint8_t *buffer;
1967 int retval;
1968 uint32_t i;
1969 uint32_t checksum = 0;
1970 if (!target_was_examined(target)) {
1971 LOG_ERROR("Target not examined yet");
1972 return ERROR_FAIL;
1975 retval = target->type->checksum_memory(target, address, size, &checksum);
1976 if (retval != ERROR_OK) {
1977 buffer = malloc(size);
1978 if (buffer == NULL) {
1979 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1980 return ERROR_COMMAND_SYNTAX_ERROR;
1982 retval = target_read_buffer(target, address, size, buffer);
1983 if (retval != ERROR_OK) {
1984 free(buffer);
1985 return retval;
1988 /* convert to target endianness */
1989 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
1990 uint32_t target_data;
1991 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1992 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1995 retval = image_calculate_checksum(buffer, size, &checksum);
1996 free(buffer);
1999 *crc = checksum;
2001 return retval;
2004 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
2006 int retval;
2007 if (!target_was_examined(target)) {
2008 LOG_ERROR("Target not examined yet");
2009 return ERROR_FAIL;
2012 if (target->type->blank_check_memory == 0)
2013 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2015 retval = target->type->blank_check_memory(target, address, size, blank);
2017 return retval;
2020 int target_read_u64(struct target *target, uint64_t address, uint64_t *value)
2022 uint8_t value_buf[8];
2023 if (!target_was_examined(target)) {
2024 LOG_ERROR("Target not examined yet");
2025 return ERROR_FAIL;
2028 int retval = target_read_memory(target, address, 8, 1, value_buf);
2030 if (retval == ERROR_OK) {
2031 *value = target_buffer_get_u64(target, value_buf);
2032 LOG_DEBUG("address: 0x%" PRIx64 ", value: 0x%16.16" PRIx64 "",
2033 address,
2034 *value);
2035 } else {
2036 *value = 0x0;
2037 LOG_DEBUG("address: 0x%" PRIx64 " failed",
2038 address);
2041 return retval;
2044 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
2046 uint8_t value_buf[4];
2047 if (!target_was_examined(target)) {
2048 LOG_ERROR("Target not examined yet");
2049 return ERROR_FAIL;
2052 int retval = target_read_memory(target, address, 4, 1, value_buf);
2054 if (retval == ERROR_OK) {
2055 *value = target_buffer_get_u32(target, value_buf);
2056 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2057 address,
2058 *value);
2059 } else {
2060 *value = 0x0;
2061 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2062 address);
2065 return retval;
2068 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
2070 uint8_t value_buf[2];
2071 if (!target_was_examined(target)) {
2072 LOG_ERROR("Target not examined yet");
2073 return ERROR_FAIL;
2076 int retval = target_read_memory(target, address, 2, 1, value_buf);
2078 if (retval == ERROR_OK) {
2079 *value = target_buffer_get_u16(target, value_buf);
2080 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
2081 address,
2082 *value);
2083 } else {
2084 *value = 0x0;
2085 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2086 address);
2089 return retval;
2092 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
2094 if (!target_was_examined(target)) {
2095 LOG_ERROR("Target not examined yet");
2096 return ERROR_FAIL;
2099 int retval = target_read_memory(target, address, 1, 1, value);
2101 if (retval == ERROR_OK) {
2102 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2103 address,
2104 *value);
2105 } else {
2106 *value = 0x0;
2107 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2108 address);
2111 return retval;
2114 int target_write_u64(struct target *target, uint64_t address, uint64_t value)
2116 int retval;
2117 uint8_t value_buf[8];
2118 if (!target_was_examined(target)) {
2119 LOG_ERROR("Target not examined yet");
2120 return ERROR_FAIL;
2123 LOG_DEBUG("address: 0x%" PRIx64 ", value: 0x%16.16" PRIx64 "",
2124 address,
2125 value);
2127 target_buffer_set_u64(target, value_buf, value);
2128 retval = target_write_memory(target, address, 8, 1, value_buf);
2129 if (retval != ERROR_OK)
2130 LOG_DEBUG("failed: %i", retval);
2132 return retval;
2135 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
2137 int retval;
2138 uint8_t value_buf[4];
2139 if (!target_was_examined(target)) {
2140 LOG_ERROR("Target not examined yet");
2141 return ERROR_FAIL;
2144 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2145 address,
2146 value);
2148 target_buffer_set_u32(target, value_buf, value);
2149 retval = target_write_memory(target, address, 4, 1, value_buf);
2150 if (retval != ERROR_OK)
2151 LOG_DEBUG("failed: %i", retval);
2153 return retval;
2156 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
2158 int retval;
2159 uint8_t value_buf[2];
2160 if (!target_was_examined(target)) {
2161 LOG_ERROR("Target not examined yet");
2162 return ERROR_FAIL;
2165 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
2166 address,
2167 value);
2169 target_buffer_set_u16(target, value_buf, value);
2170 retval = target_write_memory(target, address, 2, 1, value_buf);
2171 if (retval != ERROR_OK)
2172 LOG_DEBUG("failed: %i", retval);
2174 return retval;
2177 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
2179 int retval;
2180 if (!target_was_examined(target)) {
2181 LOG_ERROR("Target not examined yet");
2182 return ERROR_FAIL;
2185 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2186 address, value);
2188 retval = target_write_memory(target, address, 1, 1, &value);
2189 if (retval != ERROR_OK)
2190 LOG_DEBUG("failed: %i", retval);
2192 return retval;
2195 static int find_target(struct command_context *cmd_ctx, const char *name)
2197 struct target *target = get_target(name);
2198 if (target == NULL) {
2199 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2200 return ERROR_FAIL;
2202 if (!target->tap->enabled) {
2203 LOG_USER("Target: TAP %s is disabled, "
2204 "can't be the current target\n",
2205 target->tap->dotted_name);
2206 return ERROR_FAIL;
2209 cmd_ctx->current_target = target->target_number;
2210 return ERROR_OK;
2214 COMMAND_HANDLER(handle_targets_command)
2216 int retval = ERROR_OK;
2217 if (CMD_ARGC == 1) {
2218 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2219 if (retval == ERROR_OK) {
2220 /* we're done! */
2221 return retval;
2225 struct target *target = all_targets;
2226 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2227 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2228 while (target) {
2229 const char *state;
2230 char marker = ' ';
2232 if (target->tap->enabled)
2233 state = target_state_name(target);
2234 else
2235 state = "tap-disabled";
2237 if (CMD_CTX->current_target == target->target_number)
2238 marker = '*';
2240 /* keep columns lined up to match the headers above */
2241 command_print(CMD_CTX,
2242 "%2d%c %-18s %-10s %-6s %-18s %s",
2243 target->target_number,
2244 marker,
2245 target_name(target),
2246 target_type_name(target),
2247 Jim_Nvp_value2name_simple(nvp_target_endian,
2248 target->endianness)->name,
2249 target->tap->dotted_name,
2250 state);
2251 target = target->next;
2254 return retval;
2257 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2259 static int powerDropout;
2260 static int srstAsserted;
2262 static int runPowerRestore;
2263 static int runPowerDropout;
2264 static int runSrstAsserted;
2265 static int runSrstDeasserted;
2267 static int sense_handler(void)
2269 static int prevSrstAsserted;
2270 static int prevPowerdropout;
2272 int retval = jtag_power_dropout(&powerDropout);
2273 if (retval != ERROR_OK)
2274 return retval;
2276 int powerRestored;
2277 powerRestored = prevPowerdropout && !powerDropout;
2278 if (powerRestored)
2279 runPowerRestore = 1;
2281 long long current = timeval_ms();
2282 static long long lastPower;
2283 int waitMore = lastPower + 2000 > current;
2284 if (powerDropout && !waitMore) {
2285 runPowerDropout = 1;
2286 lastPower = current;
2289 retval = jtag_srst_asserted(&srstAsserted);
2290 if (retval != ERROR_OK)
2291 return retval;
2293 int srstDeasserted;
2294 srstDeasserted = prevSrstAsserted && !srstAsserted;
2296 static long long lastSrst;
2297 waitMore = lastSrst + 2000 > current;
2298 if (srstDeasserted && !waitMore) {
2299 runSrstDeasserted = 1;
2300 lastSrst = current;
2303 if (!prevSrstAsserted && srstAsserted)
2304 runSrstAsserted = 1;
2306 prevSrstAsserted = srstAsserted;
2307 prevPowerdropout = powerDropout;
2309 if (srstDeasserted || powerRestored) {
2310 /* Other than logging the event we can't do anything here.
2311 * Issuing a reset is a particularly bad idea as we might
2312 * be inside a reset already.
2316 return ERROR_OK;
2319 /* process target state changes */
2320 static int handle_target(void *priv)
2322 Jim_Interp *interp = (Jim_Interp *)priv;
2323 int retval = ERROR_OK;
2325 if (!is_jtag_poll_safe()) {
2326 /* polling is disabled currently */
2327 return ERROR_OK;
2330 /* we do not want to recurse here... */
2331 static int recursive;
2332 if (!recursive) {
2333 recursive = 1;
2334 sense_handler();
2335 /* danger! running these procedures can trigger srst assertions and power dropouts.
2336 * We need to avoid an infinite loop/recursion here and we do that by
2337 * clearing the flags after running these events.
2339 int did_something = 0;
2340 if (runSrstAsserted) {
2341 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2342 Jim_Eval(interp, "srst_asserted");
2343 did_something = 1;
2345 if (runSrstDeasserted) {
2346 Jim_Eval(interp, "srst_deasserted");
2347 did_something = 1;
2349 if (runPowerDropout) {
2350 LOG_INFO("Power dropout detected, running power_dropout proc.");
2351 Jim_Eval(interp, "power_dropout");
2352 did_something = 1;
2354 if (runPowerRestore) {
2355 Jim_Eval(interp, "power_restore");
2356 did_something = 1;
2359 if (did_something) {
2360 /* clear detect flags */
2361 sense_handler();
2364 /* clear action flags */
2366 runSrstAsserted = 0;
2367 runSrstDeasserted = 0;
2368 runPowerRestore = 0;
2369 runPowerDropout = 0;
2371 recursive = 0;
2374 /* Poll targets for state changes unless that's globally disabled.
2375 * Skip targets that are currently disabled.
2377 for (struct target *target = all_targets;
2378 is_jtag_poll_safe() && target;
2379 target = target->next) {
2380 if (!target->tap->enabled)
2381 continue;
2383 if (target->backoff.times > target->backoff.count) {
2384 /* do not poll this time as we failed previously */
2385 target->backoff.count++;
2386 continue;
2388 target->backoff.count = 0;
2390 /* only poll target if we've got power and srst isn't asserted */
2391 if (!powerDropout && !srstAsserted) {
2392 /* polling may fail silently until the target has been examined */
2393 retval = target_poll(target);
2394 if (retval != ERROR_OK) {
2395 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2396 if (target->backoff.times * polling_interval < 5000) {
2397 target->backoff.times *= 2;
2398 target->backoff.times++;
2400 LOG_USER("Polling target %s failed, GDB will be halted. Polling again in %dms",
2401 target_name(target),
2402 target->backoff.times * polling_interval);
2404 /* Tell GDB to halt the debugger. This allows the user to
2405 * run monitor commands to handle the situation.
2407 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2408 return retval;
2410 /* Since we succeeded, we reset backoff count */
2411 if (target->backoff.times > 0)
2412 LOG_USER("Polling target %s succeeded again", target_name(target));
2413 target->backoff.times = 0;
2417 return retval;
2420 COMMAND_HANDLER(handle_reg_command)
2422 struct target *target;
2423 struct reg *reg = NULL;
2424 unsigned count = 0;
2425 char *value;
2427 LOG_DEBUG("-");
2429 target = get_current_target(CMD_CTX);
2431 /* list all available registers for the current target */
2432 if (CMD_ARGC == 0) {
2433 struct reg_cache *cache = target->reg_cache;
2435 count = 0;
2436 while (cache) {
2437 unsigned i;
2439 command_print(CMD_CTX, "===== %s", cache->name);
2441 for (i = 0, reg = cache->reg_list;
2442 i < cache->num_regs;
2443 i++, reg++, count++) {
2444 /* only print cached values if they are valid */
2445 if (reg->valid) {
2446 value = buf_to_str(reg->value,
2447 reg->size, 16);
2448 command_print(CMD_CTX,
2449 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2450 count, reg->name,
2451 reg->size, value,
2452 reg->dirty
2453 ? " (dirty)"
2454 : "");
2455 free(value);
2456 } else {
2457 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2458 count, reg->name,
2459 reg->size) ;
2462 cache = cache->next;
2465 return ERROR_OK;
2468 /* access a single register by its ordinal number */
2469 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2470 unsigned num;
2471 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2473 struct reg_cache *cache = target->reg_cache;
2474 count = 0;
2475 while (cache) {
2476 unsigned i;
2477 for (i = 0; i < cache->num_regs; i++) {
2478 if (count++ == num) {
2479 reg = &cache->reg_list[i];
2480 break;
2483 if (reg)
2484 break;
2485 cache = cache->next;
2488 if (!reg) {
2489 command_print(CMD_CTX, "%i is out of bounds, the current target "
2490 "has only %i registers (0 - %i)", num, count, count - 1);
2491 return ERROR_OK;
2493 } else {
2494 /* access a single register by its name */
2495 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2497 if (!reg) {
2498 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2499 return ERROR_OK;
2503 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2505 /* display a register */
2506 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2507 && (CMD_ARGV[1][0] <= '9')))) {
2508 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2509 reg->valid = 0;
2511 if (reg->valid == 0)
2512 reg->type->get(reg);
2513 value = buf_to_str(reg->value, reg->size, 16);
2514 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2515 free(value);
2516 return ERROR_OK;
2519 /* set register value */
2520 if (CMD_ARGC == 2) {
2521 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2522 if (buf == NULL)
2523 return ERROR_FAIL;
2524 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2526 reg->type->set(reg, buf);
2528 value = buf_to_str(reg->value, reg->size, 16);
2529 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2530 free(value);
2532 free(buf);
2534 return ERROR_OK;
2537 return ERROR_COMMAND_SYNTAX_ERROR;
2540 COMMAND_HANDLER(handle_poll_command)
2542 int retval = ERROR_OK;
2543 struct target *target = get_current_target(CMD_CTX);
2545 if (CMD_ARGC == 0) {
2546 command_print(CMD_CTX, "background polling: %s",
2547 jtag_poll_get_enabled() ? "on" : "off");
2548 command_print(CMD_CTX, "TAP: %s (%s)",
2549 target->tap->dotted_name,
2550 target->tap->enabled ? "enabled" : "disabled");
2551 if (!target->tap->enabled)
2552 return ERROR_OK;
2553 retval = target_poll(target);
2554 if (retval != ERROR_OK)
2555 return retval;
2556 retval = target_arch_state(target);
2557 if (retval != ERROR_OK)
2558 return retval;
2559 } else if (CMD_ARGC == 1) {
2560 bool enable;
2561 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2562 jtag_poll_set_enabled(enable);
2563 } else
2564 return ERROR_COMMAND_SYNTAX_ERROR;
2566 return retval;
2569 COMMAND_HANDLER(handle_wait_halt_command)
2571 if (CMD_ARGC > 1)
2572 return ERROR_COMMAND_SYNTAX_ERROR;
2574 unsigned ms = DEFAULT_HALT_TIMEOUT;
2575 if (1 == CMD_ARGC) {
2576 int retval = parse_uint(CMD_ARGV[0], &ms);
2577 if (ERROR_OK != retval)
2578 return ERROR_COMMAND_SYNTAX_ERROR;
2581 struct target *target = get_current_target(CMD_CTX);
2582 return target_wait_state(target, TARGET_HALTED, ms);
2585 /* wait for target state to change. The trick here is to have a low
2586 * latency for short waits and not to suck up all the CPU time
2587 * on longer waits.
2589 * After 500ms, keep_alive() is invoked
2591 int target_wait_state(struct target *target, enum target_state state, int ms)
2593 int retval;
2594 long long then = 0, cur;
2595 int once = 1;
2597 for (;;) {
2598 retval = target_poll(target);
2599 if (retval != ERROR_OK)
2600 return retval;
2601 if (target->state == state)
2602 break;
2603 cur = timeval_ms();
2604 if (once) {
2605 once = 0;
2606 then = timeval_ms();
2607 LOG_DEBUG("waiting for target %s...",
2608 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2611 if (cur-then > 500)
2612 keep_alive();
2614 if ((cur-then) > ms) {
2615 LOG_ERROR("timed out while waiting for target %s",
2616 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2617 return ERROR_FAIL;
2621 return ERROR_OK;
2624 COMMAND_HANDLER(handle_halt_command)
2626 LOG_DEBUG("-");
2628 struct target *target = get_current_target(CMD_CTX);
2629 int retval = target_halt(target);
2630 if (ERROR_OK != retval)
2631 return retval;
2633 if (CMD_ARGC == 1) {
2634 unsigned wait_local;
2635 retval = parse_uint(CMD_ARGV[0], &wait_local);
2636 if (ERROR_OK != retval)
2637 return ERROR_COMMAND_SYNTAX_ERROR;
2638 if (!wait_local)
2639 return ERROR_OK;
2642 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2645 COMMAND_HANDLER(handle_soft_reset_halt_command)
2647 struct target *target = get_current_target(CMD_CTX);
2649 LOG_USER("requesting target halt and executing a soft reset");
2651 target_soft_reset_halt(target);
2653 return ERROR_OK;
2656 COMMAND_HANDLER(handle_reset_command)
2658 if (CMD_ARGC > 1)
2659 return ERROR_COMMAND_SYNTAX_ERROR;
2661 enum target_reset_mode reset_mode = RESET_RUN;
2662 if (CMD_ARGC == 1) {
2663 const Jim_Nvp *n;
2664 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2665 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2666 return ERROR_COMMAND_SYNTAX_ERROR;
2667 reset_mode = n->value;
2670 /* reset *all* targets */
2671 return target_process_reset(CMD_CTX, reset_mode);
2675 COMMAND_HANDLER(handle_resume_command)
2677 int current = 1;
2678 if (CMD_ARGC > 1)
2679 return ERROR_COMMAND_SYNTAX_ERROR;
2681 struct target *target = get_current_target(CMD_CTX);
2683 /* with no CMD_ARGV, resume from current pc, addr = 0,
2684 * with one arguments, addr = CMD_ARGV[0],
2685 * handle breakpoints, not debugging */
2686 uint32_t addr = 0;
2687 if (CMD_ARGC == 1) {
2688 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2689 current = 0;
2692 return target_resume(target, current, addr, 1, 0);
2695 COMMAND_HANDLER(handle_step_command)
2697 if (CMD_ARGC > 1)
2698 return ERROR_COMMAND_SYNTAX_ERROR;
2700 LOG_DEBUG("-");
2702 /* with no CMD_ARGV, step from current pc, addr = 0,
2703 * with one argument addr = CMD_ARGV[0],
2704 * handle breakpoints, debugging */
2705 uint32_t addr = 0;
2706 int current_pc = 1;
2707 if (CMD_ARGC == 1) {
2708 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2709 current_pc = 0;
2712 struct target *target = get_current_target(CMD_CTX);
2714 return target->type->step(target, current_pc, addr, 1);
2717 static void handle_md_output(struct command_context *cmd_ctx,
2718 struct target *target, uint32_t address, unsigned size,
2719 unsigned count, const uint8_t *buffer)
2721 const unsigned line_bytecnt = 32;
2722 unsigned line_modulo = line_bytecnt / size;
2724 char output[line_bytecnt * 4 + 1];
2725 unsigned output_len = 0;
2727 const char *value_fmt;
2728 switch (size) {
2729 case 4:
2730 value_fmt = "%8.8x ";
2731 break;
2732 case 2:
2733 value_fmt = "%4.4x ";
2734 break;
2735 case 1:
2736 value_fmt = "%2.2x ";
2737 break;
2738 default:
2739 /* "can't happen", caller checked */
2740 LOG_ERROR("invalid memory read size: %u", size);
2741 return;
2744 for (unsigned i = 0; i < count; i++) {
2745 if (i % line_modulo == 0) {
2746 output_len += snprintf(output + output_len,
2747 sizeof(output) - output_len,
2748 "0x%8.8x: ",
2749 (unsigned)(address + (i*size)));
2752 uint32_t value = 0;
2753 const uint8_t *value_ptr = buffer + i * size;
2754 switch (size) {
2755 case 4:
2756 value = target_buffer_get_u32(target, value_ptr);
2757 break;
2758 case 2:
2759 value = target_buffer_get_u16(target, value_ptr);
2760 break;
2761 case 1:
2762 value = *value_ptr;
2764 output_len += snprintf(output + output_len,
2765 sizeof(output) - output_len,
2766 value_fmt, value);
2768 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2769 command_print(cmd_ctx, "%s", output);
2770 output_len = 0;
2775 COMMAND_HANDLER(handle_md_command)
2777 if (CMD_ARGC < 1)
2778 return ERROR_COMMAND_SYNTAX_ERROR;
2780 unsigned size = 0;
2781 switch (CMD_NAME[2]) {
2782 case 'w':
2783 size = 4;
2784 break;
2785 case 'h':
2786 size = 2;
2787 break;
2788 case 'b':
2789 size = 1;
2790 break;
2791 default:
2792 return ERROR_COMMAND_SYNTAX_ERROR;
2795 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2796 int (*fn)(struct target *target,
2797 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2798 if (physical) {
2799 CMD_ARGC--;
2800 CMD_ARGV++;
2801 fn = target_read_phys_memory;
2802 } else
2803 fn = target_read_memory;
2804 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2805 return ERROR_COMMAND_SYNTAX_ERROR;
2807 uint32_t address;
2808 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2810 unsigned count = 1;
2811 if (CMD_ARGC == 2)
2812 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2814 uint8_t *buffer = calloc(count, size);
2816 struct target *target = get_current_target(CMD_CTX);
2817 int retval = fn(target, address, size, count, buffer);
2818 if (ERROR_OK == retval)
2819 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2821 free(buffer);
2823 return retval;
2826 typedef int (*target_write_fn)(struct target *target,
2827 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2829 static int target_fill_mem(struct target *target,
2830 uint32_t address,
2831 target_write_fn fn,
2832 unsigned data_size,
2833 /* value */
2834 uint32_t b,
2835 /* count */
2836 unsigned c)
2838 /* We have to write in reasonably large chunks to be able
2839 * to fill large memory areas with any sane speed */
2840 const unsigned chunk_size = 16384;
2841 uint8_t *target_buf = malloc(chunk_size * data_size);
2842 if (target_buf == NULL) {
2843 LOG_ERROR("Out of memory");
2844 return ERROR_FAIL;
2847 for (unsigned i = 0; i < chunk_size; i++) {
2848 switch (data_size) {
2849 case 4:
2850 target_buffer_set_u32(target, target_buf + i * data_size, b);
2851 break;
2852 case 2:
2853 target_buffer_set_u16(target, target_buf + i * data_size, b);
2854 break;
2855 case 1:
2856 target_buffer_set_u8(target, target_buf + i * data_size, b);
2857 break;
2858 default:
2859 exit(-1);
2863 int retval = ERROR_OK;
2865 for (unsigned x = 0; x < c; x += chunk_size) {
2866 unsigned current;
2867 current = c - x;
2868 if (current > chunk_size)
2869 current = chunk_size;
2870 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2871 if (retval != ERROR_OK)
2872 break;
2873 /* avoid GDB timeouts */
2874 keep_alive();
2876 free(target_buf);
2878 return retval;
2882 COMMAND_HANDLER(handle_mw_command)
2884 if (CMD_ARGC < 2)
2885 return ERROR_COMMAND_SYNTAX_ERROR;
2886 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2887 target_write_fn fn;
2888 if (physical) {
2889 CMD_ARGC--;
2890 CMD_ARGV++;
2891 fn = target_write_phys_memory;
2892 } else
2893 fn = target_write_memory;
2894 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2895 return ERROR_COMMAND_SYNTAX_ERROR;
2897 uint32_t address;
2898 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2900 uint32_t value;
2901 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2903 unsigned count = 1;
2904 if (CMD_ARGC == 3)
2905 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2907 struct target *target = get_current_target(CMD_CTX);
2908 unsigned wordsize;
2909 switch (CMD_NAME[2]) {
2910 case 'w':
2911 wordsize = 4;
2912 break;
2913 case 'h':
2914 wordsize = 2;
2915 break;
2916 case 'b':
2917 wordsize = 1;
2918 break;
2919 default:
2920 return ERROR_COMMAND_SYNTAX_ERROR;
2923 return target_fill_mem(target, address, fn, wordsize, value, count);
2926 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2927 uint32_t *min_address, uint32_t *max_address)
2929 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2930 return ERROR_COMMAND_SYNTAX_ERROR;
2932 /* a base address isn't always necessary,
2933 * default to 0x0 (i.e. don't relocate) */
2934 if (CMD_ARGC >= 2) {
2935 uint32_t addr;
2936 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2937 image->base_address = addr;
2938 image->base_address_set = 1;
2939 } else
2940 image->base_address_set = 0;
2942 image->start_address_set = 0;
2944 if (CMD_ARGC >= 4)
2945 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2946 if (CMD_ARGC == 5) {
2947 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2948 /* use size (given) to find max (required) */
2949 *max_address += *min_address;
2952 if (*min_address > *max_address)
2953 return ERROR_COMMAND_SYNTAX_ERROR;
2955 return ERROR_OK;
2958 COMMAND_HANDLER(handle_load_image_command)
2960 uint8_t *buffer;
2961 size_t buf_cnt;
2962 uint32_t image_size;
2963 uint32_t min_address = 0;
2964 uint32_t max_address = 0xffffffff;
2965 int i;
2966 struct image image;
2968 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2969 &image, &min_address, &max_address);
2970 if (ERROR_OK != retval)
2971 return retval;
2973 struct target *target = get_current_target(CMD_CTX);
2975 struct duration bench;
2976 duration_start(&bench);
2978 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2979 return ERROR_OK;
2981 image_size = 0x0;
2982 retval = ERROR_OK;
2983 for (i = 0; i < image.num_sections; i++) {
2984 buffer = malloc(image.sections[i].size);
2985 if (buffer == NULL) {
2986 command_print(CMD_CTX,
2987 "error allocating buffer for section (%d bytes)",
2988 (int)(image.sections[i].size));
2989 break;
2992 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
2993 if (retval != ERROR_OK) {
2994 free(buffer);
2995 break;
2998 uint32_t offset = 0;
2999 uint32_t length = buf_cnt;
3001 /* DANGER!!! beware of unsigned comparision here!!! */
3003 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3004 (image.sections[i].base_address < max_address)) {
3006 if (image.sections[i].base_address < min_address) {
3007 /* clip addresses below */
3008 offset += min_address-image.sections[i].base_address;
3009 length -= offset;
3012 if (image.sections[i].base_address + buf_cnt > max_address)
3013 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3015 retval = target_write_buffer(target,
3016 image.sections[i].base_address + offset, length, buffer + offset);
3017 if (retval != ERROR_OK) {
3018 free(buffer);
3019 break;
3021 image_size += length;
3022 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
3023 (unsigned int)length,
3024 image.sections[i].base_address + offset);
3027 free(buffer);
3030 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3031 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
3032 "in %fs (%0.3f KiB/s)", image_size,
3033 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3036 image_close(&image);
3038 return retval;
3042 COMMAND_HANDLER(handle_dump_image_command)
3044 struct fileio fileio;
3045 uint8_t *buffer;
3046 int retval, retvaltemp;
3047 uint32_t address, size;
3048 struct duration bench;
3049 struct target *target = get_current_target(CMD_CTX);
3051 if (CMD_ARGC != 3)
3052 return ERROR_COMMAND_SYNTAX_ERROR;
3054 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
3055 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
3057 uint32_t buf_size = (size > 4096) ? 4096 : size;
3058 buffer = malloc(buf_size);
3059 if (!buffer)
3060 return ERROR_FAIL;
3062 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3063 if (retval != ERROR_OK) {
3064 free(buffer);
3065 return retval;
3068 duration_start(&bench);
3070 while (size > 0) {
3071 size_t size_written;
3072 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3073 retval = target_read_buffer(target, address, this_run_size, buffer);
3074 if (retval != ERROR_OK)
3075 break;
3077 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
3078 if (retval != ERROR_OK)
3079 break;
3081 size -= this_run_size;
3082 address += this_run_size;
3085 free(buffer);
3087 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3088 int filesize;
3089 retval = fileio_size(&fileio, &filesize);
3090 if (retval != ERROR_OK)
3091 return retval;
3092 command_print(CMD_CTX,
3093 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
3094 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3097 retvaltemp = fileio_close(&fileio);
3098 if (retvaltemp != ERROR_OK)
3099 return retvaltemp;
3101 return retval;
3104 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
3106 uint8_t *buffer;
3107 size_t buf_cnt;
3108 uint32_t image_size;
3109 int i;
3110 int retval;
3111 uint32_t checksum = 0;
3112 uint32_t mem_checksum = 0;
3114 struct image image;
3116 struct target *target = get_current_target(CMD_CTX);
3118 if (CMD_ARGC < 1)
3119 return ERROR_COMMAND_SYNTAX_ERROR;
3121 if (!target) {
3122 LOG_ERROR("no target selected");
3123 return ERROR_FAIL;
3126 struct duration bench;
3127 duration_start(&bench);
3129 if (CMD_ARGC >= 2) {
3130 uint32_t addr;
3131 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3132 image.base_address = addr;
3133 image.base_address_set = 1;
3134 } else {
3135 image.base_address_set = 0;
3136 image.base_address = 0x0;
3139 image.start_address_set = 0;
3141 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3142 if (retval != ERROR_OK)
3143 return retval;
3145 image_size = 0x0;
3146 int diffs = 0;
3147 retval = ERROR_OK;
3148 for (i = 0; i < image.num_sections; i++) {
3149 buffer = malloc(image.sections[i].size);
3150 if (buffer == NULL) {
3151 command_print(CMD_CTX,
3152 "error allocating buffer for section (%d bytes)",
3153 (int)(image.sections[i].size));
3154 break;
3156 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3157 if (retval != ERROR_OK) {
3158 free(buffer);
3159 break;
3162 if (verify) {
3163 /* calculate checksum of image */
3164 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3165 if (retval != ERROR_OK) {
3166 free(buffer);
3167 break;
3170 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3171 if (retval != ERROR_OK) {
3172 free(buffer);
3173 break;
3176 if (checksum != mem_checksum) {
3177 /* failed crc checksum, fall back to a binary compare */
3178 uint8_t *data;
3180 if (diffs == 0)
3181 LOG_ERROR("checksum mismatch - attempting binary compare");
3183 data = (uint8_t *)malloc(buf_cnt);
3185 /* Can we use 32bit word accesses? */
3186 int size = 1;
3187 int count = buf_cnt;
3188 if ((count % 4) == 0) {
3189 size *= 4;
3190 count /= 4;
3192 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3193 if (retval == ERROR_OK) {
3194 uint32_t t;
3195 for (t = 0; t < buf_cnt; t++) {
3196 if (data[t] != buffer[t]) {
3197 command_print(CMD_CTX,
3198 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3199 diffs,
3200 (unsigned)(t + image.sections[i].base_address),
3201 data[t],
3202 buffer[t]);
3203 if (diffs++ >= 127) {
3204 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3205 free(data);
3206 free(buffer);
3207 goto done;
3210 keep_alive();
3213 free(data);
3215 } else {
3216 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3217 image.sections[i].base_address,
3218 buf_cnt);
3221 free(buffer);
3222 image_size += buf_cnt;
3224 if (diffs > 0)
3225 command_print(CMD_CTX, "No more differences found.");
3226 done:
3227 if (diffs > 0)
3228 retval = ERROR_FAIL;
3229 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3230 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3231 "in %fs (%0.3f KiB/s)", image_size,
3232 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3235 image_close(&image);
3237 return retval;
3240 COMMAND_HANDLER(handle_verify_image_command)
3242 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3245 COMMAND_HANDLER(handle_test_image_command)
3247 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3250 static int handle_bp_command_list(struct command_context *cmd_ctx)
3252 struct target *target = get_current_target(cmd_ctx);
3253 struct breakpoint *breakpoint = target->breakpoints;
3254 while (breakpoint) {
3255 if (breakpoint->type == BKPT_SOFT) {
3256 char *buf = buf_to_str(breakpoint->orig_instr,
3257 breakpoint->length, 16);
3258 command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3259 breakpoint->address,
3260 breakpoint->length,
3261 breakpoint->set, buf);
3262 free(buf);
3263 } else {
3264 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3265 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3266 breakpoint->asid,
3267 breakpoint->length, breakpoint->set);
3268 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3269 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3270 breakpoint->address,
3271 breakpoint->length, breakpoint->set);
3272 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3273 breakpoint->asid);
3274 } else
3275 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3276 breakpoint->address,
3277 breakpoint->length, breakpoint->set);
3280 breakpoint = breakpoint->next;
3282 return ERROR_OK;
3285 static int handle_bp_command_set(struct command_context *cmd_ctx,
3286 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3288 struct target *target = get_current_target(cmd_ctx);
3290 if (asid == 0) {
3291 int retval = breakpoint_add(target, addr, length, hw);
3292 if (ERROR_OK == retval)
3293 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3294 else {
3295 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3296 return retval;
3298 } else if (addr == 0) {
3299 int retval = context_breakpoint_add(target, asid, length, hw);
3300 if (ERROR_OK == retval)
3301 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3302 else {
3303 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3304 return retval;
3306 } else {
3307 int retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3308 if (ERROR_OK == retval)
3309 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3310 else {
3311 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3312 return retval;
3315 return ERROR_OK;
3318 COMMAND_HANDLER(handle_bp_command)
3320 uint32_t addr;
3321 uint32_t asid;
3322 uint32_t length;
3323 int hw = BKPT_SOFT;
3325 switch (CMD_ARGC) {
3326 case 0:
3327 return handle_bp_command_list(CMD_CTX);
3329 case 2:
3330 asid = 0;
3331 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3332 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3333 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3335 case 3:
3336 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3337 hw = BKPT_HARD;
3338 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3340 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3342 asid = 0;
3343 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3344 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3345 hw = BKPT_HARD;
3346 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3347 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3348 addr = 0;
3349 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3352 case 4:
3353 hw = BKPT_HARD;
3354 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3355 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3356 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3357 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3359 default:
3360 return ERROR_COMMAND_SYNTAX_ERROR;
3364 COMMAND_HANDLER(handle_rbp_command)
3366 if (CMD_ARGC != 1)
3367 return ERROR_COMMAND_SYNTAX_ERROR;
3369 uint32_t addr;
3370 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3372 struct target *target = get_current_target(CMD_CTX);
3373 breakpoint_remove(target, addr);
3375 return ERROR_OK;
3378 COMMAND_HANDLER(handle_wp_command)
3380 struct target *target = get_current_target(CMD_CTX);
3382 if (CMD_ARGC == 0) {
3383 struct watchpoint *watchpoint = target->watchpoints;
3385 while (watchpoint) {
3386 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3387 ", len: 0x%8.8" PRIx32
3388 ", r/w/a: %i, value: 0x%8.8" PRIx32
3389 ", mask: 0x%8.8" PRIx32,
3390 watchpoint->address,
3391 watchpoint->length,
3392 (int)watchpoint->rw,
3393 watchpoint->value,
3394 watchpoint->mask);
3395 watchpoint = watchpoint->next;
3397 return ERROR_OK;
3400 enum watchpoint_rw type = WPT_ACCESS;
3401 uint32_t addr = 0;
3402 uint32_t length = 0;
3403 uint32_t data_value = 0x0;
3404 uint32_t data_mask = 0xffffffff;
3406 switch (CMD_ARGC) {
3407 case 5:
3408 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3409 /* fall through */
3410 case 4:
3411 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3412 /* fall through */
3413 case 3:
3414 switch (CMD_ARGV[2][0]) {
3415 case 'r':
3416 type = WPT_READ;
3417 break;
3418 case 'w':
3419 type = WPT_WRITE;
3420 break;
3421 case 'a':
3422 type = WPT_ACCESS;
3423 break;
3424 default:
3425 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3426 return ERROR_COMMAND_SYNTAX_ERROR;
3428 /* fall through */
3429 case 2:
3430 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3431 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3432 break;
3434 default:
3435 return ERROR_COMMAND_SYNTAX_ERROR;
3438 int retval = watchpoint_add(target, addr, length, type,
3439 data_value, data_mask);
3440 if (ERROR_OK != retval)
3441 LOG_ERROR("Failure setting watchpoints");
3443 return retval;
3446 COMMAND_HANDLER(handle_rwp_command)
3448 if (CMD_ARGC != 1)
3449 return ERROR_COMMAND_SYNTAX_ERROR;
3451 uint32_t addr;
3452 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3454 struct target *target = get_current_target(CMD_CTX);
3455 watchpoint_remove(target, addr);
3457 return ERROR_OK;
3461 * Translate a virtual address to a physical address.
3463 * The low-level target implementation must have logged a detailed error
3464 * which is forwarded to telnet/GDB session.
3466 COMMAND_HANDLER(handle_virt2phys_command)
3468 if (CMD_ARGC != 1)
3469 return ERROR_COMMAND_SYNTAX_ERROR;
3471 uint32_t va;
3472 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3473 uint32_t pa;
3475 struct target *target = get_current_target(CMD_CTX);
3476 int retval = target->type->virt2phys(target, va, &pa);
3477 if (retval == ERROR_OK)
3478 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3480 return retval;
3483 static void writeData(FILE *f, const void *data, size_t len)
3485 size_t written = fwrite(data, 1, len, f);
3486 if (written != len)
3487 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3490 static void writeLong(FILE *f, int l)
3492 int i;
3493 for (i = 0; i < 4; i++) {
3494 char c = (l >> (i*8))&0xff;
3495 writeData(f, &c, 1);
3500 static void writeString(FILE *f, char *s)
3502 writeData(f, s, strlen(s));
3505 typedef unsigned char UNIT[2]; /* unit of profiling */
3507 /* Dump a gmon.out histogram file. */
3508 static void write_gmon(uint32_t *samples, uint32_t sampleNum, const char *filename,
3509 bool with_range, uint32_t start_address, uint32_t end_address)
3511 uint32_t i;
3512 FILE *f = fopen(filename, "w");
3513 if (f == NULL)
3514 return;
3515 writeString(f, "gmon");
3516 writeLong(f, 0x00000001); /* Version */
3517 writeLong(f, 0); /* padding */
3518 writeLong(f, 0); /* padding */
3519 writeLong(f, 0); /* padding */
3521 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3522 writeData(f, &zero, 1);
3524 /* figure out bucket size */
3525 uint32_t min;
3526 uint32_t max;
3527 if (with_range) {
3528 min = start_address;
3529 max = end_address;
3530 } else {
3531 min = samples[0];
3532 max = samples[0];
3533 for (i = 0; i < sampleNum; i++) {
3534 if (min > samples[i])
3535 min = samples[i];
3536 if (max < samples[i])
3537 max = samples[i];
3540 /* max should be (largest sample + 1)
3541 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
3542 max++;
3545 int addressSpace = max - min;
3546 assert(addressSpace >= 2);
3548 /* FIXME: What is the reasonable number of buckets?
3549 * The profiling result will be more accurate if there are enough buckets. */
3550 static const uint32_t maxBuckets = 128 * 1024; /* maximum buckets. */
3551 uint32_t numBuckets = addressSpace / sizeof(UNIT);
3552 if (numBuckets > maxBuckets)
3553 numBuckets = maxBuckets;
3554 int *buckets = malloc(sizeof(int) * numBuckets);
3555 if (buckets == NULL) {
3556 fclose(f);
3557 return;
3559 memset(buckets, 0, sizeof(int) * numBuckets);
3560 for (i = 0; i < sampleNum; i++) {
3561 uint32_t address = samples[i];
3563 if ((address < min) || (max <= address))
3564 continue;
3566 long long a = address - min;
3567 long long b = numBuckets;
3568 long long c = addressSpace;
3569 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3570 buckets[index_t]++;
3573 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3574 writeLong(f, min); /* low_pc */
3575 writeLong(f, max); /* high_pc */
3576 writeLong(f, numBuckets); /* # of buckets */
3577 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3578 writeString(f, "seconds");
3579 for (i = 0; i < (15-strlen("seconds")); i++)
3580 writeData(f, &zero, 1);
3581 writeString(f, "s");
3583 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3585 char *data = malloc(2 * numBuckets);
3586 if (data != NULL) {
3587 for (i = 0; i < numBuckets; i++) {
3588 int val;
3589 val = buckets[i];
3590 if (val > 65535)
3591 val = 65535;
3592 data[i * 2] = val&0xff;
3593 data[i * 2 + 1] = (val >> 8) & 0xff;
3595 free(buckets);
3596 writeData(f, data, numBuckets * 2);
3597 free(data);
3598 } else
3599 free(buckets);
3601 fclose(f);
3604 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3605 * which will be used as a random sampling of PC */
3606 COMMAND_HANDLER(handle_profile_command)
3608 struct target *target = get_current_target(CMD_CTX);
3610 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
3611 return ERROR_COMMAND_SYNTAX_ERROR;
3613 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
3614 uint32_t offset;
3615 uint32_t num_of_sampels;
3616 int retval = ERROR_OK;
3617 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
3618 if (samples == NULL) {
3619 LOG_ERROR("No memory to store samples.");
3620 return ERROR_FAIL;
3623 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
3626 * Some cores let us sample the PC without the
3627 * annoying halt/resume step; for example, ARMv7 PCSR.
3628 * Provide a way to use that more efficient mechanism.
3630 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
3631 &num_of_sampels, offset);
3632 if (retval != ERROR_OK) {
3633 free(samples);
3634 return retval;
3637 assert(num_of_sampels <= MAX_PROFILE_SAMPLE_NUM);
3639 retval = target_poll(target);
3640 if (retval != ERROR_OK) {
3641 free(samples);
3642 return retval;
3644 if (target->state == TARGET_RUNNING) {
3645 retval = target_halt(target);
3646 if (retval != ERROR_OK) {
3647 free(samples);
3648 return retval;
3652 retval = target_poll(target);
3653 if (retval != ERROR_OK) {
3654 free(samples);
3655 return retval;
3658 uint32_t start_address = 0;
3659 uint32_t end_address = 0;
3660 bool with_range = false;
3661 if (CMD_ARGC == 4) {
3662 with_range = true;
3663 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
3664 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
3667 write_gmon(samples, num_of_sampels, CMD_ARGV[1],
3668 with_range, start_address, end_address);
3669 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3671 free(samples);
3672 return retval;
3675 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3677 char *namebuf;
3678 Jim_Obj *nameObjPtr, *valObjPtr;
3679 int result;
3681 namebuf = alloc_printf("%s(%d)", varname, idx);
3682 if (!namebuf)
3683 return JIM_ERR;
3685 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3686 valObjPtr = Jim_NewIntObj(interp, val);
3687 if (!nameObjPtr || !valObjPtr) {
3688 free(namebuf);
3689 return JIM_ERR;
3692 Jim_IncrRefCount(nameObjPtr);
3693 Jim_IncrRefCount(valObjPtr);
3694 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3695 Jim_DecrRefCount(interp, nameObjPtr);
3696 Jim_DecrRefCount(interp, valObjPtr);
3697 free(namebuf);
3698 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3699 return result;
3702 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3704 struct command_context *context;
3705 struct target *target;
3707 context = current_command_context(interp);
3708 assert(context != NULL);
3710 target = get_current_target(context);
3711 if (target == NULL) {
3712 LOG_ERROR("mem2array: no current target");
3713 return JIM_ERR;
3716 return target_mem2array(interp, target, argc - 1, argv + 1);
3719 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3721 long l;
3722 uint32_t width;
3723 int len;
3724 uint32_t addr;
3725 uint32_t count;
3726 uint32_t v;
3727 const char *varname;
3728 int n, e, retval;
3729 uint32_t i;
3731 /* argv[1] = name of array to receive the data
3732 * argv[2] = desired width
3733 * argv[3] = memory address
3734 * argv[4] = count of times to read
3736 if (argc != 4) {
3737 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3738 return JIM_ERR;
3740 varname = Jim_GetString(argv[0], &len);
3741 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3743 e = Jim_GetLong(interp, argv[1], &l);
3744 width = l;
3745 if (e != JIM_OK)
3746 return e;
3748 e = Jim_GetLong(interp, argv[2], &l);
3749 addr = l;
3750 if (e != JIM_OK)
3751 return e;
3752 e = Jim_GetLong(interp, argv[3], &l);
3753 len = l;
3754 if (e != JIM_OK)
3755 return e;
3756 switch (width) {
3757 case 8:
3758 width = 1;
3759 break;
3760 case 16:
3761 width = 2;
3762 break;
3763 case 32:
3764 width = 4;
3765 break;
3766 default:
3767 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3768 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3769 return JIM_ERR;
3771 if (len == 0) {
3772 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3773 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3774 return JIM_ERR;
3776 if ((addr + (len * width)) < addr) {
3777 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3778 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3779 return JIM_ERR;
3781 /* absurd transfer size? */
3782 if (len > 65536) {
3783 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3784 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3785 return JIM_ERR;
3788 if ((width == 1) ||
3789 ((width == 2) && ((addr & 1) == 0)) ||
3790 ((width == 4) && ((addr & 3) == 0))) {
3791 /* all is well */
3792 } else {
3793 char buf[100];
3794 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3795 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3796 addr,
3797 width);
3798 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3799 return JIM_ERR;
3802 /* Transfer loop */
3804 /* index counter */
3805 n = 0;
3807 size_t buffersize = 4096;
3808 uint8_t *buffer = malloc(buffersize);
3809 if (buffer == NULL)
3810 return JIM_ERR;
3812 /* assume ok */
3813 e = JIM_OK;
3814 while (len) {
3815 /* Slurp... in buffer size chunks */
3817 count = len; /* in objects.. */
3818 if (count > (buffersize / width))
3819 count = (buffersize / width);
3821 retval = target_read_memory(target, addr, width, count, buffer);
3822 if (retval != ERROR_OK) {
3823 /* BOO !*/
3824 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3825 (unsigned int)addr,
3826 (int)width,
3827 (int)count);
3828 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3829 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3830 e = JIM_ERR;
3831 break;
3832 } else {
3833 v = 0; /* shut up gcc */
3834 for (i = 0; i < count ; i++, n++) {
3835 switch (width) {
3836 case 4:
3837 v = target_buffer_get_u32(target, &buffer[i*width]);
3838 break;
3839 case 2:
3840 v = target_buffer_get_u16(target, &buffer[i*width]);
3841 break;
3842 case 1:
3843 v = buffer[i] & 0x0ff;
3844 break;
3846 new_int_array_element(interp, varname, n, v);
3848 len -= count;
3849 addr += count * width;
3853 free(buffer);
3855 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3857 return e;
3860 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
3862 char *namebuf;
3863 Jim_Obj *nameObjPtr, *valObjPtr;
3864 int result;
3865 long l;
3867 namebuf = alloc_printf("%s(%d)", varname, idx);
3868 if (!namebuf)
3869 return JIM_ERR;
3871 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3872 if (!nameObjPtr) {
3873 free(namebuf);
3874 return JIM_ERR;
3877 Jim_IncrRefCount(nameObjPtr);
3878 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3879 Jim_DecrRefCount(interp, nameObjPtr);
3880 free(namebuf);
3881 if (valObjPtr == NULL)
3882 return JIM_ERR;
3884 result = Jim_GetLong(interp, valObjPtr, &l);
3885 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3886 *val = l;
3887 return result;
3890 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3892 struct command_context *context;
3893 struct target *target;
3895 context = current_command_context(interp);
3896 assert(context != NULL);
3898 target = get_current_target(context);
3899 if (target == NULL) {
3900 LOG_ERROR("array2mem: no current target");
3901 return JIM_ERR;
3904 return target_array2mem(interp, target, argc-1, argv + 1);
3907 static int target_array2mem(Jim_Interp *interp, struct target *target,
3908 int argc, Jim_Obj *const *argv)
3910 long l;
3911 uint32_t width;
3912 int len;
3913 uint32_t addr;
3914 uint32_t count;
3915 uint32_t v;
3916 const char *varname;
3917 int n, e, retval;
3918 uint32_t i;
3920 /* argv[1] = name of array to get the data
3921 * argv[2] = desired width
3922 * argv[3] = memory address
3923 * argv[4] = count to write
3925 if (argc != 4) {
3926 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3927 return JIM_ERR;
3929 varname = Jim_GetString(argv[0], &len);
3930 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3932 e = Jim_GetLong(interp, argv[1], &l);
3933 width = l;
3934 if (e != JIM_OK)
3935 return e;
3937 e = Jim_GetLong(interp, argv[2], &l);
3938 addr = l;
3939 if (e != JIM_OK)
3940 return e;
3941 e = Jim_GetLong(interp, argv[3], &l);
3942 len = l;
3943 if (e != JIM_OK)
3944 return e;
3945 switch (width) {
3946 case 8:
3947 width = 1;
3948 break;
3949 case 16:
3950 width = 2;
3951 break;
3952 case 32:
3953 width = 4;
3954 break;
3955 default:
3956 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3957 Jim_AppendStrings(interp, Jim_GetResult(interp),
3958 "Invalid width param, must be 8/16/32", NULL);
3959 return JIM_ERR;
3961 if (len == 0) {
3962 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3963 Jim_AppendStrings(interp, Jim_GetResult(interp),
3964 "array2mem: zero width read?", NULL);
3965 return JIM_ERR;
3967 if ((addr + (len * width)) < addr) {
3968 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3969 Jim_AppendStrings(interp, Jim_GetResult(interp),
3970 "array2mem: addr + len - wraps to zero?", NULL);
3971 return JIM_ERR;
3973 /* absurd transfer size? */
3974 if (len > 65536) {
3975 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3976 Jim_AppendStrings(interp, Jim_GetResult(interp),
3977 "array2mem: absurd > 64K item request", NULL);
3978 return JIM_ERR;
3981 if ((width == 1) ||
3982 ((width == 2) && ((addr & 1) == 0)) ||
3983 ((width == 4) && ((addr & 3) == 0))) {
3984 /* all is well */
3985 } else {
3986 char buf[100];
3987 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3988 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3989 (unsigned int)addr,
3990 (int)width);
3991 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3992 return JIM_ERR;
3995 /* Transfer loop */
3997 /* index counter */
3998 n = 0;
3999 /* assume ok */
4000 e = JIM_OK;
4002 size_t buffersize = 4096;
4003 uint8_t *buffer = malloc(buffersize);
4004 if (buffer == NULL)
4005 return JIM_ERR;
4007 while (len) {
4008 /* Slurp... in buffer size chunks */
4010 count = len; /* in objects.. */
4011 if (count > (buffersize / width))
4012 count = (buffersize / width);
4014 v = 0; /* shut up gcc */
4015 for (i = 0; i < count; i++, n++) {
4016 get_int_array_element(interp, varname, n, &v);
4017 switch (width) {
4018 case 4:
4019 target_buffer_set_u32(target, &buffer[i * width], v);
4020 break;
4021 case 2:
4022 target_buffer_set_u16(target, &buffer[i * width], v);
4023 break;
4024 case 1:
4025 buffer[i] = v & 0x0ff;
4026 break;
4029 len -= count;
4031 retval = target_write_memory(target, addr, width, count, buffer);
4032 if (retval != ERROR_OK) {
4033 /* BOO !*/
4034 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
4035 (unsigned int)addr,
4036 (int)width,
4037 (int)count);
4038 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4039 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4040 e = JIM_ERR;
4041 break;
4043 addr += count * width;
4046 free(buffer);
4048 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4050 return e;
4053 /* FIX? should we propagate errors here rather than printing them
4054 * and continuing?
4056 void target_handle_event(struct target *target, enum target_event e)
4058 struct target_event_action *teap;
4060 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4061 if (teap->event == e) {
4062 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
4063 target->target_number,
4064 target_name(target),
4065 target_type_name(target),
4067 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
4068 Jim_GetString(teap->body, NULL));
4069 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
4070 Jim_MakeErrorMessage(teap->interp);
4071 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
4078 * Returns true only if the target has a handler for the specified event.
4080 bool target_has_event_action(struct target *target, enum target_event event)
4082 struct target_event_action *teap;
4084 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4085 if (teap->event == event)
4086 return true;
4088 return false;
4091 enum target_cfg_param {
4092 TCFG_TYPE,
4093 TCFG_EVENT,
4094 TCFG_WORK_AREA_VIRT,
4095 TCFG_WORK_AREA_PHYS,
4096 TCFG_WORK_AREA_SIZE,
4097 TCFG_WORK_AREA_BACKUP,
4098 TCFG_ENDIAN,
4099 TCFG_VARIANT,
4100 TCFG_COREID,
4101 TCFG_CHAIN_POSITION,
4102 TCFG_DBGBASE,
4103 TCFG_RTOS,
4106 static Jim_Nvp nvp_config_opts[] = {
4107 { .name = "-type", .value = TCFG_TYPE },
4108 { .name = "-event", .value = TCFG_EVENT },
4109 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4110 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4111 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4112 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4113 { .name = "-endian" , .value = TCFG_ENDIAN },
4114 { .name = "-variant", .value = TCFG_VARIANT },
4115 { .name = "-coreid", .value = TCFG_COREID },
4116 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4117 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4118 { .name = "-rtos", .value = TCFG_RTOS },
4119 { .name = NULL, .value = -1 }
4122 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
4124 Jim_Nvp *n;
4125 Jim_Obj *o;
4126 jim_wide w;
4127 char *cp;
4128 int e;
4130 /* parse config or cget options ... */
4131 while (goi->argc > 0) {
4132 Jim_SetEmptyResult(goi->interp);
4133 /* Jim_GetOpt_Debug(goi); */
4135 if (target->type->target_jim_configure) {
4136 /* target defines a configure function */
4137 /* target gets first dibs on parameters */
4138 e = (*(target->type->target_jim_configure))(target, goi);
4139 if (e == JIM_OK) {
4140 /* more? */
4141 continue;
4143 if (e == JIM_ERR) {
4144 /* An error */
4145 return e;
4147 /* otherwise we 'continue' below */
4149 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
4150 if (e != JIM_OK) {
4151 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
4152 return e;
4154 switch (n->value) {
4155 case TCFG_TYPE:
4156 /* not setable */
4157 if (goi->isconfigure) {
4158 Jim_SetResultFormatted(goi->interp,
4159 "not settable: %s", n->name);
4160 return JIM_ERR;
4161 } else {
4162 no_params:
4163 if (goi->argc != 0) {
4164 Jim_WrongNumArgs(goi->interp,
4165 goi->argc, goi->argv,
4166 "NO PARAMS");
4167 return JIM_ERR;
4170 Jim_SetResultString(goi->interp,
4171 target_type_name(target), -1);
4172 /* loop for more */
4173 break;
4174 case TCFG_EVENT:
4175 if (goi->argc == 0) {
4176 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4177 return JIM_ERR;
4180 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4181 if (e != JIM_OK) {
4182 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4183 return e;
4186 if (goi->isconfigure) {
4187 if (goi->argc != 1) {
4188 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4189 return JIM_ERR;
4191 } else {
4192 if (goi->argc != 0) {
4193 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4194 return JIM_ERR;
4199 struct target_event_action *teap;
4201 teap = target->event_action;
4202 /* replace existing? */
4203 while (teap) {
4204 if (teap->event == (enum target_event)n->value)
4205 break;
4206 teap = teap->next;
4209 if (goi->isconfigure) {
4210 bool replace = true;
4211 if (teap == NULL) {
4212 /* create new */
4213 teap = calloc(1, sizeof(*teap));
4214 replace = false;
4216 teap->event = n->value;
4217 teap->interp = goi->interp;
4218 Jim_GetOpt_Obj(goi, &o);
4219 if (teap->body)
4220 Jim_DecrRefCount(teap->interp, teap->body);
4221 teap->body = Jim_DuplicateObj(goi->interp, o);
4223 * FIXME:
4224 * Tcl/TK - "tk events" have a nice feature.
4225 * See the "BIND" command.
4226 * We should support that here.
4227 * You can specify %X and %Y in the event code.
4228 * The idea is: %T - target name.
4229 * The idea is: %N - target number
4230 * The idea is: %E - event name.
4232 Jim_IncrRefCount(teap->body);
4234 if (!replace) {
4235 /* add to head of event list */
4236 teap->next = target->event_action;
4237 target->event_action = teap;
4239 Jim_SetEmptyResult(goi->interp);
4240 } else {
4241 /* get */
4242 if (teap == NULL)
4243 Jim_SetEmptyResult(goi->interp);
4244 else
4245 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4248 /* loop for more */
4249 break;
4251 case TCFG_WORK_AREA_VIRT:
4252 if (goi->isconfigure) {
4253 target_free_all_working_areas(target);
4254 e = Jim_GetOpt_Wide(goi, &w);
4255 if (e != JIM_OK)
4256 return e;
4257 target->working_area_virt = w;
4258 target->working_area_virt_spec = true;
4259 } else {
4260 if (goi->argc != 0)
4261 goto no_params;
4263 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4264 /* loop for more */
4265 break;
4267 case TCFG_WORK_AREA_PHYS:
4268 if (goi->isconfigure) {
4269 target_free_all_working_areas(target);
4270 e = Jim_GetOpt_Wide(goi, &w);
4271 if (e != JIM_OK)
4272 return e;
4273 target->working_area_phys = w;
4274 target->working_area_phys_spec = true;
4275 } else {
4276 if (goi->argc != 0)
4277 goto no_params;
4279 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4280 /* loop for more */
4281 break;
4283 case TCFG_WORK_AREA_SIZE:
4284 if (goi->isconfigure) {
4285 target_free_all_working_areas(target);
4286 e = Jim_GetOpt_Wide(goi, &w);
4287 if (e != JIM_OK)
4288 return e;
4289 target->working_area_size = w;
4290 } else {
4291 if (goi->argc != 0)
4292 goto no_params;
4294 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4295 /* loop for more */
4296 break;
4298 case TCFG_WORK_AREA_BACKUP:
4299 if (goi->isconfigure) {
4300 target_free_all_working_areas(target);
4301 e = Jim_GetOpt_Wide(goi, &w);
4302 if (e != JIM_OK)
4303 return e;
4304 /* make this exactly 1 or 0 */
4305 target->backup_working_area = (!!w);
4306 } else {
4307 if (goi->argc != 0)
4308 goto no_params;
4310 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4311 /* loop for more e*/
4312 break;
4315 case TCFG_ENDIAN:
4316 if (goi->isconfigure) {
4317 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4318 if (e != JIM_OK) {
4319 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4320 return e;
4322 target->endianness = n->value;
4323 } else {
4324 if (goi->argc != 0)
4325 goto no_params;
4327 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4328 if (n->name == NULL) {
4329 target->endianness = TARGET_LITTLE_ENDIAN;
4330 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4332 Jim_SetResultString(goi->interp, n->name, -1);
4333 /* loop for more */
4334 break;
4336 case TCFG_VARIANT:
4337 if (goi->isconfigure) {
4338 if (goi->argc < 1) {
4339 Jim_SetResultFormatted(goi->interp,
4340 "%s ?STRING?",
4341 n->name);
4342 return JIM_ERR;
4344 e = Jim_GetOpt_String(goi, &cp, NULL);
4345 if (e != JIM_OK)
4346 return e;
4347 free(target->variant);
4348 target->variant = strdup(cp);
4349 } else {
4350 if (goi->argc != 0)
4351 goto no_params;
4353 Jim_SetResultString(goi->interp, target->variant, -1);
4354 /* loop for more */
4355 break;
4357 case TCFG_COREID:
4358 if (goi->isconfigure) {
4359 e = Jim_GetOpt_Wide(goi, &w);
4360 if (e != JIM_OK)
4361 return e;
4362 target->coreid = (int32_t)w;
4363 } else {
4364 if (goi->argc != 0)
4365 goto no_params;
4367 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4368 /* loop for more */
4369 break;
4371 case TCFG_CHAIN_POSITION:
4372 if (goi->isconfigure) {
4373 Jim_Obj *o_t;
4374 struct jtag_tap *tap;
4375 target_free_all_working_areas(target);
4376 e = Jim_GetOpt_Obj(goi, &o_t);
4377 if (e != JIM_OK)
4378 return e;
4379 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4380 if (tap == NULL)
4381 return JIM_ERR;
4382 /* make this exactly 1 or 0 */
4383 target->tap = tap;
4384 } else {
4385 if (goi->argc != 0)
4386 goto no_params;
4388 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4389 /* loop for more e*/
4390 break;
4391 case TCFG_DBGBASE:
4392 if (goi->isconfigure) {
4393 e = Jim_GetOpt_Wide(goi, &w);
4394 if (e != JIM_OK)
4395 return e;
4396 target->dbgbase = (uint32_t)w;
4397 target->dbgbase_set = true;
4398 } else {
4399 if (goi->argc != 0)
4400 goto no_params;
4402 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4403 /* loop for more */
4404 break;
4406 case TCFG_RTOS:
4407 /* RTOS */
4409 int result = rtos_create(goi, target);
4410 if (result != JIM_OK)
4411 return result;
4413 /* loop for more */
4414 break;
4416 } /* while (goi->argc) */
4419 /* done - we return */
4420 return JIM_OK;
4423 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4425 Jim_GetOptInfo goi;
4427 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4428 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4429 int need_args = 1 + goi.isconfigure;
4430 if (goi.argc < need_args) {
4431 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4432 goi.isconfigure
4433 ? "missing: -option VALUE ..."
4434 : "missing: -option ...");
4435 return JIM_ERR;
4437 struct target *target = Jim_CmdPrivData(goi.interp);
4438 return target_configure(&goi, target);
4441 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4443 const char *cmd_name = Jim_GetString(argv[0], NULL);
4445 Jim_GetOptInfo goi;
4446 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4448 if (goi.argc < 2 || goi.argc > 4) {
4449 Jim_SetResultFormatted(goi.interp,
4450 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4451 return JIM_ERR;
4454 target_write_fn fn;
4455 fn = target_write_memory;
4457 int e;
4458 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4459 /* consume it */
4460 struct Jim_Obj *obj;
4461 e = Jim_GetOpt_Obj(&goi, &obj);
4462 if (e != JIM_OK)
4463 return e;
4465 fn = target_write_phys_memory;
4468 jim_wide a;
4469 e = Jim_GetOpt_Wide(&goi, &a);
4470 if (e != JIM_OK)
4471 return e;
4473 jim_wide b;
4474 e = Jim_GetOpt_Wide(&goi, &b);
4475 if (e != JIM_OK)
4476 return e;
4478 jim_wide c = 1;
4479 if (goi.argc == 1) {
4480 e = Jim_GetOpt_Wide(&goi, &c);
4481 if (e != JIM_OK)
4482 return e;
4485 /* all args must be consumed */
4486 if (goi.argc != 0)
4487 return JIM_ERR;
4489 struct target *target = Jim_CmdPrivData(goi.interp);
4490 unsigned data_size;
4491 if (strcasecmp(cmd_name, "mww") == 0)
4492 data_size = 4;
4493 else if (strcasecmp(cmd_name, "mwh") == 0)
4494 data_size = 2;
4495 else if (strcasecmp(cmd_name, "mwb") == 0)
4496 data_size = 1;
4497 else {
4498 LOG_ERROR("command '%s' unknown: ", cmd_name);
4499 return JIM_ERR;
4502 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4506 * @brief Reads an array of words/halfwords/bytes from target memory starting at specified address.
4508 * Usage: mdw [phys] <address> [<count>] - for 32 bit reads
4509 * mdh [phys] <address> [<count>] - for 16 bit reads
4510 * mdb [phys] <address> [<count>] - for 8 bit reads
4512 * Count defaults to 1.
4514 * Calls target_read_memory or target_read_phys_memory depending on
4515 * the presence of the "phys" argument
4516 * Reads the target memory in blocks of max. 32 bytes, and returns an array of ints formatted
4517 * to int representation in base16.
4518 * Also outputs read data in a human readable form using command_print
4520 * @param phys if present target_read_phys_memory will be used instead of target_read_memory
4521 * @param address address where to start the read. May be specified in decimal or hex using the standard "0x" prefix
4522 * @param count optional count parameter to read an array of values. If not specified, defaults to 1.
4523 * @returns: JIM_ERR on error or JIM_OK on success and sets the result string to an array of ascii formatted numbers
4524 * on success, with [<count>] number of elements.
4526 * In case of little endian target:
4527 * Example1: "mdw 0x00000000" returns "10123456"
4528 * Exmaple2: "mdh 0x00000000 1" returns "3456"
4529 * Example3: "mdb 0x00000000" returns "56"
4530 * Example4: "mdh 0x00000000 2" returns "3456 1012"
4531 * Example5: "mdb 0x00000000 3" returns "56 34 12"
4533 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4535 const char *cmd_name = Jim_GetString(argv[0], NULL);
4537 Jim_GetOptInfo goi;
4538 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4540 if ((goi.argc < 1) || (goi.argc > 3)) {
4541 Jim_SetResultFormatted(goi.interp,
4542 "usage: %s [phys] <address> [<count>]", cmd_name);
4543 return JIM_ERR;
4546 int (*fn)(struct target *target,
4547 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4548 fn = target_read_memory;
4550 int e;
4551 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4552 /* consume it */
4553 struct Jim_Obj *obj;
4554 e = Jim_GetOpt_Obj(&goi, &obj);
4555 if (e != JIM_OK)
4556 return e;
4558 fn = target_read_phys_memory;
4561 /* Read address parameter */
4562 jim_wide addr;
4563 e = Jim_GetOpt_Wide(&goi, &addr);
4564 if (e != JIM_OK)
4565 return JIM_ERR;
4567 /* If next parameter exists, read it out as the count parameter, if not, set it to 1 (default) */
4568 jim_wide count;
4569 if (goi.argc == 1) {
4570 e = Jim_GetOpt_Wide(&goi, &count);
4571 if (e != JIM_OK)
4572 return JIM_ERR;
4573 } else
4574 count = 1;
4576 /* all args must be consumed */
4577 if (goi.argc != 0)
4578 return JIM_ERR;
4580 jim_wide dwidth = 1; /* shut up gcc */
4581 if (strcasecmp(cmd_name, "mdw") == 0)
4582 dwidth = 4;
4583 else if (strcasecmp(cmd_name, "mdh") == 0)
4584 dwidth = 2;
4585 else if (strcasecmp(cmd_name, "mdb") == 0)
4586 dwidth = 1;
4587 else {
4588 LOG_ERROR("command '%s' unknown: ", cmd_name);
4589 return JIM_ERR;
4592 /* convert count to "bytes" */
4593 int bytes = count * dwidth;
4595 struct target *target = Jim_CmdPrivData(goi.interp);
4596 uint8_t target_buf[32];
4597 jim_wide x, y, z;
4598 while (bytes > 0) {
4599 y = (bytes < 16) ? bytes : 16; /* y = min(bytes, 16); */
4601 /* Try to read out next block */
4602 e = fn(target, addr, dwidth, y / dwidth, target_buf);
4604 if (e != ERROR_OK) {
4605 Jim_SetResultFormatted(interp, "error reading target @ 0x%08lx", (long)addr);
4606 return JIM_ERR;
4609 command_print_sameline(NULL, "0x%08x ", (int)(addr));
4610 switch (dwidth) {
4611 case 4:
4612 for (x = 0; x < 16 && x < y; x += 4) {
4613 z = target_buffer_get_u32(target, &(target_buf[x]));
4614 command_print_sameline(NULL, "%08x ", (int)(z));
4616 for (; (x < 16) ; x += 4)
4617 command_print_sameline(NULL, " ");
4618 break;
4619 case 2:
4620 for (x = 0; x < 16 && x < y; x += 2) {
4621 z = target_buffer_get_u16(target, &(target_buf[x]));
4622 command_print_sameline(NULL, "%04x ", (int)(z));
4624 for (; (x < 16) ; x += 2)
4625 command_print_sameline(NULL, " ");
4626 break;
4627 case 1:
4628 default:
4629 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4630 z = target_buffer_get_u8(target, &(target_buf[x]));
4631 command_print_sameline(NULL, "%02x ", (int)(z));
4633 for (; (x < 16) ; x += 1)
4634 command_print_sameline(NULL, " ");
4635 break;
4637 /* ascii-ify the bytes */
4638 for (x = 0 ; x < y ; x++) {
4639 if ((target_buf[x] >= 0x20) &&
4640 (target_buf[x] <= 0x7e)) {
4641 /* good */
4642 } else {
4643 /* smack it */
4644 target_buf[x] = '.';
4647 /* space pad */
4648 while (x < 16) {
4649 target_buf[x] = ' ';
4650 x++;
4652 /* terminate */
4653 target_buf[16] = 0;
4654 /* print - with a newline */
4655 command_print_sameline(NULL, "%s\n", target_buf);
4656 /* NEXT... */
4657 bytes -= 16;
4658 addr += 16;
4660 return JIM_OK;
4663 static int jim_target_mem2array(Jim_Interp *interp,
4664 int argc, Jim_Obj *const *argv)
4666 struct target *target = Jim_CmdPrivData(interp);
4667 return target_mem2array(interp, target, argc - 1, argv + 1);
4670 static int jim_target_array2mem(Jim_Interp *interp,
4671 int argc, Jim_Obj *const *argv)
4673 struct target *target = Jim_CmdPrivData(interp);
4674 return target_array2mem(interp, target, argc - 1, argv + 1);
4677 static int jim_target_tap_disabled(Jim_Interp *interp)
4679 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4680 return JIM_ERR;
4683 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4685 if (argc != 1) {
4686 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4687 return JIM_ERR;
4689 struct target *target = Jim_CmdPrivData(interp);
4690 if (!target->tap->enabled)
4691 return jim_target_tap_disabled(interp);
4693 int e = target->type->examine(target);
4694 if (e != ERROR_OK)
4695 return JIM_ERR;
4696 return JIM_OK;
4699 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4701 if (argc != 1) {
4702 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4703 return JIM_ERR;
4705 struct target *target = Jim_CmdPrivData(interp);
4707 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4708 return JIM_ERR;
4710 return JIM_OK;
4713 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4715 if (argc != 1) {
4716 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4717 return JIM_ERR;
4719 struct target *target = Jim_CmdPrivData(interp);
4720 if (!target->tap->enabled)
4721 return jim_target_tap_disabled(interp);
4723 int e;
4724 if (!(target_was_examined(target)))
4725 e = ERROR_TARGET_NOT_EXAMINED;
4726 else
4727 e = target->type->poll(target);
4728 if (e != ERROR_OK)
4729 return JIM_ERR;
4730 return JIM_OK;
4733 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4735 Jim_GetOptInfo goi;
4736 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4738 if (goi.argc != 2) {
4739 Jim_WrongNumArgs(interp, 0, argv,
4740 "([tT]|[fF]|assert|deassert) BOOL");
4741 return JIM_ERR;
4744 Jim_Nvp *n;
4745 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4746 if (e != JIM_OK) {
4747 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4748 return e;
4750 /* the halt or not param */
4751 jim_wide a;
4752 e = Jim_GetOpt_Wide(&goi, &a);
4753 if (e != JIM_OK)
4754 return e;
4756 struct target *target = Jim_CmdPrivData(goi.interp);
4757 if (!target->tap->enabled)
4758 return jim_target_tap_disabled(interp);
4759 if (!(target_was_examined(target))) {
4760 LOG_ERROR("Target not examined yet");
4761 return ERROR_TARGET_NOT_EXAMINED;
4763 if (!target->type->assert_reset || !target->type->deassert_reset) {
4764 Jim_SetResultFormatted(interp,
4765 "No target-specific reset for %s",
4766 target_name(target));
4767 return JIM_ERR;
4769 /* determine if we should halt or not. */
4770 target->reset_halt = !!a;
4771 /* When this happens - all workareas are invalid. */
4772 target_free_all_working_areas_restore(target, 0);
4774 /* do the assert */
4775 if (n->value == NVP_ASSERT)
4776 e = target->type->assert_reset(target);
4777 else
4778 e = target->type->deassert_reset(target);
4779 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4782 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4784 if (argc != 1) {
4785 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4786 return JIM_ERR;
4788 struct target *target = Jim_CmdPrivData(interp);
4789 if (!target->tap->enabled)
4790 return jim_target_tap_disabled(interp);
4791 int e = target->type->halt(target);
4792 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4795 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4797 Jim_GetOptInfo goi;
4798 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4800 /* params: <name> statename timeoutmsecs */
4801 if (goi.argc != 2) {
4802 const char *cmd_name = Jim_GetString(argv[0], NULL);
4803 Jim_SetResultFormatted(goi.interp,
4804 "%s <state_name> <timeout_in_msec>", cmd_name);
4805 return JIM_ERR;
4808 Jim_Nvp *n;
4809 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4810 if (e != JIM_OK) {
4811 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
4812 return e;
4814 jim_wide a;
4815 e = Jim_GetOpt_Wide(&goi, &a);
4816 if (e != JIM_OK)
4817 return e;
4818 struct target *target = Jim_CmdPrivData(interp);
4819 if (!target->tap->enabled)
4820 return jim_target_tap_disabled(interp);
4822 e = target_wait_state(target, n->value, a);
4823 if (e != ERROR_OK) {
4824 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4825 Jim_SetResultFormatted(goi.interp,
4826 "target: %s wait %s fails (%#s) %s",
4827 target_name(target), n->name,
4828 eObj, target_strerror_safe(e));
4829 Jim_FreeNewObj(interp, eObj);
4830 return JIM_ERR;
4832 return JIM_OK;
4834 /* List for human, Events defined for this target.
4835 * scripts/programs should use 'name cget -event NAME'
4837 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4839 struct command_context *cmd_ctx = current_command_context(interp);
4840 assert(cmd_ctx != NULL);
4842 struct target *target = Jim_CmdPrivData(interp);
4843 struct target_event_action *teap = target->event_action;
4844 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4845 target->target_number,
4846 target_name(target));
4847 command_print(cmd_ctx, "%-25s | Body", "Event");
4848 command_print(cmd_ctx, "------------------------- | "
4849 "----------------------------------------");
4850 while (teap) {
4851 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4852 command_print(cmd_ctx, "%-25s | %s",
4853 opt->name, Jim_GetString(teap->body, NULL));
4854 teap = teap->next;
4856 command_print(cmd_ctx, "***END***");
4857 return JIM_OK;
4859 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4861 if (argc != 1) {
4862 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4863 return JIM_ERR;
4865 struct target *target = Jim_CmdPrivData(interp);
4866 Jim_SetResultString(interp, target_state_name(target), -1);
4867 return JIM_OK;
4869 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4871 Jim_GetOptInfo goi;
4872 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4873 if (goi.argc != 1) {
4874 const char *cmd_name = Jim_GetString(argv[0], NULL);
4875 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4876 return JIM_ERR;
4878 Jim_Nvp *n;
4879 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4880 if (e != JIM_OK) {
4881 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4882 return e;
4884 struct target *target = Jim_CmdPrivData(interp);
4885 target_handle_event(target, n->value);
4886 return JIM_OK;
4889 static const struct command_registration target_instance_command_handlers[] = {
4891 .name = "configure",
4892 .mode = COMMAND_CONFIG,
4893 .jim_handler = jim_target_configure,
4894 .help = "configure a new target for use",
4895 .usage = "[target_attribute ...]",
4898 .name = "cget",
4899 .mode = COMMAND_ANY,
4900 .jim_handler = jim_target_configure,
4901 .help = "returns the specified target attribute",
4902 .usage = "target_attribute",
4905 .name = "mww",
4906 .mode = COMMAND_EXEC,
4907 .jim_handler = jim_target_mw,
4908 .help = "Write 32-bit word(s) to target memory",
4909 .usage = "address data [count]",
4912 .name = "mwh",
4913 .mode = COMMAND_EXEC,
4914 .jim_handler = jim_target_mw,
4915 .help = "Write 16-bit half-word(s) to target memory",
4916 .usage = "address data [count]",
4919 .name = "mwb",
4920 .mode = COMMAND_EXEC,
4921 .jim_handler = jim_target_mw,
4922 .help = "Write byte(s) to target memory",
4923 .usage = "address data [count]",
4926 .name = "mdw",
4927 .mode = COMMAND_EXEC,
4928 .jim_handler = jim_target_md,
4929 .help = "Display target memory as 32-bit words",
4930 .usage = "address [count]",
4933 .name = "mdh",
4934 .mode = COMMAND_EXEC,
4935 .jim_handler = jim_target_md,
4936 .help = "Display target memory as 16-bit half-words",
4937 .usage = "address [count]",
4940 .name = "mdb",
4941 .mode = COMMAND_EXEC,
4942 .jim_handler = jim_target_md,
4943 .help = "Display target memory as 8-bit bytes",
4944 .usage = "address [count]",
4947 .name = "array2mem",
4948 .mode = COMMAND_EXEC,
4949 .jim_handler = jim_target_array2mem,
4950 .help = "Writes Tcl array of 8/16/32 bit numbers "
4951 "to target memory",
4952 .usage = "arrayname bitwidth address count",
4955 .name = "mem2array",
4956 .mode = COMMAND_EXEC,
4957 .jim_handler = jim_target_mem2array,
4958 .help = "Loads Tcl array of 8/16/32 bit numbers "
4959 "from target memory",
4960 .usage = "arrayname bitwidth address count",
4963 .name = "eventlist",
4964 .mode = COMMAND_EXEC,
4965 .jim_handler = jim_target_event_list,
4966 .help = "displays a table of events defined for this target",
4969 .name = "curstate",
4970 .mode = COMMAND_EXEC,
4971 .jim_handler = jim_target_current_state,
4972 .help = "displays the current state of this target",
4975 .name = "arp_examine",
4976 .mode = COMMAND_EXEC,
4977 .jim_handler = jim_target_examine,
4978 .help = "used internally for reset processing",
4981 .name = "arp_halt_gdb",
4982 .mode = COMMAND_EXEC,
4983 .jim_handler = jim_target_halt_gdb,
4984 .help = "used internally for reset processing to halt GDB",
4987 .name = "arp_poll",
4988 .mode = COMMAND_EXEC,
4989 .jim_handler = jim_target_poll,
4990 .help = "used internally for reset processing",
4993 .name = "arp_reset",
4994 .mode = COMMAND_EXEC,
4995 .jim_handler = jim_target_reset,
4996 .help = "used internally for reset processing",
4999 .name = "arp_halt",
5000 .mode = COMMAND_EXEC,
5001 .jim_handler = jim_target_halt,
5002 .help = "used internally for reset processing",
5005 .name = "arp_waitstate",
5006 .mode = COMMAND_EXEC,
5007 .jim_handler = jim_target_wait_state,
5008 .help = "used internally for reset processing",
5011 .name = "invoke-event",
5012 .mode = COMMAND_EXEC,
5013 .jim_handler = jim_target_invoke_event,
5014 .help = "invoke handler for specified event",
5015 .usage = "event_name",
5017 COMMAND_REGISTRATION_DONE
5020 static int target_create(Jim_GetOptInfo *goi)
5022 Jim_Obj *new_cmd;
5023 Jim_Cmd *cmd;
5024 const char *cp;
5025 char *cp2;
5026 int e;
5027 int x;
5028 struct target *target;
5029 struct command_context *cmd_ctx;
5031 cmd_ctx = current_command_context(goi->interp);
5032 assert(cmd_ctx != NULL);
5034 if (goi->argc < 3) {
5035 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5036 return JIM_ERR;
5039 /* COMMAND */
5040 Jim_GetOpt_Obj(goi, &new_cmd);
5041 /* does this command exist? */
5042 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
5043 if (cmd) {
5044 cp = Jim_GetString(new_cmd, NULL);
5045 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5046 return JIM_ERR;
5049 /* TYPE */
5050 e = Jim_GetOpt_String(goi, &cp2, NULL);
5051 if (e != JIM_OK)
5052 return e;
5053 cp = cp2;
5054 /* now does target type exist */
5055 for (x = 0 ; target_types[x] ; x++) {
5056 if (0 == strcmp(cp, target_types[x]->name)) {
5057 /* found */
5058 break;
5061 /* check for deprecated name */
5062 if (target_types[x]->deprecated_name) {
5063 if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
5064 /* found */
5065 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
5066 break;
5070 if (target_types[x] == NULL) {
5071 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5072 for (x = 0 ; target_types[x] ; x++) {
5073 if (target_types[x + 1]) {
5074 Jim_AppendStrings(goi->interp,
5075 Jim_GetResult(goi->interp),
5076 target_types[x]->name,
5077 ", ", NULL);
5078 } else {
5079 Jim_AppendStrings(goi->interp,
5080 Jim_GetResult(goi->interp),
5081 " or ",
5082 target_types[x]->name, NULL);
5085 return JIM_ERR;
5088 /* Create it */
5089 target = calloc(1, sizeof(struct target));
5090 /* set target number */
5091 target->target_number = new_target_number();
5093 /* allocate memory for each unique target type */
5094 target->type = (struct target_type *)calloc(1, sizeof(struct target_type));
5096 memcpy(target->type, target_types[x], sizeof(struct target_type));
5098 /* will be set by "-endian" */
5099 target->endianness = TARGET_ENDIAN_UNKNOWN;
5101 /* default to first core, override with -coreid */
5102 target->coreid = 0;
5104 target->working_area = 0x0;
5105 target->working_area_size = 0x0;
5106 target->working_areas = NULL;
5107 target->backup_working_area = 0;
5109 target->state = TARGET_UNKNOWN;
5110 target->debug_reason = DBG_REASON_UNDEFINED;
5111 target->reg_cache = NULL;
5112 target->breakpoints = NULL;
5113 target->watchpoints = NULL;
5114 target->next = NULL;
5115 target->arch_info = NULL;
5117 target->display = 1;
5119 target->halt_issued = false;
5121 /* initialize trace information */
5122 target->trace_info = malloc(sizeof(struct trace));
5123 target->trace_info->num_trace_points = 0;
5124 target->trace_info->trace_points_size = 0;
5125 target->trace_info->trace_points = NULL;
5126 target->trace_info->trace_history_size = 0;
5127 target->trace_info->trace_history = NULL;
5128 target->trace_info->trace_history_pos = 0;
5129 target->trace_info->trace_history_overflowed = 0;
5131 target->dbgmsg = NULL;
5132 target->dbg_msg_enabled = 0;
5134 target->endianness = TARGET_ENDIAN_UNKNOWN;
5136 target->rtos = NULL;
5137 target->rtos_auto_detect = false;
5139 /* Do the rest as "configure" options */
5140 goi->isconfigure = 1;
5141 e = target_configure(goi, target);
5143 if (target->tap == NULL) {
5144 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
5145 e = JIM_ERR;
5148 if (e != JIM_OK) {
5149 free(target->type);
5150 free(target);
5151 return e;
5154 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5155 /* default endian to little if not specified */
5156 target->endianness = TARGET_LITTLE_ENDIAN;
5159 /* incase variant is not set */
5160 if (!target->variant)
5161 target->variant = strdup("");
5163 cp = Jim_GetString(new_cmd, NULL);
5164 target->cmd_name = strdup(cp);
5166 /* create the target specific commands */
5167 if (target->type->commands) {
5168 e = register_commands(cmd_ctx, NULL, target->type->commands);
5169 if (ERROR_OK != e)
5170 LOG_ERROR("unable to register '%s' commands", cp);
5172 if (target->type->target_create)
5173 (*(target->type->target_create))(target, goi->interp);
5175 /* append to end of list */
5177 struct target **tpp;
5178 tpp = &(all_targets);
5179 while (*tpp)
5180 tpp = &((*tpp)->next);
5181 *tpp = target;
5184 /* now - create the new target name command */
5185 const struct command_registration target_subcommands[] = {
5187 .chain = target_instance_command_handlers,
5190 .chain = target->type->commands,
5192 COMMAND_REGISTRATION_DONE
5194 const struct command_registration target_commands[] = {
5196 .name = cp,
5197 .mode = COMMAND_ANY,
5198 .help = "target command group",
5199 .usage = "",
5200 .chain = target_subcommands,
5202 COMMAND_REGISTRATION_DONE
5204 e = register_commands(cmd_ctx, NULL, target_commands);
5205 if (ERROR_OK != e)
5206 return JIM_ERR;
5208 struct command *c = command_find_in_context(cmd_ctx, cp);
5209 assert(c);
5210 command_set_handler_data(c, target);
5212 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5215 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5217 if (argc != 1) {
5218 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5219 return JIM_ERR;
5221 struct command_context *cmd_ctx = current_command_context(interp);
5222 assert(cmd_ctx != NULL);
5224 Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5225 return JIM_OK;
5228 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5230 if (argc != 1) {
5231 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5232 return JIM_ERR;
5234 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5235 for (unsigned x = 0; NULL != target_types[x]; x++) {
5236 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5237 Jim_NewStringObj(interp, target_types[x]->name, -1));
5239 return JIM_OK;
5242 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5244 if (argc != 1) {
5245 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5246 return JIM_ERR;
5248 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5249 struct target *target = all_targets;
5250 while (target) {
5251 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5252 Jim_NewStringObj(interp, target_name(target), -1));
5253 target = target->next;
5255 return JIM_OK;
5258 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5260 int i;
5261 const char *targetname;
5262 int retval, len;
5263 struct target *target = (struct target *) NULL;
5264 struct target_list *head, *curr, *new;
5265 curr = (struct target_list *) NULL;
5266 head = (struct target_list *) NULL;
5268 retval = 0;
5269 LOG_DEBUG("%d", argc);
5270 /* argv[1] = target to associate in smp
5271 * argv[2] = target to assoicate in smp
5272 * argv[3] ...
5275 for (i = 1; i < argc; i++) {
5277 targetname = Jim_GetString(argv[i], &len);
5278 target = get_target(targetname);
5279 LOG_DEBUG("%s ", targetname);
5280 if (target) {
5281 new = malloc(sizeof(struct target_list));
5282 new->target = target;
5283 new->next = (struct target_list *)NULL;
5284 if (head == (struct target_list *)NULL) {
5285 head = new;
5286 curr = head;
5287 } else {
5288 curr->next = new;
5289 curr = new;
5293 /* now parse the list of cpu and put the target in smp mode*/
5294 curr = head;
5296 while (curr != (struct target_list *)NULL) {
5297 target = curr->target;
5298 target->smp = 1;
5299 target->head = head;
5300 curr = curr->next;
5303 if (target && target->rtos)
5304 retval = rtos_smp_init(head->target);
5306 return retval;
5310 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5312 Jim_GetOptInfo goi;
5313 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5314 if (goi.argc < 3) {
5315 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5316 "<name> <target_type> [<target_options> ...]");
5317 return JIM_ERR;
5319 return target_create(&goi);
5322 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5324 Jim_GetOptInfo goi;
5325 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5327 /* It's OK to remove this mechanism sometime after August 2010 or so */
5328 LOG_WARNING("don't use numbers as target identifiers; use names");
5329 if (goi.argc != 1) {
5330 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
5331 return JIM_ERR;
5333 jim_wide w;
5334 int e = Jim_GetOpt_Wide(&goi, &w);
5335 if (e != JIM_OK)
5336 return JIM_ERR;
5338 struct target *target;
5339 for (target = all_targets; NULL != target; target = target->next) {
5340 if (target->target_number != w)
5341 continue;
5343 Jim_SetResultString(goi.interp, target_name(target), -1);
5344 return JIM_OK;
5347 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
5348 Jim_SetResultFormatted(goi.interp,
5349 "Target: number %#s does not exist", wObj);
5350 Jim_FreeNewObj(interp, wObj);
5352 return JIM_ERR;
5355 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5357 if (argc != 1) {
5358 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
5359 return JIM_ERR;
5361 unsigned count = 0;
5362 struct target *target = all_targets;
5363 while (NULL != target) {
5364 target = target->next;
5365 count++;
5367 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
5368 return JIM_OK;
5371 static const struct command_registration target_subcommand_handlers[] = {
5373 .name = "init",
5374 .mode = COMMAND_CONFIG,
5375 .handler = handle_target_init_command,
5376 .help = "initialize targets",
5379 .name = "create",
5380 /* REVISIT this should be COMMAND_CONFIG ... */
5381 .mode = COMMAND_ANY,
5382 .jim_handler = jim_target_create,
5383 .usage = "name type '-chain-position' name [options ...]",
5384 .help = "Creates and selects a new target",
5387 .name = "current",
5388 .mode = COMMAND_ANY,
5389 .jim_handler = jim_target_current,
5390 .help = "Returns the currently selected target",
5393 .name = "types",
5394 .mode = COMMAND_ANY,
5395 .jim_handler = jim_target_types,
5396 .help = "Returns the available target types as "
5397 "a list of strings",
5400 .name = "names",
5401 .mode = COMMAND_ANY,
5402 .jim_handler = jim_target_names,
5403 .help = "Returns the names of all targets as a list of strings",
5406 .name = "number",
5407 .mode = COMMAND_ANY,
5408 .jim_handler = jim_target_number,
5409 .usage = "number",
5410 .help = "Returns the name of the numbered target "
5411 "(DEPRECATED)",
5414 .name = "count",
5415 .mode = COMMAND_ANY,
5416 .jim_handler = jim_target_count,
5417 .help = "Returns the number of targets as an integer "
5418 "(DEPRECATED)",
5421 .name = "smp",
5422 .mode = COMMAND_ANY,
5423 .jim_handler = jim_target_smp,
5424 .usage = "targetname1 targetname2 ...",
5425 .help = "gather several target in a smp list"
5428 COMMAND_REGISTRATION_DONE
5431 struct FastLoad {
5432 uint32_t address;
5433 uint8_t *data;
5434 int length;
5438 static int fastload_num;
5439 static struct FastLoad *fastload;
5441 static void free_fastload(void)
5443 if (fastload != NULL) {
5444 int i;
5445 for (i = 0; i < fastload_num; i++) {
5446 if (fastload[i].data)
5447 free(fastload[i].data);
5449 free(fastload);
5450 fastload = NULL;
5454 COMMAND_HANDLER(handle_fast_load_image_command)
5456 uint8_t *buffer;
5457 size_t buf_cnt;
5458 uint32_t image_size;
5459 uint32_t min_address = 0;
5460 uint32_t max_address = 0xffffffff;
5461 int i;
5463 struct image image;
5465 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5466 &image, &min_address, &max_address);
5467 if (ERROR_OK != retval)
5468 return retval;
5470 struct duration bench;
5471 duration_start(&bench);
5473 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5474 if (retval != ERROR_OK)
5475 return retval;
5477 image_size = 0x0;
5478 retval = ERROR_OK;
5479 fastload_num = image.num_sections;
5480 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
5481 if (fastload == NULL) {
5482 command_print(CMD_CTX, "out of memory");
5483 image_close(&image);
5484 return ERROR_FAIL;
5486 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5487 for (i = 0; i < image.num_sections; i++) {
5488 buffer = malloc(image.sections[i].size);
5489 if (buffer == NULL) {
5490 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5491 (int)(image.sections[i].size));
5492 retval = ERROR_FAIL;
5493 break;
5496 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5497 if (retval != ERROR_OK) {
5498 free(buffer);
5499 break;
5502 uint32_t offset = 0;
5503 uint32_t length = buf_cnt;
5505 /* DANGER!!! beware of unsigned comparision here!!! */
5507 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5508 (image.sections[i].base_address < max_address)) {
5509 if (image.sections[i].base_address < min_address) {
5510 /* clip addresses below */
5511 offset += min_address-image.sections[i].base_address;
5512 length -= offset;
5515 if (image.sections[i].base_address + buf_cnt > max_address)
5516 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5518 fastload[i].address = image.sections[i].base_address + offset;
5519 fastload[i].data = malloc(length);
5520 if (fastload[i].data == NULL) {
5521 free(buffer);
5522 command_print(CMD_CTX, "error allocating buffer for section (%" PRIu32 " bytes)",
5523 length);
5524 retval = ERROR_FAIL;
5525 break;
5527 memcpy(fastload[i].data, buffer + offset, length);
5528 fastload[i].length = length;
5530 image_size += length;
5531 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5532 (unsigned int)length,
5533 ((unsigned int)(image.sections[i].base_address + offset)));
5536 free(buffer);
5539 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5540 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5541 "in %fs (%0.3f KiB/s)", image_size,
5542 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5544 command_print(CMD_CTX,
5545 "WARNING: image has not been loaded to target!"
5546 "You can issue a 'fast_load' to finish loading.");
5549 image_close(&image);
5551 if (retval != ERROR_OK)
5552 free_fastload();
5554 return retval;
5557 COMMAND_HANDLER(handle_fast_load_command)
5559 if (CMD_ARGC > 0)
5560 return ERROR_COMMAND_SYNTAX_ERROR;
5561 if (fastload == NULL) {
5562 LOG_ERROR("No image in memory");
5563 return ERROR_FAIL;
5565 int i;
5566 int ms = timeval_ms();
5567 int size = 0;
5568 int retval = ERROR_OK;
5569 for (i = 0; i < fastload_num; i++) {
5570 struct target *target = get_current_target(CMD_CTX);
5571 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5572 (unsigned int)(fastload[i].address),
5573 (unsigned int)(fastload[i].length));
5574 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5575 if (retval != ERROR_OK)
5576 break;
5577 size += fastload[i].length;
5579 if (retval == ERROR_OK) {
5580 int after = timeval_ms();
5581 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5583 return retval;
5586 static const struct command_registration target_command_handlers[] = {
5588 .name = "targets",
5589 .handler = handle_targets_command,
5590 .mode = COMMAND_ANY,
5591 .help = "change current default target (one parameter) "
5592 "or prints table of all targets (no parameters)",
5593 .usage = "[target]",
5596 .name = "target",
5597 .mode = COMMAND_CONFIG,
5598 .help = "configure target",
5600 .chain = target_subcommand_handlers,
5602 COMMAND_REGISTRATION_DONE
5605 int target_register_commands(struct command_context *cmd_ctx)
5607 return register_commands(cmd_ctx, NULL, target_command_handlers);
5610 static bool target_reset_nag = true;
5612 bool get_target_reset_nag(void)
5614 return target_reset_nag;
5617 COMMAND_HANDLER(handle_target_reset_nag)
5619 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5620 &target_reset_nag, "Nag after each reset about options to improve "
5621 "performance");
5624 COMMAND_HANDLER(handle_ps_command)
5626 struct target *target = get_current_target(CMD_CTX);
5627 char *display;
5628 if (target->state != TARGET_HALTED) {
5629 LOG_INFO("target not halted !!");
5630 return ERROR_OK;
5633 if ((target->rtos) && (target->rtos->type)
5634 && (target->rtos->type->ps_command)) {
5635 display = target->rtos->type->ps_command(target);
5636 command_print(CMD_CTX, "%s", display);
5637 free(display);
5638 return ERROR_OK;
5639 } else {
5640 LOG_INFO("failed");
5641 return ERROR_TARGET_FAILURE;
5645 static const struct command_registration target_exec_command_handlers[] = {
5647 .name = "fast_load_image",
5648 .handler = handle_fast_load_image_command,
5649 .mode = COMMAND_ANY,
5650 .help = "Load image into server memory for later use by "
5651 "fast_load; primarily for profiling",
5652 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5653 "[min_address [max_length]]",
5656 .name = "fast_load",
5657 .handler = handle_fast_load_command,
5658 .mode = COMMAND_EXEC,
5659 .help = "loads active fast load image to current target "
5660 "- mainly for profiling purposes",
5661 .usage = "",
5664 .name = "profile",
5665 .handler = handle_profile_command,
5666 .mode = COMMAND_EXEC,
5667 .usage = "seconds filename [start end]",
5668 .help = "profiling samples the CPU PC",
5670 /** @todo don't register virt2phys() unless target supports it */
5672 .name = "virt2phys",
5673 .handler = handle_virt2phys_command,
5674 .mode = COMMAND_ANY,
5675 .help = "translate a virtual address into a physical address",
5676 .usage = "virtual_address",
5679 .name = "reg",
5680 .handler = handle_reg_command,
5681 .mode = COMMAND_EXEC,
5682 .help = "display or set a register; with no arguments, "
5683 "displays all registers and their values",
5684 .usage = "[(register_name|register_number) [value]]",
5687 .name = "poll",
5688 .handler = handle_poll_command,
5689 .mode = COMMAND_EXEC,
5690 .help = "poll target state; or reconfigure background polling",
5691 .usage = "['on'|'off']",
5694 .name = "wait_halt",
5695 .handler = handle_wait_halt_command,
5696 .mode = COMMAND_EXEC,
5697 .help = "wait up to the specified number of milliseconds "
5698 "(default 5000) for a previously requested halt",
5699 .usage = "[milliseconds]",
5702 .name = "halt",
5703 .handler = handle_halt_command,
5704 .mode = COMMAND_EXEC,
5705 .help = "request target to halt, then wait up to the specified"
5706 "number of milliseconds (default 5000) for it to complete",
5707 .usage = "[milliseconds]",
5710 .name = "resume",
5711 .handler = handle_resume_command,
5712 .mode = COMMAND_EXEC,
5713 .help = "resume target execution from current PC or address",
5714 .usage = "[address]",
5717 .name = "reset",
5718 .handler = handle_reset_command,
5719 .mode = COMMAND_EXEC,
5720 .usage = "[run|halt|init]",
5721 .help = "Reset all targets into the specified mode."
5722 "Default reset mode is run, if not given.",
5725 .name = "soft_reset_halt",
5726 .handler = handle_soft_reset_halt_command,
5727 .mode = COMMAND_EXEC,
5728 .usage = "",
5729 .help = "halt the target and do a soft reset",
5732 .name = "step",
5733 .handler = handle_step_command,
5734 .mode = COMMAND_EXEC,
5735 .help = "step one instruction from current PC or address",
5736 .usage = "[address]",
5739 .name = "mdw",
5740 .handler = handle_md_command,
5741 .mode = COMMAND_EXEC,
5742 .help = "display memory words",
5743 .usage = "['phys'] address [count]",
5746 .name = "mdh",
5747 .handler = handle_md_command,
5748 .mode = COMMAND_EXEC,
5749 .help = "display memory half-words",
5750 .usage = "['phys'] address [count]",
5753 .name = "mdb",
5754 .handler = handle_md_command,
5755 .mode = COMMAND_EXEC,
5756 .help = "display memory bytes",
5757 .usage = "['phys'] address [count]",
5760 .name = "mww",
5761 .handler = handle_mw_command,
5762 .mode = COMMAND_EXEC,
5763 .help = "write memory word",
5764 .usage = "['phys'] address value [count]",
5767 .name = "mwh",
5768 .handler = handle_mw_command,
5769 .mode = COMMAND_EXEC,
5770 .help = "write memory half-word",
5771 .usage = "['phys'] address value [count]",
5774 .name = "mwb",
5775 .handler = handle_mw_command,
5776 .mode = COMMAND_EXEC,
5777 .help = "write memory byte",
5778 .usage = "['phys'] address value [count]",
5781 .name = "bp",
5782 .handler = handle_bp_command,
5783 .mode = COMMAND_EXEC,
5784 .help = "list or set hardware or software breakpoint",
5785 .usage = "<address> [<asid>]<length> ['hw'|'hw_ctx']",
5788 .name = "rbp",
5789 .handler = handle_rbp_command,
5790 .mode = COMMAND_EXEC,
5791 .help = "remove breakpoint",
5792 .usage = "address",
5795 .name = "wp",
5796 .handler = handle_wp_command,
5797 .mode = COMMAND_EXEC,
5798 .help = "list (no params) or create watchpoints",
5799 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5802 .name = "rwp",
5803 .handler = handle_rwp_command,
5804 .mode = COMMAND_EXEC,
5805 .help = "remove watchpoint",
5806 .usage = "address",
5809 .name = "load_image",
5810 .handler = handle_load_image_command,
5811 .mode = COMMAND_EXEC,
5812 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5813 "[min_address] [max_length]",
5816 .name = "dump_image",
5817 .handler = handle_dump_image_command,
5818 .mode = COMMAND_EXEC,
5819 .usage = "filename address size",
5822 .name = "verify_image",
5823 .handler = handle_verify_image_command,
5824 .mode = COMMAND_EXEC,
5825 .usage = "filename [offset [type]]",
5828 .name = "test_image",
5829 .handler = handle_test_image_command,
5830 .mode = COMMAND_EXEC,
5831 .usage = "filename [offset [type]]",
5834 .name = "mem2array",
5835 .mode = COMMAND_EXEC,
5836 .jim_handler = jim_mem2array,
5837 .help = "read 8/16/32 bit memory and return as a TCL array "
5838 "for script processing",
5839 .usage = "arrayname bitwidth address count",
5842 .name = "array2mem",
5843 .mode = COMMAND_EXEC,
5844 .jim_handler = jim_array2mem,
5845 .help = "convert a TCL array to memory locations "
5846 "and write the 8/16/32 bit values",
5847 .usage = "arrayname bitwidth address count",
5850 .name = "reset_nag",
5851 .handler = handle_target_reset_nag,
5852 .mode = COMMAND_ANY,
5853 .help = "Nag after each reset about options that could have been "
5854 "enabled to improve performance. ",
5855 .usage = "['enable'|'disable']",
5858 .name = "ps",
5859 .handler = handle_ps_command,
5860 .mode = COMMAND_EXEC,
5861 .help = "list all tasks ",
5862 .usage = " ",
5865 COMMAND_REGISTRATION_DONE
5867 static int target_register_user_commands(struct command_context *cmd_ctx)
5869 int retval = ERROR_OK;
5870 retval = target_request_register_commands(cmd_ctx);
5871 if (retval != ERROR_OK)
5872 return retval;
5874 retval = trace_register_commands(cmd_ctx);
5875 if (retval != ERROR_OK)
5876 return retval;
5879 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);