target: use correct target in target-prefixed commands and event handlers
[openocd.git] / src / target / target.c
blob32000c0474b3c2a7c0466632db288912a0a2f823
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, see <http://www.gnu.org/licenses/>. *
38 ***************************************************************************/
40 #ifdef HAVE_CONFIG_H
41 #include "config.h"
42 #endif
44 #include <helper/time_support.h>
45 #include <jtag/jtag.h>
46 #include <flash/nor/core.h>
48 #include "target.h"
49 #include "target_type.h"
50 #include "target_request.h"
51 #include "breakpoints.h"
52 #include "register.h"
53 #include "trace.h"
54 #include "image.h"
55 #include "rtos/rtos.h"
56 #include "transport/transport.h"
58 /* default halt wait timeout (ms) */
59 #define DEFAULT_HALT_TIMEOUT 5000
61 static int target_read_buffer_default(struct target *target, target_addr_t address,
62 uint32_t count, uint8_t *buffer);
63 static int target_write_buffer_default(struct target *target, target_addr_t address,
64 uint32_t count, const uint8_t *buffer);
65 static int target_array2mem(Jim_Interp *interp, struct target *target,
66 int argc, Jim_Obj * const *argv);
67 static int target_mem2array(Jim_Interp *interp, struct target *target,
68 int argc, Jim_Obj * const *argv);
69 static int target_register_user_commands(struct command_context *cmd_ctx);
70 static int target_get_gdb_fileio_info_default(struct target *target,
71 struct gdb_fileio_info *fileio_info);
72 static int target_gdb_fileio_end_default(struct target *target, int retcode,
73 int fileio_errno, bool ctrl_c);
74 static int target_profiling_default(struct target *target, uint32_t *samples,
75 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds);
77 /* targets */
78 extern struct target_type arm7tdmi_target;
79 extern struct target_type arm720t_target;
80 extern struct target_type arm9tdmi_target;
81 extern struct target_type arm920t_target;
82 extern struct target_type arm966e_target;
83 extern struct target_type arm946e_target;
84 extern struct target_type arm926ejs_target;
85 extern struct target_type fa526_target;
86 extern struct target_type feroceon_target;
87 extern struct target_type dragonite_target;
88 extern struct target_type xscale_target;
89 extern struct target_type cortexm_target;
90 extern struct target_type cortexa_target;
91 extern struct target_type aarch64_target;
92 extern struct target_type cortexr4_target;
93 extern struct target_type arm11_target;
94 extern struct target_type ls1_sap_target;
95 extern struct target_type mips_m4k_target;
96 extern struct target_type avr_target;
97 extern struct target_type dsp563xx_target;
98 extern struct target_type dsp5680xx_target;
99 extern struct target_type testee_target;
100 extern struct target_type avr32_ap7k_target;
101 extern struct target_type hla_target;
102 extern struct target_type nds32_v2_target;
103 extern struct target_type nds32_v3_target;
104 extern struct target_type nds32_v3m_target;
105 extern struct target_type or1k_target;
106 extern struct target_type quark_x10xx_target;
107 extern struct target_type quark_d20xx_target;
108 extern struct target_type stm8_target;
110 static struct target_type *target_types[] = {
111 &arm7tdmi_target,
112 &arm9tdmi_target,
113 &arm920t_target,
114 &arm720t_target,
115 &arm966e_target,
116 &arm946e_target,
117 &arm926ejs_target,
118 &fa526_target,
119 &feroceon_target,
120 &dragonite_target,
121 &xscale_target,
122 &cortexm_target,
123 &cortexa_target,
124 &cortexr4_target,
125 &arm11_target,
126 &ls1_sap_target,
127 &mips_m4k_target,
128 &avr_target,
129 &dsp563xx_target,
130 &dsp5680xx_target,
131 &testee_target,
132 &avr32_ap7k_target,
133 &hla_target,
134 &nds32_v2_target,
135 &nds32_v3_target,
136 &nds32_v3m_target,
137 &or1k_target,
138 &quark_x10xx_target,
139 &quark_d20xx_target,
140 &stm8_target,
141 #if BUILD_TARGET64
142 &aarch64_target,
143 #endif
144 NULL,
147 struct target *all_targets;
148 static struct target_event_callback *target_event_callbacks;
149 static struct target_timer_callback *target_timer_callbacks;
150 LIST_HEAD(target_reset_callback_list);
151 LIST_HEAD(target_trace_callback_list);
152 static const int polling_interval = 100;
154 static const Jim_Nvp nvp_assert[] = {
155 { .name = "assert", NVP_ASSERT },
156 { .name = "deassert", NVP_DEASSERT },
157 { .name = "T", NVP_ASSERT },
158 { .name = "F", NVP_DEASSERT },
159 { .name = "t", NVP_ASSERT },
160 { .name = "f", NVP_DEASSERT },
161 { .name = NULL, .value = -1 }
164 static const Jim_Nvp nvp_error_target[] = {
165 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
166 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
167 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
168 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
169 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
170 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
171 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
172 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
173 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
174 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
175 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
176 { .value = -1, .name = NULL }
179 static const char *target_strerror_safe(int err)
181 const Jim_Nvp *n;
183 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
184 if (n->name == NULL)
185 return "unknown";
186 else
187 return n->name;
190 static const Jim_Nvp nvp_target_event[] = {
192 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
193 { .value = TARGET_EVENT_HALTED, .name = "halted" },
194 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
195 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
196 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
198 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
199 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
201 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
202 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
203 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
204 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
205 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
206 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
207 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
208 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
210 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
211 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
213 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
214 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
216 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
217 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
219 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
220 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
222 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
223 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
225 { .value = TARGET_EVENT_TRACE_CONFIG, .name = "trace-config" },
227 { .name = NULL, .value = -1 }
230 static const Jim_Nvp nvp_target_state[] = {
231 { .name = "unknown", .value = TARGET_UNKNOWN },
232 { .name = "running", .value = TARGET_RUNNING },
233 { .name = "halted", .value = TARGET_HALTED },
234 { .name = "reset", .value = TARGET_RESET },
235 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
236 { .name = NULL, .value = -1 },
239 static const Jim_Nvp nvp_target_debug_reason[] = {
240 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
241 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
242 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
243 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
244 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
245 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
246 { .name = "program-exit" , .value = DBG_REASON_EXIT },
247 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
248 { .name = NULL, .value = -1 },
251 static const Jim_Nvp nvp_target_endian[] = {
252 { .name = "big", .value = TARGET_BIG_ENDIAN },
253 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
254 { .name = "be", .value = TARGET_BIG_ENDIAN },
255 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
256 { .name = NULL, .value = -1 },
259 static const Jim_Nvp nvp_reset_modes[] = {
260 { .name = "unknown", .value = RESET_UNKNOWN },
261 { .name = "run" , .value = RESET_RUN },
262 { .name = "halt" , .value = RESET_HALT },
263 { .name = "init" , .value = RESET_INIT },
264 { .name = NULL , .value = -1 },
267 const char *debug_reason_name(struct target *t)
269 const char *cp;
271 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
272 t->debug_reason)->name;
273 if (!cp) {
274 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
275 cp = "(*BUG*unknown*BUG*)";
277 return cp;
280 const char *target_state_name(struct target *t)
282 const char *cp;
283 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
284 if (!cp) {
285 LOG_ERROR("Invalid target state: %d", (int)(t->state));
286 cp = "(*BUG*unknown*BUG*)";
289 if (!target_was_examined(t) && t->defer_examine)
290 cp = "examine deferred";
292 return cp;
295 const char *target_event_name(enum target_event event)
297 const char *cp;
298 cp = Jim_Nvp_value2name_simple(nvp_target_event, event)->name;
299 if (!cp) {
300 LOG_ERROR("Invalid target event: %d", (int)(event));
301 cp = "(*BUG*unknown*BUG*)";
303 return cp;
306 const char *target_reset_mode_name(enum target_reset_mode reset_mode)
308 const char *cp;
309 cp = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name;
310 if (!cp) {
311 LOG_ERROR("Invalid target reset mode: %d", (int)(reset_mode));
312 cp = "(*BUG*unknown*BUG*)";
314 return cp;
317 /* determine the number of the new target */
318 static int new_target_number(void)
320 struct target *t;
321 int x;
323 /* number is 0 based */
324 x = -1;
325 t = all_targets;
326 while (t) {
327 if (x < t->target_number)
328 x = t->target_number;
329 t = t->next;
331 return x + 1;
334 /* read a uint64_t from a buffer in target memory endianness */
335 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
337 if (target->endianness == TARGET_LITTLE_ENDIAN)
338 return le_to_h_u64(buffer);
339 else
340 return be_to_h_u64(buffer);
343 /* read a uint32_t from a buffer in target memory endianness */
344 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
346 if (target->endianness == TARGET_LITTLE_ENDIAN)
347 return le_to_h_u32(buffer);
348 else
349 return be_to_h_u32(buffer);
352 /* read a uint24_t from a buffer in target memory endianness */
353 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
355 if (target->endianness == TARGET_LITTLE_ENDIAN)
356 return le_to_h_u24(buffer);
357 else
358 return be_to_h_u24(buffer);
361 /* read a uint16_t from a buffer in target memory endianness */
362 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
364 if (target->endianness == TARGET_LITTLE_ENDIAN)
365 return le_to_h_u16(buffer);
366 else
367 return be_to_h_u16(buffer);
370 /* read a uint8_t from a buffer in target memory endianness */
371 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
373 return *buffer & 0x0ff;
376 /* write a uint64_t to a buffer in target memory endianness */
377 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
379 if (target->endianness == TARGET_LITTLE_ENDIAN)
380 h_u64_to_le(buffer, value);
381 else
382 h_u64_to_be(buffer, value);
385 /* write a uint32_t to a buffer in target memory endianness */
386 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
388 if (target->endianness == TARGET_LITTLE_ENDIAN)
389 h_u32_to_le(buffer, value);
390 else
391 h_u32_to_be(buffer, value);
394 /* write a uint24_t to a buffer in target memory endianness */
395 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
397 if (target->endianness == TARGET_LITTLE_ENDIAN)
398 h_u24_to_le(buffer, value);
399 else
400 h_u24_to_be(buffer, value);
403 /* write a uint16_t to a buffer in target memory endianness */
404 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
406 if (target->endianness == TARGET_LITTLE_ENDIAN)
407 h_u16_to_le(buffer, value);
408 else
409 h_u16_to_be(buffer, value);
412 /* write a uint8_t to a buffer in target memory endianness */
413 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
415 *buffer = value;
418 /* write a uint64_t array to a buffer in target memory endianness */
419 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
421 uint32_t i;
422 for (i = 0; i < count; i++)
423 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
426 /* write a uint32_t array to a buffer in target memory endianness */
427 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
429 uint32_t i;
430 for (i = 0; i < count; i++)
431 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
434 /* write a uint16_t array to a buffer in target memory endianness */
435 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
437 uint32_t i;
438 for (i = 0; i < count; i++)
439 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
442 /* write a uint64_t array to a buffer in target memory endianness */
443 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
445 uint32_t i;
446 for (i = 0; i < count; i++)
447 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
450 /* write a uint32_t array to a buffer in target memory endianness */
451 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
453 uint32_t i;
454 for (i = 0; i < count; i++)
455 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
458 /* write a uint16_t array to a buffer in target memory endianness */
459 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
461 uint32_t i;
462 for (i = 0; i < count; i++)
463 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
466 /* return a pointer to a configured target; id is name or number */
467 struct target *get_target(const char *id)
469 struct target *target;
471 /* try as tcltarget name */
472 for (target = all_targets; target; target = target->next) {
473 if (target_name(target) == NULL)
474 continue;
475 if (strcmp(id, target_name(target)) == 0)
476 return target;
479 /* It's OK to remove this fallback sometime after August 2010 or so */
481 /* no match, try as number */
482 unsigned num;
483 if (parse_uint(id, &num) != ERROR_OK)
484 return NULL;
486 for (target = all_targets; target; target = target->next) {
487 if (target->target_number == (int)num) {
488 LOG_WARNING("use '%s' as target identifier, not '%u'",
489 target_name(target), num);
490 return target;
494 return NULL;
497 /* returns a pointer to the n-th configured target */
498 struct target *get_target_by_num(int num)
500 struct target *target = all_targets;
502 while (target) {
503 if (target->target_number == num)
504 return target;
505 target = target->next;
508 return NULL;
511 struct target *get_current_target(struct command_context *cmd_ctx)
513 struct target *target = cmd_ctx->current_target_override
514 ? cmd_ctx->current_target_override
515 : cmd_ctx->current_target;
517 if (target == NULL) {
518 LOG_ERROR("BUG: current_target out of bounds");
519 exit(-1);
522 return target;
525 int target_poll(struct target *target)
527 int retval;
529 /* We can't poll until after examine */
530 if (!target_was_examined(target)) {
531 /* Fail silently lest we pollute the log */
532 return ERROR_FAIL;
535 retval = target->type->poll(target);
536 if (retval != ERROR_OK)
537 return retval;
539 if (target->halt_issued) {
540 if (target->state == TARGET_HALTED)
541 target->halt_issued = false;
542 else {
543 int64_t t = timeval_ms() - target->halt_issued_time;
544 if (t > DEFAULT_HALT_TIMEOUT) {
545 target->halt_issued = false;
546 LOG_INFO("Halt timed out, wake up GDB.");
547 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
552 return ERROR_OK;
555 int target_halt(struct target *target)
557 int retval;
558 /* We can't poll until after examine */
559 if (!target_was_examined(target)) {
560 LOG_ERROR("Target not examined yet");
561 return ERROR_FAIL;
564 retval = target->type->halt(target);
565 if (retval != ERROR_OK)
566 return retval;
568 target->halt_issued = true;
569 target->halt_issued_time = timeval_ms();
571 return ERROR_OK;
575 * Make the target (re)start executing using its saved execution
576 * context (possibly with some modifications).
578 * @param target Which target should start executing.
579 * @param current True to use the target's saved program counter instead
580 * of the address parameter
581 * @param address Optionally used as the program counter.
582 * @param handle_breakpoints True iff breakpoints at the resumption PC
583 * should be skipped. (For example, maybe execution was stopped by
584 * such a breakpoint, in which case it would be counterprodutive to
585 * let it re-trigger.
586 * @param debug_execution False if all working areas allocated by OpenOCD
587 * should be released and/or restored to their original contents.
588 * (This would for example be true to run some downloaded "helper"
589 * algorithm code, which resides in one such working buffer and uses
590 * another for data storage.)
592 * @todo Resolve the ambiguity about what the "debug_execution" flag
593 * signifies. For example, Target implementations don't agree on how
594 * it relates to invalidation of the register cache, or to whether
595 * breakpoints and watchpoints should be enabled. (It would seem wrong
596 * to enable breakpoints when running downloaded "helper" algorithms
597 * (debug_execution true), since the breakpoints would be set to match
598 * target firmware being debugged, not the helper algorithm.... and
599 * enabling them could cause such helpers to malfunction (for example,
600 * by overwriting data with a breakpoint instruction. On the other
601 * hand the infrastructure for running such helpers might use this
602 * procedure but rely on hardware breakpoint to detect termination.)
604 int target_resume(struct target *target, int current, target_addr_t address,
605 int handle_breakpoints, int debug_execution)
607 int retval;
609 /* We can't poll until after examine */
610 if (!target_was_examined(target)) {
611 LOG_ERROR("Target not examined yet");
612 return ERROR_FAIL;
615 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
617 /* note that resume *must* be asynchronous. The CPU can halt before
618 * we poll. The CPU can even halt at the current PC as a result of
619 * a software breakpoint being inserted by (a bug?) the application.
621 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
622 if (retval != ERROR_OK)
623 return retval;
625 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
627 return retval;
630 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
632 char buf[100];
633 int retval;
634 Jim_Nvp *n;
635 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
636 if (n->name == NULL) {
637 LOG_ERROR("invalid reset mode");
638 return ERROR_FAIL;
641 struct target *target;
642 for (target = all_targets; target; target = target->next)
643 target_call_reset_callbacks(target, reset_mode);
645 /* disable polling during reset to make reset event scripts
646 * more predictable, i.e. dr/irscan & pathmove in events will
647 * not have JTAG operations injected into the middle of a sequence.
649 bool save_poll = jtag_poll_get_enabled();
651 jtag_poll_set_enabled(false);
653 sprintf(buf, "ocd_process_reset %s", n->name);
654 retval = Jim_Eval(cmd_ctx->interp, buf);
656 jtag_poll_set_enabled(save_poll);
658 if (retval != JIM_OK) {
659 Jim_MakeErrorMessage(cmd_ctx->interp);
660 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
661 return ERROR_FAIL;
664 /* We want any events to be processed before the prompt */
665 retval = target_call_timer_callbacks_now();
667 for (target = all_targets; target; target = target->next) {
668 target->type->check_reset(target);
669 target->running_alg = false;
672 return retval;
675 static int identity_virt2phys(struct target *target,
676 target_addr_t virtual, target_addr_t *physical)
678 *physical = virtual;
679 return ERROR_OK;
682 static int no_mmu(struct target *target, int *enabled)
684 *enabled = 0;
685 return ERROR_OK;
688 static int default_examine(struct target *target)
690 target_set_examined(target);
691 return ERROR_OK;
694 /* no check by default */
695 static int default_check_reset(struct target *target)
697 return ERROR_OK;
700 int target_examine_one(struct target *target)
702 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
704 int retval = target->type->examine(target);
705 if (retval != ERROR_OK)
706 return retval;
708 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
710 return ERROR_OK;
713 static int jtag_enable_callback(enum jtag_event event, void *priv)
715 struct target *target = priv;
717 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
718 return ERROR_OK;
720 jtag_unregister_event_callback(jtag_enable_callback, target);
722 return target_examine_one(target);
725 /* Targets that correctly implement init + examine, i.e.
726 * no communication with target during init:
728 * XScale
730 int target_examine(void)
732 int retval = ERROR_OK;
733 struct target *target;
735 for (target = all_targets; target; target = target->next) {
736 /* defer examination, but don't skip it */
737 if (!target->tap->enabled) {
738 jtag_register_event_callback(jtag_enable_callback,
739 target);
740 continue;
743 if (target->defer_examine)
744 continue;
746 retval = target_examine_one(target);
747 if (retval != ERROR_OK)
748 return retval;
750 return retval;
753 const char *target_type_name(struct target *target)
755 return target->type->name;
758 static int target_soft_reset_halt(struct target *target)
760 if (!target_was_examined(target)) {
761 LOG_ERROR("Target not examined yet");
762 return ERROR_FAIL;
764 if (!target->type->soft_reset_halt) {
765 LOG_ERROR("Target %s does not support soft_reset_halt",
766 target_name(target));
767 return ERROR_FAIL;
769 return target->type->soft_reset_halt(target);
773 * Downloads a target-specific native code algorithm to the target,
774 * and executes it. * Note that some targets may need to set up, enable,
775 * and tear down a breakpoint (hard or * soft) to detect algorithm
776 * termination, while others may support lower overhead schemes where
777 * soft breakpoints embedded in the algorithm automatically terminate the
778 * algorithm.
780 * @param target used to run the algorithm
781 * @param arch_info target-specific description of the algorithm.
783 int target_run_algorithm(struct target *target,
784 int num_mem_params, struct mem_param *mem_params,
785 int num_reg_params, struct reg_param *reg_param,
786 uint32_t entry_point, uint32_t exit_point,
787 int timeout_ms, void *arch_info)
789 int retval = ERROR_FAIL;
791 if (!target_was_examined(target)) {
792 LOG_ERROR("Target not examined yet");
793 goto done;
795 if (!target->type->run_algorithm) {
796 LOG_ERROR("Target type '%s' does not support %s",
797 target_type_name(target), __func__);
798 goto done;
801 target->running_alg = true;
802 retval = target->type->run_algorithm(target,
803 num_mem_params, mem_params,
804 num_reg_params, reg_param,
805 entry_point, exit_point, timeout_ms, arch_info);
806 target->running_alg = false;
808 done:
809 return retval;
813 * Executes a target-specific native code algorithm and leaves it running.
815 * @param target used to run the algorithm
816 * @param arch_info target-specific description of the algorithm.
818 int target_start_algorithm(struct target *target,
819 int num_mem_params, struct mem_param *mem_params,
820 int num_reg_params, struct reg_param *reg_params,
821 uint32_t entry_point, uint32_t exit_point,
822 void *arch_info)
824 int retval = ERROR_FAIL;
826 if (!target_was_examined(target)) {
827 LOG_ERROR("Target not examined yet");
828 goto done;
830 if (!target->type->start_algorithm) {
831 LOG_ERROR("Target type '%s' does not support %s",
832 target_type_name(target), __func__);
833 goto done;
835 if (target->running_alg) {
836 LOG_ERROR("Target is already running an algorithm");
837 goto done;
840 target->running_alg = true;
841 retval = target->type->start_algorithm(target,
842 num_mem_params, mem_params,
843 num_reg_params, reg_params,
844 entry_point, exit_point, arch_info);
846 done:
847 return retval;
851 * Waits for an algorithm started with target_start_algorithm() to complete.
853 * @param target used to run the algorithm
854 * @param arch_info target-specific description of the algorithm.
856 int target_wait_algorithm(struct target *target,
857 int num_mem_params, struct mem_param *mem_params,
858 int num_reg_params, struct reg_param *reg_params,
859 uint32_t exit_point, int timeout_ms,
860 void *arch_info)
862 int retval = ERROR_FAIL;
864 if (!target->type->wait_algorithm) {
865 LOG_ERROR("Target type '%s' does not support %s",
866 target_type_name(target), __func__);
867 goto done;
869 if (!target->running_alg) {
870 LOG_ERROR("Target is not running an algorithm");
871 goto done;
874 retval = target->type->wait_algorithm(target,
875 num_mem_params, mem_params,
876 num_reg_params, reg_params,
877 exit_point, timeout_ms, arch_info);
878 if (retval != ERROR_TARGET_TIMEOUT)
879 target->running_alg = false;
881 done:
882 return retval;
886 * Streams data to a circular buffer on target intended for consumption by code
887 * running asynchronously on target.
889 * This is intended for applications where target-specific native code runs
890 * on the target, receives data from the circular buffer, does something with
891 * it (most likely writing it to a flash memory), and advances the circular
892 * buffer pointer.
894 * This assumes that the helper algorithm has already been loaded to the target,
895 * but has not been started yet. Given memory and register parameters are passed
896 * to the algorithm.
898 * The buffer is defined by (buffer_start, buffer_size) arguments and has the
899 * following format:
901 * [buffer_start + 0, buffer_start + 4):
902 * Write Pointer address (aka head). Written and updated by this
903 * routine when new data is written to the circular buffer.
904 * [buffer_start + 4, buffer_start + 8):
905 * Read Pointer address (aka tail). Updated by code running on the
906 * target after it consumes data.
907 * [buffer_start + 8, buffer_start + buffer_size):
908 * Circular buffer contents.
910 * See contrib/loaders/flash/stm32f1x.S for an example.
912 * @param target used to run the algorithm
913 * @param buffer address on the host where data to be sent is located
914 * @param count number of blocks to send
915 * @param block_size size in bytes of each block
916 * @param num_mem_params count of memory-based params to pass to algorithm
917 * @param mem_params memory-based params to pass to algorithm
918 * @param num_reg_params count of register-based params to pass to algorithm
919 * @param reg_params memory-based params to pass to algorithm
920 * @param buffer_start address on the target of the circular buffer structure
921 * @param buffer_size size of the circular buffer structure
922 * @param entry_point address on the target to execute to start the algorithm
923 * @param exit_point address at which to set a breakpoint to catch the
924 * end of the algorithm; can be 0 if target triggers a breakpoint itself
927 int target_run_flash_async_algorithm(struct target *target,
928 const uint8_t *buffer, uint32_t count, int block_size,
929 int num_mem_params, struct mem_param *mem_params,
930 int num_reg_params, struct reg_param *reg_params,
931 uint32_t buffer_start, uint32_t buffer_size,
932 uint32_t entry_point, uint32_t exit_point, void *arch_info)
934 int retval;
935 int timeout = 0;
937 const uint8_t *buffer_orig = buffer;
939 /* Set up working area. First word is write pointer, second word is read pointer,
940 * rest is fifo data area. */
941 uint32_t wp_addr = buffer_start;
942 uint32_t rp_addr = buffer_start + 4;
943 uint32_t fifo_start_addr = buffer_start + 8;
944 uint32_t fifo_end_addr = buffer_start + buffer_size;
946 uint32_t wp = fifo_start_addr;
947 uint32_t rp = fifo_start_addr;
949 /* validate block_size is 2^n */
950 assert(!block_size || !(block_size & (block_size - 1)));
952 retval = target_write_u32(target, wp_addr, wp);
953 if (retval != ERROR_OK)
954 return retval;
955 retval = target_write_u32(target, rp_addr, rp);
956 if (retval != ERROR_OK)
957 return retval;
959 /* Start up algorithm on target and let it idle while writing the first chunk */
960 retval = target_start_algorithm(target, num_mem_params, mem_params,
961 num_reg_params, reg_params,
962 entry_point,
963 exit_point,
964 arch_info);
966 if (retval != ERROR_OK) {
967 LOG_ERROR("error starting target flash write algorithm");
968 return retval;
971 while (count > 0) {
973 retval = target_read_u32(target, rp_addr, &rp);
974 if (retval != ERROR_OK) {
975 LOG_ERROR("failed to get read pointer");
976 break;
979 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
980 (size_t) (buffer - buffer_orig), count, wp, rp);
982 if (rp == 0) {
983 LOG_ERROR("flash write algorithm aborted by target");
984 retval = ERROR_FLASH_OPERATION_FAILED;
985 break;
988 if (((rp - fifo_start_addr) & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
989 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
990 break;
993 /* Count the number of bytes available in the fifo without
994 * crossing the wrap around. Make sure to not fill it completely,
995 * because that would make wp == rp and that's the empty condition. */
996 uint32_t thisrun_bytes;
997 if (rp > wp)
998 thisrun_bytes = rp - wp - block_size;
999 else if (rp > fifo_start_addr)
1000 thisrun_bytes = fifo_end_addr - wp;
1001 else
1002 thisrun_bytes = fifo_end_addr - wp - block_size;
1004 if (thisrun_bytes == 0) {
1005 /* Throttle polling a bit if transfer is (much) faster than flash
1006 * programming. The exact delay shouldn't matter as long as it's
1007 * less than buffer size / flash speed. This is very unlikely to
1008 * run when using high latency connections such as USB. */
1009 alive_sleep(10);
1011 /* to stop an infinite loop on some targets check and increment a timeout
1012 * this issue was observed on a stellaris using the new ICDI interface */
1013 if (timeout++ >= 500) {
1014 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1015 return ERROR_FLASH_OPERATION_FAILED;
1017 continue;
1020 /* reset our timeout */
1021 timeout = 0;
1023 /* Limit to the amount of data we actually want to write */
1024 if (thisrun_bytes > count * block_size)
1025 thisrun_bytes = count * block_size;
1027 /* Write data to fifo */
1028 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
1029 if (retval != ERROR_OK)
1030 break;
1032 /* Update counters and wrap write pointer */
1033 buffer += thisrun_bytes;
1034 count -= thisrun_bytes / block_size;
1035 wp += thisrun_bytes;
1036 if (wp >= fifo_end_addr)
1037 wp = fifo_start_addr;
1039 /* Store updated write pointer to target */
1040 retval = target_write_u32(target, wp_addr, wp);
1041 if (retval != ERROR_OK)
1042 break;
1045 if (retval != ERROR_OK) {
1046 /* abort flash write algorithm on target */
1047 target_write_u32(target, wp_addr, 0);
1050 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1051 num_reg_params, reg_params,
1052 exit_point,
1053 10000,
1054 arch_info);
1056 if (retval2 != ERROR_OK) {
1057 LOG_ERROR("error waiting for target flash write algorithm");
1058 retval = retval2;
1061 if (retval == ERROR_OK) {
1062 /* check if algorithm set rp = 0 after fifo writer loop finished */
1063 retval = target_read_u32(target, rp_addr, &rp);
1064 if (retval == ERROR_OK && rp == 0) {
1065 LOG_ERROR("flash write algorithm aborted by target");
1066 retval = ERROR_FLASH_OPERATION_FAILED;
1070 return retval;
1073 int target_read_memory(struct target *target,
1074 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1076 if (!target_was_examined(target)) {
1077 LOG_ERROR("Target not examined yet");
1078 return ERROR_FAIL;
1080 if (!target->type->read_memory) {
1081 LOG_ERROR("Target %s doesn't support read_memory", target_name(target));
1082 return ERROR_FAIL;
1084 return target->type->read_memory(target, address, size, count, buffer);
1087 int target_read_phys_memory(struct target *target,
1088 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1090 if (!target_was_examined(target)) {
1091 LOG_ERROR("Target not examined yet");
1092 return ERROR_FAIL;
1094 if (!target->type->read_phys_memory) {
1095 LOG_ERROR("Target %s doesn't support read_phys_memory", target_name(target));
1096 return ERROR_FAIL;
1098 return target->type->read_phys_memory(target, address, size, count, buffer);
1101 int target_write_memory(struct target *target,
1102 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1104 if (!target_was_examined(target)) {
1105 LOG_ERROR("Target not examined yet");
1106 return ERROR_FAIL;
1108 if (!target->type->write_memory) {
1109 LOG_ERROR("Target %s doesn't support write_memory", target_name(target));
1110 return ERROR_FAIL;
1112 return target->type->write_memory(target, address, size, count, buffer);
1115 int target_write_phys_memory(struct target *target,
1116 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1118 if (!target_was_examined(target)) {
1119 LOG_ERROR("Target not examined yet");
1120 return ERROR_FAIL;
1122 if (!target->type->write_phys_memory) {
1123 LOG_ERROR("Target %s doesn't support write_phys_memory", target_name(target));
1124 return ERROR_FAIL;
1126 return target->type->write_phys_memory(target, address, size, count, buffer);
1129 int target_add_breakpoint(struct target *target,
1130 struct breakpoint *breakpoint)
1132 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1133 LOG_WARNING("target %s is not halted (add breakpoint)", target_name(target));
1134 return ERROR_TARGET_NOT_HALTED;
1136 return target->type->add_breakpoint(target, breakpoint);
1139 int target_add_context_breakpoint(struct target *target,
1140 struct breakpoint *breakpoint)
1142 if (target->state != TARGET_HALTED) {
1143 LOG_WARNING("target %s is not halted (add context breakpoint)", target_name(target));
1144 return ERROR_TARGET_NOT_HALTED;
1146 return target->type->add_context_breakpoint(target, breakpoint);
1149 int target_add_hybrid_breakpoint(struct target *target,
1150 struct breakpoint *breakpoint)
1152 if (target->state != TARGET_HALTED) {
1153 LOG_WARNING("target %s is not halted (add hybrid breakpoint)", target_name(target));
1154 return ERROR_TARGET_NOT_HALTED;
1156 return target->type->add_hybrid_breakpoint(target, breakpoint);
1159 int target_remove_breakpoint(struct target *target,
1160 struct breakpoint *breakpoint)
1162 return target->type->remove_breakpoint(target, breakpoint);
1165 int target_add_watchpoint(struct target *target,
1166 struct watchpoint *watchpoint)
1168 if (target->state != TARGET_HALTED) {
1169 LOG_WARNING("target %s is not halted (add watchpoint)", target_name(target));
1170 return ERROR_TARGET_NOT_HALTED;
1172 return target->type->add_watchpoint(target, watchpoint);
1174 int target_remove_watchpoint(struct target *target,
1175 struct watchpoint *watchpoint)
1177 return target->type->remove_watchpoint(target, watchpoint);
1179 int target_hit_watchpoint(struct target *target,
1180 struct watchpoint **hit_watchpoint)
1182 if (target->state != TARGET_HALTED) {
1183 LOG_WARNING("target %s is not halted (hit watchpoint)", target->cmd_name);
1184 return ERROR_TARGET_NOT_HALTED;
1187 if (target->type->hit_watchpoint == NULL) {
1188 /* For backward compatible, if hit_watchpoint is not implemented,
1189 * return ERROR_FAIL such that gdb_server will not take the nonsense
1190 * information. */
1191 return ERROR_FAIL;
1194 return target->type->hit_watchpoint(target, hit_watchpoint);
1197 int target_get_gdb_reg_list(struct target *target,
1198 struct reg **reg_list[], int *reg_list_size,
1199 enum target_register_class reg_class)
1201 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1203 int target_step(struct target *target,
1204 int current, target_addr_t address, int handle_breakpoints)
1206 return target->type->step(target, current, address, handle_breakpoints);
1209 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1211 if (target->state != TARGET_HALTED) {
1212 LOG_WARNING("target %s is not halted (gdb fileio)", target->cmd_name);
1213 return ERROR_TARGET_NOT_HALTED;
1215 return target->type->get_gdb_fileio_info(target, fileio_info);
1218 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1220 if (target->state != TARGET_HALTED) {
1221 LOG_WARNING("target %s is not halted (gdb fileio end)", target->cmd_name);
1222 return ERROR_TARGET_NOT_HALTED;
1224 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1227 int target_profiling(struct target *target, uint32_t *samples,
1228 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1230 if (target->state != TARGET_HALTED) {
1231 LOG_WARNING("target %s is not halted (profiling)", target->cmd_name);
1232 return ERROR_TARGET_NOT_HALTED;
1234 return target->type->profiling(target, samples, max_num_samples,
1235 num_samples, seconds);
1239 * Reset the @c examined flag for the given target.
1240 * Pure paranoia -- targets are zeroed on allocation.
1242 static void target_reset_examined(struct target *target)
1244 target->examined = false;
1247 static int handle_target(void *priv);
1249 static int target_init_one(struct command_context *cmd_ctx,
1250 struct target *target)
1252 target_reset_examined(target);
1254 struct target_type *type = target->type;
1255 if (type->examine == NULL)
1256 type->examine = default_examine;
1258 if (type->check_reset == NULL)
1259 type->check_reset = default_check_reset;
1261 assert(type->init_target != NULL);
1263 int retval = type->init_target(cmd_ctx, target);
1264 if (ERROR_OK != retval) {
1265 LOG_ERROR("target '%s' init failed", target_name(target));
1266 return retval;
1269 /* Sanity-check MMU support ... stub in what we must, to help
1270 * implement it in stages, but warn if we need to do so.
1272 if (type->mmu) {
1273 if (type->virt2phys == NULL) {
1274 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1275 type->virt2phys = identity_virt2phys;
1277 } else {
1278 /* Make sure no-MMU targets all behave the same: make no
1279 * distinction between physical and virtual addresses, and
1280 * ensure that virt2phys() is always an identity mapping.
1282 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1283 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1285 type->mmu = no_mmu;
1286 type->write_phys_memory = type->write_memory;
1287 type->read_phys_memory = type->read_memory;
1288 type->virt2phys = identity_virt2phys;
1291 if (target->type->read_buffer == NULL)
1292 target->type->read_buffer = target_read_buffer_default;
1294 if (target->type->write_buffer == NULL)
1295 target->type->write_buffer = target_write_buffer_default;
1297 if (target->type->get_gdb_fileio_info == NULL)
1298 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1300 if (target->type->gdb_fileio_end == NULL)
1301 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1303 if (target->type->profiling == NULL)
1304 target->type->profiling = target_profiling_default;
1306 return ERROR_OK;
1309 static int target_init(struct command_context *cmd_ctx)
1311 struct target *target;
1312 int retval;
1314 for (target = all_targets; target; target = target->next) {
1315 retval = target_init_one(cmd_ctx, target);
1316 if (ERROR_OK != retval)
1317 return retval;
1320 if (!all_targets)
1321 return ERROR_OK;
1323 retval = target_register_user_commands(cmd_ctx);
1324 if (ERROR_OK != retval)
1325 return retval;
1327 retval = target_register_timer_callback(&handle_target,
1328 polling_interval, 1, cmd_ctx->interp);
1329 if (ERROR_OK != retval)
1330 return retval;
1332 return ERROR_OK;
1335 COMMAND_HANDLER(handle_target_init_command)
1337 int retval;
1339 if (CMD_ARGC != 0)
1340 return ERROR_COMMAND_SYNTAX_ERROR;
1342 static bool target_initialized;
1343 if (target_initialized) {
1344 LOG_INFO("'target init' has already been called");
1345 return ERROR_OK;
1347 target_initialized = true;
1349 retval = command_run_line(CMD_CTX, "init_targets");
1350 if (ERROR_OK != retval)
1351 return retval;
1353 retval = command_run_line(CMD_CTX, "init_target_events");
1354 if (ERROR_OK != retval)
1355 return retval;
1357 retval = command_run_line(CMD_CTX, "init_board");
1358 if (ERROR_OK != retval)
1359 return retval;
1361 LOG_DEBUG("Initializing targets...");
1362 return target_init(CMD_CTX);
1365 int target_register_event_callback(int (*callback)(struct target *target,
1366 enum target_event event, void *priv), void *priv)
1368 struct target_event_callback **callbacks_p = &target_event_callbacks;
1370 if (callback == NULL)
1371 return ERROR_COMMAND_SYNTAX_ERROR;
1373 if (*callbacks_p) {
1374 while ((*callbacks_p)->next)
1375 callbacks_p = &((*callbacks_p)->next);
1376 callbacks_p = &((*callbacks_p)->next);
1379 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1380 (*callbacks_p)->callback = callback;
1381 (*callbacks_p)->priv = priv;
1382 (*callbacks_p)->next = NULL;
1384 return ERROR_OK;
1387 int target_register_reset_callback(int (*callback)(struct target *target,
1388 enum target_reset_mode reset_mode, void *priv), void *priv)
1390 struct target_reset_callback *entry;
1392 if (callback == NULL)
1393 return ERROR_COMMAND_SYNTAX_ERROR;
1395 entry = malloc(sizeof(struct target_reset_callback));
1396 if (entry == NULL) {
1397 LOG_ERROR("error allocating buffer for reset callback entry");
1398 return ERROR_COMMAND_SYNTAX_ERROR;
1401 entry->callback = callback;
1402 entry->priv = priv;
1403 list_add(&entry->list, &target_reset_callback_list);
1406 return ERROR_OK;
1409 int target_register_trace_callback(int (*callback)(struct target *target,
1410 size_t len, uint8_t *data, void *priv), void *priv)
1412 struct target_trace_callback *entry;
1414 if (callback == NULL)
1415 return ERROR_COMMAND_SYNTAX_ERROR;
1417 entry = malloc(sizeof(struct target_trace_callback));
1418 if (entry == NULL) {
1419 LOG_ERROR("error allocating buffer for trace callback entry");
1420 return ERROR_COMMAND_SYNTAX_ERROR;
1423 entry->callback = callback;
1424 entry->priv = priv;
1425 list_add(&entry->list, &target_trace_callback_list);
1428 return ERROR_OK;
1431 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1433 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1435 if (callback == NULL)
1436 return ERROR_COMMAND_SYNTAX_ERROR;
1438 if (*callbacks_p) {
1439 while ((*callbacks_p)->next)
1440 callbacks_p = &((*callbacks_p)->next);
1441 callbacks_p = &((*callbacks_p)->next);
1444 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1445 (*callbacks_p)->callback = callback;
1446 (*callbacks_p)->periodic = periodic;
1447 (*callbacks_p)->time_ms = time_ms;
1448 (*callbacks_p)->removed = false;
1450 gettimeofday(&(*callbacks_p)->when, NULL);
1451 timeval_add_time(&(*callbacks_p)->when, 0, time_ms * 1000);
1453 (*callbacks_p)->priv = priv;
1454 (*callbacks_p)->next = NULL;
1456 return ERROR_OK;
1459 int target_unregister_event_callback(int (*callback)(struct target *target,
1460 enum target_event event, void *priv), void *priv)
1462 struct target_event_callback **p = &target_event_callbacks;
1463 struct target_event_callback *c = target_event_callbacks;
1465 if (callback == NULL)
1466 return ERROR_COMMAND_SYNTAX_ERROR;
1468 while (c) {
1469 struct target_event_callback *next = c->next;
1470 if ((c->callback == callback) && (c->priv == priv)) {
1471 *p = next;
1472 free(c);
1473 return ERROR_OK;
1474 } else
1475 p = &(c->next);
1476 c = next;
1479 return ERROR_OK;
1482 int target_unregister_reset_callback(int (*callback)(struct target *target,
1483 enum target_reset_mode reset_mode, void *priv), void *priv)
1485 struct target_reset_callback *entry;
1487 if (callback == NULL)
1488 return ERROR_COMMAND_SYNTAX_ERROR;
1490 list_for_each_entry(entry, &target_reset_callback_list, list) {
1491 if (entry->callback == callback && entry->priv == priv) {
1492 list_del(&entry->list);
1493 free(entry);
1494 break;
1498 return ERROR_OK;
1501 int target_unregister_trace_callback(int (*callback)(struct target *target,
1502 size_t len, uint8_t *data, void *priv), void *priv)
1504 struct target_trace_callback *entry;
1506 if (callback == NULL)
1507 return ERROR_COMMAND_SYNTAX_ERROR;
1509 list_for_each_entry(entry, &target_trace_callback_list, list) {
1510 if (entry->callback == callback && entry->priv == priv) {
1511 list_del(&entry->list);
1512 free(entry);
1513 break;
1517 return ERROR_OK;
1520 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1522 if (callback == NULL)
1523 return ERROR_COMMAND_SYNTAX_ERROR;
1525 for (struct target_timer_callback *c = target_timer_callbacks;
1526 c; c = c->next) {
1527 if ((c->callback == callback) && (c->priv == priv)) {
1528 c->removed = true;
1529 return ERROR_OK;
1533 return ERROR_FAIL;
1536 int target_call_event_callbacks(struct target *target, enum target_event event)
1538 struct target_event_callback *callback = target_event_callbacks;
1539 struct target_event_callback *next_callback;
1541 if (event == TARGET_EVENT_HALTED) {
1542 /* execute early halted first */
1543 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1546 LOG_DEBUG("target event %i (%s)", event,
1547 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1549 target_handle_event(target, event);
1551 while (callback) {
1552 next_callback = callback->next;
1553 callback->callback(target, event, callback->priv);
1554 callback = next_callback;
1557 return ERROR_OK;
1560 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1562 struct target_reset_callback *callback;
1564 LOG_DEBUG("target reset %i (%s)", reset_mode,
1565 Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name);
1567 list_for_each_entry(callback, &target_reset_callback_list, list)
1568 callback->callback(target, reset_mode, callback->priv);
1570 return ERROR_OK;
1573 int target_call_trace_callbacks(struct target *target, size_t len, uint8_t *data)
1575 struct target_trace_callback *callback;
1577 list_for_each_entry(callback, &target_trace_callback_list, list)
1578 callback->callback(target, len, data, callback->priv);
1580 return ERROR_OK;
1583 static int target_timer_callback_periodic_restart(
1584 struct target_timer_callback *cb, struct timeval *now)
1586 cb->when = *now;
1587 timeval_add_time(&cb->when, 0, cb->time_ms * 1000L);
1588 return ERROR_OK;
1591 static int target_call_timer_callback(struct target_timer_callback *cb,
1592 struct timeval *now)
1594 cb->callback(cb->priv);
1596 if (cb->periodic)
1597 return target_timer_callback_periodic_restart(cb, now);
1599 return target_unregister_timer_callback(cb->callback, cb->priv);
1602 static int target_call_timer_callbacks_check_time(int checktime)
1604 static bool callback_processing;
1606 /* Do not allow nesting */
1607 if (callback_processing)
1608 return ERROR_OK;
1610 callback_processing = true;
1612 keep_alive();
1614 struct timeval now;
1615 gettimeofday(&now, NULL);
1617 /* Store an address of the place containing a pointer to the
1618 * next item; initially, that's a standalone "root of the
1619 * list" variable. */
1620 struct target_timer_callback **callback = &target_timer_callbacks;
1621 while (*callback) {
1622 if ((*callback)->removed) {
1623 struct target_timer_callback *p = *callback;
1624 *callback = (*callback)->next;
1625 free(p);
1626 continue;
1629 bool call_it = (*callback)->callback &&
1630 ((!checktime && (*callback)->periodic) ||
1631 timeval_compare(&now, &(*callback)->when) >= 0);
1633 if (call_it)
1634 target_call_timer_callback(*callback, &now);
1636 callback = &(*callback)->next;
1639 callback_processing = false;
1640 return ERROR_OK;
1643 int target_call_timer_callbacks(void)
1645 return target_call_timer_callbacks_check_time(1);
1648 /* invoke periodic callbacks immediately */
1649 int target_call_timer_callbacks_now(void)
1651 return target_call_timer_callbacks_check_time(0);
1654 /* Prints the working area layout for debug purposes */
1655 static void print_wa_layout(struct target *target)
1657 struct working_area *c = target->working_areas;
1659 while (c) {
1660 LOG_DEBUG("%c%c " TARGET_ADDR_FMT "-" TARGET_ADDR_FMT " (%" PRIu32 " bytes)",
1661 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1662 c->address, c->address + c->size - 1, c->size);
1663 c = c->next;
1667 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1668 static void target_split_working_area(struct working_area *area, uint32_t size)
1670 assert(area->free); /* Shouldn't split an allocated area */
1671 assert(size <= area->size); /* Caller should guarantee this */
1673 /* Split only if not already the right size */
1674 if (size < area->size) {
1675 struct working_area *new_wa = malloc(sizeof(*new_wa));
1677 if (new_wa == NULL)
1678 return;
1680 new_wa->next = area->next;
1681 new_wa->size = area->size - size;
1682 new_wa->address = area->address + size;
1683 new_wa->backup = NULL;
1684 new_wa->user = NULL;
1685 new_wa->free = true;
1687 area->next = new_wa;
1688 area->size = size;
1690 /* If backup memory was allocated to this area, it has the wrong size
1691 * now so free it and it will be reallocated if/when needed */
1692 if (area->backup) {
1693 free(area->backup);
1694 area->backup = NULL;
1699 /* Merge all adjacent free areas into one */
1700 static void target_merge_working_areas(struct target *target)
1702 struct working_area *c = target->working_areas;
1704 while (c && c->next) {
1705 assert(c->next->address == c->address + c->size); /* This is an invariant */
1707 /* Find two adjacent free areas */
1708 if (c->free && c->next->free) {
1709 /* Merge the last into the first */
1710 c->size += c->next->size;
1712 /* Remove the last */
1713 struct working_area *to_be_freed = c->next;
1714 c->next = c->next->next;
1715 if (to_be_freed->backup)
1716 free(to_be_freed->backup);
1717 free(to_be_freed);
1719 /* If backup memory was allocated to the remaining area, it's has
1720 * the wrong size now */
1721 if (c->backup) {
1722 free(c->backup);
1723 c->backup = NULL;
1725 } else {
1726 c = c->next;
1731 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1733 /* Reevaluate working area address based on MMU state*/
1734 if (target->working_areas == NULL) {
1735 int retval;
1736 int enabled;
1738 retval = target->type->mmu(target, &enabled);
1739 if (retval != ERROR_OK)
1740 return retval;
1742 if (!enabled) {
1743 if (target->working_area_phys_spec) {
1744 LOG_DEBUG("MMU disabled, using physical "
1745 "address for working memory " TARGET_ADDR_FMT,
1746 target->working_area_phys);
1747 target->working_area = target->working_area_phys;
1748 } else {
1749 LOG_ERROR("No working memory available. "
1750 "Specify -work-area-phys to target.");
1751 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1753 } else {
1754 if (target->working_area_virt_spec) {
1755 LOG_DEBUG("MMU enabled, using virtual "
1756 "address for working memory " TARGET_ADDR_FMT,
1757 target->working_area_virt);
1758 target->working_area = target->working_area_virt;
1759 } else {
1760 LOG_ERROR("No working memory available. "
1761 "Specify -work-area-virt to target.");
1762 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1766 /* Set up initial working area on first call */
1767 struct working_area *new_wa = malloc(sizeof(*new_wa));
1768 if (new_wa) {
1769 new_wa->next = NULL;
1770 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1771 new_wa->address = target->working_area;
1772 new_wa->backup = NULL;
1773 new_wa->user = NULL;
1774 new_wa->free = true;
1777 target->working_areas = new_wa;
1780 /* only allocate multiples of 4 byte */
1781 if (size % 4)
1782 size = (size + 3) & (~3UL);
1784 struct working_area *c = target->working_areas;
1786 /* Find the first large enough working area */
1787 while (c) {
1788 if (c->free && c->size >= size)
1789 break;
1790 c = c->next;
1793 if (c == NULL)
1794 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1796 /* Split the working area into the requested size */
1797 target_split_working_area(c, size);
1799 LOG_DEBUG("allocated new working area of %" PRIu32 " bytes at address " TARGET_ADDR_FMT,
1800 size, c->address);
1802 if (target->backup_working_area) {
1803 if (c->backup == NULL) {
1804 c->backup = malloc(c->size);
1805 if (c->backup == NULL)
1806 return ERROR_FAIL;
1809 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1810 if (retval != ERROR_OK)
1811 return retval;
1814 /* mark as used, and return the new (reused) area */
1815 c->free = false;
1816 *area = c;
1818 /* user pointer */
1819 c->user = area;
1821 print_wa_layout(target);
1823 return ERROR_OK;
1826 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1828 int retval;
1830 retval = target_alloc_working_area_try(target, size, area);
1831 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1832 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1833 return retval;
1837 static int target_restore_working_area(struct target *target, struct working_area *area)
1839 int retval = ERROR_OK;
1841 if (target->backup_working_area && area->backup != NULL) {
1842 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1843 if (retval != ERROR_OK)
1844 LOG_ERROR("failed to restore %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
1845 area->size, area->address);
1848 return retval;
1851 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1852 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1854 int retval = ERROR_OK;
1856 if (area->free)
1857 return retval;
1859 if (restore) {
1860 retval = target_restore_working_area(target, area);
1861 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1862 if (retval != ERROR_OK)
1863 return retval;
1866 area->free = true;
1868 LOG_DEBUG("freed %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
1869 area->size, area->address);
1871 /* mark user pointer invalid */
1872 /* TODO: Is this really safe? It points to some previous caller's memory.
1873 * How could we know that the area pointer is still in that place and not
1874 * some other vital data? What's the purpose of this, anyway? */
1875 *area->user = NULL;
1876 area->user = NULL;
1878 target_merge_working_areas(target);
1880 print_wa_layout(target);
1882 return retval;
1885 int target_free_working_area(struct target *target, struct working_area *area)
1887 return target_free_working_area_restore(target, area, 1);
1890 static void target_destroy(struct target *target)
1892 if (target->type->deinit_target)
1893 target->type->deinit_target(target);
1895 free(target->type);
1896 free(target->trace_info);
1897 free(target->cmd_name);
1898 free(target);
1901 void target_quit(void)
1903 struct target_event_callback *pe = target_event_callbacks;
1904 while (pe) {
1905 struct target_event_callback *t = pe->next;
1906 free(pe);
1907 pe = t;
1909 target_event_callbacks = NULL;
1911 struct target_timer_callback *pt = target_timer_callbacks;
1912 while (pt) {
1913 struct target_timer_callback *t = pt->next;
1914 free(pt);
1915 pt = t;
1917 target_timer_callbacks = NULL;
1919 for (struct target *target = all_targets; target;) {
1920 struct target *tmp;
1922 tmp = target->next;
1923 target_destroy(target);
1924 target = tmp;
1927 all_targets = NULL;
1930 /* free resources and restore memory, if restoring memory fails,
1931 * free up resources anyway
1933 static void target_free_all_working_areas_restore(struct target *target, int restore)
1935 struct working_area *c = target->working_areas;
1937 LOG_DEBUG("freeing all working areas");
1939 /* Loop through all areas, restoring the allocated ones and marking them as free */
1940 while (c) {
1941 if (!c->free) {
1942 if (restore)
1943 target_restore_working_area(target, c);
1944 c->free = true;
1945 *c->user = NULL; /* Same as above */
1946 c->user = NULL;
1948 c = c->next;
1951 /* Run a merge pass to combine all areas into one */
1952 target_merge_working_areas(target);
1954 print_wa_layout(target);
1957 void target_free_all_working_areas(struct target *target)
1959 target_free_all_working_areas_restore(target, 1);
1962 /* Find the largest number of bytes that can be allocated */
1963 uint32_t target_get_working_area_avail(struct target *target)
1965 struct working_area *c = target->working_areas;
1966 uint32_t max_size = 0;
1968 if (c == NULL)
1969 return target->working_area_size;
1971 while (c) {
1972 if (c->free && max_size < c->size)
1973 max_size = c->size;
1975 c = c->next;
1978 return max_size;
1981 int target_arch_state(struct target *target)
1983 int retval;
1984 if (target == NULL) {
1985 LOG_WARNING("No target has been configured");
1986 return ERROR_OK;
1989 if (target->state != TARGET_HALTED)
1990 return ERROR_OK;
1992 retval = target->type->arch_state(target);
1993 return retval;
1996 static int target_get_gdb_fileio_info_default(struct target *target,
1997 struct gdb_fileio_info *fileio_info)
1999 /* If target does not support semi-hosting function, target
2000 has no need to provide .get_gdb_fileio_info callback.
2001 It just return ERROR_FAIL and gdb_server will return "Txx"
2002 as target halted every time. */
2003 return ERROR_FAIL;
2006 static int target_gdb_fileio_end_default(struct target *target,
2007 int retcode, int fileio_errno, bool ctrl_c)
2009 return ERROR_OK;
2012 static int target_profiling_default(struct target *target, uint32_t *samples,
2013 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
2015 struct timeval timeout, now;
2017 gettimeofday(&timeout, NULL);
2018 timeval_add_time(&timeout, seconds, 0);
2020 LOG_INFO("Starting profiling. Halting and resuming the"
2021 " target as often as we can...");
2023 uint32_t sample_count = 0;
2024 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2025 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
2027 int retval = ERROR_OK;
2028 for (;;) {
2029 target_poll(target);
2030 if (target->state == TARGET_HALTED) {
2031 uint32_t t = buf_get_u32(reg->value, 0, 32);
2032 samples[sample_count++] = t;
2033 /* current pc, addr = 0, do not handle breakpoints, not debugging */
2034 retval = target_resume(target, 1, 0, 0, 0);
2035 target_poll(target);
2036 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2037 } else if (target->state == TARGET_RUNNING) {
2038 /* We want to quickly sample the PC. */
2039 retval = target_halt(target);
2040 } else {
2041 LOG_INFO("Target not halted or running");
2042 retval = ERROR_OK;
2043 break;
2046 if (retval != ERROR_OK)
2047 break;
2049 gettimeofday(&now, NULL);
2050 if ((sample_count >= max_num_samples) || timeval_compare(&now, &timeout) >= 0) {
2051 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2052 break;
2056 *num_samples = sample_count;
2057 return retval;
2060 /* Single aligned words are guaranteed to use 16 or 32 bit access
2061 * mode respectively, otherwise data is handled as quickly as
2062 * possible
2064 int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
2066 LOG_DEBUG("writing buffer of %" PRIi32 " byte at " TARGET_ADDR_FMT,
2067 size, address);
2069 if (!target_was_examined(target)) {
2070 LOG_ERROR("Target not examined yet");
2071 return ERROR_FAIL;
2074 if (size == 0)
2075 return ERROR_OK;
2077 if ((address + size - 1) < address) {
2078 /* GDB can request this when e.g. PC is 0xfffffffc */
2079 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2080 address,
2081 size);
2082 return ERROR_FAIL;
2085 return target->type->write_buffer(target, address, size, buffer);
2088 static int target_write_buffer_default(struct target *target,
2089 target_addr_t address, uint32_t count, const uint8_t *buffer)
2091 uint32_t size;
2093 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2094 * will have something to do with the size we leave to it. */
2095 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2096 if (address & size) {
2097 int retval = target_write_memory(target, address, size, 1, buffer);
2098 if (retval != ERROR_OK)
2099 return retval;
2100 address += size;
2101 count -= size;
2102 buffer += size;
2106 /* Write the data with as large access size as possible. */
2107 for (; size > 0; size /= 2) {
2108 uint32_t aligned = count - count % size;
2109 if (aligned > 0) {
2110 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2111 if (retval != ERROR_OK)
2112 return retval;
2113 address += aligned;
2114 count -= aligned;
2115 buffer += aligned;
2119 return ERROR_OK;
2122 /* Single aligned words are guaranteed to use 16 or 32 bit access
2123 * mode respectively, otherwise data is handled as quickly as
2124 * possible
2126 int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
2128 LOG_DEBUG("reading buffer of %" PRIi32 " byte at " TARGET_ADDR_FMT,
2129 size, address);
2131 if (!target_was_examined(target)) {
2132 LOG_ERROR("Target not examined yet");
2133 return ERROR_FAIL;
2136 if (size == 0)
2137 return ERROR_OK;
2139 if ((address + size - 1) < address) {
2140 /* GDB can request this when e.g. PC is 0xfffffffc */
2141 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2142 address,
2143 size);
2144 return ERROR_FAIL;
2147 return target->type->read_buffer(target, address, size, buffer);
2150 static int target_read_buffer_default(struct target *target, target_addr_t address, uint32_t count, uint8_t *buffer)
2152 uint32_t size;
2154 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2155 * will have something to do with the size we leave to it. */
2156 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2157 if (address & size) {
2158 int retval = target_read_memory(target, address, size, 1, buffer);
2159 if (retval != ERROR_OK)
2160 return retval;
2161 address += size;
2162 count -= size;
2163 buffer += size;
2167 /* Read the data with as large access size as possible. */
2168 for (; size > 0; size /= 2) {
2169 uint32_t aligned = count - count % size;
2170 if (aligned > 0) {
2171 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2172 if (retval != ERROR_OK)
2173 return retval;
2174 address += aligned;
2175 count -= aligned;
2176 buffer += aligned;
2180 return ERROR_OK;
2183 int target_checksum_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t* crc)
2185 uint8_t *buffer;
2186 int retval;
2187 uint32_t i;
2188 uint32_t checksum = 0;
2189 if (!target_was_examined(target)) {
2190 LOG_ERROR("Target not examined yet");
2191 return ERROR_FAIL;
2194 retval = target->type->checksum_memory(target, address, size, &checksum);
2195 if (retval != ERROR_OK) {
2196 buffer = malloc(size);
2197 if (buffer == NULL) {
2198 LOG_ERROR("error allocating buffer for section (%" PRId32 " bytes)", size);
2199 return ERROR_COMMAND_SYNTAX_ERROR;
2201 retval = target_read_buffer(target, address, size, buffer);
2202 if (retval != ERROR_OK) {
2203 free(buffer);
2204 return retval;
2207 /* convert to target endianness */
2208 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2209 uint32_t target_data;
2210 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2211 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2214 retval = image_calculate_checksum(buffer, size, &checksum);
2215 free(buffer);
2218 *crc = checksum;
2220 return retval;
2223 int target_blank_check_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t* blank,
2224 uint8_t erased_value)
2226 int retval;
2227 if (!target_was_examined(target)) {
2228 LOG_ERROR("Target not examined yet");
2229 return ERROR_FAIL;
2232 if (target->type->blank_check_memory == 0)
2233 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2235 retval = target->type->blank_check_memory(target, address, size, blank, erased_value);
2237 return retval;
2240 int target_read_u64(struct target *target, target_addr_t address, uint64_t *value)
2242 uint8_t value_buf[8];
2243 if (!target_was_examined(target)) {
2244 LOG_ERROR("Target not examined yet");
2245 return ERROR_FAIL;
2248 int retval = target_read_memory(target, address, 8, 1, value_buf);
2250 if (retval == ERROR_OK) {
2251 *value = target_buffer_get_u64(target, value_buf);
2252 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2253 address,
2254 *value);
2255 } else {
2256 *value = 0x0;
2257 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2258 address);
2261 return retval;
2264 int target_read_u32(struct target *target, target_addr_t address, uint32_t *value)
2266 uint8_t value_buf[4];
2267 if (!target_was_examined(target)) {
2268 LOG_ERROR("Target not examined yet");
2269 return ERROR_FAIL;
2272 int retval = target_read_memory(target, address, 4, 1, value_buf);
2274 if (retval == ERROR_OK) {
2275 *value = target_buffer_get_u32(target, value_buf);
2276 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2277 address,
2278 *value);
2279 } else {
2280 *value = 0x0;
2281 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2282 address);
2285 return retval;
2288 int target_read_u16(struct target *target, target_addr_t address, uint16_t *value)
2290 uint8_t value_buf[2];
2291 if (!target_was_examined(target)) {
2292 LOG_ERROR("Target not examined yet");
2293 return ERROR_FAIL;
2296 int retval = target_read_memory(target, address, 2, 1, value_buf);
2298 if (retval == ERROR_OK) {
2299 *value = target_buffer_get_u16(target, value_buf);
2300 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%4.4" PRIx16,
2301 address,
2302 *value);
2303 } else {
2304 *value = 0x0;
2305 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2306 address);
2309 return retval;
2312 int target_read_u8(struct target *target, target_addr_t address, uint8_t *value)
2314 if (!target_was_examined(target)) {
2315 LOG_ERROR("Target not examined yet");
2316 return ERROR_FAIL;
2319 int retval = target_read_memory(target, address, 1, 1, value);
2321 if (retval == ERROR_OK) {
2322 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2323 address,
2324 *value);
2325 } else {
2326 *value = 0x0;
2327 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2328 address);
2331 return retval;
2334 int target_write_u64(struct target *target, target_addr_t address, uint64_t value)
2336 int retval;
2337 uint8_t value_buf[8];
2338 if (!target_was_examined(target)) {
2339 LOG_ERROR("Target not examined yet");
2340 return ERROR_FAIL;
2343 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2344 address,
2345 value);
2347 target_buffer_set_u64(target, value_buf, value);
2348 retval = target_write_memory(target, address, 8, 1, value_buf);
2349 if (retval != ERROR_OK)
2350 LOG_DEBUG("failed: %i", retval);
2352 return retval;
2355 int target_write_u32(struct target *target, target_addr_t address, uint32_t value)
2357 int retval;
2358 uint8_t value_buf[4];
2359 if (!target_was_examined(target)) {
2360 LOG_ERROR("Target not examined yet");
2361 return ERROR_FAIL;
2364 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2365 address,
2366 value);
2368 target_buffer_set_u32(target, value_buf, value);
2369 retval = target_write_memory(target, address, 4, 1, value_buf);
2370 if (retval != ERROR_OK)
2371 LOG_DEBUG("failed: %i", retval);
2373 return retval;
2376 int target_write_u16(struct target *target, target_addr_t address, uint16_t value)
2378 int retval;
2379 uint8_t value_buf[2];
2380 if (!target_was_examined(target)) {
2381 LOG_ERROR("Target not examined yet");
2382 return ERROR_FAIL;
2385 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2386 address,
2387 value);
2389 target_buffer_set_u16(target, value_buf, value);
2390 retval = target_write_memory(target, address, 2, 1, value_buf);
2391 if (retval != ERROR_OK)
2392 LOG_DEBUG("failed: %i", retval);
2394 return retval;
2397 int target_write_u8(struct target *target, target_addr_t address, uint8_t value)
2399 int retval;
2400 if (!target_was_examined(target)) {
2401 LOG_ERROR("Target not examined yet");
2402 return ERROR_FAIL;
2405 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2406 address, value);
2408 retval = target_write_memory(target, address, 1, 1, &value);
2409 if (retval != ERROR_OK)
2410 LOG_DEBUG("failed: %i", retval);
2412 return retval;
2415 int target_write_phys_u64(struct target *target, target_addr_t address, uint64_t value)
2417 int retval;
2418 uint8_t value_buf[8];
2419 if (!target_was_examined(target)) {
2420 LOG_ERROR("Target not examined yet");
2421 return ERROR_FAIL;
2424 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2425 address,
2426 value);
2428 target_buffer_set_u64(target, value_buf, value);
2429 retval = target_write_phys_memory(target, address, 8, 1, value_buf);
2430 if (retval != ERROR_OK)
2431 LOG_DEBUG("failed: %i", retval);
2433 return retval;
2436 int target_write_phys_u32(struct target *target, target_addr_t address, uint32_t value)
2438 int retval;
2439 uint8_t value_buf[4];
2440 if (!target_was_examined(target)) {
2441 LOG_ERROR("Target not examined yet");
2442 return ERROR_FAIL;
2445 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2446 address,
2447 value);
2449 target_buffer_set_u32(target, value_buf, value);
2450 retval = target_write_phys_memory(target, address, 4, 1, value_buf);
2451 if (retval != ERROR_OK)
2452 LOG_DEBUG("failed: %i", retval);
2454 return retval;
2457 int target_write_phys_u16(struct target *target, target_addr_t address, uint16_t value)
2459 int retval;
2460 uint8_t value_buf[2];
2461 if (!target_was_examined(target)) {
2462 LOG_ERROR("Target not examined yet");
2463 return ERROR_FAIL;
2466 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2467 address,
2468 value);
2470 target_buffer_set_u16(target, value_buf, value);
2471 retval = target_write_phys_memory(target, address, 2, 1, value_buf);
2472 if (retval != ERROR_OK)
2473 LOG_DEBUG("failed: %i", retval);
2475 return retval;
2478 int target_write_phys_u8(struct target *target, target_addr_t address, uint8_t value)
2480 int retval;
2481 if (!target_was_examined(target)) {
2482 LOG_ERROR("Target not examined yet");
2483 return ERROR_FAIL;
2486 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2487 address, value);
2489 retval = target_write_phys_memory(target, address, 1, 1, &value);
2490 if (retval != ERROR_OK)
2491 LOG_DEBUG("failed: %i", retval);
2493 return retval;
2496 static int find_target(struct command_context *cmd_ctx, const char *name)
2498 struct target *target = get_target(name);
2499 if (target == NULL) {
2500 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2501 return ERROR_FAIL;
2503 if (!target->tap->enabled) {
2504 LOG_USER("Target: TAP %s is disabled, "
2505 "can't be the current target\n",
2506 target->tap->dotted_name);
2507 return ERROR_FAIL;
2510 cmd_ctx->current_target = target;
2511 if (cmd_ctx->current_target_override)
2512 cmd_ctx->current_target_override = target;
2514 return ERROR_OK;
2518 COMMAND_HANDLER(handle_targets_command)
2520 int retval = ERROR_OK;
2521 if (CMD_ARGC == 1) {
2522 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2523 if (retval == ERROR_OK) {
2524 /* we're done! */
2525 return retval;
2529 struct target *target = all_targets;
2530 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2531 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2532 while (target) {
2533 const char *state;
2534 char marker = ' ';
2536 if (target->tap->enabled)
2537 state = target_state_name(target);
2538 else
2539 state = "tap-disabled";
2541 if (CMD_CTX->current_target == target)
2542 marker = '*';
2544 /* keep columns lined up to match the headers above */
2545 command_print(CMD_CTX,
2546 "%2d%c %-18s %-10s %-6s %-18s %s",
2547 target->target_number,
2548 marker,
2549 target_name(target),
2550 target_type_name(target),
2551 Jim_Nvp_value2name_simple(nvp_target_endian,
2552 target->endianness)->name,
2553 target->tap->dotted_name,
2554 state);
2555 target = target->next;
2558 return retval;
2561 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2563 static int powerDropout;
2564 static int srstAsserted;
2566 static int runPowerRestore;
2567 static int runPowerDropout;
2568 static int runSrstAsserted;
2569 static int runSrstDeasserted;
2571 static int sense_handler(void)
2573 static int prevSrstAsserted;
2574 static int prevPowerdropout;
2576 int retval = jtag_power_dropout(&powerDropout);
2577 if (retval != ERROR_OK)
2578 return retval;
2580 int powerRestored;
2581 powerRestored = prevPowerdropout && !powerDropout;
2582 if (powerRestored)
2583 runPowerRestore = 1;
2585 int64_t current = timeval_ms();
2586 static int64_t lastPower;
2587 bool waitMore = lastPower + 2000 > current;
2588 if (powerDropout && !waitMore) {
2589 runPowerDropout = 1;
2590 lastPower = current;
2593 retval = jtag_srst_asserted(&srstAsserted);
2594 if (retval != ERROR_OK)
2595 return retval;
2597 int srstDeasserted;
2598 srstDeasserted = prevSrstAsserted && !srstAsserted;
2600 static int64_t lastSrst;
2601 waitMore = lastSrst + 2000 > current;
2602 if (srstDeasserted && !waitMore) {
2603 runSrstDeasserted = 1;
2604 lastSrst = current;
2607 if (!prevSrstAsserted && srstAsserted)
2608 runSrstAsserted = 1;
2610 prevSrstAsserted = srstAsserted;
2611 prevPowerdropout = powerDropout;
2613 if (srstDeasserted || powerRestored) {
2614 /* Other than logging the event we can't do anything here.
2615 * Issuing a reset is a particularly bad idea as we might
2616 * be inside a reset already.
2620 return ERROR_OK;
2623 /* process target state changes */
2624 static int handle_target(void *priv)
2626 Jim_Interp *interp = (Jim_Interp *)priv;
2627 int retval = ERROR_OK;
2629 if (!is_jtag_poll_safe()) {
2630 /* polling is disabled currently */
2631 return ERROR_OK;
2634 /* we do not want to recurse here... */
2635 static int recursive;
2636 if (!recursive) {
2637 recursive = 1;
2638 sense_handler();
2639 /* danger! running these procedures can trigger srst assertions and power dropouts.
2640 * We need to avoid an infinite loop/recursion here and we do that by
2641 * clearing the flags after running these events.
2643 int did_something = 0;
2644 if (runSrstAsserted) {
2645 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2646 Jim_Eval(interp, "srst_asserted");
2647 did_something = 1;
2649 if (runSrstDeasserted) {
2650 Jim_Eval(interp, "srst_deasserted");
2651 did_something = 1;
2653 if (runPowerDropout) {
2654 LOG_INFO("Power dropout detected, running power_dropout proc.");
2655 Jim_Eval(interp, "power_dropout");
2656 did_something = 1;
2658 if (runPowerRestore) {
2659 Jim_Eval(interp, "power_restore");
2660 did_something = 1;
2663 if (did_something) {
2664 /* clear detect flags */
2665 sense_handler();
2668 /* clear action flags */
2670 runSrstAsserted = 0;
2671 runSrstDeasserted = 0;
2672 runPowerRestore = 0;
2673 runPowerDropout = 0;
2675 recursive = 0;
2678 /* Poll targets for state changes unless that's globally disabled.
2679 * Skip targets that are currently disabled.
2681 for (struct target *target = all_targets;
2682 is_jtag_poll_safe() && target;
2683 target = target->next) {
2685 if (!target_was_examined(target))
2686 continue;
2688 if (!target->tap->enabled)
2689 continue;
2691 if (target->backoff.times > target->backoff.count) {
2692 /* do not poll this time as we failed previously */
2693 target->backoff.count++;
2694 continue;
2696 target->backoff.count = 0;
2698 /* only poll target if we've got power and srst isn't asserted */
2699 if (!powerDropout && !srstAsserted) {
2700 /* polling may fail silently until the target has been examined */
2701 retval = target_poll(target);
2702 if (retval != ERROR_OK) {
2703 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2704 if (target->backoff.times * polling_interval < 5000) {
2705 target->backoff.times *= 2;
2706 target->backoff.times++;
2709 /* Tell GDB to halt the debugger. This allows the user to
2710 * run monitor commands to handle the situation.
2712 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2714 if (target->backoff.times > 0) {
2715 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
2716 target_reset_examined(target);
2717 retval = target_examine_one(target);
2718 /* Target examination could have failed due to unstable connection,
2719 * but we set the examined flag anyway to repoll it later */
2720 if (retval != ERROR_OK) {
2721 target->examined = true;
2722 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
2723 target->backoff.times * polling_interval);
2724 return retval;
2728 /* Since we succeeded, we reset backoff count */
2729 target->backoff.times = 0;
2733 return retval;
2736 COMMAND_HANDLER(handle_reg_command)
2738 struct target *target;
2739 struct reg *reg = NULL;
2740 unsigned count = 0;
2741 char *value;
2743 LOG_DEBUG("-");
2745 target = get_current_target(CMD_CTX);
2747 /* list all available registers for the current target */
2748 if (CMD_ARGC == 0) {
2749 struct reg_cache *cache = target->reg_cache;
2751 count = 0;
2752 while (cache) {
2753 unsigned i;
2755 command_print(CMD_CTX, "===== %s", cache->name);
2757 for (i = 0, reg = cache->reg_list;
2758 i < cache->num_regs;
2759 i++, reg++, count++) {
2760 /* only print cached values if they are valid */
2761 if (reg->valid) {
2762 value = buf_to_str(reg->value,
2763 reg->size, 16);
2764 command_print(CMD_CTX,
2765 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2766 count, reg->name,
2767 reg->size, value,
2768 reg->dirty
2769 ? " (dirty)"
2770 : "");
2771 free(value);
2772 } else {
2773 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2774 count, reg->name,
2775 reg->size) ;
2778 cache = cache->next;
2781 return ERROR_OK;
2784 /* access a single register by its ordinal number */
2785 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2786 unsigned num;
2787 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2789 struct reg_cache *cache = target->reg_cache;
2790 count = 0;
2791 while (cache) {
2792 unsigned i;
2793 for (i = 0; i < cache->num_regs; i++) {
2794 if (count++ == num) {
2795 reg = &cache->reg_list[i];
2796 break;
2799 if (reg)
2800 break;
2801 cache = cache->next;
2804 if (!reg) {
2805 command_print(CMD_CTX, "%i is out of bounds, the current target "
2806 "has only %i registers (0 - %i)", num, count, count - 1);
2807 return ERROR_OK;
2809 } else {
2810 /* access a single register by its name */
2811 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2813 if (!reg) {
2814 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2815 return ERROR_OK;
2819 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2821 /* display a register */
2822 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2823 && (CMD_ARGV[1][0] <= '9')))) {
2824 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2825 reg->valid = 0;
2827 if (reg->valid == 0)
2828 reg->type->get(reg);
2829 value = buf_to_str(reg->value, reg->size, 16);
2830 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2831 free(value);
2832 return ERROR_OK;
2835 /* set register value */
2836 if (CMD_ARGC == 2) {
2837 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2838 if (buf == NULL)
2839 return ERROR_FAIL;
2840 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2842 reg->type->set(reg, buf);
2844 value = buf_to_str(reg->value, reg->size, 16);
2845 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2846 free(value);
2848 free(buf);
2850 return ERROR_OK;
2853 return ERROR_COMMAND_SYNTAX_ERROR;
2856 COMMAND_HANDLER(handle_poll_command)
2858 int retval = ERROR_OK;
2859 struct target *target = get_current_target(CMD_CTX);
2861 if (CMD_ARGC == 0) {
2862 command_print(CMD_CTX, "background polling: %s",
2863 jtag_poll_get_enabled() ? "on" : "off");
2864 command_print(CMD_CTX, "TAP: %s (%s)",
2865 target->tap->dotted_name,
2866 target->tap->enabled ? "enabled" : "disabled");
2867 if (!target->tap->enabled)
2868 return ERROR_OK;
2869 retval = target_poll(target);
2870 if (retval != ERROR_OK)
2871 return retval;
2872 retval = target_arch_state(target);
2873 if (retval != ERROR_OK)
2874 return retval;
2875 } else if (CMD_ARGC == 1) {
2876 bool enable;
2877 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2878 jtag_poll_set_enabled(enable);
2879 } else
2880 return ERROR_COMMAND_SYNTAX_ERROR;
2882 return retval;
2885 COMMAND_HANDLER(handle_wait_halt_command)
2887 if (CMD_ARGC > 1)
2888 return ERROR_COMMAND_SYNTAX_ERROR;
2890 unsigned ms = DEFAULT_HALT_TIMEOUT;
2891 if (1 == CMD_ARGC) {
2892 int retval = parse_uint(CMD_ARGV[0], &ms);
2893 if (ERROR_OK != retval)
2894 return ERROR_COMMAND_SYNTAX_ERROR;
2897 struct target *target = get_current_target(CMD_CTX);
2898 return target_wait_state(target, TARGET_HALTED, ms);
2901 /* wait for target state to change. The trick here is to have a low
2902 * latency for short waits and not to suck up all the CPU time
2903 * on longer waits.
2905 * After 500ms, keep_alive() is invoked
2907 int target_wait_state(struct target *target, enum target_state state, int ms)
2909 int retval;
2910 int64_t then = 0, cur;
2911 bool once = true;
2913 for (;;) {
2914 retval = target_poll(target);
2915 if (retval != ERROR_OK)
2916 return retval;
2917 if (target->state == state)
2918 break;
2919 cur = timeval_ms();
2920 if (once) {
2921 once = false;
2922 then = timeval_ms();
2923 LOG_DEBUG("waiting for target %s...",
2924 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2927 if (cur-then > 500)
2928 keep_alive();
2930 if ((cur-then) > ms) {
2931 LOG_ERROR("timed out while waiting for target %s",
2932 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2933 return ERROR_FAIL;
2937 return ERROR_OK;
2940 COMMAND_HANDLER(handle_halt_command)
2942 LOG_DEBUG("-");
2944 struct target *target = get_current_target(CMD_CTX);
2945 int retval = target_halt(target);
2946 if (ERROR_OK != retval)
2947 return retval;
2949 if (CMD_ARGC == 1) {
2950 unsigned wait_local;
2951 retval = parse_uint(CMD_ARGV[0], &wait_local);
2952 if (ERROR_OK != retval)
2953 return ERROR_COMMAND_SYNTAX_ERROR;
2954 if (!wait_local)
2955 return ERROR_OK;
2958 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2961 COMMAND_HANDLER(handle_soft_reset_halt_command)
2963 struct target *target = get_current_target(CMD_CTX);
2965 LOG_USER("requesting target halt and executing a soft reset");
2967 target_soft_reset_halt(target);
2969 return ERROR_OK;
2972 COMMAND_HANDLER(handle_reset_command)
2974 if (CMD_ARGC > 1)
2975 return ERROR_COMMAND_SYNTAX_ERROR;
2977 enum target_reset_mode reset_mode = RESET_RUN;
2978 if (CMD_ARGC == 1) {
2979 const Jim_Nvp *n;
2980 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2981 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2982 return ERROR_COMMAND_SYNTAX_ERROR;
2983 reset_mode = n->value;
2986 /* reset *all* targets */
2987 return target_process_reset(CMD_CTX, reset_mode);
2991 COMMAND_HANDLER(handle_resume_command)
2993 int current = 1;
2994 if (CMD_ARGC > 1)
2995 return ERROR_COMMAND_SYNTAX_ERROR;
2997 struct target *target = get_current_target(CMD_CTX);
2999 /* with no CMD_ARGV, resume from current pc, addr = 0,
3000 * with one arguments, addr = CMD_ARGV[0],
3001 * handle breakpoints, not debugging */
3002 target_addr_t addr = 0;
3003 if (CMD_ARGC == 1) {
3004 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3005 current = 0;
3008 return target_resume(target, current, addr, 1, 0);
3011 COMMAND_HANDLER(handle_step_command)
3013 if (CMD_ARGC > 1)
3014 return ERROR_COMMAND_SYNTAX_ERROR;
3016 LOG_DEBUG("-");
3018 /* with no CMD_ARGV, step from current pc, addr = 0,
3019 * with one argument addr = CMD_ARGV[0],
3020 * handle breakpoints, debugging */
3021 target_addr_t addr = 0;
3022 int current_pc = 1;
3023 if (CMD_ARGC == 1) {
3024 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3025 current_pc = 0;
3028 struct target *target = get_current_target(CMD_CTX);
3030 return target->type->step(target, current_pc, addr, 1);
3033 static void handle_md_output(struct command_context *cmd_ctx,
3034 struct target *target, target_addr_t address, unsigned size,
3035 unsigned count, const uint8_t *buffer)
3037 const unsigned line_bytecnt = 32;
3038 unsigned line_modulo = line_bytecnt / size;
3040 char output[line_bytecnt * 4 + 1];
3041 unsigned output_len = 0;
3043 const char *value_fmt;
3044 switch (size) {
3045 case 8:
3046 value_fmt = "%16.16"PRIx64" ";
3047 break;
3048 case 4:
3049 value_fmt = "%8.8"PRIx64" ";
3050 break;
3051 case 2:
3052 value_fmt = "%4.4"PRIx64" ";
3053 break;
3054 case 1:
3055 value_fmt = "%2.2"PRIx64" ";
3056 break;
3057 default:
3058 /* "can't happen", caller checked */
3059 LOG_ERROR("invalid memory read size: %u", size);
3060 return;
3063 for (unsigned i = 0; i < count; i++) {
3064 if (i % line_modulo == 0) {
3065 output_len += snprintf(output + output_len,
3066 sizeof(output) - output_len,
3067 TARGET_ADDR_FMT ": ",
3068 (address + (i * size)));
3071 uint64_t value = 0;
3072 const uint8_t *value_ptr = buffer + i * size;
3073 switch (size) {
3074 case 8:
3075 value = target_buffer_get_u64(target, value_ptr);
3076 break;
3077 case 4:
3078 value = target_buffer_get_u32(target, value_ptr);
3079 break;
3080 case 2:
3081 value = target_buffer_get_u16(target, value_ptr);
3082 break;
3083 case 1:
3084 value = *value_ptr;
3086 output_len += snprintf(output + output_len,
3087 sizeof(output) - output_len,
3088 value_fmt, value);
3090 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
3091 command_print(cmd_ctx, "%s", output);
3092 output_len = 0;
3097 COMMAND_HANDLER(handle_md_command)
3099 if (CMD_ARGC < 1)
3100 return ERROR_COMMAND_SYNTAX_ERROR;
3102 unsigned size = 0;
3103 switch (CMD_NAME[2]) {
3104 case 'd':
3105 size = 8;
3106 break;
3107 case 'w':
3108 size = 4;
3109 break;
3110 case 'h':
3111 size = 2;
3112 break;
3113 case 'b':
3114 size = 1;
3115 break;
3116 default:
3117 return ERROR_COMMAND_SYNTAX_ERROR;
3120 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3121 int (*fn)(struct target *target,
3122 target_addr_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
3123 if (physical) {
3124 CMD_ARGC--;
3125 CMD_ARGV++;
3126 fn = target_read_phys_memory;
3127 } else
3128 fn = target_read_memory;
3129 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
3130 return ERROR_COMMAND_SYNTAX_ERROR;
3132 target_addr_t address;
3133 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3135 unsigned count = 1;
3136 if (CMD_ARGC == 2)
3137 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3139 uint8_t *buffer = calloc(count, size);
3140 if (buffer == NULL) {
3141 LOG_ERROR("Failed to allocate md read buffer");
3142 return ERROR_FAIL;
3145 struct target *target = get_current_target(CMD_CTX);
3146 int retval = fn(target, address, size, count, buffer);
3147 if (ERROR_OK == retval)
3148 handle_md_output(CMD_CTX, target, address, size, count, buffer);
3150 free(buffer);
3152 return retval;
3155 typedef int (*target_write_fn)(struct target *target,
3156 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3158 static int target_fill_mem(struct target *target,
3159 target_addr_t address,
3160 target_write_fn fn,
3161 unsigned data_size,
3162 /* value */
3163 uint64_t b,
3164 /* count */
3165 unsigned c)
3167 /* We have to write in reasonably large chunks to be able
3168 * to fill large memory areas with any sane speed */
3169 const unsigned chunk_size = 16384;
3170 uint8_t *target_buf = malloc(chunk_size * data_size);
3171 if (target_buf == NULL) {
3172 LOG_ERROR("Out of memory");
3173 return ERROR_FAIL;
3176 for (unsigned i = 0; i < chunk_size; i++) {
3177 switch (data_size) {
3178 case 8:
3179 target_buffer_set_u64(target, target_buf + i * data_size, b);
3180 break;
3181 case 4:
3182 target_buffer_set_u32(target, target_buf + i * data_size, b);
3183 break;
3184 case 2:
3185 target_buffer_set_u16(target, target_buf + i * data_size, b);
3186 break;
3187 case 1:
3188 target_buffer_set_u8(target, target_buf + i * data_size, b);
3189 break;
3190 default:
3191 exit(-1);
3195 int retval = ERROR_OK;
3197 for (unsigned x = 0; x < c; x += chunk_size) {
3198 unsigned current;
3199 current = c - x;
3200 if (current > chunk_size)
3201 current = chunk_size;
3202 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3203 if (retval != ERROR_OK)
3204 break;
3205 /* avoid GDB timeouts */
3206 keep_alive();
3208 free(target_buf);
3210 return retval;
3214 COMMAND_HANDLER(handle_mw_command)
3216 if (CMD_ARGC < 2)
3217 return ERROR_COMMAND_SYNTAX_ERROR;
3218 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3219 target_write_fn fn;
3220 if (physical) {
3221 CMD_ARGC--;
3222 CMD_ARGV++;
3223 fn = target_write_phys_memory;
3224 } else
3225 fn = target_write_memory;
3226 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3227 return ERROR_COMMAND_SYNTAX_ERROR;
3229 target_addr_t address;
3230 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3232 target_addr_t value;
3233 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], value);
3235 unsigned count = 1;
3236 if (CMD_ARGC == 3)
3237 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3239 struct target *target = get_current_target(CMD_CTX);
3240 unsigned wordsize;
3241 switch (CMD_NAME[2]) {
3242 case 'd':
3243 wordsize = 8;
3244 break;
3245 case 'w':
3246 wordsize = 4;
3247 break;
3248 case 'h':
3249 wordsize = 2;
3250 break;
3251 case 'b':
3252 wordsize = 1;
3253 break;
3254 default:
3255 return ERROR_COMMAND_SYNTAX_ERROR;
3258 return target_fill_mem(target, address, fn, wordsize, value, count);
3261 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
3262 target_addr_t *min_address, target_addr_t *max_address)
3264 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3265 return ERROR_COMMAND_SYNTAX_ERROR;
3267 /* a base address isn't always necessary,
3268 * default to 0x0 (i.e. don't relocate) */
3269 if (CMD_ARGC >= 2) {
3270 target_addr_t addr;
3271 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3272 image->base_address = addr;
3273 image->base_address_set = 1;
3274 } else
3275 image->base_address_set = 0;
3277 image->start_address_set = 0;
3279 if (CMD_ARGC >= 4)
3280 COMMAND_PARSE_ADDRESS(CMD_ARGV[3], *min_address);
3281 if (CMD_ARGC == 5) {
3282 COMMAND_PARSE_ADDRESS(CMD_ARGV[4], *max_address);
3283 /* use size (given) to find max (required) */
3284 *max_address += *min_address;
3287 if (*min_address > *max_address)
3288 return ERROR_COMMAND_SYNTAX_ERROR;
3290 return ERROR_OK;
3293 COMMAND_HANDLER(handle_load_image_command)
3295 uint8_t *buffer;
3296 size_t buf_cnt;
3297 uint32_t image_size;
3298 target_addr_t min_address = 0;
3299 target_addr_t max_address = -1;
3300 int i;
3301 struct image image;
3303 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
3304 &image, &min_address, &max_address);
3305 if (ERROR_OK != retval)
3306 return retval;
3308 struct target *target = get_current_target(CMD_CTX);
3310 struct duration bench;
3311 duration_start(&bench);
3313 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3314 return ERROR_FAIL;
3316 image_size = 0x0;
3317 retval = ERROR_OK;
3318 for (i = 0; i < image.num_sections; i++) {
3319 buffer = malloc(image.sections[i].size);
3320 if (buffer == NULL) {
3321 command_print(CMD_CTX,
3322 "error allocating buffer for section (%d bytes)",
3323 (int)(image.sections[i].size));
3324 retval = ERROR_FAIL;
3325 break;
3328 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3329 if (retval != ERROR_OK) {
3330 free(buffer);
3331 break;
3334 uint32_t offset = 0;
3335 uint32_t length = buf_cnt;
3337 /* DANGER!!! beware of unsigned comparision here!!! */
3339 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3340 (image.sections[i].base_address < max_address)) {
3342 if (image.sections[i].base_address < min_address) {
3343 /* clip addresses below */
3344 offset += min_address-image.sections[i].base_address;
3345 length -= offset;
3348 if (image.sections[i].base_address + buf_cnt > max_address)
3349 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3351 retval = target_write_buffer(target,
3352 image.sections[i].base_address + offset, length, buffer + offset);
3353 if (retval != ERROR_OK) {
3354 free(buffer);
3355 break;
3357 image_size += length;
3358 command_print(CMD_CTX, "%u bytes written at address " TARGET_ADDR_FMT "",
3359 (unsigned int)length,
3360 image.sections[i].base_address + offset);
3363 free(buffer);
3366 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3367 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
3368 "in %fs (%0.3f KiB/s)", image_size,
3369 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3372 image_close(&image);
3374 return retval;
3378 COMMAND_HANDLER(handle_dump_image_command)
3380 struct fileio *fileio;
3381 uint8_t *buffer;
3382 int retval, retvaltemp;
3383 target_addr_t address, size;
3384 struct duration bench;
3385 struct target *target = get_current_target(CMD_CTX);
3387 if (CMD_ARGC != 3)
3388 return ERROR_COMMAND_SYNTAX_ERROR;
3390 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], address);
3391 COMMAND_PARSE_ADDRESS(CMD_ARGV[2], size);
3393 uint32_t buf_size = (size > 4096) ? 4096 : size;
3394 buffer = malloc(buf_size);
3395 if (!buffer)
3396 return ERROR_FAIL;
3398 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3399 if (retval != ERROR_OK) {
3400 free(buffer);
3401 return retval;
3404 duration_start(&bench);
3406 while (size > 0) {
3407 size_t size_written;
3408 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3409 retval = target_read_buffer(target, address, this_run_size, buffer);
3410 if (retval != ERROR_OK)
3411 break;
3413 retval = fileio_write(fileio, this_run_size, buffer, &size_written);
3414 if (retval != ERROR_OK)
3415 break;
3417 size -= this_run_size;
3418 address += this_run_size;
3421 free(buffer);
3423 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3424 size_t filesize;
3425 retval = fileio_size(fileio, &filesize);
3426 if (retval != ERROR_OK)
3427 return retval;
3428 command_print(CMD_CTX,
3429 "dumped %zu bytes in %fs (%0.3f KiB/s)", filesize,
3430 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3433 retvaltemp = fileio_close(fileio);
3434 if (retvaltemp != ERROR_OK)
3435 return retvaltemp;
3437 return retval;
3440 enum verify_mode {
3441 IMAGE_TEST = 0,
3442 IMAGE_VERIFY = 1,
3443 IMAGE_CHECKSUM_ONLY = 2
3446 static COMMAND_HELPER(handle_verify_image_command_internal, enum verify_mode verify)
3448 uint8_t *buffer;
3449 size_t buf_cnt;
3450 uint32_t image_size;
3451 int i;
3452 int retval;
3453 uint32_t checksum = 0;
3454 uint32_t mem_checksum = 0;
3456 struct image image;
3458 struct target *target = get_current_target(CMD_CTX);
3460 if (CMD_ARGC < 1)
3461 return ERROR_COMMAND_SYNTAX_ERROR;
3463 if (!target) {
3464 LOG_ERROR("no target selected");
3465 return ERROR_FAIL;
3468 struct duration bench;
3469 duration_start(&bench);
3471 if (CMD_ARGC >= 2) {
3472 target_addr_t addr;
3473 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3474 image.base_address = addr;
3475 image.base_address_set = 1;
3476 } else {
3477 image.base_address_set = 0;
3478 image.base_address = 0x0;
3481 image.start_address_set = 0;
3483 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3484 if (retval != ERROR_OK)
3485 return retval;
3487 image_size = 0x0;
3488 int diffs = 0;
3489 retval = ERROR_OK;
3490 for (i = 0; i < image.num_sections; i++) {
3491 buffer = malloc(image.sections[i].size);
3492 if (buffer == NULL) {
3493 command_print(CMD_CTX,
3494 "error allocating buffer for section (%d bytes)",
3495 (int)(image.sections[i].size));
3496 break;
3498 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3499 if (retval != ERROR_OK) {
3500 free(buffer);
3501 break;
3504 if (verify >= IMAGE_VERIFY) {
3505 /* calculate checksum of image */
3506 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3507 if (retval != ERROR_OK) {
3508 free(buffer);
3509 break;
3512 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3513 if (retval != ERROR_OK) {
3514 free(buffer);
3515 break;
3517 if ((checksum != mem_checksum) && (verify == IMAGE_CHECKSUM_ONLY)) {
3518 LOG_ERROR("checksum mismatch");
3519 free(buffer);
3520 retval = ERROR_FAIL;
3521 goto done;
3523 if (checksum != mem_checksum) {
3524 /* failed crc checksum, fall back to a binary compare */
3525 uint8_t *data;
3527 if (diffs == 0)
3528 LOG_ERROR("checksum mismatch - attempting binary compare");
3530 data = malloc(buf_cnt);
3532 /* Can we use 32bit word accesses? */
3533 int size = 1;
3534 int count = buf_cnt;
3535 if ((count % 4) == 0) {
3536 size *= 4;
3537 count /= 4;
3539 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3540 if (retval == ERROR_OK) {
3541 uint32_t t;
3542 for (t = 0; t < buf_cnt; t++) {
3543 if (data[t] != buffer[t]) {
3544 command_print(CMD_CTX,
3545 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3546 diffs,
3547 (unsigned)(t + image.sections[i].base_address),
3548 data[t],
3549 buffer[t]);
3550 if (diffs++ >= 127) {
3551 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3552 free(data);
3553 free(buffer);
3554 goto done;
3557 keep_alive();
3560 free(data);
3562 } else {
3563 command_print(CMD_CTX, "address " TARGET_ADDR_FMT " length 0x%08zx",
3564 image.sections[i].base_address,
3565 buf_cnt);
3568 free(buffer);
3569 image_size += buf_cnt;
3571 if (diffs > 0)
3572 command_print(CMD_CTX, "No more differences found.");
3573 done:
3574 if (diffs > 0)
3575 retval = ERROR_FAIL;
3576 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3577 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3578 "in %fs (%0.3f KiB/s)", image_size,
3579 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3582 image_close(&image);
3584 return retval;
3587 COMMAND_HANDLER(handle_verify_image_checksum_command)
3589 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_CHECKSUM_ONLY);
3592 COMMAND_HANDLER(handle_verify_image_command)
3594 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_VERIFY);
3597 COMMAND_HANDLER(handle_test_image_command)
3599 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_TEST);
3602 static int handle_bp_command_list(struct command_context *cmd_ctx)
3604 struct target *target = get_current_target(cmd_ctx);
3605 struct breakpoint *breakpoint = target->breakpoints;
3606 while (breakpoint) {
3607 if (breakpoint->type == BKPT_SOFT) {
3608 char *buf = buf_to_str(breakpoint->orig_instr,
3609 breakpoint->length, 16);
3610 command_print(cmd_ctx, "IVA breakpoint: " TARGET_ADDR_FMT ", 0x%x, %i, 0x%s",
3611 breakpoint->address,
3612 breakpoint->length,
3613 breakpoint->set, buf);
3614 free(buf);
3615 } else {
3616 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3617 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3618 breakpoint->asid,
3619 breakpoint->length, breakpoint->set);
3620 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3621 command_print(cmd_ctx, "Hybrid breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3622 breakpoint->address,
3623 breakpoint->length, breakpoint->set);
3624 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3625 breakpoint->asid);
3626 } else
3627 command_print(cmd_ctx, "Breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3628 breakpoint->address,
3629 breakpoint->length, breakpoint->set);
3632 breakpoint = breakpoint->next;
3634 return ERROR_OK;
3637 static int handle_bp_command_set(struct command_context *cmd_ctx,
3638 target_addr_t addr, uint32_t asid, uint32_t length, int hw)
3640 struct target *target = get_current_target(cmd_ctx);
3641 int retval;
3643 if (asid == 0) {
3644 retval = breakpoint_add(target, addr, length, hw);
3645 if (ERROR_OK == retval)
3646 command_print(cmd_ctx, "breakpoint set at " TARGET_ADDR_FMT "", addr);
3647 else {
3648 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3649 return retval;
3651 } else if (addr == 0) {
3652 if (target->type->add_context_breakpoint == NULL) {
3653 LOG_WARNING("Context breakpoint not available");
3654 return ERROR_OK;
3656 retval = context_breakpoint_add(target, asid, length, hw);
3657 if (ERROR_OK == retval)
3658 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3659 else {
3660 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3661 return retval;
3663 } else {
3664 if (target->type->add_hybrid_breakpoint == NULL) {
3665 LOG_WARNING("Hybrid breakpoint not available");
3666 return ERROR_OK;
3668 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3669 if (ERROR_OK == retval)
3670 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3671 else {
3672 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3673 return retval;
3676 return ERROR_OK;
3679 COMMAND_HANDLER(handle_bp_command)
3681 target_addr_t addr;
3682 uint32_t asid;
3683 uint32_t length;
3684 int hw = BKPT_SOFT;
3686 switch (CMD_ARGC) {
3687 case 0:
3688 return handle_bp_command_list(CMD_CTX);
3690 case 2:
3691 asid = 0;
3692 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3693 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3694 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3696 case 3:
3697 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3698 hw = BKPT_HARD;
3699 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3700 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3701 asid = 0;
3702 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3703 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3704 hw = BKPT_HARD;
3705 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3706 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3707 addr = 0;
3708 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3710 /* fallthrough */
3711 case 4:
3712 hw = BKPT_HARD;
3713 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3714 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3715 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3716 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3718 default:
3719 return ERROR_COMMAND_SYNTAX_ERROR;
3723 COMMAND_HANDLER(handle_rbp_command)
3725 if (CMD_ARGC != 1)
3726 return ERROR_COMMAND_SYNTAX_ERROR;
3728 target_addr_t addr;
3729 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3731 struct target *target = get_current_target(CMD_CTX);
3732 breakpoint_remove(target, addr);
3734 return ERROR_OK;
3737 COMMAND_HANDLER(handle_wp_command)
3739 struct target *target = get_current_target(CMD_CTX);
3741 if (CMD_ARGC == 0) {
3742 struct watchpoint *watchpoint = target->watchpoints;
3744 while (watchpoint) {
3745 command_print(CMD_CTX, "address: " TARGET_ADDR_FMT
3746 ", len: 0x%8.8" PRIx32
3747 ", r/w/a: %i, value: 0x%8.8" PRIx32
3748 ", mask: 0x%8.8" PRIx32,
3749 watchpoint->address,
3750 watchpoint->length,
3751 (int)watchpoint->rw,
3752 watchpoint->value,
3753 watchpoint->mask);
3754 watchpoint = watchpoint->next;
3756 return ERROR_OK;
3759 enum watchpoint_rw type = WPT_ACCESS;
3760 uint32_t addr = 0;
3761 uint32_t length = 0;
3762 uint32_t data_value = 0x0;
3763 uint32_t data_mask = 0xffffffff;
3765 switch (CMD_ARGC) {
3766 case 5:
3767 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3768 /* fall through */
3769 case 4:
3770 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3771 /* fall through */
3772 case 3:
3773 switch (CMD_ARGV[2][0]) {
3774 case 'r':
3775 type = WPT_READ;
3776 break;
3777 case 'w':
3778 type = WPT_WRITE;
3779 break;
3780 case 'a':
3781 type = WPT_ACCESS;
3782 break;
3783 default:
3784 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3785 return ERROR_COMMAND_SYNTAX_ERROR;
3787 /* fall through */
3788 case 2:
3789 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3790 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3791 break;
3793 default:
3794 return ERROR_COMMAND_SYNTAX_ERROR;
3797 int retval = watchpoint_add(target, addr, length, type,
3798 data_value, data_mask);
3799 if (ERROR_OK != retval)
3800 LOG_ERROR("Failure setting watchpoints");
3802 return retval;
3805 COMMAND_HANDLER(handle_rwp_command)
3807 if (CMD_ARGC != 1)
3808 return ERROR_COMMAND_SYNTAX_ERROR;
3810 uint32_t addr;
3811 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3813 struct target *target = get_current_target(CMD_CTX);
3814 watchpoint_remove(target, addr);
3816 return ERROR_OK;
3820 * Translate a virtual address to a physical address.
3822 * The low-level target implementation must have logged a detailed error
3823 * which is forwarded to telnet/GDB session.
3825 COMMAND_HANDLER(handle_virt2phys_command)
3827 if (CMD_ARGC != 1)
3828 return ERROR_COMMAND_SYNTAX_ERROR;
3830 target_addr_t va;
3831 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], va);
3832 target_addr_t pa;
3834 struct target *target = get_current_target(CMD_CTX);
3835 int retval = target->type->virt2phys(target, va, &pa);
3836 if (retval == ERROR_OK)
3837 command_print(CMD_CTX, "Physical address " TARGET_ADDR_FMT "", pa);
3839 return retval;
3842 static void writeData(FILE *f, const void *data, size_t len)
3844 size_t written = fwrite(data, 1, len, f);
3845 if (written != len)
3846 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3849 static void writeLong(FILE *f, int l, struct target *target)
3851 uint8_t val[4];
3853 target_buffer_set_u32(target, val, l);
3854 writeData(f, val, 4);
3857 static void writeString(FILE *f, char *s)
3859 writeData(f, s, strlen(s));
3862 typedef unsigned char UNIT[2]; /* unit of profiling */
3864 /* Dump a gmon.out histogram file. */
3865 static void write_gmon(uint32_t *samples, uint32_t sampleNum, const char *filename, bool with_range,
3866 uint32_t start_address, uint32_t end_address, struct target *target, uint32_t duration_ms)
3868 uint32_t i;
3869 FILE *f = fopen(filename, "w");
3870 if (f == NULL)
3871 return;
3872 writeString(f, "gmon");
3873 writeLong(f, 0x00000001, target); /* Version */
3874 writeLong(f, 0, target); /* padding */
3875 writeLong(f, 0, target); /* padding */
3876 writeLong(f, 0, target); /* padding */
3878 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3879 writeData(f, &zero, 1);
3881 /* figure out bucket size */
3882 uint32_t min;
3883 uint32_t max;
3884 if (with_range) {
3885 min = start_address;
3886 max = end_address;
3887 } else {
3888 min = samples[0];
3889 max = samples[0];
3890 for (i = 0; i < sampleNum; i++) {
3891 if (min > samples[i])
3892 min = samples[i];
3893 if (max < samples[i])
3894 max = samples[i];
3897 /* max should be (largest sample + 1)
3898 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
3899 max++;
3902 int addressSpace = max - min;
3903 assert(addressSpace >= 2);
3905 /* FIXME: What is the reasonable number of buckets?
3906 * The profiling result will be more accurate if there are enough buckets. */
3907 static const uint32_t maxBuckets = 128 * 1024; /* maximum buckets. */
3908 uint32_t numBuckets = addressSpace / sizeof(UNIT);
3909 if (numBuckets > maxBuckets)
3910 numBuckets = maxBuckets;
3911 int *buckets = malloc(sizeof(int) * numBuckets);
3912 if (buckets == NULL) {
3913 fclose(f);
3914 return;
3916 memset(buckets, 0, sizeof(int) * numBuckets);
3917 for (i = 0; i < sampleNum; i++) {
3918 uint32_t address = samples[i];
3920 if ((address < min) || (max <= address))
3921 continue;
3923 long long a = address - min;
3924 long long b = numBuckets;
3925 long long c = addressSpace;
3926 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3927 buckets[index_t]++;
3930 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3931 writeLong(f, min, target); /* low_pc */
3932 writeLong(f, max, target); /* high_pc */
3933 writeLong(f, numBuckets, target); /* # of buckets */
3934 float sample_rate = sampleNum / (duration_ms / 1000.0);
3935 writeLong(f, sample_rate, target);
3936 writeString(f, "seconds");
3937 for (i = 0; i < (15-strlen("seconds")); i++)
3938 writeData(f, &zero, 1);
3939 writeString(f, "s");
3941 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3943 char *data = malloc(2 * numBuckets);
3944 if (data != NULL) {
3945 for (i = 0; i < numBuckets; i++) {
3946 int val;
3947 val = buckets[i];
3948 if (val > 65535)
3949 val = 65535;
3950 data[i * 2] = val&0xff;
3951 data[i * 2 + 1] = (val >> 8) & 0xff;
3953 free(buckets);
3954 writeData(f, data, numBuckets * 2);
3955 free(data);
3956 } else
3957 free(buckets);
3959 fclose(f);
3962 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3963 * which will be used as a random sampling of PC */
3964 COMMAND_HANDLER(handle_profile_command)
3966 struct target *target = get_current_target(CMD_CTX);
3968 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
3969 return ERROR_COMMAND_SYNTAX_ERROR;
3971 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
3972 uint32_t offset;
3973 uint32_t num_of_samples;
3974 int retval = ERROR_OK;
3976 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
3978 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
3979 if (samples == NULL) {
3980 LOG_ERROR("No memory to store samples.");
3981 return ERROR_FAIL;
3984 uint64_t timestart_ms = timeval_ms();
3986 * Some cores let us sample the PC without the
3987 * annoying halt/resume step; for example, ARMv7 PCSR.
3988 * Provide a way to use that more efficient mechanism.
3990 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
3991 &num_of_samples, offset);
3992 if (retval != ERROR_OK) {
3993 free(samples);
3994 return retval;
3996 uint32_t duration_ms = timeval_ms() - timestart_ms;
3998 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
4000 retval = target_poll(target);
4001 if (retval != ERROR_OK) {
4002 free(samples);
4003 return retval;
4005 if (target->state == TARGET_RUNNING) {
4006 retval = target_halt(target);
4007 if (retval != ERROR_OK) {
4008 free(samples);
4009 return retval;
4013 retval = target_poll(target);
4014 if (retval != ERROR_OK) {
4015 free(samples);
4016 return retval;
4019 uint32_t start_address = 0;
4020 uint32_t end_address = 0;
4021 bool with_range = false;
4022 if (CMD_ARGC == 4) {
4023 with_range = true;
4024 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
4025 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
4028 write_gmon(samples, num_of_samples, CMD_ARGV[1],
4029 with_range, start_address, end_address, target, duration_ms);
4030 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
4032 free(samples);
4033 return retval;
4036 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
4038 char *namebuf;
4039 Jim_Obj *nameObjPtr, *valObjPtr;
4040 int result;
4042 namebuf = alloc_printf("%s(%d)", varname, idx);
4043 if (!namebuf)
4044 return JIM_ERR;
4046 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
4047 valObjPtr = Jim_NewIntObj(interp, val);
4048 if (!nameObjPtr || !valObjPtr) {
4049 free(namebuf);
4050 return JIM_ERR;
4053 Jim_IncrRefCount(nameObjPtr);
4054 Jim_IncrRefCount(valObjPtr);
4055 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
4056 Jim_DecrRefCount(interp, nameObjPtr);
4057 Jim_DecrRefCount(interp, valObjPtr);
4058 free(namebuf);
4059 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
4060 return result;
4063 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4065 struct command_context *context;
4066 struct target *target;
4068 context = current_command_context(interp);
4069 assert(context != NULL);
4071 target = get_current_target(context);
4072 if (target == NULL) {
4073 LOG_ERROR("mem2array: no current target");
4074 return JIM_ERR;
4077 return target_mem2array(interp, target, argc - 1, argv + 1);
4080 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
4082 long l;
4083 uint32_t width;
4084 int len;
4085 uint32_t addr;
4086 uint32_t count;
4087 uint32_t v;
4088 const char *varname;
4089 const char *phys;
4090 bool is_phys;
4091 int n, e, retval;
4092 uint32_t i;
4094 /* argv[1] = name of array to receive the data
4095 * argv[2] = desired width
4096 * argv[3] = memory address
4097 * argv[4] = count of times to read
4099 if (argc < 4 || argc > 5) {
4100 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems [phys]");
4101 return JIM_ERR;
4103 varname = Jim_GetString(argv[0], &len);
4104 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
4106 e = Jim_GetLong(interp, argv[1], &l);
4107 width = l;
4108 if (e != JIM_OK)
4109 return e;
4111 e = Jim_GetLong(interp, argv[2], &l);
4112 addr = l;
4113 if (e != JIM_OK)
4114 return e;
4115 e = Jim_GetLong(interp, argv[3], &l);
4116 len = l;
4117 if (e != JIM_OK)
4118 return e;
4119 is_phys = false;
4120 if (argc > 4) {
4121 phys = Jim_GetString(argv[4], &n);
4122 if (!strncmp(phys, "phys", n))
4123 is_phys = true;
4124 else
4125 return JIM_ERR;
4127 switch (width) {
4128 case 8:
4129 width = 1;
4130 break;
4131 case 16:
4132 width = 2;
4133 break;
4134 case 32:
4135 width = 4;
4136 break;
4137 default:
4138 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4139 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
4140 return JIM_ERR;
4142 if (len == 0) {
4143 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4144 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
4145 return JIM_ERR;
4147 if ((addr + (len * width)) < addr) {
4148 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4149 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
4150 return JIM_ERR;
4152 /* absurd transfer size? */
4153 if (len > 65536) {
4154 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4155 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
4156 return JIM_ERR;
4159 if ((width == 1) ||
4160 ((width == 2) && ((addr & 1) == 0)) ||
4161 ((width == 4) && ((addr & 3) == 0))) {
4162 /* all is well */
4163 } else {
4164 char buf[100];
4165 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4166 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
4167 addr,
4168 width);
4169 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4170 return JIM_ERR;
4173 /* Transfer loop */
4175 /* index counter */
4176 n = 0;
4178 size_t buffersize = 4096;
4179 uint8_t *buffer = malloc(buffersize);
4180 if (buffer == NULL)
4181 return JIM_ERR;
4183 /* assume ok */
4184 e = JIM_OK;
4185 while (len) {
4186 /* Slurp... in buffer size chunks */
4188 count = len; /* in objects.. */
4189 if (count > (buffersize / width))
4190 count = (buffersize / width);
4192 if (is_phys)
4193 retval = target_read_phys_memory(target, addr, width, count, buffer);
4194 else
4195 retval = target_read_memory(target, addr, width, count, buffer);
4196 if (retval != ERROR_OK) {
4197 /* BOO !*/
4198 LOG_ERROR("mem2array: Read @ 0x%08" PRIx32 ", w=%" PRId32 ", cnt=%" PRId32 ", failed",
4199 addr,
4200 width,
4201 count);
4202 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4203 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
4204 e = JIM_ERR;
4205 break;
4206 } else {
4207 v = 0; /* shut up gcc */
4208 for (i = 0; i < count ; i++, n++) {
4209 switch (width) {
4210 case 4:
4211 v = target_buffer_get_u32(target, &buffer[i*width]);
4212 break;
4213 case 2:
4214 v = target_buffer_get_u16(target, &buffer[i*width]);
4215 break;
4216 case 1:
4217 v = buffer[i] & 0x0ff;
4218 break;
4220 new_int_array_element(interp, varname, n, v);
4222 len -= count;
4223 addr += count * width;
4227 free(buffer);
4229 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4231 return e;
4234 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
4236 char *namebuf;
4237 Jim_Obj *nameObjPtr, *valObjPtr;
4238 int result;
4239 long l;
4241 namebuf = alloc_printf("%s(%d)", varname, idx);
4242 if (!namebuf)
4243 return JIM_ERR;
4245 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
4246 if (!nameObjPtr) {
4247 free(namebuf);
4248 return JIM_ERR;
4251 Jim_IncrRefCount(nameObjPtr);
4252 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
4253 Jim_DecrRefCount(interp, nameObjPtr);
4254 free(namebuf);
4255 if (valObjPtr == NULL)
4256 return JIM_ERR;
4258 result = Jim_GetLong(interp, valObjPtr, &l);
4259 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
4260 *val = l;
4261 return result;
4264 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4266 struct command_context *context;
4267 struct target *target;
4269 context = current_command_context(interp);
4270 assert(context != NULL);
4272 target = get_current_target(context);
4273 if (target == NULL) {
4274 LOG_ERROR("array2mem: no current target");
4275 return JIM_ERR;
4278 return target_array2mem(interp, target, argc-1, argv + 1);
4281 static int target_array2mem(Jim_Interp *interp, struct target *target,
4282 int argc, Jim_Obj *const *argv)
4284 long l;
4285 uint32_t width;
4286 int len;
4287 uint32_t addr;
4288 uint32_t count;
4289 uint32_t v;
4290 const char *varname;
4291 const char *phys;
4292 bool is_phys;
4293 int n, e, retval;
4294 uint32_t i;
4296 /* argv[1] = name of array to get the data
4297 * argv[2] = desired width
4298 * argv[3] = memory address
4299 * argv[4] = count to write
4301 if (argc < 4 || argc > 5) {
4302 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4303 return JIM_ERR;
4305 varname = Jim_GetString(argv[0], &len);
4306 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
4308 e = Jim_GetLong(interp, argv[1], &l);
4309 width = l;
4310 if (e != JIM_OK)
4311 return e;
4313 e = Jim_GetLong(interp, argv[2], &l);
4314 addr = l;
4315 if (e != JIM_OK)
4316 return e;
4317 e = Jim_GetLong(interp, argv[3], &l);
4318 len = l;
4319 if (e != JIM_OK)
4320 return e;
4321 is_phys = false;
4322 if (argc > 4) {
4323 phys = Jim_GetString(argv[4], &n);
4324 if (!strncmp(phys, "phys", n))
4325 is_phys = true;
4326 else
4327 return JIM_ERR;
4329 switch (width) {
4330 case 8:
4331 width = 1;
4332 break;
4333 case 16:
4334 width = 2;
4335 break;
4336 case 32:
4337 width = 4;
4338 break;
4339 default:
4340 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4341 Jim_AppendStrings(interp, Jim_GetResult(interp),
4342 "Invalid width param, must be 8/16/32", NULL);
4343 return JIM_ERR;
4345 if (len == 0) {
4346 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4347 Jim_AppendStrings(interp, Jim_GetResult(interp),
4348 "array2mem: zero width read?", NULL);
4349 return JIM_ERR;
4351 if ((addr + (len * width)) < addr) {
4352 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4353 Jim_AppendStrings(interp, Jim_GetResult(interp),
4354 "array2mem: addr + len - wraps to zero?", NULL);
4355 return JIM_ERR;
4357 /* absurd transfer size? */
4358 if (len > 65536) {
4359 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4360 Jim_AppendStrings(interp, Jim_GetResult(interp),
4361 "array2mem: absurd > 64K item request", NULL);
4362 return JIM_ERR;
4365 if ((width == 1) ||
4366 ((width == 2) && ((addr & 1) == 0)) ||
4367 ((width == 4) && ((addr & 3) == 0))) {
4368 /* all is well */
4369 } else {
4370 char buf[100];
4371 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4372 sprintf(buf, "array2mem address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
4373 addr,
4374 width);
4375 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4376 return JIM_ERR;
4379 /* Transfer loop */
4381 /* index counter */
4382 n = 0;
4383 /* assume ok */
4384 e = JIM_OK;
4386 size_t buffersize = 4096;
4387 uint8_t *buffer = malloc(buffersize);
4388 if (buffer == NULL)
4389 return JIM_ERR;
4391 while (len) {
4392 /* Slurp... in buffer size chunks */
4394 count = len; /* in objects.. */
4395 if (count > (buffersize / width))
4396 count = (buffersize / width);
4398 v = 0; /* shut up gcc */
4399 for (i = 0; i < count; i++, n++) {
4400 get_int_array_element(interp, varname, n, &v);
4401 switch (width) {
4402 case 4:
4403 target_buffer_set_u32(target, &buffer[i * width], v);
4404 break;
4405 case 2:
4406 target_buffer_set_u16(target, &buffer[i * width], v);
4407 break;
4408 case 1:
4409 buffer[i] = v & 0x0ff;
4410 break;
4413 len -= count;
4415 if (is_phys)
4416 retval = target_write_phys_memory(target, addr, width, count, buffer);
4417 else
4418 retval = target_write_memory(target, addr, width, count, buffer);
4419 if (retval != ERROR_OK) {
4420 /* BOO !*/
4421 LOG_ERROR("array2mem: Write @ 0x%08" PRIx32 ", w=%" PRId32 ", cnt=%" PRId32 ", failed",
4422 addr,
4423 width,
4424 count);
4425 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4426 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4427 e = JIM_ERR;
4428 break;
4430 addr += count * width;
4433 free(buffer);
4435 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4437 return e;
4440 /* FIX? should we propagate errors here rather than printing them
4441 * and continuing?
4443 void target_handle_event(struct target *target, enum target_event e)
4445 struct target_event_action *teap;
4447 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4448 if (teap->event == e) {
4449 LOG_DEBUG("target(%d): %s (%s) event: %d (%s) action: %s",
4450 target->target_number,
4451 target_name(target),
4452 target_type_name(target),
4454 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
4455 Jim_GetString(teap->body, NULL));
4457 /* Override current target by the target an event
4458 * is issued from (lot of scripts need it).
4459 * Return back to previous override as soon
4460 * as the handler processing is done */
4461 struct command_context *cmd_ctx = current_command_context(teap->interp);
4462 struct target *saved_target_override = cmd_ctx->current_target_override;
4463 cmd_ctx->current_target_override = target;
4465 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
4466 Jim_MakeErrorMessage(teap->interp);
4467 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
4470 cmd_ctx->current_target_override = saved_target_override;
4476 * Returns true only if the target has a handler for the specified event.
4478 bool target_has_event_action(struct target *target, enum target_event event)
4480 struct target_event_action *teap;
4482 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4483 if (teap->event == event)
4484 return true;
4486 return false;
4489 enum target_cfg_param {
4490 TCFG_TYPE,
4491 TCFG_EVENT,
4492 TCFG_WORK_AREA_VIRT,
4493 TCFG_WORK_AREA_PHYS,
4494 TCFG_WORK_AREA_SIZE,
4495 TCFG_WORK_AREA_BACKUP,
4496 TCFG_ENDIAN,
4497 TCFG_COREID,
4498 TCFG_CHAIN_POSITION,
4499 TCFG_DBGBASE,
4500 TCFG_CTIBASE,
4501 TCFG_RTOS,
4502 TCFG_DEFER_EXAMINE,
4505 static Jim_Nvp nvp_config_opts[] = {
4506 { .name = "-type", .value = TCFG_TYPE },
4507 { .name = "-event", .value = TCFG_EVENT },
4508 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4509 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4510 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4511 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4512 { .name = "-endian" , .value = TCFG_ENDIAN },
4513 { .name = "-coreid", .value = TCFG_COREID },
4514 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4515 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4516 { .name = "-ctibase", .value = TCFG_CTIBASE },
4517 { .name = "-rtos", .value = TCFG_RTOS },
4518 { .name = "-defer-examine", .value = TCFG_DEFER_EXAMINE },
4519 { .name = NULL, .value = -1 }
4522 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
4524 Jim_Nvp *n;
4525 Jim_Obj *o;
4526 jim_wide w;
4527 int e;
4529 /* parse config or cget options ... */
4530 while (goi->argc > 0) {
4531 Jim_SetEmptyResult(goi->interp);
4532 /* Jim_GetOpt_Debug(goi); */
4534 if (target->type->target_jim_configure) {
4535 /* target defines a configure function */
4536 /* target gets first dibs on parameters */
4537 e = (*(target->type->target_jim_configure))(target, goi);
4538 if (e == JIM_OK) {
4539 /* more? */
4540 continue;
4542 if (e == JIM_ERR) {
4543 /* An error */
4544 return e;
4546 /* otherwise we 'continue' below */
4548 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
4549 if (e != JIM_OK) {
4550 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
4551 return e;
4553 switch (n->value) {
4554 case TCFG_TYPE:
4555 /* not setable */
4556 if (goi->isconfigure) {
4557 Jim_SetResultFormatted(goi->interp,
4558 "not settable: %s", n->name);
4559 return JIM_ERR;
4560 } else {
4561 no_params:
4562 if (goi->argc != 0) {
4563 Jim_WrongNumArgs(goi->interp,
4564 goi->argc, goi->argv,
4565 "NO PARAMS");
4566 return JIM_ERR;
4569 Jim_SetResultString(goi->interp,
4570 target_type_name(target), -1);
4571 /* loop for more */
4572 break;
4573 case TCFG_EVENT:
4574 if (goi->argc == 0) {
4575 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4576 return JIM_ERR;
4579 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4580 if (e != JIM_OK) {
4581 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4582 return e;
4585 if (goi->isconfigure) {
4586 if (goi->argc != 1) {
4587 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4588 return JIM_ERR;
4590 } else {
4591 if (goi->argc != 0) {
4592 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4593 return JIM_ERR;
4598 struct target_event_action *teap;
4600 teap = target->event_action;
4601 /* replace existing? */
4602 while (teap) {
4603 if (teap->event == (enum target_event)n->value)
4604 break;
4605 teap = teap->next;
4608 if (goi->isconfigure) {
4609 bool replace = true;
4610 if (teap == NULL) {
4611 /* create new */
4612 teap = calloc(1, sizeof(*teap));
4613 replace = false;
4615 teap->event = n->value;
4616 teap->interp = goi->interp;
4617 Jim_GetOpt_Obj(goi, &o);
4618 if (teap->body)
4619 Jim_DecrRefCount(teap->interp, teap->body);
4620 teap->body = Jim_DuplicateObj(goi->interp, o);
4622 * FIXME:
4623 * Tcl/TK - "tk events" have a nice feature.
4624 * See the "BIND" command.
4625 * We should support that here.
4626 * You can specify %X and %Y in the event code.
4627 * The idea is: %T - target name.
4628 * The idea is: %N - target number
4629 * The idea is: %E - event name.
4631 Jim_IncrRefCount(teap->body);
4633 if (!replace) {
4634 /* add to head of event list */
4635 teap->next = target->event_action;
4636 target->event_action = teap;
4638 Jim_SetEmptyResult(goi->interp);
4639 } else {
4640 /* get */
4641 if (teap == NULL)
4642 Jim_SetEmptyResult(goi->interp);
4643 else
4644 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4647 /* loop for more */
4648 break;
4650 case TCFG_WORK_AREA_VIRT:
4651 if (goi->isconfigure) {
4652 target_free_all_working_areas(target);
4653 e = Jim_GetOpt_Wide(goi, &w);
4654 if (e != JIM_OK)
4655 return e;
4656 target->working_area_virt = w;
4657 target->working_area_virt_spec = true;
4658 } else {
4659 if (goi->argc != 0)
4660 goto no_params;
4662 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4663 /* loop for more */
4664 break;
4666 case TCFG_WORK_AREA_PHYS:
4667 if (goi->isconfigure) {
4668 target_free_all_working_areas(target);
4669 e = Jim_GetOpt_Wide(goi, &w);
4670 if (e != JIM_OK)
4671 return e;
4672 target->working_area_phys = w;
4673 target->working_area_phys_spec = true;
4674 } else {
4675 if (goi->argc != 0)
4676 goto no_params;
4678 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4679 /* loop for more */
4680 break;
4682 case TCFG_WORK_AREA_SIZE:
4683 if (goi->isconfigure) {
4684 target_free_all_working_areas(target);
4685 e = Jim_GetOpt_Wide(goi, &w);
4686 if (e != JIM_OK)
4687 return e;
4688 target->working_area_size = w;
4689 } else {
4690 if (goi->argc != 0)
4691 goto no_params;
4693 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4694 /* loop for more */
4695 break;
4697 case TCFG_WORK_AREA_BACKUP:
4698 if (goi->isconfigure) {
4699 target_free_all_working_areas(target);
4700 e = Jim_GetOpt_Wide(goi, &w);
4701 if (e != JIM_OK)
4702 return e;
4703 /* make this exactly 1 or 0 */
4704 target->backup_working_area = (!!w);
4705 } else {
4706 if (goi->argc != 0)
4707 goto no_params;
4709 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4710 /* loop for more e*/
4711 break;
4714 case TCFG_ENDIAN:
4715 if (goi->isconfigure) {
4716 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4717 if (e != JIM_OK) {
4718 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4719 return e;
4721 target->endianness = n->value;
4722 } else {
4723 if (goi->argc != 0)
4724 goto no_params;
4726 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4727 if (n->name == NULL) {
4728 target->endianness = TARGET_LITTLE_ENDIAN;
4729 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4731 Jim_SetResultString(goi->interp, n->name, -1);
4732 /* loop for more */
4733 break;
4735 case TCFG_COREID:
4736 if (goi->isconfigure) {
4737 e = Jim_GetOpt_Wide(goi, &w);
4738 if (e != JIM_OK)
4739 return e;
4740 target->coreid = (int32_t)w;
4741 } else {
4742 if (goi->argc != 0)
4743 goto no_params;
4745 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4746 /* loop for more */
4747 break;
4749 case TCFG_CHAIN_POSITION:
4750 if (goi->isconfigure) {
4751 Jim_Obj *o_t;
4752 struct jtag_tap *tap;
4753 target_free_all_working_areas(target);
4754 e = Jim_GetOpt_Obj(goi, &o_t);
4755 if (e != JIM_OK)
4756 return e;
4757 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4758 if (tap == NULL)
4759 return JIM_ERR;
4760 /* make this exactly 1 or 0 */
4761 target->tap = tap;
4762 } else {
4763 if (goi->argc != 0)
4764 goto no_params;
4766 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4767 /* loop for more e*/
4768 break;
4769 case TCFG_DBGBASE:
4770 if (goi->isconfigure) {
4771 e = Jim_GetOpt_Wide(goi, &w);
4772 if (e != JIM_OK)
4773 return e;
4774 target->dbgbase = (uint32_t)w;
4775 target->dbgbase_set = true;
4776 } else {
4777 if (goi->argc != 0)
4778 goto no_params;
4780 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4781 /* loop for more */
4782 break;
4783 case TCFG_CTIBASE:
4784 if (goi->isconfigure) {
4785 e = Jim_GetOpt_Wide(goi, &w);
4786 if (e != JIM_OK)
4787 return e;
4788 target->ctibase = (uint32_t)w;
4789 target->ctibase_set = true;
4790 } else {
4791 if (goi->argc != 0)
4792 goto no_params;
4794 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->ctibase));
4795 /* loop for more */
4796 break;
4797 case TCFG_RTOS:
4798 /* RTOS */
4800 int result = rtos_create(goi, target);
4801 if (result != JIM_OK)
4802 return result;
4804 /* loop for more */
4805 break;
4807 case TCFG_DEFER_EXAMINE:
4808 /* DEFER_EXAMINE */
4809 target->defer_examine = true;
4810 /* loop for more */
4811 break;
4814 } /* while (goi->argc) */
4817 /* done - we return */
4818 return JIM_OK;
4821 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4823 Jim_GetOptInfo goi;
4825 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4826 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4827 if (goi.argc < 1) {
4828 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4829 "missing: -option ...");
4830 return JIM_ERR;
4832 struct target *target = Jim_CmdPrivData(goi.interp);
4833 return target_configure(&goi, target);
4836 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4838 const char *cmd_name = Jim_GetString(argv[0], NULL);
4840 Jim_GetOptInfo goi;
4841 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4843 if (goi.argc < 2 || goi.argc > 4) {
4844 Jim_SetResultFormatted(goi.interp,
4845 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4846 return JIM_ERR;
4849 target_write_fn fn;
4850 fn = target_write_memory;
4852 int e;
4853 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4854 /* consume it */
4855 struct Jim_Obj *obj;
4856 e = Jim_GetOpt_Obj(&goi, &obj);
4857 if (e != JIM_OK)
4858 return e;
4860 fn = target_write_phys_memory;
4863 jim_wide a;
4864 e = Jim_GetOpt_Wide(&goi, &a);
4865 if (e != JIM_OK)
4866 return e;
4868 jim_wide b;
4869 e = Jim_GetOpt_Wide(&goi, &b);
4870 if (e != JIM_OK)
4871 return e;
4873 jim_wide c = 1;
4874 if (goi.argc == 1) {
4875 e = Jim_GetOpt_Wide(&goi, &c);
4876 if (e != JIM_OK)
4877 return e;
4880 /* all args must be consumed */
4881 if (goi.argc != 0)
4882 return JIM_ERR;
4884 struct target *target = Jim_CmdPrivData(goi.interp);
4885 unsigned data_size;
4886 if (strcasecmp(cmd_name, "mww") == 0)
4887 data_size = 4;
4888 else if (strcasecmp(cmd_name, "mwh") == 0)
4889 data_size = 2;
4890 else if (strcasecmp(cmd_name, "mwb") == 0)
4891 data_size = 1;
4892 else {
4893 LOG_ERROR("command '%s' unknown: ", cmd_name);
4894 return JIM_ERR;
4897 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4901 * @brief Reads an array of words/halfwords/bytes from target memory starting at specified address.
4903 * Usage: mdw [phys] <address> [<count>] - for 32 bit reads
4904 * mdh [phys] <address> [<count>] - for 16 bit reads
4905 * mdb [phys] <address> [<count>] - for 8 bit reads
4907 * Count defaults to 1.
4909 * Calls target_read_memory or target_read_phys_memory depending on
4910 * the presence of the "phys" argument
4911 * Reads the target memory in blocks of max. 32 bytes, and returns an array of ints formatted
4912 * to int representation in base16.
4913 * Also outputs read data in a human readable form using command_print
4915 * @param phys if present target_read_phys_memory will be used instead of target_read_memory
4916 * @param address address where to start the read. May be specified in decimal or hex using the standard "0x" prefix
4917 * @param count optional count parameter to read an array of values. If not specified, defaults to 1.
4918 * @returns: JIM_ERR on error or JIM_OK on success and sets the result string to an array of ascii formatted numbers
4919 * on success, with [<count>] number of elements.
4921 * In case of little endian target:
4922 * Example1: "mdw 0x00000000" returns "10123456"
4923 * Exmaple2: "mdh 0x00000000 1" returns "3456"
4924 * Example3: "mdb 0x00000000" returns "56"
4925 * Example4: "mdh 0x00000000 2" returns "3456 1012"
4926 * Example5: "mdb 0x00000000 3" returns "56 34 12"
4928 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4930 const char *cmd_name = Jim_GetString(argv[0], NULL);
4932 Jim_GetOptInfo goi;
4933 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4935 if ((goi.argc < 1) || (goi.argc > 3)) {
4936 Jim_SetResultFormatted(goi.interp,
4937 "usage: %s [phys] <address> [<count>]", cmd_name);
4938 return JIM_ERR;
4941 int (*fn)(struct target *target,
4942 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4943 fn = target_read_memory;
4945 int e;
4946 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4947 /* consume it */
4948 struct Jim_Obj *obj;
4949 e = Jim_GetOpt_Obj(&goi, &obj);
4950 if (e != JIM_OK)
4951 return e;
4953 fn = target_read_phys_memory;
4956 /* Read address parameter */
4957 jim_wide addr;
4958 e = Jim_GetOpt_Wide(&goi, &addr);
4959 if (e != JIM_OK)
4960 return JIM_ERR;
4962 /* If next parameter exists, read it out as the count parameter, if not, set it to 1 (default) */
4963 jim_wide count;
4964 if (goi.argc == 1) {
4965 e = Jim_GetOpt_Wide(&goi, &count);
4966 if (e != JIM_OK)
4967 return JIM_ERR;
4968 } else
4969 count = 1;
4971 /* all args must be consumed */
4972 if (goi.argc != 0)
4973 return JIM_ERR;
4975 jim_wide dwidth = 1; /* shut up gcc */
4976 if (strcasecmp(cmd_name, "mdw") == 0)
4977 dwidth = 4;
4978 else if (strcasecmp(cmd_name, "mdh") == 0)
4979 dwidth = 2;
4980 else if (strcasecmp(cmd_name, "mdb") == 0)
4981 dwidth = 1;
4982 else {
4983 LOG_ERROR("command '%s' unknown: ", cmd_name);
4984 return JIM_ERR;
4987 /* convert count to "bytes" */
4988 int bytes = count * dwidth;
4990 struct target *target = Jim_CmdPrivData(goi.interp);
4991 uint8_t target_buf[32];
4992 jim_wide x, y, z;
4993 while (bytes > 0) {
4994 y = (bytes < 16) ? bytes : 16; /* y = min(bytes, 16); */
4996 /* Try to read out next block */
4997 e = fn(target, addr, dwidth, y / dwidth, target_buf);
4999 if (e != ERROR_OK) {
5000 Jim_SetResultFormatted(interp, "error reading target @ 0x%08lx", (long)addr);
5001 return JIM_ERR;
5004 command_print_sameline(NULL, "0x%08x ", (int)(addr));
5005 switch (dwidth) {
5006 case 4:
5007 for (x = 0; x < 16 && x < y; x += 4) {
5008 z = target_buffer_get_u32(target, &(target_buf[x]));
5009 command_print_sameline(NULL, "%08x ", (int)(z));
5011 for (; (x < 16) ; x += 4)
5012 command_print_sameline(NULL, " ");
5013 break;
5014 case 2:
5015 for (x = 0; x < 16 && x < y; x += 2) {
5016 z = target_buffer_get_u16(target, &(target_buf[x]));
5017 command_print_sameline(NULL, "%04x ", (int)(z));
5019 for (; (x < 16) ; x += 2)
5020 command_print_sameline(NULL, " ");
5021 break;
5022 case 1:
5023 default:
5024 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
5025 z = target_buffer_get_u8(target, &(target_buf[x]));
5026 command_print_sameline(NULL, "%02x ", (int)(z));
5028 for (; (x < 16) ; x += 1)
5029 command_print_sameline(NULL, " ");
5030 break;
5032 /* ascii-ify the bytes */
5033 for (x = 0 ; x < y ; x++) {
5034 if ((target_buf[x] >= 0x20) &&
5035 (target_buf[x] <= 0x7e)) {
5036 /* good */
5037 } else {
5038 /* smack it */
5039 target_buf[x] = '.';
5042 /* space pad */
5043 while (x < 16) {
5044 target_buf[x] = ' ';
5045 x++;
5047 /* terminate */
5048 target_buf[16] = 0;
5049 /* print - with a newline */
5050 command_print_sameline(NULL, "%s\n", target_buf);
5051 /* NEXT... */
5052 bytes -= 16;
5053 addr += 16;
5055 return JIM_OK;
5058 static int jim_target_mem2array(Jim_Interp *interp,
5059 int argc, Jim_Obj *const *argv)
5061 struct target *target = Jim_CmdPrivData(interp);
5062 return target_mem2array(interp, target, argc - 1, argv + 1);
5065 static int jim_target_array2mem(Jim_Interp *interp,
5066 int argc, Jim_Obj *const *argv)
5068 struct target *target = Jim_CmdPrivData(interp);
5069 return target_array2mem(interp, target, argc - 1, argv + 1);
5072 static int jim_target_tap_disabled(Jim_Interp *interp)
5074 Jim_SetResultFormatted(interp, "[TAP is disabled]");
5075 return JIM_ERR;
5078 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5080 bool allow_defer = false;
5082 Jim_GetOptInfo goi;
5083 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5084 if (goi.argc > 1) {
5085 const char *cmd_name = Jim_GetString(argv[0], NULL);
5086 Jim_SetResultFormatted(goi.interp,
5087 "usage: %s ['allow-defer']", cmd_name);
5088 return JIM_ERR;
5090 if (goi.argc > 0 &&
5091 strcmp(Jim_GetString(argv[1], NULL), "allow-defer") == 0) {
5092 /* consume it */
5093 struct Jim_Obj *obj;
5094 int e = Jim_GetOpt_Obj(&goi, &obj);
5095 if (e != JIM_OK)
5096 return e;
5097 allow_defer = true;
5100 struct target *target = Jim_CmdPrivData(interp);
5101 if (!target->tap->enabled)
5102 return jim_target_tap_disabled(interp);
5104 if (allow_defer && target->defer_examine) {
5105 LOG_INFO("Deferring arp_examine of %s", target_name(target));
5106 LOG_INFO("Use arp_examine command to examine it manually!");
5107 return JIM_OK;
5110 int e = target->type->examine(target);
5111 if (e != ERROR_OK)
5112 return JIM_ERR;
5113 return JIM_OK;
5116 static int jim_target_was_examined(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5118 struct target *target = Jim_CmdPrivData(interp);
5120 Jim_SetResultBool(interp, target_was_examined(target));
5121 return JIM_OK;
5124 static int jim_target_examine_deferred(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5126 struct target *target = Jim_CmdPrivData(interp);
5128 Jim_SetResultBool(interp, target->defer_examine);
5129 return JIM_OK;
5132 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5134 if (argc != 1) {
5135 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5136 return JIM_ERR;
5138 struct target *target = Jim_CmdPrivData(interp);
5140 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
5141 return JIM_ERR;
5143 return JIM_OK;
5146 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5148 if (argc != 1) {
5149 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5150 return JIM_ERR;
5152 struct target *target = Jim_CmdPrivData(interp);
5153 if (!target->tap->enabled)
5154 return jim_target_tap_disabled(interp);
5156 int e;
5157 if (!(target_was_examined(target)))
5158 e = ERROR_TARGET_NOT_EXAMINED;
5159 else
5160 e = target->type->poll(target);
5161 if (e != ERROR_OK)
5162 return JIM_ERR;
5163 return JIM_OK;
5166 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5168 Jim_GetOptInfo goi;
5169 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5171 if (goi.argc != 2) {
5172 Jim_WrongNumArgs(interp, 0, argv,
5173 "([tT]|[fF]|assert|deassert) BOOL");
5174 return JIM_ERR;
5177 Jim_Nvp *n;
5178 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
5179 if (e != JIM_OK) {
5180 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
5181 return e;
5183 /* the halt or not param */
5184 jim_wide a;
5185 e = Jim_GetOpt_Wide(&goi, &a);
5186 if (e != JIM_OK)
5187 return e;
5189 struct target *target = Jim_CmdPrivData(goi.interp);
5190 if (!target->tap->enabled)
5191 return jim_target_tap_disabled(interp);
5193 if (!target->type->assert_reset || !target->type->deassert_reset) {
5194 Jim_SetResultFormatted(interp,
5195 "No target-specific reset for %s",
5196 target_name(target));
5197 return JIM_ERR;
5200 if (target->defer_examine)
5201 target_reset_examined(target);
5203 /* determine if we should halt or not. */
5204 target->reset_halt = !!a;
5205 /* When this happens - all workareas are invalid. */
5206 target_free_all_working_areas_restore(target, 0);
5208 /* do the assert */
5209 if (n->value == NVP_ASSERT)
5210 e = target->type->assert_reset(target);
5211 else
5212 e = target->type->deassert_reset(target);
5213 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5216 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5218 if (argc != 1) {
5219 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5220 return JIM_ERR;
5222 struct target *target = Jim_CmdPrivData(interp);
5223 if (!target->tap->enabled)
5224 return jim_target_tap_disabled(interp);
5225 int e = target->type->halt(target);
5226 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5229 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5231 Jim_GetOptInfo goi;
5232 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5234 /* params: <name> statename timeoutmsecs */
5235 if (goi.argc != 2) {
5236 const char *cmd_name = Jim_GetString(argv[0], NULL);
5237 Jim_SetResultFormatted(goi.interp,
5238 "%s <state_name> <timeout_in_msec>", cmd_name);
5239 return JIM_ERR;
5242 Jim_Nvp *n;
5243 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
5244 if (e != JIM_OK) {
5245 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
5246 return e;
5248 jim_wide a;
5249 e = Jim_GetOpt_Wide(&goi, &a);
5250 if (e != JIM_OK)
5251 return e;
5252 struct target *target = Jim_CmdPrivData(interp);
5253 if (!target->tap->enabled)
5254 return jim_target_tap_disabled(interp);
5256 e = target_wait_state(target, n->value, a);
5257 if (e != ERROR_OK) {
5258 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
5259 Jim_SetResultFormatted(goi.interp,
5260 "target: %s wait %s fails (%#s) %s",
5261 target_name(target), n->name,
5262 eObj, target_strerror_safe(e));
5263 Jim_FreeNewObj(interp, eObj);
5264 return JIM_ERR;
5266 return JIM_OK;
5268 /* List for human, Events defined for this target.
5269 * scripts/programs should use 'name cget -event NAME'
5271 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5273 struct command_context *cmd_ctx = current_command_context(interp);
5274 assert(cmd_ctx != NULL);
5276 struct target *target = Jim_CmdPrivData(interp);
5277 struct target_event_action *teap = target->event_action;
5278 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
5279 target->target_number,
5280 target_name(target));
5281 command_print(cmd_ctx, "%-25s | Body", "Event");
5282 command_print(cmd_ctx, "------------------------- | "
5283 "----------------------------------------");
5284 while (teap) {
5285 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
5286 command_print(cmd_ctx, "%-25s | %s",
5287 opt->name, Jim_GetString(teap->body, NULL));
5288 teap = teap->next;
5290 command_print(cmd_ctx, "***END***");
5291 return JIM_OK;
5293 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5295 if (argc != 1) {
5296 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5297 return JIM_ERR;
5299 struct target *target = Jim_CmdPrivData(interp);
5300 Jim_SetResultString(interp, target_state_name(target), -1);
5301 return JIM_OK;
5303 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5305 Jim_GetOptInfo goi;
5306 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5307 if (goi.argc != 1) {
5308 const char *cmd_name = Jim_GetString(argv[0], NULL);
5309 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5310 return JIM_ERR;
5312 Jim_Nvp *n;
5313 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
5314 if (e != JIM_OK) {
5315 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
5316 return e;
5318 struct target *target = Jim_CmdPrivData(interp);
5319 target_handle_event(target, n->value);
5320 return JIM_OK;
5323 static const struct command_registration target_instance_command_handlers[] = {
5325 .name = "configure",
5326 .mode = COMMAND_CONFIG,
5327 .jim_handler = jim_target_configure,
5328 .help = "configure a new target for use",
5329 .usage = "[target_attribute ...]",
5332 .name = "cget",
5333 .mode = COMMAND_ANY,
5334 .jim_handler = jim_target_configure,
5335 .help = "returns the specified target attribute",
5336 .usage = "target_attribute",
5339 .name = "mww",
5340 .mode = COMMAND_EXEC,
5341 .jim_handler = jim_target_mw,
5342 .help = "Write 32-bit word(s) to target memory",
5343 .usage = "address data [count]",
5346 .name = "mwh",
5347 .mode = COMMAND_EXEC,
5348 .jim_handler = jim_target_mw,
5349 .help = "Write 16-bit half-word(s) to target memory",
5350 .usage = "address data [count]",
5353 .name = "mwb",
5354 .mode = COMMAND_EXEC,
5355 .jim_handler = jim_target_mw,
5356 .help = "Write byte(s) to target memory",
5357 .usage = "address data [count]",
5360 .name = "mdw",
5361 .mode = COMMAND_EXEC,
5362 .jim_handler = jim_target_md,
5363 .help = "Display target memory as 32-bit words",
5364 .usage = "address [count]",
5367 .name = "mdh",
5368 .mode = COMMAND_EXEC,
5369 .jim_handler = jim_target_md,
5370 .help = "Display target memory as 16-bit half-words",
5371 .usage = "address [count]",
5374 .name = "mdb",
5375 .mode = COMMAND_EXEC,
5376 .jim_handler = jim_target_md,
5377 .help = "Display target memory as 8-bit bytes",
5378 .usage = "address [count]",
5381 .name = "array2mem",
5382 .mode = COMMAND_EXEC,
5383 .jim_handler = jim_target_array2mem,
5384 .help = "Writes Tcl array of 8/16/32 bit numbers "
5385 "to target memory",
5386 .usage = "arrayname bitwidth address count",
5389 .name = "mem2array",
5390 .mode = COMMAND_EXEC,
5391 .jim_handler = jim_target_mem2array,
5392 .help = "Loads Tcl array of 8/16/32 bit numbers "
5393 "from target memory",
5394 .usage = "arrayname bitwidth address count",
5397 .name = "eventlist",
5398 .mode = COMMAND_EXEC,
5399 .jim_handler = jim_target_event_list,
5400 .help = "displays a table of events defined for this target",
5403 .name = "curstate",
5404 .mode = COMMAND_EXEC,
5405 .jim_handler = jim_target_current_state,
5406 .help = "displays the current state of this target",
5409 .name = "arp_examine",
5410 .mode = COMMAND_EXEC,
5411 .jim_handler = jim_target_examine,
5412 .help = "used internally for reset processing",
5413 .usage = "arp_examine ['allow-defer']",
5416 .name = "was_examined",
5417 .mode = COMMAND_EXEC,
5418 .jim_handler = jim_target_was_examined,
5419 .help = "used internally for reset processing",
5420 .usage = "was_examined",
5423 .name = "examine_deferred",
5424 .mode = COMMAND_EXEC,
5425 .jim_handler = jim_target_examine_deferred,
5426 .help = "used internally for reset processing",
5427 .usage = "examine_deferred",
5430 .name = "arp_halt_gdb",
5431 .mode = COMMAND_EXEC,
5432 .jim_handler = jim_target_halt_gdb,
5433 .help = "used internally for reset processing to halt GDB",
5436 .name = "arp_poll",
5437 .mode = COMMAND_EXEC,
5438 .jim_handler = jim_target_poll,
5439 .help = "used internally for reset processing",
5442 .name = "arp_reset",
5443 .mode = COMMAND_EXEC,
5444 .jim_handler = jim_target_reset,
5445 .help = "used internally for reset processing",
5448 .name = "arp_halt",
5449 .mode = COMMAND_EXEC,
5450 .jim_handler = jim_target_halt,
5451 .help = "used internally for reset processing",
5454 .name = "arp_waitstate",
5455 .mode = COMMAND_EXEC,
5456 .jim_handler = jim_target_wait_state,
5457 .help = "used internally for reset processing",
5460 .name = "invoke-event",
5461 .mode = COMMAND_EXEC,
5462 .jim_handler = jim_target_invoke_event,
5463 .help = "invoke handler for specified event",
5464 .usage = "event_name",
5466 COMMAND_REGISTRATION_DONE
5469 static int target_create(Jim_GetOptInfo *goi)
5471 Jim_Obj *new_cmd;
5472 Jim_Cmd *cmd;
5473 const char *cp;
5474 int e;
5475 int x;
5476 struct target *target;
5477 struct command_context *cmd_ctx;
5479 cmd_ctx = current_command_context(goi->interp);
5480 assert(cmd_ctx != NULL);
5482 if (goi->argc < 3) {
5483 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5484 return JIM_ERR;
5487 /* COMMAND */
5488 Jim_GetOpt_Obj(goi, &new_cmd);
5489 /* does this command exist? */
5490 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
5491 if (cmd) {
5492 cp = Jim_GetString(new_cmd, NULL);
5493 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5494 return JIM_ERR;
5497 /* TYPE */
5498 e = Jim_GetOpt_String(goi, &cp, NULL);
5499 if (e != JIM_OK)
5500 return e;
5501 struct transport *tr = get_current_transport();
5502 if (tr->override_target) {
5503 e = tr->override_target(&cp);
5504 if (e != ERROR_OK) {
5505 LOG_ERROR("The selected transport doesn't support this target");
5506 return JIM_ERR;
5508 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5510 /* now does target type exist */
5511 for (x = 0 ; target_types[x] ; x++) {
5512 if (0 == strcmp(cp, target_types[x]->name)) {
5513 /* found */
5514 break;
5517 /* check for deprecated name */
5518 if (target_types[x]->deprecated_name) {
5519 if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
5520 /* found */
5521 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
5522 break;
5526 if (target_types[x] == NULL) {
5527 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5528 for (x = 0 ; target_types[x] ; x++) {
5529 if (target_types[x + 1]) {
5530 Jim_AppendStrings(goi->interp,
5531 Jim_GetResult(goi->interp),
5532 target_types[x]->name,
5533 ", ", NULL);
5534 } else {
5535 Jim_AppendStrings(goi->interp,
5536 Jim_GetResult(goi->interp),
5537 " or ",
5538 target_types[x]->name, NULL);
5541 return JIM_ERR;
5544 /* Create it */
5545 target = calloc(1, sizeof(struct target));
5546 /* set target number */
5547 target->target_number = new_target_number();
5548 cmd_ctx->current_target = target;
5550 /* allocate memory for each unique target type */
5551 target->type = calloc(1, sizeof(struct target_type));
5553 memcpy(target->type, target_types[x], sizeof(struct target_type));
5555 /* will be set by "-endian" */
5556 target->endianness = TARGET_ENDIAN_UNKNOWN;
5558 /* default to first core, override with -coreid */
5559 target->coreid = 0;
5561 target->working_area = 0x0;
5562 target->working_area_size = 0x0;
5563 target->working_areas = NULL;
5564 target->backup_working_area = 0;
5566 target->state = TARGET_UNKNOWN;
5567 target->debug_reason = DBG_REASON_UNDEFINED;
5568 target->reg_cache = NULL;
5569 target->breakpoints = NULL;
5570 target->watchpoints = NULL;
5571 target->next = NULL;
5572 target->arch_info = NULL;
5574 target->display = 1;
5576 target->halt_issued = false;
5578 /* initialize trace information */
5579 target->trace_info = calloc(1, sizeof(struct trace));
5581 target->dbgmsg = NULL;
5582 target->dbg_msg_enabled = 0;
5584 target->endianness = TARGET_ENDIAN_UNKNOWN;
5586 target->rtos = NULL;
5587 target->rtos_auto_detect = false;
5589 /* Do the rest as "configure" options */
5590 goi->isconfigure = 1;
5591 e = target_configure(goi, target);
5593 if (target->tap == NULL) {
5594 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
5595 e = JIM_ERR;
5598 if (e != JIM_OK) {
5599 free(target->type);
5600 free(target);
5601 return e;
5604 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5605 /* default endian to little if not specified */
5606 target->endianness = TARGET_LITTLE_ENDIAN;
5609 cp = Jim_GetString(new_cmd, NULL);
5610 target->cmd_name = strdup(cp);
5612 /* create the target specific commands */
5613 if (target->type->commands) {
5614 e = register_commands(cmd_ctx, NULL, target->type->commands);
5615 if (ERROR_OK != e)
5616 LOG_ERROR("unable to register '%s' commands", cp);
5618 if (target->type->target_create)
5619 (*(target->type->target_create))(target, goi->interp);
5621 /* append to end of list */
5623 struct target **tpp;
5624 tpp = &(all_targets);
5625 while (*tpp)
5626 tpp = &((*tpp)->next);
5627 *tpp = target;
5630 /* now - create the new target name command */
5631 const struct command_registration target_subcommands[] = {
5633 .chain = target_instance_command_handlers,
5636 .chain = target->type->commands,
5638 COMMAND_REGISTRATION_DONE
5640 const struct command_registration target_commands[] = {
5642 .name = cp,
5643 .mode = COMMAND_ANY,
5644 .help = "target command group",
5645 .usage = "",
5646 .chain = target_subcommands,
5648 COMMAND_REGISTRATION_DONE
5650 e = register_commands(cmd_ctx, NULL, target_commands);
5651 if (ERROR_OK != e)
5652 return JIM_ERR;
5654 struct command *c = command_find_in_context(cmd_ctx, cp);
5655 assert(c);
5656 command_set_handler_data(c, target);
5658 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5661 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5663 if (argc != 1) {
5664 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5665 return JIM_ERR;
5667 struct command_context *cmd_ctx = current_command_context(interp);
5668 assert(cmd_ctx != NULL);
5670 Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5671 return JIM_OK;
5674 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5676 if (argc != 1) {
5677 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5678 return JIM_ERR;
5680 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5681 for (unsigned x = 0; NULL != target_types[x]; x++) {
5682 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5683 Jim_NewStringObj(interp, target_types[x]->name, -1));
5685 return JIM_OK;
5688 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5690 if (argc != 1) {
5691 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5692 return JIM_ERR;
5694 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5695 struct target *target = all_targets;
5696 while (target) {
5697 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5698 Jim_NewStringObj(interp, target_name(target), -1));
5699 target = target->next;
5701 return JIM_OK;
5704 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5706 int i;
5707 const char *targetname;
5708 int retval, len;
5709 struct target *target = (struct target *) NULL;
5710 struct target_list *head, *curr, *new;
5711 curr = (struct target_list *) NULL;
5712 head = (struct target_list *) NULL;
5714 retval = 0;
5715 LOG_DEBUG("%d", argc);
5716 /* argv[1] = target to associate in smp
5717 * argv[2] = target to assoicate in smp
5718 * argv[3] ...
5721 for (i = 1; i < argc; i++) {
5723 targetname = Jim_GetString(argv[i], &len);
5724 target = get_target(targetname);
5725 LOG_DEBUG("%s ", targetname);
5726 if (target) {
5727 new = malloc(sizeof(struct target_list));
5728 new->target = target;
5729 new->next = (struct target_list *)NULL;
5730 if (head == (struct target_list *)NULL) {
5731 head = new;
5732 curr = head;
5733 } else {
5734 curr->next = new;
5735 curr = new;
5739 /* now parse the list of cpu and put the target in smp mode*/
5740 curr = head;
5742 while (curr != (struct target_list *)NULL) {
5743 target = curr->target;
5744 target->smp = 1;
5745 target->head = head;
5746 curr = curr->next;
5749 if (target && target->rtos)
5750 retval = rtos_smp_init(head->target);
5752 return retval;
5756 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5758 Jim_GetOptInfo goi;
5759 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5760 if (goi.argc < 3) {
5761 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5762 "<name> <target_type> [<target_options> ...]");
5763 return JIM_ERR;
5765 return target_create(&goi);
5768 static const struct command_registration target_subcommand_handlers[] = {
5770 .name = "init",
5771 .mode = COMMAND_CONFIG,
5772 .handler = handle_target_init_command,
5773 .help = "initialize targets",
5776 .name = "create",
5777 /* REVISIT this should be COMMAND_CONFIG ... */
5778 .mode = COMMAND_ANY,
5779 .jim_handler = jim_target_create,
5780 .usage = "name type '-chain-position' name [options ...]",
5781 .help = "Creates and selects a new target",
5784 .name = "current",
5785 .mode = COMMAND_ANY,
5786 .jim_handler = jim_target_current,
5787 .help = "Returns the currently selected target",
5790 .name = "types",
5791 .mode = COMMAND_ANY,
5792 .jim_handler = jim_target_types,
5793 .help = "Returns the available target types as "
5794 "a list of strings",
5797 .name = "names",
5798 .mode = COMMAND_ANY,
5799 .jim_handler = jim_target_names,
5800 .help = "Returns the names of all targets as a list of strings",
5803 .name = "smp",
5804 .mode = COMMAND_ANY,
5805 .jim_handler = jim_target_smp,
5806 .usage = "targetname1 targetname2 ...",
5807 .help = "gather several target in a smp list"
5810 COMMAND_REGISTRATION_DONE
5813 struct FastLoad {
5814 target_addr_t address;
5815 uint8_t *data;
5816 int length;
5820 static int fastload_num;
5821 static struct FastLoad *fastload;
5823 static void free_fastload(void)
5825 if (fastload != NULL) {
5826 int i;
5827 for (i = 0; i < fastload_num; i++) {
5828 if (fastload[i].data)
5829 free(fastload[i].data);
5831 free(fastload);
5832 fastload = NULL;
5836 COMMAND_HANDLER(handle_fast_load_image_command)
5838 uint8_t *buffer;
5839 size_t buf_cnt;
5840 uint32_t image_size;
5841 target_addr_t min_address = 0;
5842 target_addr_t max_address = -1;
5843 int i;
5845 struct image image;
5847 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5848 &image, &min_address, &max_address);
5849 if (ERROR_OK != retval)
5850 return retval;
5852 struct duration bench;
5853 duration_start(&bench);
5855 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5856 if (retval != ERROR_OK)
5857 return retval;
5859 image_size = 0x0;
5860 retval = ERROR_OK;
5861 fastload_num = image.num_sections;
5862 fastload = malloc(sizeof(struct FastLoad)*image.num_sections);
5863 if (fastload == NULL) {
5864 command_print(CMD_CTX, "out of memory");
5865 image_close(&image);
5866 return ERROR_FAIL;
5868 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5869 for (i = 0; i < image.num_sections; i++) {
5870 buffer = malloc(image.sections[i].size);
5871 if (buffer == NULL) {
5872 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5873 (int)(image.sections[i].size));
5874 retval = ERROR_FAIL;
5875 break;
5878 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5879 if (retval != ERROR_OK) {
5880 free(buffer);
5881 break;
5884 uint32_t offset = 0;
5885 uint32_t length = buf_cnt;
5887 /* DANGER!!! beware of unsigned comparision here!!! */
5889 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5890 (image.sections[i].base_address < max_address)) {
5891 if (image.sections[i].base_address < min_address) {
5892 /* clip addresses below */
5893 offset += min_address-image.sections[i].base_address;
5894 length -= offset;
5897 if (image.sections[i].base_address + buf_cnt > max_address)
5898 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5900 fastload[i].address = image.sections[i].base_address + offset;
5901 fastload[i].data = malloc(length);
5902 if (fastload[i].data == NULL) {
5903 free(buffer);
5904 command_print(CMD_CTX, "error allocating buffer for section (%" PRIu32 " bytes)",
5905 length);
5906 retval = ERROR_FAIL;
5907 break;
5909 memcpy(fastload[i].data, buffer + offset, length);
5910 fastload[i].length = length;
5912 image_size += length;
5913 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5914 (unsigned int)length,
5915 ((unsigned int)(image.sections[i].base_address + offset)));
5918 free(buffer);
5921 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5922 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5923 "in %fs (%0.3f KiB/s)", image_size,
5924 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5926 command_print(CMD_CTX,
5927 "WARNING: image has not been loaded to target!"
5928 "You can issue a 'fast_load' to finish loading.");
5931 image_close(&image);
5933 if (retval != ERROR_OK)
5934 free_fastload();
5936 return retval;
5939 COMMAND_HANDLER(handle_fast_load_command)
5941 if (CMD_ARGC > 0)
5942 return ERROR_COMMAND_SYNTAX_ERROR;
5943 if (fastload == NULL) {
5944 LOG_ERROR("No image in memory");
5945 return ERROR_FAIL;
5947 int i;
5948 int64_t ms = timeval_ms();
5949 int size = 0;
5950 int retval = ERROR_OK;
5951 for (i = 0; i < fastload_num; i++) {
5952 struct target *target = get_current_target(CMD_CTX);
5953 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5954 (unsigned int)(fastload[i].address),
5955 (unsigned int)(fastload[i].length));
5956 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5957 if (retval != ERROR_OK)
5958 break;
5959 size += fastload[i].length;
5961 if (retval == ERROR_OK) {
5962 int64_t after = timeval_ms();
5963 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5965 return retval;
5968 static const struct command_registration target_command_handlers[] = {
5970 .name = "targets",
5971 .handler = handle_targets_command,
5972 .mode = COMMAND_ANY,
5973 .help = "change current default target (one parameter) "
5974 "or prints table of all targets (no parameters)",
5975 .usage = "[target]",
5978 .name = "target",
5979 .mode = COMMAND_CONFIG,
5980 .help = "configure target",
5982 .chain = target_subcommand_handlers,
5984 COMMAND_REGISTRATION_DONE
5987 int target_register_commands(struct command_context *cmd_ctx)
5989 return register_commands(cmd_ctx, NULL, target_command_handlers);
5992 static bool target_reset_nag = true;
5994 bool get_target_reset_nag(void)
5996 return target_reset_nag;
5999 COMMAND_HANDLER(handle_target_reset_nag)
6001 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
6002 &target_reset_nag, "Nag after each reset about options to improve "
6003 "performance");
6006 COMMAND_HANDLER(handle_ps_command)
6008 struct target *target = get_current_target(CMD_CTX);
6009 char *display;
6010 if (target->state != TARGET_HALTED) {
6011 LOG_INFO("target not halted !!");
6012 return ERROR_OK;
6015 if ((target->rtos) && (target->rtos->type)
6016 && (target->rtos->type->ps_command)) {
6017 display = target->rtos->type->ps_command(target);
6018 command_print(CMD_CTX, "%s", display);
6019 free(display);
6020 return ERROR_OK;
6021 } else {
6022 LOG_INFO("failed");
6023 return ERROR_TARGET_FAILURE;
6027 static void binprint(struct command_context *cmd_ctx, const char *text, const uint8_t *buf, int size)
6029 if (text != NULL)
6030 command_print_sameline(cmd_ctx, "%s", text);
6031 for (int i = 0; i < size; i++)
6032 command_print_sameline(cmd_ctx, " %02x", buf[i]);
6033 command_print(cmd_ctx, " ");
6036 COMMAND_HANDLER(handle_test_mem_access_command)
6038 struct target *target = get_current_target(CMD_CTX);
6039 uint32_t test_size;
6040 int retval = ERROR_OK;
6042 if (target->state != TARGET_HALTED) {
6043 LOG_INFO("target not halted !!");
6044 return ERROR_FAIL;
6047 if (CMD_ARGC != 1)
6048 return ERROR_COMMAND_SYNTAX_ERROR;
6050 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
6052 /* Test reads */
6053 size_t num_bytes = test_size + 4;
6055 struct working_area *wa = NULL;
6056 retval = target_alloc_working_area(target, num_bytes, &wa);
6057 if (retval != ERROR_OK) {
6058 LOG_ERROR("Not enough working area");
6059 return ERROR_FAIL;
6062 uint8_t *test_pattern = malloc(num_bytes);
6064 for (size_t i = 0; i < num_bytes; i++)
6065 test_pattern[i] = rand();
6067 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6068 if (retval != ERROR_OK) {
6069 LOG_ERROR("Test pattern write failed");
6070 goto out;
6073 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6074 for (int size = 1; size <= 4; size *= 2) {
6075 for (int offset = 0; offset < 4; offset++) {
6076 uint32_t count = test_size / size;
6077 size_t host_bufsiz = (count + 2) * size + host_offset;
6078 uint8_t *read_ref = malloc(host_bufsiz);
6079 uint8_t *read_buf = malloc(host_bufsiz);
6081 for (size_t i = 0; i < host_bufsiz; i++) {
6082 read_ref[i] = rand();
6083 read_buf[i] = read_ref[i];
6085 command_print_sameline(CMD_CTX,
6086 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
6087 size, offset, host_offset ? "un" : "");
6089 struct duration bench;
6090 duration_start(&bench);
6092 retval = target_read_memory(target, wa->address + offset, size, count,
6093 read_buf + size + host_offset);
6095 duration_measure(&bench);
6097 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6098 command_print(CMD_CTX, "Unsupported alignment");
6099 goto next;
6100 } else if (retval != ERROR_OK) {
6101 command_print(CMD_CTX, "Memory read failed");
6102 goto next;
6105 /* replay on host */
6106 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
6108 /* check result */
6109 int result = memcmp(read_ref, read_buf, host_bufsiz);
6110 if (result == 0) {
6111 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
6112 duration_elapsed(&bench),
6113 duration_kbps(&bench, count * size));
6114 } else {
6115 command_print(CMD_CTX, "Compare failed");
6116 binprint(CMD_CTX, "ref:", read_ref, host_bufsiz);
6117 binprint(CMD_CTX, "buf:", read_buf, host_bufsiz);
6119 next:
6120 free(read_ref);
6121 free(read_buf);
6126 out:
6127 free(test_pattern);
6129 if (wa != NULL)
6130 target_free_working_area(target, wa);
6132 /* Test writes */
6133 num_bytes = test_size + 4 + 4 + 4;
6135 retval = target_alloc_working_area(target, num_bytes, &wa);
6136 if (retval != ERROR_OK) {
6137 LOG_ERROR("Not enough working area");
6138 return ERROR_FAIL;
6141 test_pattern = malloc(num_bytes);
6143 for (size_t i = 0; i < num_bytes; i++)
6144 test_pattern[i] = rand();
6146 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6147 for (int size = 1; size <= 4; size *= 2) {
6148 for (int offset = 0; offset < 4; offset++) {
6149 uint32_t count = test_size / size;
6150 size_t host_bufsiz = count * size + host_offset;
6151 uint8_t *read_ref = malloc(num_bytes);
6152 uint8_t *read_buf = malloc(num_bytes);
6153 uint8_t *write_buf = malloc(host_bufsiz);
6155 for (size_t i = 0; i < host_bufsiz; i++)
6156 write_buf[i] = rand();
6157 command_print_sameline(CMD_CTX,
6158 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
6159 size, offset, host_offset ? "un" : "");
6161 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6162 if (retval != ERROR_OK) {
6163 command_print(CMD_CTX, "Test pattern write failed");
6164 goto nextw;
6167 /* replay on host */
6168 memcpy(read_ref, test_pattern, num_bytes);
6169 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
6171 struct duration bench;
6172 duration_start(&bench);
6174 retval = target_write_memory(target, wa->address + size + offset, size, count,
6175 write_buf + host_offset);
6177 duration_measure(&bench);
6179 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6180 command_print(CMD_CTX, "Unsupported alignment");
6181 goto nextw;
6182 } else if (retval != ERROR_OK) {
6183 command_print(CMD_CTX, "Memory write failed");
6184 goto nextw;
6187 /* read back */
6188 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
6189 if (retval != ERROR_OK) {
6190 command_print(CMD_CTX, "Test pattern write failed");
6191 goto nextw;
6194 /* check result */
6195 int result = memcmp(read_ref, read_buf, num_bytes);
6196 if (result == 0) {
6197 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
6198 duration_elapsed(&bench),
6199 duration_kbps(&bench, count * size));
6200 } else {
6201 command_print(CMD_CTX, "Compare failed");
6202 binprint(CMD_CTX, "ref:", read_ref, num_bytes);
6203 binprint(CMD_CTX, "buf:", read_buf, num_bytes);
6205 nextw:
6206 free(read_ref);
6207 free(read_buf);
6212 free(test_pattern);
6214 if (wa != NULL)
6215 target_free_working_area(target, wa);
6216 return retval;
6219 static const struct command_registration target_exec_command_handlers[] = {
6221 .name = "fast_load_image",
6222 .handler = handle_fast_load_image_command,
6223 .mode = COMMAND_ANY,
6224 .help = "Load image into server memory for later use by "
6225 "fast_load; primarily for profiling",
6226 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6227 "[min_address [max_length]]",
6230 .name = "fast_load",
6231 .handler = handle_fast_load_command,
6232 .mode = COMMAND_EXEC,
6233 .help = "loads active fast load image to current target "
6234 "- mainly for profiling purposes",
6235 .usage = "",
6238 .name = "profile",
6239 .handler = handle_profile_command,
6240 .mode = COMMAND_EXEC,
6241 .usage = "seconds filename [start end]",
6242 .help = "profiling samples the CPU PC",
6244 /** @todo don't register virt2phys() unless target supports it */
6246 .name = "virt2phys",
6247 .handler = handle_virt2phys_command,
6248 .mode = COMMAND_ANY,
6249 .help = "translate a virtual address into a physical address",
6250 .usage = "virtual_address",
6253 .name = "reg",
6254 .handler = handle_reg_command,
6255 .mode = COMMAND_EXEC,
6256 .help = "display (reread from target with \"force\") or set a register; "
6257 "with no arguments, displays all registers and their values",
6258 .usage = "[(register_number|register_name) [(value|'force')]]",
6261 .name = "poll",
6262 .handler = handle_poll_command,
6263 .mode = COMMAND_EXEC,
6264 .help = "poll target state; or reconfigure background polling",
6265 .usage = "['on'|'off']",
6268 .name = "wait_halt",
6269 .handler = handle_wait_halt_command,
6270 .mode = COMMAND_EXEC,
6271 .help = "wait up to the specified number of milliseconds "
6272 "(default 5000) for a previously requested halt",
6273 .usage = "[milliseconds]",
6276 .name = "halt",
6277 .handler = handle_halt_command,
6278 .mode = COMMAND_EXEC,
6279 .help = "request target to halt, then wait up to the specified"
6280 "number of milliseconds (default 5000) for it to complete",
6281 .usage = "[milliseconds]",
6284 .name = "resume",
6285 .handler = handle_resume_command,
6286 .mode = COMMAND_EXEC,
6287 .help = "resume target execution from current PC or address",
6288 .usage = "[address]",
6291 .name = "reset",
6292 .handler = handle_reset_command,
6293 .mode = COMMAND_EXEC,
6294 .usage = "[run|halt|init]",
6295 .help = "Reset all targets into the specified mode."
6296 "Default reset mode is run, if not given.",
6299 .name = "soft_reset_halt",
6300 .handler = handle_soft_reset_halt_command,
6301 .mode = COMMAND_EXEC,
6302 .usage = "",
6303 .help = "halt the target and do a soft reset",
6306 .name = "step",
6307 .handler = handle_step_command,
6308 .mode = COMMAND_EXEC,
6309 .help = "step one instruction from current PC or address",
6310 .usage = "[address]",
6313 .name = "mdd",
6314 .handler = handle_md_command,
6315 .mode = COMMAND_EXEC,
6316 .help = "display memory words",
6317 .usage = "['phys'] address [count]",
6320 .name = "mdw",
6321 .handler = handle_md_command,
6322 .mode = COMMAND_EXEC,
6323 .help = "display memory words",
6324 .usage = "['phys'] address [count]",
6327 .name = "mdh",
6328 .handler = handle_md_command,
6329 .mode = COMMAND_EXEC,
6330 .help = "display memory half-words",
6331 .usage = "['phys'] address [count]",
6334 .name = "mdb",
6335 .handler = handle_md_command,
6336 .mode = COMMAND_EXEC,
6337 .help = "display memory bytes",
6338 .usage = "['phys'] address [count]",
6341 .name = "mwd",
6342 .handler = handle_mw_command,
6343 .mode = COMMAND_EXEC,
6344 .help = "write memory word",
6345 .usage = "['phys'] address value [count]",
6348 .name = "mww",
6349 .handler = handle_mw_command,
6350 .mode = COMMAND_EXEC,
6351 .help = "write memory word",
6352 .usage = "['phys'] address value [count]",
6355 .name = "mwh",
6356 .handler = handle_mw_command,
6357 .mode = COMMAND_EXEC,
6358 .help = "write memory half-word",
6359 .usage = "['phys'] address value [count]",
6362 .name = "mwb",
6363 .handler = handle_mw_command,
6364 .mode = COMMAND_EXEC,
6365 .help = "write memory byte",
6366 .usage = "['phys'] address value [count]",
6369 .name = "bp",
6370 .handler = handle_bp_command,
6371 .mode = COMMAND_EXEC,
6372 .help = "list or set hardware or software breakpoint",
6373 .usage = "<address> [<asid>]<length> ['hw'|'hw_ctx']",
6376 .name = "rbp",
6377 .handler = handle_rbp_command,
6378 .mode = COMMAND_EXEC,
6379 .help = "remove breakpoint",
6380 .usage = "address",
6383 .name = "wp",
6384 .handler = handle_wp_command,
6385 .mode = COMMAND_EXEC,
6386 .help = "list (no params) or create watchpoints",
6387 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
6390 .name = "rwp",
6391 .handler = handle_rwp_command,
6392 .mode = COMMAND_EXEC,
6393 .help = "remove watchpoint",
6394 .usage = "address",
6397 .name = "load_image",
6398 .handler = handle_load_image_command,
6399 .mode = COMMAND_EXEC,
6400 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6401 "[min_address] [max_length]",
6404 .name = "dump_image",
6405 .handler = handle_dump_image_command,
6406 .mode = COMMAND_EXEC,
6407 .usage = "filename address size",
6410 .name = "verify_image_checksum",
6411 .handler = handle_verify_image_checksum_command,
6412 .mode = COMMAND_EXEC,
6413 .usage = "filename [offset [type]]",
6416 .name = "verify_image",
6417 .handler = handle_verify_image_command,
6418 .mode = COMMAND_EXEC,
6419 .usage = "filename [offset [type]]",
6422 .name = "test_image",
6423 .handler = handle_test_image_command,
6424 .mode = COMMAND_EXEC,
6425 .usage = "filename [offset [type]]",
6428 .name = "mem2array",
6429 .mode = COMMAND_EXEC,
6430 .jim_handler = jim_mem2array,
6431 .help = "read 8/16/32 bit memory and return as a TCL array "
6432 "for script processing",
6433 .usage = "arrayname bitwidth address count",
6436 .name = "array2mem",
6437 .mode = COMMAND_EXEC,
6438 .jim_handler = jim_array2mem,
6439 .help = "convert a TCL array to memory locations "
6440 "and write the 8/16/32 bit values",
6441 .usage = "arrayname bitwidth address count",
6444 .name = "reset_nag",
6445 .handler = handle_target_reset_nag,
6446 .mode = COMMAND_ANY,
6447 .help = "Nag after each reset about options that could have been "
6448 "enabled to improve performance. ",
6449 .usage = "['enable'|'disable']",
6452 .name = "ps",
6453 .handler = handle_ps_command,
6454 .mode = COMMAND_EXEC,
6455 .help = "list all tasks ",
6456 .usage = " ",
6459 .name = "test_mem_access",
6460 .handler = handle_test_mem_access_command,
6461 .mode = COMMAND_EXEC,
6462 .help = "Test the target's memory access functions",
6463 .usage = "size",
6466 COMMAND_REGISTRATION_DONE
6468 static int target_register_user_commands(struct command_context *cmd_ctx)
6470 int retval = ERROR_OK;
6471 retval = target_request_register_commands(cmd_ctx);
6472 if (retval != ERROR_OK)
6473 return retval;
6475 retval = trace_register_commands(cmd_ctx);
6476 if (retval != ERROR_OK)
6477 return retval;
6480 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);