update files to correct FSF address
[openocd.git] / src / target / target.c
blob464954141e35baa7df04ec4e63156b3a4840ea12
1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
4 * *
5 * Copyright (C) 2007-2010 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
7 * *
8 * Copyright (C) 2008, Duane Ellis *
9 * openocd@duaneeellis.com *
10 * *
11 * Copyright (C) 2008 by Spencer Oliver *
12 * spen@spen-soft.co.uk *
13 * *
14 * Copyright (C) 2008 by Rick Altherr *
15 * kc8apf@kc8apf.net> *
16 * *
17 * Copyright (C) 2011 by Broadcom Corporation *
18 * Evan Hunter - ehunter@broadcom.com *
19 * *
20 * Copyright (C) ST-Ericsson SA 2011 *
21 * michel.jaouen@stericsson.com : smp minimum support *
22 * *
23 * Copyright (C) 2011 Andreas Fritiofson *
24 * andreas.fritiofson@gmail.com *
25 * *
26 * This program is free software; you can redistribute it and/or modify *
27 * it under the terms of the GNU General Public License as published by *
28 * the Free Software Foundation; either version 2 of the License, or *
29 * (at your option) any later version. *
30 * *
31 * This program is distributed in the hope that it will be useful, *
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
34 * GNU General Public License for more details. *
35 * *
36 * You should have received a copy of the GNU General Public License *
37 * along with this program; if not, write to the *
38 * Free Software Foundation, Inc., *
39 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
40 ***************************************************************************/
42 #ifdef HAVE_CONFIG_H
43 #include "config.h"
44 #endif
46 #include <helper/time_support.h>
47 #include <jtag/jtag.h>
48 #include <flash/nor/core.h>
50 #include "target.h"
51 #include "target_type.h"
52 #include "target_request.h"
53 #include "breakpoints.h"
54 #include "register.h"
55 #include "trace.h"
56 #include "image.h"
57 #include "rtos/rtos.h"
59 static int target_read_buffer_default(struct target *target, uint32_t address,
60 uint32_t size, uint8_t *buffer);
61 static int target_write_buffer_default(struct target *target, uint32_t address,
62 uint32_t size, const uint8_t *buffer);
63 static int target_array2mem(Jim_Interp *interp, struct target *target,
64 int argc, Jim_Obj * const *argv);
65 static int target_mem2array(Jim_Interp *interp, struct target *target,
66 int argc, Jim_Obj * const *argv);
67 static int target_register_user_commands(struct command_context *cmd_ctx);
69 /* targets */
70 extern struct target_type arm7tdmi_target;
71 extern struct target_type arm720t_target;
72 extern struct target_type arm9tdmi_target;
73 extern struct target_type arm920t_target;
74 extern struct target_type arm966e_target;
75 extern struct target_type arm946e_target;
76 extern struct target_type arm926ejs_target;
77 extern struct target_type fa526_target;
78 extern struct target_type feroceon_target;
79 extern struct target_type dragonite_target;
80 extern struct target_type xscale_target;
81 extern struct target_type cortexm3_target;
82 extern struct target_type cortexa8_target;
83 extern struct target_type cortexr4_target;
84 extern struct target_type arm11_target;
85 extern struct target_type mips_m4k_target;
86 extern struct target_type avr_target;
87 extern struct target_type dsp563xx_target;
88 extern struct target_type dsp5680xx_target;
89 extern struct target_type testee_target;
90 extern struct target_type avr32_ap7k_target;
91 extern struct target_type hla_target;
92 extern struct target_type nds32_v2_target;
93 extern struct target_type nds32_v3_target;
94 extern struct target_type nds32_v3m_target;
96 static struct target_type *target_types[] = {
97 &arm7tdmi_target,
98 &arm9tdmi_target,
99 &arm920t_target,
100 &arm720t_target,
101 &arm966e_target,
102 &arm946e_target,
103 &arm926ejs_target,
104 &fa526_target,
105 &feroceon_target,
106 &dragonite_target,
107 &xscale_target,
108 &cortexm3_target,
109 &cortexa8_target,
110 &cortexr4_target,
111 &arm11_target,
112 &mips_m4k_target,
113 &avr_target,
114 &dsp563xx_target,
115 &dsp5680xx_target,
116 &testee_target,
117 &avr32_ap7k_target,
118 &hla_target,
119 &nds32_v2_target,
120 &nds32_v3_target,
121 &nds32_v3m_target,
122 NULL,
125 struct target *all_targets;
126 static struct target_event_callback *target_event_callbacks;
127 static struct target_timer_callback *target_timer_callbacks;
128 static const int polling_interval = 100;
130 static const Jim_Nvp nvp_assert[] = {
131 { .name = "assert", NVP_ASSERT },
132 { .name = "deassert", NVP_DEASSERT },
133 { .name = "T", NVP_ASSERT },
134 { .name = "F", NVP_DEASSERT },
135 { .name = "t", NVP_ASSERT },
136 { .name = "f", NVP_DEASSERT },
137 { .name = NULL, .value = -1 }
140 static const Jim_Nvp nvp_error_target[] = {
141 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
142 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
143 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
144 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
145 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
146 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
147 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
148 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
149 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
150 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
151 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
152 { .value = -1, .name = NULL }
155 static const char *target_strerror_safe(int err)
157 const Jim_Nvp *n;
159 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
160 if (n->name == NULL)
161 return "unknown";
162 else
163 return n->name;
166 static const Jim_Nvp nvp_target_event[] = {
168 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
169 { .value = TARGET_EVENT_HALTED, .name = "halted" },
170 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
171 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
172 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
174 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
175 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
177 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
178 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
179 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
180 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
181 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
182 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
183 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
184 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
185 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
186 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
187 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
188 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
190 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
191 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
193 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
194 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
196 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
197 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
199 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
200 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
202 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
203 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
205 { .name = NULL, .value = -1 }
208 static const Jim_Nvp nvp_target_state[] = {
209 { .name = "unknown", .value = TARGET_UNKNOWN },
210 { .name = "running", .value = TARGET_RUNNING },
211 { .name = "halted", .value = TARGET_HALTED },
212 { .name = "reset", .value = TARGET_RESET },
213 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
214 { .name = NULL, .value = -1 },
217 static const Jim_Nvp nvp_target_debug_reason[] = {
218 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
219 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
220 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
221 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
222 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
223 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
224 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
225 { .name = NULL, .value = -1 },
228 static const Jim_Nvp nvp_target_endian[] = {
229 { .name = "big", .value = TARGET_BIG_ENDIAN },
230 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
231 { .name = "be", .value = TARGET_BIG_ENDIAN },
232 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
233 { .name = NULL, .value = -1 },
236 static const Jim_Nvp nvp_reset_modes[] = {
237 { .name = "unknown", .value = RESET_UNKNOWN },
238 { .name = "run" , .value = RESET_RUN },
239 { .name = "halt" , .value = RESET_HALT },
240 { .name = "init" , .value = RESET_INIT },
241 { .name = NULL , .value = -1 },
244 const char *debug_reason_name(struct target *t)
246 const char *cp;
248 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
249 t->debug_reason)->name;
250 if (!cp) {
251 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
252 cp = "(*BUG*unknown*BUG*)";
254 return cp;
257 const char *target_state_name(struct target *t)
259 const char *cp;
260 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
261 if (!cp) {
262 LOG_ERROR("Invalid target state: %d", (int)(t->state));
263 cp = "(*BUG*unknown*BUG*)";
265 return cp;
268 /* determine the number of the new target */
269 static int new_target_number(void)
271 struct target *t;
272 int x;
274 /* number is 0 based */
275 x = -1;
276 t = all_targets;
277 while (t) {
278 if (x < t->target_number)
279 x = t->target_number;
280 t = t->next;
282 return x + 1;
285 /* read a uint32_t from a buffer in target memory endianness */
286 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
288 if (target->endianness == TARGET_LITTLE_ENDIAN)
289 return le_to_h_u32(buffer);
290 else
291 return be_to_h_u32(buffer);
294 /* read a uint24_t from a buffer in target memory endianness */
295 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
297 if (target->endianness == TARGET_LITTLE_ENDIAN)
298 return le_to_h_u24(buffer);
299 else
300 return be_to_h_u24(buffer);
303 /* read a uint16_t from a buffer in target memory endianness */
304 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
306 if (target->endianness == TARGET_LITTLE_ENDIAN)
307 return le_to_h_u16(buffer);
308 else
309 return be_to_h_u16(buffer);
312 /* read a uint8_t from a buffer in target memory endianness */
313 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
315 return *buffer & 0x0ff;
318 /* write a uint32_t to a buffer in target memory endianness */
319 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
321 if (target->endianness == TARGET_LITTLE_ENDIAN)
322 h_u32_to_le(buffer, value);
323 else
324 h_u32_to_be(buffer, value);
327 /* write a uint24_t to a buffer in target memory endianness */
328 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
330 if (target->endianness == TARGET_LITTLE_ENDIAN)
331 h_u24_to_le(buffer, value);
332 else
333 h_u24_to_be(buffer, value);
336 /* write a uint16_t to a buffer in target memory endianness */
337 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
339 if (target->endianness == TARGET_LITTLE_ENDIAN)
340 h_u16_to_le(buffer, value);
341 else
342 h_u16_to_be(buffer, value);
345 /* write a uint8_t to a buffer in target memory endianness */
346 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
348 *buffer = value;
351 /* write a uint32_t array to a buffer in target memory endianness */
352 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
354 uint32_t i;
355 for (i = 0; i < count; i++)
356 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
359 /* write a uint16_t array to a buffer in target memory endianness */
360 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
362 uint32_t i;
363 for (i = 0; i < count; i++)
364 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
367 /* write a uint32_t array to a buffer in target memory endianness */
368 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, uint32_t *srcbuf)
370 uint32_t i;
371 for (i = 0; i < count; i++)
372 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
375 /* write a uint16_t array to a buffer in target memory endianness */
376 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, uint16_t *srcbuf)
378 uint32_t i;
379 for (i = 0; i < count; i++)
380 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
383 /* return a pointer to a configured target; id is name or number */
384 struct target *get_target(const char *id)
386 struct target *target;
388 /* try as tcltarget name */
389 for (target = all_targets; target; target = target->next) {
390 if (target_name(target) == NULL)
391 continue;
392 if (strcmp(id, target_name(target)) == 0)
393 return target;
396 /* It's OK to remove this fallback sometime after August 2010 or so */
398 /* no match, try as number */
399 unsigned num;
400 if (parse_uint(id, &num) != ERROR_OK)
401 return NULL;
403 for (target = all_targets; target; target = target->next) {
404 if (target->target_number == (int)num) {
405 LOG_WARNING("use '%s' as target identifier, not '%u'",
406 target_name(target), num);
407 return target;
411 return NULL;
414 /* returns a pointer to the n-th configured target */
415 static struct target *get_target_by_num(int num)
417 struct target *target = all_targets;
419 while (target) {
420 if (target->target_number == num)
421 return target;
422 target = target->next;
425 return NULL;
428 struct target *get_current_target(struct command_context *cmd_ctx)
430 struct target *target = get_target_by_num(cmd_ctx->current_target);
432 if (target == NULL) {
433 LOG_ERROR("BUG: current_target out of bounds");
434 exit(-1);
437 return target;
440 int target_poll(struct target *target)
442 int retval;
444 /* We can't poll until after examine */
445 if (!target_was_examined(target)) {
446 /* Fail silently lest we pollute the log */
447 return ERROR_FAIL;
450 retval = target->type->poll(target);
451 if (retval != ERROR_OK)
452 return retval;
454 if (target->halt_issued) {
455 if (target->state == TARGET_HALTED)
456 target->halt_issued = false;
457 else {
458 long long t = timeval_ms() - target->halt_issued_time;
459 if (t > 1000) {
460 target->halt_issued = false;
461 LOG_INFO("Halt timed out, wake up GDB.");
462 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
467 return ERROR_OK;
470 int target_halt(struct target *target)
472 int retval;
473 /* We can't poll until after examine */
474 if (!target_was_examined(target)) {
475 LOG_ERROR("Target not examined yet");
476 return ERROR_FAIL;
479 retval = target->type->halt(target);
480 if (retval != ERROR_OK)
481 return retval;
483 target->halt_issued = true;
484 target->halt_issued_time = timeval_ms();
486 return ERROR_OK;
490 * Make the target (re)start executing using its saved execution
491 * context (possibly with some modifications).
493 * @param target Which target should start executing.
494 * @param current True to use the target's saved program counter instead
495 * of the address parameter
496 * @param address Optionally used as the program counter.
497 * @param handle_breakpoints True iff breakpoints at the resumption PC
498 * should be skipped. (For example, maybe execution was stopped by
499 * such a breakpoint, in which case it would be counterprodutive to
500 * let it re-trigger.
501 * @param debug_execution False if all working areas allocated by OpenOCD
502 * should be released and/or restored to their original contents.
503 * (This would for example be true to run some downloaded "helper"
504 * algorithm code, which resides in one such working buffer and uses
505 * another for data storage.)
507 * @todo Resolve the ambiguity about what the "debug_execution" flag
508 * signifies. For example, Target implementations don't agree on how
509 * it relates to invalidation of the register cache, or to whether
510 * breakpoints and watchpoints should be enabled. (It would seem wrong
511 * to enable breakpoints when running downloaded "helper" algorithms
512 * (debug_execution true), since the breakpoints would be set to match
513 * target firmware being debugged, not the helper algorithm.... and
514 * enabling them could cause such helpers to malfunction (for example,
515 * by overwriting data with a breakpoint instruction. On the other
516 * hand the infrastructure for running such helpers might use this
517 * procedure but rely on hardware breakpoint to detect termination.)
519 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
521 int retval;
523 /* We can't poll until after examine */
524 if (!target_was_examined(target)) {
525 LOG_ERROR("Target not examined yet");
526 return ERROR_FAIL;
529 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
531 /* note that resume *must* be asynchronous. The CPU can halt before
532 * we poll. The CPU can even halt at the current PC as a result of
533 * a software breakpoint being inserted by (a bug?) the application.
535 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
536 if (retval != ERROR_OK)
537 return retval;
539 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
541 return retval;
544 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
546 char buf[100];
547 int retval;
548 Jim_Nvp *n;
549 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
550 if (n->name == NULL) {
551 LOG_ERROR("invalid reset mode");
552 return ERROR_FAIL;
555 /* disable polling during reset to make reset event scripts
556 * more predictable, i.e. dr/irscan & pathmove in events will
557 * not have JTAG operations injected into the middle of a sequence.
559 bool save_poll = jtag_poll_get_enabled();
561 jtag_poll_set_enabled(false);
563 sprintf(buf, "ocd_process_reset %s", n->name);
564 retval = Jim_Eval(cmd_ctx->interp, buf);
566 jtag_poll_set_enabled(save_poll);
568 if (retval != JIM_OK) {
569 Jim_MakeErrorMessage(cmd_ctx->interp);
570 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
571 return ERROR_FAIL;
574 /* We want any events to be processed before the prompt */
575 retval = target_call_timer_callbacks_now();
577 struct target *target;
578 for (target = all_targets; target; target = target->next)
579 target->type->check_reset(target);
581 return retval;
584 static int identity_virt2phys(struct target *target,
585 uint32_t virtual, uint32_t *physical)
587 *physical = virtual;
588 return ERROR_OK;
591 static int no_mmu(struct target *target, int *enabled)
593 *enabled = 0;
594 return ERROR_OK;
597 static int default_examine(struct target *target)
599 target_set_examined(target);
600 return ERROR_OK;
603 /* no check by default */
604 static int default_check_reset(struct target *target)
606 return ERROR_OK;
609 int target_examine_one(struct target *target)
611 return target->type->examine(target);
614 static int jtag_enable_callback(enum jtag_event event, void *priv)
616 struct target *target = priv;
618 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
619 return ERROR_OK;
621 jtag_unregister_event_callback(jtag_enable_callback, target);
623 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
625 int retval = target_examine_one(target);
626 if (retval != ERROR_OK)
627 return retval;
629 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
631 return retval;
634 /* Targets that correctly implement init + examine, i.e.
635 * no communication with target during init:
637 * XScale
639 int target_examine(void)
641 int retval = ERROR_OK;
642 struct target *target;
644 for (target = all_targets; target; target = target->next) {
645 /* defer examination, but don't skip it */
646 if (!target->tap->enabled) {
647 jtag_register_event_callback(jtag_enable_callback,
648 target);
649 continue;
652 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
654 retval = target_examine_one(target);
655 if (retval != ERROR_OK)
656 return retval;
658 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
660 return retval;
663 const char *target_type_name(struct target *target)
665 return target->type->name;
668 static int target_soft_reset_halt(struct target *target)
670 if (!target_was_examined(target)) {
671 LOG_ERROR("Target not examined yet");
672 return ERROR_FAIL;
674 if (!target->type->soft_reset_halt) {
675 LOG_ERROR("Target %s does not support soft_reset_halt",
676 target_name(target));
677 return ERROR_FAIL;
679 return target->type->soft_reset_halt(target);
683 * Downloads a target-specific native code algorithm to the target,
684 * and executes it. * Note that some targets may need to set up, enable,
685 * and tear down a breakpoint (hard or * soft) to detect algorithm
686 * termination, while others may support lower overhead schemes where
687 * soft breakpoints embedded in the algorithm automatically terminate the
688 * algorithm.
690 * @param target used to run the algorithm
691 * @param arch_info target-specific description of the algorithm.
693 int target_run_algorithm(struct target *target,
694 int num_mem_params, struct mem_param *mem_params,
695 int num_reg_params, struct reg_param *reg_param,
696 uint32_t entry_point, uint32_t exit_point,
697 int timeout_ms, void *arch_info)
699 int retval = ERROR_FAIL;
701 if (!target_was_examined(target)) {
702 LOG_ERROR("Target not examined yet");
703 goto done;
705 if (!target->type->run_algorithm) {
706 LOG_ERROR("Target type '%s' does not support %s",
707 target_type_name(target), __func__);
708 goto done;
711 target->running_alg = true;
712 retval = target->type->run_algorithm(target,
713 num_mem_params, mem_params,
714 num_reg_params, reg_param,
715 entry_point, exit_point, timeout_ms, arch_info);
716 target->running_alg = false;
718 done:
719 return retval;
723 * Downloads a target-specific native code algorithm to the target,
724 * executes and leaves it running.
726 * @param target used to run the algorithm
727 * @param arch_info target-specific description of the algorithm.
729 int target_start_algorithm(struct target *target,
730 int num_mem_params, struct mem_param *mem_params,
731 int num_reg_params, struct reg_param *reg_params,
732 uint32_t entry_point, uint32_t exit_point,
733 void *arch_info)
735 int retval = ERROR_FAIL;
737 if (!target_was_examined(target)) {
738 LOG_ERROR("Target not examined yet");
739 goto done;
741 if (!target->type->start_algorithm) {
742 LOG_ERROR("Target type '%s' does not support %s",
743 target_type_name(target), __func__);
744 goto done;
746 if (target->running_alg) {
747 LOG_ERROR("Target is already running an algorithm");
748 goto done;
751 target->running_alg = true;
752 retval = target->type->start_algorithm(target,
753 num_mem_params, mem_params,
754 num_reg_params, reg_params,
755 entry_point, exit_point, arch_info);
757 done:
758 return retval;
762 * Waits for an algorithm started with target_start_algorithm() to complete.
764 * @param target used to run the algorithm
765 * @param arch_info target-specific description of the algorithm.
767 int target_wait_algorithm(struct target *target,
768 int num_mem_params, struct mem_param *mem_params,
769 int num_reg_params, struct reg_param *reg_params,
770 uint32_t exit_point, int timeout_ms,
771 void *arch_info)
773 int retval = ERROR_FAIL;
775 if (!target->type->wait_algorithm) {
776 LOG_ERROR("Target type '%s' does not support %s",
777 target_type_name(target), __func__);
778 goto done;
780 if (!target->running_alg) {
781 LOG_ERROR("Target is not running an algorithm");
782 goto done;
785 retval = target->type->wait_algorithm(target,
786 num_mem_params, mem_params,
787 num_reg_params, reg_params,
788 exit_point, timeout_ms, arch_info);
789 if (retval != ERROR_TARGET_TIMEOUT)
790 target->running_alg = false;
792 done:
793 return retval;
797 * Executes a target-specific native code algorithm in the target.
798 * It differs from target_run_algorithm in that the algorithm is asynchronous.
799 * Because of this it requires an compliant algorithm:
800 * see contrib/loaders/flash/stm32f1x.S for example.
802 * @param target used to run the algorithm
805 int target_run_flash_async_algorithm(struct target *target,
806 uint8_t *buffer, uint32_t count, int block_size,
807 int num_mem_params, struct mem_param *mem_params,
808 int num_reg_params, struct reg_param *reg_params,
809 uint32_t buffer_start, uint32_t buffer_size,
810 uint32_t entry_point, uint32_t exit_point, void *arch_info)
812 int retval;
813 int timeout = 0;
815 /* Set up working area. First word is write pointer, second word is read pointer,
816 * rest is fifo data area. */
817 uint32_t wp_addr = buffer_start;
818 uint32_t rp_addr = buffer_start + 4;
819 uint32_t fifo_start_addr = buffer_start + 8;
820 uint32_t fifo_end_addr = buffer_start + buffer_size;
822 uint32_t wp = fifo_start_addr;
823 uint32_t rp = fifo_start_addr;
825 /* validate block_size is 2^n */
826 assert(!block_size || !(block_size & (block_size - 1)));
828 retval = target_write_u32(target, wp_addr, wp);
829 if (retval != ERROR_OK)
830 return retval;
831 retval = target_write_u32(target, rp_addr, rp);
832 if (retval != ERROR_OK)
833 return retval;
835 /* Start up algorithm on target and let it idle while writing the first chunk */
836 retval = target_start_algorithm(target, num_mem_params, mem_params,
837 num_reg_params, reg_params,
838 entry_point,
839 exit_point,
840 arch_info);
842 if (retval != ERROR_OK) {
843 LOG_ERROR("error starting target flash write algorithm");
844 return retval;
847 while (count > 0) {
849 retval = target_read_u32(target, rp_addr, &rp);
850 if (retval != ERROR_OK) {
851 LOG_ERROR("failed to get read pointer");
852 break;
855 LOG_DEBUG("count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32, count, wp, rp);
857 if (rp == 0) {
858 LOG_ERROR("flash write algorithm aborted by target");
859 retval = ERROR_FLASH_OPERATION_FAILED;
860 break;
863 if ((rp & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
864 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
865 break;
868 /* Count the number of bytes available in the fifo without
869 * crossing the wrap around. Make sure to not fill it completely,
870 * because that would make wp == rp and that's the empty condition. */
871 uint32_t thisrun_bytes;
872 if (rp > wp)
873 thisrun_bytes = rp - wp - block_size;
874 else if (rp > fifo_start_addr)
875 thisrun_bytes = fifo_end_addr - wp;
876 else
877 thisrun_bytes = fifo_end_addr - wp - block_size;
879 if (thisrun_bytes == 0) {
880 /* Throttle polling a bit if transfer is (much) faster than flash
881 * programming. The exact delay shouldn't matter as long as it's
882 * less than buffer size / flash speed. This is very unlikely to
883 * run when using high latency connections such as USB. */
884 alive_sleep(10);
886 /* to stop an infinite loop on some targets check and increment a timeout
887 * this issue was observed on a stellaris using the new ICDI interface */
888 if (timeout++ >= 500) {
889 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
890 return ERROR_FLASH_OPERATION_FAILED;
892 continue;
895 /* reset our timeout */
896 timeout = 0;
898 /* Limit to the amount of data we actually want to write */
899 if (thisrun_bytes > count * block_size)
900 thisrun_bytes = count * block_size;
902 /* Write data to fifo */
903 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
904 if (retval != ERROR_OK)
905 break;
907 /* Update counters and wrap write pointer */
908 buffer += thisrun_bytes;
909 count -= thisrun_bytes / block_size;
910 wp += thisrun_bytes;
911 if (wp >= fifo_end_addr)
912 wp = fifo_start_addr;
914 /* Store updated write pointer to target */
915 retval = target_write_u32(target, wp_addr, wp);
916 if (retval != ERROR_OK)
917 break;
920 if (retval != ERROR_OK) {
921 /* abort flash write algorithm on target */
922 target_write_u32(target, wp_addr, 0);
925 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
926 num_reg_params, reg_params,
927 exit_point,
928 10000,
929 arch_info);
931 if (retval2 != ERROR_OK) {
932 LOG_ERROR("error waiting for target flash write algorithm");
933 retval = retval2;
936 return retval;
939 int target_read_memory(struct target *target,
940 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
942 if (!target_was_examined(target)) {
943 LOG_ERROR("Target not examined yet");
944 return ERROR_FAIL;
946 return target->type->read_memory(target, address, size, count, buffer);
949 int target_read_phys_memory(struct target *target,
950 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
952 if (!target_was_examined(target)) {
953 LOG_ERROR("Target not examined yet");
954 return ERROR_FAIL;
956 return target->type->read_phys_memory(target, address, size, count, buffer);
959 int target_write_memory(struct target *target,
960 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
962 if (!target_was_examined(target)) {
963 LOG_ERROR("Target not examined yet");
964 return ERROR_FAIL;
966 return target->type->write_memory(target, address, size, count, buffer);
969 int target_write_phys_memory(struct target *target,
970 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
972 if (!target_was_examined(target)) {
973 LOG_ERROR("Target not examined yet");
974 return ERROR_FAIL;
976 return target->type->write_phys_memory(target, address, size, count, buffer);
979 static int target_bulk_write_memory_default(struct target *target,
980 uint32_t address, uint32_t count, const uint8_t *buffer)
982 return target_write_memory(target, address, 4, count, buffer);
985 int target_add_breakpoint(struct target *target,
986 struct breakpoint *breakpoint)
988 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
989 LOG_WARNING("target %s is not halted", target_name(target));
990 return ERROR_TARGET_NOT_HALTED;
992 return target->type->add_breakpoint(target, breakpoint);
995 int target_add_context_breakpoint(struct target *target,
996 struct breakpoint *breakpoint)
998 if (target->state != TARGET_HALTED) {
999 LOG_WARNING("target %s is not halted", target_name(target));
1000 return ERROR_TARGET_NOT_HALTED;
1002 return target->type->add_context_breakpoint(target, breakpoint);
1005 int target_add_hybrid_breakpoint(struct target *target,
1006 struct breakpoint *breakpoint)
1008 if (target->state != TARGET_HALTED) {
1009 LOG_WARNING("target %s is not halted", target_name(target));
1010 return ERROR_TARGET_NOT_HALTED;
1012 return target->type->add_hybrid_breakpoint(target, breakpoint);
1015 int target_remove_breakpoint(struct target *target,
1016 struct breakpoint *breakpoint)
1018 return target->type->remove_breakpoint(target, breakpoint);
1021 int target_add_watchpoint(struct target *target,
1022 struct watchpoint *watchpoint)
1024 if (target->state != TARGET_HALTED) {
1025 LOG_WARNING("target %s is not halted", target_name(target));
1026 return ERROR_TARGET_NOT_HALTED;
1028 return target->type->add_watchpoint(target, watchpoint);
1030 int target_remove_watchpoint(struct target *target,
1031 struct watchpoint *watchpoint)
1033 return target->type->remove_watchpoint(target, watchpoint);
1036 int target_get_gdb_reg_list(struct target *target,
1037 struct reg **reg_list[], int *reg_list_size)
1039 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
1041 int target_step(struct target *target,
1042 int current, uint32_t address, int handle_breakpoints)
1044 return target->type->step(target, current, address, handle_breakpoints);
1048 * Reset the @c examined flag for the given target.
1049 * Pure paranoia -- targets are zeroed on allocation.
1051 static void target_reset_examined(struct target *target)
1053 target->examined = false;
1056 static int err_read_phys_memory(struct target *target, uint32_t address,
1057 uint32_t size, uint32_t count, uint8_t *buffer)
1059 LOG_ERROR("Not implemented: %s", __func__);
1060 return ERROR_FAIL;
1063 static int err_write_phys_memory(struct target *target, uint32_t address,
1064 uint32_t size, uint32_t count, const uint8_t *buffer)
1066 LOG_ERROR("Not implemented: %s", __func__);
1067 return ERROR_FAIL;
1070 static int handle_target(void *priv);
1072 static int target_init_one(struct command_context *cmd_ctx,
1073 struct target *target)
1075 target_reset_examined(target);
1077 struct target_type *type = target->type;
1078 if (type->examine == NULL)
1079 type->examine = default_examine;
1081 if (type->check_reset == NULL)
1082 type->check_reset = default_check_reset;
1084 assert(type->init_target != NULL);
1086 int retval = type->init_target(cmd_ctx, target);
1087 if (ERROR_OK != retval) {
1088 LOG_ERROR("target '%s' init failed", target_name(target));
1089 return retval;
1092 /* Sanity-check MMU support ... stub in what we must, to help
1093 * implement it in stages, but warn if we need to do so.
1095 if (type->mmu) {
1096 if (type->write_phys_memory == NULL) {
1097 LOG_ERROR("type '%s' is missing write_phys_memory",
1098 type->name);
1099 type->write_phys_memory = err_write_phys_memory;
1101 if (type->read_phys_memory == NULL) {
1102 LOG_ERROR("type '%s' is missing read_phys_memory",
1103 type->name);
1104 type->read_phys_memory = err_read_phys_memory;
1106 if (type->virt2phys == NULL) {
1107 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1108 type->virt2phys = identity_virt2phys;
1110 } else {
1111 /* Make sure no-MMU targets all behave the same: make no
1112 * distinction between physical and virtual addresses, and
1113 * ensure that virt2phys() is always an identity mapping.
1115 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1116 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1118 type->mmu = no_mmu;
1119 type->write_phys_memory = type->write_memory;
1120 type->read_phys_memory = type->read_memory;
1121 type->virt2phys = identity_virt2phys;
1124 if (target->type->read_buffer == NULL)
1125 target->type->read_buffer = target_read_buffer_default;
1127 if (target->type->write_buffer == NULL)
1128 target->type->write_buffer = target_write_buffer_default;
1130 if (target->type->bulk_write_memory == NULL)
1131 target->type->bulk_write_memory = target_bulk_write_memory_default;
1133 return ERROR_OK;
1136 static int target_init(struct command_context *cmd_ctx)
1138 struct target *target;
1139 int retval;
1141 for (target = all_targets; target; target = target->next) {
1142 retval = target_init_one(cmd_ctx, target);
1143 if (ERROR_OK != retval)
1144 return retval;
1147 if (!all_targets)
1148 return ERROR_OK;
1150 retval = target_register_user_commands(cmd_ctx);
1151 if (ERROR_OK != retval)
1152 return retval;
1154 retval = target_register_timer_callback(&handle_target,
1155 polling_interval, 1, cmd_ctx->interp);
1156 if (ERROR_OK != retval)
1157 return retval;
1159 return ERROR_OK;
1162 COMMAND_HANDLER(handle_target_init_command)
1164 int retval;
1166 if (CMD_ARGC != 0)
1167 return ERROR_COMMAND_SYNTAX_ERROR;
1169 static bool target_initialized;
1170 if (target_initialized) {
1171 LOG_INFO("'target init' has already been called");
1172 return ERROR_OK;
1174 target_initialized = true;
1176 retval = command_run_line(CMD_CTX, "init_targets");
1177 if (ERROR_OK != retval)
1178 return retval;
1180 retval = command_run_line(CMD_CTX, "init_board");
1181 if (ERROR_OK != retval)
1182 return retval;
1184 LOG_DEBUG("Initializing targets...");
1185 return target_init(CMD_CTX);
1188 int target_register_event_callback(int (*callback)(struct target *target,
1189 enum target_event event, void *priv), void *priv)
1191 struct target_event_callback **callbacks_p = &target_event_callbacks;
1193 if (callback == NULL)
1194 return ERROR_COMMAND_SYNTAX_ERROR;
1196 if (*callbacks_p) {
1197 while ((*callbacks_p)->next)
1198 callbacks_p = &((*callbacks_p)->next);
1199 callbacks_p = &((*callbacks_p)->next);
1202 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1203 (*callbacks_p)->callback = callback;
1204 (*callbacks_p)->priv = priv;
1205 (*callbacks_p)->next = NULL;
1207 return ERROR_OK;
1210 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1212 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1213 struct timeval now;
1215 if (callback == NULL)
1216 return ERROR_COMMAND_SYNTAX_ERROR;
1218 if (*callbacks_p) {
1219 while ((*callbacks_p)->next)
1220 callbacks_p = &((*callbacks_p)->next);
1221 callbacks_p = &((*callbacks_p)->next);
1224 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1225 (*callbacks_p)->callback = callback;
1226 (*callbacks_p)->periodic = periodic;
1227 (*callbacks_p)->time_ms = time_ms;
1229 gettimeofday(&now, NULL);
1230 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
1231 time_ms -= (time_ms % 1000);
1232 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
1233 if ((*callbacks_p)->when.tv_usec > 1000000) {
1234 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
1235 (*callbacks_p)->when.tv_sec += 1;
1238 (*callbacks_p)->priv = priv;
1239 (*callbacks_p)->next = NULL;
1241 return ERROR_OK;
1244 int target_unregister_event_callback(int (*callback)(struct target *target,
1245 enum target_event event, void *priv), void *priv)
1247 struct target_event_callback **p = &target_event_callbacks;
1248 struct target_event_callback *c = target_event_callbacks;
1250 if (callback == NULL)
1251 return ERROR_COMMAND_SYNTAX_ERROR;
1253 while (c) {
1254 struct target_event_callback *next = c->next;
1255 if ((c->callback == callback) && (c->priv == priv)) {
1256 *p = next;
1257 free(c);
1258 return ERROR_OK;
1259 } else
1260 p = &(c->next);
1261 c = next;
1264 return ERROR_OK;
1267 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1269 struct target_timer_callback **p = &target_timer_callbacks;
1270 struct target_timer_callback *c = target_timer_callbacks;
1272 if (callback == NULL)
1273 return ERROR_COMMAND_SYNTAX_ERROR;
1275 while (c) {
1276 struct target_timer_callback *next = c->next;
1277 if ((c->callback == callback) && (c->priv == priv)) {
1278 *p = next;
1279 free(c);
1280 return ERROR_OK;
1281 } else
1282 p = &(c->next);
1283 c = next;
1286 return ERROR_OK;
1289 int target_call_event_callbacks(struct target *target, enum target_event event)
1291 struct target_event_callback *callback = target_event_callbacks;
1292 struct target_event_callback *next_callback;
1294 if (event == TARGET_EVENT_HALTED) {
1295 /* execute early halted first */
1296 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1299 LOG_DEBUG("target event %i (%s)", event,
1300 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1302 target_handle_event(target, event);
1304 while (callback) {
1305 next_callback = callback->next;
1306 callback->callback(target, event, callback->priv);
1307 callback = next_callback;
1310 return ERROR_OK;
1313 static int target_timer_callback_periodic_restart(
1314 struct target_timer_callback *cb, struct timeval *now)
1316 int time_ms = cb->time_ms;
1317 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1318 time_ms -= (time_ms % 1000);
1319 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1320 if (cb->when.tv_usec > 1000000) {
1321 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1322 cb->when.tv_sec += 1;
1324 return ERROR_OK;
1327 static int target_call_timer_callback(struct target_timer_callback *cb,
1328 struct timeval *now)
1330 cb->callback(cb->priv);
1332 if (cb->periodic)
1333 return target_timer_callback_periodic_restart(cb, now);
1335 return target_unregister_timer_callback(cb->callback, cb->priv);
1338 static int target_call_timer_callbacks_check_time(int checktime)
1340 keep_alive();
1342 struct timeval now;
1343 gettimeofday(&now, NULL);
1345 struct target_timer_callback *callback = target_timer_callbacks;
1346 while (callback) {
1347 /* cleaning up may unregister and free this callback */
1348 struct target_timer_callback *next_callback = callback->next;
1350 bool call_it = callback->callback &&
1351 ((!checktime && callback->periodic) ||
1352 now.tv_sec > callback->when.tv_sec ||
1353 (now.tv_sec == callback->when.tv_sec &&
1354 now.tv_usec >= callback->when.tv_usec));
1356 if (call_it) {
1357 int retval = target_call_timer_callback(callback, &now);
1358 if (retval != ERROR_OK)
1359 return retval;
1362 callback = next_callback;
1365 return ERROR_OK;
1368 int target_call_timer_callbacks(void)
1370 return target_call_timer_callbacks_check_time(1);
1373 /* invoke periodic callbacks immediately */
1374 int target_call_timer_callbacks_now(void)
1376 return target_call_timer_callbacks_check_time(0);
1379 /* Prints the working area layout for debug purposes */
1380 static void print_wa_layout(struct target *target)
1382 struct working_area *c = target->working_areas;
1384 while (c) {
1385 LOG_DEBUG("%c%c 0x%08"PRIx32"-0x%08"PRIx32" (%"PRIu32" bytes)",
1386 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1387 c->address, c->address + c->size - 1, c->size);
1388 c = c->next;
1392 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1393 static void target_split_working_area(struct working_area *area, uint32_t size)
1395 assert(area->free); /* Shouldn't split an allocated area */
1396 assert(size <= area->size); /* Caller should guarantee this */
1398 /* Split only if not already the right size */
1399 if (size < area->size) {
1400 struct working_area *new_wa = malloc(sizeof(*new_wa));
1402 if (new_wa == NULL)
1403 return;
1405 new_wa->next = area->next;
1406 new_wa->size = area->size - size;
1407 new_wa->address = area->address + size;
1408 new_wa->backup = NULL;
1409 new_wa->user = NULL;
1410 new_wa->free = true;
1412 area->next = new_wa;
1413 area->size = size;
1415 /* If backup memory was allocated to this area, it has the wrong size
1416 * now so free it and it will be reallocated if/when needed */
1417 if (area->backup) {
1418 free(area->backup);
1419 area->backup = NULL;
1424 /* Merge all adjacent free areas into one */
1425 static void target_merge_working_areas(struct target *target)
1427 struct working_area *c = target->working_areas;
1429 while (c && c->next) {
1430 assert(c->next->address == c->address + c->size); /* This is an invariant */
1432 /* Find two adjacent free areas */
1433 if (c->free && c->next->free) {
1434 /* Merge the last into the first */
1435 c->size += c->next->size;
1437 /* Remove the last */
1438 struct working_area *to_be_freed = c->next;
1439 c->next = c->next->next;
1440 if (to_be_freed->backup)
1441 free(to_be_freed->backup);
1442 free(to_be_freed);
1444 /* If backup memory was allocated to the remaining area, it's has
1445 * the wrong size now */
1446 if (c->backup) {
1447 free(c->backup);
1448 c->backup = NULL;
1450 } else {
1451 c = c->next;
1456 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1458 /* Reevaluate working area address based on MMU state*/
1459 if (target->working_areas == NULL) {
1460 int retval;
1461 int enabled;
1463 retval = target->type->mmu(target, &enabled);
1464 if (retval != ERROR_OK)
1465 return retval;
1467 if (!enabled) {
1468 if (target->working_area_phys_spec) {
1469 LOG_DEBUG("MMU disabled, using physical "
1470 "address for working memory 0x%08"PRIx32,
1471 target->working_area_phys);
1472 target->working_area = target->working_area_phys;
1473 } else {
1474 LOG_ERROR("No working memory available. "
1475 "Specify -work-area-phys to target.");
1476 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1478 } else {
1479 if (target->working_area_virt_spec) {
1480 LOG_DEBUG("MMU enabled, using virtual "
1481 "address for working memory 0x%08"PRIx32,
1482 target->working_area_virt);
1483 target->working_area = target->working_area_virt;
1484 } else {
1485 LOG_ERROR("No working memory available. "
1486 "Specify -work-area-virt to target.");
1487 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1491 /* Set up initial working area on first call */
1492 struct working_area *new_wa = malloc(sizeof(*new_wa));
1493 if (new_wa) {
1494 new_wa->next = NULL;
1495 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1496 new_wa->address = target->working_area;
1497 new_wa->backup = NULL;
1498 new_wa->user = NULL;
1499 new_wa->free = true;
1502 target->working_areas = new_wa;
1505 /* only allocate multiples of 4 byte */
1506 if (size % 4)
1507 size = (size + 3) & (~3UL);
1509 struct working_area *c = target->working_areas;
1511 /* Find the first large enough working area */
1512 while (c) {
1513 if (c->free && c->size >= size)
1514 break;
1515 c = c->next;
1518 if (c == NULL)
1519 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1521 /* Split the working area into the requested size */
1522 target_split_working_area(c, size);
1524 LOG_DEBUG("allocated new working area of %"PRIu32" bytes at address 0x%08"PRIx32, size, c->address);
1526 if (target->backup_working_area) {
1527 if (c->backup == NULL) {
1528 c->backup = malloc(c->size);
1529 if (c->backup == NULL)
1530 return ERROR_FAIL;
1533 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1534 if (retval != ERROR_OK)
1535 return retval;
1538 /* mark as used, and return the new (reused) area */
1539 c->free = false;
1540 *area = c;
1542 /* user pointer */
1543 c->user = area;
1545 print_wa_layout(target);
1547 return ERROR_OK;
1550 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1552 int retval;
1554 retval = target_alloc_working_area_try(target, size, area);
1555 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1556 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1557 return retval;
1561 static int target_restore_working_area(struct target *target, struct working_area *area)
1563 int retval = ERROR_OK;
1565 if (target->backup_working_area && area->backup != NULL) {
1566 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1567 if (retval != ERROR_OK)
1568 LOG_ERROR("failed to restore %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1569 area->size, area->address);
1572 return retval;
1575 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1576 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1578 int retval = ERROR_OK;
1580 if (area->free)
1581 return retval;
1583 if (restore) {
1584 retval = target_restore_working_area(target, area);
1585 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1586 if (retval != ERROR_OK)
1587 return retval;
1590 area->free = true;
1592 LOG_DEBUG("freed %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1593 area->size, area->address);
1595 /* mark user pointer invalid */
1596 /* TODO: Is this really safe? It points to some previous caller's memory.
1597 * How could we know that the area pointer is still in that place and not
1598 * some other vital data? What's the purpose of this, anyway? */
1599 *area->user = NULL;
1600 area->user = NULL;
1602 target_merge_working_areas(target);
1604 print_wa_layout(target);
1606 return retval;
1609 int target_free_working_area(struct target *target, struct working_area *area)
1611 return target_free_working_area_restore(target, area, 1);
1614 /* free resources and restore memory, if restoring memory fails,
1615 * free up resources anyway
1617 static void target_free_all_working_areas_restore(struct target *target, int restore)
1619 struct working_area *c = target->working_areas;
1621 LOG_DEBUG("freeing all working areas");
1623 /* Loop through all areas, restoring the allocated ones and marking them as free */
1624 while (c) {
1625 if (!c->free) {
1626 if (restore)
1627 target_restore_working_area(target, c);
1628 c->free = true;
1629 *c->user = NULL; /* Same as above */
1630 c->user = NULL;
1632 c = c->next;
1635 /* Run a merge pass to combine all areas into one */
1636 target_merge_working_areas(target);
1638 print_wa_layout(target);
1641 void target_free_all_working_areas(struct target *target)
1643 target_free_all_working_areas_restore(target, 1);
1646 /* Find the largest number of bytes that can be allocated */
1647 uint32_t target_get_working_area_avail(struct target *target)
1649 struct working_area *c = target->working_areas;
1650 uint32_t max_size = 0;
1652 if (c == NULL)
1653 return target->working_area_size;
1655 while (c) {
1656 if (c->free && max_size < c->size)
1657 max_size = c->size;
1659 c = c->next;
1662 return max_size;
1665 int target_arch_state(struct target *target)
1667 int retval;
1668 if (target == NULL) {
1669 LOG_USER("No target has been configured");
1670 return ERROR_OK;
1673 LOG_USER("target state: %s", target_state_name(target));
1675 if (target->state != TARGET_HALTED)
1676 return ERROR_OK;
1678 retval = target->type->arch_state(target);
1679 return retval;
1682 /* Single aligned words are guaranteed to use 16 or 32 bit access
1683 * mode respectively, otherwise data is handled as quickly as
1684 * possible
1686 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1688 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1689 (int)size, (unsigned)address);
1691 if (!target_was_examined(target)) {
1692 LOG_ERROR("Target not examined yet");
1693 return ERROR_FAIL;
1696 if (size == 0)
1697 return ERROR_OK;
1699 if ((address + size - 1) < address) {
1700 /* GDB can request this when e.g. PC is 0xfffffffc*/
1701 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1702 (unsigned)address,
1703 (unsigned)size);
1704 return ERROR_FAIL;
1707 return target->type->write_buffer(target, address, size, buffer);
1710 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1712 int retval = ERROR_OK;
1714 if (((address % 2) == 0) && (size == 2))
1715 return target_write_memory(target, address, 2, 1, buffer);
1717 /* handle unaligned head bytes */
1718 if (address % 4) {
1719 uint32_t unaligned = 4 - (address % 4);
1721 if (unaligned > size)
1722 unaligned = size;
1724 retval = target_write_memory(target, address, 1, unaligned, buffer);
1725 if (retval != ERROR_OK)
1726 return retval;
1728 buffer += unaligned;
1729 address += unaligned;
1730 size -= unaligned;
1733 /* handle aligned words */
1734 if (size >= 4) {
1735 int aligned = size - (size % 4);
1737 /* use bulk writes above a certain limit. This may have to be changed */
1738 if (aligned > 128) {
1739 retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer);
1740 if (retval != ERROR_OK)
1741 return retval;
1742 } else {
1743 retval = target_write_memory(target, address, 4, aligned / 4, buffer);
1744 if (retval != ERROR_OK)
1745 return retval;
1748 buffer += aligned;
1749 address += aligned;
1750 size -= aligned;
1753 /* handle tail writes of less than 4 bytes */
1754 if (size > 0) {
1755 retval = target_write_memory(target, address, 1, size, buffer);
1756 if (retval != ERROR_OK)
1757 return retval;
1760 return retval;
1763 /* Single aligned words are guaranteed to use 16 or 32 bit access
1764 * mode respectively, otherwise data is handled as quickly as
1765 * possible
1767 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1769 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1770 (int)size, (unsigned)address);
1772 if (!target_was_examined(target)) {
1773 LOG_ERROR("Target not examined yet");
1774 return ERROR_FAIL;
1777 if (size == 0)
1778 return ERROR_OK;
1780 if ((address + size - 1) < address) {
1781 /* GDB can request this when e.g. PC is 0xfffffffc*/
1782 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1783 address,
1784 size);
1785 return ERROR_FAIL;
1788 return target->type->read_buffer(target, address, size, buffer);
1791 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1793 int retval = ERROR_OK;
1795 if (((address % 2) == 0) && (size == 2))
1796 return target_read_memory(target, address, 2, 1, buffer);
1798 /* handle unaligned head bytes */
1799 if (address % 4) {
1800 uint32_t unaligned = 4 - (address % 4);
1802 if (unaligned > size)
1803 unaligned = size;
1805 retval = target_read_memory(target, address, 1, unaligned, buffer);
1806 if (retval != ERROR_OK)
1807 return retval;
1809 buffer += unaligned;
1810 address += unaligned;
1811 size -= unaligned;
1814 /* handle aligned words */
1815 if (size >= 4) {
1816 int aligned = size - (size % 4);
1818 retval = target_read_memory(target, address, 4, aligned / 4, buffer);
1819 if (retval != ERROR_OK)
1820 return retval;
1822 buffer += aligned;
1823 address += aligned;
1824 size -= aligned;
1827 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1828 if (size >= 2) {
1829 int aligned = size - (size % 2);
1830 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1831 if (retval != ERROR_OK)
1832 return retval;
1834 buffer += aligned;
1835 address += aligned;
1836 size -= aligned;
1838 /* handle tail writes of less than 4 bytes */
1839 if (size > 0) {
1840 retval = target_read_memory(target, address, 1, size, buffer);
1841 if (retval != ERROR_OK)
1842 return retval;
1845 return ERROR_OK;
1848 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1850 uint8_t *buffer;
1851 int retval;
1852 uint32_t i;
1853 uint32_t checksum = 0;
1854 if (!target_was_examined(target)) {
1855 LOG_ERROR("Target not examined yet");
1856 return ERROR_FAIL;
1859 retval = target->type->checksum_memory(target, address, size, &checksum);
1860 if (retval != ERROR_OK) {
1861 buffer = malloc(size);
1862 if (buffer == NULL) {
1863 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1864 return ERROR_COMMAND_SYNTAX_ERROR;
1866 retval = target_read_buffer(target, address, size, buffer);
1867 if (retval != ERROR_OK) {
1868 free(buffer);
1869 return retval;
1872 /* convert to target endianness */
1873 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
1874 uint32_t target_data;
1875 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1876 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1879 retval = image_calculate_checksum(buffer, size, &checksum);
1880 free(buffer);
1883 *crc = checksum;
1885 return retval;
1888 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1890 int retval;
1891 if (!target_was_examined(target)) {
1892 LOG_ERROR("Target not examined yet");
1893 return ERROR_FAIL;
1896 if (target->type->blank_check_memory == 0)
1897 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1899 retval = target->type->blank_check_memory(target, address, size, blank);
1901 return retval;
1904 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1906 uint8_t value_buf[4];
1907 if (!target_was_examined(target)) {
1908 LOG_ERROR("Target not examined yet");
1909 return ERROR_FAIL;
1912 int retval = target_read_memory(target, address, 4, 1, value_buf);
1914 if (retval == ERROR_OK) {
1915 *value = target_buffer_get_u32(target, value_buf);
1916 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1917 address,
1918 *value);
1919 } else {
1920 *value = 0x0;
1921 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1922 address);
1925 return retval;
1928 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1930 uint8_t value_buf[2];
1931 if (!target_was_examined(target)) {
1932 LOG_ERROR("Target not examined yet");
1933 return ERROR_FAIL;
1936 int retval = target_read_memory(target, address, 2, 1, value_buf);
1938 if (retval == ERROR_OK) {
1939 *value = target_buffer_get_u16(target, value_buf);
1940 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1941 address,
1942 *value);
1943 } else {
1944 *value = 0x0;
1945 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1946 address);
1949 return retval;
1952 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1954 int retval = target_read_memory(target, address, 1, 1, value);
1955 if (!target_was_examined(target)) {
1956 LOG_ERROR("Target not examined yet");
1957 return ERROR_FAIL;
1960 if (retval == ERROR_OK) {
1961 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1962 address,
1963 *value);
1964 } else {
1965 *value = 0x0;
1966 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1967 address);
1970 return retval;
1973 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1975 int retval;
1976 uint8_t value_buf[4];
1977 if (!target_was_examined(target)) {
1978 LOG_ERROR("Target not examined yet");
1979 return ERROR_FAIL;
1982 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1983 address,
1984 value);
1986 target_buffer_set_u32(target, value_buf, value);
1987 retval = target_write_memory(target, address, 4, 1, value_buf);
1988 if (retval != ERROR_OK)
1989 LOG_DEBUG("failed: %i", retval);
1991 return retval;
1994 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1996 int retval;
1997 uint8_t value_buf[2];
1998 if (!target_was_examined(target)) {
1999 LOG_ERROR("Target not examined yet");
2000 return ERROR_FAIL;
2003 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
2004 address,
2005 value);
2007 target_buffer_set_u16(target, value_buf, value);
2008 retval = target_write_memory(target, address, 2, 1, value_buf);
2009 if (retval != ERROR_OK)
2010 LOG_DEBUG("failed: %i", retval);
2012 return retval;
2015 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
2017 int retval;
2018 if (!target_was_examined(target)) {
2019 LOG_ERROR("Target not examined yet");
2020 return ERROR_FAIL;
2023 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2024 address, value);
2026 retval = target_write_memory(target, address, 1, 1, &value);
2027 if (retval != ERROR_OK)
2028 LOG_DEBUG("failed: %i", retval);
2030 return retval;
2033 static int find_target(struct command_context *cmd_ctx, const char *name)
2035 struct target *target = get_target(name);
2036 if (target == NULL) {
2037 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2038 return ERROR_FAIL;
2040 if (!target->tap->enabled) {
2041 LOG_USER("Target: TAP %s is disabled, "
2042 "can't be the current target\n",
2043 target->tap->dotted_name);
2044 return ERROR_FAIL;
2047 cmd_ctx->current_target = target->target_number;
2048 return ERROR_OK;
2052 COMMAND_HANDLER(handle_targets_command)
2054 int retval = ERROR_OK;
2055 if (CMD_ARGC == 1) {
2056 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2057 if (retval == ERROR_OK) {
2058 /* we're done! */
2059 return retval;
2063 struct target *target = all_targets;
2064 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2065 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2066 while (target) {
2067 const char *state;
2068 char marker = ' ';
2070 if (target->tap->enabled)
2071 state = target_state_name(target);
2072 else
2073 state = "tap-disabled";
2075 if (CMD_CTX->current_target == target->target_number)
2076 marker = '*';
2078 /* keep columns lined up to match the headers above */
2079 command_print(CMD_CTX,
2080 "%2d%c %-18s %-10s %-6s %-18s %s",
2081 target->target_number,
2082 marker,
2083 target_name(target),
2084 target_type_name(target),
2085 Jim_Nvp_value2name_simple(nvp_target_endian,
2086 target->endianness)->name,
2087 target->tap->dotted_name,
2088 state);
2089 target = target->next;
2092 return retval;
2095 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2097 static int powerDropout;
2098 static int srstAsserted;
2100 static int runPowerRestore;
2101 static int runPowerDropout;
2102 static int runSrstAsserted;
2103 static int runSrstDeasserted;
2105 static int sense_handler(void)
2107 static int prevSrstAsserted;
2108 static int prevPowerdropout;
2110 int retval = jtag_power_dropout(&powerDropout);
2111 if (retval != ERROR_OK)
2112 return retval;
2114 int powerRestored;
2115 powerRestored = prevPowerdropout && !powerDropout;
2116 if (powerRestored)
2117 runPowerRestore = 1;
2119 long long current = timeval_ms();
2120 static long long lastPower;
2121 int waitMore = lastPower + 2000 > current;
2122 if (powerDropout && !waitMore) {
2123 runPowerDropout = 1;
2124 lastPower = current;
2127 retval = jtag_srst_asserted(&srstAsserted);
2128 if (retval != ERROR_OK)
2129 return retval;
2131 int srstDeasserted;
2132 srstDeasserted = prevSrstAsserted && !srstAsserted;
2134 static long long lastSrst;
2135 waitMore = lastSrst + 2000 > current;
2136 if (srstDeasserted && !waitMore) {
2137 runSrstDeasserted = 1;
2138 lastSrst = current;
2141 if (!prevSrstAsserted && srstAsserted)
2142 runSrstAsserted = 1;
2144 prevSrstAsserted = srstAsserted;
2145 prevPowerdropout = powerDropout;
2147 if (srstDeasserted || powerRestored) {
2148 /* Other than logging the event we can't do anything here.
2149 * Issuing a reset is a particularly bad idea as we might
2150 * be inside a reset already.
2154 return ERROR_OK;
2157 /* process target state changes */
2158 static int handle_target(void *priv)
2160 Jim_Interp *interp = (Jim_Interp *)priv;
2161 int retval = ERROR_OK;
2163 if (!is_jtag_poll_safe()) {
2164 /* polling is disabled currently */
2165 return ERROR_OK;
2168 /* we do not want to recurse here... */
2169 static int recursive;
2170 if (!recursive) {
2171 recursive = 1;
2172 sense_handler();
2173 /* danger! running these procedures can trigger srst assertions and power dropouts.
2174 * We need to avoid an infinite loop/recursion here and we do that by
2175 * clearing the flags after running these events.
2177 int did_something = 0;
2178 if (runSrstAsserted) {
2179 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2180 Jim_Eval(interp, "srst_asserted");
2181 did_something = 1;
2183 if (runSrstDeasserted) {
2184 Jim_Eval(interp, "srst_deasserted");
2185 did_something = 1;
2187 if (runPowerDropout) {
2188 LOG_INFO("Power dropout detected, running power_dropout proc.");
2189 Jim_Eval(interp, "power_dropout");
2190 did_something = 1;
2192 if (runPowerRestore) {
2193 Jim_Eval(interp, "power_restore");
2194 did_something = 1;
2197 if (did_something) {
2198 /* clear detect flags */
2199 sense_handler();
2202 /* clear action flags */
2204 runSrstAsserted = 0;
2205 runSrstDeasserted = 0;
2206 runPowerRestore = 0;
2207 runPowerDropout = 0;
2209 recursive = 0;
2212 /* Poll targets for state changes unless that's globally disabled.
2213 * Skip targets that are currently disabled.
2215 for (struct target *target = all_targets;
2216 is_jtag_poll_safe() && target;
2217 target = target->next) {
2218 if (!target->tap->enabled)
2219 continue;
2221 if (target->backoff.times > target->backoff.count) {
2222 /* do not poll this time as we failed previously */
2223 target->backoff.count++;
2224 continue;
2226 target->backoff.count = 0;
2228 /* only poll target if we've got power and srst isn't asserted */
2229 if (!powerDropout && !srstAsserted) {
2230 /* polling may fail silently until the target has been examined */
2231 retval = target_poll(target);
2232 if (retval != ERROR_OK) {
2233 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2234 if (target->backoff.times * polling_interval < 5000) {
2235 target->backoff.times *= 2;
2236 target->backoff.times++;
2238 LOG_USER("Polling target %s failed, GDB will be halted. Polling again in %dms",
2239 target_name(target),
2240 target->backoff.times * polling_interval);
2242 /* Tell GDB to halt the debugger. This allows the user to
2243 * run monitor commands to handle the situation.
2245 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2246 return retval;
2248 /* Since we succeeded, we reset backoff count */
2249 if (target->backoff.times > 0)
2250 LOG_USER("Polling target %s succeeded again", target_name(target));
2251 target->backoff.times = 0;
2255 return retval;
2258 COMMAND_HANDLER(handle_reg_command)
2260 struct target *target;
2261 struct reg *reg = NULL;
2262 unsigned count = 0;
2263 char *value;
2265 LOG_DEBUG("-");
2267 target = get_current_target(CMD_CTX);
2269 /* list all available registers for the current target */
2270 if (CMD_ARGC == 0) {
2271 struct reg_cache *cache = target->reg_cache;
2273 count = 0;
2274 while (cache) {
2275 unsigned i;
2277 command_print(CMD_CTX, "===== %s", cache->name);
2279 for (i = 0, reg = cache->reg_list;
2280 i < cache->num_regs;
2281 i++, reg++, count++) {
2282 /* only print cached values if they are valid */
2283 if (reg->valid) {
2284 value = buf_to_str(reg->value,
2285 reg->size, 16);
2286 command_print(CMD_CTX,
2287 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2288 count, reg->name,
2289 reg->size, value,
2290 reg->dirty
2291 ? " (dirty)"
2292 : "");
2293 free(value);
2294 } else {
2295 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2296 count, reg->name,
2297 reg->size) ;
2300 cache = cache->next;
2303 return ERROR_OK;
2306 /* access a single register by its ordinal number */
2307 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2308 unsigned num;
2309 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2311 struct reg_cache *cache = target->reg_cache;
2312 count = 0;
2313 while (cache) {
2314 unsigned i;
2315 for (i = 0; i < cache->num_regs; i++) {
2316 if (count++ == num) {
2317 reg = &cache->reg_list[i];
2318 break;
2321 if (reg)
2322 break;
2323 cache = cache->next;
2326 if (!reg) {
2327 command_print(CMD_CTX, "%i is out of bounds, the current target "
2328 "has only %i registers (0 - %i)", num, count, count - 1);
2329 return ERROR_OK;
2331 } else {
2332 /* access a single register by its name */
2333 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2335 if (!reg) {
2336 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2337 return ERROR_OK;
2341 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2343 /* display a register */
2344 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2345 && (CMD_ARGV[1][0] <= '9')))) {
2346 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2347 reg->valid = 0;
2349 if (reg->valid == 0)
2350 reg->type->get(reg);
2351 value = buf_to_str(reg->value, reg->size, 16);
2352 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2353 free(value);
2354 return ERROR_OK;
2357 /* set register value */
2358 if (CMD_ARGC == 2) {
2359 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2360 if (buf == NULL)
2361 return ERROR_FAIL;
2362 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2364 reg->type->set(reg, buf);
2366 value = buf_to_str(reg->value, reg->size, 16);
2367 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2368 free(value);
2370 free(buf);
2372 return ERROR_OK;
2375 return ERROR_COMMAND_SYNTAX_ERROR;
2378 COMMAND_HANDLER(handle_poll_command)
2380 int retval = ERROR_OK;
2381 struct target *target = get_current_target(CMD_CTX);
2383 if (CMD_ARGC == 0) {
2384 command_print(CMD_CTX, "background polling: %s",
2385 jtag_poll_get_enabled() ? "on" : "off");
2386 command_print(CMD_CTX, "TAP: %s (%s)",
2387 target->tap->dotted_name,
2388 target->tap->enabled ? "enabled" : "disabled");
2389 if (!target->tap->enabled)
2390 return ERROR_OK;
2391 retval = target_poll(target);
2392 if (retval != ERROR_OK)
2393 return retval;
2394 retval = target_arch_state(target);
2395 if (retval != ERROR_OK)
2396 return retval;
2397 } else if (CMD_ARGC == 1) {
2398 bool enable;
2399 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2400 jtag_poll_set_enabled(enable);
2401 } else
2402 return ERROR_COMMAND_SYNTAX_ERROR;
2404 return retval;
2407 COMMAND_HANDLER(handle_wait_halt_command)
2409 if (CMD_ARGC > 1)
2410 return ERROR_COMMAND_SYNTAX_ERROR;
2412 unsigned ms = 5000;
2413 if (1 == CMD_ARGC) {
2414 int retval = parse_uint(CMD_ARGV[0], &ms);
2415 if (ERROR_OK != retval)
2416 return ERROR_COMMAND_SYNTAX_ERROR;
2417 /* convert seconds (given) to milliseconds (needed) */
2418 ms *= 1000;
2421 struct target *target = get_current_target(CMD_CTX);
2422 return target_wait_state(target, TARGET_HALTED, ms);
2425 /* wait for target state to change. The trick here is to have a low
2426 * latency for short waits and not to suck up all the CPU time
2427 * on longer waits.
2429 * After 500ms, keep_alive() is invoked
2431 int target_wait_state(struct target *target, enum target_state state, int ms)
2433 int retval;
2434 long long then = 0, cur;
2435 int once = 1;
2437 for (;;) {
2438 retval = target_poll(target);
2439 if (retval != ERROR_OK)
2440 return retval;
2441 if (target->state == state)
2442 break;
2443 cur = timeval_ms();
2444 if (once) {
2445 once = 0;
2446 then = timeval_ms();
2447 LOG_DEBUG("waiting for target %s...",
2448 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2451 if (cur-then > 500)
2452 keep_alive();
2454 if ((cur-then) > ms) {
2455 LOG_ERROR("timed out while waiting for target %s",
2456 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2457 return ERROR_FAIL;
2461 return ERROR_OK;
2464 COMMAND_HANDLER(handle_halt_command)
2466 LOG_DEBUG("-");
2468 struct target *target = get_current_target(CMD_CTX);
2469 int retval = target_halt(target);
2470 if (ERROR_OK != retval)
2471 return retval;
2473 if (CMD_ARGC == 1) {
2474 unsigned wait_local;
2475 retval = parse_uint(CMD_ARGV[0], &wait_local);
2476 if (ERROR_OK != retval)
2477 return ERROR_COMMAND_SYNTAX_ERROR;
2478 if (!wait_local)
2479 return ERROR_OK;
2482 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2485 COMMAND_HANDLER(handle_soft_reset_halt_command)
2487 struct target *target = get_current_target(CMD_CTX);
2489 LOG_USER("requesting target halt and executing a soft reset");
2491 target_soft_reset_halt(target);
2493 return ERROR_OK;
2496 COMMAND_HANDLER(handle_reset_command)
2498 if (CMD_ARGC > 1)
2499 return ERROR_COMMAND_SYNTAX_ERROR;
2501 enum target_reset_mode reset_mode = RESET_RUN;
2502 if (CMD_ARGC == 1) {
2503 const Jim_Nvp *n;
2504 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2505 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2506 return ERROR_COMMAND_SYNTAX_ERROR;
2507 reset_mode = n->value;
2510 /* reset *all* targets */
2511 return target_process_reset(CMD_CTX, reset_mode);
2515 COMMAND_HANDLER(handle_resume_command)
2517 int current = 1;
2518 if (CMD_ARGC > 1)
2519 return ERROR_COMMAND_SYNTAX_ERROR;
2521 struct target *target = get_current_target(CMD_CTX);
2523 /* with no CMD_ARGV, resume from current pc, addr = 0,
2524 * with one arguments, addr = CMD_ARGV[0],
2525 * handle breakpoints, not debugging */
2526 uint32_t addr = 0;
2527 if (CMD_ARGC == 1) {
2528 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2529 current = 0;
2532 return target_resume(target, current, addr, 1, 0);
2535 COMMAND_HANDLER(handle_step_command)
2537 if (CMD_ARGC > 1)
2538 return ERROR_COMMAND_SYNTAX_ERROR;
2540 LOG_DEBUG("-");
2542 /* with no CMD_ARGV, step from current pc, addr = 0,
2543 * with one argument addr = CMD_ARGV[0],
2544 * handle breakpoints, debugging */
2545 uint32_t addr = 0;
2546 int current_pc = 1;
2547 if (CMD_ARGC == 1) {
2548 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2549 current_pc = 0;
2552 struct target *target = get_current_target(CMD_CTX);
2554 return target->type->step(target, current_pc, addr, 1);
2557 static void handle_md_output(struct command_context *cmd_ctx,
2558 struct target *target, uint32_t address, unsigned size,
2559 unsigned count, const uint8_t *buffer)
2561 const unsigned line_bytecnt = 32;
2562 unsigned line_modulo = line_bytecnt / size;
2564 char output[line_bytecnt * 4 + 1];
2565 unsigned output_len = 0;
2567 const char *value_fmt;
2568 switch (size) {
2569 case 4:
2570 value_fmt = "%8.8x ";
2571 break;
2572 case 2:
2573 value_fmt = "%4.4x ";
2574 break;
2575 case 1:
2576 value_fmt = "%2.2x ";
2577 break;
2578 default:
2579 /* "can't happen", caller checked */
2580 LOG_ERROR("invalid memory read size: %u", size);
2581 return;
2584 for (unsigned i = 0; i < count; i++) {
2585 if (i % line_modulo == 0) {
2586 output_len += snprintf(output + output_len,
2587 sizeof(output) - output_len,
2588 "0x%8.8x: ",
2589 (unsigned)(address + (i*size)));
2592 uint32_t value = 0;
2593 const uint8_t *value_ptr = buffer + i * size;
2594 switch (size) {
2595 case 4:
2596 value = target_buffer_get_u32(target, value_ptr);
2597 break;
2598 case 2:
2599 value = target_buffer_get_u16(target, value_ptr);
2600 break;
2601 case 1:
2602 value = *value_ptr;
2604 output_len += snprintf(output + output_len,
2605 sizeof(output) - output_len,
2606 value_fmt, value);
2608 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2609 command_print(cmd_ctx, "%s", output);
2610 output_len = 0;
2615 COMMAND_HANDLER(handle_md_command)
2617 if (CMD_ARGC < 1)
2618 return ERROR_COMMAND_SYNTAX_ERROR;
2620 unsigned size = 0;
2621 switch (CMD_NAME[2]) {
2622 case 'w':
2623 size = 4;
2624 break;
2625 case 'h':
2626 size = 2;
2627 break;
2628 case 'b':
2629 size = 1;
2630 break;
2631 default:
2632 return ERROR_COMMAND_SYNTAX_ERROR;
2635 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2636 int (*fn)(struct target *target,
2637 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2638 if (physical) {
2639 CMD_ARGC--;
2640 CMD_ARGV++;
2641 fn = target_read_phys_memory;
2642 } else
2643 fn = target_read_memory;
2644 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2645 return ERROR_COMMAND_SYNTAX_ERROR;
2647 uint32_t address;
2648 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2650 unsigned count = 1;
2651 if (CMD_ARGC == 2)
2652 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2654 uint8_t *buffer = calloc(count, size);
2656 struct target *target = get_current_target(CMD_CTX);
2657 int retval = fn(target, address, size, count, buffer);
2658 if (ERROR_OK == retval)
2659 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2661 free(buffer);
2663 return retval;
2666 typedef int (*target_write_fn)(struct target *target,
2667 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2669 static int target_write_memory_fast(struct target *target,
2670 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
2672 return target_write_buffer(target, address, size * count, buffer);
2675 static int target_fill_mem(struct target *target,
2676 uint32_t address,
2677 target_write_fn fn,
2678 unsigned data_size,
2679 /* value */
2680 uint32_t b,
2681 /* count */
2682 unsigned c)
2684 /* We have to write in reasonably large chunks to be able
2685 * to fill large memory areas with any sane speed */
2686 const unsigned chunk_size = 16384;
2687 uint8_t *target_buf = malloc(chunk_size * data_size);
2688 if (target_buf == NULL) {
2689 LOG_ERROR("Out of memory");
2690 return ERROR_FAIL;
2693 for (unsigned i = 0; i < chunk_size; i++) {
2694 switch (data_size) {
2695 case 4:
2696 target_buffer_set_u32(target, target_buf + i * data_size, b);
2697 break;
2698 case 2:
2699 target_buffer_set_u16(target, target_buf + i * data_size, b);
2700 break;
2701 case 1:
2702 target_buffer_set_u8(target, target_buf + i * data_size, b);
2703 break;
2704 default:
2705 exit(-1);
2709 int retval = ERROR_OK;
2711 for (unsigned x = 0; x < c; x += chunk_size) {
2712 unsigned current;
2713 current = c - x;
2714 if (current > chunk_size)
2715 current = chunk_size;
2716 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2717 if (retval != ERROR_OK)
2718 break;
2719 /* avoid GDB timeouts */
2720 keep_alive();
2722 free(target_buf);
2724 return retval;
2728 COMMAND_HANDLER(handle_mw_command)
2730 if (CMD_ARGC < 2)
2731 return ERROR_COMMAND_SYNTAX_ERROR;
2732 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2733 target_write_fn fn;
2734 if (physical) {
2735 CMD_ARGC--;
2736 CMD_ARGV++;
2737 fn = target_write_phys_memory;
2738 } else
2739 fn = target_write_memory_fast;
2740 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2741 return ERROR_COMMAND_SYNTAX_ERROR;
2743 uint32_t address;
2744 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2746 uint32_t value;
2747 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2749 unsigned count = 1;
2750 if (CMD_ARGC == 3)
2751 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2753 struct target *target = get_current_target(CMD_CTX);
2754 unsigned wordsize;
2755 switch (CMD_NAME[2]) {
2756 case 'w':
2757 wordsize = 4;
2758 break;
2759 case 'h':
2760 wordsize = 2;
2761 break;
2762 case 'b':
2763 wordsize = 1;
2764 break;
2765 default:
2766 return ERROR_COMMAND_SYNTAX_ERROR;
2769 return target_fill_mem(target, address, fn, wordsize, value, count);
2772 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2773 uint32_t *min_address, uint32_t *max_address)
2775 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2776 return ERROR_COMMAND_SYNTAX_ERROR;
2778 /* a base address isn't always necessary,
2779 * default to 0x0 (i.e. don't relocate) */
2780 if (CMD_ARGC >= 2) {
2781 uint32_t addr;
2782 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2783 image->base_address = addr;
2784 image->base_address_set = 1;
2785 } else
2786 image->base_address_set = 0;
2788 image->start_address_set = 0;
2790 if (CMD_ARGC >= 4)
2791 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2792 if (CMD_ARGC == 5) {
2793 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2794 /* use size (given) to find max (required) */
2795 *max_address += *min_address;
2798 if (*min_address > *max_address)
2799 return ERROR_COMMAND_SYNTAX_ERROR;
2801 return ERROR_OK;
2804 COMMAND_HANDLER(handle_load_image_command)
2806 uint8_t *buffer;
2807 size_t buf_cnt;
2808 uint32_t image_size;
2809 uint32_t min_address = 0;
2810 uint32_t max_address = 0xffffffff;
2811 int i;
2812 struct image image;
2814 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2815 &image, &min_address, &max_address);
2816 if (ERROR_OK != retval)
2817 return retval;
2819 struct target *target = get_current_target(CMD_CTX);
2821 struct duration bench;
2822 duration_start(&bench);
2824 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2825 return ERROR_OK;
2827 image_size = 0x0;
2828 retval = ERROR_OK;
2829 for (i = 0; i < image.num_sections; i++) {
2830 buffer = malloc(image.sections[i].size);
2831 if (buffer == NULL) {
2832 command_print(CMD_CTX,
2833 "error allocating buffer for section (%d bytes)",
2834 (int)(image.sections[i].size));
2835 break;
2838 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
2839 if (retval != ERROR_OK) {
2840 free(buffer);
2841 break;
2844 uint32_t offset = 0;
2845 uint32_t length = buf_cnt;
2847 /* DANGER!!! beware of unsigned comparision here!!! */
2849 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
2850 (image.sections[i].base_address < max_address)) {
2852 if (image.sections[i].base_address < min_address) {
2853 /* clip addresses below */
2854 offset += min_address-image.sections[i].base_address;
2855 length -= offset;
2858 if (image.sections[i].base_address + buf_cnt > max_address)
2859 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2861 retval = target_write_buffer(target,
2862 image.sections[i].base_address + offset, length, buffer + offset);
2863 if (retval != ERROR_OK) {
2864 free(buffer);
2865 break;
2867 image_size += length;
2868 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2869 (unsigned int)length,
2870 image.sections[i].base_address + offset);
2873 free(buffer);
2876 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
2877 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2878 "in %fs (%0.3f KiB/s)", image_size,
2879 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2882 image_close(&image);
2884 return retval;
2888 COMMAND_HANDLER(handle_dump_image_command)
2890 struct fileio fileio;
2891 uint8_t *buffer;
2892 int retval, retvaltemp;
2893 uint32_t address, size;
2894 struct duration bench;
2895 struct target *target = get_current_target(CMD_CTX);
2897 if (CMD_ARGC != 3)
2898 return ERROR_COMMAND_SYNTAX_ERROR;
2900 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2901 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2903 uint32_t buf_size = (size > 4096) ? 4096 : size;
2904 buffer = malloc(buf_size);
2905 if (!buffer)
2906 return ERROR_FAIL;
2908 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2909 if (retval != ERROR_OK) {
2910 free(buffer);
2911 return retval;
2914 duration_start(&bench);
2916 while (size > 0) {
2917 size_t size_written;
2918 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
2919 retval = target_read_buffer(target, address, this_run_size, buffer);
2920 if (retval != ERROR_OK)
2921 break;
2923 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2924 if (retval != ERROR_OK)
2925 break;
2927 size -= this_run_size;
2928 address += this_run_size;
2931 free(buffer);
2933 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
2934 int filesize;
2935 retval = fileio_size(&fileio, &filesize);
2936 if (retval != ERROR_OK)
2937 return retval;
2938 command_print(CMD_CTX,
2939 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
2940 duration_elapsed(&bench), duration_kbps(&bench, filesize));
2943 retvaltemp = fileio_close(&fileio);
2944 if (retvaltemp != ERROR_OK)
2945 return retvaltemp;
2947 return retval;
2950 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2952 uint8_t *buffer;
2953 size_t buf_cnt;
2954 uint32_t image_size;
2955 int i;
2956 int retval;
2957 uint32_t checksum = 0;
2958 uint32_t mem_checksum = 0;
2960 struct image image;
2962 struct target *target = get_current_target(CMD_CTX);
2964 if (CMD_ARGC < 1)
2965 return ERROR_COMMAND_SYNTAX_ERROR;
2967 if (!target) {
2968 LOG_ERROR("no target selected");
2969 return ERROR_FAIL;
2972 struct duration bench;
2973 duration_start(&bench);
2975 if (CMD_ARGC >= 2) {
2976 uint32_t addr;
2977 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2978 image.base_address = addr;
2979 image.base_address_set = 1;
2980 } else {
2981 image.base_address_set = 0;
2982 image.base_address = 0x0;
2985 image.start_address_set = 0;
2987 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
2988 if (retval != ERROR_OK)
2989 return retval;
2991 image_size = 0x0;
2992 int diffs = 0;
2993 retval = ERROR_OK;
2994 for (i = 0; i < image.num_sections; i++) {
2995 buffer = malloc(image.sections[i].size);
2996 if (buffer == NULL) {
2997 command_print(CMD_CTX,
2998 "error allocating buffer for section (%d bytes)",
2999 (int)(image.sections[i].size));
3000 break;
3002 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3003 if (retval != ERROR_OK) {
3004 free(buffer);
3005 break;
3008 if (verify) {
3009 /* calculate checksum of image */
3010 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3011 if (retval != ERROR_OK) {
3012 free(buffer);
3013 break;
3016 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3017 if (retval != ERROR_OK) {
3018 free(buffer);
3019 break;
3022 if (checksum != mem_checksum) {
3023 /* failed crc checksum, fall back to a binary compare */
3024 uint8_t *data;
3026 if (diffs == 0)
3027 LOG_ERROR("checksum mismatch - attempting binary compare");
3029 data = (uint8_t *)malloc(buf_cnt);
3031 /* Can we use 32bit word accesses? */
3032 int size = 1;
3033 int count = buf_cnt;
3034 if ((count % 4) == 0) {
3035 size *= 4;
3036 count /= 4;
3038 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3039 if (retval == ERROR_OK) {
3040 uint32_t t;
3041 for (t = 0; t < buf_cnt; t++) {
3042 if (data[t] != buffer[t]) {
3043 command_print(CMD_CTX,
3044 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3045 diffs,
3046 (unsigned)(t + image.sections[i].base_address),
3047 data[t],
3048 buffer[t]);
3049 if (diffs++ >= 127) {
3050 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3051 free(data);
3052 free(buffer);
3053 goto done;
3056 keep_alive();
3059 free(data);
3061 } else {
3062 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3063 image.sections[i].base_address,
3064 buf_cnt);
3067 free(buffer);
3068 image_size += buf_cnt;
3070 if (diffs > 0)
3071 command_print(CMD_CTX, "No more differences found.");
3072 done:
3073 if (diffs > 0)
3074 retval = ERROR_FAIL;
3075 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3076 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3077 "in %fs (%0.3f KiB/s)", image_size,
3078 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3081 image_close(&image);
3083 return retval;
3086 COMMAND_HANDLER(handle_verify_image_command)
3088 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3091 COMMAND_HANDLER(handle_test_image_command)
3093 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3096 static int handle_bp_command_list(struct command_context *cmd_ctx)
3098 struct target *target = get_current_target(cmd_ctx);
3099 struct breakpoint *breakpoint = target->breakpoints;
3100 while (breakpoint) {
3101 if (breakpoint->type == BKPT_SOFT) {
3102 char *buf = buf_to_str(breakpoint->orig_instr,
3103 breakpoint->length, 16);
3104 command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3105 breakpoint->address,
3106 breakpoint->length,
3107 breakpoint->set, buf);
3108 free(buf);
3109 } else {
3110 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3111 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3112 breakpoint->asid,
3113 breakpoint->length, breakpoint->set);
3114 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3115 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3116 breakpoint->address,
3117 breakpoint->length, breakpoint->set);
3118 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3119 breakpoint->asid);
3120 } else
3121 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3122 breakpoint->address,
3123 breakpoint->length, breakpoint->set);
3126 breakpoint = breakpoint->next;
3128 return ERROR_OK;
3131 static int handle_bp_command_set(struct command_context *cmd_ctx,
3132 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3134 struct target *target = get_current_target(cmd_ctx);
3136 if (asid == 0) {
3137 int retval = breakpoint_add(target, addr, length, hw);
3138 if (ERROR_OK == retval)
3139 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3140 else {
3141 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3142 return retval;
3144 } else if (addr == 0) {
3145 int retval = context_breakpoint_add(target, asid, length, hw);
3146 if (ERROR_OK == retval)
3147 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3148 else {
3149 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3150 return retval;
3152 } else {
3153 int retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3154 if (ERROR_OK == retval)
3155 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3156 else {
3157 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3158 return retval;
3161 return ERROR_OK;
3164 COMMAND_HANDLER(handle_bp_command)
3166 uint32_t addr;
3167 uint32_t asid;
3168 uint32_t length;
3169 int hw = BKPT_SOFT;
3171 switch (CMD_ARGC) {
3172 case 0:
3173 return handle_bp_command_list(CMD_CTX);
3175 case 2:
3176 asid = 0;
3177 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3178 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3179 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3181 case 3:
3182 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3183 hw = BKPT_HARD;
3184 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3186 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3188 asid = 0;
3189 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3190 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3191 hw = BKPT_HARD;
3192 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3193 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3194 addr = 0;
3195 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3198 case 4:
3199 hw = BKPT_HARD;
3200 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3201 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3202 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3203 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3205 default:
3206 return ERROR_COMMAND_SYNTAX_ERROR;
3210 COMMAND_HANDLER(handle_rbp_command)
3212 if (CMD_ARGC != 1)
3213 return ERROR_COMMAND_SYNTAX_ERROR;
3215 uint32_t addr;
3216 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3218 struct target *target = get_current_target(CMD_CTX);
3219 breakpoint_remove(target, addr);
3221 return ERROR_OK;
3224 COMMAND_HANDLER(handle_wp_command)
3226 struct target *target = get_current_target(CMD_CTX);
3228 if (CMD_ARGC == 0) {
3229 struct watchpoint *watchpoint = target->watchpoints;
3231 while (watchpoint) {
3232 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3233 ", len: 0x%8.8" PRIx32
3234 ", r/w/a: %i, value: 0x%8.8" PRIx32
3235 ", mask: 0x%8.8" PRIx32,
3236 watchpoint->address,
3237 watchpoint->length,
3238 (int)watchpoint->rw,
3239 watchpoint->value,
3240 watchpoint->mask);
3241 watchpoint = watchpoint->next;
3243 return ERROR_OK;
3246 enum watchpoint_rw type = WPT_ACCESS;
3247 uint32_t addr = 0;
3248 uint32_t length = 0;
3249 uint32_t data_value = 0x0;
3250 uint32_t data_mask = 0xffffffff;
3252 switch (CMD_ARGC) {
3253 case 5:
3254 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3255 /* fall through */
3256 case 4:
3257 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3258 /* fall through */
3259 case 3:
3260 switch (CMD_ARGV[2][0]) {
3261 case 'r':
3262 type = WPT_READ;
3263 break;
3264 case 'w':
3265 type = WPT_WRITE;
3266 break;
3267 case 'a':
3268 type = WPT_ACCESS;
3269 break;
3270 default:
3271 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3272 return ERROR_COMMAND_SYNTAX_ERROR;
3274 /* fall through */
3275 case 2:
3276 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3277 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3278 break;
3280 default:
3281 return ERROR_COMMAND_SYNTAX_ERROR;
3284 int retval = watchpoint_add(target, addr, length, type,
3285 data_value, data_mask);
3286 if (ERROR_OK != retval)
3287 LOG_ERROR("Failure setting watchpoints");
3289 return retval;
3292 COMMAND_HANDLER(handle_rwp_command)
3294 if (CMD_ARGC != 1)
3295 return ERROR_COMMAND_SYNTAX_ERROR;
3297 uint32_t addr;
3298 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3300 struct target *target = get_current_target(CMD_CTX);
3301 watchpoint_remove(target, addr);
3303 return ERROR_OK;
3307 * Translate a virtual address to a physical address.
3309 * The low-level target implementation must have logged a detailed error
3310 * which is forwarded to telnet/GDB session.
3312 COMMAND_HANDLER(handle_virt2phys_command)
3314 if (CMD_ARGC != 1)
3315 return ERROR_COMMAND_SYNTAX_ERROR;
3317 uint32_t va;
3318 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3319 uint32_t pa;
3321 struct target *target = get_current_target(CMD_CTX);
3322 int retval = target->type->virt2phys(target, va, &pa);
3323 if (retval == ERROR_OK)
3324 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3326 return retval;
3329 static void writeData(FILE *f, const void *data, size_t len)
3331 size_t written = fwrite(data, 1, len, f);
3332 if (written != len)
3333 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3336 static void writeLong(FILE *f, int l)
3338 int i;
3339 for (i = 0; i < 4; i++) {
3340 char c = (l >> (i*8))&0xff;
3341 writeData(f, &c, 1);
3346 static void writeString(FILE *f, char *s)
3348 writeData(f, s, strlen(s));
3351 /* Dump a gmon.out histogram file. */
3352 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3354 uint32_t i;
3355 FILE *f = fopen(filename, "w");
3356 if (f == NULL)
3357 return;
3358 writeString(f, "gmon");
3359 writeLong(f, 0x00000001); /* Version */
3360 writeLong(f, 0); /* padding */
3361 writeLong(f, 0); /* padding */
3362 writeLong(f, 0); /* padding */
3364 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3365 writeData(f, &zero, 1);
3367 /* figure out bucket size */
3368 uint32_t min = samples[0];
3369 uint32_t max = samples[0];
3370 for (i = 0; i < sampleNum; i++) {
3371 if (min > samples[i])
3372 min = samples[i];
3373 if (max < samples[i])
3374 max = samples[i];
3377 int addressSpace = (max - min + 1);
3378 assert(addressSpace >= 2);
3380 static const uint32_t maxBuckets = 16 * 1024; /* maximum buckets. */
3381 uint32_t length = addressSpace;
3382 if (length > maxBuckets)
3383 length = maxBuckets;
3384 int *buckets = malloc(sizeof(int)*length);
3385 if (buckets == NULL) {
3386 fclose(f);
3387 return;
3389 memset(buckets, 0, sizeof(int) * length);
3390 for (i = 0; i < sampleNum; i++) {
3391 uint32_t address = samples[i];
3392 long long a = address - min;
3393 long long b = length - 1;
3394 long long c = addressSpace - 1;
3395 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3396 buckets[index_t]++;
3399 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3400 writeLong(f, min); /* low_pc */
3401 writeLong(f, max); /* high_pc */
3402 writeLong(f, length); /* # of samples */
3403 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3404 writeString(f, "seconds");
3405 for (i = 0; i < (15-strlen("seconds")); i++)
3406 writeData(f, &zero, 1);
3407 writeString(f, "s");
3409 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3411 char *data = malloc(2 * length);
3412 if (data != NULL) {
3413 for (i = 0; i < length; i++) {
3414 int val;
3415 val = buckets[i];
3416 if (val > 65535)
3417 val = 65535;
3418 data[i * 2] = val&0xff;
3419 data[i * 2 + 1] = (val >> 8) & 0xff;
3421 free(buckets);
3422 writeData(f, data, length * 2);
3423 free(data);
3424 } else
3425 free(buckets);
3427 fclose(f);
3430 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3431 * which will be used as a random sampling of PC */
3432 COMMAND_HANDLER(handle_profile_command)
3434 struct target *target = get_current_target(CMD_CTX);
3435 struct timeval timeout, now;
3437 gettimeofday(&timeout, NULL);
3438 if (CMD_ARGC != 2)
3439 return ERROR_COMMAND_SYNTAX_ERROR;
3440 unsigned offset;
3441 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3443 timeval_add_time(&timeout, offset, 0);
3446 * @todo: Some cores let us sample the PC without the
3447 * annoying halt/resume step; for example, ARMv7 PCSR.
3448 * Provide a way to use that more efficient mechanism.
3451 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3453 static const int maxSample = 10000;
3454 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3455 if (samples == NULL)
3456 return ERROR_OK;
3458 int numSamples = 0;
3459 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3460 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3462 int retval = ERROR_OK;
3463 for (;;) {
3464 target_poll(target);
3465 if (target->state == TARGET_HALTED) {
3466 uint32_t t = *((uint32_t *)reg->value);
3467 samples[numSamples++] = t;
3468 /* current pc, addr = 0, do not handle breakpoints, not debugging */
3469 retval = target_resume(target, 1, 0, 0, 0);
3470 target_poll(target);
3471 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3472 } else if (target->state == TARGET_RUNNING) {
3473 /* We want to quickly sample the PC. */
3474 retval = target_halt(target);
3475 if (retval != ERROR_OK) {
3476 free(samples);
3477 return retval;
3479 } else {
3480 command_print(CMD_CTX, "Target not halted or running");
3481 retval = ERROR_OK;
3482 break;
3484 if (retval != ERROR_OK)
3485 break;
3487 gettimeofday(&now, NULL);
3488 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec)
3489 && (now.tv_usec >= timeout.tv_usec))) {
3490 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3491 retval = target_poll(target);
3492 if (retval != ERROR_OK) {
3493 free(samples);
3494 return retval;
3496 if (target->state == TARGET_HALTED) {
3497 /* current pc, addr = 0, do not handle
3498 * breakpoints, not debugging */
3499 target_resume(target, 1, 0, 0, 0);
3501 retval = target_poll(target);
3502 if (retval != ERROR_OK) {
3503 free(samples);
3504 return retval;
3506 writeGmon(samples, numSamples, CMD_ARGV[1]);
3507 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3508 break;
3511 free(samples);
3513 return retval;
3516 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3518 char *namebuf;
3519 Jim_Obj *nameObjPtr, *valObjPtr;
3520 int result;
3522 namebuf = alloc_printf("%s(%d)", varname, idx);
3523 if (!namebuf)
3524 return JIM_ERR;
3526 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3527 valObjPtr = Jim_NewIntObj(interp, val);
3528 if (!nameObjPtr || !valObjPtr) {
3529 free(namebuf);
3530 return JIM_ERR;
3533 Jim_IncrRefCount(nameObjPtr);
3534 Jim_IncrRefCount(valObjPtr);
3535 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3536 Jim_DecrRefCount(interp, nameObjPtr);
3537 Jim_DecrRefCount(interp, valObjPtr);
3538 free(namebuf);
3539 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3540 return result;
3543 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3545 struct command_context *context;
3546 struct target *target;
3548 context = current_command_context(interp);
3549 assert(context != NULL);
3551 target = get_current_target(context);
3552 if (target == NULL) {
3553 LOG_ERROR("mem2array: no current target");
3554 return JIM_ERR;
3557 return target_mem2array(interp, target, argc - 1, argv + 1);
3560 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3562 long l;
3563 uint32_t width;
3564 int len;
3565 uint32_t addr;
3566 uint32_t count;
3567 uint32_t v;
3568 const char *varname;
3569 int n, e, retval;
3570 uint32_t i;
3572 /* argv[1] = name of array to receive the data
3573 * argv[2] = desired width
3574 * argv[3] = memory address
3575 * argv[4] = count of times to read
3577 if (argc != 4) {
3578 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3579 return JIM_ERR;
3581 varname = Jim_GetString(argv[0], &len);
3582 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3584 e = Jim_GetLong(interp, argv[1], &l);
3585 width = l;
3586 if (e != JIM_OK)
3587 return e;
3589 e = Jim_GetLong(interp, argv[2], &l);
3590 addr = l;
3591 if (e != JIM_OK)
3592 return e;
3593 e = Jim_GetLong(interp, argv[3], &l);
3594 len = l;
3595 if (e != JIM_OK)
3596 return e;
3597 switch (width) {
3598 case 8:
3599 width = 1;
3600 break;
3601 case 16:
3602 width = 2;
3603 break;
3604 case 32:
3605 width = 4;
3606 break;
3607 default:
3608 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3609 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3610 return JIM_ERR;
3612 if (len == 0) {
3613 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3614 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3615 return JIM_ERR;
3617 if ((addr + (len * width)) < addr) {
3618 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3619 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3620 return JIM_ERR;
3622 /* absurd transfer size? */
3623 if (len > 65536) {
3624 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3625 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3626 return JIM_ERR;
3629 if ((width == 1) ||
3630 ((width == 2) && ((addr & 1) == 0)) ||
3631 ((width == 4) && ((addr & 3) == 0))) {
3632 /* all is well */
3633 } else {
3634 char buf[100];
3635 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3636 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3637 addr,
3638 width);
3639 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3640 return JIM_ERR;
3643 /* Transfer loop */
3645 /* index counter */
3646 n = 0;
3648 size_t buffersize = 4096;
3649 uint8_t *buffer = malloc(buffersize);
3650 if (buffer == NULL)
3651 return JIM_ERR;
3653 /* assume ok */
3654 e = JIM_OK;
3655 while (len) {
3656 /* Slurp... in buffer size chunks */
3658 count = len; /* in objects.. */
3659 if (count > (buffersize / width))
3660 count = (buffersize / width);
3662 retval = target_read_memory(target, addr, width, count, buffer);
3663 if (retval != ERROR_OK) {
3664 /* BOO !*/
3665 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3666 (unsigned int)addr,
3667 (int)width,
3668 (int)count);
3669 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3670 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3671 e = JIM_ERR;
3672 break;
3673 } else {
3674 v = 0; /* shut up gcc */
3675 for (i = 0; i < count ; i++, n++) {
3676 switch (width) {
3677 case 4:
3678 v = target_buffer_get_u32(target, &buffer[i*width]);
3679 break;
3680 case 2:
3681 v = target_buffer_get_u16(target, &buffer[i*width]);
3682 break;
3683 case 1:
3684 v = buffer[i] & 0x0ff;
3685 break;
3687 new_int_array_element(interp, varname, n, v);
3689 len -= count;
3693 free(buffer);
3695 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3697 return e;
3700 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
3702 char *namebuf;
3703 Jim_Obj *nameObjPtr, *valObjPtr;
3704 int result;
3705 long l;
3707 namebuf = alloc_printf("%s(%d)", varname, idx);
3708 if (!namebuf)
3709 return JIM_ERR;
3711 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3712 if (!nameObjPtr) {
3713 free(namebuf);
3714 return JIM_ERR;
3717 Jim_IncrRefCount(nameObjPtr);
3718 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3719 Jim_DecrRefCount(interp, nameObjPtr);
3720 free(namebuf);
3721 if (valObjPtr == NULL)
3722 return JIM_ERR;
3724 result = Jim_GetLong(interp, valObjPtr, &l);
3725 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3726 *val = l;
3727 return result;
3730 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3732 struct command_context *context;
3733 struct target *target;
3735 context = current_command_context(interp);
3736 assert(context != NULL);
3738 target = get_current_target(context);
3739 if (target == NULL) {
3740 LOG_ERROR("array2mem: no current target");
3741 return JIM_ERR;
3744 return target_array2mem(interp, target, argc-1, argv + 1);
3747 static int target_array2mem(Jim_Interp *interp, struct target *target,
3748 int argc, Jim_Obj *const *argv)
3750 long l;
3751 uint32_t width;
3752 int len;
3753 uint32_t addr;
3754 uint32_t count;
3755 uint32_t v;
3756 const char *varname;
3757 int n, e, retval;
3758 uint32_t i;
3760 /* argv[1] = name of array to get the data
3761 * argv[2] = desired width
3762 * argv[3] = memory address
3763 * argv[4] = count to write
3765 if (argc != 4) {
3766 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3767 return JIM_ERR;
3769 varname = Jim_GetString(argv[0], &len);
3770 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3772 e = Jim_GetLong(interp, argv[1], &l);
3773 width = l;
3774 if (e != JIM_OK)
3775 return e;
3777 e = Jim_GetLong(interp, argv[2], &l);
3778 addr = l;
3779 if (e != JIM_OK)
3780 return e;
3781 e = Jim_GetLong(interp, argv[3], &l);
3782 len = l;
3783 if (e != JIM_OK)
3784 return e;
3785 switch (width) {
3786 case 8:
3787 width = 1;
3788 break;
3789 case 16:
3790 width = 2;
3791 break;
3792 case 32:
3793 width = 4;
3794 break;
3795 default:
3796 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3797 Jim_AppendStrings(interp, Jim_GetResult(interp),
3798 "Invalid width param, must be 8/16/32", NULL);
3799 return JIM_ERR;
3801 if (len == 0) {
3802 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3803 Jim_AppendStrings(interp, Jim_GetResult(interp),
3804 "array2mem: zero width read?", NULL);
3805 return JIM_ERR;
3807 if ((addr + (len * width)) < addr) {
3808 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3809 Jim_AppendStrings(interp, Jim_GetResult(interp),
3810 "array2mem: addr + len - wraps to zero?", NULL);
3811 return JIM_ERR;
3813 /* absurd transfer size? */
3814 if (len > 65536) {
3815 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3816 Jim_AppendStrings(interp, Jim_GetResult(interp),
3817 "array2mem: absurd > 64K item request", NULL);
3818 return JIM_ERR;
3821 if ((width == 1) ||
3822 ((width == 2) && ((addr & 1) == 0)) ||
3823 ((width == 4) && ((addr & 3) == 0))) {
3824 /* all is well */
3825 } else {
3826 char buf[100];
3827 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3828 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3829 (unsigned int)addr,
3830 (int)width);
3831 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3832 return JIM_ERR;
3835 /* Transfer loop */
3837 /* index counter */
3838 n = 0;
3839 /* assume ok */
3840 e = JIM_OK;
3842 size_t buffersize = 4096;
3843 uint8_t *buffer = malloc(buffersize);
3844 if (buffer == NULL)
3845 return JIM_ERR;
3847 while (len) {
3848 /* Slurp... in buffer size chunks */
3850 count = len; /* in objects.. */
3851 if (count > (buffersize / width))
3852 count = (buffersize / width);
3854 v = 0; /* shut up gcc */
3855 for (i = 0; i < count; i++, n++) {
3856 get_int_array_element(interp, varname, n, &v);
3857 switch (width) {
3858 case 4:
3859 target_buffer_set_u32(target, &buffer[i * width], v);
3860 break;
3861 case 2:
3862 target_buffer_set_u16(target, &buffer[i * width], v);
3863 break;
3864 case 1:
3865 buffer[i] = v & 0x0ff;
3866 break;
3869 len -= count;
3871 retval = target_write_memory(target, addr, width, count, buffer);
3872 if (retval != ERROR_OK) {
3873 /* BOO !*/
3874 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3875 (unsigned int)addr,
3876 (int)width,
3877 (int)count);
3878 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3879 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3880 e = JIM_ERR;
3881 break;
3885 free(buffer);
3887 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3889 return e;
3892 /* FIX? should we propagate errors here rather than printing them
3893 * and continuing?
3895 void target_handle_event(struct target *target, enum target_event e)
3897 struct target_event_action *teap;
3899 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3900 if (teap->event == e) {
3901 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3902 target->target_number,
3903 target_name(target),
3904 target_type_name(target),
3906 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3907 Jim_GetString(teap->body, NULL));
3908 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
3909 Jim_MakeErrorMessage(teap->interp);
3910 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
3917 * Returns true only if the target has a handler for the specified event.
3919 bool target_has_event_action(struct target *target, enum target_event event)
3921 struct target_event_action *teap;
3923 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3924 if (teap->event == event)
3925 return true;
3927 return false;
3930 enum target_cfg_param {
3931 TCFG_TYPE,
3932 TCFG_EVENT,
3933 TCFG_WORK_AREA_VIRT,
3934 TCFG_WORK_AREA_PHYS,
3935 TCFG_WORK_AREA_SIZE,
3936 TCFG_WORK_AREA_BACKUP,
3937 TCFG_ENDIAN,
3938 TCFG_VARIANT,
3939 TCFG_COREID,
3940 TCFG_CHAIN_POSITION,
3941 TCFG_DBGBASE,
3942 TCFG_RTOS,
3945 static Jim_Nvp nvp_config_opts[] = {
3946 { .name = "-type", .value = TCFG_TYPE },
3947 { .name = "-event", .value = TCFG_EVENT },
3948 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3949 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3950 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3951 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3952 { .name = "-endian" , .value = TCFG_ENDIAN },
3953 { .name = "-variant", .value = TCFG_VARIANT },
3954 { .name = "-coreid", .value = TCFG_COREID },
3955 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3956 { .name = "-dbgbase", .value = TCFG_DBGBASE },
3957 { .name = "-rtos", .value = TCFG_RTOS },
3958 { .name = NULL, .value = -1 }
3961 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3963 Jim_Nvp *n;
3964 Jim_Obj *o;
3965 jim_wide w;
3966 char *cp;
3967 int e;
3969 /* parse config or cget options ... */
3970 while (goi->argc > 0) {
3971 Jim_SetEmptyResult(goi->interp);
3972 /* Jim_GetOpt_Debug(goi); */
3974 if (target->type->target_jim_configure) {
3975 /* target defines a configure function */
3976 /* target gets first dibs on parameters */
3977 e = (*(target->type->target_jim_configure))(target, goi);
3978 if (e == JIM_OK) {
3979 /* more? */
3980 continue;
3982 if (e == JIM_ERR) {
3983 /* An error */
3984 return e;
3986 /* otherwise we 'continue' below */
3988 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3989 if (e != JIM_OK) {
3990 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3991 return e;
3993 switch (n->value) {
3994 case TCFG_TYPE:
3995 /* not setable */
3996 if (goi->isconfigure) {
3997 Jim_SetResultFormatted(goi->interp,
3998 "not settable: %s", n->name);
3999 return JIM_ERR;
4000 } else {
4001 no_params:
4002 if (goi->argc != 0) {
4003 Jim_WrongNumArgs(goi->interp,
4004 goi->argc, goi->argv,
4005 "NO PARAMS");
4006 return JIM_ERR;
4009 Jim_SetResultString(goi->interp,
4010 target_type_name(target), -1);
4011 /* loop for more */
4012 break;
4013 case TCFG_EVENT:
4014 if (goi->argc == 0) {
4015 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4016 return JIM_ERR;
4019 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4020 if (e != JIM_OK) {
4021 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4022 return e;
4025 if (goi->isconfigure) {
4026 if (goi->argc != 1) {
4027 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4028 return JIM_ERR;
4030 } else {
4031 if (goi->argc != 0) {
4032 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4033 return JIM_ERR;
4038 struct target_event_action *teap;
4040 teap = target->event_action;
4041 /* replace existing? */
4042 while (teap) {
4043 if (teap->event == (enum target_event)n->value)
4044 break;
4045 teap = teap->next;
4048 if (goi->isconfigure) {
4049 bool replace = true;
4050 if (teap == NULL) {
4051 /* create new */
4052 teap = calloc(1, sizeof(*teap));
4053 replace = false;
4055 teap->event = n->value;
4056 teap->interp = goi->interp;
4057 Jim_GetOpt_Obj(goi, &o);
4058 if (teap->body)
4059 Jim_DecrRefCount(teap->interp, teap->body);
4060 teap->body = Jim_DuplicateObj(goi->interp, o);
4062 * FIXME:
4063 * Tcl/TK - "tk events" have a nice feature.
4064 * See the "BIND" command.
4065 * We should support that here.
4066 * You can specify %X and %Y in the event code.
4067 * The idea is: %T - target name.
4068 * The idea is: %N - target number
4069 * The idea is: %E - event name.
4071 Jim_IncrRefCount(teap->body);
4073 if (!replace) {
4074 /* add to head of event list */
4075 teap->next = target->event_action;
4076 target->event_action = teap;
4078 Jim_SetEmptyResult(goi->interp);
4079 } else {
4080 /* get */
4081 if (teap == NULL)
4082 Jim_SetEmptyResult(goi->interp);
4083 else
4084 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4087 /* loop for more */
4088 break;
4090 case TCFG_WORK_AREA_VIRT:
4091 if (goi->isconfigure) {
4092 target_free_all_working_areas(target);
4093 e = Jim_GetOpt_Wide(goi, &w);
4094 if (e != JIM_OK)
4095 return e;
4096 target->working_area_virt = w;
4097 target->working_area_virt_spec = true;
4098 } else {
4099 if (goi->argc != 0)
4100 goto no_params;
4102 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4103 /* loop for more */
4104 break;
4106 case TCFG_WORK_AREA_PHYS:
4107 if (goi->isconfigure) {
4108 target_free_all_working_areas(target);
4109 e = Jim_GetOpt_Wide(goi, &w);
4110 if (e != JIM_OK)
4111 return e;
4112 target->working_area_phys = w;
4113 target->working_area_phys_spec = true;
4114 } else {
4115 if (goi->argc != 0)
4116 goto no_params;
4118 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4119 /* loop for more */
4120 break;
4122 case TCFG_WORK_AREA_SIZE:
4123 if (goi->isconfigure) {
4124 target_free_all_working_areas(target);
4125 e = Jim_GetOpt_Wide(goi, &w);
4126 if (e != JIM_OK)
4127 return e;
4128 target->working_area_size = w;
4129 } else {
4130 if (goi->argc != 0)
4131 goto no_params;
4133 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4134 /* loop for more */
4135 break;
4137 case TCFG_WORK_AREA_BACKUP:
4138 if (goi->isconfigure) {
4139 target_free_all_working_areas(target);
4140 e = Jim_GetOpt_Wide(goi, &w);
4141 if (e != JIM_OK)
4142 return e;
4143 /* make this exactly 1 or 0 */
4144 target->backup_working_area = (!!w);
4145 } else {
4146 if (goi->argc != 0)
4147 goto no_params;
4149 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4150 /* loop for more e*/
4151 break;
4154 case TCFG_ENDIAN:
4155 if (goi->isconfigure) {
4156 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4157 if (e != JIM_OK) {
4158 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4159 return e;
4161 target->endianness = n->value;
4162 } else {
4163 if (goi->argc != 0)
4164 goto no_params;
4166 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4167 if (n->name == NULL) {
4168 target->endianness = TARGET_LITTLE_ENDIAN;
4169 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4171 Jim_SetResultString(goi->interp, n->name, -1);
4172 /* loop for more */
4173 break;
4175 case TCFG_VARIANT:
4176 if (goi->isconfigure) {
4177 if (goi->argc < 1) {
4178 Jim_SetResultFormatted(goi->interp,
4179 "%s ?STRING?",
4180 n->name);
4181 return JIM_ERR;
4183 if (target->variant)
4184 free((void *)(target->variant));
4185 e = Jim_GetOpt_String(goi, &cp, NULL);
4186 if (e != JIM_OK)
4187 return e;
4188 target->variant = strdup(cp);
4189 } else {
4190 if (goi->argc != 0)
4191 goto no_params;
4193 Jim_SetResultString(goi->interp, target->variant, -1);
4194 /* loop for more */
4195 break;
4197 case TCFG_COREID:
4198 if (goi->isconfigure) {
4199 e = Jim_GetOpt_Wide(goi, &w);
4200 if (e != JIM_OK)
4201 return e;
4202 target->coreid = (int32_t)w;
4203 } else {
4204 if (goi->argc != 0)
4205 goto no_params;
4207 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4208 /* loop for more */
4209 break;
4211 case TCFG_CHAIN_POSITION:
4212 if (goi->isconfigure) {
4213 Jim_Obj *o_t;
4214 struct jtag_tap *tap;
4215 target_free_all_working_areas(target);
4216 e = Jim_GetOpt_Obj(goi, &o_t);
4217 if (e != JIM_OK)
4218 return e;
4219 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4220 if (tap == NULL)
4221 return JIM_ERR;
4222 /* make this exactly 1 or 0 */
4223 target->tap = tap;
4224 } else {
4225 if (goi->argc != 0)
4226 goto no_params;
4228 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4229 /* loop for more e*/
4230 break;
4231 case TCFG_DBGBASE:
4232 if (goi->isconfigure) {
4233 e = Jim_GetOpt_Wide(goi, &w);
4234 if (e != JIM_OK)
4235 return e;
4236 target->dbgbase = (uint32_t)w;
4237 target->dbgbase_set = true;
4238 } else {
4239 if (goi->argc != 0)
4240 goto no_params;
4242 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4243 /* loop for more */
4244 break;
4246 case TCFG_RTOS:
4247 /* RTOS */
4249 int result = rtos_create(goi, target);
4250 if (result != JIM_OK)
4251 return result;
4253 /* loop for more */
4254 break;
4256 } /* while (goi->argc) */
4259 /* done - we return */
4260 return JIM_OK;
4263 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4265 Jim_GetOptInfo goi;
4267 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4268 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4269 int need_args = 1 + goi.isconfigure;
4270 if (goi.argc < need_args) {
4271 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4272 goi.isconfigure
4273 ? "missing: -option VALUE ..."
4274 : "missing: -option ...");
4275 return JIM_ERR;
4277 struct target *target = Jim_CmdPrivData(goi.interp);
4278 return target_configure(&goi, target);
4281 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4283 const char *cmd_name = Jim_GetString(argv[0], NULL);
4285 Jim_GetOptInfo goi;
4286 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4288 if (goi.argc < 2 || goi.argc > 4) {
4289 Jim_SetResultFormatted(goi.interp,
4290 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4291 return JIM_ERR;
4294 target_write_fn fn;
4295 fn = target_write_memory_fast;
4297 int e;
4298 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4299 /* consume it */
4300 struct Jim_Obj *obj;
4301 e = Jim_GetOpt_Obj(&goi, &obj);
4302 if (e != JIM_OK)
4303 return e;
4305 fn = target_write_phys_memory;
4308 jim_wide a;
4309 e = Jim_GetOpt_Wide(&goi, &a);
4310 if (e != JIM_OK)
4311 return e;
4313 jim_wide b;
4314 e = Jim_GetOpt_Wide(&goi, &b);
4315 if (e != JIM_OK)
4316 return e;
4318 jim_wide c = 1;
4319 if (goi.argc == 1) {
4320 e = Jim_GetOpt_Wide(&goi, &c);
4321 if (e != JIM_OK)
4322 return e;
4325 /* all args must be consumed */
4326 if (goi.argc != 0)
4327 return JIM_ERR;
4329 struct target *target = Jim_CmdPrivData(goi.interp);
4330 unsigned data_size;
4331 if (strcasecmp(cmd_name, "mww") == 0)
4332 data_size = 4;
4333 else if (strcasecmp(cmd_name, "mwh") == 0)
4334 data_size = 2;
4335 else if (strcasecmp(cmd_name, "mwb") == 0)
4336 data_size = 1;
4337 else {
4338 LOG_ERROR("command '%s' unknown: ", cmd_name);
4339 return JIM_ERR;
4342 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4346 * @brief Reads an array of words/halfwords/bytes from target memory starting at specified address.
4348 * Usage: mdw [phys] <address> [<count>] - for 32 bit reads
4349 * mdh [phys] <address> [<count>] - for 16 bit reads
4350 * mdb [phys] <address> [<count>] - for 8 bit reads
4352 * Count defaults to 1.
4354 * Calls target_read_memory or target_read_phys_memory depending on
4355 * the presence of the "phys" argument
4356 * Reads the target memory in blocks of max. 32 bytes, and returns an array of ints formatted
4357 * to int representation in base16.
4358 * Also outputs read data in a human readable form using command_print
4360 * @param phys if present target_read_phys_memory will be used instead of target_read_memory
4361 * @param address address where to start the read. May be specified in decimal or hex using the standard "0x" prefix
4362 * @param count optional count parameter to read an array of values. If not specified, defaults to 1.
4363 * @returns: JIM_ERR on error or JIM_OK on success and sets the result string to an array of ascii formatted numbers
4364 * on success, with [<count>] number of elements.
4366 * In case of little endian target:
4367 * Example1: "mdw 0x00000000" returns "10123456"
4368 * Exmaple2: "mdh 0x00000000 1" returns "3456"
4369 * Example3: "mdb 0x00000000" returns "56"
4370 * Example4: "mdh 0x00000000 2" returns "3456 1012"
4371 * Example5: "mdb 0x00000000 3" returns "56 34 12"
4373 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4375 const char *cmd_name = Jim_GetString(argv[0], NULL);
4377 Jim_GetOptInfo goi;
4378 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4380 if ((goi.argc < 1) || (goi.argc > 3)) {
4381 Jim_SetResultFormatted(goi.interp,
4382 "usage: %s [phys] <address> [<count>]", cmd_name);
4383 return JIM_ERR;
4386 int (*fn)(struct target *target,
4387 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4388 fn = target_read_memory;
4390 int e;
4391 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4392 /* consume it */
4393 struct Jim_Obj *obj;
4394 e = Jim_GetOpt_Obj(&goi, &obj);
4395 if (e != JIM_OK)
4396 return e;
4398 fn = target_read_phys_memory;
4401 /* Read address parameter */
4402 jim_wide addr;
4403 e = Jim_GetOpt_Wide(&goi, &addr);
4404 if (e != JIM_OK)
4405 return JIM_ERR;
4407 /* If next parameter exists, read it out as the count parameter, if not, set it to 1 (default) */
4408 jim_wide count;
4409 if (goi.argc == 1) {
4410 e = Jim_GetOpt_Wide(&goi, &count);
4411 if (e != JIM_OK)
4412 return JIM_ERR;
4413 } else
4414 count = 1;
4416 /* all args must be consumed */
4417 if (goi.argc != 0)
4418 return JIM_ERR;
4420 jim_wide dwidth = 1; /* shut up gcc */
4421 if (strcasecmp(cmd_name, "mdw") == 0)
4422 dwidth = 4;
4423 else if (strcasecmp(cmd_name, "mdh") == 0)
4424 dwidth = 2;
4425 else if (strcasecmp(cmd_name, "mdb") == 0)
4426 dwidth = 1;
4427 else {
4428 LOG_ERROR("command '%s' unknown: ", cmd_name);
4429 return JIM_ERR;
4432 /* convert count to "bytes" */
4433 int bytes = count * dwidth;
4435 struct target *target = Jim_CmdPrivData(goi.interp);
4436 uint8_t target_buf[32];
4437 jim_wide x, y, z;
4438 while (bytes > 0) {
4439 y = (bytes < 16) ? bytes : 16; /* y = min(bytes, 16); */
4441 /* Try to read out next block */
4442 e = fn(target, addr, dwidth, y / dwidth, target_buf);
4444 if (e != ERROR_OK) {
4445 Jim_SetResultFormatted(interp, "error reading target @ 0x%08lx", (long)addr);
4446 return JIM_ERR;
4449 command_print_sameline(NULL, "0x%08x ", (int)(addr));
4450 switch (dwidth) {
4451 case 4:
4452 for (x = 0; x < 16 && x < y; x += 4) {
4453 z = target_buffer_get_u32(target, &(target_buf[x]));
4454 command_print_sameline(NULL, "%08x ", (int)(z));
4456 for (; (x < 16) ; x += 4)
4457 command_print_sameline(NULL, " ");
4458 break;
4459 case 2:
4460 for (x = 0; x < 16 && x < y; x += 2) {
4461 z = target_buffer_get_u16(target, &(target_buf[x]));
4462 command_print_sameline(NULL, "%04x ", (int)(z));
4464 for (; (x < 16) ; x += 2)
4465 command_print_sameline(NULL, " ");
4466 break;
4467 case 1:
4468 default:
4469 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4470 z = target_buffer_get_u8(target, &(target_buf[x]));
4471 command_print_sameline(NULL, "%02x ", (int)(z));
4473 for (; (x < 16) ; x += 1)
4474 command_print_sameline(NULL, " ");
4475 break;
4477 /* ascii-ify the bytes */
4478 for (x = 0 ; x < y ; x++) {
4479 if ((target_buf[x] >= 0x20) &&
4480 (target_buf[x] <= 0x7e)) {
4481 /* good */
4482 } else {
4483 /* smack it */
4484 target_buf[x] = '.';
4487 /* space pad */
4488 while (x < 16) {
4489 target_buf[x] = ' ';
4490 x++;
4492 /* terminate */
4493 target_buf[16] = 0;
4494 /* print - with a newline */
4495 command_print_sameline(NULL, "%s\n", target_buf);
4496 /* NEXT... */
4497 bytes -= 16;
4498 addr += 16;
4500 return JIM_OK;
4503 static int jim_target_mem2array(Jim_Interp *interp,
4504 int argc, Jim_Obj *const *argv)
4506 struct target *target = Jim_CmdPrivData(interp);
4507 return target_mem2array(interp, target, argc - 1, argv + 1);
4510 static int jim_target_array2mem(Jim_Interp *interp,
4511 int argc, Jim_Obj *const *argv)
4513 struct target *target = Jim_CmdPrivData(interp);
4514 return target_array2mem(interp, target, argc - 1, argv + 1);
4517 static int jim_target_tap_disabled(Jim_Interp *interp)
4519 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4520 return JIM_ERR;
4523 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4525 if (argc != 1) {
4526 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4527 return JIM_ERR;
4529 struct target *target = Jim_CmdPrivData(interp);
4530 if (!target->tap->enabled)
4531 return jim_target_tap_disabled(interp);
4533 int e = target->type->examine(target);
4534 if (e != ERROR_OK)
4535 return JIM_ERR;
4536 return JIM_OK;
4539 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4541 if (argc != 1) {
4542 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4543 return JIM_ERR;
4545 struct target *target = Jim_CmdPrivData(interp);
4547 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4548 return JIM_ERR;
4550 return JIM_OK;
4553 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4555 if (argc != 1) {
4556 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4557 return JIM_ERR;
4559 struct target *target = Jim_CmdPrivData(interp);
4560 if (!target->tap->enabled)
4561 return jim_target_tap_disabled(interp);
4563 int e;
4564 if (!(target_was_examined(target)))
4565 e = ERROR_TARGET_NOT_EXAMINED;
4566 else
4567 e = target->type->poll(target);
4568 if (e != ERROR_OK)
4569 return JIM_ERR;
4570 return JIM_OK;
4573 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4575 Jim_GetOptInfo goi;
4576 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4578 if (goi.argc != 2) {
4579 Jim_WrongNumArgs(interp, 0, argv,
4580 "([tT]|[fF]|assert|deassert) BOOL");
4581 return JIM_ERR;
4584 Jim_Nvp *n;
4585 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4586 if (e != JIM_OK) {
4587 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4588 return e;
4590 /* the halt or not param */
4591 jim_wide a;
4592 e = Jim_GetOpt_Wide(&goi, &a);
4593 if (e != JIM_OK)
4594 return e;
4596 struct target *target = Jim_CmdPrivData(goi.interp);
4597 if (!target->tap->enabled)
4598 return jim_target_tap_disabled(interp);
4599 if (!(target_was_examined(target))) {
4600 LOG_ERROR("Target not examined yet");
4601 return ERROR_TARGET_NOT_EXAMINED;
4603 if (!target->type->assert_reset || !target->type->deassert_reset) {
4604 Jim_SetResultFormatted(interp,
4605 "No target-specific reset for %s",
4606 target_name(target));
4607 return JIM_ERR;
4609 /* determine if we should halt or not. */
4610 target->reset_halt = !!a;
4611 /* When this happens - all workareas are invalid. */
4612 target_free_all_working_areas_restore(target, 0);
4614 /* do the assert */
4615 if (n->value == NVP_ASSERT)
4616 e = target->type->assert_reset(target);
4617 else
4618 e = target->type->deassert_reset(target);
4619 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4622 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4624 if (argc != 1) {
4625 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4626 return JIM_ERR;
4628 struct target *target = Jim_CmdPrivData(interp);
4629 if (!target->tap->enabled)
4630 return jim_target_tap_disabled(interp);
4631 int e = target->type->halt(target);
4632 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4635 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4637 Jim_GetOptInfo goi;
4638 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4640 /* params: <name> statename timeoutmsecs */
4641 if (goi.argc != 2) {
4642 const char *cmd_name = Jim_GetString(argv[0], NULL);
4643 Jim_SetResultFormatted(goi.interp,
4644 "%s <state_name> <timeout_in_msec>", cmd_name);
4645 return JIM_ERR;
4648 Jim_Nvp *n;
4649 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4650 if (e != JIM_OK) {
4651 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
4652 return e;
4654 jim_wide a;
4655 e = Jim_GetOpt_Wide(&goi, &a);
4656 if (e != JIM_OK)
4657 return e;
4658 struct target *target = Jim_CmdPrivData(interp);
4659 if (!target->tap->enabled)
4660 return jim_target_tap_disabled(interp);
4662 e = target_wait_state(target, n->value, a);
4663 if (e != ERROR_OK) {
4664 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4665 Jim_SetResultFormatted(goi.interp,
4666 "target: %s wait %s fails (%#s) %s",
4667 target_name(target), n->name,
4668 eObj, target_strerror_safe(e));
4669 Jim_FreeNewObj(interp, eObj);
4670 return JIM_ERR;
4672 return JIM_OK;
4674 /* List for human, Events defined for this target.
4675 * scripts/programs should use 'name cget -event NAME'
4677 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4679 struct command_context *cmd_ctx = current_command_context(interp);
4680 assert(cmd_ctx != NULL);
4682 struct target *target = Jim_CmdPrivData(interp);
4683 struct target_event_action *teap = target->event_action;
4684 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4685 target->target_number,
4686 target_name(target));
4687 command_print(cmd_ctx, "%-25s | Body", "Event");
4688 command_print(cmd_ctx, "------------------------- | "
4689 "----------------------------------------");
4690 while (teap) {
4691 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4692 command_print(cmd_ctx, "%-25s | %s",
4693 opt->name, Jim_GetString(teap->body, NULL));
4694 teap = teap->next;
4696 command_print(cmd_ctx, "***END***");
4697 return JIM_OK;
4699 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4701 if (argc != 1) {
4702 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4703 return JIM_ERR;
4705 struct target *target = Jim_CmdPrivData(interp);
4706 Jim_SetResultString(interp, target_state_name(target), -1);
4707 return JIM_OK;
4709 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4711 Jim_GetOptInfo goi;
4712 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4713 if (goi.argc != 1) {
4714 const char *cmd_name = Jim_GetString(argv[0], NULL);
4715 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4716 return JIM_ERR;
4718 Jim_Nvp *n;
4719 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4720 if (e != JIM_OK) {
4721 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4722 return e;
4724 struct target *target = Jim_CmdPrivData(interp);
4725 target_handle_event(target, n->value);
4726 return JIM_OK;
4729 static const struct command_registration target_instance_command_handlers[] = {
4731 .name = "configure",
4732 .mode = COMMAND_CONFIG,
4733 .jim_handler = jim_target_configure,
4734 .help = "configure a new target for use",
4735 .usage = "[target_attribute ...]",
4738 .name = "cget",
4739 .mode = COMMAND_ANY,
4740 .jim_handler = jim_target_configure,
4741 .help = "returns the specified target attribute",
4742 .usage = "target_attribute",
4745 .name = "mww",
4746 .mode = COMMAND_EXEC,
4747 .jim_handler = jim_target_mw,
4748 .help = "Write 32-bit word(s) to target memory",
4749 .usage = "address data [count]",
4752 .name = "mwh",
4753 .mode = COMMAND_EXEC,
4754 .jim_handler = jim_target_mw,
4755 .help = "Write 16-bit half-word(s) to target memory",
4756 .usage = "address data [count]",
4759 .name = "mwb",
4760 .mode = COMMAND_EXEC,
4761 .jim_handler = jim_target_mw,
4762 .help = "Write byte(s) to target memory",
4763 .usage = "address data [count]",
4766 .name = "mdw",
4767 .mode = COMMAND_EXEC,
4768 .jim_handler = jim_target_md,
4769 .help = "Display target memory as 32-bit words",
4770 .usage = "address [count]",
4773 .name = "mdh",
4774 .mode = COMMAND_EXEC,
4775 .jim_handler = jim_target_md,
4776 .help = "Display target memory as 16-bit half-words",
4777 .usage = "address [count]",
4780 .name = "mdb",
4781 .mode = COMMAND_EXEC,
4782 .jim_handler = jim_target_md,
4783 .help = "Display target memory as 8-bit bytes",
4784 .usage = "address [count]",
4787 .name = "array2mem",
4788 .mode = COMMAND_EXEC,
4789 .jim_handler = jim_target_array2mem,
4790 .help = "Writes Tcl array of 8/16/32 bit numbers "
4791 "to target memory",
4792 .usage = "arrayname bitwidth address count",
4795 .name = "mem2array",
4796 .mode = COMMAND_EXEC,
4797 .jim_handler = jim_target_mem2array,
4798 .help = "Loads Tcl array of 8/16/32 bit numbers "
4799 "from target memory",
4800 .usage = "arrayname bitwidth address count",
4803 .name = "eventlist",
4804 .mode = COMMAND_EXEC,
4805 .jim_handler = jim_target_event_list,
4806 .help = "displays a table of events defined for this target",
4809 .name = "curstate",
4810 .mode = COMMAND_EXEC,
4811 .jim_handler = jim_target_current_state,
4812 .help = "displays the current state of this target",
4815 .name = "arp_examine",
4816 .mode = COMMAND_EXEC,
4817 .jim_handler = jim_target_examine,
4818 .help = "used internally for reset processing",
4821 .name = "arp_halt_gdb",
4822 .mode = COMMAND_EXEC,
4823 .jim_handler = jim_target_halt_gdb,
4824 .help = "used internally for reset processing to halt GDB",
4827 .name = "arp_poll",
4828 .mode = COMMAND_EXEC,
4829 .jim_handler = jim_target_poll,
4830 .help = "used internally for reset processing",
4833 .name = "arp_reset",
4834 .mode = COMMAND_EXEC,
4835 .jim_handler = jim_target_reset,
4836 .help = "used internally for reset processing",
4839 .name = "arp_halt",
4840 .mode = COMMAND_EXEC,
4841 .jim_handler = jim_target_halt,
4842 .help = "used internally for reset processing",
4845 .name = "arp_waitstate",
4846 .mode = COMMAND_EXEC,
4847 .jim_handler = jim_target_wait_state,
4848 .help = "used internally for reset processing",
4851 .name = "invoke-event",
4852 .mode = COMMAND_EXEC,
4853 .jim_handler = jim_target_invoke_event,
4854 .help = "invoke handler for specified event",
4855 .usage = "event_name",
4857 COMMAND_REGISTRATION_DONE
4860 static int target_create(Jim_GetOptInfo *goi)
4862 Jim_Obj *new_cmd;
4863 Jim_Cmd *cmd;
4864 const char *cp;
4865 char *cp2;
4866 int e;
4867 int x;
4868 struct target *target;
4869 struct command_context *cmd_ctx;
4871 cmd_ctx = current_command_context(goi->interp);
4872 assert(cmd_ctx != NULL);
4874 if (goi->argc < 3) {
4875 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4876 return JIM_ERR;
4879 /* COMMAND */
4880 Jim_GetOpt_Obj(goi, &new_cmd);
4881 /* does this command exist? */
4882 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4883 if (cmd) {
4884 cp = Jim_GetString(new_cmd, NULL);
4885 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
4886 return JIM_ERR;
4889 /* TYPE */
4890 e = Jim_GetOpt_String(goi, &cp2, NULL);
4891 if (e != JIM_OK)
4892 return e;
4893 cp = cp2;
4894 /* now does target type exist */
4895 for (x = 0 ; target_types[x] ; x++) {
4896 if (0 == strcmp(cp, target_types[x]->name)) {
4897 /* found */
4898 break;
4901 /* check for deprecated name */
4902 if (target_types[x]->deprecated_name) {
4903 if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
4904 /* found */
4905 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
4906 break;
4910 if (target_types[x] == NULL) {
4911 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
4912 for (x = 0 ; target_types[x] ; x++) {
4913 if (target_types[x + 1]) {
4914 Jim_AppendStrings(goi->interp,
4915 Jim_GetResult(goi->interp),
4916 target_types[x]->name,
4917 ", ", NULL);
4918 } else {
4919 Jim_AppendStrings(goi->interp,
4920 Jim_GetResult(goi->interp),
4921 " or ",
4922 target_types[x]->name, NULL);
4925 return JIM_ERR;
4928 /* Create it */
4929 target = calloc(1, sizeof(struct target));
4930 /* set target number */
4931 target->target_number = new_target_number();
4933 /* allocate memory for each unique target type */
4934 target->type = (struct target_type *)calloc(1, sizeof(struct target_type));
4936 memcpy(target->type, target_types[x], sizeof(struct target_type));
4938 /* will be set by "-endian" */
4939 target->endianness = TARGET_ENDIAN_UNKNOWN;
4941 /* default to first core, override with -coreid */
4942 target->coreid = 0;
4944 target->working_area = 0x0;
4945 target->working_area_size = 0x0;
4946 target->working_areas = NULL;
4947 target->backup_working_area = 0;
4949 target->state = TARGET_UNKNOWN;
4950 target->debug_reason = DBG_REASON_UNDEFINED;
4951 target->reg_cache = NULL;
4952 target->breakpoints = NULL;
4953 target->watchpoints = NULL;
4954 target->next = NULL;
4955 target->arch_info = NULL;
4957 target->display = 1;
4959 target->halt_issued = false;
4961 /* initialize trace information */
4962 target->trace_info = malloc(sizeof(struct trace));
4963 target->trace_info->num_trace_points = 0;
4964 target->trace_info->trace_points_size = 0;
4965 target->trace_info->trace_points = NULL;
4966 target->trace_info->trace_history_size = 0;
4967 target->trace_info->trace_history = NULL;
4968 target->trace_info->trace_history_pos = 0;
4969 target->trace_info->trace_history_overflowed = 0;
4971 target->dbgmsg = NULL;
4972 target->dbg_msg_enabled = 0;
4974 target->endianness = TARGET_ENDIAN_UNKNOWN;
4976 target->rtos = NULL;
4977 target->rtos_auto_detect = false;
4979 /* Do the rest as "configure" options */
4980 goi->isconfigure = 1;
4981 e = target_configure(goi, target);
4983 if (target->tap == NULL) {
4984 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4985 e = JIM_ERR;
4988 if (e != JIM_OK) {
4989 free(target->type);
4990 free(target);
4991 return e;
4994 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4995 /* default endian to little if not specified */
4996 target->endianness = TARGET_LITTLE_ENDIAN;
4999 /* incase variant is not set */
5000 if (!target->variant)
5001 target->variant = strdup("");
5003 cp = Jim_GetString(new_cmd, NULL);
5004 target->cmd_name = strdup(cp);
5006 /* create the target specific commands */
5007 if (target->type->commands) {
5008 e = register_commands(cmd_ctx, NULL, target->type->commands);
5009 if (ERROR_OK != e)
5010 LOG_ERROR("unable to register '%s' commands", cp);
5012 if (target->type->target_create)
5013 (*(target->type->target_create))(target, goi->interp);
5015 /* append to end of list */
5017 struct target **tpp;
5018 tpp = &(all_targets);
5019 while (*tpp)
5020 tpp = &((*tpp)->next);
5021 *tpp = target;
5024 /* now - create the new target name command */
5025 const const struct command_registration target_subcommands[] = {
5027 .chain = target_instance_command_handlers,
5030 .chain = target->type->commands,
5032 COMMAND_REGISTRATION_DONE
5034 const const struct command_registration target_commands[] = {
5036 .name = cp,
5037 .mode = COMMAND_ANY,
5038 .help = "target command group",
5039 .usage = "",
5040 .chain = target_subcommands,
5042 COMMAND_REGISTRATION_DONE
5044 e = register_commands(cmd_ctx, NULL, target_commands);
5045 if (ERROR_OK != e)
5046 return JIM_ERR;
5048 struct command *c = command_find_in_context(cmd_ctx, cp);
5049 assert(c);
5050 command_set_handler_data(c, target);
5052 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5055 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5057 if (argc != 1) {
5058 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5059 return JIM_ERR;
5061 struct command_context *cmd_ctx = current_command_context(interp);
5062 assert(cmd_ctx != NULL);
5064 Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5065 return JIM_OK;
5068 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5070 if (argc != 1) {
5071 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5072 return JIM_ERR;
5074 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5075 for (unsigned x = 0; NULL != target_types[x]; x++) {
5076 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5077 Jim_NewStringObj(interp, target_types[x]->name, -1));
5079 return JIM_OK;
5082 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5084 if (argc != 1) {
5085 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5086 return JIM_ERR;
5088 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5089 struct target *target = all_targets;
5090 while (target) {
5091 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5092 Jim_NewStringObj(interp, target_name(target), -1));
5093 target = target->next;
5095 return JIM_OK;
5098 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5100 int i;
5101 const char *targetname;
5102 int retval, len;
5103 struct target *target = (struct target *) NULL;
5104 struct target_list *head, *curr, *new;
5105 curr = (struct target_list *) NULL;
5106 head = (struct target_list *) NULL;
5108 retval = 0;
5109 LOG_DEBUG("%d", argc);
5110 /* argv[1] = target to associate in smp
5111 * argv[2] = target to assoicate in smp
5112 * argv[3] ...
5115 for (i = 1; i < argc; i++) {
5117 targetname = Jim_GetString(argv[i], &len);
5118 target = get_target(targetname);
5119 LOG_DEBUG("%s ", targetname);
5120 if (target) {
5121 new = malloc(sizeof(struct target_list));
5122 new->target = target;
5123 new->next = (struct target_list *)NULL;
5124 if (head == (struct target_list *)NULL) {
5125 head = new;
5126 curr = head;
5127 } else {
5128 curr->next = new;
5129 curr = new;
5133 /* now parse the list of cpu and put the target in smp mode*/
5134 curr = head;
5136 while (curr != (struct target_list *)NULL) {
5137 target = curr->target;
5138 target->smp = 1;
5139 target->head = head;
5140 curr = curr->next;
5143 if (target && target->rtos)
5144 retval = rtos_smp_init(head->target);
5146 return retval;
5150 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5152 Jim_GetOptInfo goi;
5153 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5154 if (goi.argc < 3) {
5155 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5156 "<name> <target_type> [<target_options> ...]");
5157 return JIM_ERR;
5159 return target_create(&goi);
5162 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5164 Jim_GetOptInfo goi;
5165 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5167 /* It's OK to remove this mechanism sometime after August 2010 or so */
5168 LOG_WARNING("don't use numbers as target identifiers; use names");
5169 if (goi.argc != 1) {
5170 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
5171 return JIM_ERR;
5173 jim_wide w;
5174 int e = Jim_GetOpt_Wide(&goi, &w);
5175 if (e != JIM_OK)
5176 return JIM_ERR;
5178 struct target *target;
5179 for (target = all_targets; NULL != target; target = target->next) {
5180 if (target->target_number != w)
5181 continue;
5183 Jim_SetResultString(goi.interp, target_name(target), -1);
5184 return JIM_OK;
5187 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
5188 Jim_SetResultFormatted(goi.interp,
5189 "Target: number %#s does not exist", wObj);
5190 Jim_FreeNewObj(interp, wObj);
5192 return JIM_ERR;
5195 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5197 if (argc != 1) {
5198 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
5199 return JIM_ERR;
5201 unsigned count = 0;
5202 struct target *target = all_targets;
5203 while (NULL != target) {
5204 target = target->next;
5205 count++;
5207 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
5208 return JIM_OK;
5211 static const struct command_registration target_subcommand_handlers[] = {
5213 .name = "init",
5214 .mode = COMMAND_CONFIG,
5215 .handler = handle_target_init_command,
5216 .help = "initialize targets",
5219 .name = "create",
5220 /* REVISIT this should be COMMAND_CONFIG ... */
5221 .mode = COMMAND_ANY,
5222 .jim_handler = jim_target_create,
5223 .usage = "name type '-chain-position' name [options ...]",
5224 .help = "Creates and selects a new target",
5227 .name = "current",
5228 .mode = COMMAND_ANY,
5229 .jim_handler = jim_target_current,
5230 .help = "Returns the currently selected target",
5233 .name = "types",
5234 .mode = COMMAND_ANY,
5235 .jim_handler = jim_target_types,
5236 .help = "Returns the available target types as "
5237 "a list of strings",
5240 .name = "names",
5241 .mode = COMMAND_ANY,
5242 .jim_handler = jim_target_names,
5243 .help = "Returns the names of all targets as a list of strings",
5246 .name = "number",
5247 .mode = COMMAND_ANY,
5248 .jim_handler = jim_target_number,
5249 .usage = "number",
5250 .help = "Returns the name of the numbered target "
5251 "(DEPRECATED)",
5254 .name = "count",
5255 .mode = COMMAND_ANY,
5256 .jim_handler = jim_target_count,
5257 .help = "Returns the number of targets as an integer "
5258 "(DEPRECATED)",
5261 .name = "smp",
5262 .mode = COMMAND_ANY,
5263 .jim_handler = jim_target_smp,
5264 .usage = "targetname1 targetname2 ...",
5265 .help = "gather several target in a smp list"
5268 COMMAND_REGISTRATION_DONE
5271 struct FastLoad {
5272 uint32_t address;
5273 uint8_t *data;
5274 int length;
5278 static int fastload_num;
5279 static struct FastLoad *fastload;
5281 static void free_fastload(void)
5283 if (fastload != NULL) {
5284 int i;
5285 for (i = 0; i < fastload_num; i++) {
5286 if (fastload[i].data)
5287 free(fastload[i].data);
5289 free(fastload);
5290 fastload = NULL;
5294 COMMAND_HANDLER(handle_fast_load_image_command)
5296 uint8_t *buffer;
5297 size_t buf_cnt;
5298 uint32_t image_size;
5299 uint32_t min_address = 0;
5300 uint32_t max_address = 0xffffffff;
5301 int i;
5303 struct image image;
5305 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5306 &image, &min_address, &max_address);
5307 if (ERROR_OK != retval)
5308 return retval;
5310 struct duration bench;
5311 duration_start(&bench);
5313 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5314 if (retval != ERROR_OK)
5315 return retval;
5317 image_size = 0x0;
5318 retval = ERROR_OK;
5319 fastload_num = image.num_sections;
5320 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
5321 if (fastload == NULL) {
5322 command_print(CMD_CTX, "out of memory");
5323 image_close(&image);
5324 return ERROR_FAIL;
5326 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5327 for (i = 0; i < image.num_sections; i++) {
5328 buffer = malloc(image.sections[i].size);
5329 if (buffer == NULL) {
5330 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5331 (int)(image.sections[i].size));
5332 retval = ERROR_FAIL;
5333 break;
5336 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5337 if (retval != ERROR_OK) {
5338 free(buffer);
5339 break;
5342 uint32_t offset = 0;
5343 uint32_t length = buf_cnt;
5345 /* DANGER!!! beware of unsigned comparision here!!! */
5347 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5348 (image.sections[i].base_address < max_address)) {
5349 if (image.sections[i].base_address < min_address) {
5350 /* clip addresses below */
5351 offset += min_address-image.sections[i].base_address;
5352 length -= offset;
5355 if (image.sections[i].base_address + buf_cnt > max_address)
5356 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5358 fastload[i].address = image.sections[i].base_address + offset;
5359 fastload[i].data = malloc(length);
5360 if (fastload[i].data == NULL) {
5361 free(buffer);
5362 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5363 length);
5364 retval = ERROR_FAIL;
5365 break;
5367 memcpy(fastload[i].data, buffer + offset, length);
5368 fastload[i].length = length;
5370 image_size += length;
5371 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5372 (unsigned int)length,
5373 ((unsigned int)(image.sections[i].base_address + offset)));
5376 free(buffer);
5379 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5380 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5381 "in %fs (%0.3f KiB/s)", image_size,
5382 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5384 command_print(CMD_CTX,
5385 "WARNING: image has not been loaded to target!"
5386 "You can issue a 'fast_load' to finish loading.");
5389 image_close(&image);
5391 if (retval != ERROR_OK)
5392 free_fastload();
5394 return retval;
5397 COMMAND_HANDLER(handle_fast_load_command)
5399 if (CMD_ARGC > 0)
5400 return ERROR_COMMAND_SYNTAX_ERROR;
5401 if (fastload == NULL) {
5402 LOG_ERROR("No image in memory");
5403 return ERROR_FAIL;
5405 int i;
5406 int ms = timeval_ms();
5407 int size = 0;
5408 int retval = ERROR_OK;
5409 for (i = 0; i < fastload_num; i++) {
5410 struct target *target = get_current_target(CMD_CTX);
5411 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5412 (unsigned int)(fastload[i].address),
5413 (unsigned int)(fastload[i].length));
5414 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5415 if (retval != ERROR_OK)
5416 break;
5417 size += fastload[i].length;
5419 if (retval == ERROR_OK) {
5420 int after = timeval_ms();
5421 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5423 return retval;
5426 static const struct command_registration target_command_handlers[] = {
5428 .name = "targets",
5429 .handler = handle_targets_command,
5430 .mode = COMMAND_ANY,
5431 .help = "change current default target (one parameter) "
5432 "or prints table of all targets (no parameters)",
5433 .usage = "[target]",
5436 .name = "target",
5437 .mode = COMMAND_CONFIG,
5438 .help = "configure target",
5440 .chain = target_subcommand_handlers,
5442 COMMAND_REGISTRATION_DONE
5445 int target_register_commands(struct command_context *cmd_ctx)
5447 return register_commands(cmd_ctx, NULL, target_command_handlers);
5450 static bool target_reset_nag = true;
5452 bool get_target_reset_nag(void)
5454 return target_reset_nag;
5457 COMMAND_HANDLER(handle_target_reset_nag)
5459 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5460 &target_reset_nag, "Nag after each reset about options to improve "
5461 "performance");
5464 COMMAND_HANDLER(handle_ps_command)
5466 struct target *target = get_current_target(CMD_CTX);
5467 char *display;
5468 if (target->state != TARGET_HALTED) {
5469 LOG_INFO("target not halted !!");
5470 return ERROR_OK;
5473 if ((target->rtos) && (target->rtos->type)
5474 && (target->rtos->type->ps_command)) {
5475 display = target->rtos->type->ps_command(target);
5476 command_print(CMD_CTX, "%s", display);
5477 free(display);
5478 return ERROR_OK;
5479 } else {
5480 LOG_INFO("failed");
5481 return ERROR_TARGET_FAILURE;
5485 static const struct command_registration target_exec_command_handlers[] = {
5487 .name = "fast_load_image",
5488 .handler = handle_fast_load_image_command,
5489 .mode = COMMAND_ANY,
5490 .help = "Load image into server memory for later use by "
5491 "fast_load; primarily for profiling",
5492 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5493 "[min_address [max_length]]",
5496 .name = "fast_load",
5497 .handler = handle_fast_load_command,
5498 .mode = COMMAND_EXEC,
5499 .help = "loads active fast load image to current target "
5500 "- mainly for profiling purposes",
5501 .usage = "",
5504 .name = "profile",
5505 .handler = handle_profile_command,
5506 .mode = COMMAND_EXEC,
5507 .usage = "seconds filename",
5508 .help = "profiling samples the CPU PC",
5510 /** @todo don't register virt2phys() unless target supports it */
5512 .name = "virt2phys",
5513 .handler = handle_virt2phys_command,
5514 .mode = COMMAND_ANY,
5515 .help = "translate a virtual address into a physical address",
5516 .usage = "virtual_address",
5519 .name = "reg",
5520 .handler = handle_reg_command,
5521 .mode = COMMAND_EXEC,
5522 .help = "display or set a register; with no arguments, "
5523 "displays all registers and their values",
5524 .usage = "[(register_name|register_number) [value]]",
5527 .name = "poll",
5528 .handler = handle_poll_command,
5529 .mode = COMMAND_EXEC,
5530 .help = "poll target state; or reconfigure background polling",
5531 .usage = "['on'|'off']",
5534 .name = "wait_halt",
5535 .handler = handle_wait_halt_command,
5536 .mode = COMMAND_EXEC,
5537 .help = "wait up to the specified number of milliseconds "
5538 "(default 5) for a previously requested halt",
5539 .usage = "[milliseconds]",
5542 .name = "halt",
5543 .handler = handle_halt_command,
5544 .mode = COMMAND_EXEC,
5545 .help = "request target to halt, then wait up to the specified"
5546 "number of milliseconds (default 5) for it to complete",
5547 .usage = "[milliseconds]",
5550 .name = "resume",
5551 .handler = handle_resume_command,
5552 .mode = COMMAND_EXEC,
5553 .help = "resume target execution from current PC or address",
5554 .usage = "[address]",
5557 .name = "reset",
5558 .handler = handle_reset_command,
5559 .mode = COMMAND_EXEC,
5560 .usage = "[run|halt|init]",
5561 .help = "Reset all targets into the specified mode."
5562 "Default reset mode is run, if not given.",
5565 .name = "soft_reset_halt",
5566 .handler = handle_soft_reset_halt_command,
5567 .mode = COMMAND_EXEC,
5568 .usage = "",
5569 .help = "halt the target and do a soft reset",
5572 .name = "step",
5573 .handler = handle_step_command,
5574 .mode = COMMAND_EXEC,
5575 .help = "step one instruction from current PC or address",
5576 .usage = "[address]",
5579 .name = "mdw",
5580 .handler = handle_md_command,
5581 .mode = COMMAND_EXEC,
5582 .help = "display memory words",
5583 .usage = "['phys'] address [count]",
5586 .name = "mdh",
5587 .handler = handle_md_command,
5588 .mode = COMMAND_EXEC,
5589 .help = "display memory half-words",
5590 .usage = "['phys'] address [count]",
5593 .name = "mdb",
5594 .handler = handle_md_command,
5595 .mode = COMMAND_EXEC,
5596 .help = "display memory bytes",
5597 .usage = "['phys'] address [count]",
5600 .name = "mww",
5601 .handler = handle_mw_command,
5602 .mode = COMMAND_EXEC,
5603 .help = "write memory word",
5604 .usage = "['phys'] address value [count]",
5607 .name = "mwh",
5608 .handler = handle_mw_command,
5609 .mode = COMMAND_EXEC,
5610 .help = "write memory half-word",
5611 .usage = "['phys'] address value [count]",
5614 .name = "mwb",
5615 .handler = handle_mw_command,
5616 .mode = COMMAND_EXEC,
5617 .help = "write memory byte",
5618 .usage = "['phys'] address value [count]",
5621 .name = "bp",
5622 .handler = handle_bp_command,
5623 .mode = COMMAND_EXEC,
5624 .help = "list or set hardware or software breakpoint",
5625 .usage = "<address> [<asid>]<length> ['hw'|'hw_ctx']",
5628 .name = "rbp",
5629 .handler = handle_rbp_command,
5630 .mode = COMMAND_EXEC,
5631 .help = "remove breakpoint",
5632 .usage = "address",
5635 .name = "wp",
5636 .handler = handle_wp_command,
5637 .mode = COMMAND_EXEC,
5638 .help = "list (no params) or create watchpoints",
5639 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5642 .name = "rwp",
5643 .handler = handle_rwp_command,
5644 .mode = COMMAND_EXEC,
5645 .help = "remove watchpoint",
5646 .usage = "address",
5649 .name = "load_image",
5650 .handler = handle_load_image_command,
5651 .mode = COMMAND_EXEC,
5652 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5653 "[min_address] [max_length]",
5656 .name = "dump_image",
5657 .handler = handle_dump_image_command,
5658 .mode = COMMAND_EXEC,
5659 .usage = "filename address size",
5662 .name = "verify_image",
5663 .handler = handle_verify_image_command,
5664 .mode = COMMAND_EXEC,
5665 .usage = "filename [offset [type]]",
5668 .name = "test_image",
5669 .handler = handle_test_image_command,
5670 .mode = COMMAND_EXEC,
5671 .usage = "filename [offset [type]]",
5674 .name = "mem2array",
5675 .mode = COMMAND_EXEC,
5676 .jim_handler = jim_mem2array,
5677 .help = "read 8/16/32 bit memory and return as a TCL array "
5678 "for script processing",
5679 .usage = "arrayname bitwidth address count",
5682 .name = "array2mem",
5683 .mode = COMMAND_EXEC,
5684 .jim_handler = jim_array2mem,
5685 .help = "convert a TCL array to memory locations "
5686 "and write the 8/16/32 bit values",
5687 .usage = "arrayname bitwidth address count",
5690 .name = "reset_nag",
5691 .handler = handle_target_reset_nag,
5692 .mode = COMMAND_ANY,
5693 .help = "Nag after each reset about options that could have been "
5694 "enabled to improve performance. ",
5695 .usage = "['enable'|'disable']",
5698 .name = "ps",
5699 .handler = handle_ps_command,
5700 .mode = COMMAND_EXEC,
5701 .help = "list all tasks ",
5702 .usage = " ",
5705 COMMAND_REGISTRATION_DONE
5707 static int target_register_user_commands(struct command_context *cmd_ctx)
5709 int retval = ERROR_OK;
5710 retval = target_request_register_commands(cmd_ctx);
5711 if (retval != ERROR_OK)
5712 return retval;
5714 retval = trace_register_commands(cmd_ctx);
5715 if (retval != ERROR_OK)
5716 return retval;
5719 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);