4a8d9aaafb91b2c5b183f309d59f003af524845f
[openocd.git] / src / target / target.c
blob4a8d9aaafb91b2c5b183f309d59f003af524845f
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 cortexm3_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;
105 static struct target_type *target_types[] = {
106 &arm7tdmi_target,
107 &arm9tdmi_target,
108 &arm920t_target,
109 &arm720t_target,
110 &arm966e_target,
111 &arm946e_target,
112 &arm926ejs_target,
113 &fa526_target,
114 &feroceon_target,
115 &dragonite_target,
116 &xscale_target,
117 &cortexm3_target,
118 &cortexa8_target,
119 &cortexr4_target,
120 &arm11_target,
121 &mips_m4k_target,
122 &avr_target,
123 &dsp563xx_target,
124 &dsp5680xx_target,
125 &testee_target,
126 &avr32_ap7k_target,
127 &hla_target,
128 &nds32_v2_target,
129 &nds32_v3_target,
130 &nds32_v3m_target,
131 NULL,
134 struct target *all_targets;
135 static struct target_event_callback *target_event_callbacks;
136 static struct target_timer_callback *target_timer_callbacks;
137 static const int polling_interval = 100;
139 static const Jim_Nvp nvp_assert[] = {
140 { .name = "assert", NVP_ASSERT },
141 { .name = "deassert", NVP_DEASSERT },
142 { .name = "T", NVP_ASSERT },
143 { .name = "F", NVP_DEASSERT },
144 { .name = "t", NVP_ASSERT },
145 { .name = "f", NVP_DEASSERT },
146 { .name = NULL, .value = -1 }
149 static const Jim_Nvp nvp_error_target[] = {
150 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
151 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
152 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
153 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
154 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
155 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
156 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
157 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
158 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
159 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
160 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
161 { .value = -1, .name = NULL }
164 static const char *target_strerror_safe(int err)
166 const Jim_Nvp *n;
168 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
169 if (n->name == NULL)
170 return "unknown";
171 else
172 return n->name;
175 static const Jim_Nvp nvp_target_event[] = {
177 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
178 { .value = TARGET_EVENT_HALTED, .name = "halted" },
179 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
180 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
181 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
183 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
184 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
186 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
187 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
188 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
189 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
190 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
191 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
192 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
193 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
194 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
195 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
196 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
197 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
199 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
200 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
202 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
203 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
205 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
206 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
208 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
209 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
211 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
212 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
214 { .name = NULL, .value = -1 }
217 static const Jim_Nvp nvp_target_state[] = {
218 { .name = "unknown", .value = TARGET_UNKNOWN },
219 { .name = "running", .value = TARGET_RUNNING },
220 { .name = "halted", .value = TARGET_HALTED },
221 { .name = "reset", .value = TARGET_RESET },
222 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
223 { .name = NULL, .value = -1 },
226 static const Jim_Nvp nvp_target_debug_reason[] = {
227 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
228 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
229 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
230 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
231 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
232 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
233 { .name = "program-exit" , .value = DBG_REASON_EXIT },
234 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
235 { .name = NULL, .value = -1 },
238 static const Jim_Nvp nvp_target_endian[] = {
239 { .name = "big", .value = TARGET_BIG_ENDIAN },
240 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
241 { .name = "be", .value = TARGET_BIG_ENDIAN },
242 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
243 { .name = NULL, .value = -1 },
246 static const Jim_Nvp nvp_reset_modes[] = {
247 { .name = "unknown", .value = RESET_UNKNOWN },
248 { .name = "run" , .value = RESET_RUN },
249 { .name = "halt" , .value = RESET_HALT },
250 { .name = "init" , .value = RESET_INIT },
251 { .name = NULL , .value = -1 },
254 const char *debug_reason_name(struct target *t)
256 const char *cp;
258 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
259 t->debug_reason)->name;
260 if (!cp) {
261 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
262 cp = "(*BUG*unknown*BUG*)";
264 return cp;
267 const char *target_state_name(struct target *t)
269 const char *cp;
270 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
271 if (!cp) {
272 LOG_ERROR("Invalid target state: %d", (int)(t->state));
273 cp = "(*BUG*unknown*BUG*)";
275 return cp;
278 /* determine the number of the new target */
279 static int new_target_number(void)
281 struct target *t;
282 int x;
284 /* number is 0 based */
285 x = -1;
286 t = all_targets;
287 while (t) {
288 if (x < t->target_number)
289 x = t->target_number;
290 t = t->next;
292 return x + 1;
295 /* read a uint32_t from a buffer in target memory endianness */
296 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
298 if (target->endianness == TARGET_LITTLE_ENDIAN)
299 return le_to_h_u32(buffer);
300 else
301 return be_to_h_u32(buffer);
304 /* read a uint24_t from a buffer in target memory endianness */
305 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
307 if (target->endianness == TARGET_LITTLE_ENDIAN)
308 return le_to_h_u24(buffer);
309 else
310 return be_to_h_u24(buffer);
313 /* read a uint16_t from a buffer in target memory endianness */
314 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
316 if (target->endianness == TARGET_LITTLE_ENDIAN)
317 return le_to_h_u16(buffer);
318 else
319 return be_to_h_u16(buffer);
322 /* read a uint8_t from a buffer in target memory endianness */
323 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
325 return *buffer & 0x0ff;
328 /* write a uint32_t to a buffer in target memory endianness */
329 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
331 if (target->endianness == TARGET_LITTLE_ENDIAN)
332 h_u32_to_le(buffer, value);
333 else
334 h_u32_to_be(buffer, value);
337 /* write a uint24_t to a buffer in target memory endianness */
338 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
340 if (target->endianness == TARGET_LITTLE_ENDIAN)
341 h_u24_to_le(buffer, value);
342 else
343 h_u24_to_be(buffer, value);
346 /* write a uint16_t to a buffer in target memory endianness */
347 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
349 if (target->endianness == TARGET_LITTLE_ENDIAN)
350 h_u16_to_le(buffer, value);
351 else
352 h_u16_to_be(buffer, value);
355 /* write a uint8_t to a buffer in target memory endianness */
356 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
358 *buffer = value;
361 /* write a uint32_t array to a buffer in target memory endianness */
362 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
364 uint32_t i;
365 for (i = 0; i < count; i++)
366 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
369 /* write a uint16_t array to a buffer in target memory endianness */
370 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
372 uint32_t i;
373 for (i = 0; i < count; i++)
374 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
377 /* write a uint32_t array to a buffer in target memory endianness */
378 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, uint32_t *srcbuf)
380 uint32_t i;
381 for (i = 0; i < count; i++)
382 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
385 /* write a uint16_t array to a buffer in target memory endianness */
386 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, uint16_t *srcbuf)
388 uint32_t i;
389 for (i = 0; i < count; i++)
390 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
393 /* return a pointer to a configured target; id is name or number */
394 struct target *get_target(const char *id)
396 struct target *target;
398 /* try as tcltarget name */
399 for (target = all_targets; target; target = target->next) {
400 if (target_name(target) == NULL)
401 continue;
402 if (strcmp(id, target_name(target)) == 0)
403 return target;
406 /* It's OK to remove this fallback sometime after August 2010 or so */
408 /* no match, try as number */
409 unsigned num;
410 if (parse_uint(id, &num) != ERROR_OK)
411 return NULL;
413 for (target = all_targets; target; target = target->next) {
414 if (target->target_number == (int)num) {
415 LOG_WARNING("use '%s' as target identifier, not '%u'",
416 target_name(target), num);
417 return target;
421 return NULL;
424 /* returns a pointer to the n-th configured target */
425 static struct target *get_target_by_num(int num)
427 struct target *target = all_targets;
429 while (target) {
430 if (target->target_number == num)
431 return target;
432 target = target->next;
435 return NULL;
438 struct target *get_current_target(struct command_context *cmd_ctx)
440 struct target *target = get_target_by_num(cmd_ctx->current_target);
442 if (target == NULL) {
443 LOG_ERROR("BUG: current_target out of bounds");
444 exit(-1);
447 return target;
450 int target_poll(struct target *target)
452 int retval;
454 /* We can't poll until after examine */
455 if (!target_was_examined(target)) {
456 /* Fail silently lest we pollute the log */
457 return ERROR_FAIL;
460 retval = target->type->poll(target);
461 if (retval != ERROR_OK)
462 return retval;
464 if (target->halt_issued) {
465 if (target->state == TARGET_HALTED)
466 target->halt_issued = false;
467 else {
468 long long t = timeval_ms() - target->halt_issued_time;
469 if (t > DEFAULT_HALT_TIMEOUT) {
470 target->halt_issued = false;
471 LOG_INFO("Halt timed out, wake up GDB.");
472 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
477 return ERROR_OK;
480 int target_halt(struct target *target)
482 int retval;
483 /* We can't poll until after examine */
484 if (!target_was_examined(target)) {
485 LOG_ERROR("Target not examined yet");
486 return ERROR_FAIL;
489 retval = target->type->halt(target);
490 if (retval != ERROR_OK)
491 return retval;
493 target->halt_issued = true;
494 target->halt_issued_time = timeval_ms();
496 return ERROR_OK;
500 * Make the target (re)start executing using its saved execution
501 * context (possibly with some modifications).
503 * @param target Which target should start executing.
504 * @param current True to use the target's saved program counter instead
505 * of the address parameter
506 * @param address Optionally used as the program counter.
507 * @param handle_breakpoints True iff breakpoints at the resumption PC
508 * should be skipped. (For example, maybe execution was stopped by
509 * such a breakpoint, in which case it would be counterprodutive to
510 * let it re-trigger.
511 * @param debug_execution False if all working areas allocated by OpenOCD
512 * should be released and/or restored to their original contents.
513 * (This would for example be true to run some downloaded "helper"
514 * algorithm code, which resides in one such working buffer and uses
515 * another for data storage.)
517 * @todo Resolve the ambiguity about what the "debug_execution" flag
518 * signifies. For example, Target implementations don't agree on how
519 * it relates to invalidation of the register cache, or to whether
520 * breakpoints and watchpoints should be enabled. (It would seem wrong
521 * to enable breakpoints when running downloaded "helper" algorithms
522 * (debug_execution true), since the breakpoints would be set to match
523 * target firmware being debugged, not the helper algorithm.... and
524 * enabling them could cause such helpers to malfunction (for example,
525 * by overwriting data with a breakpoint instruction. On the other
526 * hand the infrastructure for running such helpers might use this
527 * procedure but rely on hardware breakpoint to detect termination.)
529 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
531 int retval;
533 /* We can't poll until after examine */
534 if (!target_was_examined(target)) {
535 LOG_ERROR("Target not examined yet");
536 return ERROR_FAIL;
539 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
541 /* note that resume *must* be asynchronous. The CPU can halt before
542 * we poll. The CPU can even halt at the current PC as a result of
543 * a software breakpoint being inserted by (a bug?) the application.
545 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
546 if (retval != ERROR_OK)
547 return retval;
549 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
551 return retval;
554 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
556 char buf[100];
557 int retval;
558 Jim_Nvp *n;
559 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
560 if (n->name == NULL) {
561 LOG_ERROR("invalid reset mode");
562 return ERROR_FAIL;
565 /* disable polling during reset to make reset event scripts
566 * more predictable, i.e. dr/irscan & pathmove in events will
567 * not have JTAG operations injected into the middle of a sequence.
569 bool save_poll = jtag_poll_get_enabled();
571 jtag_poll_set_enabled(false);
573 sprintf(buf, "ocd_process_reset %s", n->name);
574 retval = Jim_Eval(cmd_ctx->interp, buf);
576 jtag_poll_set_enabled(save_poll);
578 if (retval != JIM_OK) {
579 Jim_MakeErrorMessage(cmd_ctx->interp);
580 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
581 return ERROR_FAIL;
584 /* We want any events to be processed before the prompt */
585 retval = target_call_timer_callbacks_now();
587 struct target *target;
588 for (target = all_targets; target; target = target->next) {
589 target->type->check_reset(target);
590 target->running_alg = false;
593 return retval;
596 static int identity_virt2phys(struct target *target,
597 uint32_t virtual, uint32_t *physical)
599 *physical = virtual;
600 return ERROR_OK;
603 static int no_mmu(struct target *target, int *enabled)
605 *enabled = 0;
606 return ERROR_OK;
609 static int default_examine(struct target *target)
611 target_set_examined(target);
612 return ERROR_OK;
615 /* no check by default */
616 static int default_check_reset(struct target *target)
618 return ERROR_OK;
621 int target_examine_one(struct target *target)
623 return target->type->examine(target);
626 static int jtag_enable_callback(enum jtag_event event, void *priv)
628 struct target *target = priv;
630 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
631 return ERROR_OK;
633 jtag_unregister_event_callback(jtag_enable_callback, target);
635 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
637 int retval = target_examine_one(target);
638 if (retval != ERROR_OK)
639 return retval;
641 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
643 return retval;
646 /* Targets that correctly implement init + examine, i.e.
647 * no communication with target during init:
649 * XScale
651 int target_examine(void)
653 int retval = ERROR_OK;
654 struct target *target;
656 for (target = all_targets; target; target = target->next) {
657 /* defer examination, but don't skip it */
658 if (!target->tap->enabled) {
659 jtag_register_event_callback(jtag_enable_callback,
660 target);
661 continue;
664 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
666 retval = target_examine_one(target);
667 if (retval != ERROR_OK)
668 return retval;
670 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
672 return retval;
675 const char *target_type_name(struct target *target)
677 return target->type->name;
680 static int target_soft_reset_halt(struct target *target)
682 if (!target_was_examined(target)) {
683 LOG_ERROR("Target not examined yet");
684 return ERROR_FAIL;
686 if (!target->type->soft_reset_halt) {
687 LOG_ERROR("Target %s does not support soft_reset_halt",
688 target_name(target));
689 return ERROR_FAIL;
691 return target->type->soft_reset_halt(target);
695 * Downloads a target-specific native code algorithm to the target,
696 * and executes it. * Note that some targets may need to set up, enable,
697 * and tear down a breakpoint (hard or * soft) to detect algorithm
698 * termination, while others may support lower overhead schemes where
699 * soft breakpoints embedded in the algorithm automatically terminate the
700 * algorithm.
702 * @param target used to run the algorithm
703 * @param arch_info target-specific description of the algorithm.
705 int target_run_algorithm(struct target *target,
706 int num_mem_params, struct mem_param *mem_params,
707 int num_reg_params, struct reg_param *reg_param,
708 uint32_t entry_point, uint32_t exit_point,
709 int timeout_ms, void *arch_info)
711 int retval = ERROR_FAIL;
713 if (!target_was_examined(target)) {
714 LOG_ERROR("Target not examined yet");
715 goto done;
717 if (!target->type->run_algorithm) {
718 LOG_ERROR("Target type '%s' does not support %s",
719 target_type_name(target), __func__);
720 goto done;
723 target->running_alg = true;
724 retval = target->type->run_algorithm(target,
725 num_mem_params, mem_params,
726 num_reg_params, reg_param,
727 entry_point, exit_point, timeout_ms, arch_info);
728 target->running_alg = false;
730 done:
731 return retval;
735 * Downloads a target-specific native code algorithm to the target,
736 * executes and leaves it running.
738 * @param target used to run the algorithm
739 * @param arch_info target-specific description of the algorithm.
741 int target_start_algorithm(struct target *target,
742 int num_mem_params, struct mem_param *mem_params,
743 int num_reg_params, struct reg_param *reg_params,
744 uint32_t entry_point, uint32_t exit_point,
745 void *arch_info)
747 int retval = ERROR_FAIL;
749 if (!target_was_examined(target)) {
750 LOG_ERROR("Target not examined yet");
751 goto done;
753 if (!target->type->start_algorithm) {
754 LOG_ERROR("Target type '%s' does not support %s",
755 target_type_name(target), __func__);
756 goto done;
758 if (target->running_alg) {
759 LOG_ERROR("Target is already running an algorithm");
760 goto done;
763 target->running_alg = true;
764 retval = target->type->start_algorithm(target,
765 num_mem_params, mem_params,
766 num_reg_params, reg_params,
767 entry_point, exit_point, arch_info);
769 done:
770 return retval;
774 * Waits for an algorithm started with target_start_algorithm() to complete.
776 * @param target used to run the algorithm
777 * @param arch_info target-specific description of the algorithm.
779 int target_wait_algorithm(struct target *target,
780 int num_mem_params, struct mem_param *mem_params,
781 int num_reg_params, struct reg_param *reg_params,
782 uint32_t exit_point, int timeout_ms,
783 void *arch_info)
785 int retval = ERROR_FAIL;
787 if (!target->type->wait_algorithm) {
788 LOG_ERROR("Target type '%s' does not support %s",
789 target_type_name(target), __func__);
790 goto done;
792 if (!target->running_alg) {
793 LOG_ERROR("Target is not running an algorithm");
794 goto done;
797 retval = target->type->wait_algorithm(target,
798 num_mem_params, mem_params,
799 num_reg_params, reg_params,
800 exit_point, timeout_ms, arch_info);
801 if (retval != ERROR_TARGET_TIMEOUT)
802 target->running_alg = false;
804 done:
805 return retval;
809 * Executes a target-specific native code algorithm in the target.
810 * It differs from target_run_algorithm in that the algorithm is asynchronous.
811 * Because of this it requires an compliant algorithm:
812 * see contrib/loaders/flash/stm32f1x.S for example.
814 * @param target used to run the algorithm
817 int target_run_flash_async_algorithm(struct target *target,
818 uint8_t *buffer, uint32_t count, int block_size,
819 int num_mem_params, struct mem_param *mem_params,
820 int num_reg_params, struct reg_param *reg_params,
821 uint32_t buffer_start, uint32_t buffer_size,
822 uint32_t entry_point, uint32_t exit_point, void *arch_info)
824 int retval;
825 int timeout = 0;
827 /* Set up working area. First word is write pointer, second word is read pointer,
828 * rest is fifo data area. */
829 uint32_t wp_addr = buffer_start;
830 uint32_t rp_addr = buffer_start + 4;
831 uint32_t fifo_start_addr = buffer_start + 8;
832 uint32_t fifo_end_addr = buffer_start + buffer_size;
834 uint32_t wp = fifo_start_addr;
835 uint32_t rp = fifo_start_addr;
837 /* validate block_size is 2^n */
838 assert(!block_size || !(block_size & (block_size - 1)));
840 retval = target_write_u32(target, wp_addr, wp);
841 if (retval != ERROR_OK)
842 return retval;
843 retval = target_write_u32(target, rp_addr, rp);
844 if (retval != ERROR_OK)
845 return retval;
847 /* Start up algorithm on target and let it idle while writing the first chunk */
848 retval = target_start_algorithm(target, num_mem_params, mem_params,
849 num_reg_params, reg_params,
850 entry_point,
851 exit_point,
852 arch_info);
854 if (retval != ERROR_OK) {
855 LOG_ERROR("error starting target flash write algorithm");
856 return retval;
859 while (count > 0) {
861 retval = target_read_u32(target, rp_addr, &rp);
862 if (retval != ERROR_OK) {
863 LOG_ERROR("failed to get read pointer");
864 break;
867 LOG_DEBUG("count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32, count, wp, rp);
869 if (rp == 0) {
870 LOG_ERROR("flash write algorithm aborted by target");
871 retval = ERROR_FLASH_OPERATION_FAILED;
872 break;
875 if ((rp & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
876 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
877 break;
880 /* Count the number of bytes available in the fifo without
881 * crossing the wrap around. Make sure to not fill it completely,
882 * because that would make wp == rp and that's the empty condition. */
883 uint32_t thisrun_bytes;
884 if (rp > wp)
885 thisrun_bytes = rp - wp - block_size;
886 else if (rp > fifo_start_addr)
887 thisrun_bytes = fifo_end_addr - wp;
888 else
889 thisrun_bytes = fifo_end_addr - wp - block_size;
891 if (thisrun_bytes == 0) {
892 /* Throttle polling a bit if transfer is (much) faster than flash
893 * programming. The exact delay shouldn't matter as long as it's
894 * less than buffer size / flash speed. This is very unlikely to
895 * run when using high latency connections such as USB. */
896 alive_sleep(10);
898 /* to stop an infinite loop on some targets check and increment a timeout
899 * this issue was observed on a stellaris using the new ICDI interface */
900 if (timeout++ >= 500) {
901 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
902 return ERROR_FLASH_OPERATION_FAILED;
904 continue;
907 /* reset our timeout */
908 timeout = 0;
910 /* Limit to the amount of data we actually want to write */
911 if (thisrun_bytes > count * block_size)
912 thisrun_bytes = count * block_size;
914 /* Write data to fifo */
915 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
916 if (retval != ERROR_OK)
917 break;
919 /* Update counters and wrap write pointer */
920 buffer += thisrun_bytes;
921 count -= thisrun_bytes / block_size;
922 wp += thisrun_bytes;
923 if (wp >= fifo_end_addr)
924 wp = fifo_start_addr;
926 /* Store updated write pointer to target */
927 retval = target_write_u32(target, wp_addr, wp);
928 if (retval != ERROR_OK)
929 break;
932 if (retval != ERROR_OK) {
933 /* abort flash write algorithm on target */
934 target_write_u32(target, wp_addr, 0);
937 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
938 num_reg_params, reg_params,
939 exit_point,
940 10000,
941 arch_info);
943 if (retval2 != ERROR_OK) {
944 LOG_ERROR("error waiting for target flash write algorithm");
945 retval = retval2;
948 return retval;
951 int target_read_memory(struct target *target,
952 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
954 if (!target_was_examined(target)) {
955 LOG_ERROR("Target not examined yet");
956 return ERROR_FAIL;
958 return target->type->read_memory(target, address, size, count, buffer);
961 int target_read_phys_memory(struct target *target,
962 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
964 if (!target_was_examined(target)) {
965 LOG_ERROR("Target not examined yet");
966 return ERROR_FAIL;
968 return target->type->read_phys_memory(target, address, size, count, buffer);
971 int target_write_memory(struct target *target,
972 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
974 if (!target_was_examined(target)) {
975 LOG_ERROR("Target not examined yet");
976 return ERROR_FAIL;
978 return target->type->write_memory(target, address, size, count, buffer);
981 int target_write_phys_memory(struct target *target,
982 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
984 if (!target_was_examined(target)) {
985 LOG_ERROR("Target not examined yet");
986 return ERROR_FAIL;
988 return target->type->write_phys_memory(target, address, size, count, buffer);
991 int target_add_breakpoint(struct target *target,
992 struct breakpoint *breakpoint)
994 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
995 LOG_WARNING("target %s is not halted", target_name(target));
996 return ERROR_TARGET_NOT_HALTED;
998 return target->type->add_breakpoint(target, breakpoint);
1001 int target_add_context_breakpoint(struct target *target,
1002 struct breakpoint *breakpoint)
1004 if (target->state != TARGET_HALTED) {
1005 LOG_WARNING("target %s is not halted", target_name(target));
1006 return ERROR_TARGET_NOT_HALTED;
1008 return target->type->add_context_breakpoint(target, breakpoint);
1011 int target_add_hybrid_breakpoint(struct target *target,
1012 struct breakpoint *breakpoint)
1014 if (target->state != TARGET_HALTED) {
1015 LOG_WARNING("target %s is not halted", target_name(target));
1016 return ERROR_TARGET_NOT_HALTED;
1018 return target->type->add_hybrid_breakpoint(target, breakpoint);
1021 int target_remove_breakpoint(struct target *target,
1022 struct breakpoint *breakpoint)
1024 return target->type->remove_breakpoint(target, breakpoint);
1027 int target_add_watchpoint(struct target *target,
1028 struct watchpoint *watchpoint)
1030 if (target->state != TARGET_HALTED) {
1031 LOG_WARNING("target %s is not halted", target_name(target));
1032 return ERROR_TARGET_NOT_HALTED;
1034 return target->type->add_watchpoint(target, watchpoint);
1036 int target_remove_watchpoint(struct target *target,
1037 struct watchpoint *watchpoint)
1039 return target->type->remove_watchpoint(target, watchpoint);
1041 int target_hit_watchpoint(struct target *target,
1042 struct watchpoint **hit_watchpoint)
1044 if (target->state != TARGET_HALTED) {
1045 LOG_WARNING("target %s is not halted", target->cmd_name);
1046 return ERROR_TARGET_NOT_HALTED;
1049 if (target->type->hit_watchpoint == NULL) {
1050 /* For backward compatible, if hit_watchpoint is not implemented,
1051 * return ERROR_FAIL such that gdb_server will not take the nonsense
1052 * information. */
1053 return ERROR_FAIL;
1056 return target->type->hit_watchpoint(target, hit_watchpoint);
1059 int target_get_gdb_reg_list(struct target *target,
1060 struct reg **reg_list[], int *reg_list_size,
1061 enum target_register_class reg_class)
1063 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1065 int target_step(struct target *target,
1066 int current, uint32_t address, int handle_breakpoints)
1068 return target->type->step(target, current, address, handle_breakpoints);
1071 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1073 if (target->state != TARGET_HALTED) {
1074 LOG_WARNING("target %s is not halted", target->cmd_name);
1075 return ERROR_TARGET_NOT_HALTED;
1077 return target->type->get_gdb_fileio_info(target, fileio_info);
1080 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1082 if (target->state != TARGET_HALTED) {
1083 LOG_WARNING("target %s is not halted", target->cmd_name);
1084 return ERROR_TARGET_NOT_HALTED;
1086 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1089 int target_profiling(struct target *target, uint32_t *samples,
1090 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1092 if (target->state != TARGET_HALTED) {
1093 LOG_WARNING("target %s is not halted", target->cmd_name);
1094 return ERROR_TARGET_NOT_HALTED;
1096 return target->type->profiling(target, samples, max_num_samples,
1097 num_samples, seconds);
1101 * Reset the @c examined flag for the given target.
1102 * Pure paranoia -- targets are zeroed on allocation.
1104 static void target_reset_examined(struct target *target)
1106 target->examined = false;
1109 static int err_read_phys_memory(struct target *target, uint32_t address,
1110 uint32_t size, uint32_t count, uint8_t *buffer)
1112 LOG_ERROR("Not implemented: %s", __func__);
1113 return ERROR_FAIL;
1116 static int err_write_phys_memory(struct target *target, uint32_t address,
1117 uint32_t size, uint32_t count, const uint8_t *buffer)
1119 LOG_ERROR("Not implemented: %s", __func__);
1120 return ERROR_FAIL;
1123 static int handle_target(void *priv);
1125 static int target_init_one(struct command_context *cmd_ctx,
1126 struct target *target)
1128 target_reset_examined(target);
1130 struct target_type *type = target->type;
1131 if (type->examine == NULL)
1132 type->examine = default_examine;
1134 if (type->check_reset == NULL)
1135 type->check_reset = default_check_reset;
1137 assert(type->init_target != NULL);
1139 int retval = type->init_target(cmd_ctx, target);
1140 if (ERROR_OK != retval) {
1141 LOG_ERROR("target '%s' init failed", target_name(target));
1142 return retval;
1145 /* Sanity-check MMU support ... stub in what we must, to help
1146 * implement it in stages, but warn if we need to do so.
1148 if (type->mmu) {
1149 if (type->write_phys_memory == NULL) {
1150 LOG_ERROR("type '%s' is missing write_phys_memory",
1151 type->name);
1152 type->write_phys_memory = err_write_phys_memory;
1154 if (type->read_phys_memory == NULL) {
1155 LOG_ERROR("type '%s' is missing read_phys_memory",
1156 type->name);
1157 type->read_phys_memory = err_read_phys_memory;
1159 if (type->virt2phys == NULL) {
1160 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1161 type->virt2phys = identity_virt2phys;
1163 } else {
1164 /* Make sure no-MMU targets all behave the same: make no
1165 * distinction between physical and virtual addresses, and
1166 * ensure that virt2phys() is always an identity mapping.
1168 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1169 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1171 type->mmu = no_mmu;
1172 type->write_phys_memory = type->write_memory;
1173 type->read_phys_memory = type->read_memory;
1174 type->virt2phys = identity_virt2phys;
1177 if (target->type->read_buffer == NULL)
1178 target->type->read_buffer = target_read_buffer_default;
1180 if (target->type->write_buffer == NULL)
1181 target->type->write_buffer = target_write_buffer_default;
1183 if (target->type->get_gdb_fileio_info == NULL)
1184 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1186 if (target->type->gdb_fileio_end == NULL)
1187 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1189 if (target->type->profiling == NULL)
1190 target->type->profiling = target_profiling_default;
1192 return ERROR_OK;
1195 static int target_init(struct command_context *cmd_ctx)
1197 struct target *target;
1198 int retval;
1200 for (target = all_targets; target; target = target->next) {
1201 retval = target_init_one(cmd_ctx, target);
1202 if (ERROR_OK != retval)
1203 return retval;
1206 if (!all_targets)
1207 return ERROR_OK;
1209 retval = target_register_user_commands(cmd_ctx);
1210 if (ERROR_OK != retval)
1211 return retval;
1213 retval = target_register_timer_callback(&handle_target,
1214 polling_interval, 1, cmd_ctx->interp);
1215 if (ERROR_OK != retval)
1216 return retval;
1218 return ERROR_OK;
1221 COMMAND_HANDLER(handle_target_init_command)
1223 int retval;
1225 if (CMD_ARGC != 0)
1226 return ERROR_COMMAND_SYNTAX_ERROR;
1228 static bool target_initialized;
1229 if (target_initialized) {
1230 LOG_INFO("'target init' has already been called");
1231 return ERROR_OK;
1233 target_initialized = true;
1235 retval = command_run_line(CMD_CTX, "init_targets");
1236 if (ERROR_OK != retval)
1237 return retval;
1239 retval = command_run_line(CMD_CTX, "init_board");
1240 if (ERROR_OK != retval)
1241 return retval;
1243 LOG_DEBUG("Initializing targets...");
1244 return target_init(CMD_CTX);
1247 int target_register_event_callback(int (*callback)(struct target *target,
1248 enum target_event event, void *priv), void *priv)
1250 struct target_event_callback **callbacks_p = &target_event_callbacks;
1252 if (callback == NULL)
1253 return ERROR_COMMAND_SYNTAX_ERROR;
1255 if (*callbacks_p) {
1256 while ((*callbacks_p)->next)
1257 callbacks_p = &((*callbacks_p)->next);
1258 callbacks_p = &((*callbacks_p)->next);
1261 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1262 (*callbacks_p)->callback = callback;
1263 (*callbacks_p)->priv = priv;
1264 (*callbacks_p)->next = NULL;
1266 return ERROR_OK;
1269 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1271 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1272 struct timeval now;
1274 if (callback == NULL)
1275 return ERROR_COMMAND_SYNTAX_ERROR;
1277 if (*callbacks_p) {
1278 while ((*callbacks_p)->next)
1279 callbacks_p = &((*callbacks_p)->next);
1280 callbacks_p = &((*callbacks_p)->next);
1283 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1284 (*callbacks_p)->callback = callback;
1285 (*callbacks_p)->periodic = periodic;
1286 (*callbacks_p)->time_ms = time_ms;
1288 gettimeofday(&now, NULL);
1289 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
1290 time_ms -= (time_ms % 1000);
1291 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
1292 if ((*callbacks_p)->when.tv_usec > 1000000) {
1293 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
1294 (*callbacks_p)->when.tv_sec += 1;
1297 (*callbacks_p)->priv = priv;
1298 (*callbacks_p)->next = NULL;
1300 return ERROR_OK;
1303 int target_unregister_event_callback(int (*callback)(struct target *target,
1304 enum target_event event, void *priv), void *priv)
1306 struct target_event_callback **p = &target_event_callbacks;
1307 struct target_event_callback *c = target_event_callbacks;
1309 if (callback == NULL)
1310 return ERROR_COMMAND_SYNTAX_ERROR;
1312 while (c) {
1313 struct target_event_callback *next = c->next;
1314 if ((c->callback == callback) && (c->priv == priv)) {
1315 *p = next;
1316 free(c);
1317 return ERROR_OK;
1318 } else
1319 p = &(c->next);
1320 c = next;
1323 return ERROR_OK;
1326 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1328 struct target_timer_callback **p = &target_timer_callbacks;
1329 struct target_timer_callback *c = target_timer_callbacks;
1331 if (callback == NULL)
1332 return ERROR_COMMAND_SYNTAX_ERROR;
1334 while (c) {
1335 struct target_timer_callback *next = c->next;
1336 if ((c->callback == callback) && (c->priv == priv)) {
1337 *p = next;
1338 free(c);
1339 return ERROR_OK;
1340 } else
1341 p = &(c->next);
1342 c = next;
1345 return ERROR_OK;
1348 int target_call_event_callbacks(struct target *target, enum target_event event)
1350 struct target_event_callback *callback = target_event_callbacks;
1351 struct target_event_callback *next_callback;
1353 if (event == TARGET_EVENT_HALTED) {
1354 /* execute early halted first */
1355 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1358 LOG_DEBUG("target event %i (%s)", event,
1359 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1361 target_handle_event(target, event);
1363 while (callback) {
1364 next_callback = callback->next;
1365 callback->callback(target, event, callback->priv);
1366 callback = next_callback;
1369 return ERROR_OK;
1372 static int target_timer_callback_periodic_restart(
1373 struct target_timer_callback *cb, struct timeval *now)
1375 int time_ms = cb->time_ms;
1376 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1377 time_ms -= (time_ms % 1000);
1378 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1379 if (cb->when.tv_usec > 1000000) {
1380 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1381 cb->when.tv_sec += 1;
1383 return ERROR_OK;
1386 static int target_call_timer_callback(struct target_timer_callback *cb,
1387 struct timeval *now)
1389 cb->callback(cb->priv);
1391 if (cb->periodic)
1392 return target_timer_callback_periodic_restart(cb, now);
1394 return target_unregister_timer_callback(cb->callback, cb->priv);
1397 static int target_call_timer_callbacks_check_time(int checktime)
1399 keep_alive();
1401 struct timeval now;
1402 gettimeofday(&now, NULL);
1404 struct target_timer_callback *callback = target_timer_callbacks;
1405 while (callback) {
1406 /* cleaning up may unregister and free this callback */
1407 struct target_timer_callback *next_callback = callback->next;
1409 bool call_it = callback->callback &&
1410 ((!checktime && callback->periodic) ||
1411 now.tv_sec > callback->when.tv_sec ||
1412 (now.tv_sec == callback->when.tv_sec &&
1413 now.tv_usec >= callback->when.tv_usec));
1415 if (call_it) {
1416 int retval = target_call_timer_callback(callback, &now);
1417 if (retval != ERROR_OK)
1418 return retval;
1421 callback = next_callback;
1424 return ERROR_OK;
1427 int target_call_timer_callbacks(void)
1429 return target_call_timer_callbacks_check_time(1);
1432 /* invoke periodic callbacks immediately */
1433 int target_call_timer_callbacks_now(void)
1435 return target_call_timer_callbacks_check_time(0);
1438 /* Prints the working area layout for debug purposes */
1439 static void print_wa_layout(struct target *target)
1441 struct working_area *c = target->working_areas;
1443 while (c) {
1444 LOG_DEBUG("%c%c 0x%08"PRIx32"-0x%08"PRIx32" (%"PRIu32" bytes)",
1445 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1446 c->address, c->address + c->size - 1, c->size);
1447 c = c->next;
1451 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1452 static void target_split_working_area(struct working_area *area, uint32_t size)
1454 assert(area->free); /* Shouldn't split an allocated area */
1455 assert(size <= area->size); /* Caller should guarantee this */
1457 /* Split only if not already the right size */
1458 if (size < area->size) {
1459 struct working_area *new_wa = malloc(sizeof(*new_wa));
1461 if (new_wa == NULL)
1462 return;
1464 new_wa->next = area->next;
1465 new_wa->size = area->size - size;
1466 new_wa->address = area->address + size;
1467 new_wa->backup = NULL;
1468 new_wa->user = NULL;
1469 new_wa->free = true;
1471 area->next = new_wa;
1472 area->size = size;
1474 /* If backup memory was allocated to this area, it has the wrong size
1475 * now so free it and it will be reallocated if/when needed */
1476 if (area->backup) {
1477 free(area->backup);
1478 area->backup = NULL;
1483 /* Merge all adjacent free areas into one */
1484 static void target_merge_working_areas(struct target *target)
1486 struct working_area *c = target->working_areas;
1488 while (c && c->next) {
1489 assert(c->next->address == c->address + c->size); /* This is an invariant */
1491 /* Find two adjacent free areas */
1492 if (c->free && c->next->free) {
1493 /* Merge the last into the first */
1494 c->size += c->next->size;
1496 /* Remove the last */
1497 struct working_area *to_be_freed = c->next;
1498 c->next = c->next->next;
1499 if (to_be_freed->backup)
1500 free(to_be_freed->backup);
1501 free(to_be_freed);
1503 /* If backup memory was allocated to the remaining area, it's has
1504 * the wrong size now */
1505 if (c->backup) {
1506 free(c->backup);
1507 c->backup = NULL;
1509 } else {
1510 c = c->next;
1515 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1517 /* Reevaluate working area address based on MMU state*/
1518 if (target->working_areas == NULL) {
1519 int retval;
1520 int enabled;
1522 retval = target->type->mmu(target, &enabled);
1523 if (retval != ERROR_OK)
1524 return retval;
1526 if (!enabled) {
1527 if (target->working_area_phys_spec) {
1528 LOG_DEBUG("MMU disabled, using physical "
1529 "address for working memory 0x%08"PRIx32,
1530 target->working_area_phys);
1531 target->working_area = target->working_area_phys;
1532 } else {
1533 LOG_ERROR("No working memory available. "
1534 "Specify -work-area-phys to target.");
1535 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1537 } else {
1538 if (target->working_area_virt_spec) {
1539 LOG_DEBUG("MMU enabled, using virtual "
1540 "address for working memory 0x%08"PRIx32,
1541 target->working_area_virt);
1542 target->working_area = target->working_area_virt;
1543 } else {
1544 LOG_ERROR("No working memory available. "
1545 "Specify -work-area-virt to target.");
1546 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1550 /* Set up initial working area on first call */
1551 struct working_area *new_wa = malloc(sizeof(*new_wa));
1552 if (new_wa) {
1553 new_wa->next = NULL;
1554 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1555 new_wa->address = target->working_area;
1556 new_wa->backup = NULL;
1557 new_wa->user = NULL;
1558 new_wa->free = true;
1561 target->working_areas = new_wa;
1564 /* only allocate multiples of 4 byte */
1565 if (size % 4)
1566 size = (size + 3) & (~3UL);
1568 struct working_area *c = target->working_areas;
1570 /* Find the first large enough working area */
1571 while (c) {
1572 if (c->free && c->size >= size)
1573 break;
1574 c = c->next;
1577 if (c == NULL)
1578 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1580 /* Split the working area into the requested size */
1581 target_split_working_area(c, size);
1583 LOG_DEBUG("allocated new working area of %"PRIu32" bytes at address 0x%08"PRIx32, size, c->address);
1585 if (target->backup_working_area) {
1586 if (c->backup == NULL) {
1587 c->backup = malloc(c->size);
1588 if (c->backup == NULL)
1589 return ERROR_FAIL;
1592 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1593 if (retval != ERROR_OK)
1594 return retval;
1597 /* mark as used, and return the new (reused) area */
1598 c->free = false;
1599 *area = c;
1601 /* user pointer */
1602 c->user = area;
1604 print_wa_layout(target);
1606 return ERROR_OK;
1609 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1611 int retval;
1613 retval = target_alloc_working_area_try(target, size, area);
1614 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1615 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1616 return retval;
1620 static int target_restore_working_area(struct target *target, struct working_area *area)
1622 int retval = ERROR_OK;
1624 if (target->backup_working_area && area->backup != NULL) {
1625 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1626 if (retval != ERROR_OK)
1627 LOG_ERROR("failed to restore %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1628 area->size, area->address);
1631 return retval;
1634 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1635 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1637 int retval = ERROR_OK;
1639 if (area->free)
1640 return retval;
1642 if (restore) {
1643 retval = target_restore_working_area(target, area);
1644 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1645 if (retval != ERROR_OK)
1646 return retval;
1649 area->free = true;
1651 LOG_DEBUG("freed %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1652 area->size, area->address);
1654 /* mark user pointer invalid */
1655 /* TODO: Is this really safe? It points to some previous caller's memory.
1656 * How could we know that the area pointer is still in that place and not
1657 * some other vital data? What's the purpose of this, anyway? */
1658 *area->user = NULL;
1659 area->user = NULL;
1661 target_merge_working_areas(target);
1663 print_wa_layout(target);
1665 return retval;
1668 int target_free_working_area(struct target *target, struct working_area *area)
1670 return target_free_working_area_restore(target, area, 1);
1673 /* free resources and restore memory, if restoring memory fails,
1674 * free up resources anyway
1676 static void target_free_all_working_areas_restore(struct target *target, int restore)
1678 struct working_area *c = target->working_areas;
1680 LOG_DEBUG("freeing all working areas");
1682 /* Loop through all areas, restoring the allocated ones and marking them as free */
1683 while (c) {
1684 if (!c->free) {
1685 if (restore)
1686 target_restore_working_area(target, c);
1687 c->free = true;
1688 *c->user = NULL; /* Same as above */
1689 c->user = NULL;
1691 c = c->next;
1694 /* Run a merge pass to combine all areas into one */
1695 target_merge_working_areas(target);
1697 print_wa_layout(target);
1700 void target_free_all_working_areas(struct target *target)
1702 target_free_all_working_areas_restore(target, 1);
1705 /* Find the largest number of bytes that can be allocated */
1706 uint32_t target_get_working_area_avail(struct target *target)
1708 struct working_area *c = target->working_areas;
1709 uint32_t max_size = 0;
1711 if (c == NULL)
1712 return target->working_area_size;
1714 while (c) {
1715 if (c->free && max_size < c->size)
1716 max_size = c->size;
1718 c = c->next;
1721 return max_size;
1724 int target_arch_state(struct target *target)
1726 int retval;
1727 if (target == NULL) {
1728 LOG_USER("No target has been configured");
1729 return ERROR_OK;
1732 LOG_USER("target state: %s", target_state_name(target));
1734 if (target->state != TARGET_HALTED)
1735 return ERROR_OK;
1737 retval = target->type->arch_state(target);
1738 return retval;
1741 static int target_get_gdb_fileio_info_default(struct target *target,
1742 struct gdb_fileio_info *fileio_info)
1744 /* If target does not support semi-hosting function, target
1745 has no need to provide .get_gdb_fileio_info callback.
1746 It just return ERROR_FAIL and gdb_server will return "Txx"
1747 as target halted every time. */
1748 return ERROR_FAIL;
1751 static int target_gdb_fileio_end_default(struct target *target,
1752 int retcode, int fileio_errno, bool ctrl_c)
1754 return ERROR_OK;
1757 static int target_profiling_default(struct target *target, uint32_t *samples,
1758 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1760 struct timeval timeout, now;
1762 gettimeofday(&timeout, NULL);
1763 timeval_add_time(&timeout, seconds, 0);
1765 LOG_INFO("Starting profiling. Halting and resuming the"
1766 " target as often as we can...");
1768 uint32_t sample_count = 0;
1769 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
1770 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
1772 int retval = ERROR_OK;
1773 for (;;) {
1774 target_poll(target);
1775 if (target->state == TARGET_HALTED) {
1776 uint32_t t = *((uint32_t *)reg->value);
1777 samples[sample_count++] = t;
1778 /* current pc, addr = 0, do not handle breakpoints, not debugging */
1779 retval = target_resume(target, 1, 0, 0, 0);
1780 target_poll(target);
1781 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
1782 } else if (target->state == TARGET_RUNNING) {
1783 /* We want to quickly sample the PC. */
1784 retval = target_halt(target);
1785 } else {
1786 LOG_INFO("Target not halted or running");
1787 retval = ERROR_OK;
1788 break;
1791 if (retval != ERROR_OK)
1792 break;
1794 gettimeofday(&now, NULL);
1795 if ((sample_count >= max_num_samples) ||
1796 ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec))) {
1797 LOG_INFO("Profiling completed. %d samples.", sample_count);
1798 break;
1802 *num_samples = sample_count;
1803 return retval;
1806 /* Single aligned words are guaranteed to use 16 or 32 bit access
1807 * mode respectively, otherwise data is handled as quickly as
1808 * possible
1810 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1812 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1813 (int)size, (unsigned)address);
1815 if (!target_was_examined(target)) {
1816 LOG_ERROR("Target not examined yet");
1817 return ERROR_FAIL;
1820 if (size == 0)
1821 return ERROR_OK;
1823 if ((address + size - 1) < address) {
1824 /* GDB can request this when e.g. PC is 0xfffffffc*/
1825 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1826 (unsigned)address,
1827 (unsigned)size);
1828 return ERROR_FAIL;
1831 return target->type->write_buffer(target, address, size, buffer);
1834 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t count, const uint8_t *buffer)
1836 uint32_t size;
1838 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
1839 * will have something to do with the size we leave to it. */
1840 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
1841 if (address & size) {
1842 int retval = target_write_memory(target, address, size, 1, buffer);
1843 if (retval != ERROR_OK)
1844 return retval;
1845 address += size;
1846 count -= size;
1847 buffer += size;
1851 /* Write the data with as large access size as possible. */
1852 for (; size > 0; size /= 2) {
1853 uint32_t aligned = count - count % size;
1854 if (aligned > 0) {
1855 int retval = target_write_memory(target, address, size, aligned / size, buffer);
1856 if (retval != ERROR_OK)
1857 return retval;
1858 address += aligned;
1859 count -= aligned;
1860 buffer += aligned;
1864 return ERROR_OK;
1867 /* Single aligned words are guaranteed to use 16 or 32 bit access
1868 * mode respectively, otherwise data is handled as quickly as
1869 * possible
1871 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1873 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1874 (int)size, (unsigned)address);
1876 if (!target_was_examined(target)) {
1877 LOG_ERROR("Target not examined yet");
1878 return ERROR_FAIL;
1881 if (size == 0)
1882 return ERROR_OK;
1884 if ((address + size - 1) < address) {
1885 /* GDB can request this when e.g. PC is 0xfffffffc*/
1886 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1887 address,
1888 size);
1889 return ERROR_FAIL;
1892 return target->type->read_buffer(target, address, size, buffer);
1895 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t count, uint8_t *buffer)
1897 uint32_t size;
1899 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
1900 * will have something to do with the size we leave to it. */
1901 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
1902 if (address & size) {
1903 int retval = target_read_memory(target, address, size, 1, buffer);
1904 if (retval != ERROR_OK)
1905 return retval;
1906 address += size;
1907 count -= size;
1908 buffer += size;
1912 /* Read the data with as large access size as possible. */
1913 for (; size > 0; size /= 2) {
1914 uint32_t aligned = count - count % size;
1915 if (aligned > 0) {
1916 int retval = target_read_memory(target, address, size, aligned / size, buffer);
1917 if (retval != ERROR_OK)
1918 return retval;
1919 address += aligned;
1920 count -= aligned;
1921 buffer += aligned;
1925 return ERROR_OK;
1928 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1930 uint8_t *buffer;
1931 int retval;
1932 uint32_t i;
1933 uint32_t checksum = 0;
1934 if (!target_was_examined(target)) {
1935 LOG_ERROR("Target not examined yet");
1936 return ERROR_FAIL;
1939 retval = target->type->checksum_memory(target, address, size, &checksum);
1940 if (retval != ERROR_OK) {
1941 buffer = malloc(size);
1942 if (buffer == NULL) {
1943 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1944 return ERROR_COMMAND_SYNTAX_ERROR;
1946 retval = target_read_buffer(target, address, size, buffer);
1947 if (retval != ERROR_OK) {
1948 free(buffer);
1949 return retval;
1952 /* convert to target endianness */
1953 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
1954 uint32_t target_data;
1955 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1956 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1959 retval = image_calculate_checksum(buffer, size, &checksum);
1960 free(buffer);
1963 *crc = checksum;
1965 return retval;
1968 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1970 int retval;
1971 if (!target_was_examined(target)) {
1972 LOG_ERROR("Target not examined yet");
1973 return ERROR_FAIL;
1976 if (target->type->blank_check_memory == 0)
1977 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1979 retval = target->type->blank_check_memory(target, address, size, blank);
1981 return retval;
1984 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1986 uint8_t value_buf[4];
1987 if (!target_was_examined(target)) {
1988 LOG_ERROR("Target not examined yet");
1989 return ERROR_FAIL;
1992 int retval = target_read_memory(target, address, 4, 1, value_buf);
1994 if (retval == ERROR_OK) {
1995 *value = target_buffer_get_u32(target, value_buf);
1996 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1997 address,
1998 *value);
1999 } else {
2000 *value = 0x0;
2001 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2002 address);
2005 return retval;
2008 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
2010 uint8_t value_buf[2];
2011 if (!target_was_examined(target)) {
2012 LOG_ERROR("Target not examined yet");
2013 return ERROR_FAIL;
2016 int retval = target_read_memory(target, address, 2, 1, value_buf);
2018 if (retval == ERROR_OK) {
2019 *value = target_buffer_get_u16(target, value_buf);
2020 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
2021 address,
2022 *value);
2023 } else {
2024 *value = 0x0;
2025 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2026 address);
2029 return retval;
2032 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
2034 if (!target_was_examined(target)) {
2035 LOG_ERROR("Target not examined yet");
2036 return ERROR_FAIL;
2039 int retval = target_read_memory(target, address, 1, 1, value);
2041 if (retval == ERROR_OK) {
2042 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2043 address,
2044 *value);
2045 } else {
2046 *value = 0x0;
2047 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2048 address);
2051 return retval;
2054 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
2056 int retval;
2057 uint8_t value_buf[4];
2058 if (!target_was_examined(target)) {
2059 LOG_ERROR("Target not examined yet");
2060 return ERROR_FAIL;
2063 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2064 address,
2065 value);
2067 target_buffer_set_u32(target, value_buf, value);
2068 retval = target_write_memory(target, address, 4, 1, value_buf);
2069 if (retval != ERROR_OK)
2070 LOG_DEBUG("failed: %i", retval);
2072 return retval;
2075 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
2077 int retval;
2078 uint8_t value_buf[2];
2079 if (!target_was_examined(target)) {
2080 LOG_ERROR("Target not examined yet");
2081 return ERROR_FAIL;
2084 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
2085 address,
2086 value);
2088 target_buffer_set_u16(target, value_buf, value);
2089 retval = target_write_memory(target, address, 2, 1, value_buf);
2090 if (retval != ERROR_OK)
2091 LOG_DEBUG("failed: %i", retval);
2093 return retval;
2096 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
2098 int retval;
2099 if (!target_was_examined(target)) {
2100 LOG_ERROR("Target not examined yet");
2101 return ERROR_FAIL;
2104 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2105 address, value);
2107 retval = target_write_memory(target, address, 1, 1, &value);
2108 if (retval != ERROR_OK)
2109 LOG_DEBUG("failed: %i", retval);
2111 return retval;
2114 static int find_target(struct command_context *cmd_ctx, const char *name)
2116 struct target *target = get_target(name);
2117 if (target == NULL) {
2118 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2119 return ERROR_FAIL;
2121 if (!target->tap->enabled) {
2122 LOG_USER("Target: TAP %s is disabled, "
2123 "can't be the current target\n",
2124 target->tap->dotted_name);
2125 return ERROR_FAIL;
2128 cmd_ctx->current_target = target->target_number;
2129 return ERROR_OK;
2133 COMMAND_HANDLER(handle_targets_command)
2135 int retval = ERROR_OK;
2136 if (CMD_ARGC == 1) {
2137 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2138 if (retval == ERROR_OK) {
2139 /* we're done! */
2140 return retval;
2144 struct target *target = all_targets;
2145 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2146 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2147 while (target) {
2148 const char *state;
2149 char marker = ' ';
2151 if (target->tap->enabled)
2152 state = target_state_name(target);
2153 else
2154 state = "tap-disabled";
2156 if (CMD_CTX->current_target == target->target_number)
2157 marker = '*';
2159 /* keep columns lined up to match the headers above */
2160 command_print(CMD_CTX,
2161 "%2d%c %-18s %-10s %-6s %-18s %s",
2162 target->target_number,
2163 marker,
2164 target_name(target),
2165 target_type_name(target),
2166 Jim_Nvp_value2name_simple(nvp_target_endian,
2167 target->endianness)->name,
2168 target->tap->dotted_name,
2169 state);
2170 target = target->next;
2173 return retval;
2176 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2178 static int powerDropout;
2179 static int srstAsserted;
2181 static int runPowerRestore;
2182 static int runPowerDropout;
2183 static int runSrstAsserted;
2184 static int runSrstDeasserted;
2186 static int sense_handler(void)
2188 static int prevSrstAsserted;
2189 static int prevPowerdropout;
2191 int retval = jtag_power_dropout(&powerDropout);
2192 if (retval != ERROR_OK)
2193 return retval;
2195 int powerRestored;
2196 powerRestored = prevPowerdropout && !powerDropout;
2197 if (powerRestored)
2198 runPowerRestore = 1;
2200 long long current = timeval_ms();
2201 static long long lastPower;
2202 int waitMore = lastPower + 2000 > current;
2203 if (powerDropout && !waitMore) {
2204 runPowerDropout = 1;
2205 lastPower = current;
2208 retval = jtag_srst_asserted(&srstAsserted);
2209 if (retval != ERROR_OK)
2210 return retval;
2212 int srstDeasserted;
2213 srstDeasserted = prevSrstAsserted && !srstAsserted;
2215 static long long lastSrst;
2216 waitMore = lastSrst + 2000 > current;
2217 if (srstDeasserted && !waitMore) {
2218 runSrstDeasserted = 1;
2219 lastSrst = current;
2222 if (!prevSrstAsserted && srstAsserted)
2223 runSrstAsserted = 1;
2225 prevSrstAsserted = srstAsserted;
2226 prevPowerdropout = powerDropout;
2228 if (srstDeasserted || powerRestored) {
2229 /* Other than logging the event we can't do anything here.
2230 * Issuing a reset is a particularly bad idea as we might
2231 * be inside a reset already.
2235 return ERROR_OK;
2238 /* process target state changes */
2239 static int handle_target(void *priv)
2241 Jim_Interp *interp = (Jim_Interp *)priv;
2242 int retval = ERROR_OK;
2244 if (!is_jtag_poll_safe()) {
2245 /* polling is disabled currently */
2246 return ERROR_OK;
2249 /* we do not want to recurse here... */
2250 static int recursive;
2251 if (!recursive) {
2252 recursive = 1;
2253 sense_handler();
2254 /* danger! running these procedures can trigger srst assertions and power dropouts.
2255 * We need to avoid an infinite loop/recursion here and we do that by
2256 * clearing the flags after running these events.
2258 int did_something = 0;
2259 if (runSrstAsserted) {
2260 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2261 Jim_Eval(interp, "srst_asserted");
2262 did_something = 1;
2264 if (runSrstDeasserted) {
2265 Jim_Eval(interp, "srst_deasserted");
2266 did_something = 1;
2268 if (runPowerDropout) {
2269 LOG_INFO("Power dropout detected, running power_dropout proc.");
2270 Jim_Eval(interp, "power_dropout");
2271 did_something = 1;
2273 if (runPowerRestore) {
2274 Jim_Eval(interp, "power_restore");
2275 did_something = 1;
2278 if (did_something) {
2279 /* clear detect flags */
2280 sense_handler();
2283 /* clear action flags */
2285 runSrstAsserted = 0;
2286 runSrstDeasserted = 0;
2287 runPowerRestore = 0;
2288 runPowerDropout = 0;
2290 recursive = 0;
2293 /* Poll targets for state changes unless that's globally disabled.
2294 * Skip targets that are currently disabled.
2296 for (struct target *target = all_targets;
2297 is_jtag_poll_safe() && target;
2298 target = target->next) {
2299 if (!target->tap->enabled)
2300 continue;
2302 if (target->backoff.times > target->backoff.count) {
2303 /* do not poll this time as we failed previously */
2304 target->backoff.count++;
2305 continue;
2307 target->backoff.count = 0;
2309 /* only poll target if we've got power and srst isn't asserted */
2310 if (!powerDropout && !srstAsserted) {
2311 /* polling may fail silently until the target has been examined */
2312 retval = target_poll(target);
2313 if (retval != ERROR_OK) {
2314 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2315 if (target->backoff.times * polling_interval < 5000) {
2316 target->backoff.times *= 2;
2317 target->backoff.times++;
2319 LOG_USER("Polling target %s failed, GDB will be halted. Polling again in %dms",
2320 target_name(target),
2321 target->backoff.times * polling_interval);
2323 /* Tell GDB to halt the debugger. This allows the user to
2324 * run monitor commands to handle the situation.
2326 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2327 return retval;
2329 /* Since we succeeded, we reset backoff count */
2330 if (target->backoff.times > 0)
2331 LOG_USER("Polling target %s succeeded again", target_name(target));
2332 target->backoff.times = 0;
2336 return retval;
2339 COMMAND_HANDLER(handle_reg_command)
2341 struct target *target;
2342 struct reg *reg = NULL;
2343 unsigned count = 0;
2344 char *value;
2346 LOG_DEBUG("-");
2348 target = get_current_target(CMD_CTX);
2350 /* list all available registers for the current target */
2351 if (CMD_ARGC == 0) {
2352 struct reg_cache *cache = target->reg_cache;
2354 count = 0;
2355 while (cache) {
2356 unsigned i;
2358 command_print(CMD_CTX, "===== %s", cache->name);
2360 for (i = 0, reg = cache->reg_list;
2361 i < cache->num_regs;
2362 i++, reg++, count++) {
2363 /* only print cached values if they are valid */
2364 if (reg->valid) {
2365 value = buf_to_str(reg->value,
2366 reg->size, 16);
2367 command_print(CMD_CTX,
2368 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2369 count, reg->name,
2370 reg->size, value,
2371 reg->dirty
2372 ? " (dirty)"
2373 : "");
2374 free(value);
2375 } else {
2376 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2377 count, reg->name,
2378 reg->size) ;
2381 cache = cache->next;
2384 return ERROR_OK;
2387 /* access a single register by its ordinal number */
2388 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2389 unsigned num;
2390 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2392 struct reg_cache *cache = target->reg_cache;
2393 count = 0;
2394 while (cache) {
2395 unsigned i;
2396 for (i = 0; i < cache->num_regs; i++) {
2397 if (count++ == num) {
2398 reg = &cache->reg_list[i];
2399 break;
2402 if (reg)
2403 break;
2404 cache = cache->next;
2407 if (!reg) {
2408 command_print(CMD_CTX, "%i is out of bounds, the current target "
2409 "has only %i registers (0 - %i)", num, count, count - 1);
2410 return ERROR_OK;
2412 } else {
2413 /* access a single register by its name */
2414 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2416 if (!reg) {
2417 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2418 return ERROR_OK;
2422 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2424 /* display a register */
2425 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2426 && (CMD_ARGV[1][0] <= '9')))) {
2427 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2428 reg->valid = 0;
2430 if (reg->valid == 0)
2431 reg->type->get(reg);
2432 value = buf_to_str(reg->value, reg->size, 16);
2433 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2434 free(value);
2435 return ERROR_OK;
2438 /* set register value */
2439 if (CMD_ARGC == 2) {
2440 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2441 if (buf == NULL)
2442 return ERROR_FAIL;
2443 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2445 reg->type->set(reg, buf);
2447 value = buf_to_str(reg->value, reg->size, 16);
2448 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2449 free(value);
2451 free(buf);
2453 return ERROR_OK;
2456 return ERROR_COMMAND_SYNTAX_ERROR;
2459 COMMAND_HANDLER(handle_poll_command)
2461 int retval = ERROR_OK;
2462 struct target *target = get_current_target(CMD_CTX);
2464 if (CMD_ARGC == 0) {
2465 command_print(CMD_CTX, "background polling: %s",
2466 jtag_poll_get_enabled() ? "on" : "off");
2467 command_print(CMD_CTX, "TAP: %s (%s)",
2468 target->tap->dotted_name,
2469 target->tap->enabled ? "enabled" : "disabled");
2470 if (!target->tap->enabled)
2471 return ERROR_OK;
2472 retval = target_poll(target);
2473 if (retval != ERROR_OK)
2474 return retval;
2475 retval = target_arch_state(target);
2476 if (retval != ERROR_OK)
2477 return retval;
2478 } else if (CMD_ARGC == 1) {
2479 bool enable;
2480 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2481 jtag_poll_set_enabled(enable);
2482 } else
2483 return ERROR_COMMAND_SYNTAX_ERROR;
2485 return retval;
2488 COMMAND_HANDLER(handle_wait_halt_command)
2490 if (CMD_ARGC > 1)
2491 return ERROR_COMMAND_SYNTAX_ERROR;
2493 unsigned ms = DEFAULT_HALT_TIMEOUT;
2494 if (1 == CMD_ARGC) {
2495 int retval = parse_uint(CMD_ARGV[0], &ms);
2496 if (ERROR_OK != retval)
2497 return ERROR_COMMAND_SYNTAX_ERROR;
2500 struct target *target = get_current_target(CMD_CTX);
2501 return target_wait_state(target, TARGET_HALTED, ms);
2504 /* wait for target state to change. The trick here is to have a low
2505 * latency for short waits and not to suck up all the CPU time
2506 * on longer waits.
2508 * After 500ms, keep_alive() is invoked
2510 int target_wait_state(struct target *target, enum target_state state, int ms)
2512 int retval;
2513 long long then = 0, cur;
2514 int once = 1;
2516 for (;;) {
2517 retval = target_poll(target);
2518 if (retval != ERROR_OK)
2519 return retval;
2520 if (target->state == state)
2521 break;
2522 cur = timeval_ms();
2523 if (once) {
2524 once = 0;
2525 then = timeval_ms();
2526 LOG_DEBUG("waiting for target %s...",
2527 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2530 if (cur-then > 500)
2531 keep_alive();
2533 if ((cur-then) > ms) {
2534 LOG_ERROR("timed out while waiting for target %s",
2535 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2536 return ERROR_FAIL;
2540 return ERROR_OK;
2543 COMMAND_HANDLER(handle_halt_command)
2545 LOG_DEBUG("-");
2547 struct target *target = get_current_target(CMD_CTX);
2548 int retval = target_halt(target);
2549 if (ERROR_OK != retval)
2550 return retval;
2552 if (CMD_ARGC == 1) {
2553 unsigned wait_local;
2554 retval = parse_uint(CMD_ARGV[0], &wait_local);
2555 if (ERROR_OK != retval)
2556 return ERROR_COMMAND_SYNTAX_ERROR;
2557 if (!wait_local)
2558 return ERROR_OK;
2561 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2564 COMMAND_HANDLER(handle_soft_reset_halt_command)
2566 struct target *target = get_current_target(CMD_CTX);
2568 LOG_USER("requesting target halt and executing a soft reset");
2570 target_soft_reset_halt(target);
2572 return ERROR_OK;
2575 COMMAND_HANDLER(handle_reset_command)
2577 if (CMD_ARGC > 1)
2578 return ERROR_COMMAND_SYNTAX_ERROR;
2580 enum target_reset_mode reset_mode = RESET_RUN;
2581 if (CMD_ARGC == 1) {
2582 const Jim_Nvp *n;
2583 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2584 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2585 return ERROR_COMMAND_SYNTAX_ERROR;
2586 reset_mode = n->value;
2589 /* reset *all* targets */
2590 return target_process_reset(CMD_CTX, reset_mode);
2594 COMMAND_HANDLER(handle_resume_command)
2596 int current = 1;
2597 if (CMD_ARGC > 1)
2598 return ERROR_COMMAND_SYNTAX_ERROR;
2600 struct target *target = get_current_target(CMD_CTX);
2602 /* with no CMD_ARGV, resume from current pc, addr = 0,
2603 * with one arguments, addr = CMD_ARGV[0],
2604 * handle breakpoints, not debugging */
2605 uint32_t addr = 0;
2606 if (CMD_ARGC == 1) {
2607 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2608 current = 0;
2611 return target_resume(target, current, addr, 1, 0);
2614 COMMAND_HANDLER(handle_step_command)
2616 if (CMD_ARGC > 1)
2617 return ERROR_COMMAND_SYNTAX_ERROR;
2619 LOG_DEBUG("-");
2621 /* with no CMD_ARGV, step from current pc, addr = 0,
2622 * with one argument addr = CMD_ARGV[0],
2623 * handle breakpoints, debugging */
2624 uint32_t addr = 0;
2625 int current_pc = 1;
2626 if (CMD_ARGC == 1) {
2627 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2628 current_pc = 0;
2631 struct target *target = get_current_target(CMD_CTX);
2633 return target->type->step(target, current_pc, addr, 1);
2636 static void handle_md_output(struct command_context *cmd_ctx,
2637 struct target *target, uint32_t address, unsigned size,
2638 unsigned count, const uint8_t *buffer)
2640 const unsigned line_bytecnt = 32;
2641 unsigned line_modulo = line_bytecnt / size;
2643 char output[line_bytecnt * 4 + 1];
2644 unsigned output_len = 0;
2646 const char *value_fmt;
2647 switch (size) {
2648 case 4:
2649 value_fmt = "%8.8x ";
2650 break;
2651 case 2:
2652 value_fmt = "%4.4x ";
2653 break;
2654 case 1:
2655 value_fmt = "%2.2x ";
2656 break;
2657 default:
2658 /* "can't happen", caller checked */
2659 LOG_ERROR("invalid memory read size: %u", size);
2660 return;
2663 for (unsigned i = 0; i < count; i++) {
2664 if (i % line_modulo == 0) {
2665 output_len += snprintf(output + output_len,
2666 sizeof(output) - output_len,
2667 "0x%8.8x: ",
2668 (unsigned)(address + (i*size)));
2671 uint32_t value = 0;
2672 const uint8_t *value_ptr = buffer + i * size;
2673 switch (size) {
2674 case 4:
2675 value = target_buffer_get_u32(target, value_ptr);
2676 break;
2677 case 2:
2678 value = target_buffer_get_u16(target, value_ptr);
2679 break;
2680 case 1:
2681 value = *value_ptr;
2683 output_len += snprintf(output + output_len,
2684 sizeof(output) - output_len,
2685 value_fmt, value);
2687 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2688 command_print(cmd_ctx, "%s", output);
2689 output_len = 0;
2694 COMMAND_HANDLER(handle_md_command)
2696 if (CMD_ARGC < 1)
2697 return ERROR_COMMAND_SYNTAX_ERROR;
2699 unsigned size = 0;
2700 switch (CMD_NAME[2]) {
2701 case 'w':
2702 size = 4;
2703 break;
2704 case 'h':
2705 size = 2;
2706 break;
2707 case 'b':
2708 size = 1;
2709 break;
2710 default:
2711 return ERROR_COMMAND_SYNTAX_ERROR;
2714 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2715 int (*fn)(struct target *target,
2716 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2717 if (physical) {
2718 CMD_ARGC--;
2719 CMD_ARGV++;
2720 fn = target_read_phys_memory;
2721 } else
2722 fn = target_read_memory;
2723 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2724 return ERROR_COMMAND_SYNTAX_ERROR;
2726 uint32_t address;
2727 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2729 unsigned count = 1;
2730 if (CMD_ARGC == 2)
2731 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2733 uint8_t *buffer = calloc(count, size);
2735 struct target *target = get_current_target(CMD_CTX);
2736 int retval = fn(target, address, size, count, buffer);
2737 if (ERROR_OK == retval)
2738 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2740 free(buffer);
2742 return retval;
2745 typedef int (*target_write_fn)(struct target *target,
2746 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2748 static int target_fill_mem(struct target *target,
2749 uint32_t address,
2750 target_write_fn fn,
2751 unsigned data_size,
2752 /* value */
2753 uint32_t b,
2754 /* count */
2755 unsigned c)
2757 /* We have to write in reasonably large chunks to be able
2758 * to fill large memory areas with any sane speed */
2759 const unsigned chunk_size = 16384;
2760 uint8_t *target_buf = malloc(chunk_size * data_size);
2761 if (target_buf == NULL) {
2762 LOG_ERROR("Out of memory");
2763 return ERROR_FAIL;
2766 for (unsigned i = 0; i < chunk_size; i++) {
2767 switch (data_size) {
2768 case 4:
2769 target_buffer_set_u32(target, target_buf + i * data_size, b);
2770 break;
2771 case 2:
2772 target_buffer_set_u16(target, target_buf + i * data_size, b);
2773 break;
2774 case 1:
2775 target_buffer_set_u8(target, target_buf + i * data_size, b);
2776 break;
2777 default:
2778 exit(-1);
2782 int retval = ERROR_OK;
2784 for (unsigned x = 0; x < c; x += chunk_size) {
2785 unsigned current;
2786 current = c - x;
2787 if (current > chunk_size)
2788 current = chunk_size;
2789 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2790 if (retval != ERROR_OK)
2791 break;
2792 /* avoid GDB timeouts */
2793 keep_alive();
2795 free(target_buf);
2797 return retval;
2801 COMMAND_HANDLER(handle_mw_command)
2803 if (CMD_ARGC < 2)
2804 return ERROR_COMMAND_SYNTAX_ERROR;
2805 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2806 target_write_fn fn;
2807 if (physical) {
2808 CMD_ARGC--;
2809 CMD_ARGV++;
2810 fn = target_write_phys_memory;
2811 } else
2812 fn = target_write_memory;
2813 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2814 return ERROR_COMMAND_SYNTAX_ERROR;
2816 uint32_t address;
2817 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2819 uint32_t value;
2820 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2822 unsigned count = 1;
2823 if (CMD_ARGC == 3)
2824 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2826 struct target *target = get_current_target(CMD_CTX);
2827 unsigned wordsize;
2828 switch (CMD_NAME[2]) {
2829 case 'w':
2830 wordsize = 4;
2831 break;
2832 case 'h':
2833 wordsize = 2;
2834 break;
2835 case 'b':
2836 wordsize = 1;
2837 break;
2838 default:
2839 return ERROR_COMMAND_SYNTAX_ERROR;
2842 return target_fill_mem(target, address, fn, wordsize, value, count);
2845 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2846 uint32_t *min_address, uint32_t *max_address)
2848 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2849 return ERROR_COMMAND_SYNTAX_ERROR;
2851 /* a base address isn't always necessary,
2852 * default to 0x0 (i.e. don't relocate) */
2853 if (CMD_ARGC >= 2) {
2854 uint32_t addr;
2855 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2856 image->base_address = addr;
2857 image->base_address_set = 1;
2858 } else
2859 image->base_address_set = 0;
2861 image->start_address_set = 0;
2863 if (CMD_ARGC >= 4)
2864 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2865 if (CMD_ARGC == 5) {
2866 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2867 /* use size (given) to find max (required) */
2868 *max_address += *min_address;
2871 if (*min_address > *max_address)
2872 return ERROR_COMMAND_SYNTAX_ERROR;
2874 return ERROR_OK;
2877 COMMAND_HANDLER(handle_load_image_command)
2879 uint8_t *buffer;
2880 size_t buf_cnt;
2881 uint32_t image_size;
2882 uint32_t min_address = 0;
2883 uint32_t max_address = 0xffffffff;
2884 int i;
2885 struct image image;
2887 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2888 &image, &min_address, &max_address);
2889 if (ERROR_OK != retval)
2890 return retval;
2892 struct target *target = get_current_target(CMD_CTX);
2894 struct duration bench;
2895 duration_start(&bench);
2897 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2898 return ERROR_OK;
2900 image_size = 0x0;
2901 retval = ERROR_OK;
2902 for (i = 0; i < image.num_sections; i++) {
2903 buffer = malloc(image.sections[i].size);
2904 if (buffer == NULL) {
2905 command_print(CMD_CTX,
2906 "error allocating buffer for section (%d bytes)",
2907 (int)(image.sections[i].size));
2908 break;
2911 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
2912 if (retval != ERROR_OK) {
2913 free(buffer);
2914 break;
2917 uint32_t offset = 0;
2918 uint32_t length = buf_cnt;
2920 /* DANGER!!! beware of unsigned comparision here!!! */
2922 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
2923 (image.sections[i].base_address < max_address)) {
2925 if (image.sections[i].base_address < min_address) {
2926 /* clip addresses below */
2927 offset += min_address-image.sections[i].base_address;
2928 length -= offset;
2931 if (image.sections[i].base_address + buf_cnt > max_address)
2932 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2934 retval = target_write_buffer(target,
2935 image.sections[i].base_address + offset, length, buffer + offset);
2936 if (retval != ERROR_OK) {
2937 free(buffer);
2938 break;
2940 image_size += length;
2941 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2942 (unsigned int)length,
2943 image.sections[i].base_address + offset);
2946 free(buffer);
2949 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
2950 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2951 "in %fs (%0.3f KiB/s)", image_size,
2952 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2955 image_close(&image);
2957 return retval;
2961 COMMAND_HANDLER(handle_dump_image_command)
2963 struct fileio fileio;
2964 uint8_t *buffer;
2965 int retval, retvaltemp;
2966 uint32_t address, size;
2967 struct duration bench;
2968 struct target *target = get_current_target(CMD_CTX);
2970 if (CMD_ARGC != 3)
2971 return ERROR_COMMAND_SYNTAX_ERROR;
2973 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2974 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2976 uint32_t buf_size = (size > 4096) ? 4096 : size;
2977 buffer = malloc(buf_size);
2978 if (!buffer)
2979 return ERROR_FAIL;
2981 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2982 if (retval != ERROR_OK) {
2983 free(buffer);
2984 return retval;
2987 duration_start(&bench);
2989 while (size > 0) {
2990 size_t size_written;
2991 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
2992 retval = target_read_buffer(target, address, this_run_size, buffer);
2993 if (retval != ERROR_OK)
2994 break;
2996 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2997 if (retval != ERROR_OK)
2998 break;
3000 size -= this_run_size;
3001 address += this_run_size;
3004 free(buffer);
3006 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3007 int filesize;
3008 retval = fileio_size(&fileio, &filesize);
3009 if (retval != ERROR_OK)
3010 return retval;
3011 command_print(CMD_CTX,
3012 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
3013 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3016 retvaltemp = fileio_close(&fileio);
3017 if (retvaltemp != ERROR_OK)
3018 return retvaltemp;
3020 return retval;
3023 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
3025 uint8_t *buffer;
3026 size_t buf_cnt;
3027 uint32_t image_size;
3028 int i;
3029 int retval;
3030 uint32_t checksum = 0;
3031 uint32_t mem_checksum = 0;
3033 struct image image;
3035 struct target *target = get_current_target(CMD_CTX);
3037 if (CMD_ARGC < 1)
3038 return ERROR_COMMAND_SYNTAX_ERROR;
3040 if (!target) {
3041 LOG_ERROR("no target selected");
3042 return ERROR_FAIL;
3045 struct duration bench;
3046 duration_start(&bench);
3048 if (CMD_ARGC >= 2) {
3049 uint32_t addr;
3050 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3051 image.base_address = addr;
3052 image.base_address_set = 1;
3053 } else {
3054 image.base_address_set = 0;
3055 image.base_address = 0x0;
3058 image.start_address_set = 0;
3060 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3061 if (retval != ERROR_OK)
3062 return retval;
3064 image_size = 0x0;
3065 int diffs = 0;
3066 retval = ERROR_OK;
3067 for (i = 0; i < image.num_sections; i++) {
3068 buffer = malloc(image.sections[i].size);
3069 if (buffer == NULL) {
3070 command_print(CMD_CTX,
3071 "error allocating buffer for section (%d bytes)",
3072 (int)(image.sections[i].size));
3073 break;
3075 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3076 if (retval != ERROR_OK) {
3077 free(buffer);
3078 break;
3081 if (verify) {
3082 /* calculate checksum of image */
3083 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3084 if (retval != ERROR_OK) {
3085 free(buffer);
3086 break;
3089 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3090 if (retval != ERROR_OK) {
3091 free(buffer);
3092 break;
3095 if (checksum != mem_checksum) {
3096 /* failed crc checksum, fall back to a binary compare */
3097 uint8_t *data;
3099 if (diffs == 0)
3100 LOG_ERROR("checksum mismatch - attempting binary compare");
3102 data = (uint8_t *)malloc(buf_cnt);
3104 /* Can we use 32bit word accesses? */
3105 int size = 1;
3106 int count = buf_cnt;
3107 if ((count % 4) == 0) {
3108 size *= 4;
3109 count /= 4;
3111 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3112 if (retval == ERROR_OK) {
3113 uint32_t t;
3114 for (t = 0; t < buf_cnt; t++) {
3115 if (data[t] != buffer[t]) {
3116 command_print(CMD_CTX,
3117 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3118 diffs,
3119 (unsigned)(t + image.sections[i].base_address),
3120 data[t],
3121 buffer[t]);
3122 if (diffs++ >= 127) {
3123 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3124 free(data);
3125 free(buffer);
3126 goto done;
3129 keep_alive();
3132 free(data);
3134 } else {
3135 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3136 image.sections[i].base_address,
3137 buf_cnt);
3140 free(buffer);
3141 image_size += buf_cnt;
3143 if (diffs > 0)
3144 command_print(CMD_CTX, "No more differences found.");
3145 done:
3146 if (diffs > 0)
3147 retval = ERROR_FAIL;
3148 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3149 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3150 "in %fs (%0.3f KiB/s)", image_size,
3151 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3154 image_close(&image);
3156 return retval;
3159 COMMAND_HANDLER(handle_verify_image_command)
3161 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3164 COMMAND_HANDLER(handle_test_image_command)
3166 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3169 static int handle_bp_command_list(struct command_context *cmd_ctx)
3171 struct target *target = get_current_target(cmd_ctx);
3172 struct breakpoint *breakpoint = target->breakpoints;
3173 while (breakpoint) {
3174 if (breakpoint->type == BKPT_SOFT) {
3175 char *buf = buf_to_str(breakpoint->orig_instr,
3176 breakpoint->length, 16);
3177 command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3178 breakpoint->address,
3179 breakpoint->length,
3180 breakpoint->set, buf);
3181 free(buf);
3182 } else {
3183 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3184 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3185 breakpoint->asid,
3186 breakpoint->length, breakpoint->set);
3187 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3188 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3189 breakpoint->address,
3190 breakpoint->length, breakpoint->set);
3191 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3192 breakpoint->asid);
3193 } else
3194 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3195 breakpoint->address,
3196 breakpoint->length, breakpoint->set);
3199 breakpoint = breakpoint->next;
3201 return ERROR_OK;
3204 static int handle_bp_command_set(struct command_context *cmd_ctx,
3205 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3207 struct target *target = get_current_target(cmd_ctx);
3209 if (asid == 0) {
3210 int retval = breakpoint_add(target, addr, length, hw);
3211 if (ERROR_OK == retval)
3212 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3213 else {
3214 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3215 return retval;
3217 } else if (addr == 0) {
3218 int retval = context_breakpoint_add(target, asid, length, hw);
3219 if (ERROR_OK == retval)
3220 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3221 else {
3222 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3223 return retval;
3225 } else {
3226 int retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3227 if (ERROR_OK == retval)
3228 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3229 else {
3230 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3231 return retval;
3234 return ERROR_OK;
3237 COMMAND_HANDLER(handle_bp_command)
3239 uint32_t addr;
3240 uint32_t asid;
3241 uint32_t length;
3242 int hw = BKPT_SOFT;
3244 switch (CMD_ARGC) {
3245 case 0:
3246 return handle_bp_command_list(CMD_CTX);
3248 case 2:
3249 asid = 0;
3250 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3251 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3252 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3254 case 3:
3255 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3256 hw = BKPT_HARD;
3257 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3259 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3261 asid = 0;
3262 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3263 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3264 hw = BKPT_HARD;
3265 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3266 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3267 addr = 0;
3268 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3271 case 4:
3272 hw = BKPT_HARD;
3273 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3274 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3275 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3276 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3278 default:
3279 return ERROR_COMMAND_SYNTAX_ERROR;
3283 COMMAND_HANDLER(handle_rbp_command)
3285 if (CMD_ARGC != 1)
3286 return ERROR_COMMAND_SYNTAX_ERROR;
3288 uint32_t addr;
3289 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3291 struct target *target = get_current_target(CMD_CTX);
3292 breakpoint_remove(target, addr);
3294 return ERROR_OK;
3297 COMMAND_HANDLER(handle_wp_command)
3299 struct target *target = get_current_target(CMD_CTX);
3301 if (CMD_ARGC == 0) {
3302 struct watchpoint *watchpoint = target->watchpoints;
3304 while (watchpoint) {
3305 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3306 ", len: 0x%8.8" PRIx32
3307 ", r/w/a: %i, value: 0x%8.8" PRIx32
3308 ", mask: 0x%8.8" PRIx32,
3309 watchpoint->address,
3310 watchpoint->length,
3311 (int)watchpoint->rw,
3312 watchpoint->value,
3313 watchpoint->mask);
3314 watchpoint = watchpoint->next;
3316 return ERROR_OK;
3319 enum watchpoint_rw type = WPT_ACCESS;
3320 uint32_t addr = 0;
3321 uint32_t length = 0;
3322 uint32_t data_value = 0x0;
3323 uint32_t data_mask = 0xffffffff;
3325 switch (CMD_ARGC) {
3326 case 5:
3327 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3328 /* fall through */
3329 case 4:
3330 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3331 /* fall through */
3332 case 3:
3333 switch (CMD_ARGV[2][0]) {
3334 case 'r':
3335 type = WPT_READ;
3336 break;
3337 case 'w':
3338 type = WPT_WRITE;
3339 break;
3340 case 'a':
3341 type = WPT_ACCESS;
3342 break;
3343 default:
3344 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3345 return ERROR_COMMAND_SYNTAX_ERROR;
3347 /* fall through */
3348 case 2:
3349 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3350 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3351 break;
3353 default:
3354 return ERROR_COMMAND_SYNTAX_ERROR;
3357 int retval = watchpoint_add(target, addr, length, type,
3358 data_value, data_mask);
3359 if (ERROR_OK != retval)
3360 LOG_ERROR("Failure setting watchpoints");
3362 return retval;
3365 COMMAND_HANDLER(handle_rwp_command)
3367 if (CMD_ARGC != 1)
3368 return ERROR_COMMAND_SYNTAX_ERROR;
3370 uint32_t addr;
3371 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3373 struct target *target = get_current_target(CMD_CTX);
3374 watchpoint_remove(target, addr);
3376 return ERROR_OK;
3380 * Translate a virtual address to a physical address.
3382 * The low-level target implementation must have logged a detailed error
3383 * which is forwarded to telnet/GDB session.
3385 COMMAND_HANDLER(handle_virt2phys_command)
3387 if (CMD_ARGC != 1)
3388 return ERROR_COMMAND_SYNTAX_ERROR;
3390 uint32_t va;
3391 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3392 uint32_t pa;
3394 struct target *target = get_current_target(CMD_CTX);
3395 int retval = target->type->virt2phys(target, va, &pa);
3396 if (retval == ERROR_OK)
3397 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3399 return retval;
3402 static void writeData(FILE *f, const void *data, size_t len)
3404 size_t written = fwrite(data, 1, len, f);
3405 if (written != len)
3406 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3409 static void writeLong(FILE *f, int l)
3411 int i;
3412 for (i = 0; i < 4; i++) {
3413 char c = (l >> (i*8))&0xff;
3414 writeData(f, &c, 1);
3419 static void writeString(FILE *f, char *s)
3421 writeData(f, s, strlen(s));
3424 typedef unsigned char UNIT[2]; /* unit of profiling */
3426 /* Dump a gmon.out histogram file. */
3427 static void write_gmon(uint32_t *samples, uint32_t sampleNum, const char *filename,
3428 bool with_range, uint32_t start_address, uint32_t end_address)
3430 uint32_t i;
3431 FILE *f = fopen(filename, "w");
3432 if (f == NULL)
3433 return;
3434 writeString(f, "gmon");
3435 writeLong(f, 0x00000001); /* Version */
3436 writeLong(f, 0); /* padding */
3437 writeLong(f, 0); /* padding */
3438 writeLong(f, 0); /* padding */
3440 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3441 writeData(f, &zero, 1);
3443 /* figure out bucket size */
3444 uint32_t min;
3445 uint32_t max;
3446 if (with_range) {
3447 min = start_address;
3448 max = end_address;
3449 } else {
3450 min = samples[0];
3451 max = samples[0];
3452 for (i = 0; i < sampleNum; i++) {
3453 if (min > samples[i])
3454 min = samples[i];
3455 if (max < samples[i])
3456 max = samples[i];
3459 /* max should be (largest sample + 1)
3460 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
3461 max++;
3464 int addressSpace = max - min;
3465 assert(addressSpace >= 2);
3467 /* FIXME: What is the reasonable number of buckets?
3468 * The profiling result will be more accurate if there are enough buckets. */
3469 static const uint32_t maxBuckets = 128 * 1024; /* maximum buckets. */
3470 uint32_t numBuckets = addressSpace / sizeof(UNIT);
3471 if (numBuckets > maxBuckets)
3472 numBuckets = maxBuckets;
3473 int *buckets = malloc(sizeof(int) * numBuckets);
3474 if (buckets == NULL) {
3475 fclose(f);
3476 return;
3478 memset(buckets, 0, sizeof(int) * numBuckets);
3479 for (i = 0; i < sampleNum; i++) {
3480 uint32_t address = samples[i];
3482 if ((address < min) || (max <= address))
3483 continue;
3485 long long a = address - min;
3486 long long b = numBuckets;
3487 long long c = addressSpace;
3488 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3489 buckets[index_t]++;
3492 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3493 writeLong(f, min); /* low_pc */
3494 writeLong(f, max); /* high_pc */
3495 writeLong(f, numBuckets); /* # of buckets */
3496 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3497 writeString(f, "seconds");
3498 for (i = 0; i < (15-strlen("seconds")); i++)
3499 writeData(f, &zero, 1);
3500 writeString(f, "s");
3502 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3504 char *data = malloc(2 * numBuckets);
3505 if (data != NULL) {
3506 for (i = 0; i < numBuckets; i++) {
3507 int val;
3508 val = buckets[i];
3509 if (val > 65535)
3510 val = 65535;
3511 data[i * 2] = val&0xff;
3512 data[i * 2 + 1] = (val >> 8) & 0xff;
3514 free(buckets);
3515 writeData(f, data, numBuckets * 2);
3516 free(data);
3517 } else
3518 free(buckets);
3520 fclose(f);
3523 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3524 * which will be used as a random sampling of PC */
3525 COMMAND_HANDLER(handle_profile_command)
3527 struct target *target = get_current_target(CMD_CTX);
3529 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
3530 return ERROR_COMMAND_SYNTAX_ERROR;
3532 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
3533 uint32_t offset;
3534 uint32_t num_of_sampels;
3535 int retval = ERROR_OK;
3536 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
3537 if (samples == NULL) {
3538 LOG_ERROR("No memory to store samples.");
3539 return ERROR_FAIL;
3542 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3545 * Some cores let us sample the PC without the
3546 * annoying halt/resume step; for example, ARMv7 PCSR.
3547 * Provide a way to use that more efficient mechanism.
3549 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
3550 &num_of_sampels, offset);
3551 if (retval != ERROR_OK) {
3552 free(samples);
3553 return retval;
3556 assert(num_of_sampels <= MAX_PROFILE_SAMPLE_NUM);
3558 retval = target_poll(target);
3559 if (retval != ERROR_OK) {
3560 free(samples);
3561 return retval;
3563 if (target->state == TARGET_RUNNING) {
3564 retval = target_halt(target);
3565 if (retval != ERROR_OK) {
3566 free(samples);
3567 return retval;
3571 retval = target_poll(target);
3572 if (retval != ERROR_OK) {
3573 free(samples);
3574 return retval;
3577 uint32_t start_address = 0;
3578 uint32_t end_address = 0;
3579 bool with_range = false;
3580 if (CMD_ARGC == 4) {
3581 with_range = true;
3582 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], start_address);
3583 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[3], end_address);
3586 write_gmon(samples, num_of_sampels, CMD_ARGV[1],
3587 with_range, start_address, end_address);
3588 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3590 free(samples);
3591 return retval;
3594 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3596 char *namebuf;
3597 Jim_Obj *nameObjPtr, *valObjPtr;
3598 int result;
3600 namebuf = alloc_printf("%s(%d)", varname, idx);
3601 if (!namebuf)
3602 return JIM_ERR;
3604 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3605 valObjPtr = Jim_NewIntObj(interp, val);
3606 if (!nameObjPtr || !valObjPtr) {
3607 free(namebuf);
3608 return JIM_ERR;
3611 Jim_IncrRefCount(nameObjPtr);
3612 Jim_IncrRefCount(valObjPtr);
3613 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3614 Jim_DecrRefCount(interp, nameObjPtr);
3615 Jim_DecrRefCount(interp, valObjPtr);
3616 free(namebuf);
3617 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3618 return result;
3621 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3623 struct command_context *context;
3624 struct target *target;
3626 context = current_command_context(interp);
3627 assert(context != NULL);
3629 target = get_current_target(context);
3630 if (target == NULL) {
3631 LOG_ERROR("mem2array: no current target");
3632 return JIM_ERR;
3635 return target_mem2array(interp, target, argc - 1, argv + 1);
3638 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3640 long l;
3641 uint32_t width;
3642 int len;
3643 uint32_t addr;
3644 uint32_t count;
3645 uint32_t v;
3646 const char *varname;
3647 int n, e, retval;
3648 uint32_t i;
3650 /* argv[1] = name of array to receive the data
3651 * argv[2] = desired width
3652 * argv[3] = memory address
3653 * argv[4] = count of times to read
3655 if (argc != 4) {
3656 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3657 return JIM_ERR;
3659 varname = Jim_GetString(argv[0], &len);
3660 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3662 e = Jim_GetLong(interp, argv[1], &l);
3663 width = l;
3664 if (e != JIM_OK)
3665 return e;
3667 e = Jim_GetLong(interp, argv[2], &l);
3668 addr = l;
3669 if (e != JIM_OK)
3670 return e;
3671 e = Jim_GetLong(interp, argv[3], &l);
3672 len = l;
3673 if (e != JIM_OK)
3674 return e;
3675 switch (width) {
3676 case 8:
3677 width = 1;
3678 break;
3679 case 16:
3680 width = 2;
3681 break;
3682 case 32:
3683 width = 4;
3684 break;
3685 default:
3686 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3687 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3688 return JIM_ERR;
3690 if (len == 0) {
3691 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3692 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3693 return JIM_ERR;
3695 if ((addr + (len * width)) < addr) {
3696 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3697 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3698 return JIM_ERR;
3700 /* absurd transfer size? */
3701 if (len > 65536) {
3702 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3703 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3704 return JIM_ERR;
3707 if ((width == 1) ||
3708 ((width == 2) && ((addr & 1) == 0)) ||
3709 ((width == 4) && ((addr & 3) == 0))) {
3710 /* all is well */
3711 } else {
3712 char buf[100];
3713 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3714 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3715 addr,
3716 width);
3717 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3718 return JIM_ERR;
3721 /* Transfer loop */
3723 /* index counter */
3724 n = 0;
3726 size_t buffersize = 4096;
3727 uint8_t *buffer = malloc(buffersize);
3728 if (buffer == NULL)
3729 return JIM_ERR;
3731 /* assume ok */
3732 e = JIM_OK;
3733 while (len) {
3734 /* Slurp... in buffer size chunks */
3736 count = len; /* in objects.. */
3737 if (count > (buffersize / width))
3738 count = (buffersize / width);
3740 retval = target_read_memory(target, addr, width, count, buffer);
3741 if (retval != ERROR_OK) {
3742 /* BOO !*/
3743 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3744 (unsigned int)addr,
3745 (int)width,
3746 (int)count);
3747 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3748 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3749 e = JIM_ERR;
3750 break;
3751 } else {
3752 v = 0; /* shut up gcc */
3753 for (i = 0; i < count ; i++, n++) {
3754 switch (width) {
3755 case 4:
3756 v = target_buffer_get_u32(target, &buffer[i*width]);
3757 break;
3758 case 2:
3759 v = target_buffer_get_u16(target, &buffer[i*width]);
3760 break;
3761 case 1:
3762 v = buffer[i] & 0x0ff;
3763 break;
3765 new_int_array_element(interp, varname, n, v);
3767 len -= count;
3771 free(buffer);
3773 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3775 return e;
3778 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
3780 char *namebuf;
3781 Jim_Obj *nameObjPtr, *valObjPtr;
3782 int result;
3783 long l;
3785 namebuf = alloc_printf("%s(%d)", varname, idx);
3786 if (!namebuf)
3787 return JIM_ERR;
3789 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3790 if (!nameObjPtr) {
3791 free(namebuf);
3792 return JIM_ERR;
3795 Jim_IncrRefCount(nameObjPtr);
3796 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3797 Jim_DecrRefCount(interp, nameObjPtr);
3798 free(namebuf);
3799 if (valObjPtr == NULL)
3800 return JIM_ERR;
3802 result = Jim_GetLong(interp, valObjPtr, &l);
3803 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3804 *val = l;
3805 return result;
3808 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3810 struct command_context *context;
3811 struct target *target;
3813 context = current_command_context(interp);
3814 assert(context != NULL);
3816 target = get_current_target(context);
3817 if (target == NULL) {
3818 LOG_ERROR("array2mem: no current target");
3819 return JIM_ERR;
3822 return target_array2mem(interp, target, argc-1, argv + 1);
3825 static int target_array2mem(Jim_Interp *interp, struct target *target,
3826 int argc, Jim_Obj *const *argv)
3828 long l;
3829 uint32_t width;
3830 int len;
3831 uint32_t addr;
3832 uint32_t count;
3833 uint32_t v;
3834 const char *varname;
3835 int n, e, retval;
3836 uint32_t i;
3838 /* argv[1] = name of array to get the data
3839 * argv[2] = desired width
3840 * argv[3] = memory address
3841 * argv[4] = count to write
3843 if (argc != 4) {
3844 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3845 return JIM_ERR;
3847 varname = Jim_GetString(argv[0], &len);
3848 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3850 e = Jim_GetLong(interp, argv[1], &l);
3851 width = l;
3852 if (e != JIM_OK)
3853 return e;
3855 e = Jim_GetLong(interp, argv[2], &l);
3856 addr = l;
3857 if (e != JIM_OK)
3858 return e;
3859 e = Jim_GetLong(interp, argv[3], &l);
3860 len = l;
3861 if (e != JIM_OK)
3862 return e;
3863 switch (width) {
3864 case 8:
3865 width = 1;
3866 break;
3867 case 16:
3868 width = 2;
3869 break;
3870 case 32:
3871 width = 4;
3872 break;
3873 default:
3874 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3875 Jim_AppendStrings(interp, Jim_GetResult(interp),
3876 "Invalid width param, must be 8/16/32", NULL);
3877 return JIM_ERR;
3879 if (len == 0) {
3880 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3881 Jim_AppendStrings(interp, Jim_GetResult(interp),
3882 "array2mem: zero width read?", NULL);
3883 return JIM_ERR;
3885 if ((addr + (len * width)) < addr) {
3886 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3887 Jim_AppendStrings(interp, Jim_GetResult(interp),
3888 "array2mem: addr + len - wraps to zero?", NULL);
3889 return JIM_ERR;
3891 /* absurd transfer size? */
3892 if (len > 65536) {
3893 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3894 Jim_AppendStrings(interp, Jim_GetResult(interp),
3895 "array2mem: absurd > 64K item request", NULL);
3896 return JIM_ERR;
3899 if ((width == 1) ||
3900 ((width == 2) && ((addr & 1) == 0)) ||
3901 ((width == 4) && ((addr & 3) == 0))) {
3902 /* all is well */
3903 } else {
3904 char buf[100];
3905 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3906 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3907 (unsigned int)addr,
3908 (int)width);
3909 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3910 return JIM_ERR;
3913 /* Transfer loop */
3915 /* index counter */
3916 n = 0;
3917 /* assume ok */
3918 e = JIM_OK;
3920 size_t buffersize = 4096;
3921 uint8_t *buffer = malloc(buffersize);
3922 if (buffer == NULL)
3923 return JIM_ERR;
3925 while (len) {
3926 /* Slurp... in buffer size chunks */
3928 count = len; /* in objects.. */
3929 if (count > (buffersize / width))
3930 count = (buffersize / width);
3932 v = 0; /* shut up gcc */
3933 for (i = 0; i < count; i++, n++) {
3934 get_int_array_element(interp, varname, n, &v);
3935 switch (width) {
3936 case 4:
3937 target_buffer_set_u32(target, &buffer[i * width], v);
3938 break;
3939 case 2:
3940 target_buffer_set_u16(target, &buffer[i * width], v);
3941 break;
3942 case 1:
3943 buffer[i] = v & 0x0ff;
3944 break;
3947 len -= count;
3949 retval = target_write_memory(target, addr, width, count, buffer);
3950 if (retval != ERROR_OK) {
3951 /* BOO !*/
3952 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3953 (unsigned int)addr,
3954 (int)width,
3955 (int)count);
3956 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3957 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3958 e = JIM_ERR;
3959 break;
3963 free(buffer);
3965 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3967 return e;
3970 /* FIX? should we propagate errors here rather than printing them
3971 * and continuing?
3973 void target_handle_event(struct target *target, enum target_event e)
3975 struct target_event_action *teap;
3977 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3978 if (teap->event == e) {
3979 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3980 target->target_number,
3981 target_name(target),
3982 target_type_name(target),
3984 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3985 Jim_GetString(teap->body, NULL));
3986 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
3987 Jim_MakeErrorMessage(teap->interp);
3988 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
3995 * Returns true only if the target has a handler for the specified event.
3997 bool target_has_event_action(struct target *target, enum target_event event)
3999 struct target_event_action *teap;
4001 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4002 if (teap->event == event)
4003 return true;
4005 return false;
4008 enum target_cfg_param {
4009 TCFG_TYPE,
4010 TCFG_EVENT,
4011 TCFG_WORK_AREA_VIRT,
4012 TCFG_WORK_AREA_PHYS,
4013 TCFG_WORK_AREA_SIZE,
4014 TCFG_WORK_AREA_BACKUP,
4015 TCFG_ENDIAN,
4016 TCFG_VARIANT,
4017 TCFG_COREID,
4018 TCFG_CHAIN_POSITION,
4019 TCFG_DBGBASE,
4020 TCFG_RTOS,
4023 static Jim_Nvp nvp_config_opts[] = {
4024 { .name = "-type", .value = TCFG_TYPE },
4025 { .name = "-event", .value = TCFG_EVENT },
4026 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4027 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4028 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4029 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4030 { .name = "-endian" , .value = TCFG_ENDIAN },
4031 { .name = "-variant", .value = TCFG_VARIANT },
4032 { .name = "-coreid", .value = TCFG_COREID },
4033 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4034 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4035 { .name = "-rtos", .value = TCFG_RTOS },
4036 { .name = NULL, .value = -1 }
4039 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
4041 Jim_Nvp *n;
4042 Jim_Obj *o;
4043 jim_wide w;
4044 char *cp;
4045 int e;
4047 /* parse config or cget options ... */
4048 while (goi->argc > 0) {
4049 Jim_SetEmptyResult(goi->interp);
4050 /* Jim_GetOpt_Debug(goi); */
4052 if (target->type->target_jim_configure) {
4053 /* target defines a configure function */
4054 /* target gets first dibs on parameters */
4055 e = (*(target->type->target_jim_configure))(target, goi);
4056 if (e == JIM_OK) {
4057 /* more? */
4058 continue;
4060 if (e == JIM_ERR) {
4061 /* An error */
4062 return e;
4064 /* otherwise we 'continue' below */
4066 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
4067 if (e != JIM_OK) {
4068 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
4069 return e;
4071 switch (n->value) {
4072 case TCFG_TYPE:
4073 /* not setable */
4074 if (goi->isconfigure) {
4075 Jim_SetResultFormatted(goi->interp,
4076 "not settable: %s", n->name);
4077 return JIM_ERR;
4078 } else {
4079 no_params:
4080 if (goi->argc != 0) {
4081 Jim_WrongNumArgs(goi->interp,
4082 goi->argc, goi->argv,
4083 "NO PARAMS");
4084 return JIM_ERR;
4087 Jim_SetResultString(goi->interp,
4088 target_type_name(target), -1);
4089 /* loop for more */
4090 break;
4091 case TCFG_EVENT:
4092 if (goi->argc == 0) {
4093 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4094 return JIM_ERR;
4097 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4098 if (e != JIM_OK) {
4099 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4100 return e;
4103 if (goi->isconfigure) {
4104 if (goi->argc != 1) {
4105 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4106 return JIM_ERR;
4108 } else {
4109 if (goi->argc != 0) {
4110 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4111 return JIM_ERR;
4116 struct target_event_action *teap;
4118 teap = target->event_action;
4119 /* replace existing? */
4120 while (teap) {
4121 if (teap->event == (enum target_event)n->value)
4122 break;
4123 teap = teap->next;
4126 if (goi->isconfigure) {
4127 bool replace = true;
4128 if (teap == NULL) {
4129 /* create new */
4130 teap = calloc(1, sizeof(*teap));
4131 replace = false;
4133 teap->event = n->value;
4134 teap->interp = goi->interp;
4135 Jim_GetOpt_Obj(goi, &o);
4136 if (teap->body)
4137 Jim_DecrRefCount(teap->interp, teap->body);
4138 teap->body = Jim_DuplicateObj(goi->interp, o);
4140 * FIXME:
4141 * Tcl/TK - "tk events" have a nice feature.
4142 * See the "BIND" command.
4143 * We should support that here.
4144 * You can specify %X and %Y in the event code.
4145 * The idea is: %T - target name.
4146 * The idea is: %N - target number
4147 * The idea is: %E - event name.
4149 Jim_IncrRefCount(teap->body);
4151 if (!replace) {
4152 /* add to head of event list */
4153 teap->next = target->event_action;
4154 target->event_action = teap;
4156 Jim_SetEmptyResult(goi->interp);
4157 } else {
4158 /* get */
4159 if (teap == NULL)
4160 Jim_SetEmptyResult(goi->interp);
4161 else
4162 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4165 /* loop for more */
4166 break;
4168 case TCFG_WORK_AREA_VIRT:
4169 if (goi->isconfigure) {
4170 target_free_all_working_areas(target);
4171 e = Jim_GetOpt_Wide(goi, &w);
4172 if (e != JIM_OK)
4173 return e;
4174 target->working_area_virt = w;
4175 target->working_area_virt_spec = true;
4176 } else {
4177 if (goi->argc != 0)
4178 goto no_params;
4180 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4181 /* loop for more */
4182 break;
4184 case TCFG_WORK_AREA_PHYS:
4185 if (goi->isconfigure) {
4186 target_free_all_working_areas(target);
4187 e = Jim_GetOpt_Wide(goi, &w);
4188 if (e != JIM_OK)
4189 return e;
4190 target->working_area_phys = w;
4191 target->working_area_phys_spec = true;
4192 } else {
4193 if (goi->argc != 0)
4194 goto no_params;
4196 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4197 /* loop for more */
4198 break;
4200 case TCFG_WORK_AREA_SIZE:
4201 if (goi->isconfigure) {
4202 target_free_all_working_areas(target);
4203 e = Jim_GetOpt_Wide(goi, &w);
4204 if (e != JIM_OK)
4205 return e;
4206 target->working_area_size = w;
4207 } else {
4208 if (goi->argc != 0)
4209 goto no_params;
4211 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4212 /* loop for more */
4213 break;
4215 case TCFG_WORK_AREA_BACKUP:
4216 if (goi->isconfigure) {
4217 target_free_all_working_areas(target);
4218 e = Jim_GetOpt_Wide(goi, &w);
4219 if (e != JIM_OK)
4220 return e;
4221 /* make this exactly 1 or 0 */
4222 target->backup_working_area = (!!w);
4223 } else {
4224 if (goi->argc != 0)
4225 goto no_params;
4227 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4228 /* loop for more e*/
4229 break;
4232 case TCFG_ENDIAN:
4233 if (goi->isconfigure) {
4234 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4235 if (e != JIM_OK) {
4236 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4237 return e;
4239 target->endianness = n->value;
4240 } else {
4241 if (goi->argc != 0)
4242 goto no_params;
4244 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4245 if (n->name == NULL) {
4246 target->endianness = TARGET_LITTLE_ENDIAN;
4247 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4249 Jim_SetResultString(goi->interp, n->name, -1);
4250 /* loop for more */
4251 break;
4253 case TCFG_VARIANT:
4254 if (goi->isconfigure) {
4255 if (goi->argc < 1) {
4256 Jim_SetResultFormatted(goi->interp,
4257 "%s ?STRING?",
4258 n->name);
4259 return JIM_ERR;
4261 if (target->variant)
4262 free((void *)(target->variant));
4263 e = Jim_GetOpt_String(goi, &cp, NULL);
4264 if (e != JIM_OK)
4265 return e;
4266 target->variant = strdup(cp);
4267 } else {
4268 if (goi->argc != 0)
4269 goto no_params;
4271 Jim_SetResultString(goi->interp, target->variant, -1);
4272 /* loop for more */
4273 break;
4275 case TCFG_COREID:
4276 if (goi->isconfigure) {
4277 e = Jim_GetOpt_Wide(goi, &w);
4278 if (e != JIM_OK)
4279 return e;
4280 target->coreid = (int32_t)w;
4281 } else {
4282 if (goi->argc != 0)
4283 goto no_params;
4285 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4286 /* loop for more */
4287 break;
4289 case TCFG_CHAIN_POSITION:
4290 if (goi->isconfigure) {
4291 Jim_Obj *o_t;
4292 struct jtag_tap *tap;
4293 target_free_all_working_areas(target);
4294 e = Jim_GetOpt_Obj(goi, &o_t);
4295 if (e != JIM_OK)
4296 return e;
4297 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4298 if (tap == NULL)
4299 return JIM_ERR;
4300 /* make this exactly 1 or 0 */
4301 target->tap = tap;
4302 } else {
4303 if (goi->argc != 0)
4304 goto no_params;
4306 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4307 /* loop for more e*/
4308 break;
4309 case TCFG_DBGBASE:
4310 if (goi->isconfigure) {
4311 e = Jim_GetOpt_Wide(goi, &w);
4312 if (e != JIM_OK)
4313 return e;
4314 target->dbgbase = (uint32_t)w;
4315 target->dbgbase_set = true;
4316 } else {
4317 if (goi->argc != 0)
4318 goto no_params;
4320 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4321 /* loop for more */
4322 break;
4324 case TCFG_RTOS:
4325 /* RTOS */
4327 int result = rtos_create(goi, target);
4328 if (result != JIM_OK)
4329 return result;
4331 /* loop for more */
4332 break;
4334 } /* while (goi->argc) */
4337 /* done - we return */
4338 return JIM_OK;
4341 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4343 Jim_GetOptInfo goi;
4345 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4346 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4347 int need_args = 1 + goi.isconfigure;
4348 if (goi.argc < need_args) {
4349 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4350 goi.isconfigure
4351 ? "missing: -option VALUE ..."
4352 : "missing: -option ...");
4353 return JIM_ERR;
4355 struct target *target = Jim_CmdPrivData(goi.interp);
4356 return target_configure(&goi, target);
4359 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4361 const char *cmd_name = Jim_GetString(argv[0], NULL);
4363 Jim_GetOptInfo goi;
4364 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4366 if (goi.argc < 2 || goi.argc > 4) {
4367 Jim_SetResultFormatted(goi.interp,
4368 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4369 return JIM_ERR;
4372 target_write_fn fn;
4373 fn = target_write_memory;
4375 int e;
4376 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4377 /* consume it */
4378 struct Jim_Obj *obj;
4379 e = Jim_GetOpt_Obj(&goi, &obj);
4380 if (e != JIM_OK)
4381 return e;
4383 fn = target_write_phys_memory;
4386 jim_wide a;
4387 e = Jim_GetOpt_Wide(&goi, &a);
4388 if (e != JIM_OK)
4389 return e;
4391 jim_wide b;
4392 e = Jim_GetOpt_Wide(&goi, &b);
4393 if (e != JIM_OK)
4394 return e;
4396 jim_wide c = 1;
4397 if (goi.argc == 1) {
4398 e = Jim_GetOpt_Wide(&goi, &c);
4399 if (e != JIM_OK)
4400 return e;
4403 /* all args must be consumed */
4404 if (goi.argc != 0)
4405 return JIM_ERR;
4407 struct target *target = Jim_CmdPrivData(goi.interp);
4408 unsigned data_size;
4409 if (strcasecmp(cmd_name, "mww") == 0)
4410 data_size = 4;
4411 else if (strcasecmp(cmd_name, "mwh") == 0)
4412 data_size = 2;
4413 else if (strcasecmp(cmd_name, "mwb") == 0)
4414 data_size = 1;
4415 else {
4416 LOG_ERROR("command '%s' unknown: ", cmd_name);
4417 return JIM_ERR;
4420 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4424 * @brief Reads an array of words/halfwords/bytes from target memory starting at specified address.
4426 * Usage: mdw [phys] <address> [<count>] - for 32 bit reads
4427 * mdh [phys] <address> [<count>] - for 16 bit reads
4428 * mdb [phys] <address> [<count>] - for 8 bit reads
4430 * Count defaults to 1.
4432 * Calls target_read_memory or target_read_phys_memory depending on
4433 * the presence of the "phys" argument
4434 * Reads the target memory in blocks of max. 32 bytes, and returns an array of ints formatted
4435 * to int representation in base16.
4436 * Also outputs read data in a human readable form using command_print
4438 * @param phys if present target_read_phys_memory will be used instead of target_read_memory
4439 * @param address address where to start the read. May be specified in decimal or hex using the standard "0x" prefix
4440 * @param count optional count parameter to read an array of values. If not specified, defaults to 1.
4441 * @returns: JIM_ERR on error or JIM_OK on success and sets the result string to an array of ascii formatted numbers
4442 * on success, with [<count>] number of elements.
4444 * In case of little endian target:
4445 * Example1: "mdw 0x00000000" returns "10123456"
4446 * Exmaple2: "mdh 0x00000000 1" returns "3456"
4447 * Example3: "mdb 0x00000000" returns "56"
4448 * Example4: "mdh 0x00000000 2" returns "3456 1012"
4449 * Example5: "mdb 0x00000000 3" returns "56 34 12"
4451 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4453 const char *cmd_name = Jim_GetString(argv[0], NULL);
4455 Jim_GetOptInfo goi;
4456 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4458 if ((goi.argc < 1) || (goi.argc > 3)) {
4459 Jim_SetResultFormatted(goi.interp,
4460 "usage: %s [phys] <address> [<count>]", cmd_name);
4461 return JIM_ERR;
4464 int (*fn)(struct target *target,
4465 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4466 fn = target_read_memory;
4468 int e;
4469 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4470 /* consume it */
4471 struct Jim_Obj *obj;
4472 e = Jim_GetOpt_Obj(&goi, &obj);
4473 if (e != JIM_OK)
4474 return e;
4476 fn = target_read_phys_memory;
4479 /* Read address parameter */
4480 jim_wide addr;
4481 e = Jim_GetOpt_Wide(&goi, &addr);
4482 if (e != JIM_OK)
4483 return JIM_ERR;
4485 /* If next parameter exists, read it out as the count parameter, if not, set it to 1 (default) */
4486 jim_wide count;
4487 if (goi.argc == 1) {
4488 e = Jim_GetOpt_Wide(&goi, &count);
4489 if (e != JIM_OK)
4490 return JIM_ERR;
4491 } else
4492 count = 1;
4494 /* all args must be consumed */
4495 if (goi.argc != 0)
4496 return JIM_ERR;
4498 jim_wide dwidth = 1; /* shut up gcc */
4499 if (strcasecmp(cmd_name, "mdw") == 0)
4500 dwidth = 4;
4501 else if (strcasecmp(cmd_name, "mdh") == 0)
4502 dwidth = 2;
4503 else if (strcasecmp(cmd_name, "mdb") == 0)
4504 dwidth = 1;
4505 else {
4506 LOG_ERROR("command '%s' unknown: ", cmd_name);
4507 return JIM_ERR;
4510 /* convert count to "bytes" */
4511 int bytes = count * dwidth;
4513 struct target *target = Jim_CmdPrivData(goi.interp);
4514 uint8_t target_buf[32];
4515 jim_wide x, y, z;
4516 while (bytes > 0) {
4517 y = (bytes < 16) ? bytes : 16; /* y = min(bytes, 16); */
4519 /* Try to read out next block */
4520 e = fn(target, addr, dwidth, y / dwidth, target_buf);
4522 if (e != ERROR_OK) {
4523 Jim_SetResultFormatted(interp, "error reading target @ 0x%08lx", (long)addr);
4524 return JIM_ERR;
4527 command_print_sameline(NULL, "0x%08x ", (int)(addr));
4528 switch (dwidth) {
4529 case 4:
4530 for (x = 0; x < 16 && x < y; x += 4) {
4531 z = target_buffer_get_u32(target, &(target_buf[x]));
4532 command_print_sameline(NULL, "%08x ", (int)(z));
4534 for (; (x < 16) ; x += 4)
4535 command_print_sameline(NULL, " ");
4536 break;
4537 case 2:
4538 for (x = 0; x < 16 && x < y; x += 2) {
4539 z = target_buffer_get_u16(target, &(target_buf[x]));
4540 command_print_sameline(NULL, "%04x ", (int)(z));
4542 for (; (x < 16) ; x += 2)
4543 command_print_sameline(NULL, " ");
4544 break;
4545 case 1:
4546 default:
4547 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4548 z = target_buffer_get_u8(target, &(target_buf[x]));
4549 command_print_sameline(NULL, "%02x ", (int)(z));
4551 for (; (x < 16) ; x += 1)
4552 command_print_sameline(NULL, " ");
4553 break;
4555 /* ascii-ify the bytes */
4556 for (x = 0 ; x < y ; x++) {
4557 if ((target_buf[x] >= 0x20) &&
4558 (target_buf[x] <= 0x7e)) {
4559 /* good */
4560 } else {
4561 /* smack it */
4562 target_buf[x] = '.';
4565 /* space pad */
4566 while (x < 16) {
4567 target_buf[x] = ' ';
4568 x++;
4570 /* terminate */
4571 target_buf[16] = 0;
4572 /* print - with a newline */
4573 command_print_sameline(NULL, "%s\n", target_buf);
4574 /* NEXT... */
4575 bytes -= 16;
4576 addr += 16;
4578 return JIM_OK;
4581 static int jim_target_mem2array(Jim_Interp *interp,
4582 int argc, Jim_Obj *const *argv)
4584 struct target *target = Jim_CmdPrivData(interp);
4585 return target_mem2array(interp, target, argc - 1, argv + 1);
4588 static int jim_target_array2mem(Jim_Interp *interp,
4589 int argc, Jim_Obj *const *argv)
4591 struct target *target = Jim_CmdPrivData(interp);
4592 return target_array2mem(interp, target, argc - 1, argv + 1);
4595 static int jim_target_tap_disabled(Jim_Interp *interp)
4597 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4598 return JIM_ERR;
4601 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4603 if (argc != 1) {
4604 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4605 return JIM_ERR;
4607 struct target *target = Jim_CmdPrivData(interp);
4608 if (!target->tap->enabled)
4609 return jim_target_tap_disabled(interp);
4611 int e = target->type->examine(target);
4612 if (e != ERROR_OK)
4613 return JIM_ERR;
4614 return JIM_OK;
4617 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4619 if (argc != 1) {
4620 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4621 return JIM_ERR;
4623 struct target *target = Jim_CmdPrivData(interp);
4625 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4626 return JIM_ERR;
4628 return JIM_OK;
4631 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4633 if (argc != 1) {
4634 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4635 return JIM_ERR;
4637 struct target *target = Jim_CmdPrivData(interp);
4638 if (!target->tap->enabled)
4639 return jim_target_tap_disabled(interp);
4641 int e;
4642 if (!(target_was_examined(target)))
4643 e = ERROR_TARGET_NOT_EXAMINED;
4644 else
4645 e = target->type->poll(target);
4646 if (e != ERROR_OK)
4647 return JIM_ERR;
4648 return JIM_OK;
4651 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4653 Jim_GetOptInfo goi;
4654 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4656 if (goi.argc != 2) {
4657 Jim_WrongNumArgs(interp, 0, argv,
4658 "([tT]|[fF]|assert|deassert) BOOL");
4659 return JIM_ERR;
4662 Jim_Nvp *n;
4663 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4664 if (e != JIM_OK) {
4665 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4666 return e;
4668 /* the halt or not param */
4669 jim_wide a;
4670 e = Jim_GetOpt_Wide(&goi, &a);
4671 if (e != JIM_OK)
4672 return e;
4674 struct target *target = Jim_CmdPrivData(goi.interp);
4675 if (!target->tap->enabled)
4676 return jim_target_tap_disabled(interp);
4677 if (!(target_was_examined(target))) {
4678 LOG_ERROR("Target not examined yet");
4679 return ERROR_TARGET_NOT_EXAMINED;
4681 if (!target->type->assert_reset || !target->type->deassert_reset) {
4682 Jim_SetResultFormatted(interp,
4683 "No target-specific reset for %s",
4684 target_name(target));
4685 return JIM_ERR;
4687 /* determine if we should halt or not. */
4688 target->reset_halt = !!a;
4689 /* When this happens - all workareas are invalid. */
4690 target_free_all_working_areas_restore(target, 0);
4692 /* do the assert */
4693 if (n->value == NVP_ASSERT)
4694 e = target->type->assert_reset(target);
4695 else
4696 e = target->type->deassert_reset(target);
4697 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4700 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4702 if (argc != 1) {
4703 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4704 return JIM_ERR;
4706 struct target *target = Jim_CmdPrivData(interp);
4707 if (!target->tap->enabled)
4708 return jim_target_tap_disabled(interp);
4709 int e = target->type->halt(target);
4710 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4713 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4715 Jim_GetOptInfo goi;
4716 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4718 /* params: <name> statename timeoutmsecs */
4719 if (goi.argc != 2) {
4720 const char *cmd_name = Jim_GetString(argv[0], NULL);
4721 Jim_SetResultFormatted(goi.interp,
4722 "%s <state_name> <timeout_in_msec>", cmd_name);
4723 return JIM_ERR;
4726 Jim_Nvp *n;
4727 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4728 if (e != JIM_OK) {
4729 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
4730 return e;
4732 jim_wide a;
4733 e = Jim_GetOpt_Wide(&goi, &a);
4734 if (e != JIM_OK)
4735 return e;
4736 struct target *target = Jim_CmdPrivData(interp);
4737 if (!target->tap->enabled)
4738 return jim_target_tap_disabled(interp);
4740 e = target_wait_state(target, n->value, a);
4741 if (e != ERROR_OK) {
4742 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4743 Jim_SetResultFormatted(goi.interp,
4744 "target: %s wait %s fails (%#s) %s",
4745 target_name(target), n->name,
4746 eObj, target_strerror_safe(e));
4747 Jim_FreeNewObj(interp, eObj);
4748 return JIM_ERR;
4750 return JIM_OK;
4752 /* List for human, Events defined for this target.
4753 * scripts/programs should use 'name cget -event NAME'
4755 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4757 struct command_context *cmd_ctx = current_command_context(interp);
4758 assert(cmd_ctx != NULL);
4760 struct target *target = Jim_CmdPrivData(interp);
4761 struct target_event_action *teap = target->event_action;
4762 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4763 target->target_number,
4764 target_name(target));
4765 command_print(cmd_ctx, "%-25s | Body", "Event");
4766 command_print(cmd_ctx, "------------------------- | "
4767 "----------------------------------------");
4768 while (teap) {
4769 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4770 command_print(cmd_ctx, "%-25s | %s",
4771 opt->name, Jim_GetString(teap->body, NULL));
4772 teap = teap->next;
4774 command_print(cmd_ctx, "***END***");
4775 return JIM_OK;
4777 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4779 if (argc != 1) {
4780 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4781 return JIM_ERR;
4783 struct target *target = Jim_CmdPrivData(interp);
4784 Jim_SetResultString(interp, target_state_name(target), -1);
4785 return JIM_OK;
4787 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4789 Jim_GetOptInfo goi;
4790 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4791 if (goi.argc != 1) {
4792 const char *cmd_name = Jim_GetString(argv[0], NULL);
4793 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4794 return JIM_ERR;
4796 Jim_Nvp *n;
4797 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4798 if (e != JIM_OK) {
4799 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4800 return e;
4802 struct target *target = Jim_CmdPrivData(interp);
4803 target_handle_event(target, n->value);
4804 return JIM_OK;
4807 static const struct command_registration target_instance_command_handlers[] = {
4809 .name = "configure",
4810 .mode = COMMAND_CONFIG,
4811 .jim_handler = jim_target_configure,
4812 .help = "configure a new target for use",
4813 .usage = "[target_attribute ...]",
4816 .name = "cget",
4817 .mode = COMMAND_ANY,
4818 .jim_handler = jim_target_configure,
4819 .help = "returns the specified target attribute",
4820 .usage = "target_attribute",
4823 .name = "mww",
4824 .mode = COMMAND_EXEC,
4825 .jim_handler = jim_target_mw,
4826 .help = "Write 32-bit word(s) to target memory",
4827 .usage = "address data [count]",
4830 .name = "mwh",
4831 .mode = COMMAND_EXEC,
4832 .jim_handler = jim_target_mw,
4833 .help = "Write 16-bit half-word(s) to target memory",
4834 .usage = "address data [count]",
4837 .name = "mwb",
4838 .mode = COMMAND_EXEC,
4839 .jim_handler = jim_target_mw,
4840 .help = "Write byte(s) to target memory",
4841 .usage = "address data [count]",
4844 .name = "mdw",
4845 .mode = COMMAND_EXEC,
4846 .jim_handler = jim_target_md,
4847 .help = "Display target memory as 32-bit words",
4848 .usage = "address [count]",
4851 .name = "mdh",
4852 .mode = COMMAND_EXEC,
4853 .jim_handler = jim_target_md,
4854 .help = "Display target memory as 16-bit half-words",
4855 .usage = "address [count]",
4858 .name = "mdb",
4859 .mode = COMMAND_EXEC,
4860 .jim_handler = jim_target_md,
4861 .help = "Display target memory as 8-bit bytes",
4862 .usage = "address [count]",
4865 .name = "array2mem",
4866 .mode = COMMAND_EXEC,
4867 .jim_handler = jim_target_array2mem,
4868 .help = "Writes Tcl array of 8/16/32 bit numbers "
4869 "to target memory",
4870 .usage = "arrayname bitwidth address count",
4873 .name = "mem2array",
4874 .mode = COMMAND_EXEC,
4875 .jim_handler = jim_target_mem2array,
4876 .help = "Loads Tcl array of 8/16/32 bit numbers "
4877 "from target memory",
4878 .usage = "arrayname bitwidth address count",
4881 .name = "eventlist",
4882 .mode = COMMAND_EXEC,
4883 .jim_handler = jim_target_event_list,
4884 .help = "displays a table of events defined for this target",
4887 .name = "curstate",
4888 .mode = COMMAND_EXEC,
4889 .jim_handler = jim_target_current_state,
4890 .help = "displays the current state of this target",
4893 .name = "arp_examine",
4894 .mode = COMMAND_EXEC,
4895 .jim_handler = jim_target_examine,
4896 .help = "used internally for reset processing",
4899 .name = "arp_halt_gdb",
4900 .mode = COMMAND_EXEC,
4901 .jim_handler = jim_target_halt_gdb,
4902 .help = "used internally for reset processing to halt GDB",
4905 .name = "arp_poll",
4906 .mode = COMMAND_EXEC,
4907 .jim_handler = jim_target_poll,
4908 .help = "used internally for reset processing",
4911 .name = "arp_reset",
4912 .mode = COMMAND_EXEC,
4913 .jim_handler = jim_target_reset,
4914 .help = "used internally for reset processing",
4917 .name = "arp_halt",
4918 .mode = COMMAND_EXEC,
4919 .jim_handler = jim_target_halt,
4920 .help = "used internally for reset processing",
4923 .name = "arp_waitstate",
4924 .mode = COMMAND_EXEC,
4925 .jim_handler = jim_target_wait_state,
4926 .help = "used internally for reset processing",
4929 .name = "invoke-event",
4930 .mode = COMMAND_EXEC,
4931 .jim_handler = jim_target_invoke_event,
4932 .help = "invoke handler for specified event",
4933 .usage = "event_name",
4935 COMMAND_REGISTRATION_DONE
4938 static int target_create(Jim_GetOptInfo *goi)
4940 Jim_Obj *new_cmd;
4941 Jim_Cmd *cmd;
4942 const char *cp;
4943 char *cp2;
4944 int e;
4945 int x;
4946 struct target *target;
4947 struct command_context *cmd_ctx;
4949 cmd_ctx = current_command_context(goi->interp);
4950 assert(cmd_ctx != NULL);
4952 if (goi->argc < 3) {
4953 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4954 return JIM_ERR;
4957 /* COMMAND */
4958 Jim_GetOpt_Obj(goi, &new_cmd);
4959 /* does this command exist? */
4960 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4961 if (cmd) {
4962 cp = Jim_GetString(new_cmd, NULL);
4963 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
4964 return JIM_ERR;
4967 /* TYPE */
4968 e = Jim_GetOpt_String(goi, &cp2, NULL);
4969 if (e != JIM_OK)
4970 return e;
4971 cp = cp2;
4972 /* now does target type exist */
4973 for (x = 0 ; target_types[x] ; x++) {
4974 if (0 == strcmp(cp, target_types[x]->name)) {
4975 /* found */
4976 break;
4979 /* check for deprecated name */
4980 if (target_types[x]->deprecated_name) {
4981 if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
4982 /* found */
4983 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
4984 break;
4988 if (target_types[x] == NULL) {
4989 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
4990 for (x = 0 ; target_types[x] ; x++) {
4991 if (target_types[x + 1]) {
4992 Jim_AppendStrings(goi->interp,
4993 Jim_GetResult(goi->interp),
4994 target_types[x]->name,
4995 ", ", NULL);
4996 } else {
4997 Jim_AppendStrings(goi->interp,
4998 Jim_GetResult(goi->interp),
4999 " or ",
5000 target_types[x]->name, NULL);
5003 return JIM_ERR;
5006 /* Create it */
5007 target = calloc(1, sizeof(struct target));
5008 /* set target number */
5009 target->target_number = new_target_number();
5011 /* allocate memory for each unique target type */
5012 target->type = (struct target_type *)calloc(1, sizeof(struct target_type));
5014 memcpy(target->type, target_types[x], sizeof(struct target_type));
5016 /* will be set by "-endian" */
5017 target->endianness = TARGET_ENDIAN_UNKNOWN;
5019 /* default to first core, override with -coreid */
5020 target->coreid = 0;
5022 target->working_area = 0x0;
5023 target->working_area_size = 0x0;
5024 target->working_areas = NULL;
5025 target->backup_working_area = 0;
5027 target->state = TARGET_UNKNOWN;
5028 target->debug_reason = DBG_REASON_UNDEFINED;
5029 target->reg_cache = NULL;
5030 target->breakpoints = NULL;
5031 target->watchpoints = NULL;
5032 target->next = NULL;
5033 target->arch_info = NULL;
5035 target->display = 1;
5037 target->halt_issued = false;
5039 /* initialize trace information */
5040 target->trace_info = malloc(sizeof(struct trace));
5041 target->trace_info->num_trace_points = 0;
5042 target->trace_info->trace_points_size = 0;
5043 target->trace_info->trace_points = NULL;
5044 target->trace_info->trace_history_size = 0;
5045 target->trace_info->trace_history = NULL;
5046 target->trace_info->trace_history_pos = 0;
5047 target->trace_info->trace_history_overflowed = 0;
5049 target->dbgmsg = NULL;
5050 target->dbg_msg_enabled = 0;
5052 target->endianness = TARGET_ENDIAN_UNKNOWN;
5054 target->rtos = NULL;
5055 target->rtos_auto_detect = false;
5057 /* Do the rest as "configure" options */
5058 goi->isconfigure = 1;
5059 e = target_configure(goi, target);
5061 if (target->tap == NULL) {
5062 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
5063 e = JIM_ERR;
5066 if (e != JIM_OK) {
5067 free(target->type);
5068 free(target);
5069 return e;
5072 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5073 /* default endian to little if not specified */
5074 target->endianness = TARGET_LITTLE_ENDIAN;
5077 /* incase variant is not set */
5078 if (!target->variant)
5079 target->variant = strdup("");
5081 cp = Jim_GetString(new_cmd, NULL);
5082 target->cmd_name = strdup(cp);
5084 /* create the target specific commands */
5085 if (target->type->commands) {
5086 e = register_commands(cmd_ctx, NULL, target->type->commands);
5087 if (ERROR_OK != e)
5088 LOG_ERROR("unable to register '%s' commands", cp);
5090 if (target->type->target_create)
5091 (*(target->type->target_create))(target, goi->interp);
5093 /* append to end of list */
5095 struct target **tpp;
5096 tpp = &(all_targets);
5097 while (*tpp)
5098 tpp = &((*tpp)->next);
5099 *tpp = target;
5102 /* now - create the new target name command */
5103 const struct command_registration target_subcommands[] = {
5105 .chain = target_instance_command_handlers,
5108 .chain = target->type->commands,
5110 COMMAND_REGISTRATION_DONE
5112 const struct command_registration target_commands[] = {
5114 .name = cp,
5115 .mode = COMMAND_ANY,
5116 .help = "target command group",
5117 .usage = "",
5118 .chain = target_subcommands,
5120 COMMAND_REGISTRATION_DONE
5122 e = register_commands(cmd_ctx, NULL, target_commands);
5123 if (ERROR_OK != e)
5124 return JIM_ERR;
5126 struct command *c = command_find_in_context(cmd_ctx, cp);
5127 assert(c);
5128 command_set_handler_data(c, target);
5130 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5133 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5135 if (argc != 1) {
5136 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5137 return JIM_ERR;
5139 struct command_context *cmd_ctx = current_command_context(interp);
5140 assert(cmd_ctx != NULL);
5142 Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5143 return JIM_OK;
5146 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5148 if (argc != 1) {
5149 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5150 return JIM_ERR;
5152 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5153 for (unsigned x = 0; NULL != target_types[x]; x++) {
5154 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5155 Jim_NewStringObj(interp, target_types[x]->name, -1));
5157 return JIM_OK;
5160 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5162 if (argc != 1) {
5163 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5164 return JIM_ERR;
5166 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5167 struct target *target = all_targets;
5168 while (target) {
5169 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5170 Jim_NewStringObj(interp, target_name(target), -1));
5171 target = target->next;
5173 return JIM_OK;
5176 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5178 int i;
5179 const char *targetname;
5180 int retval, len;
5181 struct target *target = (struct target *) NULL;
5182 struct target_list *head, *curr, *new;
5183 curr = (struct target_list *) NULL;
5184 head = (struct target_list *) NULL;
5186 retval = 0;
5187 LOG_DEBUG("%d", argc);
5188 /* argv[1] = target to associate in smp
5189 * argv[2] = target to assoicate in smp
5190 * argv[3] ...
5193 for (i = 1; i < argc; i++) {
5195 targetname = Jim_GetString(argv[i], &len);
5196 target = get_target(targetname);
5197 LOG_DEBUG("%s ", targetname);
5198 if (target) {
5199 new = malloc(sizeof(struct target_list));
5200 new->target = target;
5201 new->next = (struct target_list *)NULL;
5202 if (head == (struct target_list *)NULL) {
5203 head = new;
5204 curr = head;
5205 } else {
5206 curr->next = new;
5207 curr = new;
5211 /* now parse the list of cpu and put the target in smp mode*/
5212 curr = head;
5214 while (curr != (struct target_list *)NULL) {
5215 target = curr->target;
5216 target->smp = 1;
5217 target->head = head;
5218 curr = curr->next;
5221 if (target && target->rtos)
5222 retval = rtos_smp_init(head->target);
5224 return retval;
5228 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5230 Jim_GetOptInfo goi;
5231 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5232 if (goi.argc < 3) {
5233 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5234 "<name> <target_type> [<target_options> ...]");
5235 return JIM_ERR;
5237 return target_create(&goi);
5240 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5242 Jim_GetOptInfo goi;
5243 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5245 /* It's OK to remove this mechanism sometime after August 2010 or so */
5246 LOG_WARNING("don't use numbers as target identifiers; use names");
5247 if (goi.argc != 1) {
5248 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
5249 return JIM_ERR;
5251 jim_wide w;
5252 int e = Jim_GetOpt_Wide(&goi, &w);
5253 if (e != JIM_OK)
5254 return JIM_ERR;
5256 struct target *target;
5257 for (target = all_targets; NULL != target; target = target->next) {
5258 if (target->target_number != w)
5259 continue;
5261 Jim_SetResultString(goi.interp, target_name(target), -1);
5262 return JIM_OK;
5265 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
5266 Jim_SetResultFormatted(goi.interp,
5267 "Target: number %#s does not exist", wObj);
5268 Jim_FreeNewObj(interp, wObj);
5270 return JIM_ERR;
5273 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5275 if (argc != 1) {
5276 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
5277 return JIM_ERR;
5279 unsigned count = 0;
5280 struct target *target = all_targets;
5281 while (NULL != target) {
5282 target = target->next;
5283 count++;
5285 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
5286 return JIM_OK;
5289 static const struct command_registration target_subcommand_handlers[] = {
5291 .name = "init",
5292 .mode = COMMAND_CONFIG,
5293 .handler = handle_target_init_command,
5294 .help = "initialize targets",
5297 .name = "create",
5298 /* REVISIT this should be COMMAND_CONFIG ... */
5299 .mode = COMMAND_ANY,
5300 .jim_handler = jim_target_create,
5301 .usage = "name type '-chain-position' name [options ...]",
5302 .help = "Creates and selects a new target",
5305 .name = "current",
5306 .mode = COMMAND_ANY,
5307 .jim_handler = jim_target_current,
5308 .help = "Returns the currently selected target",
5311 .name = "types",
5312 .mode = COMMAND_ANY,
5313 .jim_handler = jim_target_types,
5314 .help = "Returns the available target types as "
5315 "a list of strings",
5318 .name = "names",
5319 .mode = COMMAND_ANY,
5320 .jim_handler = jim_target_names,
5321 .help = "Returns the names of all targets as a list of strings",
5324 .name = "number",
5325 .mode = COMMAND_ANY,
5326 .jim_handler = jim_target_number,
5327 .usage = "number",
5328 .help = "Returns the name of the numbered target "
5329 "(DEPRECATED)",
5332 .name = "count",
5333 .mode = COMMAND_ANY,
5334 .jim_handler = jim_target_count,
5335 .help = "Returns the number of targets as an integer "
5336 "(DEPRECATED)",
5339 .name = "smp",
5340 .mode = COMMAND_ANY,
5341 .jim_handler = jim_target_smp,
5342 .usage = "targetname1 targetname2 ...",
5343 .help = "gather several target in a smp list"
5346 COMMAND_REGISTRATION_DONE
5349 struct FastLoad {
5350 uint32_t address;
5351 uint8_t *data;
5352 int length;
5356 static int fastload_num;
5357 static struct FastLoad *fastload;
5359 static void free_fastload(void)
5361 if (fastload != NULL) {
5362 int i;
5363 for (i = 0; i < fastload_num; i++) {
5364 if (fastload[i].data)
5365 free(fastload[i].data);
5367 free(fastload);
5368 fastload = NULL;
5372 COMMAND_HANDLER(handle_fast_load_image_command)
5374 uint8_t *buffer;
5375 size_t buf_cnt;
5376 uint32_t image_size;
5377 uint32_t min_address = 0;
5378 uint32_t max_address = 0xffffffff;
5379 int i;
5381 struct image image;
5383 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5384 &image, &min_address, &max_address);
5385 if (ERROR_OK != retval)
5386 return retval;
5388 struct duration bench;
5389 duration_start(&bench);
5391 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5392 if (retval != ERROR_OK)
5393 return retval;
5395 image_size = 0x0;
5396 retval = ERROR_OK;
5397 fastload_num = image.num_sections;
5398 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
5399 if (fastload == NULL) {
5400 command_print(CMD_CTX, "out of memory");
5401 image_close(&image);
5402 return ERROR_FAIL;
5404 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5405 for (i = 0; i < image.num_sections; i++) {
5406 buffer = malloc(image.sections[i].size);
5407 if (buffer == NULL) {
5408 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5409 (int)(image.sections[i].size));
5410 retval = ERROR_FAIL;
5411 break;
5414 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5415 if (retval != ERROR_OK) {
5416 free(buffer);
5417 break;
5420 uint32_t offset = 0;
5421 uint32_t length = buf_cnt;
5423 /* DANGER!!! beware of unsigned comparision here!!! */
5425 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5426 (image.sections[i].base_address < max_address)) {
5427 if (image.sections[i].base_address < min_address) {
5428 /* clip addresses below */
5429 offset += min_address-image.sections[i].base_address;
5430 length -= offset;
5433 if (image.sections[i].base_address + buf_cnt > max_address)
5434 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5436 fastload[i].address = image.sections[i].base_address + offset;
5437 fastload[i].data = malloc(length);
5438 if (fastload[i].data == NULL) {
5439 free(buffer);
5440 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5441 length);
5442 retval = ERROR_FAIL;
5443 break;
5445 memcpy(fastload[i].data, buffer + offset, length);
5446 fastload[i].length = length;
5448 image_size += length;
5449 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5450 (unsigned int)length,
5451 ((unsigned int)(image.sections[i].base_address + offset)));
5454 free(buffer);
5457 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5458 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5459 "in %fs (%0.3f KiB/s)", image_size,
5460 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5462 command_print(CMD_CTX,
5463 "WARNING: image has not been loaded to target!"
5464 "You can issue a 'fast_load' to finish loading.");
5467 image_close(&image);
5469 if (retval != ERROR_OK)
5470 free_fastload();
5472 return retval;
5475 COMMAND_HANDLER(handle_fast_load_command)
5477 if (CMD_ARGC > 0)
5478 return ERROR_COMMAND_SYNTAX_ERROR;
5479 if (fastload == NULL) {
5480 LOG_ERROR("No image in memory");
5481 return ERROR_FAIL;
5483 int i;
5484 int ms = timeval_ms();
5485 int size = 0;
5486 int retval = ERROR_OK;
5487 for (i = 0; i < fastload_num; i++) {
5488 struct target *target = get_current_target(CMD_CTX);
5489 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5490 (unsigned int)(fastload[i].address),
5491 (unsigned int)(fastload[i].length));
5492 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5493 if (retval != ERROR_OK)
5494 break;
5495 size += fastload[i].length;
5497 if (retval == ERROR_OK) {
5498 int after = timeval_ms();
5499 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5501 return retval;
5504 static const struct command_registration target_command_handlers[] = {
5506 .name = "targets",
5507 .handler = handle_targets_command,
5508 .mode = COMMAND_ANY,
5509 .help = "change current default target (one parameter) "
5510 "or prints table of all targets (no parameters)",
5511 .usage = "[target]",
5514 .name = "target",
5515 .mode = COMMAND_CONFIG,
5516 .help = "configure target",
5518 .chain = target_subcommand_handlers,
5520 COMMAND_REGISTRATION_DONE
5523 int target_register_commands(struct command_context *cmd_ctx)
5525 return register_commands(cmd_ctx, NULL, target_command_handlers);
5528 static bool target_reset_nag = true;
5530 bool get_target_reset_nag(void)
5532 return target_reset_nag;
5535 COMMAND_HANDLER(handle_target_reset_nag)
5537 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5538 &target_reset_nag, "Nag after each reset about options to improve "
5539 "performance");
5542 COMMAND_HANDLER(handle_ps_command)
5544 struct target *target = get_current_target(CMD_CTX);
5545 char *display;
5546 if (target->state != TARGET_HALTED) {
5547 LOG_INFO("target not halted !!");
5548 return ERROR_OK;
5551 if ((target->rtos) && (target->rtos->type)
5552 && (target->rtos->type->ps_command)) {
5553 display = target->rtos->type->ps_command(target);
5554 command_print(CMD_CTX, "%s", display);
5555 free(display);
5556 return ERROR_OK;
5557 } else {
5558 LOG_INFO("failed");
5559 return ERROR_TARGET_FAILURE;
5563 static const struct command_registration target_exec_command_handlers[] = {
5565 .name = "fast_load_image",
5566 .handler = handle_fast_load_image_command,
5567 .mode = COMMAND_ANY,
5568 .help = "Load image into server memory for later use by "
5569 "fast_load; primarily for profiling",
5570 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5571 "[min_address [max_length]]",
5574 .name = "fast_load",
5575 .handler = handle_fast_load_command,
5576 .mode = COMMAND_EXEC,
5577 .help = "loads active fast load image to current target "
5578 "- mainly for profiling purposes",
5579 .usage = "",
5582 .name = "profile",
5583 .handler = handle_profile_command,
5584 .mode = COMMAND_EXEC,
5585 .usage = "seconds filename [start end]",
5586 .help = "profiling samples the CPU PC",
5588 /** @todo don't register virt2phys() unless target supports it */
5590 .name = "virt2phys",
5591 .handler = handle_virt2phys_command,
5592 .mode = COMMAND_ANY,
5593 .help = "translate a virtual address into a physical address",
5594 .usage = "virtual_address",
5597 .name = "reg",
5598 .handler = handle_reg_command,
5599 .mode = COMMAND_EXEC,
5600 .help = "display or set a register; with no arguments, "
5601 "displays all registers and their values",
5602 .usage = "[(register_name|register_number) [value]]",
5605 .name = "poll",
5606 .handler = handle_poll_command,
5607 .mode = COMMAND_EXEC,
5608 .help = "poll target state; or reconfigure background polling",
5609 .usage = "['on'|'off']",
5612 .name = "wait_halt",
5613 .handler = handle_wait_halt_command,
5614 .mode = COMMAND_EXEC,
5615 .help = "wait up to the specified number of milliseconds "
5616 "(default 5000) for a previously requested halt",
5617 .usage = "[milliseconds]",
5620 .name = "halt",
5621 .handler = handle_halt_command,
5622 .mode = COMMAND_EXEC,
5623 .help = "request target to halt, then wait up to the specified"
5624 "number of milliseconds (default 5000) for it to complete",
5625 .usage = "[milliseconds]",
5628 .name = "resume",
5629 .handler = handle_resume_command,
5630 .mode = COMMAND_EXEC,
5631 .help = "resume target execution from current PC or address",
5632 .usage = "[address]",
5635 .name = "reset",
5636 .handler = handle_reset_command,
5637 .mode = COMMAND_EXEC,
5638 .usage = "[run|halt|init]",
5639 .help = "Reset all targets into the specified mode."
5640 "Default reset mode is run, if not given.",
5643 .name = "soft_reset_halt",
5644 .handler = handle_soft_reset_halt_command,
5645 .mode = COMMAND_EXEC,
5646 .usage = "",
5647 .help = "halt the target and do a soft reset",
5650 .name = "step",
5651 .handler = handle_step_command,
5652 .mode = COMMAND_EXEC,
5653 .help = "step one instruction from current PC or address",
5654 .usage = "[address]",
5657 .name = "mdw",
5658 .handler = handle_md_command,
5659 .mode = COMMAND_EXEC,
5660 .help = "display memory words",
5661 .usage = "['phys'] address [count]",
5664 .name = "mdh",
5665 .handler = handle_md_command,
5666 .mode = COMMAND_EXEC,
5667 .help = "display memory half-words",
5668 .usage = "['phys'] address [count]",
5671 .name = "mdb",
5672 .handler = handle_md_command,
5673 .mode = COMMAND_EXEC,
5674 .help = "display memory bytes",
5675 .usage = "['phys'] address [count]",
5678 .name = "mww",
5679 .handler = handle_mw_command,
5680 .mode = COMMAND_EXEC,
5681 .help = "write memory word",
5682 .usage = "['phys'] address value [count]",
5685 .name = "mwh",
5686 .handler = handle_mw_command,
5687 .mode = COMMAND_EXEC,
5688 .help = "write memory half-word",
5689 .usage = "['phys'] address value [count]",
5692 .name = "mwb",
5693 .handler = handle_mw_command,
5694 .mode = COMMAND_EXEC,
5695 .help = "write memory byte",
5696 .usage = "['phys'] address value [count]",
5699 .name = "bp",
5700 .handler = handle_bp_command,
5701 .mode = COMMAND_EXEC,
5702 .help = "list or set hardware or software breakpoint",
5703 .usage = "<address> [<asid>]<length> ['hw'|'hw_ctx']",
5706 .name = "rbp",
5707 .handler = handle_rbp_command,
5708 .mode = COMMAND_EXEC,
5709 .help = "remove breakpoint",
5710 .usage = "address",
5713 .name = "wp",
5714 .handler = handle_wp_command,
5715 .mode = COMMAND_EXEC,
5716 .help = "list (no params) or create watchpoints",
5717 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5720 .name = "rwp",
5721 .handler = handle_rwp_command,
5722 .mode = COMMAND_EXEC,
5723 .help = "remove watchpoint",
5724 .usage = "address",
5727 .name = "load_image",
5728 .handler = handle_load_image_command,
5729 .mode = COMMAND_EXEC,
5730 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5731 "[min_address] [max_length]",
5734 .name = "dump_image",
5735 .handler = handle_dump_image_command,
5736 .mode = COMMAND_EXEC,
5737 .usage = "filename address size",
5740 .name = "verify_image",
5741 .handler = handle_verify_image_command,
5742 .mode = COMMAND_EXEC,
5743 .usage = "filename [offset [type]]",
5746 .name = "test_image",
5747 .handler = handle_test_image_command,
5748 .mode = COMMAND_EXEC,
5749 .usage = "filename [offset [type]]",
5752 .name = "mem2array",
5753 .mode = COMMAND_EXEC,
5754 .jim_handler = jim_mem2array,
5755 .help = "read 8/16/32 bit memory and return as a TCL array "
5756 "for script processing",
5757 .usage = "arrayname bitwidth address count",
5760 .name = "array2mem",
5761 .mode = COMMAND_EXEC,
5762 .jim_handler = jim_array2mem,
5763 .help = "convert a TCL array to memory locations "
5764 "and write the 8/16/32 bit values",
5765 .usage = "arrayname bitwidth address count",
5768 .name = "reset_nag",
5769 .handler = handle_target_reset_nag,
5770 .mode = COMMAND_ANY,
5771 .help = "Nag after each reset about options that could have been "
5772 "enabled to improve performance. ",
5773 .usage = "['enable'|'disable']",
5776 .name = "ps",
5777 .handler = handle_ps_command,
5778 .mode = COMMAND_EXEC,
5779 .help = "list all tasks ",
5780 .usage = " ",
5783 COMMAND_REGISTRATION_DONE
5785 static int target_register_user_commands(struct command_context *cmd_ctx)
5787 int retval = ERROR_OK;
5788 retval = target_request_register_commands(cmd_ctx);
5789 if (retval != ERROR_OK)
5790 return retval;
5792 retval = trace_register_commands(cmd_ctx);
5793 if (retval != ERROR_OK)
5794 return retval;
5797 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);