Add new target type: OpenRISC
[openocd.git] / src / target / target.c
blob0eb578828e962f99e7d160ff431b2966c14f443d
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;
104 extern struct target_type or1k_target;
106 static struct target_type *target_types[] = {
107 &arm7tdmi_target,
108 &arm9tdmi_target,
109 &arm920t_target,
110 &arm720t_target,
111 &arm966e_target,
112 &arm946e_target,
113 &arm926ejs_target,
114 &fa526_target,
115 &feroceon_target,
116 &dragonite_target,
117 &xscale_target,
118 &cortexm3_target,
119 &cortexa8_target,
120 &cortexr4_target,
121 &arm11_target,
122 &mips_m4k_target,
123 &avr_target,
124 &dsp563xx_target,
125 &dsp5680xx_target,
126 &testee_target,
127 &avr32_ap7k_target,
128 &hla_target,
129 &nds32_v2_target,
130 &nds32_v3_target,
131 &nds32_v3m_target,
132 &or1k_target,
133 NULL,
136 struct target *all_targets;
137 static struct target_event_callback *target_event_callbacks;
138 static struct target_timer_callback *target_timer_callbacks;
139 static const int polling_interval = 100;
141 static const Jim_Nvp nvp_assert[] = {
142 { .name = "assert", NVP_ASSERT },
143 { .name = "deassert", NVP_DEASSERT },
144 { .name = "T", NVP_ASSERT },
145 { .name = "F", NVP_DEASSERT },
146 { .name = "t", NVP_ASSERT },
147 { .name = "f", NVP_DEASSERT },
148 { .name = NULL, .value = -1 }
151 static const Jim_Nvp nvp_error_target[] = {
152 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
153 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
154 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
155 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
156 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
157 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
158 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
159 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
160 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
161 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
162 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
163 { .value = -1, .name = NULL }
166 static const char *target_strerror_safe(int err)
168 const Jim_Nvp *n;
170 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
171 if (n->name == NULL)
172 return "unknown";
173 else
174 return n->name;
177 static const Jim_Nvp nvp_target_event[] = {
179 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
180 { .value = TARGET_EVENT_HALTED, .name = "halted" },
181 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
182 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
183 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
185 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
186 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
188 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
189 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
190 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
191 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
192 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
193 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
194 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
195 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
196 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
197 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
198 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
199 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
201 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
202 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
204 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
205 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
207 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
208 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
210 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
211 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
213 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
214 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
216 { .name = NULL, .value = -1 }
219 static const Jim_Nvp nvp_target_state[] = {
220 { .name = "unknown", .value = TARGET_UNKNOWN },
221 { .name = "running", .value = TARGET_RUNNING },
222 { .name = "halted", .value = TARGET_HALTED },
223 { .name = "reset", .value = TARGET_RESET },
224 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
225 { .name = NULL, .value = -1 },
228 static const Jim_Nvp nvp_target_debug_reason[] = {
229 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
230 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
231 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
232 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
233 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
234 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
235 { .name = "program-exit" , .value = DBG_REASON_EXIT },
236 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
237 { .name = NULL, .value = -1 },
240 static const Jim_Nvp nvp_target_endian[] = {
241 { .name = "big", .value = TARGET_BIG_ENDIAN },
242 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
243 { .name = "be", .value = TARGET_BIG_ENDIAN },
244 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
245 { .name = NULL, .value = -1 },
248 static const Jim_Nvp nvp_reset_modes[] = {
249 { .name = "unknown", .value = RESET_UNKNOWN },
250 { .name = "run" , .value = RESET_RUN },
251 { .name = "halt" , .value = RESET_HALT },
252 { .name = "init" , .value = RESET_INIT },
253 { .name = NULL , .value = -1 },
256 const char *debug_reason_name(struct target *t)
258 const char *cp;
260 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
261 t->debug_reason)->name;
262 if (!cp) {
263 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
264 cp = "(*BUG*unknown*BUG*)";
266 return cp;
269 const char *target_state_name(struct target *t)
271 const char *cp;
272 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
273 if (!cp) {
274 LOG_ERROR("Invalid target state: %d", (int)(t->state));
275 cp = "(*BUG*unknown*BUG*)";
277 return cp;
280 /* determine the number of the new target */
281 static int new_target_number(void)
283 struct target *t;
284 int x;
286 /* number is 0 based */
287 x = -1;
288 t = all_targets;
289 while (t) {
290 if (x < t->target_number)
291 x = t->target_number;
292 t = t->next;
294 return x + 1;
297 /* read a uint32_t from a buffer in target memory endianness */
298 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
300 if (target->endianness == TARGET_LITTLE_ENDIAN)
301 return le_to_h_u32(buffer);
302 else
303 return be_to_h_u32(buffer);
306 /* read a uint24_t from a buffer in target memory endianness */
307 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
309 if (target->endianness == TARGET_LITTLE_ENDIAN)
310 return le_to_h_u24(buffer);
311 else
312 return be_to_h_u24(buffer);
315 /* read a uint16_t from a buffer in target memory endianness */
316 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
318 if (target->endianness == TARGET_LITTLE_ENDIAN)
319 return le_to_h_u16(buffer);
320 else
321 return be_to_h_u16(buffer);
324 /* read a uint8_t from a buffer in target memory endianness */
325 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
327 return *buffer & 0x0ff;
330 /* write a uint32_t to a buffer in target memory endianness */
331 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
333 if (target->endianness == TARGET_LITTLE_ENDIAN)
334 h_u32_to_le(buffer, value);
335 else
336 h_u32_to_be(buffer, value);
339 /* write a uint24_t to a buffer in target memory endianness */
340 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
342 if (target->endianness == TARGET_LITTLE_ENDIAN)
343 h_u24_to_le(buffer, value);
344 else
345 h_u24_to_be(buffer, value);
348 /* write a uint16_t to a buffer in target memory endianness */
349 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
351 if (target->endianness == TARGET_LITTLE_ENDIAN)
352 h_u16_to_le(buffer, value);
353 else
354 h_u16_to_be(buffer, value);
357 /* write a uint8_t to a buffer in target memory endianness */
358 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
360 *buffer = value;
363 /* write a uint32_t array to a buffer in target memory endianness */
364 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
366 uint32_t i;
367 for (i = 0; i < count; i++)
368 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
371 /* write a uint16_t array to a buffer in target memory endianness */
372 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
374 uint32_t i;
375 for (i = 0; i < count; i++)
376 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
379 /* write a uint32_t array to a buffer in target memory endianness */
380 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, uint32_t *srcbuf)
382 uint32_t i;
383 for (i = 0; i < count; i++)
384 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
387 /* write a uint16_t array to a buffer in target memory endianness */
388 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, uint16_t *srcbuf)
390 uint32_t i;
391 for (i = 0; i < count; i++)
392 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
395 /* return a pointer to a configured target; id is name or number */
396 struct target *get_target(const char *id)
398 struct target *target;
400 /* try as tcltarget name */
401 for (target = all_targets; target; target = target->next) {
402 if (target_name(target) == NULL)
403 continue;
404 if (strcmp(id, target_name(target)) == 0)
405 return target;
408 /* It's OK to remove this fallback sometime after August 2010 or so */
410 /* no match, try as number */
411 unsigned num;
412 if (parse_uint(id, &num) != ERROR_OK)
413 return NULL;
415 for (target = all_targets; target; target = target->next) {
416 if (target->target_number == (int)num) {
417 LOG_WARNING("use '%s' as target identifier, not '%u'",
418 target_name(target), num);
419 return target;
423 return NULL;
426 /* returns a pointer to the n-th configured target */
427 static struct target *get_target_by_num(int num)
429 struct target *target = all_targets;
431 while (target) {
432 if (target->target_number == num)
433 return target;
434 target = target->next;
437 return NULL;
440 struct target *get_current_target(struct command_context *cmd_ctx)
442 struct target *target = get_target_by_num(cmd_ctx->current_target);
444 if (target == NULL) {
445 LOG_ERROR("BUG: current_target out of bounds");
446 exit(-1);
449 return target;
452 int target_poll(struct target *target)
454 int retval;
456 /* We can't poll until after examine */
457 if (!target_was_examined(target)) {
458 /* Fail silently lest we pollute the log */
459 return ERROR_FAIL;
462 retval = target->type->poll(target);
463 if (retval != ERROR_OK)
464 return retval;
466 if (target->halt_issued) {
467 if (target->state == TARGET_HALTED)
468 target->halt_issued = false;
469 else {
470 long long t = timeval_ms() - target->halt_issued_time;
471 if (t > DEFAULT_HALT_TIMEOUT) {
472 target->halt_issued = false;
473 LOG_INFO("Halt timed out, wake up GDB.");
474 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
479 return ERROR_OK;
482 int target_halt(struct target *target)
484 int retval;
485 /* We can't poll until after examine */
486 if (!target_was_examined(target)) {
487 LOG_ERROR("Target not examined yet");
488 return ERROR_FAIL;
491 retval = target->type->halt(target);
492 if (retval != ERROR_OK)
493 return retval;
495 target->halt_issued = true;
496 target->halt_issued_time = timeval_ms();
498 return ERROR_OK;
502 * Make the target (re)start executing using its saved execution
503 * context (possibly with some modifications).
505 * @param target Which target should start executing.
506 * @param current True to use the target's saved program counter instead
507 * of the address parameter
508 * @param address Optionally used as the program counter.
509 * @param handle_breakpoints True iff breakpoints at the resumption PC
510 * should be skipped. (For example, maybe execution was stopped by
511 * such a breakpoint, in which case it would be counterprodutive to
512 * let it re-trigger.
513 * @param debug_execution False if all working areas allocated by OpenOCD
514 * should be released and/or restored to their original contents.
515 * (This would for example be true to run some downloaded "helper"
516 * algorithm code, which resides in one such working buffer and uses
517 * another for data storage.)
519 * @todo Resolve the ambiguity about what the "debug_execution" flag
520 * signifies. For example, Target implementations don't agree on how
521 * it relates to invalidation of the register cache, or to whether
522 * breakpoints and watchpoints should be enabled. (It would seem wrong
523 * to enable breakpoints when running downloaded "helper" algorithms
524 * (debug_execution true), since the breakpoints would be set to match
525 * target firmware being debugged, not the helper algorithm.... and
526 * enabling them could cause such helpers to malfunction (for example,
527 * by overwriting data with a breakpoint instruction. On the other
528 * hand the infrastructure for running such helpers might use this
529 * procedure but rely on hardware breakpoint to detect termination.)
531 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
533 int retval;
535 /* We can't poll until after examine */
536 if (!target_was_examined(target)) {
537 LOG_ERROR("Target not examined yet");
538 return ERROR_FAIL;
541 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
543 /* note that resume *must* be asynchronous. The CPU can halt before
544 * we poll. The CPU can even halt at the current PC as a result of
545 * a software breakpoint being inserted by (a bug?) the application.
547 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
548 if (retval != ERROR_OK)
549 return retval;
551 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
553 return retval;
556 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
558 char buf[100];
559 int retval;
560 Jim_Nvp *n;
561 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
562 if (n->name == NULL) {
563 LOG_ERROR("invalid reset mode");
564 return ERROR_FAIL;
567 /* disable polling during reset to make reset event scripts
568 * more predictable, i.e. dr/irscan & pathmove in events will
569 * not have JTAG operations injected into the middle of a sequence.
571 bool save_poll = jtag_poll_get_enabled();
573 jtag_poll_set_enabled(false);
575 sprintf(buf, "ocd_process_reset %s", n->name);
576 retval = Jim_Eval(cmd_ctx->interp, buf);
578 jtag_poll_set_enabled(save_poll);
580 if (retval != JIM_OK) {
581 Jim_MakeErrorMessage(cmd_ctx->interp);
582 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
583 return ERROR_FAIL;
586 /* We want any events to be processed before the prompt */
587 retval = target_call_timer_callbacks_now();
589 struct target *target;
590 for (target = all_targets; target; target = target->next) {
591 target->type->check_reset(target);
592 target->running_alg = false;
595 return retval;
598 static int identity_virt2phys(struct target *target,
599 uint32_t virtual, uint32_t *physical)
601 *physical = virtual;
602 return ERROR_OK;
605 static int no_mmu(struct target *target, int *enabled)
607 *enabled = 0;
608 return ERROR_OK;
611 static int default_examine(struct target *target)
613 target_set_examined(target);
614 return ERROR_OK;
617 /* no check by default */
618 static int default_check_reset(struct target *target)
620 return ERROR_OK;
623 int target_examine_one(struct target *target)
625 return target->type->examine(target);
628 static int jtag_enable_callback(enum jtag_event event, void *priv)
630 struct target *target = priv;
632 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
633 return ERROR_OK;
635 jtag_unregister_event_callback(jtag_enable_callback, target);
637 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
639 int retval = target_examine_one(target);
640 if (retval != ERROR_OK)
641 return retval;
643 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
645 return retval;
648 /* Targets that correctly implement init + examine, i.e.
649 * no communication with target during init:
651 * XScale
653 int target_examine(void)
655 int retval = ERROR_OK;
656 struct target *target;
658 for (target = all_targets; target; target = target->next) {
659 /* defer examination, but don't skip it */
660 if (!target->tap->enabled) {
661 jtag_register_event_callback(jtag_enable_callback,
662 target);
663 continue;
666 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
668 retval = target_examine_one(target);
669 if (retval != ERROR_OK)
670 return retval;
672 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
674 return retval;
677 const char *target_type_name(struct target *target)
679 return target->type->name;
682 static int target_soft_reset_halt(struct target *target)
684 if (!target_was_examined(target)) {
685 LOG_ERROR("Target not examined yet");
686 return ERROR_FAIL;
688 if (!target->type->soft_reset_halt) {
689 LOG_ERROR("Target %s does not support soft_reset_halt",
690 target_name(target));
691 return ERROR_FAIL;
693 return target->type->soft_reset_halt(target);
697 * Downloads a target-specific native code algorithm to the target,
698 * and executes it. * Note that some targets may need to set up, enable,
699 * and tear down a breakpoint (hard or * soft) to detect algorithm
700 * termination, while others may support lower overhead schemes where
701 * soft breakpoints embedded in the algorithm automatically terminate the
702 * algorithm.
704 * @param target used to run the algorithm
705 * @param arch_info target-specific description of the algorithm.
707 int target_run_algorithm(struct target *target,
708 int num_mem_params, struct mem_param *mem_params,
709 int num_reg_params, struct reg_param *reg_param,
710 uint32_t entry_point, uint32_t exit_point,
711 int timeout_ms, void *arch_info)
713 int retval = ERROR_FAIL;
715 if (!target_was_examined(target)) {
716 LOG_ERROR("Target not examined yet");
717 goto done;
719 if (!target->type->run_algorithm) {
720 LOG_ERROR("Target type '%s' does not support %s",
721 target_type_name(target), __func__);
722 goto done;
725 target->running_alg = true;
726 retval = target->type->run_algorithm(target,
727 num_mem_params, mem_params,
728 num_reg_params, reg_param,
729 entry_point, exit_point, timeout_ms, arch_info);
730 target->running_alg = false;
732 done:
733 return retval;
737 * Downloads a target-specific native code algorithm to the target,
738 * executes and leaves it running.
740 * @param target used to run the algorithm
741 * @param arch_info target-specific description of the algorithm.
743 int target_start_algorithm(struct target *target,
744 int num_mem_params, struct mem_param *mem_params,
745 int num_reg_params, struct reg_param *reg_params,
746 uint32_t entry_point, uint32_t exit_point,
747 void *arch_info)
749 int retval = ERROR_FAIL;
751 if (!target_was_examined(target)) {
752 LOG_ERROR("Target not examined yet");
753 goto done;
755 if (!target->type->start_algorithm) {
756 LOG_ERROR("Target type '%s' does not support %s",
757 target_type_name(target), __func__);
758 goto done;
760 if (target->running_alg) {
761 LOG_ERROR("Target is already running an algorithm");
762 goto done;
765 target->running_alg = true;
766 retval = target->type->start_algorithm(target,
767 num_mem_params, mem_params,
768 num_reg_params, reg_params,
769 entry_point, exit_point, arch_info);
771 done:
772 return retval;
776 * Waits for an algorithm started with target_start_algorithm() to complete.
778 * @param target used to run the algorithm
779 * @param arch_info target-specific description of the algorithm.
781 int target_wait_algorithm(struct target *target,
782 int num_mem_params, struct mem_param *mem_params,
783 int num_reg_params, struct reg_param *reg_params,
784 uint32_t exit_point, int timeout_ms,
785 void *arch_info)
787 int retval = ERROR_FAIL;
789 if (!target->type->wait_algorithm) {
790 LOG_ERROR("Target type '%s' does not support %s",
791 target_type_name(target), __func__);
792 goto done;
794 if (!target->running_alg) {
795 LOG_ERROR("Target is not running an algorithm");
796 goto done;
799 retval = target->type->wait_algorithm(target,
800 num_mem_params, mem_params,
801 num_reg_params, reg_params,
802 exit_point, timeout_ms, arch_info);
803 if (retval != ERROR_TARGET_TIMEOUT)
804 target->running_alg = false;
806 done:
807 return retval;
811 * Executes a target-specific native code algorithm in the target.
812 * It differs from target_run_algorithm in that the algorithm is asynchronous.
813 * Because of this it requires an compliant algorithm:
814 * see contrib/loaders/flash/stm32f1x.S for example.
816 * @param target used to run the algorithm
819 int target_run_flash_async_algorithm(struct target *target,
820 uint8_t *buffer, uint32_t count, int block_size,
821 int num_mem_params, struct mem_param *mem_params,
822 int num_reg_params, struct reg_param *reg_params,
823 uint32_t buffer_start, uint32_t buffer_size,
824 uint32_t entry_point, uint32_t exit_point, void *arch_info)
826 int retval;
827 int timeout = 0;
829 /* Set up working area. First word is write pointer, second word is read pointer,
830 * rest is fifo data area. */
831 uint32_t wp_addr = buffer_start;
832 uint32_t rp_addr = buffer_start + 4;
833 uint32_t fifo_start_addr = buffer_start + 8;
834 uint32_t fifo_end_addr = buffer_start + buffer_size;
836 uint32_t wp = fifo_start_addr;
837 uint32_t rp = fifo_start_addr;
839 /* validate block_size is 2^n */
840 assert(!block_size || !(block_size & (block_size - 1)));
842 retval = target_write_u32(target, wp_addr, wp);
843 if (retval != ERROR_OK)
844 return retval;
845 retval = target_write_u32(target, rp_addr, rp);
846 if (retval != ERROR_OK)
847 return retval;
849 /* Start up algorithm on target and let it idle while writing the first chunk */
850 retval = target_start_algorithm(target, num_mem_params, mem_params,
851 num_reg_params, reg_params,
852 entry_point,
853 exit_point,
854 arch_info);
856 if (retval != ERROR_OK) {
857 LOG_ERROR("error starting target flash write algorithm");
858 return retval;
861 while (count > 0) {
863 retval = target_read_u32(target, rp_addr, &rp);
864 if (retval != ERROR_OK) {
865 LOG_ERROR("failed to get read pointer");
866 break;
869 LOG_DEBUG("count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32, count, wp, rp);
871 if (rp == 0) {
872 LOG_ERROR("flash write algorithm aborted by target");
873 retval = ERROR_FLASH_OPERATION_FAILED;
874 break;
877 if ((rp & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
878 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
879 break;
882 /* Count the number of bytes available in the fifo without
883 * crossing the wrap around. Make sure to not fill it completely,
884 * because that would make wp == rp and that's the empty condition. */
885 uint32_t thisrun_bytes;
886 if (rp > wp)
887 thisrun_bytes = rp - wp - block_size;
888 else if (rp > fifo_start_addr)
889 thisrun_bytes = fifo_end_addr - wp;
890 else
891 thisrun_bytes = fifo_end_addr - wp - block_size;
893 if (thisrun_bytes == 0) {
894 /* Throttle polling a bit if transfer is (much) faster than flash
895 * programming. The exact delay shouldn't matter as long as it's
896 * less than buffer size / flash speed. This is very unlikely to
897 * run when using high latency connections such as USB. */
898 alive_sleep(10);
900 /* to stop an infinite loop on some targets check and increment a timeout
901 * this issue was observed on a stellaris using the new ICDI interface */
902 if (timeout++ >= 500) {
903 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
904 return ERROR_FLASH_OPERATION_FAILED;
906 continue;
909 /* reset our timeout */
910 timeout = 0;
912 /* Limit to the amount of data we actually want to write */
913 if (thisrun_bytes > count * block_size)
914 thisrun_bytes = count * block_size;
916 /* Write data to fifo */
917 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
918 if (retval != ERROR_OK)
919 break;
921 /* Update counters and wrap write pointer */
922 buffer += thisrun_bytes;
923 count -= thisrun_bytes / block_size;
924 wp += thisrun_bytes;
925 if (wp >= fifo_end_addr)
926 wp = fifo_start_addr;
928 /* Store updated write pointer to target */
929 retval = target_write_u32(target, wp_addr, wp);
930 if (retval != ERROR_OK)
931 break;
934 if (retval != ERROR_OK) {
935 /* abort flash write algorithm on target */
936 target_write_u32(target, wp_addr, 0);
939 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
940 num_reg_params, reg_params,
941 exit_point,
942 10000,
943 arch_info);
945 if (retval2 != ERROR_OK) {
946 LOG_ERROR("error waiting for target flash write algorithm");
947 retval = retval2;
950 return retval;
953 int target_read_memory(struct target *target,
954 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
956 if (!target_was_examined(target)) {
957 LOG_ERROR("Target not examined yet");
958 return ERROR_FAIL;
960 return target->type->read_memory(target, address, size, count, buffer);
963 int target_read_phys_memory(struct target *target,
964 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
966 if (!target_was_examined(target)) {
967 LOG_ERROR("Target not examined yet");
968 return ERROR_FAIL;
970 return target->type->read_phys_memory(target, address, size, count, buffer);
973 int target_write_memory(struct target *target,
974 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
976 if (!target_was_examined(target)) {
977 LOG_ERROR("Target not examined yet");
978 return ERROR_FAIL;
980 return target->type->write_memory(target, address, size, count, buffer);
983 int target_write_phys_memory(struct target *target,
984 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
986 if (!target_was_examined(target)) {
987 LOG_ERROR("Target not examined yet");
988 return ERROR_FAIL;
990 return target->type->write_phys_memory(target, address, size, count, buffer);
993 int target_add_breakpoint(struct target *target,
994 struct breakpoint *breakpoint)
996 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
997 LOG_WARNING("target %s is not halted", target_name(target));
998 return ERROR_TARGET_NOT_HALTED;
1000 return target->type->add_breakpoint(target, breakpoint);
1003 int target_add_context_breakpoint(struct target *target,
1004 struct breakpoint *breakpoint)
1006 if (target->state != TARGET_HALTED) {
1007 LOG_WARNING("target %s is not halted", target_name(target));
1008 return ERROR_TARGET_NOT_HALTED;
1010 return target->type->add_context_breakpoint(target, breakpoint);
1013 int target_add_hybrid_breakpoint(struct target *target,
1014 struct breakpoint *breakpoint)
1016 if (target->state != TARGET_HALTED) {
1017 LOG_WARNING("target %s is not halted", target_name(target));
1018 return ERROR_TARGET_NOT_HALTED;
1020 return target->type->add_hybrid_breakpoint(target, breakpoint);
1023 int target_remove_breakpoint(struct target *target,
1024 struct breakpoint *breakpoint)
1026 return target->type->remove_breakpoint(target, breakpoint);
1029 int target_add_watchpoint(struct target *target,
1030 struct watchpoint *watchpoint)
1032 if (target->state != TARGET_HALTED) {
1033 LOG_WARNING("target %s is not halted", target_name(target));
1034 return ERROR_TARGET_NOT_HALTED;
1036 return target->type->add_watchpoint(target, watchpoint);
1038 int target_remove_watchpoint(struct target *target,
1039 struct watchpoint *watchpoint)
1041 return target->type->remove_watchpoint(target, watchpoint);
1043 int target_hit_watchpoint(struct target *target,
1044 struct watchpoint **hit_watchpoint)
1046 if (target->state != TARGET_HALTED) {
1047 LOG_WARNING("target %s is not halted", target->cmd_name);
1048 return ERROR_TARGET_NOT_HALTED;
1051 if (target->type->hit_watchpoint == NULL) {
1052 /* For backward compatible, if hit_watchpoint is not implemented,
1053 * return ERROR_FAIL such that gdb_server will not take the nonsense
1054 * information. */
1055 return ERROR_FAIL;
1058 return target->type->hit_watchpoint(target, hit_watchpoint);
1061 int target_get_gdb_reg_list(struct target *target,
1062 struct reg **reg_list[], int *reg_list_size,
1063 enum target_register_class reg_class)
1065 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1067 int target_step(struct target *target,
1068 int current, uint32_t address, int handle_breakpoints)
1070 return target->type->step(target, current, address, handle_breakpoints);
1073 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1075 if (target->state != TARGET_HALTED) {
1076 LOG_WARNING("target %s is not halted", target->cmd_name);
1077 return ERROR_TARGET_NOT_HALTED;
1079 return target->type->get_gdb_fileio_info(target, fileio_info);
1082 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1084 if (target->state != TARGET_HALTED) {
1085 LOG_WARNING("target %s is not halted", target->cmd_name);
1086 return ERROR_TARGET_NOT_HALTED;
1088 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1091 int target_profiling(struct target *target, uint32_t *samples,
1092 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1094 if (target->state != TARGET_HALTED) {
1095 LOG_WARNING("target %s is not halted", target->cmd_name);
1096 return ERROR_TARGET_NOT_HALTED;
1098 return target->type->profiling(target, samples, max_num_samples,
1099 num_samples, seconds);
1103 * Reset the @c examined flag for the given target.
1104 * Pure paranoia -- targets are zeroed on allocation.
1106 static void target_reset_examined(struct target *target)
1108 target->examined = false;
1111 static int err_read_phys_memory(struct target *target, uint32_t address,
1112 uint32_t size, uint32_t count, uint8_t *buffer)
1114 LOG_ERROR("Not implemented: %s", __func__);
1115 return ERROR_FAIL;
1118 static int err_write_phys_memory(struct target *target, uint32_t address,
1119 uint32_t size, uint32_t count, const uint8_t *buffer)
1121 LOG_ERROR("Not implemented: %s", __func__);
1122 return ERROR_FAIL;
1125 static int handle_target(void *priv);
1127 static int target_init_one(struct command_context *cmd_ctx,
1128 struct target *target)
1130 target_reset_examined(target);
1132 struct target_type *type = target->type;
1133 if (type->examine == NULL)
1134 type->examine = default_examine;
1136 if (type->check_reset == NULL)
1137 type->check_reset = default_check_reset;
1139 assert(type->init_target != NULL);
1141 int retval = type->init_target(cmd_ctx, target);
1142 if (ERROR_OK != retval) {
1143 LOG_ERROR("target '%s' init failed", target_name(target));
1144 return retval;
1147 /* Sanity-check MMU support ... stub in what we must, to help
1148 * implement it in stages, but warn if we need to do so.
1150 if (type->mmu) {
1151 if (type->write_phys_memory == NULL) {
1152 LOG_ERROR("type '%s' is missing write_phys_memory",
1153 type->name);
1154 type->write_phys_memory = err_write_phys_memory;
1156 if (type->read_phys_memory == NULL) {
1157 LOG_ERROR("type '%s' is missing read_phys_memory",
1158 type->name);
1159 type->read_phys_memory = err_read_phys_memory;
1161 if (type->virt2phys == NULL) {
1162 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1163 type->virt2phys = identity_virt2phys;
1165 } else {
1166 /* Make sure no-MMU targets all behave the same: make no
1167 * distinction between physical and virtual addresses, and
1168 * ensure that virt2phys() is always an identity mapping.
1170 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1171 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1173 type->mmu = no_mmu;
1174 type->write_phys_memory = type->write_memory;
1175 type->read_phys_memory = type->read_memory;
1176 type->virt2phys = identity_virt2phys;
1179 if (target->type->read_buffer == NULL)
1180 target->type->read_buffer = target_read_buffer_default;
1182 if (target->type->write_buffer == NULL)
1183 target->type->write_buffer = target_write_buffer_default;
1185 if (target->type->get_gdb_fileio_info == NULL)
1186 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1188 if (target->type->gdb_fileio_end == NULL)
1189 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1191 if (target->type->profiling == NULL)
1192 target->type->profiling = target_profiling_default;
1194 return ERROR_OK;
1197 static int target_init(struct command_context *cmd_ctx)
1199 struct target *target;
1200 int retval;
1202 for (target = all_targets; target; target = target->next) {
1203 retval = target_init_one(cmd_ctx, target);
1204 if (ERROR_OK != retval)
1205 return retval;
1208 if (!all_targets)
1209 return ERROR_OK;
1211 retval = target_register_user_commands(cmd_ctx);
1212 if (ERROR_OK != retval)
1213 return retval;
1215 retval = target_register_timer_callback(&handle_target,
1216 polling_interval, 1, cmd_ctx->interp);
1217 if (ERROR_OK != retval)
1218 return retval;
1220 return ERROR_OK;
1223 COMMAND_HANDLER(handle_target_init_command)
1225 int retval;
1227 if (CMD_ARGC != 0)
1228 return ERROR_COMMAND_SYNTAX_ERROR;
1230 static bool target_initialized;
1231 if (target_initialized) {
1232 LOG_INFO("'target init' has already been called");
1233 return ERROR_OK;
1235 target_initialized = true;
1237 retval = command_run_line(CMD_CTX, "init_targets");
1238 if (ERROR_OK != retval)
1239 return retval;
1241 retval = command_run_line(CMD_CTX, "init_board");
1242 if (ERROR_OK != retval)
1243 return retval;
1245 LOG_DEBUG("Initializing targets...");
1246 return target_init(CMD_CTX);
1249 int target_register_event_callback(int (*callback)(struct target *target,
1250 enum target_event event, void *priv), void *priv)
1252 struct target_event_callback **callbacks_p = &target_event_callbacks;
1254 if (callback == NULL)
1255 return ERROR_COMMAND_SYNTAX_ERROR;
1257 if (*callbacks_p) {
1258 while ((*callbacks_p)->next)
1259 callbacks_p = &((*callbacks_p)->next);
1260 callbacks_p = &((*callbacks_p)->next);
1263 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1264 (*callbacks_p)->callback = callback;
1265 (*callbacks_p)->priv = priv;
1266 (*callbacks_p)->next = NULL;
1268 return ERROR_OK;
1271 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1273 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1274 struct timeval now;
1276 if (callback == NULL)
1277 return ERROR_COMMAND_SYNTAX_ERROR;
1279 if (*callbacks_p) {
1280 while ((*callbacks_p)->next)
1281 callbacks_p = &((*callbacks_p)->next);
1282 callbacks_p = &((*callbacks_p)->next);
1285 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1286 (*callbacks_p)->callback = callback;
1287 (*callbacks_p)->periodic = periodic;
1288 (*callbacks_p)->time_ms = time_ms;
1290 gettimeofday(&now, NULL);
1291 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
1292 time_ms -= (time_ms % 1000);
1293 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
1294 if ((*callbacks_p)->when.tv_usec > 1000000) {
1295 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
1296 (*callbacks_p)->when.tv_sec += 1;
1299 (*callbacks_p)->priv = priv;
1300 (*callbacks_p)->next = NULL;
1302 return ERROR_OK;
1305 int target_unregister_event_callback(int (*callback)(struct target *target,
1306 enum target_event event, void *priv), void *priv)
1308 struct target_event_callback **p = &target_event_callbacks;
1309 struct target_event_callback *c = target_event_callbacks;
1311 if (callback == NULL)
1312 return ERROR_COMMAND_SYNTAX_ERROR;
1314 while (c) {
1315 struct target_event_callback *next = c->next;
1316 if ((c->callback == callback) && (c->priv == priv)) {
1317 *p = next;
1318 free(c);
1319 return ERROR_OK;
1320 } else
1321 p = &(c->next);
1322 c = next;
1325 return ERROR_OK;
1328 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1330 struct target_timer_callback **p = &target_timer_callbacks;
1331 struct target_timer_callback *c = target_timer_callbacks;
1333 if (callback == NULL)
1334 return ERROR_COMMAND_SYNTAX_ERROR;
1336 while (c) {
1337 struct target_timer_callback *next = c->next;
1338 if ((c->callback == callback) && (c->priv == priv)) {
1339 *p = next;
1340 free(c);
1341 return ERROR_OK;
1342 } else
1343 p = &(c->next);
1344 c = next;
1347 return ERROR_OK;
1350 int target_call_event_callbacks(struct target *target, enum target_event event)
1352 struct target_event_callback *callback = target_event_callbacks;
1353 struct target_event_callback *next_callback;
1355 if (event == TARGET_EVENT_HALTED) {
1356 /* execute early halted first */
1357 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1360 LOG_DEBUG("target event %i (%s)", event,
1361 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1363 target_handle_event(target, event);
1365 while (callback) {
1366 next_callback = callback->next;
1367 callback->callback(target, event, callback->priv);
1368 callback = next_callback;
1371 return ERROR_OK;
1374 static int target_timer_callback_periodic_restart(
1375 struct target_timer_callback *cb, struct timeval *now)
1377 int time_ms = cb->time_ms;
1378 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1379 time_ms -= (time_ms % 1000);
1380 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1381 if (cb->when.tv_usec > 1000000) {
1382 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1383 cb->when.tv_sec += 1;
1385 return ERROR_OK;
1388 static int target_call_timer_callback(struct target_timer_callback *cb,
1389 struct timeval *now)
1391 cb->callback(cb->priv);
1393 if (cb->periodic)
1394 return target_timer_callback_periodic_restart(cb, now);
1396 return target_unregister_timer_callback(cb->callback, cb->priv);
1399 static int target_call_timer_callbacks_check_time(int checktime)
1401 keep_alive();
1403 struct timeval now;
1404 gettimeofday(&now, NULL);
1406 struct target_timer_callback *callback = target_timer_callbacks;
1407 while (callback) {
1408 /* cleaning up may unregister and free this callback */
1409 struct target_timer_callback *next_callback = callback->next;
1411 bool call_it = callback->callback &&
1412 ((!checktime && callback->periodic) ||
1413 now.tv_sec > callback->when.tv_sec ||
1414 (now.tv_sec == callback->when.tv_sec &&
1415 now.tv_usec >= callback->when.tv_usec));
1417 if (call_it) {
1418 int retval = target_call_timer_callback(callback, &now);
1419 if (retval != ERROR_OK)
1420 return retval;
1423 callback = next_callback;
1426 return ERROR_OK;
1429 int target_call_timer_callbacks(void)
1431 return target_call_timer_callbacks_check_time(1);
1434 /* invoke periodic callbacks immediately */
1435 int target_call_timer_callbacks_now(void)
1437 return target_call_timer_callbacks_check_time(0);
1440 /* Prints the working area layout for debug purposes */
1441 static void print_wa_layout(struct target *target)
1443 struct working_area *c = target->working_areas;
1445 while (c) {
1446 LOG_DEBUG("%c%c 0x%08"PRIx32"-0x%08"PRIx32" (%"PRIu32" bytes)",
1447 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1448 c->address, c->address + c->size - 1, c->size);
1449 c = c->next;
1453 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1454 static void target_split_working_area(struct working_area *area, uint32_t size)
1456 assert(area->free); /* Shouldn't split an allocated area */
1457 assert(size <= area->size); /* Caller should guarantee this */
1459 /* Split only if not already the right size */
1460 if (size < area->size) {
1461 struct working_area *new_wa = malloc(sizeof(*new_wa));
1463 if (new_wa == NULL)
1464 return;
1466 new_wa->next = area->next;
1467 new_wa->size = area->size - size;
1468 new_wa->address = area->address + size;
1469 new_wa->backup = NULL;
1470 new_wa->user = NULL;
1471 new_wa->free = true;
1473 area->next = new_wa;
1474 area->size = size;
1476 /* If backup memory was allocated to this area, it has the wrong size
1477 * now so free it and it will be reallocated if/when needed */
1478 if (area->backup) {
1479 free(area->backup);
1480 area->backup = NULL;
1485 /* Merge all adjacent free areas into one */
1486 static void target_merge_working_areas(struct target *target)
1488 struct working_area *c = target->working_areas;
1490 while (c && c->next) {
1491 assert(c->next->address == c->address + c->size); /* This is an invariant */
1493 /* Find two adjacent free areas */
1494 if (c->free && c->next->free) {
1495 /* Merge the last into the first */
1496 c->size += c->next->size;
1498 /* Remove the last */
1499 struct working_area *to_be_freed = c->next;
1500 c->next = c->next->next;
1501 if (to_be_freed->backup)
1502 free(to_be_freed->backup);
1503 free(to_be_freed);
1505 /* If backup memory was allocated to the remaining area, it's has
1506 * the wrong size now */
1507 if (c->backup) {
1508 free(c->backup);
1509 c->backup = NULL;
1511 } else {
1512 c = c->next;
1517 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1519 /* Reevaluate working area address based on MMU state*/
1520 if (target->working_areas == NULL) {
1521 int retval;
1522 int enabled;
1524 retval = target->type->mmu(target, &enabled);
1525 if (retval != ERROR_OK)
1526 return retval;
1528 if (!enabled) {
1529 if (target->working_area_phys_spec) {
1530 LOG_DEBUG("MMU disabled, using physical "
1531 "address for working memory 0x%08"PRIx32,
1532 target->working_area_phys);
1533 target->working_area = target->working_area_phys;
1534 } else {
1535 LOG_ERROR("No working memory available. "
1536 "Specify -work-area-phys to target.");
1537 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1539 } else {
1540 if (target->working_area_virt_spec) {
1541 LOG_DEBUG("MMU enabled, using virtual "
1542 "address for working memory 0x%08"PRIx32,
1543 target->working_area_virt);
1544 target->working_area = target->working_area_virt;
1545 } else {
1546 LOG_ERROR("No working memory available. "
1547 "Specify -work-area-virt to target.");
1548 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1552 /* Set up initial working area on first call */
1553 struct working_area *new_wa = malloc(sizeof(*new_wa));
1554 if (new_wa) {
1555 new_wa->next = NULL;
1556 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1557 new_wa->address = target->working_area;
1558 new_wa->backup = NULL;
1559 new_wa->user = NULL;
1560 new_wa->free = true;
1563 target->working_areas = new_wa;
1566 /* only allocate multiples of 4 byte */
1567 if (size % 4)
1568 size = (size + 3) & (~3UL);
1570 struct working_area *c = target->working_areas;
1572 /* Find the first large enough working area */
1573 while (c) {
1574 if (c->free && c->size >= size)
1575 break;
1576 c = c->next;
1579 if (c == NULL)
1580 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1582 /* Split the working area into the requested size */
1583 target_split_working_area(c, size);
1585 LOG_DEBUG("allocated new working area of %"PRIu32" bytes at address 0x%08"PRIx32, size, c->address);
1587 if (target->backup_working_area) {
1588 if (c->backup == NULL) {
1589 c->backup = malloc(c->size);
1590 if (c->backup == NULL)
1591 return ERROR_FAIL;
1594 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1595 if (retval != ERROR_OK)
1596 return retval;
1599 /* mark as used, and return the new (reused) area */
1600 c->free = false;
1601 *area = c;
1603 /* user pointer */
1604 c->user = area;
1606 print_wa_layout(target);
1608 return ERROR_OK;
1611 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1613 int retval;
1615 retval = target_alloc_working_area_try(target, size, area);
1616 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1617 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1618 return retval;
1622 static int target_restore_working_area(struct target *target, struct working_area *area)
1624 int retval = ERROR_OK;
1626 if (target->backup_working_area && area->backup != NULL) {
1627 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1628 if (retval != ERROR_OK)
1629 LOG_ERROR("failed to restore %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1630 area->size, area->address);
1633 return retval;
1636 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1637 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1639 int retval = ERROR_OK;
1641 if (area->free)
1642 return retval;
1644 if (restore) {
1645 retval = target_restore_working_area(target, area);
1646 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1647 if (retval != ERROR_OK)
1648 return retval;
1651 area->free = true;
1653 LOG_DEBUG("freed %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1654 area->size, area->address);
1656 /* mark user pointer invalid */
1657 /* TODO: Is this really safe? It points to some previous caller's memory.
1658 * How could we know that the area pointer is still in that place and not
1659 * some other vital data? What's the purpose of this, anyway? */
1660 *area->user = NULL;
1661 area->user = NULL;
1663 target_merge_working_areas(target);
1665 print_wa_layout(target);
1667 return retval;
1670 int target_free_working_area(struct target *target, struct working_area *area)
1672 return target_free_working_area_restore(target, area, 1);
1675 /* free resources and restore memory, if restoring memory fails,
1676 * free up resources anyway
1678 static void target_free_all_working_areas_restore(struct target *target, int restore)
1680 struct working_area *c = target->working_areas;
1682 LOG_DEBUG("freeing all working areas");
1684 /* Loop through all areas, restoring the allocated ones and marking them as free */
1685 while (c) {
1686 if (!c->free) {
1687 if (restore)
1688 target_restore_working_area(target, c);
1689 c->free = true;
1690 *c->user = NULL; /* Same as above */
1691 c->user = NULL;
1693 c = c->next;
1696 /* Run a merge pass to combine all areas into one */
1697 target_merge_working_areas(target);
1699 print_wa_layout(target);
1702 void target_free_all_working_areas(struct target *target)
1704 target_free_all_working_areas_restore(target, 1);
1707 /* Find the largest number of bytes that can be allocated */
1708 uint32_t target_get_working_area_avail(struct target *target)
1710 struct working_area *c = target->working_areas;
1711 uint32_t max_size = 0;
1713 if (c == NULL)
1714 return target->working_area_size;
1716 while (c) {
1717 if (c->free && max_size < c->size)
1718 max_size = c->size;
1720 c = c->next;
1723 return max_size;
1726 int target_arch_state(struct target *target)
1728 int retval;
1729 if (target == NULL) {
1730 LOG_USER("No target has been configured");
1731 return ERROR_OK;
1734 LOG_USER("target state: %s", target_state_name(target));
1736 if (target->state != TARGET_HALTED)
1737 return ERROR_OK;
1739 retval = target->type->arch_state(target);
1740 return retval;
1743 static int target_get_gdb_fileio_info_default(struct target *target,
1744 struct gdb_fileio_info *fileio_info)
1746 /* If target does not support semi-hosting function, target
1747 has no need to provide .get_gdb_fileio_info callback.
1748 It just return ERROR_FAIL and gdb_server will return "Txx"
1749 as target halted every time. */
1750 return ERROR_FAIL;
1753 static int target_gdb_fileio_end_default(struct target *target,
1754 int retcode, int fileio_errno, bool ctrl_c)
1756 return ERROR_OK;
1759 static int target_profiling_default(struct target *target, uint32_t *samples,
1760 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1762 struct timeval timeout, now;
1764 gettimeofday(&timeout, NULL);
1765 timeval_add_time(&timeout, seconds, 0);
1767 LOG_INFO("Starting profiling. Halting and resuming the"
1768 " target as often as we can...");
1770 uint32_t sample_count = 0;
1771 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
1772 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
1774 int retval = ERROR_OK;
1775 for (;;) {
1776 target_poll(target);
1777 if (target->state == TARGET_HALTED) {
1778 uint32_t t = *((uint32_t *)reg->value);
1779 samples[sample_count++] = t;
1780 /* current pc, addr = 0, do not handle breakpoints, not debugging */
1781 retval = target_resume(target, 1, 0, 0, 0);
1782 target_poll(target);
1783 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
1784 } else if (target->state == TARGET_RUNNING) {
1785 /* We want to quickly sample the PC. */
1786 retval = target_halt(target);
1787 } else {
1788 LOG_INFO("Target not halted or running");
1789 retval = ERROR_OK;
1790 break;
1793 if (retval != ERROR_OK)
1794 break;
1796 gettimeofday(&now, NULL);
1797 if ((sample_count >= max_num_samples) ||
1798 ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec))) {
1799 LOG_INFO("Profiling completed. %d samples.", sample_count);
1800 break;
1804 *num_samples = sample_count;
1805 return retval;
1808 /* Single aligned words are guaranteed to use 16 or 32 bit access
1809 * mode respectively, otherwise data is handled as quickly as
1810 * possible
1812 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1814 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1815 (int)size, (unsigned)address);
1817 if (!target_was_examined(target)) {
1818 LOG_ERROR("Target not examined yet");
1819 return ERROR_FAIL;
1822 if (size == 0)
1823 return ERROR_OK;
1825 if ((address + size - 1) < address) {
1826 /* GDB can request this when e.g. PC is 0xfffffffc*/
1827 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1828 (unsigned)address,
1829 (unsigned)size);
1830 return ERROR_FAIL;
1833 return target->type->write_buffer(target, address, size, buffer);
1836 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t count, const uint8_t *buffer)
1838 uint32_t size;
1840 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
1841 * will have something to do with the size we leave to it. */
1842 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
1843 if (address & size) {
1844 int retval = target_write_memory(target, address, size, 1, buffer);
1845 if (retval != ERROR_OK)
1846 return retval;
1847 address += size;
1848 count -= size;
1849 buffer += size;
1853 /* Write the data with as large access size as possible. */
1854 for (; size > 0; size /= 2) {
1855 uint32_t aligned = count - count % size;
1856 if (aligned > 0) {
1857 int retval = target_write_memory(target, address, size, aligned / size, buffer);
1858 if (retval != ERROR_OK)
1859 return retval;
1860 address += aligned;
1861 count -= aligned;
1862 buffer += aligned;
1866 return ERROR_OK;
1869 /* Single aligned words are guaranteed to use 16 or 32 bit access
1870 * mode respectively, otherwise data is handled as quickly as
1871 * possible
1873 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1875 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1876 (int)size, (unsigned)address);
1878 if (!target_was_examined(target)) {
1879 LOG_ERROR("Target not examined yet");
1880 return ERROR_FAIL;
1883 if (size == 0)
1884 return ERROR_OK;
1886 if ((address + size - 1) < address) {
1887 /* GDB can request this when e.g. PC is 0xfffffffc*/
1888 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1889 address,
1890 size);
1891 return ERROR_FAIL;
1894 return target->type->read_buffer(target, address, size, buffer);
1897 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t count, uint8_t *buffer)
1899 uint32_t size;
1901 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
1902 * will have something to do with the size we leave to it. */
1903 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
1904 if (address & size) {
1905 int retval = target_read_memory(target, address, size, 1, buffer);
1906 if (retval != ERROR_OK)
1907 return retval;
1908 address += size;
1909 count -= size;
1910 buffer += size;
1914 /* Read the data with as large access size as possible. */
1915 for (; size > 0; size /= 2) {
1916 uint32_t aligned = count - count % size;
1917 if (aligned > 0) {
1918 int retval = target_read_memory(target, address, size, aligned / size, buffer);
1919 if (retval != ERROR_OK)
1920 return retval;
1921 address += aligned;
1922 count -= aligned;
1923 buffer += aligned;
1927 return ERROR_OK;
1930 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1932 uint8_t *buffer;
1933 int retval;
1934 uint32_t i;
1935 uint32_t checksum = 0;
1936 if (!target_was_examined(target)) {
1937 LOG_ERROR("Target not examined yet");
1938 return ERROR_FAIL;
1941 retval = target->type->checksum_memory(target, address, size, &checksum);
1942 if (retval != ERROR_OK) {
1943 buffer = malloc(size);
1944 if (buffer == NULL) {
1945 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1946 return ERROR_COMMAND_SYNTAX_ERROR;
1948 retval = target_read_buffer(target, address, size, buffer);
1949 if (retval != ERROR_OK) {
1950 free(buffer);
1951 return retval;
1954 /* convert to target endianness */
1955 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
1956 uint32_t target_data;
1957 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1958 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1961 retval = image_calculate_checksum(buffer, size, &checksum);
1962 free(buffer);
1965 *crc = checksum;
1967 return retval;
1970 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1972 int retval;
1973 if (!target_was_examined(target)) {
1974 LOG_ERROR("Target not examined yet");
1975 return ERROR_FAIL;
1978 if (target->type->blank_check_memory == 0)
1979 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1981 retval = target->type->blank_check_memory(target, address, size, blank);
1983 return retval;
1986 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1988 uint8_t value_buf[4];
1989 if (!target_was_examined(target)) {
1990 LOG_ERROR("Target not examined yet");
1991 return ERROR_FAIL;
1994 int retval = target_read_memory(target, address, 4, 1, value_buf);
1996 if (retval == ERROR_OK) {
1997 *value = target_buffer_get_u32(target, value_buf);
1998 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1999 address,
2000 *value);
2001 } else {
2002 *value = 0x0;
2003 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2004 address);
2007 return retval;
2010 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
2012 uint8_t value_buf[2];
2013 if (!target_was_examined(target)) {
2014 LOG_ERROR("Target not examined yet");
2015 return ERROR_FAIL;
2018 int retval = target_read_memory(target, address, 2, 1, value_buf);
2020 if (retval == ERROR_OK) {
2021 *value = target_buffer_get_u16(target, value_buf);
2022 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
2023 address,
2024 *value);
2025 } else {
2026 *value = 0x0;
2027 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2028 address);
2031 return retval;
2034 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
2036 if (!target_was_examined(target)) {
2037 LOG_ERROR("Target not examined yet");
2038 return ERROR_FAIL;
2041 int retval = target_read_memory(target, address, 1, 1, value);
2043 if (retval == ERROR_OK) {
2044 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2045 address,
2046 *value);
2047 } else {
2048 *value = 0x0;
2049 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2050 address);
2053 return retval;
2056 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
2058 int retval;
2059 uint8_t value_buf[4];
2060 if (!target_was_examined(target)) {
2061 LOG_ERROR("Target not examined yet");
2062 return ERROR_FAIL;
2065 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2066 address,
2067 value);
2069 target_buffer_set_u32(target, value_buf, value);
2070 retval = target_write_memory(target, address, 4, 1, value_buf);
2071 if (retval != ERROR_OK)
2072 LOG_DEBUG("failed: %i", retval);
2074 return retval;
2077 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
2079 int retval;
2080 uint8_t value_buf[2];
2081 if (!target_was_examined(target)) {
2082 LOG_ERROR("Target not examined yet");
2083 return ERROR_FAIL;
2086 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
2087 address,
2088 value);
2090 target_buffer_set_u16(target, value_buf, value);
2091 retval = target_write_memory(target, address, 2, 1, value_buf);
2092 if (retval != ERROR_OK)
2093 LOG_DEBUG("failed: %i", retval);
2095 return retval;
2098 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
2100 int retval;
2101 if (!target_was_examined(target)) {
2102 LOG_ERROR("Target not examined yet");
2103 return ERROR_FAIL;
2106 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2107 address, value);
2109 retval = target_write_memory(target, address, 1, 1, &value);
2110 if (retval != ERROR_OK)
2111 LOG_DEBUG("failed: %i", retval);
2113 return retval;
2116 static int find_target(struct command_context *cmd_ctx, const char *name)
2118 struct target *target = get_target(name);
2119 if (target == NULL) {
2120 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2121 return ERROR_FAIL;
2123 if (!target->tap->enabled) {
2124 LOG_USER("Target: TAP %s is disabled, "
2125 "can't be the current target\n",
2126 target->tap->dotted_name);
2127 return ERROR_FAIL;
2130 cmd_ctx->current_target = target->target_number;
2131 return ERROR_OK;
2135 COMMAND_HANDLER(handle_targets_command)
2137 int retval = ERROR_OK;
2138 if (CMD_ARGC == 1) {
2139 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2140 if (retval == ERROR_OK) {
2141 /* we're done! */
2142 return retval;
2146 struct target *target = all_targets;
2147 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2148 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2149 while (target) {
2150 const char *state;
2151 char marker = ' ';
2153 if (target->tap->enabled)
2154 state = target_state_name(target);
2155 else
2156 state = "tap-disabled";
2158 if (CMD_CTX->current_target == target->target_number)
2159 marker = '*';
2161 /* keep columns lined up to match the headers above */
2162 command_print(CMD_CTX,
2163 "%2d%c %-18s %-10s %-6s %-18s %s",
2164 target->target_number,
2165 marker,
2166 target_name(target),
2167 target_type_name(target),
2168 Jim_Nvp_value2name_simple(nvp_target_endian,
2169 target->endianness)->name,
2170 target->tap->dotted_name,
2171 state);
2172 target = target->next;
2175 return retval;
2178 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2180 static int powerDropout;
2181 static int srstAsserted;
2183 static int runPowerRestore;
2184 static int runPowerDropout;
2185 static int runSrstAsserted;
2186 static int runSrstDeasserted;
2188 static int sense_handler(void)
2190 static int prevSrstAsserted;
2191 static int prevPowerdropout;
2193 int retval = jtag_power_dropout(&powerDropout);
2194 if (retval != ERROR_OK)
2195 return retval;
2197 int powerRestored;
2198 powerRestored = prevPowerdropout && !powerDropout;
2199 if (powerRestored)
2200 runPowerRestore = 1;
2202 long long current = timeval_ms();
2203 static long long lastPower;
2204 int waitMore = lastPower + 2000 > current;
2205 if (powerDropout && !waitMore) {
2206 runPowerDropout = 1;
2207 lastPower = current;
2210 retval = jtag_srst_asserted(&srstAsserted);
2211 if (retval != ERROR_OK)
2212 return retval;
2214 int srstDeasserted;
2215 srstDeasserted = prevSrstAsserted && !srstAsserted;
2217 static long long lastSrst;
2218 waitMore = lastSrst + 2000 > current;
2219 if (srstDeasserted && !waitMore) {
2220 runSrstDeasserted = 1;
2221 lastSrst = current;
2224 if (!prevSrstAsserted && srstAsserted)
2225 runSrstAsserted = 1;
2227 prevSrstAsserted = srstAsserted;
2228 prevPowerdropout = powerDropout;
2230 if (srstDeasserted || powerRestored) {
2231 /* Other than logging the event we can't do anything here.
2232 * Issuing a reset is a particularly bad idea as we might
2233 * be inside a reset already.
2237 return ERROR_OK;
2240 /* process target state changes */
2241 static int handle_target(void *priv)
2243 Jim_Interp *interp = (Jim_Interp *)priv;
2244 int retval = ERROR_OK;
2246 if (!is_jtag_poll_safe()) {
2247 /* polling is disabled currently */
2248 return ERROR_OK;
2251 /* we do not want to recurse here... */
2252 static int recursive;
2253 if (!recursive) {
2254 recursive = 1;
2255 sense_handler();
2256 /* danger! running these procedures can trigger srst assertions and power dropouts.
2257 * We need to avoid an infinite loop/recursion here and we do that by
2258 * clearing the flags after running these events.
2260 int did_something = 0;
2261 if (runSrstAsserted) {
2262 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2263 Jim_Eval(interp, "srst_asserted");
2264 did_something = 1;
2266 if (runSrstDeasserted) {
2267 Jim_Eval(interp, "srst_deasserted");
2268 did_something = 1;
2270 if (runPowerDropout) {
2271 LOG_INFO("Power dropout detected, running power_dropout proc.");
2272 Jim_Eval(interp, "power_dropout");
2273 did_something = 1;
2275 if (runPowerRestore) {
2276 Jim_Eval(interp, "power_restore");
2277 did_something = 1;
2280 if (did_something) {
2281 /* clear detect flags */
2282 sense_handler();
2285 /* clear action flags */
2287 runSrstAsserted = 0;
2288 runSrstDeasserted = 0;
2289 runPowerRestore = 0;
2290 runPowerDropout = 0;
2292 recursive = 0;
2295 /* Poll targets for state changes unless that's globally disabled.
2296 * Skip targets that are currently disabled.
2298 for (struct target *target = all_targets;
2299 is_jtag_poll_safe() && target;
2300 target = target->next) {
2301 if (!target->tap->enabled)
2302 continue;
2304 if (target->backoff.times > target->backoff.count) {
2305 /* do not poll this time as we failed previously */
2306 target->backoff.count++;
2307 continue;
2309 target->backoff.count = 0;
2311 /* only poll target if we've got power and srst isn't asserted */
2312 if (!powerDropout && !srstAsserted) {
2313 /* polling may fail silently until the target has been examined */
2314 retval = target_poll(target);
2315 if (retval != ERROR_OK) {
2316 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2317 if (target->backoff.times * polling_interval < 5000) {
2318 target->backoff.times *= 2;
2319 target->backoff.times++;
2321 LOG_USER("Polling target %s failed, GDB will be halted. Polling again in %dms",
2322 target_name(target),
2323 target->backoff.times * polling_interval);
2325 /* Tell GDB to halt the debugger. This allows the user to
2326 * run monitor commands to handle the situation.
2328 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2329 return retval;
2331 /* Since we succeeded, we reset backoff count */
2332 if (target->backoff.times > 0)
2333 LOG_USER("Polling target %s succeeded again", target_name(target));
2334 target->backoff.times = 0;
2338 return retval;
2341 COMMAND_HANDLER(handle_reg_command)
2343 struct target *target;
2344 struct reg *reg = NULL;
2345 unsigned count = 0;
2346 char *value;
2348 LOG_DEBUG("-");
2350 target = get_current_target(CMD_CTX);
2352 /* list all available registers for the current target */
2353 if (CMD_ARGC == 0) {
2354 struct reg_cache *cache = target->reg_cache;
2356 count = 0;
2357 while (cache) {
2358 unsigned i;
2360 command_print(CMD_CTX, "===== %s", cache->name);
2362 for (i = 0, reg = cache->reg_list;
2363 i < cache->num_regs;
2364 i++, reg++, count++) {
2365 /* only print cached values if they are valid */
2366 if (reg->valid) {
2367 value = buf_to_str(reg->value,
2368 reg->size, 16);
2369 command_print(CMD_CTX,
2370 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2371 count, reg->name,
2372 reg->size, value,
2373 reg->dirty
2374 ? " (dirty)"
2375 : "");
2376 free(value);
2377 } else {
2378 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2379 count, reg->name,
2380 reg->size) ;
2383 cache = cache->next;
2386 return ERROR_OK;
2389 /* access a single register by its ordinal number */
2390 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2391 unsigned num;
2392 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2394 struct reg_cache *cache = target->reg_cache;
2395 count = 0;
2396 while (cache) {
2397 unsigned i;
2398 for (i = 0; i < cache->num_regs; i++) {
2399 if (count++ == num) {
2400 reg = &cache->reg_list[i];
2401 break;
2404 if (reg)
2405 break;
2406 cache = cache->next;
2409 if (!reg) {
2410 command_print(CMD_CTX, "%i is out of bounds, the current target "
2411 "has only %i registers (0 - %i)", num, count, count - 1);
2412 return ERROR_OK;
2414 } else {
2415 /* access a single register by its name */
2416 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2418 if (!reg) {
2419 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2420 return ERROR_OK;
2424 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2426 /* display a register */
2427 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2428 && (CMD_ARGV[1][0] <= '9')))) {
2429 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2430 reg->valid = 0;
2432 if (reg->valid == 0)
2433 reg->type->get(reg);
2434 value = buf_to_str(reg->value, reg->size, 16);
2435 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2436 free(value);
2437 return ERROR_OK;
2440 /* set register value */
2441 if (CMD_ARGC == 2) {
2442 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2443 if (buf == NULL)
2444 return ERROR_FAIL;
2445 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2447 reg->type->set(reg, buf);
2449 value = buf_to_str(reg->value, reg->size, 16);
2450 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2451 free(value);
2453 free(buf);
2455 return ERROR_OK;
2458 return ERROR_COMMAND_SYNTAX_ERROR;
2461 COMMAND_HANDLER(handle_poll_command)
2463 int retval = ERROR_OK;
2464 struct target *target = get_current_target(CMD_CTX);
2466 if (CMD_ARGC == 0) {
2467 command_print(CMD_CTX, "background polling: %s",
2468 jtag_poll_get_enabled() ? "on" : "off");
2469 command_print(CMD_CTX, "TAP: %s (%s)",
2470 target->tap->dotted_name,
2471 target->tap->enabled ? "enabled" : "disabled");
2472 if (!target->tap->enabled)
2473 return ERROR_OK;
2474 retval = target_poll(target);
2475 if (retval != ERROR_OK)
2476 return retval;
2477 retval = target_arch_state(target);
2478 if (retval != ERROR_OK)
2479 return retval;
2480 } else if (CMD_ARGC == 1) {
2481 bool enable;
2482 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2483 jtag_poll_set_enabled(enable);
2484 } else
2485 return ERROR_COMMAND_SYNTAX_ERROR;
2487 return retval;
2490 COMMAND_HANDLER(handle_wait_halt_command)
2492 if (CMD_ARGC > 1)
2493 return ERROR_COMMAND_SYNTAX_ERROR;
2495 unsigned ms = DEFAULT_HALT_TIMEOUT;
2496 if (1 == CMD_ARGC) {
2497 int retval = parse_uint(CMD_ARGV[0], &ms);
2498 if (ERROR_OK != retval)
2499 return ERROR_COMMAND_SYNTAX_ERROR;
2502 struct target *target = get_current_target(CMD_CTX);
2503 return target_wait_state(target, TARGET_HALTED, ms);
2506 /* wait for target state to change. The trick here is to have a low
2507 * latency for short waits and not to suck up all the CPU time
2508 * on longer waits.
2510 * After 500ms, keep_alive() is invoked
2512 int target_wait_state(struct target *target, enum target_state state, int ms)
2514 int retval;
2515 long long then = 0, cur;
2516 int once = 1;
2518 for (;;) {
2519 retval = target_poll(target);
2520 if (retval != ERROR_OK)
2521 return retval;
2522 if (target->state == state)
2523 break;
2524 cur = timeval_ms();
2525 if (once) {
2526 once = 0;
2527 then = timeval_ms();
2528 LOG_DEBUG("waiting for target %s...",
2529 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2532 if (cur-then > 500)
2533 keep_alive();
2535 if ((cur-then) > ms) {
2536 LOG_ERROR("timed out while waiting for target %s",
2537 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2538 return ERROR_FAIL;
2542 return ERROR_OK;
2545 COMMAND_HANDLER(handle_halt_command)
2547 LOG_DEBUG("-");
2549 struct target *target = get_current_target(CMD_CTX);
2550 int retval = target_halt(target);
2551 if (ERROR_OK != retval)
2552 return retval;
2554 if (CMD_ARGC == 1) {
2555 unsigned wait_local;
2556 retval = parse_uint(CMD_ARGV[0], &wait_local);
2557 if (ERROR_OK != retval)
2558 return ERROR_COMMAND_SYNTAX_ERROR;
2559 if (!wait_local)
2560 return ERROR_OK;
2563 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2566 COMMAND_HANDLER(handle_soft_reset_halt_command)
2568 struct target *target = get_current_target(CMD_CTX);
2570 LOG_USER("requesting target halt and executing a soft reset");
2572 target_soft_reset_halt(target);
2574 return ERROR_OK;
2577 COMMAND_HANDLER(handle_reset_command)
2579 if (CMD_ARGC > 1)
2580 return ERROR_COMMAND_SYNTAX_ERROR;
2582 enum target_reset_mode reset_mode = RESET_RUN;
2583 if (CMD_ARGC == 1) {
2584 const Jim_Nvp *n;
2585 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2586 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2587 return ERROR_COMMAND_SYNTAX_ERROR;
2588 reset_mode = n->value;
2591 /* reset *all* targets */
2592 return target_process_reset(CMD_CTX, reset_mode);
2596 COMMAND_HANDLER(handle_resume_command)
2598 int current = 1;
2599 if (CMD_ARGC > 1)
2600 return ERROR_COMMAND_SYNTAX_ERROR;
2602 struct target *target = get_current_target(CMD_CTX);
2604 /* with no CMD_ARGV, resume from current pc, addr = 0,
2605 * with one arguments, addr = CMD_ARGV[0],
2606 * handle breakpoints, not debugging */
2607 uint32_t addr = 0;
2608 if (CMD_ARGC == 1) {
2609 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2610 current = 0;
2613 return target_resume(target, current, addr, 1, 0);
2616 COMMAND_HANDLER(handle_step_command)
2618 if (CMD_ARGC > 1)
2619 return ERROR_COMMAND_SYNTAX_ERROR;
2621 LOG_DEBUG("-");
2623 /* with no CMD_ARGV, step from current pc, addr = 0,
2624 * with one argument addr = CMD_ARGV[0],
2625 * handle breakpoints, debugging */
2626 uint32_t addr = 0;
2627 int current_pc = 1;
2628 if (CMD_ARGC == 1) {
2629 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2630 current_pc = 0;
2633 struct target *target = get_current_target(CMD_CTX);
2635 return target->type->step(target, current_pc, addr, 1);
2638 static void handle_md_output(struct command_context *cmd_ctx,
2639 struct target *target, uint32_t address, unsigned size,
2640 unsigned count, const uint8_t *buffer)
2642 const unsigned line_bytecnt = 32;
2643 unsigned line_modulo = line_bytecnt / size;
2645 char output[line_bytecnt * 4 + 1];
2646 unsigned output_len = 0;
2648 const char *value_fmt;
2649 switch (size) {
2650 case 4:
2651 value_fmt = "%8.8x ";
2652 break;
2653 case 2:
2654 value_fmt = "%4.4x ";
2655 break;
2656 case 1:
2657 value_fmt = "%2.2x ";
2658 break;
2659 default:
2660 /* "can't happen", caller checked */
2661 LOG_ERROR("invalid memory read size: %u", size);
2662 return;
2665 for (unsigned i = 0; i < count; i++) {
2666 if (i % line_modulo == 0) {
2667 output_len += snprintf(output + output_len,
2668 sizeof(output) - output_len,
2669 "0x%8.8x: ",
2670 (unsigned)(address + (i*size)));
2673 uint32_t value = 0;
2674 const uint8_t *value_ptr = buffer + i * size;
2675 switch (size) {
2676 case 4:
2677 value = target_buffer_get_u32(target, value_ptr);
2678 break;
2679 case 2:
2680 value = target_buffer_get_u16(target, value_ptr);
2681 break;
2682 case 1:
2683 value = *value_ptr;
2685 output_len += snprintf(output + output_len,
2686 sizeof(output) - output_len,
2687 value_fmt, value);
2689 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2690 command_print(cmd_ctx, "%s", output);
2691 output_len = 0;
2696 COMMAND_HANDLER(handle_md_command)
2698 if (CMD_ARGC < 1)
2699 return ERROR_COMMAND_SYNTAX_ERROR;
2701 unsigned size = 0;
2702 switch (CMD_NAME[2]) {
2703 case 'w':
2704 size = 4;
2705 break;
2706 case 'h':
2707 size = 2;
2708 break;
2709 case 'b':
2710 size = 1;
2711 break;
2712 default:
2713 return ERROR_COMMAND_SYNTAX_ERROR;
2716 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2717 int (*fn)(struct target *target,
2718 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2719 if (physical) {
2720 CMD_ARGC--;
2721 CMD_ARGV++;
2722 fn = target_read_phys_memory;
2723 } else
2724 fn = target_read_memory;
2725 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2726 return ERROR_COMMAND_SYNTAX_ERROR;
2728 uint32_t address;
2729 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2731 unsigned count = 1;
2732 if (CMD_ARGC == 2)
2733 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2735 uint8_t *buffer = calloc(count, size);
2737 struct target *target = get_current_target(CMD_CTX);
2738 int retval = fn(target, address, size, count, buffer);
2739 if (ERROR_OK == retval)
2740 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2742 free(buffer);
2744 return retval;
2747 typedef int (*target_write_fn)(struct target *target,
2748 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2750 static int target_fill_mem(struct target *target,
2751 uint32_t address,
2752 target_write_fn fn,
2753 unsigned data_size,
2754 /* value */
2755 uint32_t b,
2756 /* count */
2757 unsigned c)
2759 /* We have to write in reasonably large chunks to be able
2760 * to fill large memory areas with any sane speed */
2761 const unsigned chunk_size = 16384;
2762 uint8_t *target_buf = malloc(chunk_size * data_size);
2763 if (target_buf == NULL) {
2764 LOG_ERROR("Out of memory");
2765 return ERROR_FAIL;
2768 for (unsigned i = 0; i < chunk_size; i++) {
2769 switch (data_size) {
2770 case 4:
2771 target_buffer_set_u32(target, target_buf + i * data_size, b);
2772 break;
2773 case 2:
2774 target_buffer_set_u16(target, target_buf + i * data_size, b);
2775 break;
2776 case 1:
2777 target_buffer_set_u8(target, target_buf + i * data_size, b);
2778 break;
2779 default:
2780 exit(-1);
2784 int retval = ERROR_OK;
2786 for (unsigned x = 0; x < c; x += chunk_size) {
2787 unsigned current;
2788 current = c - x;
2789 if (current > chunk_size)
2790 current = chunk_size;
2791 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2792 if (retval != ERROR_OK)
2793 break;
2794 /* avoid GDB timeouts */
2795 keep_alive();
2797 free(target_buf);
2799 return retval;
2803 COMMAND_HANDLER(handle_mw_command)
2805 if (CMD_ARGC < 2)
2806 return ERROR_COMMAND_SYNTAX_ERROR;
2807 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2808 target_write_fn fn;
2809 if (physical) {
2810 CMD_ARGC--;
2811 CMD_ARGV++;
2812 fn = target_write_phys_memory;
2813 } else
2814 fn = target_write_memory;
2815 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2816 return ERROR_COMMAND_SYNTAX_ERROR;
2818 uint32_t address;
2819 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2821 uint32_t value;
2822 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2824 unsigned count = 1;
2825 if (CMD_ARGC == 3)
2826 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2828 struct target *target = get_current_target(CMD_CTX);
2829 unsigned wordsize;
2830 switch (CMD_NAME[2]) {
2831 case 'w':
2832 wordsize = 4;
2833 break;
2834 case 'h':
2835 wordsize = 2;
2836 break;
2837 case 'b':
2838 wordsize = 1;
2839 break;
2840 default:
2841 return ERROR_COMMAND_SYNTAX_ERROR;
2844 return target_fill_mem(target, address, fn, wordsize, value, count);
2847 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2848 uint32_t *min_address, uint32_t *max_address)
2850 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2851 return ERROR_COMMAND_SYNTAX_ERROR;
2853 /* a base address isn't always necessary,
2854 * default to 0x0 (i.e. don't relocate) */
2855 if (CMD_ARGC >= 2) {
2856 uint32_t addr;
2857 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2858 image->base_address = addr;
2859 image->base_address_set = 1;
2860 } else
2861 image->base_address_set = 0;
2863 image->start_address_set = 0;
2865 if (CMD_ARGC >= 4)
2866 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2867 if (CMD_ARGC == 5) {
2868 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2869 /* use size (given) to find max (required) */
2870 *max_address += *min_address;
2873 if (*min_address > *max_address)
2874 return ERROR_COMMAND_SYNTAX_ERROR;
2876 return ERROR_OK;
2879 COMMAND_HANDLER(handle_load_image_command)
2881 uint8_t *buffer;
2882 size_t buf_cnt;
2883 uint32_t image_size;
2884 uint32_t min_address = 0;
2885 uint32_t max_address = 0xffffffff;
2886 int i;
2887 struct image image;
2889 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2890 &image, &min_address, &max_address);
2891 if (ERROR_OK != retval)
2892 return retval;
2894 struct target *target = get_current_target(CMD_CTX);
2896 struct duration bench;
2897 duration_start(&bench);
2899 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2900 return ERROR_OK;
2902 image_size = 0x0;
2903 retval = ERROR_OK;
2904 for (i = 0; i < image.num_sections; i++) {
2905 buffer = malloc(image.sections[i].size);
2906 if (buffer == NULL) {
2907 command_print(CMD_CTX,
2908 "error allocating buffer for section (%d bytes)",
2909 (int)(image.sections[i].size));
2910 break;
2913 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
2914 if (retval != ERROR_OK) {
2915 free(buffer);
2916 break;
2919 uint32_t offset = 0;
2920 uint32_t length = buf_cnt;
2922 /* DANGER!!! beware of unsigned comparision here!!! */
2924 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
2925 (image.sections[i].base_address < max_address)) {
2927 if (image.sections[i].base_address < min_address) {
2928 /* clip addresses below */
2929 offset += min_address-image.sections[i].base_address;
2930 length -= offset;
2933 if (image.sections[i].base_address + buf_cnt > max_address)
2934 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2936 retval = target_write_buffer(target,
2937 image.sections[i].base_address + offset, length, buffer + offset);
2938 if (retval != ERROR_OK) {
2939 free(buffer);
2940 break;
2942 image_size += length;
2943 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2944 (unsigned int)length,
2945 image.sections[i].base_address + offset);
2948 free(buffer);
2951 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
2952 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2953 "in %fs (%0.3f KiB/s)", image_size,
2954 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2957 image_close(&image);
2959 return retval;
2963 COMMAND_HANDLER(handle_dump_image_command)
2965 struct fileio fileio;
2966 uint8_t *buffer;
2967 int retval, retvaltemp;
2968 uint32_t address, size;
2969 struct duration bench;
2970 struct target *target = get_current_target(CMD_CTX);
2972 if (CMD_ARGC != 3)
2973 return ERROR_COMMAND_SYNTAX_ERROR;
2975 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2976 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2978 uint32_t buf_size = (size > 4096) ? 4096 : size;
2979 buffer = malloc(buf_size);
2980 if (!buffer)
2981 return ERROR_FAIL;
2983 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2984 if (retval != ERROR_OK) {
2985 free(buffer);
2986 return retval;
2989 duration_start(&bench);
2991 while (size > 0) {
2992 size_t size_written;
2993 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
2994 retval = target_read_buffer(target, address, this_run_size, buffer);
2995 if (retval != ERROR_OK)
2996 break;
2998 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2999 if (retval != ERROR_OK)
3000 break;
3002 size -= this_run_size;
3003 address += this_run_size;
3006 free(buffer);
3008 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3009 int filesize;
3010 retval = fileio_size(&fileio, &filesize);
3011 if (retval != ERROR_OK)
3012 return retval;
3013 command_print(CMD_CTX,
3014 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
3015 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3018 retvaltemp = fileio_close(&fileio);
3019 if (retvaltemp != ERROR_OK)
3020 return retvaltemp;
3022 return retval;
3025 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
3027 uint8_t *buffer;
3028 size_t buf_cnt;
3029 uint32_t image_size;
3030 int i;
3031 int retval;
3032 uint32_t checksum = 0;
3033 uint32_t mem_checksum = 0;
3035 struct image image;
3037 struct target *target = get_current_target(CMD_CTX);
3039 if (CMD_ARGC < 1)
3040 return ERROR_COMMAND_SYNTAX_ERROR;
3042 if (!target) {
3043 LOG_ERROR("no target selected");
3044 return ERROR_FAIL;
3047 struct duration bench;
3048 duration_start(&bench);
3050 if (CMD_ARGC >= 2) {
3051 uint32_t addr;
3052 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3053 image.base_address = addr;
3054 image.base_address_set = 1;
3055 } else {
3056 image.base_address_set = 0;
3057 image.base_address = 0x0;
3060 image.start_address_set = 0;
3062 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3063 if (retval != ERROR_OK)
3064 return retval;
3066 image_size = 0x0;
3067 int diffs = 0;
3068 retval = ERROR_OK;
3069 for (i = 0; i < image.num_sections; i++) {
3070 buffer = malloc(image.sections[i].size);
3071 if (buffer == NULL) {
3072 command_print(CMD_CTX,
3073 "error allocating buffer for section (%d bytes)",
3074 (int)(image.sections[i].size));
3075 break;
3077 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3078 if (retval != ERROR_OK) {
3079 free(buffer);
3080 break;
3083 if (verify) {
3084 /* calculate checksum of image */
3085 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3086 if (retval != ERROR_OK) {
3087 free(buffer);
3088 break;
3091 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3092 if (retval != ERROR_OK) {
3093 free(buffer);
3094 break;
3097 if (checksum != mem_checksum) {
3098 /* failed crc checksum, fall back to a binary compare */
3099 uint8_t *data;
3101 if (diffs == 0)
3102 LOG_ERROR("checksum mismatch - attempting binary compare");
3104 data = (uint8_t *)malloc(buf_cnt);
3106 /* Can we use 32bit word accesses? */
3107 int size = 1;
3108 int count = buf_cnt;
3109 if ((count % 4) == 0) {
3110 size *= 4;
3111 count /= 4;
3113 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3114 if (retval == ERROR_OK) {
3115 uint32_t t;
3116 for (t = 0; t < buf_cnt; t++) {
3117 if (data[t] != buffer[t]) {
3118 command_print(CMD_CTX,
3119 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3120 diffs,
3121 (unsigned)(t + image.sections[i].base_address),
3122 data[t],
3123 buffer[t]);
3124 if (diffs++ >= 127) {
3125 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3126 free(data);
3127 free(buffer);
3128 goto done;
3131 keep_alive();
3134 free(data);
3136 } else {
3137 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3138 image.sections[i].base_address,
3139 buf_cnt);
3142 free(buffer);
3143 image_size += buf_cnt;
3145 if (diffs > 0)
3146 command_print(CMD_CTX, "No more differences found.");
3147 done:
3148 if (diffs > 0)
3149 retval = ERROR_FAIL;
3150 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3151 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3152 "in %fs (%0.3f KiB/s)", image_size,
3153 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3156 image_close(&image);
3158 return retval;
3161 COMMAND_HANDLER(handle_verify_image_command)
3163 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3166 COMMAND_HANDLER(handle_test_image_command)
3168 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3171 static int handle_bp_command_list(struct command_context *cmd_ctx)
3173 struct target *target = get_current_target(cmd_ctx);
3174 struct breakpoint *breakpoint = target->breakpoints;
3175 while (breakpoint) {
3176 if (breakpoint->type == BKPT_SOFT) {
3177 char *buf = buf_to_str(breakpoint->orig_instr,
3178 breakpoint->length, 16);
3179 command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3180 breakpoint->address,
3181 breakpoint->length,
3182 breakpoint->set, buf);
3183 free(buf);
3184 } else {
3185 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3186 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3187 breakpoint->asid,
3188 breakpoint->length, breakpoint->set);
3189 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3190 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3191 breakpoint->address,
3192 breakpoint->length, breakpoint->set);
3193 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3194 breakpoint->asid);
3195 } else
3196 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3197 breakpoint->address,
3198 breakpoint->length, breakpoint->set);
3201 breakpoint = breakpoint->next;
3203 return ERROR_OK;
3206 static int handle_bp_command_set(struct command_context *cmd_ctx,
3207 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3209 struct target *target = get_current_target(cmd_ctx);
3211 if (asid == 0) {
3212 int retval = breakpoint_add(target, addr, length, hw);
3213 if (ERROR_OK == retval)
3214 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3215 else {
3216 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3217 return retval;
3219 } else if (addr == 0) {
3220 int retval = context_breakpoint_add(target, asid, length, hw);
3221 if (ERROR_OK == retval)
3222 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3223 else {
3224 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3225 return retval;
3227 } else {
3228 int retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3229 if (ERROR_OK == retval)
3230 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3231 else {
3232 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3233 return retval;
3236 return ERROR_OK;
3239 COMMAND_HANDLER(handle_bp_command)
3241 uint32_t addr;
3242 uint32_t asid;
3243 uint32_t length;
3244 int hw = BKPT_SOFT;
3246 switch (CMD_ARGC) {
3247 case 0:
3248 return handle_bp_command_list(CMD_CTX);
3250 case 2:
3251 asid = 0;
3252 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3253 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3254 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3256 case 3:
3257 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3258 hw = BKPT_HARD;
3259 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3261 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3263 asid = 0;
3264 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3265 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3266 hw = BKPT_HARD;
3267 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3268 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3269 addr = 0;
3270 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3273 case 4:
3274 hw = BKPT_HARD;
3275 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3276 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3277 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3278 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3280 default:
3281 return ERROR_COMMAND_SYNTAX_ERROR;
3285 COMMAND_HANDLER(handle_rbp_command)
3287 if (CMD_ARGC != 1)
3288 return ERROR_COMMAND_SYNTAX_ERROR;
3290 uint32_t addr;
3291 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3293 struct target *target = get_current_target(CMD_CTX);
3294 breakpoint_remove(target, addr);
3296 return ERROR_OK;
3299 COMMAND_HANDLER(handle_wp_command)
3301 struct target *target = get_current_target(CMD_CTX);
3303 if (CMD_ARGC == 0) {
3304 struct watchpoint *watchpoint = target->watchpoints;
3306 while (watchpoint) {
3307 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3308 ", len: 0x%8.8" PRIx32
3309 ", r/w/a: %i, value: 0x%8.8" PRIx32
3310 ", mask: 0x%8.8" PRIx32,
3311 watchpoint->address,
3312 watchpoint->length,
3313 (int)watchpoint->rw,
3314 watchpoint->value,
3315 watchpoint->mask);
3316 watchpoint = watchpoint->next;
3318 return ERROR_OK;
3321 enum watchpoint_rw type = WPT_ACCESS;
3322 uint32_t addr = 0;
3323 uint32_t length = 0;
3324 uint32_t data_value = 0x0;
3325 uint32_t data_mask = 0xffffffff;
3327 switch (CMD_ARGC) {
3328 case 5:
3329 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3330 /* fall through */
3331 case 4:
3332 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3333 /* fall through */
3334 case 3:
3335 switch (CMD_ARGV[2][0]) {
3336 case 'r':
3337 type = WPT_READ;
3338 break;
3339 case 'w':
3340 type = WPT_WRITE;
3341 break;
3342 case 'a':
3343 type = WPT_ACCESS;
3344 break;
3345 default:
3346 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3347 return ERROR_COMMAND_SYNTAX_ERROR;
3349 /* fall through */
3350 case 2:
3351 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3352 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3353 break;
3355 default:
3356 return ERROR_COMMAND_SYNTAX_ERROR;
3359 int retval = watchpoint_add(target, addr, length, type,
3360 data_value, data_mask);
3361 if (ERROR_OK != retval)
3362 LOG_ERROR("Failure setting watchpoints");
3364 return retval;
3367 COMMAND_HANDLER(handle_rwp_command)
3369 if (CMD_ARGC != 1)
3370 return ERROR_COMMAND_SYNTAX_ERROR;
3372 uint32_t addr;
3373 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3375 struct target *target = get_current_target(CMD_CTX);
3376 watchpoint_remove(target, addr);
3378 return ERROR_OK;
3382 * Translate a virtual address to a physical address.
3384 * The low-level target implementation must have logged a detailed error
3385 * which is forwarded to telnet/GDB session.
3387 COMMAND_HANDLER(handle_virt2phys_command)
3389 if (CMD_ARGC != 1)
3390 return ERROR_COMMAND_SYNTAX_ERROR;
3392 uint32_t va;
3393 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3394 uint32_t pa;
3396 struct target *target = get_current_target(CMD_CTX);
3397 int retval = target->type->virt2phys(target, va, &pa);
3398 if (retval == ERROR_OK)
3399 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3401 return retval;
3404 static void writeData(FILE *f, const void *data, size_t len)
3406 size_t written = fwrite(data, 1, len, f);
3407 if (written != len)
3408 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3411 static void writeLong(FILE *f, int l)
3413 int i;
3414 for (i = 0; i < 4; i++) {
3415 char c = (l >> (i*8))&0xff;
3416 writeData(f, &c, 1);
3421 static void writeString(FILE *f, char *s)
3423 writeData(f, s, strlen(s));
3426 typedef unsigned char UNIT[2]; /* unit of profiling */
3428 /* Dump a gmon.out histogram file. */
3429 static void write_gmon(uint32_t *samples, uint32_t sampleNum, const char *filename,
3430 bool with_range, uint32_t start_address, uint32_t end_address)
3432 uint32_t i;
3433 FILE *f = fopen(filename, "w");
3434 if (f == NULL)
3435 return;
3436 writeString(f, "gmon");
3437 writeLong(f, 0x00000001); /* Version */
3438 writeLong(f, 0); /* padding */
3439 writeLong(f, 0); /* padding */
3440 writeLong(f, 0); /* padding */
3442 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3443 writeData(f, &zero, 1);
3445 /* figure out bucket size */
3446 uint32_t min;
3447 uint32_t max;
3448 if (with_range) {
3449 min = start_address;
3450 max = end_address;
3451 } else {
3452 min = samples[0];
3453 max = samples[0];
3454 for (i = 0; i < sampleNum; i++) {
3455 if (min > samples[i])
3456 min = samples[i];
3457 if (max < samples[i])
3458 max = samples[i];
3461 /* max should be (largest sample + 1)
3462 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
3463 max++;
3466 int addressSpace = max - min;
3467 assert(addressSpace >= 2);
3469 /* FIXME: What is the reasonable number of buckets?
3470 * The profiling result will be more accurate if there are enough buckets. */
3471 static const uint32_t maxBuckets = 128 * 1024; /* maximum buckets. */
3472 uint32_t numBuckets = addressSpace / sizeof(UNIT);
3473 if (numBuckets > maxBuckets)
3474 numBuckets = maxBuckets;
3475 int *buckets = malloc(sizeof(int) * numBuckets);
3476 if (buckets == NULL) {
3477 fclose(f);
3478 return;
3480 memset(buckets, 0, sizeof(int) * numBuckets);
3481 for (i = 0; i < sampleNum; i++) {
3482 uint32_t address = samples[i];
3484 if ((address < min) || (max <= address))
3485 continue;
3487 long long a = address - min;
3488 long long b = numBuckets;
3489 long long c = addressSpace;
3490 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3491 buckets[index_t]++;
3494 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3495 writeLong(f, min); /* low_pc */
3496 writeLong(f, max); /* high_pc */
3497 writeLong(f, numBuckets); /* # of buckets */
3498 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3499 writeString(f, "seconds");
3500 for (i = 0; i < (15-strlen("seconds")); i++)
3501 writeData(f, &zero, 1);
3502 writeString(f, "s");
3504 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3506 char *data = malloc(2 * numBuckets);
3507 if (data != NULL) {
3508 for (i = 0; i < numBuckets; i++) {
3509 int val;
3510 val = buckets[i];
3511 if (val > 65535)
3512 val = 65535;
3513 data[i * 2] = val&0xff;
3514 data[i * 2 + 1] = (val >> 8) & 0xff;
3516 free(buckets);
3517 writeData(f, data, numBuckets * 2);
3518 free(data);
3519 } else
3520 free(buckets);
3522 fclose(f);
3525 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3526 * which will be used as a random sampling of PC */
3527 COMMAND_HANDLER(handle_profile_command)
3529 struct target *target = get_current_target(CMD_CTX);
3531 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
3532 return ERROR_COMMAND_SYNTAX_ERROR;
3534 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
3535 uint32_t offset;
3536 uint32_t num_of_sampels;
3537 int retval = ERROR_OK;
3538 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
3539 if (samples == NULL) {
3540 LOG_ERROR("No memory to store samples.");
3541 return ERROR_FAIL;
3544 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3547 * Some cores let us sample the PC without the
3548 * annoying halt/resume step; for example, ARMv7 PCSR.
3549 * Provide a way to use that more efficient mechanism.
3551 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
3552 &num_of_sampels, offset);
3553 if (retval != ERROR_OK) {
3554 free(samples);
3555 return retval;
3558 assert(num_of_sampels <= MAX_PROFILE_SAMPLE_NUM);
3560 retval = target_poll(target);
3561 if (retval != ERROR_OK) {
3562 free(samples);
3563 return retval;
3565 if (target->state == TARGET_RUNNING) {
3566 retval = target_halt(target);
3567 if (retval != ERROR_OK) {
3568 free(samples);
3569 return retval;
3573 retval = target_poll(target);
3574 if (retval != ERROR_OK) {
3575 free(samples);
3576 return retval;
3579 uint32_t start_address = 0;
3580 uint32_t end_address = 0;
3581 bool with_range = false;
3582 if (CMD_ARGC == 4) {
3583 with_range = true;
3584 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], start_address);
3585 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[3], end_address);
3588 write_gmon(samples, num_of_sampels, CMD_ARGV[1],
3589 with_range, start_address, end_address);
3590 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3592 free(samples);
3593 return retval;
3596 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3598 char *namebuf;
3599 Jim_Obj *nameObjPtr, *valObjPtr;
3600 int result;
3602 namebuf = alloc_printf("%s(%d)", varname, idx);
3603 if (!namebuf)
3604 return JIM_ERR;
3606 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3607 valObjPtr = Jim_NewIntObj(interp, val);
3608 if (!nameObjPtr || !valObjPtr) {
3609 free(namebuf);
3610 return JIM_ERR;
3613 Jim_IncrRefCount(nameObjPtr);
3614 Jim_IncrRefCount(valObjPtr);
3615 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3616 Jim_DecrRefCount(interp, nameObjPtr);
3617 Jim_DecrRefCount(interp, valObjPtr);
3618 free(namebuf);
3619 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3620 return result;
3623 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3625 struct command_context *context;
3626 struct target *target;
3628 context = current_command_context(interp);
3629 assert(context != NULL);
3631 target = get_current_target(context);
3632 if (target == NULL) {
3633 LOG_ERROR("mem2array: no current target");
3634 return JIM_ERR;
3637 return target_mem2array(interp, target, argc - 1, argv + 1);
3640 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3642 long l;
3643 uint32_t width;
3644 int len;
3645 uint32_t addr;
3646 uint32_t count;
3647 uint32_t v;
3648 const char *varname;
3649 int n, e, retval;
3650 uint32_t i;
3652 /* argv[1] = name of array to receive the data
3653 * argv[2] = desired width
3654 * argv[3] = memory address
3655 * argv[4] = count of times to read
3657 if (argc != 4) {
3658 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3659 return JIM_ERR;
3661 varname = Jim_GetString(argv[0], &len);
3662 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3664 e = Jim_GetLong(interp, argv[1], &l);
3665 width = l;
3666 if (e != JIM_OK)
3667 return e;
3669 e = Jim_GetLong(interp, argv[2], &l);
3670 addr = l;
3671 if (e != JIM_OK)
3672 return e;
3673 e = Jim_GetLong(interp, argv[3], &l);
3674 len = l;
3675 if (e != JIM_OK)
3676 return e;
3677 switch (width) {
3678 case 8:
3679 width = 1;
3680 break;
3681 case 16:
3682 width = 2;
3683 break;
3684 case 32:
3685 width = 4;
3686 break;
3687 default:
3688 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3689 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3690 return JIM_ERR;
3692 if (len == 0) {
3693 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3694 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3695 return JIM_ERR;
3697 if ((addr + (len * width)) < addr) {
3698 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3699 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3700 return JIM_ERR;
3702 /* absurd transfer size? */
3703 if (len > 65536) {
3704 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3705 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3706 return JIM_ERR;
3709 if ((width == 1) ||
3710 ((width == 2) && ((addr & 1) == 0)) ||
3711 ((width == 4) && ((addr & 3) == 0))) {
3712 /* all is well */
3713 } else {
3714 char buf[100];
3715 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3716 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3717 addr,
3718 width);
3719 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3720 return JIM_ERR;
3723 /* Transfer loop */
3725 /* index counter */
3726 n = 0;
3728 size_t buffersize = 4096;
3729 uint8_t *buffer = malloc(buffersize);
3730 if (buffer == NULL)
3731 return JIM_ERR;
3733 /* assume ok */
3734 e = JIM_OK;
3735 while (len) {
3736 /* Slurp... in buffer size chunks */
3738 count = len; /* in objects.. */
3739 if (count > (buffersize / width))
3740 count = (buffersize / width);
3742 retval = target_read_memory(target, addr, width, count, buffer);
3743 if (retval != ERROR_OK) {
3744 /* BOO !*/
3745 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3746 (unsigned int)addr,
3747 (int)width,
3748 (int)count);
3749 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3750 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3751 e = JIM_ERR;
3752 break;
3753 } else {
3754 v = 0; /* shut up gcc */
3755 for (i = 0; i < count ; i++, n++) {
3756 switch (width) {
3757 case 4:
3758 v = target_buffer_get_u32(target, &buffer[i*width]);
3759 break;
3760 case 2:
3761 v = target_buffer_get_u16(target, &buffer[i*width]);
3762 break;
3763 case 1:
3764 v = buffer[i] & 0x0ff;
3765 break;
3767 new_int_array_element(interp, varname, n, v);
3769 len -= count;
3773 free(buffer);
3775 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3777 return e;
3780 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
3782 char *namebuf;
3783 Jim_Obj *nameObjPtr, *valObjPtr;
3784 int result;
3785 long l;
3787 namebuf = alloc_printf("%s(%d)", varname, idx);
3788 if (!namebuf)
3789 return JIM_ERR;
3791 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3792 if (!nameObjPtr) {
3793 free(namebuf);
3794 return JIM_ERR;
3797 Jim_IncrRefCount(nameObjPtr);
3798 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3799 Jim_DecrRefCount(interp, nameObjPtr);
3800 free(namebuf);
3801 if (valObjPtr == NULL)
3802 return JIM_ERR;
3804 result = Jim_GetLong(interp, valObjPtr, &l);
3805 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3806 *val = l;
3807 return result;
3810 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3812 struct command_context *context;
3813 struct target *target;
3815 context = current_command_context(interp);
3816 assert(context != NULL);
3818 target = get_current_target(context);
3819 if (target == NULL) {
3820 LOG_ERROR("array2mem: no current target");
3821 return JIM_ERR;
3824 return target_array2mem(interp, target, argc-1, argv + 1);
3827 static int target_array2mem(Jim_Interp *interp, struct target *target,
3828 int argc, Jim_Obj *const *argv)
3830 long l;
3831 uint32_t width;
3832 int len;
3833 uint32_t addr;
3834 uint32_t count;
3835 uint32_t v;
3836 const char *varname;
3837 int n, e, retval;
3838 uint32_t i;
3840 /* argv[1] = name of array to get the data
3841 * argv[2] = desired width
3842 * argv[3] = memory address
3843 * argv[4] = count to write
3845 if (argc != 4) {
3846 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3847 return JIM_ERR;
3849 varname = Jim_GetString(argv[0], &len);
3850 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3852 e = Jim_GetLong(interp, argv[1], &l);
3853 width = l;
3854 if (e != JIM_OK)
3855 return e;
3857 e = Jim_GetLong(interp, argv[2], &l);
3858 addr = l;
3859 if (e != JIM_OK)
3860 return e;
3861 e = Jim_GetLong(interp, argv[3], &l);
3862 len = l;
3863 if (e != JIM_OK)
3864 return e;
3865 switch (width) {
3866 case 8:
3867 width = 1;
3868 break;
3869 case 16:
3870 width = 2;
3871 break;
3872 case 32:
3873 width = 4;
3874 break;
3875 default:
3876 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3877 Jim_AppendStrings(interp, Jim_GetResult(interp),
3878 "Invalid width param, must be 8/16/32", NULL);
3879 return JIM_ERR;
3881 if (len == 0) {
3882 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3883 Jim_AppendStrings(interp, Jim_GetResult(interp),
3884 "array2mem: zero width read?", NULL);
3885 return JIM_ERR;
3887 if ((addr + (len * width)) < addr) {
3888 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3889 Jim_AppendStrings(interp, Jim_GetResult(interp),
3890 "array2mem: addr + len - wraps to zero?", NULL);
3891 return JIM_ERR;
3893 /* absurd transfer size? */
3894 if (len > 65536) {
3895 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3896 Jim_AppendStrings(interp, Jim_GetResult(interp),
3897 "array2mem: absurd > 64K item request", NULL);
3898 return JIM_ERR;
3901 if ((width == 1) ||
3902 ((width == 2) && ((addr & 1) == 0)) ||
3903 ((width == 4) && ((addr & 3) == 0))) {
3904 /* all is well */
3905 } else {
3906 char buf[100];
3907 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3908 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3909 (unsigned int)addr,
3910 (int)width);
3911 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3912 return JIM_ERR;
3915 /* Transfer loop */
3917 /* index counter */
3918 n = 0;
3919 /* assume ok */
3920 e = JIM_OK;
3922 size_t buffersize = 4096;
3923 uint8_t *buffer = malloc(buffersize);
3924 if (buffer == NULL)
3925 return JIM_ERR;
3927 while (len) {
3928 /* Slurp... in buffer size chunks */
3930 count = len; /* in objects.. */
3931 if (count > (buffersize / width))
3932 count = (buffersize / width);
3934 v = 0; /* shut up gcc */
3935 for (i = 0; i < count; i++, n++) {
3936 get_int_array_element(interp, varname, n, &v);
3937 switch (width) {
3938 case 4:
3939 target_buffer_set_u32(target, &buffer[i * width], v);
3940 break;
3941 case 2:
3942 target_buffer_set_u16(target, &buffer[i * width], v);
3943 break;
3944 case 1:
3945 buffer[i] = v & 0x0ff;
3946 break;
3949 len -= count;
3951 retval = target_write_memory(target, addr, width, count, buffer);
3952 if (retval != ERROR_OK) {
3953 /* BOO !*/
3954 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3955 (unsigned int)addr,
3956 (int)width,
3957 (int)count);
3958 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3959 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3960 e = JIM_ERR;
3961 break;
3965 free(buffer);
3967 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3969 return e;
3972 /* FIX? should we propagate errors here rather than printing them
3973 * and continuing?
3975 void target_handle_event(struct target *target, enum target_event e)
3977 struct target_event_action *teap;
3979 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3980 if (teap->event == e) {
3981 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3982 target->target_number,
3983 target_name(target),
3984 target_type_name(target),
3986 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3987 Jim_GetString(teap->body, NULL));
3988 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
3989 Jim_MakeErrorMessage(teap->interp);
3990 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
3997 * Returns true only if the target has a handler for the specified event.
3999 bool target_has_event_action(struct target *target, enum target_event event)
4001 struct target_event_action *teap;
4003 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4004 if (teap->event == event)
4005 return true;
4007 return false;
4010 enum target_cfg_param {
4011 TCFG_TYPE,
4012 TCFG_EVENT,
4013 TCFG_WORK_AREA_VIRT,
4014 TCFG_WORK_AREA_PHYS,
4015 TCFG_WORK_AREA_SIZE,
4016 TCFG_WORK_AREA_BACKUP,
4017 TCFG_ENDIAN,
4018 TCFG_VARIANT,
4019 TCFG_COREID,
4020 TCFG_CHAIN_POSITION,
4021 TCFG_DBGBASE,
4022 TCFG_RTOS,
4025 static Jim_Nvp nvp_config_opts[] = {
4026 { .name = "-type", .value = TCFG_TYPE },
4027 { .name = "-event", .value = TCFG_EVENT },
4028 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4029 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4030 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4031 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4032 { .name = "-endian" , .value = TCFG_ENDIAN },
4033 { .name = "-variant", .value = TCFG_VARIANT },
4034 { .name = "-coreid", .value = TCFG_COREID },
4035 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4036 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4037 { .name = "-rtos", .value = TCFG_RTOS },
4038 { .name = NULL, .value = -1 }
4041 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
4043 Jim_Nvp *n;
4044 Jim_Obj *o;
4045 jim_wide w;
4046 char *cp;
4047 int e;
4049 /* parse config or cget options ... */
4050 while (goi->argc > 0) {
4051 Jim_SetEmptyResult(goi->interp);
4052 /* Jim_GetOpt_Debug(goi); */
4054 if (target->type->target_jim_configure) {
4055 /* target defines a configure function */
4056 /* target gets first dibs on parameters */
4057 e = (*(target->type->target_jim_configure))(target, goi);
4058 if (e == JIM_OK) {
4059 /* more? */
4060 continue;
4062 if (e == JIM_ERR) {
4063 /* An error */
4064 return e;
4066 /* otherwise we 'continue' below */
4068 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
4069 if (e != JIM_OK) {
4070 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
4071 return e;
4073 switch (n->value) {
4074 case TCFG_TYPE:
4075 /* not setable */
4076 if (goi->isconfigure) {
4077 Jim_SetResultFormatted(goi->interp,
4078 "not settable: %s", n->name);
4079 return JIM_ERR;
4080 } else {
4081 no_params:
4082 if (goi->argc != 0) {
4083 Jim_WrongNumArgs(goi->interp,
4084 goi->argc, goi->argv,
4085 "NO PARAMS");
4086 return JIM_ERR;
4089 Jim_SetResultString(goi->interp,
4090 target_type_name(target), -1);
4091 /* loop for more */
4092 break;
4093 case TCFG_EVENT:
4094 if (goi->argc == 0) {
4095 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4096 return JIM_ERR;
4099 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4100 if (e != JIM_OK) {
4101 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4102 return e;
4105 if (goi->isconfigure) {
4106 if (goi->argc != 1) {
4107 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4108 return JIM_ERR;
4110 } else {
4111 if (goi->argc != 0) {
4112 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4113 return JIM_ERR;
4118 struct target_event_action *teap;
4120 teap = target->event_action;
4121 /* replace existing? */
4122 while (teap) {
4123 if (teap->event == (enum target_event)n->value)
4124 break;
4125 teap = teap->next;
4128 if (goi->isconfigure) {
4129 bool replace = true;
4130 if (teap == NULL) {
4131 /* create new */
4132 teap = calloc(1, sizeof(*teap));
4133 replace = false;
4135 teap->event = n->value;
4136 teap->interp = goi->interp;
4137 Jim_GetOpt_Obj(goi, &o);
4138 if (teap->body)
4139 Jim_DecrRefCount(teap->interp, teap->body);
4140 teap->body = Jim_DuplicateObj(goi->interp, o);
4142 * FIXME:
4143 * Tcl/TK - "tk events" have a nice feature.
4144 * See the "BIND" command.
4145 * We should support that here.
4146 * You can specify %X and %Y in the event code.
4147 * The idea is: %T - target name.
4148 * The idea is: %N - target number
4149 * The idea is: %E - event name.
4151 Jim_IncrRefCount(teap->body);
4153 if (!replace) {
4154 /* add to head of event list */
4155 teap->next = target->event_action;
4156 target->event_action = teap;
4158 Jim_SetEmptyResult(goi->interp);
4159 } else {
4160 /* get */
4161 if (teap == NULL)
4162 Jim_SetEmptyResult(goi->interp);
4163 else
4164 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4167 /* loop for more */
4168 break;
4170 case TCFG_WORK_AREA_VIRT:
4171 if (goi->isconfigure) {
4172 target_free_all_working_areas(target);
4173 e = Jim_GetOpt_Wide(goi, &w);
4174 if (e != JIM_OK)
4175 return e;
4176 target->working_area_virt = w;
4177 target->working_area_virt_spec = true;
4178 } else {
4179 if (goi->argc != 0)
4180 goto no_params;
4182 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4183 /* loop for more */
4184 break;
4186 case TCFG_WORK_AREA_PHYS:
4187 if (goi->isconfigure) {
4188 target_free_all_working_areas(target);
4189 e = Jim_GetOpt_Wide(goi, &w);
4190 if (e != JIM_OK)
4191 return e;
4192 target->working_area_phys = w;
4193 target->working_area_phys_spec = true;
4194 } else {
4195 if (goi->argc != 0)
4196 goto no_params;
4198 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4199 /* loop for more */
4200 break;
4202 case TCFG_WORK_AREA_SIZE:
4203 if (goi->isconfigure) {
4204 target_free_all_working_areas(target);
4205 e = Jim_GetOpt_Wide(goi, &w);
4206 if (e != JIM_OK)
4207 return e;
4208 target->working_area_size = w;
4209 } else {
4210 if (goi->argc != 0)
4211 goto no_params;
4213 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4214 /* loop for more */
4215 break;
4217 case TCFG_WORK_AREA_BACKUP:
4218 if (goi->isconfigure) {
4219 target_free_all_working_areas(target);
4220 e = Jim_GetOpt_Wide(goi, &w);
4221 if (e != JIM_OK)
4222 return e;
4223 /* make this exactly 1 or 0 */
4224 target->backup_working_area = (!!w);
4225 } else {
4226 if (goi->argc != 0)
4227 goto no_params;
4229 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4230 /* loop for more e*/
4231 break;
4234 case TCFG_ENDIAN:
4235 if (goi->isconfigure) {
4236 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4237 if (e != JIM_OK) {
4238 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4239 return e;
4241 target->endianness = n->value;
4242 } else {
4243 if (goi->argc != 0)
4244 goto no_params;
4246 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4247 if (n->name == NULL) {
4248 target->endianness = TARGET_LITTLE_ENDIAN;
4249 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4251 Jim_SetResultString(goi->interp, n->name, -1);
4252 /* loop for more */
4253 break;
4255 case TCFG_VARIANT:
4256 if (goi->isconfigure) {
4257 if (goi->argc < 1) {
4258 Jim_SetResultFormatted(goi->interp,
4259 "%s ?STRING?",
4260 n->name);
4261 return JIM_ERR;
4263 if (target->variant)
4264 free((void *)(target->variant));
4265 e = Jim_GetOpt_String(goi, &cp, NULL);
4266 if (e != JIM_OK)
4267 return e;
4268 target->variant = strdup(cp);
4269 } else {
4270 if (goi->argc != 0)
4271 goto no_params;
4273 Jim_SetResultString(goi->interp, target->variant, -1);
4274 /* loop for more */
4275 break;
4277 case TCFG_COREID:
4278 if (goi->isconfigure) {
4279 e = Jim_GetOpt_Wide(goi, &w);
4280 if (e != JIM_OK)
4281 return e;
4282 target->coreid = (int32_t)w;
4283 } else {
4284 if (goi->argc != 0)
4285 goto no_params;
4287 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4288 /* loop for more */
4289 break;
4291 case TCFG_CHAIN_POSITION:
4292 if (goi->isconfigure) {
4293 Jim_Obj *o_t;
4294 struct jtag_tap *tap;
4295 target_free_all_working_areas(target);
4296 e = Jim_GetOpt_Obj(goi, &o_t);
4297 if (e != JIM_OK)
4298 return e;
4299 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4300 if (tap == NULL)
4301 return JIM_ERR;
4302 /* make this exactly 1 or 0 */
4303 target->tap = tap;
4304 } else {
4305 if (goi->argc != 0)
4306 goto no_params;
4308 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4309 /* loop for more e*/
4310 break;
4311 case TCFG_DBGBASE:
4312 if (goi->isconfigure) {
4313 e = Jim_GetOpt_Wide(goi, &w);
4314 if (e != JIM_OK)
4315 return e;
4316 target->dbgbase = (uint32_t)w;
4317 target->dbgbase_set = true;
4318 } else {
4319 if (goi->argc != 0)
4320 goto no_params;
4322 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4323 /* loop for more */
4324 break;
4326 case TCFG_RTOS:
4327 /* RTOS */
4329 int result = rtos_create(goi, target);
4330 if (result != JIM_OK)
4331 return result;
4333 /* loop for more */
4334 break;
4336 } /* while (goi->argc) */
4339 /* done - we return */
4340 return JIM_OK;
4343 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4345 Jim_GetOptInfo goi;
4347 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4348 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4349 int need_args = 1 + goi.isconfigure;
4350 if (goi.argc < need_args) {
4351 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4352 goi.isconfigure
4353 ? "missing: -option VALUE ..."
4354 : "missing: -option ...");
4355 return JIM_ERR;
4357 struct target *target = Jim_CmdPrivData(goi.interp);
4358 return target_configure(&goi, target);
4361 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4363 const char *cmd_name = Jim_GetString(argv[0], NULL);
4365 Jim_GetOptInfo goi;
4366 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4368 if (goi.argc < 2 || goi.argc > 4) {
4369 Jim_SetResultFormatted(goi.interp,
4370 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4371 return JIM_ERR;
4374 target_write_fn fn;
4375 fn = target_write_memory;
4377 int e;
4378 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4379 /* consume it */
4380 struct Jim_Obj *obj;
4381 e = Jim_GetOpt_Obj(&goi, &obj);
4382 if (e != JIM_OK)
4383 return e;
4385 fn = target_write_phys_memory;
4388 jim_wide a;
4389 e = Jim_GetOpt_Wide(&goi, &a);
4390 if (e != JIM_OK)
4391 return e;
4393 jim_wide b;
4394 e = Jim_GetOpt_Wide(&goi, &b);
4395 if (e != JIM_OK)
4396 return e;
4398 jim_wide c = 1;
4399 if (goi.argc == 1) {
4400 e = Jim_GetOpt_Wide(&goi, &c);
4401 if (e != JIM_OK)
4402 return e;
4405 /* all args must be consumed */
4406 if (goi.argc != 0)
4407 return JIM_ERR;
4409 struct target *target = Jim_CmdPrivData(goi.interp);
4410 unsigned data_size;
4411 if (strcasecmp(cmd_name, "mww") == 0)
4412 data_size = 4;
4413 else if (strcasecmp(cmd_name, "mwh") == 0)
4414 data_size = 2;
4415 else if (strcasecmp(cmd_name, "mwb") == 0)
4416 data_size = 1;
4417 else {
4418 LOG_ERROR("command '%s' unknown: ", cmd_name);
4419 return JIM_ERR;
4422 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4426 * @brief Reads an array of words/halfwords/bytes from target memory starting at specified address.
4428 * Usage: mdw [phys] <address> [<count>] - for 32 bit reads
4429 * mdh [phys] <address> [<count>] - for 16 bit reads
4430 * mdb [phys] <address> [<count>] - for 8 bit reads
4432 * Count defaults to 1.
4434 * Calls target_read_memory or target_read_phys_memory depending on
4435 * the presence of the "phys" argument
4436 * Reads the target memory in blocks of max. 32 bytes, and returns an array of ints formatted
4437 * to int representation in base16.
4438 * Also outputs read data in a human readable form using command_print
4440 * @param phys if present target_read_phys_memory will be used instead of target_read_memory
4441 * @param address address where to start the read. May be specified in decimal or hex using the standard "0x" prefix
4442 * @param count optional count parameter to read an array of values. If not specified, defaults to 1.
4443 * @returns: JIM_ERR on error or JIM_OK on success and sets the result string to an array of ascii formatted numbers
4444 * on success, with [<count>] number of elements.
4446 * In case of little endian target:
4447 * Example1: "mdw 0x00000000" returns "10123456"
4448 * Exmaple2: "mdh 0x00000000 1" returns "3456"
4449 * Example3: "mdb 0x00000000" returns "56"
4450 * Example4: "mdh 0x00000000 2" returns "3456 1012"
4451 * Example5: "mdb 0x00000000 3" returns "56 34 12"
4453 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4455 const char *cmd_name = Jim_GetString(argv[0], NULL);
4457 Jim_GetOptInfo goi;
4458 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4460 if ((goi.argc < 1) || (goi.argc > 3)) {
4461 Jim_SetResultFormatted(goi.interp,
4462 "usage: %s [phys] <address> [<count>]", cmd_name);
4463 return JIM_ERR;
4466 int (*fn)(struct target *target,
4467 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4468 fn = target_read_memory;
4470 int e;
4471 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4472 /* consume it */
4473 struct Jim_Obj *obj;
4474 e = Jim_GetOpt_Obj(&goi, &obj);
4475 if (e != JIM_OK)
4476 return e;
4478 fn = target_read_phys_memory;
4481 /* Read address parameter */
4482 jim_wide addr;
4483 e = Jim_GetOpt_Wide(&goi, &addr);
4484 if (e != JIM_OK)
4485 return JIM_ERR;
4487 /* If next parameter exists, read it out as the count parameter, if not, set it to 1 (default) */
4488 jim_wide count;
4489 if (goi.argc == 1) {
4490 e = Jim_GetOpt_Wide(&goi, &count);
4491 if (e != JIM_OK)
4492 return JIM_ERR;
4493 } else
4494 count = 1;
4496 /* all args must be consumed */
4497 if (goi.argc != 0)
4498 return JIM_ERR;
4500 jim_wide dwidth = 1; /* shut up gcc */
4501 if (strcasecmp(cmd_name, "mdw") == 0)
4502 dwidth = 4;
4503 else if (strcasecmp(cmd_name, "mdh") == 0)
4504 dwidth = 2;
4505 else if (strcasecmp(cmd_name, "mdb") == 0)
4506 dwidth = 1;
4507 else {
4508 LOG_ERROR("command '%s' unknown: ", cmd_name);
4509 return JIM_ERR;
4512 /* convert count to "bytes" */
4513 int bytes = count * dwidth;
4515 struct target *target = Jim_CmdPrivData(goi.interp);
4516 uint8_t target_buf[32];
4517 jim_wide x, y, z;
4518 while (bytes > 0) {
4519 y = (bytes < 16) ? bytes : 16; /* y = min(bytes, 16); */
4521 /* Try to read out next block */
4522 e = fn(target, addr, dwidth, y / dwidth, target_buf);
4524 if (e != ERROR_OK) {
4525 Jim_SetResultFormatted(interp, "error reading target @ 0x%08lx", (long)addr);
4526 return JIM_ERR;
4529 command_print_sameline(NULL, "0x%08x ", (int)(addr));
4530 switch (dwidth) {
4531 case 4:
4532 for (x = 0; x < 16 && x < y; x += 4) {
4533 z = target_buffer_get_u32(target, &(target_buf[x]));
4534 command_print_sameline(NULL, "%08x ", (int)(z));
4536 for (; (x < 16) ; x += 4)
4537 command_print_sameline(NULL, " ");
4538 break;
4539 case 2:
4540 for (x = 0; x < 16 && x < y; x += 2) {
4541 z = target_buffer_get_u16(target, &(target_buf[x]));
4542 command_print_sameline(NULL, "%04x ", (int)(z));
4544 for (; (x < 16) ; x += 2)
4545 command_print_sameline(NULL, " ");
4546 break;
4547 case 1:
4548 default:
4549 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4550 z = target_buffer_get_u8(target, &(target_buf[x]));
4551 command_print_sameline(NULL, "%02x ", (int)(z));
4553 for (; (x < 16) ; x += 1)
4554 command_print_sameline(NULL, " ");
4555 break;
4557 /* ascii-ify the bytes */
4558 for (x = 0 ; x < y ; x++) {
4559 if ((target_buf[x] >= 0x20) &&
4560 (target_buf[x] <= 0x7e)) {
4561 /* good */
4562 } else {
4563 /* smack it */
4564 target_buf[x] = '.';
4567 /* space pad */
4568 while (x < 16) {
4569 target_buf[x] = ' ';
4570 x++;
4572 /* terminate */
4573 target_buf[16] = 0;
4574 /* print - with a newline */
4575 command_print_sameline(NULL, "%s\n", target_buf);
4576 /* NEXT... */
4577 bytes -= 16;
4578 addr += 16;
4580 return JIM_OK;
4583 static int jim_target_mem2array(Jim_Interp *interp,
4584 int argc, Jim_Obj *const *argv)
4586 struct target *target = Jim_CmdPrivData(interp);
4587 return target_mem2array(interp, target, argc - 1, argv + 1);
4590 static int jim_target_array2mem(Jim_Interp *interp,
4591 int argc, Jim_Obj *const *argv)
4593 struct target *target = Jim_CmdPrivData(interp);
4594 return target_array2mem(interp, target, argc - 1, argv + 1);
4597 static int jim_target_tap_disabled(Jim_Interp *interp)
4599 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4600 return JIM_ERR;
4603 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4605 if (argc != 1) {
4606 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4607 return JIM_ERR;
4609 struct target *target = Jim_CmdPrivData(interp);
4610 if (!target->tap->enabled)
4611 return jim_target_tap_disabled(interp);
4613 int e = target->type->examine(target);
4614 if (e != ERROR_OK)
4615 return JIM_ERR;
4616 return JIM_OK;
4619 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4621 if (argc != 1) {
4622 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4623 return JIM_ERR;
4625 struct target *target = Jim_CmdPrivData(interp);
4627 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4628 return JIM_ERR;
4630 return JIM_OK;
4633 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4635 if (argc != 1) {
4636 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4637 return JIM_ERR;
4639 struct target *target = Jim_CmdPrivData(interp);
4640 if (!target->tap->enabled)
4641 return jim_target_tap_disabled(interp);
4643 int e;
4644 if (!(target_was_examined(target)))
4645 e = ERROR_TARGET_NOT_EXAMINED;
4646 else
4647 e = target->type->poll(target);
4648 if (e != ERROR_OK)
4649 return JIM_ERR;
4650 return JIM_OK;
4653 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4655 Jim_GetOptInfo goi;
4656 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4658 if (goi.argc != 2) {
4659 Jim_WrongNumArgs(interp, 0, argv,
4660 "([tT]|[fF]|assert|deassert) BOOL");
4661 return JIM_ERR;
4664 Jim_Nvp *n;
4665 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4666 if (e != JIM_OK) {
4667 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4668 return e;
4670 /* the halt or not param */
4671 jim_wide a;
4672 e = Jim_GetOpt_Wide(&goi, &a);
4673 if (e != JIM_OK)
4674 return e;
4676 struct target *target = Jim_CmdPrivData(goi.interp);
4677 if (!target->tap->enabled)
4678 return jim_target_tap_disabled(interp);
4679 if (!(target_was_examined(target))) {
4680 LOG_ERROR("Target not examined yet");
4681 return ERROR_TARGET_NOT_EXAMINED;
4683 if (!target->type->assert_reset || !target->type->deassert_reset) {
4684 Jim_SetResultFormatted(interp,
4685 "No target-specific reset for %s",
4686 target_name(target));
4687 return JIM_ERR;
4689 /* determine if we should halt or not. */
4690 target->reset_halt = !!a;
4691 /* When this happens - all workareas are invalid. */
4692 target_free_all_working_areas_restore(target, 0);
4694 /* do the assert */
4695 if (n->value == NVP_ASSERT)
4696 e = target->type->assert_reset(target);
4697 else
4698 e = target->type->deassert_reset(target);
4699 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4702 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4704 if (argc != 1) {
4705 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4706 return JIM_ERR;
4708 struct target *target = Jim_CmdPrivData(interp);
4709 if (!target->tap->enabled)
4710 return jim_target_tap_disabled(interp);
4711 int e = target->type->halt(target);
4712 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4715 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4717 Jim_GetOptInfo goi;
4718 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4720 /* params: <name> statename timeoutmsecs */
4721 if (goi.argc != 2) {
4722 const char *cmd_name = Jim_GetString(argv[0], NULL);
4723 Jim_SetResultFormatted(goi.interp,
4724 "%s <state_name> <timeout_in_msec>", cmd_name);
4725 return JIM_ERR;
4728 Jim_Nvp *n;
4729 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4730 if (e != JIM_OK) {
4731 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
4732 return e;
4734 jim_wide a;
4735 e = Jim_GetOpt_Wide(&goi, &a);
4736 if (e != JIM_OK)
4737 return e;
4738 struct target *target = Jim_CmdPrivData(interp);
4739 if (!target->tap->enabled)
4740 return jim_target_tap_disabled(interp);
4742 e = target_wait_state(target, n->value, a);
4743 if (e != ERROR_OK) {
4744 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4745 Jim_SetResultFormatted(goi.interp,
4746 "target: %s wait %s fails (%#s) %s",
4747 target_name(target), n->name,
4748 eObj, target_strerror_safe(e));
4749 Jim_FreeNewObj(interp, eObj);
4750 return JIM_ERR;
4752 return JIM_OK;
4754 /* List for human, Events defined for this target.
4755 * scripts/programs should use 'name cget -event NAME'
4757 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4759 struct command_context *cmd_ctx = current_command_context(interp);
4760 assert(cmd_ctx != NULL);
4762 struct target *target = Jim_CmdPrivData(interp);
4763 struct target_event_action *teap = target->event_action;
4764 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4765 target->target_number,
4766 target_name(target));
4767 command_print(cmd_ctx, "%-25s | Body", "Event");
4768 command_print(cmd_ctx, "------------------------- | "
4769 "----------------------------------------");
4770 while (teap) {
4771 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4772 command_print(cmd_ctx, "%-25s | %s",
4773 opt->name, Jim_GetString(teap->body, NULL));
4774 teap = teap->next;
4776 command_print(cmd_ctx, "***END***");
4777 return JIM_OK;
4779 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4781 if (argc != 1) {
4782 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4783 return JIM_ERR;
4785 struct target *target = Jim_CmdPrivData(interp);
4786 Jim_SetResultString(interp, target_state_name(target), -1);
4787 return JIM_OK;
4789 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4791 Jim_GetOptInfo goi;
4792 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4793 if (goi.argc != 1) {
4794 const char *cmd_name = Jim_GetString(argv[0], NULL);
4795 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4796 return JIM_ERR;
4798 Jim_Nvp *n;
4799 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4800 if (e != JIM_OK) {
4801 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4802 return e;
4804 struct target *target = Jim_CmdPrivData(interp);
4805 target_handle_event(target, n->value);
4806 return JIM_OK;
4809 static const struct command_registration target_instance_command_handlers[] = {
4811 .name = "configure",
4812 .mode = COMMAND_CONFIG,
4813 .jim_handler = jim_target_configure,
4814 .help = "configure a new target for use",
4815 .usage = "[target_attribute ...]",
4818 .name = "cget",
4819 .mode = COMMAND_ANY,
4820 .jim_handler = jim_target_configure,
4821 .help = "returns the specified target attribute",
4822 .usage = "target_attribute",
4825 .name = "mww",
4826 .mode = COMMAND_EXEC,
4827 .jim_handler = jim_target_mw,
4828 .help = "Write 32-bit word(s) to target memory",
4829 .usage = "address data [count]",
4832 .name = "mwh",
4833 .mode = COMMAND_EXEC,
4834 .jim_handler = jim_target_mw,
4835 .help = "Write 16-bit half-word(s) to target memory",
4836 .usage = "address data [count]",
4839 .name = "mwb",
4840 .mode = COMMAND_EXEC,
4841 .jim_handler = jim_target_mw,
4842 .help = "Write byte(s) to target memory",
4843 .usage = "address data [count]",
4846 .name = "mdw",
4847 .mode = COMMAND_EXEC,
4848 .jim_handler = jim_target_md,
4849 .help = "Display target memory as 32-bit words",
4850 .usage = "address [count]",
4853 .name = "mdh",
4854 .mode = COMMAND_EXEC,
4855 .jim_handler = jim_target_md,
4856 .help = "Display target memory as 16-bit half-words",
4857 .usage = "address [count]",
4860 .name = "mdb",
4861 .mode = COMMAND_EXEC,
4862 .jim_handler = jim_target_md,
4863 .help = "Display target memory as 8-bit bytes",
4864 .usage = "address [count]",
4867 .name = "array2mem",
4868 .mode = COMMAND_EXEC,
4869 .jim_handler = jim_target_array2mem,
4870 .help = "Writes Tcl array of 8/16/32 bit numbers "
4871 "to target memory",
4872 .usage = "arrayname bitwidth address count",
4875 .name = "mem2array",
4876 .mode = COMMAND_EXEC,
4877 .jim_handler = jim_target_mem2array,
4878 .help = "Loads Tcl array of 8/16/32 bit numbers "
4879 "from target memory",
4880 .usage = "arrayname bitwidth address count",
4883 .name = "eventlist",
4884 .mode = COMMAND_EXEC,
4885 .jim_handler = jim_target_event_list,
4886 .help = "displays a table of events defined for this target",
4889 .name = "curstate",
4890 .mode = COMMAND_EXEC,
4891 .jim_handler = jim_target_current_state,
4892 .help = "displays the current state of this target",
4895 .name = "arp_examine",
4896 .mode = COMMAND_EXEC,
4897 .jim_handler = jim_target_examine,
4898 .help = "used internally for reset processing",
4901 .name = "arp_halt_gdb",
4902 .mode = COMMAND_EXEC,
4903 .jim_handler = jim_target_halt_gdb,
4904 .help = "used internally for reset processing to halt GDB",
4907 .name = "arp_poll",
4908 .mode = COMMAND_EXEC,
4909 .jim_handler = jim_target_poll,
4910 .help = "used internally for reset processing",
4913 .name = "arp_reset",
4914 .mode = COMMAND_EXEC,
4915 .jim_handler = jim_target_reset,
4916 .help = "used internally for reset processing",
4919 .name = "arp_halt",
4920 .mode = COMMAND_EXEC,
4921 .jim_handler = jim_target_halt,
4922 .help = "used internally for reset processing",
4925 .name = "arp_waitstate",
4926 .mode = COMMAND_EXEC,
4927 .jim_handler = jim_target_wait_state,
4928 .help = "used internally for reset processing",
4931 .name = "invoke-event",
4932 .mode = COMMAND_EXEC,
4933 .jim_handler = jim_target_invoke_event,
4934 .help = "invoke handler for specified event",
4935 .usage = "event_name",
4937 COMMAND_REGISTRATION_DONE
4940 static int target_create(Jim_GetOptInfo *goi)
4942 Jim_Obj *new_cmd;
4943 Jim_Cmd *cmd;
4944 const char *cp;
4945 char *cp2;
4946 int e;
4947 int x;
4948 struct target *target;
4949 struct command_context *cmd_ctx;
4951 cmd_ctx = current_command_context(goi->interp);
4952 assert(cmd_ctx != NULL);
4954 if (goi->argc < 3) {
4955 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4956 return JIM_ERR;
4959 /* COMMAND */
4960 Jim_GetOpt_Obj(goi, &new_cmd);
4961 /* does this command exist? */
4962 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4963 if (cmd) {
4964 cp = Jim_GetString(new_cmd, NULL);
4965 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
4966 return JIM_ERR;
4969 /* TYPE */
4970 e = Jim_GetOpt_String(goi, &cp2, NULL);
4971 if (e != JIM_OK)
4972 return e;
4973 cp = cp2;
4974 /* now does target type exist */
4975 for (x = 0 ; target_types[x] ; x++) {
4976 if (0 == strcmp(cp, target_types[x]->name)) {
4977 /* found */
4978 break;
4981 /* check for deprecated name */
4982 if (target_types[x]->deprecated_name) {
4983 if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
4984 /* found */
4985 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
4986 break;
4990 if (target_types[x] == NULL) {
4991 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
4992 for (x = 0 ; target_types[x] ; x++) {
4993 if (target_types[x + 1]) {
4994 Jim_AppendStrings(goi->interp,
4995 Jim_GetResult(goi->interp),
4996 target_types[x]->name,
4997 ", ", NULL);
4998 } else {
4999 Jim_AppendStrings(goi->interp,
5000 Jim_GetResult(goi->interp),
5001 " or ",
5002 target_types[x]->name, NULL);
5005 return JIM_ERR;
5008 /* Create it */
5009 target = calloc(1, sizeof(struct target));
5010 /* set target number */
5011 target->target_number = new_target_number();
5013 /* allocate memory for each unique target type */
5014 target->type = (struct target_type *)calloc(1, sizeof(struct target_type));
5016 memcpy(target->type, target_types[x], sizeof(struct target_type));
5018 /* will be set by "-endian" */
5019 target->endianness = TARGET_ENDIAN_UNKNOWN;
5021 /* default to first core, override with -coreid */
5022 target->coreid = 0;
5024 target->working_area = 0x0;
5025 target->working_area_size = 0x0;
5026 target->working_areas = NULL;
5027 target->backup_working_area = 0;
5029 target->state = TARGET_UNKNOWN;
5030 target->debug_reason = DBG_REASON_UNDEFINED;
5031 target->reg_cache = NULL;
5032 target->breakpoints = NULL;
5033 target->watchpoints = NULL;
5034 target->next = NULL;
5035 target->arch_info = NULL;
5037 target->display = 1;
5039 target->halt_issued = false;
5041 /* initialize trace information */
5042 target->trace_info = malloc(sizeof(struct trace));
5043 target->trace_info->num_trace_points = 0;
5044 target->trace_info->trace_points_size = 0;
5045 target->trace_info->trace_points = NULL;
5046 target->trace_info->trace_history_size = 0;
5047 target->trace_info->trace_history = NULL;
5048 target->trace_info->trace_history_pos = 0;
5049 target->trace_info->trace_history_overflowed = 0;
5051 target->dbgmsg = NULL;
5052 target->dbg_msg_enabled = 0;
5054 target->endianness = TARGET_ENDIAN_UNKNOWN;
5056 target->rtos = NULL;
5057 target->rtos_auto_detect = false;
5059 /* Do the rest as "configure" options */
5060 goi->isconfigure = 1;
5061 e = target_configure(goi, target);
5063 if (target->tap == NULL) {
5064 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
5065 e = JIM_ERR;
5068 if (e != JIM_OK) {
5069 free(target->type);
5070 free(target);
5071 return e;
5074 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5075 /* default endian to little if not specified */
5076 target->endianness = TARGET_LITTLE_ENDIAN;
5079 /* incase variant is not set */
5080 if (!target->variant)
5081 target->variant = strdup("");
5083 cp = Jim_GetString(new_cmd, NULL);
5084 target->cmd_name = strdup(cp);
5086 /* create the target specific commands */
5087 if (target->type->commands) {
5088 e = register_commands(cmd_ctx, NULL, target->type->commands);
5089 if (ERROR_OK != e)
5090 LOG_ERROR("unable to register '%s' commands", cp);
5092 if (target->type->target_create)
5093 (*(target->type->target_create))(target, goi->interp);
5095 /* append to end of list */
5097 struct target **tpp;
5098 tpp = &(all_targets);
5099 while (*tpp)
5100 tpp = &((*tpp)->next);
5101 *tpp = target;
5104 /* now - create the new target name command */
5105 const struct command_registration target_subcommands[] = {
5107 .chain = target_instance_command_handlers,
5110 .chain = target->type->commands,
5112 COMMAND_REGISTRATION_DONE
5114 const struct command_registration target_commands[] = {
5116 .name = cp,
5117 .mode = COMMAND_ANY,
5118 .help = "target command group",
5119 .usage = "",
5120 .chain = target_subcommands,
5122 COMMAND_REGISTRATION_DONE
5124 e = register_commands(cmd_ctx, NULL, target_commands);
5125 if (ERROR_OK != e)
5126 return JIM_ERR;
5128 struct command *c = command_find_in_context(cmd_ctx, cp);
5129 assert(c);
5130 command_set_handler_data(c, target);
5132 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5135 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5137 if (argc != 1) {
5138 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5139 return JIM_ERR;
5141 struct command_context *cmd_ctx = current_command_context(interp);
5142 assert(cmd_ctx != NULL);
5144 Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5145 return JIM_OK;
5148 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5150 if (argc != 1) {
5151 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5152 return JIM_ERR;
5154 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5155 for (unsigned x = 0; NULL != target_types[x]; x++) {
5156 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5157 Jim_NewStringObj(interp, target_types[x]->name, -1));
5159 return JIM_OK;
5162 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5164 if (argc != 1) {
5165 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5166 return JIM_ERR;
5168 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5169 struct target *target = all_targets;
5170 while (target) {
5171 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5172 Jim_NewStringObj(interp, target_name(target), -1));
5173 target = target->next;
5175 return JIM_OK;
5178 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5180 int i;
5181 const char *targetname;
5182 int retval, len;
5183 struct target *target = (struct target *) NULL;
5184 struct target_list *head, *curr, *new;
5185 curr = (struct target_list *) NULL;
5186 head = (struct target_list *) NULL;
5188 retval = 0;
5189 LOG_DEBUG("%d", argc);
5190 /* argv[1] = target to associate in smp
5191 * argv[2] = target to assoicate in smp
5192 * argv[3] ...
5195 for (i = 1; i < argc; i++) {
5197 targetname = Jim_GetString(argv[i], &len);
5198 target = get_target(targetname);
5199 LOG_DEBUG("%s ", targetname);
5200 if (target) {
5201 new = malloc(sizeof(struct target_list));
5202 new->target = target;
5203 new->next = (struct target_list *)NULL;
5204 if (head == (struct target_list *)NULL) {
5205 head = new;
5206 curr = head;
5207 } else {
5208 curr->next = new;
5209 curr = new;
5213 /* now parse the list of cpu and put the target in smp mode*/
5214 curr = head;
5216 while (curr != (struct target_list *)NULL) {
5217 target = curr->target;
5218 target->smp = 1;
5219 target->head = head;
5220 curr = curr->next;
5223 if (target && target->rtos)
5224 retval = rtos_smp_init(head->target);
5226 return retval;
5230 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5232 Jim_GetOptInfo goi;
5233 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5234 if (goi.argc < 3) {
5235 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5236 "<name> <target_type> [<target_options> ...]");
5237 return JIM_ERR;
5239 return target_create(&goi);
5242 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5244 Jim_GetOptInfo goi;
5245 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5247 /* It's OK to remove this mechanism sometime after August 2010 or so */
5248 LOG_WARNING("don't use numbers as target identifiers; use names");
5249 if (goi.argc != 1) {
5250 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
5251 return JIM_ERR;
5253 jim_wide w;
5254 int e = Jim_GetOpt_Wide(&goi, &w);
5255 if (e != JIM_OK)
5256 return JIM_ERR;
5258 struct target *target;
5259 for (target = all_targets; NULL != target; target = target->next) {
5260 if (target->target_number != w)
5261 continue;
5263 Jim_SetResultString(goi.interp, target_name(target), -1);
5264 return JIM_OK;
5267 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
5268 Jim_SetResultFormatted(goi.interp,
5269 "Target: number %#s does not exist", wObj);
5270 Jim_FreeNewObj(interp, wObj);
5272 return JIM_ERR;
5275 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5277 if (argc != 1) {
5278 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
5279 return JIM_ERR;
5281 unsigned count = 0;
5282 struct target *target = all_targets;
5283 while (NULL != target) {
5284 target = target->next;
5285 count++;
5287 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
5288 return JIM_OK;
5291 static const struct command_registration target_subcommand_handlers[] = {
5293 .name = "init",
5294 .mode = COMMAND_CONFIG,
5295 .handler = handle_target_init_command,
5296 .help = "initialize targets",
5299 .name = "create",
5300 /* REVISIT this should be COMMAND_CONFIG ... */
5301 .mode = COMMAND_ANY,
5302 .jim_handler = jim_target_create,
5303 .usage = "name type '-chain-position' name [options ...]",
5304 .help = "Creates and selects a new target",
5307 .name = "current",
5308 .mode = COMMAND_ANY,
5309 .jim_handler = jim_target_current,
5310 .help = "Returns the currently selected target",
5313 .name = "types",
5314 .mode = COMMAND_ANY,
5315 .jim_handler = jim_target_types,
5316 .help = "Returns the available target types as "
5317 "a list of strings",
5320 .name = "names",
5321 .mode = COMMAND_ANY,
5322 .jim_handler = jim_target_names,
5323 .help = "Returns the names of all targets as a list of strings",
5326 .name = "number",
5327 .mode = COMMAND_ANY,
5328 .jim_handler = jim_target_number,
5329 .usage = "number",
5330 .help = "Returns the name of the numbered target "
5331 "(DEPRECATED)",
5334 .name = "count",
5335 .mode = COMMAND_ANY,
5336 .jim_handler = jim_target_count,
5337 .help = "Returns the number of targets as an integer "
5338 "(DEPRECATED)",
5341 .name = "smp",
5342 .mode = COMMAND_ANY,
5343 .jim_handler = jim_target_smp,
5344 .usage = "targetname1 targetname2 ...",
5345 .help = "gather several target in a smp list"
5348 COMMAND_REGISTRATION_DONE
5351 struct FastLoad {
5352 uint32_t address;
5353 uint8_t *data;
5354 int length;
5358 static int fastload_num;
5359 static struct FastLoad *fastload;
5361 static void free_fastload(void)
5363 if (fastload != NULL) {
5364 int i;
5365 for (i = 0; i < fastload_num; i++) {
5366 if (fastload[i].data)
5367 free(fastload[i].data);
5369 free(fastload);
5370 fastload = NULL;
5374 COMMAND_HANDLER(handle_fast_load_image_command)
5376 uint8_t *buffer;
5377 size_t buf_cnt;
5378 uint32_t image_size;
5379 uint32_t min_address = 0;
5380 uint32_t max_address = 0xffffffff;
5381 int i;
5383 struct image image;
5385 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5386 &image, &min_address, &max_address);
5387 if (ERROR_OK != retval)
5388 return retval;
5390 struct duration bench;
5391 duration_start(&bench);
5393 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5394 if (retval != ERROR_OK)
5395 return retval;
5397 image_size = 0x0;
5398 retval = ERROR_OK;
5399 fastload_num = image.num_sections;
5400 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
5401 if (fastload == NULL) {
5402 command_print(CMD_CTX, "out of memory");
5403 image_close(&image);
5404 return ERROR_FAIL;
5406 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5407 for (i = 0; i < image.num_sections; i++) {
5408 buffer = malloc(image.sections[i].size);
5409 if (buffer == NULL) {
5410 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5411 (int)(image.sections[i].size));
5412 retval = ERROR_FAIL;
5413 break;
5416 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5417 if (retval != ERROR_OK) {
5418 free(buffer);
5419 break;
5422 uint32_t offset = 0;
5423 uint32_t length = buf_cnt;
5425 /* DANGER!!! beware of unsigned comparision here!!! */
5427 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5428 (image.sections[i].base_address < max_address)) {
5429 if (image.sections[i].base_address < min_address) {
5430 /* clip addresses below */
5431 offset += min_address-image.sections[i].base_address;
5432 length -= offset;
5435 if (image.sections[i].base_address + buf_cnt > max_address)
5436 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5438 fastload[i].address = image.sections[i].base_address + offset;
5439 fastload[i].data = malloc(length);
5440 if (fastload[i].data == NULL) {
5441 free(buffer);
5442 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5443 length);
5444 retval = ERROR_FAIL;
5445 break;
5447 memcpy(fastload[i].data, buffer + offset, length);
5448 fastload[i].length = length;
5450 image_size += length;
5451 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5452 (unsigned int)length,
5453 ((unsigned int)(image.sections[i].base_address + offset)));
5456 free(buffer);
5459 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5460 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5461 "in %fs (%0.3f KiB/s)", image_size,
5462 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5464 command_print(CMD_CTX,
5465 "WARNING: image has not been loaded to target!"
5466 "You can issue a 'fast_load' to finish loading.");
5469 image_close(&image);
5471 if (retval != ERROR_OK)
5472 free_fastload();
5474 return retval;
5477 COMMAND_HANDLER(handle_fast_load_command)
5479 if (CMD_ARGC > 0)
5480 return ERROR_COMMAND_SYNTAX_ERROR;
5481 if (fastload == NULL) {
5482 LOG_ERROR("No image in memory");
5483 return ERROR_FAIL;
5485 int i;
5486 int ms = timeval_ms();
5487 int size = 0;
5488 int retval = ERROR_OK;
5489 for (i = 0; i < fastload_num; i++) {
5490 struct target *target = get_current_target(CMD_CTX);
5491 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5492 (unsigned int)(fastload[i].address),
5493 (unsigned int)(fastload[i].length));
5494 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5495 if (retval != ERROR_OK)
5496 break;
5497 size += fastload[i].length;
5499 if (retval == ERROR_OK) {
5500 int after = timeval_ms();
5501 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5503 return retval;
5506 static const struct command_registration target_command_handlers[] = {
5508 .name = "targets",
5509 .handler = handle_targets_command,
5510 .mode = COMMAND_ANY,
5511 .help = "change current default target (one parameter) "
5512 "or prints table of all targets (no parameters)",
5513 .usage = "[target]",
5516 .name = "target",
5517 .mode = COMMAND_CONFIG,
5518 .help = "configure target",
5520 .chain = target_subcommand_handlers,
5522 COMMAND_REGISTRATION_DONE
5525 int target_register_commands(struct command_context *cmd_ctx)
5527 return register_commands(cmd_ctx, NULL, target_command_handlers);
5530 static bool target_reset_nag = true;
5532 bool get_target_reset_nag(void)
5534 return target_reset_nag;
5537 COMMAND_HANDLER(handle_target_reset_nag)
5539 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5540 &target_reset_nag, "Nag after each reset about options to improve "
5541 "performance");
5544 COMMAND_HANDLER(handle_ps_command)
5546 struct target *target = get_current_target(CMD_CTX);
5547 char *display;
5548 if (target->state != TARGET_HALTED) {
5549 LOG_INFO("target not halted !!");
5550 return ERROR_OK;
5553 if ((target->rtos) && (target->rtos->type)
5554 && (target->rtos->type->ps_command)) {
5555 display = target->rtos->type->ps_command(target);
5556 command_print(CMD_CTX, "%s", display);
5557 free(display);
5558 return ERROR_OK;
5559 } else {
5560 LOG_INFO("failed");
5561 return ERROR_TARGET_FAILURE;
5565 static const struct command_registration target_exec_command_handlers[] = {
5567 .name = "fast_load_image",
5568 .handler = handle_fast_load_image_command,
5569 .mode = COMMAND_ANY,
5570 .help = "Load image into server memory for later use by "
5571 "fast_load; primarily for profiling",
5572 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5573 "[min_address [max_length]]",
5576 .name = "fast_load",
5577 .handler = handle_fast_load_command,
5578 .mode = COMMAND_EXEC,
5579 .help = "loads active fast load image to current target "
5580 "- mainly for profiling purposes",
5581 .usage = "",
5584 .name = "profile",
5585 .handler = handle_profile_command,
5586 .mode = COMMAND_EXEC,
5587 .usage = "seconds filename [start end]",
5588 .help = "profiling samples the CPU PC",
5590 /** @todo don't register virt2phys() unless target supports it */
5592 .name = "virt2phys",
5593 .handler = handle_virt2phys_command,
5594 .mode = COMMAND_ANY,
5595 .help = "translate a virtual address into a physical address",
5596 .usage = "virtual_address",
5599 .name = "reg",
5600 .handler = handle_reg_command,
5601 .mode = COMMAND_EXEC,
5602 .help = "display or set a register; with no arguments, "
5603 "displays all registers and their values",
5604 .usage = "[(register_name|register_number) [value]]",
5607 .name = "poll",
5608 .handler = handle_poll_command,
5609 .mode = COMMAND_EXEC,
5610 .help = "poll target state; or reconfigure background polling",
5611 .usage = "['on'|'off']",
5614 .name = "wait_halt",
5615 .handler = handle_wait_halt_command,
5616 .mode = COMMAND_EXEC,
5617 .help = "wait up to the specified number of milliseconds "
5618 "(default 5000) for a previously requested halt",
5619 .usage = "[milliseconds]",
5622 .name = "halt",
5623 .handler = handle_halt_command,
5624 .mode = COMMAND_EXEC,
5625 .help = "request target to halt, then wait up to the specified"
5626 "number of milliseconds (default 5000) for it to complete",
5627 .usage = "[milliseconds]",
5630 .name = "resume",
5631 .handler = handle_resume_command,
5632 .mode = COMMAND_EXEC,
5633 .help = "resume target execution from current PC or address",
5634 .usage = "[address]",
5637 .name = "reset",
5638 .handler = handle_reset_command,
5639 .mode = COMMAND_EXEC,
5640 .usage = "[run|halt|init]",
5641 .help = "Reset all targets into the specified mode."
5642 "Default reset mode is run, if not given.",
5645 .name = "soft_reset_halt",
5646 .handler = handle_soft_reset_halt_command,
5647 .mode = COMMAND_EXEC,
5648 .usage = "",
5649 .help = "halt the target and do a soft reset",
5652 .name = "step",
5653 .handler = handle_step_command,
5654 .mode = COMMAND_EXEC,
5655 .help = "step one instruction from current PC or address",
5656 .usage = "[address]",
5659 .name = "mdw",
5660 .handler = handle_md_command,
5661 .mode = COMMAND_EXEC,
5662 .help = "display memory words",
5663 .usage = "['phys'] address [count]",
5666 .name = "mdh",
5667 .handler = handle_md_command,
5668 .mode = COMMAND_EXEC,
5669 .help = "display memory half-words",
5670 .usage = "['phys'] address [count]",
5673 .name = "mdb",
5674 .handler = handle_md_command,
5675 .mode = COMMAND_EXEC,
5676 .help = "display memory bytes",
5677 .usage = "['phys'] address [count]",
5680 .name = "mww",
5681 .handler = handle_mw_command,
5682 .mode = COMMAND_EXEC,
5683 .help = "write memory word",
5684 .usage = "['phys'] address value [count]",
5687 .name = "mwh",
5688 .handler = handle_mw_command,
5689 .mode = COMMAND_EXEC,
5690 .help = "write memory half-word",
5691 .usage = "['phys'] address value [count]",
5694 .name = "mwb",
5695 .handler = handle_mw_command,
5696 .mode = COMMAND_EXEC,
5697 .help = "write memory byte",
5698 .usage = "['phys'] address value [count]",
5701 .name = "bp",
5702 .handler = handle_bp_command,
5703 .mode = COMMAND_EXEC,
5704 .help = "list or set hardware or software breakpoint",
5705 .usage = "<address> [<asid>]<length> ['hw'|'hw_ctx']",
5708 .name = "rbp",
5709 .handler = handle_rbp_command,
5710 .mode = COMMAND_EXEC,
5711 .help = "remove breakpoint",
5712 .usage = "address",
5715 .name = "wp",
5716 .handler = handle_wp_command,
5717 .mode = COMMAND_EXEC,
5718 .help = "list (no params) or create watchpoints",
5719 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5722 .name = "rwp",
5723 .handler = handle_rwp_command,
5724 .mode = COMMAND_EXEC,
5725 .help = "remove watchpoint",
5726 .usage = "address",
5729 .name = "load_image",
5730 .handler = handle_load_image_command,
5731 .mode = COMMAND_EXEC,
5732 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5733 "[min_address] [max_length]",
5736 .name = "dump_image",
5737 .handler = handle_dump_image_command,
5738 .mode = COMMAND_EXEC,
5739 .usage = "filename address size",
5742 .name = "verify_image",
5743 .handler = handle_verify_image_command,
5744 .mode = COMMAND_EXEC,
5745 .usage = "filename [offset [type]]",
5748 .name = "test_image",
5749 .handler = handle_test_image_command,
5750 .mode = COMMAND_EXEC,
5751 .usage = "filename [offset [type]]",
5754 .name = "mem2array",
5755 .mode = COMMAND_EXEC,
5756 .jim_handler = jim_mem2array,
5757 .help = "read 8/16/32 bit memory and return as a TCL array "
5758 "for script processing",
5759 .usage = "arrayname bitwidth address count",
5762 .name = "array2mem",
5763 .mode = COMMAND_EXEC,
5764 .jim_handler = jim_array2mem,
5765 .help = "convert a TCL array to memory locations "
5766 "and write the 8/16/32 bit values",
5767 .usage = "arrayname bitwidth address count",
5770 .name = "reset_nag",
5771 .handler = handle_target_reset_nag,
5772 .mode = COMMAND_ANY,
5773 .help = "Nag after each reset about options that could have been "
5774 "enabled to improve performance. ",
5775 .usage = "['enable'|'disable']",
5778 .name = "ps",
5779 .handler = handle_ps_command,
5780 .mode = COMMAND_EXEC,
5781 .help = "list all tasks ",
5782 .usage = " ",
5785 COMMAND_REGISTRATION_DONE
5787 static int target_register_user_commands(struct command_context *cmd_ctx)
5789 int retval = ERROR_OK;
5790 retval = target_request_register_commands(cmd_ctx);
5791 if (retval != ERROR_OK)
5792 return retval;
5794 retval = trace_register_commands(cmd_ctx);
5795 if (retval != ERROR_OK)
5796 return retval;
5799 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);