partial support for 568013 and 568037, target integration.
[openocd.git] / src / target / target.c
blob03431560f57cd89724937794aa749a93ffef17a6
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 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
27 * *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
32 * *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the *
35 * Free Software Foundation, Inc., *
36 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
37 ***************************************************************************/
38 #ifdef HAVE_CONFIG_H
39 #include "config.h"
40 #endif
42 #include <helper/time_support.h>
43 #include <jtag/jtag.h>
44 #include <flash/nor/core.h>
46 #include "target.h"
47 #include "target_type.h"
48 #include "target_request.h"
49 #include "breakpoints.h"
50 #include "register.h"
51 #include "trace.h"
52 #include "image.h"
53 #include "rtos/rtos.h"
56 static int target_read_buffer_default(struct target *target, uint32_t address,
57 uint32_t size, uint8_t *buffer);
58 static int target_write_buffer_default(struct target *target, uint32_t address,
59 uint32_t size, const uint8_t *buffer);
60 static int target_array2mem(Jim_Interp *interp, struct target *target,
61 int argc, Jim_Obj *const *argv);
62 static int target_mem2array(Jim_Interp *interp, struct target *target,
63 int argc, Jim_Obj *const *argv);
64 static int target_register_user_commands(struct command_context *cmd_ctx);
66 /* targets */
67 extern struct target_type arm7tdmi_target;
68 extern struct target_type arm720t_target;
69 extern struct target_type arm9tdmi_target;
70 extern struct target_type arm920t_target;
71 extern struct target_type arm966e_target;
72 extern struct target_type arm946e_target;
73 extern struct target_type arm926ejs_target;
74 extern struct target_type fa526_target;
75 extern struct target_type feroceon_target;
76 extern struct target_type dragonite_target;
77 extern struct target_type xscale_target;
78 extern struct target_type cortexm3_target;
79 extern struct target_type cortexa8_target;
80 extern struct target_type arm11_target;
81 extern struct target_type mips_m4k_target;
82 extern struct target_type avr_target;
83 extern struct target_type dsp563xx_target;
84 extern struct target_type dsp5680xx_target;
85 extern struct target_type testee_target;
86 extern struct target_type avr32_ap7k_target;
88 static struct target_type *target_types[] =
90 &arm7tdmi_target,
91 &arm9tdmi_target,
92 &arm920t_target,
93 &arm720t_target,
94 &arm966e_target,
95 &arm946e_target,
96 &arm926ejs_target,
97 &fa526_target,
98 &feroceon_target,
99 &dragonite_target,
100 &xscale_target,
101 &cortexm3_target,
102 &cortexa8_target,
103 &arm11_target,
104 &mips_m4k_target,
105 &avr_target,
106 &dsp563xx_target,
107 &dsp5680xx_target,
108 &testee_target,
109 &avr32_ap7k_target,
110 NULL,
113 struct target *all_targets = NULL;
114 static struct target_event_callback *target_event_callbacks = NULL;
115 static struct target_timer_callback *target_timer_callbacks = NULL;
116 static const int polling_interval = 100;
118 static const Jim_Nvp nvp_assert[] = {
119 { .name = "assert", NVP_ASSERT },
120 { .name = "deassert", NVP_DEASSERT },
121 { .name = "T", NVP_ASSERT },
122 { .name = "F", NVP_DEASSERT },
123 { .name = "t", NVP_ASSERT },
124 { .name = "f", NVP_DEASSERT },
125 { .name = NULL, .value = -1 }
128 static const Jim_Nvp nvp_error_target[] = {
129 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
130 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
131 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
132 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
133 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
134 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
135 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
136 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
137 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
138 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
139 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
140 { .value = -1, .name = NULL }
143 static const char *target_strerror_safe(int err)
145 const Jim_Nvp *n;
147 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
148 if (n->name == NULL) {
149 return "unknown";
150 } else {
151 return n->name;
155 static const Jim_Nvp nvp_target_event[] = {
156 { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
157 { .value = TARGET_EVENT_OLD_pre_resume , .name = "old-pre_resume" },
159 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
160 { .value = TARGET_EVENT_HALTED, .name = "halted" },
161 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
162 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
163 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
165 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
166 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
168 /* historical name */
170 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
172 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
173 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
174 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
175 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
176 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
177 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
178 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
179 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
180 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
181 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
182 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
184 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
185 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
187 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
188 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
190 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
191 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
193 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
194 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
196 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
197 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
199 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
200 { .value = TARGET_EVENT_RESUMED , .name = "resume-ok" },
201 { .value = TARGET_EVENT_RESUME_END , .name = "resume-end" },
203 { .name = NULL, .value = -1 }
206 static const Jim_Nvp nvp_target_state[] = {
207 { .name = "unknown", .value = TARGET_UNKNOWN },
208 { .name = "running", .value = TARGET_RUNNING },
209 { .name = "halted", .value = TARGET_HALTED },
210 { .name = "reset", .value = TARGET_RESET },
211 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
212 { .name = NULL, .value = -1 },
215 static const Jim_Nvp nvp_target_debug_reason [] = {
216 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
217 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
218 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
219 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
220 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
221 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
222 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
223 { .name = NULL, .value = -1 },
226 static const Jim_Nvp nvp_target_endian[] = {
227 { .name = "big", .value = TARGET_BIG_ENDIAN },
228 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
229 { .name = "be", .value = TARGET_BIG_ENDIAN },
230 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
231 { .name = NULL, .value = -1 },
234 static const Jim_Nvp nvp_reset_modes[] = {
235 { .name = "unknown", .value = RESET_UNKNOWN },
236 { .name = "run" , .value = RESET_RUN },
237 { .name = "halt" , .value = RESET_HALT },
238 { .name = "init" , .value = RESET_INIT },
239 { .name = NULL , .value = -1 },
242 const char *debug_reason_name(struct target *t)
244 const char *cp;
246 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
247 t->debug_reason)->name;
248 if (!cp) {
249 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
250 cp = "(*BUG*unknown*BUG*)";
252 return cp;
255 const char *
256 target_state_name( struct target *t )
258 const char *cp;
259 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
260 if( !cp ){
261 LOG_ERROR("Invalid target state: %d", (int)(t->state));
262 cp = "(*BUG*unknown*BUG*)";
264 return cp;
267 /* determine the number of the new target */
268 static int new_target_number(void)
270 struct target *t;
271 int x;
273 /* number is 0 based */
274 x = -1;
275 t = all_targets;
276 while (t) {
277 if (x < t->target_number) {
278 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 /* return a pointer to a configured target; id is name or number */
352 struct target *get_target(const char *id)
354 struct target *target;
356 /* try as tcltarget name */
357 for (target = all_targets; target; target = target->next) {
358 if (target->cmd_name == NULL)
359 continue;
360 if (strcmp(id, target->cmd_name) == 0)
361 return target;
364 /* It's OK to remove this fallback sometime after August 2010 or so */
366 /* no match, try as number */
367 unsigned num;
368 if (parse_uint(id, &num) != ERROR_OK)
369 return NULL;
371 for (target = all_targets; target; target = target->next) {
372 if (target->target_number == (int)num) {
373 LOG_WARNING("use '%s' as target identifier, not '%u'",
374 target->cmd_name, num);
375 return target;
379 return NULL;
382 /* returns a pointer to the n-th configured target */
383 static struct target *get_target_by_num(int num)
385 struct target *target = all_targets;
387 while (target) {
388 if (target->target_number == num) {
389 return target;
391 target = target->next;
394 return NULL;
397 struct target* get_current_target(struct command_context *cmd_ctx)
399 struct target *target = get_target_by_num(cmd_ctx->current_target);
401 if (target == NULL)
403 LOG_ERROR("BUG: current_target out of bounds");
404 exit(-1);
407 return target;
410 int target_poll(struct target *target)
412 int retval;
414 /* We can't poll until after examine */
415 if (!target_was_examined(target))
417 /* Fail silently lest we pollute the log */
418 return ERROR_FAIL;
421 retval = target->type->poll(target);
422 if (retval != ERROR_OK)
423 return retval;
425 if (target->halt_issued)
427 if (target->state == TARGET_HALTED)
429 target->halt_issued = false;
430 } else
432 long long t = timeval_ms() - target->halt_issued_time;
433 if (t>1000)
435 target->halt_issued = false;
436 LOG_INFO("Halt timed out, wake up GDB.");
437 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
442 return ERROR_OK;
445 int target_halt(struct target *target)
447 int retval;
448 /* We can't poll until after examine */
449 if (!target_was_examined(target))
451 LOG_ERROR("Target not examined yet");
452 return ERROR_FAIL;
455 retval = target->type->halt(target);
456 if (retval != ERROR_OK)
457 return retval;
459 target->halt_issued = true;
460 target->halt_issued_time = timeval_ms();
462 return ERROR_OK;
466 * Make the target (re)start executing using its saved execution
467 * context (possibly with some modifications).
469 * @param target Which target should start executing.
470 * @param current True to use the target's saved program counter instead
471 * of the address parameter
472 * @param address Optionally used as the program counter.
473 * @param handle_breakpoints True iff breakpoints at the resumption PC
474 * should be skipped. (For example, maybe execution was stopped by
475 * such a breakpoint, in which case it would be counterprodutive to
476 * let it re-trigger.
477 * @param debug_execution False if all working areas allocated by OpenOCD
478 * should be released and/or restored to their original contents.
479 * (This would for example be true to run some downloaded "helper"
480 * algorithm code, which resides in one such working buffer and uses
481 * another for data storage.)
483 * @todo Resolve the ambiguity about what the "debug_execution" flag
484 * signifies. For example, Target implementations don't agree on how
485 * it relates to invalidation of the register cache, or to whether
486 * breakpoints and watchpoints should be enabled. (It would seem wrong
487 * to enable breakpoints when running downloaded "helper" algorithms
488 * (debug_execution true), since the breakpoints would be set to match
489 * target firmware being debugged, not the helper algorithm.... and
490 * enabling them could cause such helpers to malfunction (for example,
491 * by overwriting data with a breakpoint instruction. On the other
492 * hand the infrastructure for running such helpers might use this
493 * procedure but rely on hardware breakpoint to detect termination.)
495 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
497 int retval;
499 /* We can't poll until after examine */
500 if (!target_was_examined(target))
502 LOG_ERROR("Target not examined yet");
503 return ERROR_FAIL;
506 /* note that resume *must* be asynchronous. The CPU can halt before
507 * we poll. The CPU can even halt at the current PC as a result of
508 * a software breakpoint being inserted by (a bug?) the application.
510 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
511 return retval;
513 return retval;
516 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
518 char buf[100];
519 int retval;
520 Jim_Nvp *n;
521 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
522 if (n->name == NULL) {
523 LOG_ERROR("invalid reset mode");
524 return ERROR_FAIL;
527 /* disable polling during reset to make reset event scripts
528 * more predictable, i.e. dr/irscan & pathmove in events will
529 * not have JTAG operations injected into the middle of a sequence.
531 bool save_poll = jtag_poll_get_enabled();
533 jtag_poll_set_enabled(false);
535 sprintf(buf, "ocd_process_reset %s", n->name);
536 retval = Jim_Eval(cmd_ctx->interp, buf);
538 jtag_poll_set_enabled(save_poll);
540 if (retval != JIM_OK) {
541 Jim_MakeErrorMessage(cmd_ctx->interp);
542 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
543 return ERROR_FAIL;
546 /* We want any events to be processed before the prompt */
547 retval = target_call_timer_callbacks_now();
549 struct target *target;
550 for (target = all_targets; target; target = target->next) {
551 target->type->check_reset(target);
554 return retval;
557 static int identity_virt2phys(struct target *target,
558 uint32_t virtual, uint32_t *physical)
560 *physical = virtual;
561 return ERROR_OK;
564 static int no_mmu(struct target *target, int *enabled)
566 *enabled = 0;
567 return ERROR_OK;
570 static int default_examine(struct target *target)
572 target_set_examined(target);
573 return ERROR_OK;
576 /* no check by default */
577 static int default_check_reset(struct target *target)
579 return ERROR_OK;
582 int target_examine_one(struct target *target)
584 return target->type->examine(target);
587 static int jtag_enable_callback(enum jtag_event event, void *priv)
589 struct target *target = priv;
591 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
592 return ERROR_OK;
594 jtag_unregister_event_callback(jtag_enable_callback, target);
595 return target_examine_one(target);
599 /* Targets that correctly implement init + examine, i.e.
600 * no communication with target during init:
602 * XScale
604 int target_examine(void)
606 int retval = ERROR_OK;
607 struct target *target;
609 for (target = all_targets; target; target = target->next)
611 /* defer examination, but don't skip it */
612 if (!target->tap->enabled) {
613 jtag_register_event_callback(jtag_enable_callback,
614 target);
615 continue;
617 if ((retval = target_examine_one(target)) != ERROR_OK)
618 return retval;
620 return retval;
622 const char *target_type_name(struct target *target)
624 return target->type->name;
627 static int target_write_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
629 if (!target_was_examined(target))
631 LOG_ERROR("Target not examined yet");
632 return ERROR_FAIL;
634 return target->type->write_memory_imp(target, address, size, count, buffer);
637 static int target_read_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
639 if (!target_was_examined(target))
641 LOG_ERROR("Target not examined yet");
642 return ERROR_FAIL;
644 return target->type->read_memory_imp(target, address, size, count, buffer);
647 static int target_soft_reset_halt_imp(struct target *target)
649 if (!target_was_examined(target))
651 LOG_ERROR("Target not examined yet");
652 return ERROR_FAIL;
654 if (!target->type->soft_reset_halt_imp) {
655 LOG_ERROR("Target %s does not support soft_reset_halt",
656 target_name(target));
657 return ERROR_FAIL;
659 return target->type->soft_reset_halt_imp(target);
663 * Downloads a target-specific native code algorithm to the target,
664 * and executes it. * Note that some targets may need to set up, enable,
665 * and tear down a breakpoint (hard or * soft) to detect algorithm
666 * termination, while others may support lower overhead schemes where
667 * soft breakpoints embedded in the algorithm automatically terminate the
668 * algorithm.
670 * @param target used to run the algorithm
671 * @param arch_info target-specific description of the algorithm.
673 int target_run_algorithm(struct target *target,
674 int num_mem_params, struct mem_param *mem_params,
675 int num_reg_params, struct reg_param *reg_param,
676 uint32_t entry_point, uint32_t exit_point,
677 int timeout_ms, void *arch_info)
679 int retval = ERROR_FAIL;
681 if (!target_was_examined(target))
683 LOG_ERROR("Target not examined yet");
684 goto done;
686 if (!target->type->run_algorithm) {
687 LOG_ERROR("Target type '%s' does not support %s",
688 target_type_name(target), __func__);
689 goto done;
692 target->running_alg = true;
693 retval = target->type->run_algorithm(target,
694 num_mem_params, mem_params,
695 num_reg_params, reg_param,
696 entry_point, exit_point, timeout_ms, arch_info);
697 target->running_alg = false;
699 done:
700 return retval;
704 int target_read_memory(struct target *target,
705 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
707 return target->type->read_memory(target, address, size, count, buffer);
710 static int target_read_phys_memory(struct target *target,
711 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
713 return target->type->read_phys_memory(target, address, size, count, buffer);
716 int target_write_memory(struct target *target,
717 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
719 return target->type->write_memory(target, address, size, count, buffer);
722 static int target_write_phys_memory(struct target *target,
723 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
725 return target->type->write_phys_memory(target, address, size, count, buffer);
728 int target_bulk_write_memory(struct target *target,
729 uint32_t address, uint32_t count, const uint8_t *buffer)
731 return target->type->bulk_write_memory(target, address, count, buffer);
734 int target_add_breakpoint(struct target *target,
735 struct breakpoint *breakpoint)
737 if ((target->state != TARGET_HALTED)&&(breakpoint->type!=BKPT_HARD)) {
738 LOG_WARNING("target %s is not halted", target->cmd_name);
739 return ERROR_TARGET_NOT_HALTED;
741 return target->type->add_breakpoint(target, breakpoint);
743 int target_remove_breakpoint(struct target *target,
744 struct breakpoint *breakpoint)
746 return target->type->remove_breakpoint(target, breakpoint);
749 int target_add_watchpoint(struct target *target,
750 struct watchpoint *watchpoint)
752 if (target->state != TARGET_HALTED) {
753 LOG_WARNING("target %s is not halted", target->cmd_name);
754 return ERROR_TARGET_NOT_HALTED;
756 return target->type->add_watchpoint(target, watchpoint);
758 int target_remove_watchpoint(struct target *target,
759 struct watchpoint *watchpoint)
761 return target->type->remove_watchpoint(target, watchpoint);
764 int target_get_gdb_reg_list(struct target *target,
765 struct reg **reg_list[], int *reg_list_size)
767 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
769 int target_step(struct target *target,
770 int current, uint32_t address, int handle_breakpoints)
772 return target->type->step(target, current, address, handle_breakpoints);
777 * Reset the @c examined flag for the given target.
778 * Pure paranoia -- targets are zeroed on allocation.
780 static void target_reset_examined(struct target *target)
782 target->examined = false;
785 static int
786 err_read_phys_memory(struct target *target, uint32_t address,
787 uint32_t size, uint32_t count, uint8_t *buffer)
789 LOG_ERROR("Not implemented: %s", __func__);
790 return ERROR_FAIL;
793 static int
794 err_write_phys_memory(struct target *target, uint32_t address,
795 uint32_t size, uint32_t count, const uint8_t *buffer)
797 LOG_ERROR("Not implemented: %s", __func__);
798 return ERROR_FAIL;
801 static int handle_target(void *priv);
803 static int target_init_one(struct command_context *cmd_ctx,
804 struct target *target)
806 target_reset_examined(target);
808 struct target_type *type = target->type;
809 if (type->examine == NULL)
810 type->examine = default_examine;
812 if (type->check_reset== NULL)
813 type->check_reset = default_check_reset;
815 int retval = type->init_target(cmd_ctx, target);
816 if (ERROR_OK != retval)
818 LOG_ERROR("target '%s' init failed", target_name(target));
819 return retval;
823 * @todo get rid of those *memory_imp() methods, now that all
824 * callers are using target_*_memory() accessors ... and make
825 * sure the "physical" paths handle the same issues.
827 /* a non-invasive way(in terms of patches) to add some code that
828 * runs before the type->write/read_memory implementation
830 type->write_memory_imp = target->type->write_memory;
831 type->write_memory = target_write_memory_imp;
833 type->read_memory_imp = target->type->read_memory;
834 type->read_memory = target_read_memory_imp;
836 type->soft_reset_halt_imp = target->type->soft_reset_halt;
837 type->soft_reset_halt = target_soft_reset_halt_imp;
839 /* Sanity-check MMU support ... stub in what we must, to help
840 * implement it in stages, but warn if we need to do so.
842 if (type->mmu)
844 if (type->write_phys_memory == NULL)
846 LOG_ERROR("type '%s' is missing write_phys_memory",
847 type->name);
848 type->write_phys_memory = err_write_phys_memory;
850 if (type->read_phys_memory == NULL)
852 LOG_ERROR("type '%s' is missing read_phys_memory",
853 type->name);
854 type->read_phys_memory = err_read_phys_memory;
856 if (type->virt2phys == NULL)
858 LOG_ERROR("type '%s' is missing virt2phys", type->name);
859 type->virt2phys = identity_virt2phys;
862 else
864 /* Make sure no-MMU targets all behave the same: make no
865 * distinction between physical and virtual addresses, and
866 * ensure that virt2phys() is always an identity mapping.
868 if (type->write_phys_memory || type->read_phys_memory
869 || type->virt2phys)
871 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
874 type->mmu = no_mmu;
875 type->write_phys_memory = type->write_memory;
876 type->read_phys_memory = type->read_memory;
877 type->virt2phys = identity_virt2phys;
880 if (target->type->read_buffer == NULL)
881 target->type->read_buffer = target_read_buffer_default;
883 if (target->type->write_buffer == NULL)
884 target->type->write_buffer = target_write_buffer_default;
886 return ERROR_OK;
889 static int target_init(struct command_context *cmd_ctx)
891 struct target *target;
892 int retval;
894 for (target = all_targets; target; target = target->next)
896 retval = target_init_one(cmd_ctx, target);
897 if (ERROR_OK != retval)
898 return retval;
901 if (!all_targets)
902 return ERROR_OK;
904 retval = target_register_user_commands(cmd_ctx);
905 if (ERROR_OK != retval)
906 return retval;
908 retval = target_register_timer_callback(&handle_target,
909 polling_interval, 1, cmd_ctx->interp);
910 if (ERROR_OK != retval)
911 return retval;
913 return ERROR_OK;
916 COMMAND_HANDLER(handle_target_init_command)
918 if (CMD_ARGC != 0)
919 return ERROR_COMMAND_SYNTAX_ERROR;
921 static bool target_initialized = false;
922 if (target_initialized)
924 LOG_INFO("'target init' has already been called");
925 return ERROR_OK;
927 target_initialized = true;
929 LOG_DEBUG("Initializing targets...");
930 return target_init(CMD_CTX);
933 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
935 struct target_event_callback **callbacks_p = &target_event_callbacks;
937 if (callback == NULL)
939 return ERROR_INVALID_ARGUMENTS;
942 if (*callbacks_p)
944 while ((*callbacks_p)->next)
945 callbacks_p = &((*callbacks_p)->next);
946 callbacks_p = &((*callbacks_p)->next);
949 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
950 (*callbacks_p)->callback = callback;
951 (*callbacks_p)->priv = priv;
952 (*callbacks_p)->next = NULL;
954 return ERROR_OK;
957 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
959 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
960 struct timeval now;
962 if (callback == NULL)
964 return ERROR_INVALID_ARGUMENTS;
967 if (*callbacks_p)
969 while ((*callbacks_p)->next)
970 callbacks_p = &((*callbacks_p)->next);
971 callbacks_p = &((*callbacks_p)->next);
974 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
975 (*callbacks_p)->callback = callback;
976 (*callbacks_p)->periodic = periodic;
977 (*callbacks_p)->time_ms = time_ms;
979 gettimeofday(&now, NULL);
980 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
981 time_ms -= (time_ms % 1000);
982 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
983 if ((*callbacks_p)->when.tv_usec > 1000000)
985 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
986 (*callbacks_p)->when.tv_sec += 1;
989 (*callbacks_p)->priv = priv;
990 (*callbacks_p)->next = NULL;
992 return ERROR_OK;
995 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
997 struct target_event_callback **p = &target_event_callbacks;
998 struct target_event_callback *c = target_event_callbacks;
1000 if (callback == NULL)
1002 return ERROR_INVALID_ARGUMENTS;
1005 while (c)
1007 struct target_event_callback *next = c->next;
1008 if ((c->callback == callback) && (c->priv == priv))
1010 *p = next;
1011 free(c);
1012 return ERROR_OK;
1014 else
1015 p = &(c->next);
1016 c = next;
1019 return ERROR_OK;
1022 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1024 struct target_timer_callback **p = &target_timer_callbacks;
1025 struct target_timer_callback *c = target_timer_callbacks;
1027 if (callback == NULL)
1029 return ERROR_INVALID_ARGUMENTS;
1032 while (c)
1034 struct target_timer_callback *next = c->next;
1035 if ((c->callback == callback) && (c->priv == priv))
1037 *p = next;
1038 free(c);
1039 return ERROR_OK;
1041 else
1042 p = &(c->next);
1043 c = next;
1046 return ERROR_OK;
1049 int target_call_event_callbacks(struct target *target, enum target_event event)
1051 struct target_event_callback *callback = target_event_callbacks;
1052 struct target_event_callback *next_callback;
1054 if (event == TARGET_EVENT_HALTED)
1056 /* execute early halted first */
1057 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1060 LOG_DEBUG("target event %i (%s)",
1061 event,
1062 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1064 target_handle_event(target, event);
1066 while (callback)
1068 next_callback = callback->next;
1069 callback->callback(target, event, callback->priv);
1070 callback = next_callback;
1073 return ERROR_OK;
1076 static int target_timer_callback_periodic_restart(
1077 struct target_timer_callback *cb, struct timeval *now)
1079 int time_ms = cb->time_ms;
1080 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1081 time_ms -= (time_ms % 1000);
1082 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1083 if (cb->when.tv_usec > 1000000)
1085 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1086 cb->when.tv_sec += 1;
1088 return ERROR_OK;
1091 static int target_call_timer_callback(struct target_timer_callback *cb,
1092 struct timeval *now)
1094 cb->callback(cb->priv);
1096 if (cb->periodic)
1097 return target_timer_callback_periodic_restart(cb, now);
1099 return target_unregister_timer_callback(cb->callback, cb->priv);
1102 static int target_call_timer_callbacks_check_time(int checktime)
1104 keep_alive();
1106 struct timeval now;
1107 gettimeofday(&now, NULL);
1109 struct target_timer_callback *callback = target_timer_callbacks;
1110 while (callback)
1112 // cleaning up may unregister and free this callback
1113 struct target_timer_callback *next_callback = callback->next;
1115 bool call_it = callback->callback &&
1116 ((!checktime && callback->periodic) ||
1117 now.tv_sec > callback->when.tv_sec ||
1118 (now.tv_sec == callback->when.tv_sec &&
1119 now.tv_usec >= callback->when.tv_usec));
1121 if (call_it)
1123 int retval = target_call_timer_callback(callback, &now);
1124 if (retval != ERROR_OK)
1125 return retval;
1128 callback = next_callback;
1131 return ERROR_OK;
1134 int target_call_timer_callbacks(void)
1136 return target_call_timer_callbacks_check_time(1);
1139 /* invoke periodic callbacks immediately */
1140 int target_call_timer_callbacks_now(void)
1142 return target_call_timer_callbacks_check_time(0);
1145 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1147 struct working_area *c = target->working_areas;
1148 struct working_area *new_wa = NULL;
1150 /* Reevaluate working area address based on MMU state*/
1151 if (target->working_areas == NULL)
1153 int retval;
1154 int enabled;
1156 retval = target->type->mmu(target, &enabled);
1157 if (retval != ERROR_OK)
1159 return retval;
1162 if (!enabled) {
1163 if (target->working_area_phys_spec) {
1164 LOG_DEBUG("MMU disabled, using physical "
1165 "address for working memory 0x%08x",
1166 (unsigned)target->working_area_phys);
1167 target->working_area = target->working_area_phys;
1168 } else {
1169 LOG_ERROR("No working memory available. "
1170 "Specify -work-area-phys to target.");
1171 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1173 } else {
1174 if (target->working_area_virt_spec) {
1175 LOG_DEBUG("MMU enabled, using virtual "
1176 "address for working memory 0x%08x",
1177 (unsigned)target->working_area_virt);
1178 target->working_area = target->working_area_virt;
1179 } else {
1180 LOG_ERROR("No working memory available. "
1181 "Specify -work-area-virt to target.");
1182 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1187 /* only allocate multiples of 4 byte */
1188 if (size % 4)
1190 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1191 size = (size + 3) & (~3);
1194 /* see if there's already a matching working area */
1195 while (c)
1197 if ((c->free) && (c->size == size))
1199 new_wa = c;
1200 break;
1202 c = c->next;
1205 /* if not, allocate a new one */
1206 if (!new_wa)
1208 struct working_area **p = &target->working_areas;
1209 uint32_t first_free = target->working_area;
1210 uint32_t free_size = target->working_area_size;
1212 c = target->working_areas;
1213 while (c)
1215 first_free += c->size;
1216 free_size -= c->size;
1217 p = &c->next;
1218 c = c->next;
1221 if (free_size < size)
1223 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1226 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1228 new_wa = malloc(sizeof(struct working_area));
1229 new_wa->next = NULL;
1230 new_wa->size = size;
1231 new_wa->address = first_free;
1233 if (target->backup_working_area)
1235 int retval;
1236 new_wa->backup = malloc(new_wa->size);
1237 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1239 free(new_wa->backup);
1240 free(new_wa);
1241 return retval;
1244 else
1246 new_wa->backup = NULL;
1249 /* put new entry in list */
1250 *p = new_wa;
1253 /* mark as used, and return the new (reused) area */
1254 new_wa->free = false;
1255 *area = new_wa;
1257 /* user pointer */
1258 new_wa->user = area;
1260 return ERROR_OK;
1263 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1265 int retval;
1267 retval = target_alloc_working_area_try(target, size, area);
1268 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1270 LOG_WARNING("not enough working area available(requested %u)", (unsigned)(size));
1272 return retval;
1276 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1278 if (area->free)
1279 return ERROR_OK;
1281 if (restore && target->backup_working_area)
1283 int retval;
1284 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1285 return retval;
1288 area->free = true;
1290 /* mark user pointer invalid */
1291 *area->user = NULL;
1292 area->user = NULL;
1294 return ERROR_OK;
1297 int target_free_working_area(struct target *target, struct working_area *area)
1299 return target_free_working_area_restore(target, area, 1);
1302 /* free resources and restore memory, if restoring memory fails,
1303 * free up resources anyway
1305 static void target_free_all_working_areas_restore(struct target *target, int restore)
1307 struct working_area *c = target->working_areas;
1309 while (c)
1311 struct working_area *next = c->next;
1312 target_free_working_area_restore(target, c, restore);
1314 if (c->backup)
1315 free(c->backup);
1317 free(c);
1319 c = next;
1322 target->working_areas = NULL;
1325 void target_free_all_working_areas(struct target *target)
1327 target_free_all_working_areas_restore(target, 1);
1330 int target_arch_state(struct target *target)
1332 int retval;
1333 if (target == NULL)
1335 LOG_USER("No target has been configured");
1336 return ERROR_OK;
1339 LOG_USER("target state: %s", target_state_name( target ));
1341 if (target->state != TARGET_HALTED)
1342 return ERROR_OK;
1344 retval = target->type->arch_state(target);
1345 return retval;
1348 /* Single aligned words are guaranteed to use 16 or 32 bit access
1349 * mode respectively, otherwise data is handled as quickly as
1350 * possible
1352 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1354 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1355 (int)size, (unsigned)address);
1357 if (!target_was_examined(target))
1359 LOG_ERROR("Target not examined yet");
1360 return ERROR_FAIL;
1363 if (size == 0) {
1364 return ERROR_OK;
1367 if ((address + size - 1) < address)
1369 /* GDB can request this when e.g. PC is 0xfffffffc*/
1370 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1371 (unsigned)address,
1372 (unsigned)size);
1373 return ERROR_FAIL;
1376 return target->type->write_buffer(target, address, size, buffer);
1379 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1381 int retval = ERROR_OK;
1383 if (((address % 2) == 0) && (size == 2))
1385 return target_write_memory(target, address, 2, 1, buffer);
1388 /* handle unaligned head bytes */
1389 if (address % 4)
1391 uint32_t unaligned = 4 - (address % 4);
1393 if (unaligned > size)
1394 unaligned = size;
1396 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1397 return retval;
1399 buffer += unaligned;
1400 address += unaligned;
1401 size -= unaligned;
1404 /* handle aligned words */
1405 if (size >= 4)
1407 int aligned = size - (size % 4);
1409 /* use bulk writes above a certain limit. This may have to be changed */
1410 if (aligned > 128)
1412 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1413 return retval;
1415 else
1417 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1418 return retval;
1421 buffer += aligned;
1422 address += aligned;
1423 size -= aligned;
1426 /* handle tail writes of less than 4 bytes */
1427 if (size > 0)
1429 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1430 return retval;
1433 return retval;
1436 /* Single aligned words are guaranteed to use 16 or 32 bit access
1437 * mode respectively, otherwise data is handled as quickly as
1438 * possible
1440 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1442 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1443 (int)size, (unsigned)address);
1445 if (!target_was_examined(target))
1447 LOG_ERROR("Target not examined yet");
1448 return ERROR_FAIL;
1451 if (size == 0) {
1452 return ERROR_OK;
1455 if ((address + size - 1) < address)
1457 /* GDB can request this when e.g. PC is 0xfffffffc*/
1458 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1459 address,
1460 size);
1461 return ERROR_FAIL;
1464 return target->type->read_buffer(target, address, size, buffer);
1467 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1469 int retval = ERROR_OK;
1471 if (((address % 2) == 0) && (size == 2))
1473 return target_read_memory(target, address, 2, 1, buffer);
1476 /* handle unaligned head bytes */
1477 if (address % 4)
1479 uint32_t unaligned = 4 - (address % 4);
1481 if (unaligned > size)
1482 unaligned = size;
1484 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1485 return retval;
1487 buffer += unaligned;
1488 address += unaligned;
1489 size -= unaligned;
1492 /* handle aligned words */
1493 if (size >= 4)
1495 int aligned = size - (size % 4);
1497 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1498 return retval;
1500 buffer += aligned;
1501 address += aligned;
1502 size -= aligned;
1505 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1506 if(size >=2)
1508 int aligned = size - (size%2);
1509 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1510 if (retval != ERROR_OK)
1511 return retval;
1513 buffer += aligned;
1514 address += aligned;
1515 size -= aligned;
1517 /* handle tail writes of less than 4 bytes */
1518 if (size > 0)
1520 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1521 return retval;
1524 return ERROR_OK;
1527 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1529 uint8_t *buffer;
1530 int retval;
1531 uint32_t i;
1532 uint32_t checksum = 0;
1533 if (!target_was_examined(target))
1535 LOG_ERROR("Target not examined yet");
1536 return ERROR_FAIL;
1539 if ((retval = target->type->checksum_memory(target, address,
1540 size, &checksum)) != ERROR_OK)
1542 buffer = malloc(size);
1543 if (buffer == NULL)
1545 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1546 return ERROR_INVALID_ARGUMENTS;
1548 retval = target_read_buffer(target, address, size, buffer);
1549 if (retval != ERROR_OK)
1551 free(buffer);
1552 return retval;
1555 /* convert to target endianness */
1556 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1558 uint32_t target_data;
1559 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1560 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1563 retval = image_calculate_checksum(buffer, size, &checksum);
1564 free(buffer);
1567 *crc = checksum;
1569 return retval;
1572 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1574 int retval;
1575 if (!target_was_examined(target))
1577 LOG_ERROR("Target not examined yet");
1578 return ERROR_FAIL;
1581 if (target->type->blank_check_memory == 0)
1582 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1584 retval = target->type->blank_check_memory(target, address, size, blank);
1586 return retval;
1589 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1591 uint8_t value_buf[4];
1592 if (!target_was_examined(target))
1594 LOG_ERROR("Target not examined yet");
1595 return ERROR_FAIL;
1598 int retval = target_read_memory(target, address, 4, 1, value_buf);
1600 if (retval == ERROR_OK)
1602 *value = target_buffer_get_u32(target, value_buf);
1603 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1604 address,
1605 *value);
1607 else
1609 *value = 0x0;
1610 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1611 address);
1614 return retval;
1617 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1619 uint8_t value_buf[2];
1620 if (!target_was_examined(target))
1622 LOG_ERROR("Target not examined yet");
1623 return ERROR_FAIL;
1626 int retval = target_read_memory(target, address, 2, 1, value_buf);
1628 if (retval == ERROR_OK)
1630 *value = target_buffer_get_u16(target, value_buf);
1631 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1632 address,
1633 *value);
1635 else
1637 *value = 0x0;
1638 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1639 address);
1642 return retval;
1645 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1647 int retval = target_read_memory(target, address, 1, 1, value);
1648 if (!target_was_examined(target))
1650 LOG_ERROR("Target not examined yet");
1651 return ERROR_FAIL;
1654 if (retval == ERROR_OK)
1656 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1657 address,
1658 *value);
1660 else
1662 *value = 0x0;
1663 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1664 address);
1667 return retval;
1670 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1672 int retval;
1673 uint8_t value_buf[4];
1674 if (!target_was_examined(target))
1676 LOG_ERROR("Target not examined yet");
1677 return ERROR_FAIL;
1680 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1681 address,
1682 value);
1684 target_buffer_set_u32(target, value_buf, value);
1685 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1687 LOG_DEBUG("failed: %i", retval);
1690 return retval;
1693 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1695 int retval;
1696 uint8_t value_buf[2];
1697 if (!target_was_examined(target))
1699 LOG_ERROR("Target not examined yet");
1700 return ERROR_FAIL;
1703 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1704 address,
1705 value);
1707 target_buffer_set_u16(target, value_buf, value);
1708 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1710 LOG_DEBUG("failed: %i", retval);
1713 return retval;
1716 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1718 int retval;
1719 if (!target_was_examined(target))
1721 LOG_ERROR("Target not examined yet");
1722 return ERROR_FAIL;
1725 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1726 address, value);
1728 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1730 LOG_DEBUG("failed: %i", retval);
1733 return retval;
1736 COMMAND_HANDLER(handle_targets_command)
1738 struct target *target = all_targets;
1740 if (CMD_ARGC == 1)
1742 target = get_target(CMD_ARGV[0]);
1743 if (target == NULL) {
1744 command_print(CMD_CTX,"Target: %s is unknown, try one of:\n", CMD_ARGV[0]);
1745 goto DumpTargets;
1747 if (!target->tap->enabled) {
1748 command_print(CMD_CTX,"Target: TAP %s is disabled, "
1749 "can't be the current target\n",
1750 target->tap->dotted_name);
1751 return ERROR_FAIL;
1754 CMD_CTX->current_target = target->target_number;
1755 return ERROR_OK;
1757 DumpTargets:
1759 target = all_targets;
1760 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
1761 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
1762 while (target)
1764 const char *state;
1765 char marker = ' ';
1767 if (target->tap->enabled)
1768 state = target_state_name( target );
1769 else
1770 state = "tap-disabled";
1772 if (CMD_CTX->current_target == target->target_number)
1773 marker = '*';
1775 /* keep columns lined up to match the headers above */
1776 command_print(CMD_CTX, "%2d%c %-18s %-10s %-6s %-18s %s",
1777 target->target_number,
1778 marker,
1779 target_name(target),
1780 target_type_name(target),
1781 Jim_Nvp_value2name_simple(nvp_target_endian,
1782 target->endianness)->name,
1783 target->tap->dotted_name,
1784 state);
1785 target = target->next;
1788 return ERROR_OK;
1791 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1793 static int powerDropout;
1794 static int srstAsserted;
1796 static int runPowerRestore;
1797 static int runPowerDropout;
1798 static int runSrstAsserted;
1799 static int runSrstDeasserted;
1801 static int sense_handler(void)
1803 static int prevSrstAsserted = 0;
1804 static int prevPowerdropout = 0;
1806 int retval;
1807 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1808 return retval;
1810 int powerRestored;
1811 powerRestored = prevPowerdropout && !powerDropout;
1812 if (powerRestored)
1814 runPowerRestore = 1;
1817 long long current = timeval_ms();
1818 static long long lastPower = 0;
1819 int waitMore = lastPower + 2000 > current;
1820 if (powerDropout && !waitMore)
1822 runPowerDropout = 1;
1823 lastPower = current;
1826 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1827 return retval;
1829 int srstDeasserted;
1830 srstDeasserted = prevSrstAsserted && !srstAsserted;
1832 static long long lastSrst = 0;
1833 waitMore = lastSrst + 2000 > current;
1834 if (srstDeasserted && !waitMore)
1836 runSrstDeasserted = 1;
1837 lastSrst = current;
1840 if (!prevSrstAsserted && srstAsserted)
1842 runSrstAsserted = 1;
1845 prevSrstAsserted = srstAsserted;
1846 prevPowerdropout = powerDropout;
1848 if (srstDeasserted || powerRestored)
1850 /* Other than logging the event we can't do anything here.
1851 * Issuing a reset is a particularly bad idea as we might
1852 * be inside a reset already.
1856 return ERROR_OK;
1859 static int backoff_times = 0;
1860 static int backoff_count = 0;
1862 /* process target state changes */
1863 static int handle_target(void *priv)
1865 Jim_Interp *interp = (Jim_Interp *)priv;
1866 int retval = ERROR_OK;
1868 if (!is_jtag_poll_safe())
1870 /* polling is disabled currently */
1871 return ERROR_OK;
1874 /* we do not want to recurse here... */
1875 static int recursive = 0;
1876 if (! recursive)
1878 recursive = 1;
1879 sense_handler();
1880 /* danger! running these procedures can trigger srst assertions and power dropouts.
1881 * We need to avoid an infinite loop/recursion here and we do that by
1882 * clearing the flags after running these events.
1884 int did_something = 0;
1885 if (runSrstAsserted)
1887 LOG_INFO("srst asserted detected, running srst_asserted proc.");
1888 Jim_Eval(interp, "srst_asserted");
1889 did_something = 1;
1891 if (runSrstDeasserted)
1893 Jim_Eval(interp, "srst_deasserted");
1894 did_something = 1;
1896 if (runPowerDropout)
1898 LOG_INFO("Power dropout detected, running power_dropout proc.");
1899 Jim_Eval(interp, "power_dropout");
1900 did_something = 1;
1902 if (runPowerRestore)
1904 Jim_Eval(interp, "power_restore");
1905 did_something = 1;
1908 if (did_something)
1910 /* clear detect flags */
1911 sense_handler();
1914 /* clear action flags */
1916 runSrstAsserted = 0;
1917 runSrstDeasserted = 0;
1918 runPowerRestore = 0;
1919 runPowerDropout = 0;
1921 recursive = 0;
1924 if (backoff_times > backoff_count)
1926 /* do not poll this time as we failed previously */
1927 backoff_count++;
1928 return ERROR_OK;
1930 backoff_count = 0;
1932 /* Poll targets for state changes unless that's globally disabled.
1933 * Skip targets that are currently disabled.
1935 for (struct target *target = all_targets;
1936 is_jtag_poll_safe() && target;
1937 target = target->next)
1939 if (!target->tap->enabled)
1940 continue;
1942 /* only poll target if we've got power and srst isn't asserted */
1943 if (!powerDropout && !srstAsserted)
1945 /* polling may fail silently until the target has been examined */
1946 if ((retval = target_poll(target)) != ERROR_OK)
1948 /* 100ms polling interval. Increase interval between polling up to 5000ms */
1949 if (backoff_times * polling_interval < 5000)
1951 backoff_times *= 2;
1952 backoff_times++;
1954 LOG_USER("Polling target failed, GDB will be halted. Polling again in %dms", backoff_times * polling_interval);
1956 /* Tell GDB to halt the debugger. This allows the user to
1957 * run monitor commands to handle the situation.
1959 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1960 return retval;
1962 /* Since we succeeded, we reset backoff count */
1963 if (backoff_times > 0)
1965 LOG_USER("Polling succeeded again");
1967 backoff_times = 0;
1971 return retval;
1974 COMMAND_HANDLER(handle_reg_command)
1976 struct target *target;
1977 struct reg *reg = NULL;
1978 unsigned count = 0;
1979 char *value;
1981 LOG_DEBUG("-");
1983 target = get_current_target(CMD_CTX);
1985 /* list all available registers for the current target */
1986 if (CMD_ARGC == 0)
1988 struct reg_cache *cache = target->reg_cache;
1990 count = 0;
1991 while (cache)
1993 unsigned i;
1995 command_print(CMD_CTX, "===== %s", cache->name);
1997 for (i = 0, reg = cache->reg_list;
1998 i < cache->num_regs;
1999 i++, reg++, count++)
2001 /* only print cached values if they are valid */
2002 if (reg->valid) {
2003 value = buf_to_str(reg->value,
2004 reg->size, 16);
2005 command_print(CMD_CTX,
2006 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2007 count, reg->name,
2008 reg->size, value,
2009 reg->dirty
2010 ? " (dirty)"
2011 : "");
2012 free(value);
2013 } else {
2014 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2015 count, reg->name,
2016 reg->size) ;
2019 cache = cache->next;
2022 return ERROR_OK;
2025 /* access a single register by its ordinal number */
2026 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9'))
2028 unsigned num;
2029 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2031 struct reg_cache *cache = target->reg_cache;
2032 count = 0;
2033 while (cache)
2035 unsigned i;
2036 for (i = 0; i < cache->num_regs; i++)
2038 if (count++ == num)
2040 reg = &cache->reg_list[i];
2041 break;
2044 if (reg)
2045 break;
2046 cache = cache->next;
2049 if (!reg)
2051 command_print(CMD_CTX, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
2052 return ERROR_OK;
2054 } else /* access a single register by its name */
2056 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2058 if (!reg)
2060 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2061 return ERROR_OK;
2065 /* display a register */
2066 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0') && (CMD_ARGV[1][0] <= '9'))))
2068 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2069 reg->valid = 0;
2071 if (reg->valid == 0)
2073 reg->type->get(reg);
2075 value = buf_to_str(reg->value, reg->size, 16);
2076 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2077 free(value);
2078 return ERROR_OK;
2081 /* set register value */
2082 if (CMD_ARGC == 2)
2084 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2085 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2087 reg->type->set(reg, buf);
2089 value = buf_to_str(reg->value, reg->size, 16);
2090 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2091 free(value);
2093 free(buf);
2095 return ERROR_OK;
2098 command_print(CMD_CTX, "usage: reg <#|name> [value]");
2100 return ERROR_OK;
2103 COMMAND_HANDLER(handle_poll_command)
2105 int retval = ERROR_OK;
2106 struct target *target = get_current_target(CMD_CTX);
2108 if (CMD_ARGC == 0)
2110 command_print(CMD_CTX, "background polling: %s",
2111 jtag_poll_get_enabled() ? "on" : "off");
2112 command_print(CMD_CTX, "TAP: %s (%s)",
2113 target->tap->dotted_name,
2114 target->tap->enabled ? "enabled" : "disabled");
2115 if (!target->tap->enabled)
2116 return ERROR_OK;
2117 if ((retval = target_poll(target)) != ERROR_OK)
2118 return retval;
2119 if ((retval = target_arch_state(target)) != ERROR_OK)
2120 return retval;
2122 else if (CMD_ARGC == 1)
2124 bool enable;
2125 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2126 jtag_poll_set_enabled(enable);
2128 else
2130 return ERROR_COMMAND_SYNTAX_ERROR;
2133 return retval;
2136 COMMAND_HANDLER(handle_wait_halt_command)
2138 if (CMD_ARGC > 1)
2139 return ERROR_COMMAND_SYNTAX_ERROR;
2141 unsigned ms = 5000;
2142 if (1 == CMD_ARGC)
2144 int retval = parse_uint(CMD_ARGV[0], &ms);
2145 if (ERROR_OK != retval)
2147 command_print(CMD_CTX, "usage: %s [seconds]", CMD_NAME);
2148 return ERROR_COMMAND_SYNTAX_ERROR;
2150 // convert seconds (given) to milliseconds (needed)
2151 ms *= 1000;
2154 struct target *target = get_current_target(CMD_CTX);
2155 return target_wait_state(target, TARGET_HALTED, ms);
2158 /* wait for target state to change. The trick here is to have a low
2159 * latency for short waits and not to suck up all the CPU time
2160 * on longer waits.
2162 * After 500ms, keep_alive() is invoked
2164 int target_wait_state(struct target *target, enum target_state state, int ms)
2166 int retval;
2167 long long then = 0, cur;
2168 int once = 1;
2170 for (;;)
2172 if ((retval = target_poll(target)) != ERROR_OK)
2173 return retval;
2174 if (target->state == state)
2176 break;
2178 cur = timeval_ms();
2179 if (once)
2181 once = 0;
2182 then = timeval_ms();
2183 LOG_DEBUG("waiting for target %s...",
2184 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2187 if (cur-then > 500)
2189 keep_alive();
2192 if ((cur-then) > ms)
2194 LOG_ERROR("timed out while waiting for target %s",
2195 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2196 return ERROR_FAIL;
2200 return ERROR_OK;
2203 COMMAND_HANDLER(handle_halt_command)
2205 LOG_DEBUG("-");
2207 struct target *target = get_current_target(CMD_CTX);
2208 int retval = target_halt(target);
2209 if (ERROR_OK != retval)
2210 return retval;
2212 if (CMD_ARGC == 1)
2214 unsigned wait_local;
2215 retval = parse_uint(CMD_ARGV[0], &wait_local);
2216 if (ERROR_OK != retval)
2217 return ERROR_COMMAND_SYNTAX_ERROR;
2218 if (!wait_local)
2219 return ERROR_OK;
2222 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2225 COMMAND_HANDLER(handle_soft_reset_halt_command)
2227 struct target *target = get_current_target(CMD_CTX);
2229 LOG_USER("requesting target halt and executing a soft reset");
2231 target->type->soft_reset_halt(target);
2233 return ERROR_OK;
2236 COMMAND_HANDLER(handle_reset_command)
2238 if (CMD_ARGC > 1)
2239 return ERROR_COMMAND_SYNTAX_ERROR;
2241 enum target_reset_mode reset_mode = RESET_RUN;
2242 if (CMD_ARGC == 1)
2244 const Jim_Nvp *n;
2245 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2246 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2247 return ERROR_COMMAND_SYNTAX_ERROR;
2249 reset_mode = n->value;
2252 /* reset *all* targets */
2253 return target_process_reset(CMD_CTX, reset_mode);
2257 COMMAND_HANDLER(handle_resume_command)
2259 int current = 1;
2260 if (CMD_ARGC > 1)
2261 return ERROR_COMMAND_SYNTAX_ERROR;
2263 struct target *target = get_current_target(CMD_CTX);
2264 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2266 /* with no CMD_ARGV, resume from current pc, addr = 0,
2267 * with one arguments, addr = CMD_ARGV[0],
2268 * handle breakpoints, not debugging */
2269 uint32_t addr = 0;
2270 if (CMD_ARGC == 1)
2272 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2273 current = 0;
2276 return target_resume(target, current, addr, 1, 0);
2279 COMMAND_HANDLER(handle_step_command)
2281 if (CMD_ARGC > 1)
2282 return ERROR_COMMAND_SYNTAX_ERROR;
2284 LOG_DEBUG("-");
2286 /* with no CMD_ARGV, step from current pc, addr = 0,
2287 * with one argument addr = CMD_ARGV[0],
2288 * handle breakpoints, debugging */
2289 uint32_t addr = 0;
2290 int current_pc = 1;
2291 if (CMD_ARGC == 1)
2293 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2294 current_pc = 0;
2297 struct target *target = get_current_target(CMD_CTX);
2299 return target->type->step(target, current_pc, addr, 1);
2302 static void handle_md_output(struct command_context *cmd_ctx,
2303 struct target *target, uint32_t address, unsigned size,
2304 unsigned count, const uint8_t *buffer)
2306 const unsigned line_bytecnt = 32;
2307 unsigned line_modulo = line_bytecnt / size;
2309 char output[line_bytecnt * 4 + 1];
2310 unsigned output_len = 0;
2312 const char *value_fmt;
2313 switch (size) {
2314 case 4: value_fmt = "%8.8x "; break;
2315 case 2: value_fmt = "%4.4x "; break;
2316 case 1: value_fmt = "%2.2x "; break;
2317 default:
2318 /* "can't happen", caller checked */
2319 LOG_ERROR("invalid memory read size: %u", size);
2320 return;
2323 for (unsigned i = 0; i < count; i++)
2325 if (i % line_modulo == 0)
2327 output_len += snprintf(output + output_len,
2328 sizeof(output) - output_len,
2329 "0x%8.8x: ",
2330 (unsigned)(address + (i*size)));
2333 uint32_t value = 0;
2334 const uint8_t *value_ptr = buffer + i * size;
2335 switch (size) {
2336 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2337 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2338 case 1: value = *value_ptr;
2340 output_len += snprintf(output + output_len,
2341 sizeof(output) - output_len,
2342 value_fmt, value);
2344 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2346 command_print(cmd_ctx, "%s", output);
2347 output_len = 0;
2352 COMMAND_HANDLER(handle_md_command)
2354 if (CMD_ARGC < 1)
2355 return ERROR_COMMAND_SYNTAX_ERROR;
2357 unsigned size = 0;
2358 switch (CMD_NAME[2]) {
2359 case 'w': size = 4; break;
2360 case 'h': size = 2; break;
2361 case 'b': size = 1; break;
2362 default: return ERROR_COMMAND_SYNTAX_ERROR;
2365 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2366 int (*fn)(struct target *target,
2367 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2368 if (physical)
2370 CMD_ARGC--;
2371 CMD_ARGV++;
2372 fn=target_read_phys_memory;
2373 } else
2375 fn=target_read_memory;
2377 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2379 return ERROR_COMMAND_SYNTAX_ERROR;
2382 uint32_t address;
2383 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2385 unsigned count = 1;
2386 if (CMD_ARGC == 2)
2387 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2389 uint8_t *buffer = calloc(count, size);
2391 struct target *target = get_current_target(CMD_CTX);
2392 int retval = fn(target, address, size, count, buffer);
2393 if (ERROR_OK == retval)
2394 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2396 free(buffer);
2398 return retval;
2401 typedef int (*target_write_fn)(struct target *target,
2402 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2404 static int target_write_memory_fast(struct target *target,
2405 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
2407 return target_write_buffer(target, address, size * count, buffer);
2410 static int target_fill_mem(struct target *target,
2411 uint32_t address,
2412 target_write_fn fn,
2413 unsigned data_size,
2414 /* value */
2415 uint32_t b,
2416 /* count */
2417 unsigned c)
2419 /* We have to write in reasonably large chunks to be able
2420 * to fill large memory areas with any sane speed */
2421 const unsigned chunk_size = 16384;
2422 uint8_t *target_buf = malloc(chunk_size * data_size);
2423 if (target_buf == NULL)
2425 LOG_ERROR("Out of memory");
2426 return ERROR_FAIL;
2429 for (unsigned i = 0; i < chunk_size; i ++)
2431 switch (data_size)
2433 case 4:
2434 target_buffer_set_u32(target, target_buf + i*data_size, b);
2435 break;
2436 case 2:
2437 target_buffer_set_u16(target, target_buf + i*data_size, b);
2438 break;
2439 case 1:
2440 target_buffer_set_u8(target, target_buf + i*data_size, b);
2441 break;
2442 default:
2443 exit(-1);
2447 int retval = ERROR_OK;
2449 for (unsigned x = 0; x < c; x += chunk_size)
2451 unsigned current;
2452 current = c - x;
2453 if (current > chunk_size)
2455 current = chunk_size;
2457 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2458 if (retval != ERROR_OK)
2460 break;
2462 /* avoid GDB timeouts */
2463 keep_alive();
2465 free(target_buf);
2467 return retval;
2471 COMMAND_HANDLER(handle_mw_command)
2473 if (CMD_ARGC < 2)
2475 return ERROR_COMMAND_SYNTAX_ERROR;
2477 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2478 target_write_fn fn;
2479 if (physical)
2481 CMD_ARGC--;
2482 CMD_ARGV++;
2483 fn=target_write_phys_memory;
2484 } else
2486 fn = target_write_memory_fast;
2488 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2489 return ERROR_COMMAND_SYNTAX_ERROR;
2491 uint32_t address;
2492 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2494 uint32_t value;
2495 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2497 unsigned count = 1;
2498 if (CMD_ARGC == 3)
2499 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2501 struct target *target = get_current_target(CMD_CTX);
2502 unsigned wordsize;
2503 switch (CMD_NAME[2])
2505 case 'w':
2506 wordsize = 4;
2507 break;
2508 case 'h':
2509 wordsize = 2;
2510 break;
2511 case 'b':
2512 wordsize = 1;
2513 break;
2514 default:
2515 return ERROR_COMMAND_SYNTAX_ERROR;
2518 return target_fill_mem(target, address, fn, wordsize, value, count);
2521 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2522 uint32_t *min_address, uint32_t *max_address)
2524 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2525 return ERROR_COMMAND_SYNTAX_ERROR;
2527 /* a base address isn't always necessary,
2528 * default to 0x0 (i.e. don't relocate) */
2529 if (CMD_ARGC >= 2)
2531 uint32_t addr;
2532 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2533 image->base_address = addr;
2534 image->base_address_set = 1;
2536 else
2537 image->base_address_set = 0;
2539 image->start_address_set = 0;
2541 if (CMD_ARGC >= 4)
2543 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2545 if (CMD_ARGC == 5)
2547 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2548 // use size (given) to find max (required)
2549 *max_address += *min_address;
2552 if (*min_address > *max_address)
2553 return ERROR_COMMAND_SYNTAX_ERROR;
2555 return ERROR_OK;
2558 COMMAND_HANDLER(handle_load_image_command)
2560 uint8_t *buffer;
2561 size_t buf_cnt;
2562 uint32_t image_size;
2563 uint32_t min_address = 0;
2564 uint32_t max_address = 0xffffffff;
2565 int i;
2566 struct image image;
2568 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2569 &image, &min_address, &max_address);
2570 if (ERROR_OK != retval)
2571 return retval;
2573 struct target *target = get_current_target(CMD_CTX);
2575 struct duration bench;
2576 duration_start(&bench);
2578 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2580 return ERROR_OK;
2583 image_size = 0x0;
2584 retval = ERROR_OK;
2585 for (i = 0; i < image.num_sections; i++)
2587 buffer = malloc(image.sections[i].size);
2588 if (buffer == NULL)
2590 command_print(CMD_CTX,
2591 "error allocating buffer for section (%d bytes)",
2592 (int)(image.sections[i].size));
2593 break;
2596 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2598 free(buffer);
2599 break;
2602 uint32_t offset = 0;
2603 uint32_t length = buf_cnt;
2605 /* DANGER!!! beware of unsigned comparision here!!! */
2607 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2608 (image.sections[i].base_address < max_address))
2610 if (image.sections[i].base_address < min_address)
2612 /* clip addresses below */
2613 offset += min_address-image.sections[i].base_address;
2614 length -= offset;
2617 if (image.sections[i].base_address + buf_cnt > max_address)
2619 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2622 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2624 free(buffer);
2625 break;
2627 image_size += length;
2628 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2629 (unsigned int)length,
2630 image.sections[i].base_address + offset);
2633 free(buffer);
2636 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2638 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2639 "in %fs (%0.3f KiB/s)", image_size,
2640 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2643 image_close(&image);
2645 return retval;
2649 COMMAND_HANDLER(handle_dump_image_command)
2651 struct fileio fileio;
2652 uint8_t buffer[560];
2653 int retval, retvaltemp;
2654 uint32_t address, size;
2655 struct duration bench;
2656 struct target *target = get_current_target(CMD_CTX);
2658 if (CMD_ARGC != 3)
2659 return ERROR_COMMAND_SYNTAX_ERROR;
2661 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2662 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2664 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2665 if (retval != ERROR_OK)
2666 return retval;
2668 duration_start(&bench);
2670 retval = ERROR_OK;
2671 while (size > 0)
2673 size_t size_written;
2674 uint32_t this_run_size = (size > 560) ? 560 : size;
2675 retval = target_read_buffer(target, address, this_run_size, buffer);
2676 if (retval != ERROR_OK)
2678 break;
2681 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2682 if (retval != ERROR_OK)
2684 break;
2687 size -= this_run_size;
2688 address += this_run_size;
2691 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2693 int filesize;
2694 retval = fileio_size(&fileio, &filesize);
2695 if (retval != ERROR_OK)
2696 return retval;
2697 command_print(CMD_CTX,
2698 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
2699 duration_elapsed(&bench), duration_kbps(&bench, filesize));
2702 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2703 return retvaltemp;
2705 return retval;
2708 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2710 uint8_t *buffer;
2711 size_t buf_cnt;
2712 uint32_t image_size;
2713 int i;
2714 int retval;
2715 uint32_t checksum = 0;
2716 uint32_t mem_checksum = 0;
2718 struct image image;
2720 struct target *target = get_current_target(CMD_CTX);
2722 if (CMD_ARGC < 1)
2724 return ERROR_COMMAND_SYNTAX_ERROR;
2727 if (!target)
2729 LOG_ERROR("no target selected");
2730 return ERROR_FAIL;
2733 struct duration bench;
2734 duration_start(&bench);
2736 if (CMD_ARGC >= 2)
2738 uint32_t addr;
2739 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2740 image.base_address = addr;
2741 image.base_address_set = 1;
2743 else
2745 image.base_address_set = 0;
2746 image.base_address = 0x0;
2749 image.start_address_set = 0;
2751 if ((retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL)) != ERROR_OK)
2753 return retval;
2756 image_size = 0x0;
2757 int diffs = 0;
2758 retval = ERROR_OK;
2759 for (i = 0; i < image.num_sections; i++)
2761 buffer = malloc(image.sections[i].size);
2762 if (buffer == NULL)
2764 command_print(CMD_CTX,
2765 "error allocating buffer for section (%d bytes)",
2766 (int)(image.sections[i].size));
2767 break;
2769 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2771 free(buffer);
2772 break;
2775 if (verify)
2777 /* calculate checksum of image */
2778 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
2779 if (retval != ERROR_OK)
2781 free(buffer);
2782 break;
2785 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2786 if (retval != ERROR_OK)
2788 free(buffer);
2789 break;
2792 if (checksum != mem_checksum)
2794 /* failed crc checksum, fall back to a binary compare */
2795 uint8_t *data;
2797 if (diffs == 0)
2799 LOG_ERROR("checksum mismatch - attempting binary compare");
2802 data = (uint8_t*)malloc(buf_cnt);
2804 /* Can we use 32bit word accesses? */
2805 int size = 1;
2806 int count = buf_cnt;
2807 if ((count % 4) == 0)
2809 size *= 4;
2810 count /= 4;
2812 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2813 if (retval == ERROR_OK)
2815 uint32_t t;
2816 for (t = 0; t < buf_cnt; t++)
2818 if (data[t] != buffer[t])
2820 command_print(CMD_CTX,
2821 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
2822 diffs,
2823 (unsigned)(t + image.sections[i].base_address),
2824 data[t],
2825 buffer[t]);
2826 if (diffs++ >= 127)
2828 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
2829 free(data);
2830 free(buffer);
2831 goto done;
2834 keep_alive();
2837 free(data);
2839 } else
2841 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
2842 image.sections[i].base_address,
2843 buf_cnt);
2846 free(buffer);
2847 image_size += buf_cnt;
2849 if (diffs > 0)
2851 command_print(CMD_CTX, "No more differences found.");
2853 done:
2854 if (diffs > 0)
2856 retval = ERROR_FAIL;
2858 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2860 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
2861 "in %fs (%0.3f KiB/s)", image_size,
2862 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2865 image_close(&image);
2867 return retval;
2870 COMMAND_HANDLER(handle_verify_image_command)
2872 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2875 COMMAND_HANDLER(handle_test_image_command)
2877 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2880 static int handle_bp_command_list(struct command_context *cmd_ctx)
2882 struct target *target = get_current_target(cmd_ctx);
2883 struct breakpoint *breakpoint = target->breakpoints;
2884 while (breakpoint)
2886 if (breakpoint->type == BKPT_SOFT)
2888 char* buf = buf_to_str(breakpoint->orig_instr,
2889 breakpoint->length, 16);
2890 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2891 breakpoint->address,
2892 breakpoint->length,
2893 breakpoint->set, buf);
2894 free(buf);
2896 else
2898 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2899 breakpoint->address,
2900 breakpoint->length, breakpoint->set);
2903 breakpoint = breakpoint->next;
2905 return ERROR_OK;
2908 static int handle_bp_command_set(struct command_context *cmd_ctx,
2909 uint32_t addr, uint32_t length, int hw)
2911 struct target *target = get_current_target(cmd_ctx);
2912 int retval = breakpoint_add(target, addr, length, hw);
2913 if (ERROR_OK == retval)
2914 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2915 else
2916 LOG_ERROR("Failure setting breakpoint");
2917 return retval;
2920 COMMAND_HANDLER(handle_bp_command)
2922 if (CMD_ARGC == 0)
2923 return handle_bp_command_list(CMD_CTX);
2925 if (CMD_ARGC < 2 || CMD_ARGC > 3)
2927 command_print(CMD_CTX, "usage: bp <address> <length> ['hw']");
2928 return ERROR_COMMAND_SYNTAX_ERROR;
2931 uint32_t addr;
2932 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2933 uint32_t length;
2934 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2936 int hw = BKPT_SOFT;
2937 if (CMD_ARGC == 3)
2939 if (strcmp(CMD_ARGV[2], "hw") == 0)
2940 hw = BKPT_HARD;
2941 else
2942 return ERROR_COMMAND_SYNTAX_ERROR;
2945 return handle_bp_command_set(CMD_CTX, addr, length, hw);
2948 COMMAND_HANDLER(handle_rbp_command)
2950 if (CMD_ARGC != 1)
2951 return ERROR_COMMAND_SYNTAX_ERROR;
2953 uint32_t addr;
2954 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2956 struct target *target = get_current_target(CMD_CTX);
2957 breakpoint_remove(target, addr);
2959 return ERROR_OK;
2962 COMMAND_HANDLER(handle_wp_command)
2964 struct target *target = get_current_target(CMD_CTX);
2966 if (CMD_ARGC == 0)
2968 struct watchpoint *watchpoint = target->watchpoints;
2970 while (watchpoint)
2972 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
2973 ", len: 0x%8.8" PRIx32
2974 ", r/w/a: %i, value: 0x%8.8" PRIx32
2975 ", mask: 0x%8.8" PRIx32,
2976 watchpoint->address,
2977 watchpoint->length,
2978 (int)watchpoint->rw,
2979 watchpoint->value,
2980 watchpoint->mask);
2981 watchpoint = watchpoint->next;
2983 return ERROR_OK;
2986 enum watchpoint_rw type = WPT_ACCESS;
2987 uint32_t addr = 0;
2988 uint32_t length = 0;
2989 uint32_t data_value = 0x0;
2990 uint32_t data_mask = 0xffffffff;
2992 switch (CMD_ARGC)
2994 case 5:
2995 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
2996 // fall through
2997 case 4:
2998 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
2999 // fall through
3000 case 3:
3001 switch (CMD_ARGV[2][0])
3003 case 'r':
3004 type = WPT_READ;
3005 break;
3006 case 'w':
3007 type = WPT_WRITE;
3008 break;
3009 case 'a':
3010 type = WPT_ACCESS;
3011 break;
3012 default:
3013 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3014 return ERROR_COMMAND_SYNTAX_ERROR;
3016 // fall through
3017 case 2:
3018 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3019 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3020 break;
3022 default:
3023 command_print(CMD_CTX, "usage: wp [address length "
3024 "[(r|w|a) [value [mask]]]]");
3025 return ERROR_COMMAND_SYNTAX_ERROR;
3028 int retval = watchpoint_add(target, addr, length, type,
3029 data_value, data_mask);
3030 if (ERROR_OK != retval)
3031 LOG_ERROR("Failure setting watchpoints");
3033 return retval;
3036 COMMAND_HANDLER(handle_rwp_command)
3038 if (CMD_ARGC != 1)
3039 return ERROR_COMMAND_SYNTAX_ERROR;
3041 uint32_t addr;
3042 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3044 struct target *target = get_current_target(CMD_CTX);
3045 watchpoint_remove(target, addr);
3047 return ERROR_OK;
3052 * Translate a virtual address to a physical address.
3054 * The low-level target implementation must have logged a detailed error
3055 * which is forwarded to telnet/GDB session.
3057 COMMAND_HANDLER(handle_virt2phys_command)
3059 if (CMD_ARGC != 1)
3060 return ERROR_COMMAND_SYNTAX_ERROR;
3062 uint32_t va;
3063 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3064 uint32_t pa;
3066 struct target *target = get_current_target(CMD_CTX);
3067 int retval = target->type->virt2phys(target, va, &pa);
3068 if (retval == ERROR_OK)
3069 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3071 return retval;
3074 static void writeData(FILE *f, const void *data, size_t len)
3076 size_t written = fwrite(data, 1, len, f);
3077 if (written != len)
3078 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3081 static void writeLong(FILE *f, int l)
3083 int i;
3084 for (i = 0; i < 4; i++)
3086 char c = (l >> (i*8))&0xff;
3087 writeData(f, &c, 1);
3092 static void writeString(FILE *f, char *s)
3094 writeData(f, s, strlen(s));
3097 /* Dump a gmon.out histogram file. */
3098 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3100 uint32_t i;
3101 FILE *f = fopen(filename, "w");
3102 if (f == NULL)
3103 return;
3104 writeString(f, "gmon");
3105 writeLong(f, 0x00000001); /* Version */
3106 writeLong(f, 0); /* padding */
3107 writeLong(f, 0); /* padding */
3108 writeLong(f, 0); /* padding */
3110 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3111 writeData(f, &zero, 1);
3113 /* figure out bucket size */
3114 uint32_t min = samples[0];
3115 uint32_t max = samples[0];
3116 for (i = 0; i < sampleNum; i++)
3118 if (min > samples[i])
3120 min = samples[i];
3122 if (max < samples[i])
3124 max = samples[i];
3128 int addressSpace = (max-min + 1);
3130 static const uint32_t maxBuckets = 16 * 1024; /* maximum buckets. */
3131 uint32_t length = addressSpace;
3132 if (length > maxBuckets)
3134 length = maxBuckets;
3136 int *buckets = malloc(sizeof(int)*length);
3137 if (buckets == NULL)
3139 fclose(f);
3140 return;
3142 memset(buckets, 0, sizeof(int)*length);
3143 for (i = 0; i < sampleNum;i++)
3145 uint32_t address = samples[i];
3146 long long a = address-min;
3147 long long b = length-1;
3148 long long c = addressSpace-1;
3149 int index_t = (a*b)/c; /* danger!!!! int32 overflows */
3150 buckets[index_t]++;
3153 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3154 writeLong(f, min); /* low_pc */
3155 writeLong(f, max); /* high_pc */
3156 writeLong(f, length); /* # of samples */
3157 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3158 writeString(f, "seconds");
3159 for (i = 0; i < (15-strlen("seconds")); i++)
3160 writeData(f, &zero, 1);
3161 writeString(f, "s");
3163 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3165 char *data = malloc(2*length);
3166 if (data != NULL)
3168 for (i = 0; i < length;i++)
3170 int val;
3171 val = buckets[i];
3172 if (val > 65535)
3174 val = 65535;
3176 data[i*2]=val&0xff;
3177 data[i*2 + 1]=(val >> 8)&0xff;
3179 free(buckets);
3180 writeData(f, data, length * 2);
3181 free(data);
3182 } else
3184 free(buckets);
3187 fclose(f);
3190 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3191 * which will be used as a random sampling of PC */
3192 COMMAND_HANDLER(handle_profile_command)
3194 struct target *target = get_current_target(CMD_CTX);
3195 struct timeval timeout, now;
3197 gettimeofday(&timeout, NULL);
3198 if (CMD_ARGC != 2)
3200 return ERROR_COMMAND_SYNTAX_ERROR;
3202 unsigned offset;
3203 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3205 timeval_add_time(&timeout, offset, 0);
3208 * @todo: Some cores let us sample the PC without the
3209 * annoying halt/resume step; for example, ARMv7 PCSR.
3210 * Provide a way to use that more efficient mechanism.
3213 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3215 static const int maxSample = 10000;
3216 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3217 if (samples == NULL)
3218 return ERROR_OK;
3220 int numSamples = 0;
3221 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3222 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3224 for (;;)
3226 int retval;
3227 target_poll(target);
3228 if (target->state == TARGET_HALTED)
3230 uint32_t t=*((uint32_t *)reg->value);
3231 samples[numSamples++]=t;
3232 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3233 target_poll(target);
3234 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3235 } else if (target->state == TARGET_RUNNING)
3237 /* We want to quickly sample the PC. */
3238 if ((retval = target_halt(target)) != ERROR_OK)
3240 free(samples);
3241 return retval;
3243 } else
3245 command_print(CMD_CTX, "Target not halted or running");
3246 retval = ERROR_OK;
3247 break;
3249 if (retval != ERROR_OK)
3251 break;
3254 gettimeofday(&now, NULL);
3255 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3257 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3258 if ((retval = target_poll(target)) != ERROR_OK)
3260 free(samples);
3261 return retval;
3263 if (target->state == TARGET_HALTED)
3265 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3267 if ((retval = target_poll(target)) != ERROR_OK)
3269 free(samples);
3270 return retval;
3272 writeGmon(samples, numSamples, CMD_ARGV[1]);
3273 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3274 break;
3277 free(samples);
3279 return ERROR_OK;
3282 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3284 char *namebuf;
3285 Jim_Obj *nameObjPtr, *valObjPtr;
3286 int result;
3288 namebuf = alloc_printf("%s(%d)", varname, idx);
3289 if (!namebuf)
3290 return JIM_ERR;
3292 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3293 valObjPtr = Jim_NewIntObj(interp, val);
3294 if (!nameObjPtr || !valObjPtr)
3296 free(namebuf);
3297 return JIM_ERR;
3300 Jim_IncrRefCount(nameObjPtr);
3301 Jim_IncrRefCount(valObjPtr);
3302 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3303 Jim_DecrRefCount(interp, nameObjPtr);
3304 Jim_DecrRefCount(interp, valObjPtr);
3305 free(namebuf);
3306 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3307 return result;
3310 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3312 struct command_context *context;
3313 struct target *target;
3315 context = current_command_context(interp);
3316 assert (context != NULL);
3318 target = get_current_target(context);
3319 if (target == NULL)
3321 LOG_ERROR("mem2array: no current target");
3322 return JIM_ERR;
3325 return target_mem2array(interp, target, argc-1, argv + 1);
3328 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3330 long l;
3331 uint32_t width;
3332 int len;
3333 uint32_t addr;
3334 uint32_t count;
3335 uint32_t v;
3336 const char *varname;
3337 int n, e, retval;
3338 uint32_t i;
3340 /* argv[1] = name of array to receive the data
3341 * argv[2] = desired width
3342 * argv[3] = memory address
3343 * argv[4] = count of times to read
3345 if (argc != 4) {
3346 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3347 return JIM_ERR;
3349 varname = Jim_GetString(argv[0], &len);
3350 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3352 e = Jim_GetLong(interp, argv[1], &l);
3353 width = l;
3354 if (e != JIM_OK) {
3355 return e;
3358 e = Jim_GetLong(interp, argv[2], &l);
3359 addr = l;
3360 if (e != JIM_OK) {
3361 return e;
3363 e = Jim_GetLong(interp, argv[3], &l);
3364 len = l;
3365 if (e != JIM_OK) {
3366 return e;
3368 switch (width) {
3369 case 8:
3370 width = 1;
3371 break;
3372 case 16:
3373 width = 2;
3374 break;
3375 case 32:
3376 width = 4;
3377 break;
3378 default:
3379 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3380 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3381 return JIM_ERR;
3383 if (len == 0) {
3384 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3385 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3386 return JIM_ERR;
3388 if ((addr + (len * width)) < addr) {
3389 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3390 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3391 return JIM_ERR;
3393 /* absurd transfer size? */
3394 if (len > 65536) {
3395 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3396 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3397 return JIM_ERR;
3400 if ((width == 1) ||
3401 ((width == 2) && ((addr & 1) == 0)) ||
3402 ((width == 4) && ((addr & 3) == 0))) {
3403 /* all is well */
3404 } else {
3405 char buf[100];
3406 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3407 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3408 addr,
3409 width);
3410 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3411 return JIM_ERR;
3414 /* Transfer loop */
3416 /* index counter */
3417 n = 0;
3419 size_t buffersize = 4096;
3420 uint8_t *buffer = malloc(buffersize);
3421 if (buffer == NULL)
3422 return JIM_ERR;
3424 /* assume ok */
3425 e = JIM_OK;
3426 while (len) {
3427 /* Slurp... in buffer size chunks */
3429 count = len; /* in objects.. */
3430 if (count > (buffersize/width)) {
3431 count = (buffersize/width);
3434 retval = target_read_memory(target, addr, width, count, buffer);
3435 if (retval != ERROR_OK) {
3436 /* BOO !*/
3437 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3438 (unsigned int)addr,
3439 (int)width,
3440 (int)count);
3441 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3442 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3443 e = JIM_ERR;
3444 len = 0;
3445 } else {
3446 v = 0; /* shut up gcc */
3447 for (i = 0 ;i < count ;i++, n++) {
3448 switch (width) {
3449 case 4:
3450 v = target_buffer_get_u32(target, &buffer[i*width]);
3451 break;
3452 case 2:
3453 v = target_buffer_get_u16(target, &buffer[i*width]);
3454 break;
3455 case 1:
3456 v = buffer[i] & 0x0ff;
3457 break;
3459 new_int_array_element(interp, varname, n, v);
3461 len -= count;
3465 free(buffer);
3467 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3469 return JIM_OK;
3472 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3474 char *namebuf;
3475 Jim_Obj *nameObjPtr, *valObjPtr;
3476 int result;
3477 long l;
3479 namebuf = alloc_printf("%s(%d)", varname, idx);
3480 if (!namebuf)
3481 return JIM_ERR;
3483 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3484 if (!nameObjPtr)
3486 free(namebuf);
3487 return JIM_ERR;
3490 Jim_IncrRefCount(nameObjPtr);
3491 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3492 Jim_DecrRefCount(interp, nameObjPtr);
3493 free(namebuf);
3494 if (valObjPtr == NULL)
3495 return JIM_ERR;
3497 result = Jim_GetLong(interp, valObjPtr, &l);
3498 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3499 *val = l;
3500 return result;
3503 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3505 struct command_context *context;
3506 struct target *target;
3508 context = current_command_context(interp);
3509 assert (context != NULL);
3511 target = get_current_target(context);
3512 if (target == NULL) {
3513 LOG_ERROR("array2mem: no current target");
3514 return JIM_ERR;
3517 return target_array2mem(interp,target, argc-1, argv + 1);
3520 static int target_array2mem(Jim_Interp *interp, struct target *target,
3521 int argc, Jim_Obj *const *argv)
3523 long l;
3524 uint32_t width;
3525 int len;
3526 uint32_t addr;
3527 uint32_t count;
3528 uint32_t v;
3529 const char *varname;
3530 int n, e, retval;
3531 uint32_t i;
3533 /* argv[1] = name of array to get the data
3534 * argv[2] = desired width
3535 * argv[3] = memory address
3536 * argv[4] = count to write
3538 if (argc != 4) {
3539 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3540 return JIM_ERR;
3542 varname = Jim_GetString(argv[0], &len);
3543 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3545 e = Jim_GetLong(interp, argv[1], &l);
3546 width = l;
3547 if (e != JIM_OK) {
3548 return e;
3551 e = Jim_GetLong(interp, argv[2], &l);
3552 addr = l;
3553 if (e != JIM_OK) {
3554 return e;
3556 e = Jim_GetLong(interp, argv[3], &l);
3557 len = l;
3558 if (e != JIM_OK) {
3559 return e;
3561 switch (width) {
3562 case 8:
3563 width = 1;
3564 break;
3565 case 16:
3566 width = 2;
3567 break;
3568 case 32:
3569 width = 4;
3570 break;
3571 default:
3572 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3573 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3574 return JIM_ERR;
3576 if (len == 0) {
3577 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3578 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3579 return JIM_ERR;
3581 if ((addr + (len * width)) < addr) {
3582 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3583 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3584 return JIM_ERR;
3586 /* absurd transfer size? */
3587 if (len > 65536) {
3588 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3589 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3590 return JIM_ERR;
3593 if ((width == 1) ||
3594 ((width == 2) && ((addr & 1) == 0)) ||
3595 ((width == 4) && ((addr & 3) == 0))) {
3596 /* all is well */
3597 } else {
3598 char buf[100];
3599 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3600 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3601 (unsigned int)addr,
3602 (int)width);
3603 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3604 return JIM_ERR;
3607 /* Transfer loop */
3609 /* index counter */
3610 n = 0;
3611 /* assume ok */
3612 e = JIM_OK;
3614 size_t buffersize = 4096;
3615 uint8_t *buffer = malloc(buffersize);
3616 if (buffer == NULL)
3617 return JIM_ERR;
3619 while (len) {
3620 /* Slurp... in buffer size chunks */
3622 count = len; /* in objects.. */
3623 if (count > (buffersize/width)) {
3624 count = (buffersize/width);
3627 v = 0; /* shut up gcc */
3628 for (i = 0 ;i < count ;i++, n++) {
3629 get_int_array_element(interp, varname, n, &v);
3630 switch (width) {
3631 case 4:
3632 target_buffer_set_u32(target, &buffer[i*width], v);
3633 break;
3634 case 2:
3635 target_buffer_set_u16(target, &buffer[i*width], v);
3636 break;
3637 case 1:
3638 buffer[i] = v & 0x0ff;
3639 break;
3642 len -= count;
3644 retval = target_write_memory(target, addr, width, count, buffer);
3645 if (retval != ERROR_OK) {
3646 /* BOO !*/
3647 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3648 (unsigned int)addr,
3649 (int)width,
3650 (int)count);
3651 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3652 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3653 e = JIM_ERR;
3654 len = 0;
3658 free(buffer);
3660 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3662 return JIM_OK;
3665 /* FIX? should we propagate errors here rather than printing them
3666 * and continuing?
3668 void target_handle_event(struct target *target, enum target_event e)
3670 struct target_event_action *teap;
3672 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3673 if (teap->event == e) {
3674 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3675 target->target_number,
3676 target_name(target),
3677 target_type_name(target),
3679 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3680 Jim_GetString(teap->body, NULL));
3681 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK)
3683 Jim_MakeErrorMessage(teap->interp);
3684 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
3691 * Returns true only if the target has a handler for the specified event.
3693 bool target_has_event_action(struct target *target, enum target_event event)
3695 struct target_event_action *teap;
3697 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3698 if (teap->event == event)
3699 return true;
3701 return false;
3704 enum target_cfg_param {
3705 TCFG_TYPE,
3706 TCFG_EVENT,
3707 TCFG_WORK_AREA_VIRT,
3708 TCFG_WORK_AREA_PHYS,
3709 TCFG_WORK_AREA_SIZE,
3710 TCFG_WORK_AREA_BACKUP,
3711 TCFG_ENDIAN,
3712 TCFG_VARIANT,
3713 TCFG_COREID,
3714 TCFG_CHAIN_POSITION,
3715 TCFG_DBGBASE,
3716 TCFG_RTOS,
3719 static Jim_Nvp nvp_config_opts[] = {
3720 { .name = "-type", .value = TCFG_TYPE },
3721 { .name = "-event", .value = TCFG_EVENT },
3722 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3723 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3724 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3725 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3726 { .name = "-endian" , .value = TCFG_ENDIAN },
3727 { .name = "-variant", .value = TCFG_VARIANT },
3728 { .name = "-coreid", .value = TCFG_COREID },
3729 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3730 { .name = "-dbgbase", .value = TCFG_DBGBASE },
3731 { .name = "-rtos", .value = TCFG_RTOS },
3732 { .name = NULL, .value = -1 }
3735 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3737 Jim_Nvp *n;
3738 Jim_Obj *o;
3739 jim_wide w;
3740 char *cp;
3741 int e;
3743 /* parse config or cget options ... */
3744 while (goi->argc > 0) {
3745 Jim_SetEmptyResult(goi->interp);
3746 /* Jim_GetOpt_Debug(goi); */
3748 if (target->type->target_jim_configure) {
3749 /* target defines a configure function */
3750 /* target gets first dibs on parameters */
3751 e = (*(target->type->target_jim_configure))(target, goi);
3752 if (e == JIM_OK) {
3753 /* more? */
3754 continue;
3756 if (e == JIM_ERR) {
3757 /* An error */
3758 return e;
3760 /* otherwise we 'continue' below */
3762 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3763 if (e != JIM_OK) {
3764 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3765 return e;
3767 switch (n->value) {
3768 case TCFG_TYPE:
3769 /* not setable */
3770 if (goi->isconfigure) {
3771 Jim_SetResultFormatted(goi->interp,
3772 "not settable: %s", n->name);
3773 return JIM_ERR;
3774 } else {
3775 no_params:
3776 if (goi->argc != 0) {
3777 Jim_WrongNumArgs(goi->interp,
3778 goi->argc, goi->argv,
3779 "NO PARAMS");
3780 return JIM_ERR;
3783 Jim_SetResultString(goi->interp,
3784 target_type_name(target), -1);
3785 /* loop for more */
3786 break;
3787 case TCFG_EVENT:
3788 if (goi->argc == 0) {
3789 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3790 return JIM_ERR;
3793 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3794 if (e != JIM_OK) {
3795 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3796 return e;
3799 if (goi->isconfigure) {
3800 if (goi->argc != 1) {
3801 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3802 return JIM_ERR;
3804 } else {
3805 if (goi->argc != 0) {
3806 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3807 return JIM_ERR;
3812 struct target_event_action *teap;
3814 teap = target->event_action;
3815 /* replace existing? */
3816 while (teap) {
3817 if (teap->event == (enum target_event)n->value) {
3818 break;
3820 teap = teap->next;
3823 if (goi->isconfigure) {
3824 bool replace = true;
3825 if (teap == NULL) {
3826 /* create new */
3827 teap = calloc(1, sizeof(*teap));
3828 replace = false;
3830 teap->event = n->value;
3831 teap->interp = goi->interp;
3832 Jim_GetOpt_Obj(goi, &o);
3833 if (teap->body) {
3834 Jim_DecrRefCount(teap->interp, teap->body);
3836 teap->body = Jim_DuplicateObj(goi->interp, o);
3838 * FIXME:
3839 * Tcl/TK - "tk events" have a nice feature.
3840 * See the "BIND" command.
3841 * We should support that here.
3842 * You can specify %X and %Y in the event code.
3843 * The idea is: %T - target name.
3844 * The idea is: %N - target number
3845 * The idea is: %E - event name.
3847 Jim_IncrRefCount(teap->body);
3849 if (!replace)
3851 /* add to head of event list */
3852 teap->next = target->event_action;
3853 target->event_action = teap;
3855 Jim_SetEmptyResult(goi->interp);
3856 } else {
3857 /* get */
3858 if (teap == NULL) {
3859 Jim_SetEmptyResult(goi->interp);
3860 } else {
3861 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3865 /* loop for more */
3866 break;
3868 case TCFG_WORK_AREA_VIRT:
3869 if (goi->isconfigure) {
3870 target_free_all_working_areas(target);
3871 e = Jim_GetOpt_Wide(goi, &w);
3872 if (e != JIM_OK) {
3873 return e;
3875 target->working_area_virt = w;
3876 target->working_area_virt_spec = true;
3877 } else {
3878 if (goi->argc != 0) {
3879 goto no_params;
3882 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3883 /* loop for more */
3884 break;
3886 case TCFG_WORK_AREA_PHYS:
3887 if (goi->isconfigure) {
3888 target_free_all_working_areas(target);
3889 e = Jim_GetOpt_Wide(goi, &w);
3890 if (e != JIM_OK) {
3891 return e;
3893 target->working_area_phys = w;
3894 target->working_area_phys_spec = true;
3895 } else {
3896 if (goi->argc != 0) {
3897 goto no_params;
3900 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3901 /* loop for more */
3902 break;
3904 case TCFG_WORK_AREA_SIZE:
3905 if (goi->isconfigure) {
3906 target_free_all_working_areas(target);
3907 e = Jim_GetOpt_Wide(goi, &w);
3908 if (e != JIM_OK) {
3909 return e;
3911 target->working_area_size = w;
3912 } else {
3913 if (goi->argc != 0) {
3914 goto no_params;
3917 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3918 /* loop for more */
3919 break;
3921 case TCFG_WORK_AREA_BACKUP:
3922 if (goi->isconfigure) {
3923 target_free_all_working_areas(target);
3924 e = Jim_GetOpt_Wide(goi, &w);
3925 if (e != JIM_OK) {
3926 return e;
3928 /* make this exactly 1 or 0 */
3929 target->backup_working_area = (!!w);
3930 } else {
3931 if (goi->argc != 0) {
3932 goto no_params;
3935 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3936 /* loop for more e*/
3937 break;
3940 case TCFG_ENDIAN:
3941 if (goi->isconfigure) {
3942 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3943 if (e != JIM_OK) {
3944 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3945 return e;
3947 target->endianness = n->value;
3948 } else {
3949 if (goi->argc != 0) {
3950 goto no_params;
3953 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3954 if (n->name == NULL) {
3955 target->endianness = TARGET_LITTLE_ENDIAN;
3956 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3958 Jim_SetResultString(goi->interp, n->name, -1);
3959 /* loop for more */
3960 break;
3962 case TCFG_VARIANT:
3963 if (goi->isconfigure) {
3964 if (goi->argc < 1) {
3965 Jim_SetResultFormatted(goi->interp,
3966 "%s ?STRING?",
3967 n->name);
3968 return JIM_ERR;
3970 if (target->variant) {
3971 free((void *)(target->variant));
3973 e = Jim_GetOpt_String(goi, &cp, NULL);
3974 target->variant = strdup(cp);
3975 } else {
3976 if (goi->argc != 0) {
3977 goto no_params;
3980 Jim_SetResultString(goi->interp, target->variant,-1);
3981 /* loop for more */
3982 break;
3984 case TCFG_COREID:
3985 if (goi->isconfigure) {
3986 e = Jim_GetOpt_Wide(goi, &w);
3987 if (e != JIM_OK) {
3988 return e;
3990 target->coreid = (int32_t)w;
3991 } else {
3992 if (goi->argc != 0) {
3993 goto no_params;
3996 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3997 /* loop for more */
3998 break;
4000 case TCFG_CHAIN_POSITION:
4001 if (goi->isconfigure) {
4002 Jim_Obj *o_t;
4003 struct jtag_tap *tap;
4004 target_free_all_working_areas(target);
4005 e = Jim_GetOpt_Obj(goi, &o_t);
4006 if (e != JIM_OK) {
4007 return e;
4009 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4010 if (tap == NULL) {
4011 return JIM_ERR;
4013 /* make this exactly 1 or 0 */
4014 target->tap = tap;
4015 } else {
4016 if (goi->argc != 0) {
4017 goto no_params;
4020 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4021 /* loop for more e*/
4022 break;
4023 case TCFG_DBGBASE:
4024 if (goi->isconfigure) {
4025 e = Jim_GetOpt_Wide(goi, &w);
4026 if (e != JIM_OK) {
4027 return e;
4029 target->dbgbase = (uint32_t)w;
4030 target->dbgbase_set = true;
4031 } else {
4032 if (goi->argc != 0) {
4033 goto no_params;
4036 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4037 /* loop for more */
4038 break;
4040 case TCFG_RTOS:
4041 /* RTOS */
4043 int result = rtos_create( goi, target );
4044 if ( result != JIM_OK )
4046 return result;
4049 /* loop for more */
4050 break;
4052 } /* while (goi->argc) */
4055 /* done - we return */
4056 return JIM_OK;
4059 static int
4060 jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4062 Jim_GetOptInfo goi;
4064 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4065 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4066 int need_args = 1 + goi.isconfigure;
4067 if (goi.argc < need_args)
4069 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4070 goi.isconfigure
4071 ? "missing: -option VALUE ..."
4072 : "missing: -option ...");
4073 return JIM_ERR;
4075 struct target *target = Jim_CmdPrivData(goi.interp);
4076 return target_configure(&goi, target);
4079 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4081 const char *cmd_name = Jim_GetString(argv[0], NULL);
4083 Jim_GetOptInfo goi;
4084 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4086 if (goi.argc < 2 || goi.argc > 4)
4088 Jim_SetResultFormatted(goi.interp,
4089 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4090 return JIM_ERR;
4093 target_write_fn fn;
4094 fn = target_write_memory_fast;
4096 int e;
4097 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4099 /* consume it */
4100 struct Jim_Obj *obj;
4101 e = Jim_GetOpt_Obj(&goi, &obj);
4102 if (e != JIM_OK)
4103 return e;
4105 fn = target_write_phys_memory;
4108 jim_wide a;
4109 e = Jim_GetOpt_Wide(&goi, &a);
4110 if (e != JIM_OK)
4111 return e;
4113 jim_wide b;
4114 e = Jim_GetOpt_Wide(&goi, &b);
4115 if (e != JIM_OK)
4116 return e;
4118 jim_wide c = 1;
4119 if (goi.argc == 1)
4121 e = Jim_GetOpt_Wide(&goi, &c);
4122 if (e != JIM_OK)
4123 return e;
4126 /* all args must be consumed */
4127 if (goi.argc != 0)
4129 return JIM_ERR;
4132 struct target *target = Jim_CmdPrivData(goi.interp);
4133 unsigned data_size;
4134 if (strcasecmp(cmd_name, "mww") == 0) {
4135 data_size = 4;
4137 else if (strcasecmp(cmd_name, "mwh") == 0) {
4138 data_size = 2;
4140 else if (strcasecmp(cmd_name, "mwb") == 0) {
4141 data_size = 1;
4142 } else {
4143 LOG_ERROR("command '%s' unknown: ", cmd_name);
4144 return JIM_ERR;
4147 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4150 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4152 const char *cmd_name = Jim_GetString(argv[0], NULL);
4154 Jim_GetOptInfo goi;
4155 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4157 if ((goi.argc < 1) || (goi.argc > 3))
4159 Jim_SetResultFormatted(goi.interp,
4160 "usage: %s [phys] <address> [<count>]", cmd_name);
4161 return JIM_ERR;
4164 int (*fn)(struct target *target,
4165 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4166 fn=target_read_memory;
4168 int e;
4169 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4171 /* consume it */
4172 struct Jim_Obj *obj;
4173 e = Jim_GetOpt_Obj(&goi, &obj);
4174 if (e != JIM_OK)
4175 return e;
4177 fn=target_read_phys_memory;
4180 jim_wide a;
4181 e = Jim_GetOpt_Wide(&goi, &a);
4182 if (e != JIM_OK) {
4183 return JIM_ERR;
4185 jim_wide c;
4186 if (goi.argc == 1) {
4187 e = Jim_GetOpt_Wide(&goi, &c);
4188 if (e != JIM_OK) {
4189 return JIM_ERR;
4191 } else {
4192 c = 1;
4195 /* all args must be consumed */
4196 if (goi.argc != 0)
4198 return JIM_ERR;
4201 jim_wide b = 1; /* shut up gcc */
4202 if (strcasecmp(cmd_name, "mdw") == 0)
4203 b = 4;
4204 else if (strcasecmp(cmd_name, "mdh") == 0)
4205 b = 2;
4206 else if (strcasecmp(cmd_name, "mdb") == 0)
4207 b = 1;
4208 else {
4209 LOG_ERROR("command '%s' unknown: ", cmd_name);
4210 return JIM_ERR;
4213 /* convert count to "bytes" */
4214 c = c * b;
4216 struct target *target = Jim_CmdPrivData(goi.interp);
4217 uint8_t target_buf[32];
4218 jim_wide x, y, z;
4219 while (c > 0) {
4220 y = c;
4221 if (y > 16) {
4222 y = 16;
4224 e = fn(target, a, b, y / b, target_buf);
4225 if (e != ERROR_OK) {
4226 char tmp[10];
4227 snprintf(tmp, sizeof(tmp), "%08lx", (long)a);
4228 Jim_SetResultFormatted(interp, "error reading target @ 0x%s", tmp);
4229 return JIM_ERR;
4232 command_print(NULL, "0x%08x ", (int)(a));
4233 switch (b) {
4234 case 4:
4235 for (x = 0; x < 16 && x < y; x += 4)
4237 z = target_buffer_get_u32(target, &(target_buf[ x ]));
4238 command_print(NULL, "%08x ", (int)(z));
4240 for (; (x < 16) ; x += 4) {
4241 command_print(NULL, " ");
4243 break;
4244 case 2:
4245 for (x = 0; x < 16 && x < y; x += 2)
4247 z = target_buffer_get_u16(target, &(target_buf[ x ]));
4248 command_print(NULL, "%04x ", (int)(z));
4250 for (; (x < 16) ; x += 2) {
4251 command_print(NULL, " ");
4253 break;
4254 case 1:
4255 default:
4256 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4257 z = target_buffer_get_u8(target, &(target_buf[ x ]));
4258 command_print(NULL, "%02x ", (int)(z));
4260 for (; (x < 16) ; x += 1) {
4261 command_print(NULL, " ");
4263 break;
4265 /* ascii-ify the bytes */
4266 for (x = 0 ; x < y ; x++) {
4267 if ((target_buf[x] >= 0x20) &&
4268 (target_buf[x] <= 0x7e)) {
4269 /* good */
4270 } else {
4271 /* smack it */
4272 target_buf[x] = '.';
4275 /* space pad */
4276 while (x < 16) {
4277 target_buf[x] = ' ';
4278 x++;
4280 /* terminate */
4281 target_buf[16] = 0;
4282 /* print - with a newline */
4283 command_print(NULL, "%s\n", target_buf);
4284 /* NEXT... */
4285 c -= 16;
4286 a += 16;
4288 return JIM_OK;
4291 static int jim_target_mem2array(Jim_Interp *interp,
4292 int argc, Jim_Obj *const *argv)
4294 struct target *target = Jim_CmdPrivData(interp);
4295 return target_mem2array(interp, target, argc - 1, argv + 1);
4298 static int jim_target_array2mem(Jim_Interp *interp,
4299 int argc, Jim_Obj *const *argv)
4301 struct target *target = Jim_CmdPrivData(interp);
4302 return target_array2mem(interp, target, argc - 1, argv + 1);
4305 static int jim_target_tap_disabled(Jim_Interp *interp)
4307 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4308 return JIM_ERR;
4311 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4313 if (argc != 1)
4315 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4316 return JIM_ERR;
4318 struct target *target = Jim_CmdPrivData(interp);
4319 if (!target->tap->enabled)
4320 return jim_target_tap_disabled(interp);
4322 int e = target->type->examine(target);
4323 if (e != ERROR_OK)
4325 return JIM_ERR;
4327 return JIM_OK;
4330 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4332 if (argc != 1)
4334 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4335 return JIM_ERR;
4337 struct target *target = Jim_CmdPrivData(interp);
4339 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4340 return JIM_ERR;
4342 return JIM_OK;
4345 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4347 if (argc != 1)
4349 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4350 return JIM_ERR;
4352 struct target *target = Jim_CmdPrivData(interp);
4353 if (!target->tap->enabled)
4354 return jim_target_tap_disabled(interp);
4356 int e;
4357 if (!(target_was_examined(target))) {
4358 e = ERROR_TARGET_NOT_EXAMINED;
4359 } else {
4360 e = target->type->poll(target);
4362 if (e != ERROR_OK)
4364 return JIM_ERR;
4366 return JIM_OK;
4369 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4371 Jim_GetOptInfo goi;
4372 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4374 if (goi.argc != 2)
4376 Jim_WrongNumArgs(interp, 0, argv,
4377 "([tT]|[fF]|assert|deassert) BOOL");
4378 return JIM_ERR;
4381 Jim_Nvp *n;
4382 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4383 if (e != JIM_OK)
4385 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4386 return e;
4388 /* the halt or not param */
4389 jim_wide a;
4390 e = Jim_GetOpt_Wide(&goi, &a);
4391 if (e != JIM_OK)
4392 return e;
4394 struct target *target = Jim_CmdPrivData(goi.interp);
4395 if (!target->tap->enabled)
4396 return jim_target_tap_disabled(interp);
4397 if (!(target_was_examined(target)))
4399 LOG_ERROR("Target not examined yet");
4400 return ERROR_TARGET_NOT_EXAMINED;
4402 if (!target->type->assert_reset || !target->type->deassert_reset)
4404 Jim_SetResultFormatted(interp,
4405 "No target-specific reset for %s",
4406 target_name(target));
4407 return JIM_ERR;
4409 /* determine if we should halt or not. */
4410 target->reset_halt = !!a;
4411 /* When this happens - all workareas are invalid. */
4412 target_free_all_working_areas_restore(target, 0);
4414 /* do the assert */
4415 if (n->value == NVP_ASSERT) {
4416 e = target->type->assert_reset(target);
4417 } else {
4418 e = target->type->deassert_reset(target);
4420 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4423 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4425 if (argc != 1) {
4426 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4427 return JIM_ERR;
4429 struct target *target = Jim_CmdPrivData(interp);
4430 if (!target->tap->enabled)
4431 return jim_target_tap_disabled(interp);
4432 int e = target->type->halt(target);
4433 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4436 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4438 Jim_GetOptInfo goi;
4439 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4441 /* params: <name> statename timeoutmsecs */
4442 if (goi.argc != 2)
4444 const char *cmd_name = Jim_GetString(argv[0], NULL);
4445 Jim_SetResultFormatted(goi.interp,
4446 "%s <state_name> <timeout_in_msec>", cmd_name);
4447 return JIM_ERR;
4450 Jim_Nvp *n;
4451 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4452 if (e != JIM_OK) {
4453 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4454 return e;
4456 jim_wide a;
4457 e = Jim_GetOpt_Wide(&goi, &a);
4458 if (e != JIM_OK) {
4459 return e;
4461 struct target *target = Jim_CmdPrivData(interp);
4462 if (!target->tap->enabled)
4463 return jim_target_tap_disabled(interp);
4465 e = target_wait_state(target, n->value, a);
4466 if (e != ERROR_OK)
4468 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4469 Jim_SetResultFormatted(goi.interp,
4470 "target: %s wait %s fails (%#s) %s",
4471 target_name(target), n->name,
4472 eObj, target_strerror_safe(e));
4473 Jim_FreeNewObj(interp, eObj);
4474 return JIM_ERR;
4476 return JIM_OK;
4478 /* List for human, Events defined for this target.
4479 * scripts/programs should use 'name cget -event NAME'
4481 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4483 struct command_context *cmd_ctx = current_command_context(interp);
4484 assert (cmd_ctx != NULL);
4486 struct target *target = Jim_CmdPrivData(interp);
4487 struct target_event_action *teap = target->event_action;
4488 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4489 target->target_number,
4490 target_name(target));
4491 command_print(cmd_ctx, "%-25s | Body", "Event");
4492 command_print(cmd_ctx, "------------------------- | "
4493 "----------------------------------------");
4494 while (teap)
4496 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4497 command_print(cmd_ctx, "%-25s | %s",
4498 opt->name, Jim_GetString(teap->body, NULL));
4499 teap = teap->next;
4501 command_print(cmd_ctx, "***END***");
4502 return JIM_OK;
4504 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4506 if (argc != 1)
4508 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4509 return JIM_ERR;
4511 struct target *target = Jim_CmdPrivData(interp);
4512 Jim_SetResultString(interp, target_state_name(target), -1);
4513 return JIM_OK;
4515 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4517 Jim_GetOptInfo goi;
4518 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4519 if (goi.argc != 1)
4521 const char *cmd_name = Jim_GetString(argv[0], NULL);
4522 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4523 return JIM_ERR;
4525 Jim_Nvp *n;
4526 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4527 if (e != JIM_OK)
4529 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4530 return e;
4532 struct target *target = Jim_CmdPrivData(interp);
4533 target_handle_event(target, n->value);
4534 return JIM_OK;
4537 static const struct command_registration target_instance_command_handlers[] = {
4539 .name = "configure",
4540 .mode = COMMAND_CONFIG,
4541 .jim_handler = jim_target_configure,
4542 .help = "configure a new target for use",
4543 .usage = "[target_attribute ...]",
4546 .name = "cget",
4547 .mode = COMMAND_ANY,
4548 .jim_handler = jim_target_configure,
4549 .help = "returns the specified target attribute",
4550 .usage = "target_attribute",
4553 .name = "mww",
4554 .mode = COMMAND_EXEC,
4555 .jim_handler = jim_target_mw,
4556 .help = "Write 32-bit word(s) to target memory",
4557 .usage = "address data [count]",
4560 .name = "mwh",
4561 .mode = COMMAND_EXEC,
4562 .jim_handler = jim_target_mw,
4563 .help = "Write 16-bit half-word(s) to target memory",
4564 .usage = "address data [count]",
4567 .name = "mwb",
4568 .mode = COMMAND_EXEC,
4569 .jim_handler = jim_target_mw,
4570 .help = "Write byte(s) to target memory",
4571 .usage = "address data [count]",
4574 .name = "mdw",
4575 .mode = COMMAND_EXEC,
4576 .jim_handler = jim_target_md,
4577 .help = "Display target memory as 32-bit words",
4578 .usage = "address [count]",
4581 .name = "mdh",
4582 .mode = COMMAND_EXEC,
4583 .jim_handler = jim_target_md,
4584 .help = "Display target memory as 16-bit half-words",
4585 .usage = "address [count]",
4588 .name = "mdb",
4589 .mode = COMMAND_EXEC,
4590 .jim_handler = jim_target_md,
4591 .help = "Display target memory as 8-bit bytes",
4592 .usage = "address [count]",
4595 .name = "array2mem",
4596 .mode = COMMAND_EXEC,
4597 .jim_handler = jim_target_array2mem,
4598 .help = "Writes Tcl array of 8/16/32 bit numbers "
4599 "to target memory",
4600 .usage = "arrayname bitwidth address count",
4603 .name = "mem2array",
4604 .mode = COMMAND_EXEC,
4605 .jim_handler = jim_target_mem2array,
4606 .help = "Loads Tcl array of 8/16/32 bit numbers "
4607 "from target memory",
4608 .usage = "arrayname bitwidth address count",
4611 .name = "eventlist",
4612 .mode = COMMAND_EXEC,
4613 .jim_handler = jim_target_event_list,
4614 .help = "displays a table of events defined for this target",
4617 .name = "curstate",
4618 .mode = COMMAND_EXEC,
4619 .jim_handler = jim_target_current_state,
4620 .help = "displays the current state of this target",
4623 .name = "arp_examine",
4624 .mode = COMMAND_EXEC,
4625 .jim_handler = jim_target_examine,
4626 .help = "used internally for reset processing",
4629 .name = "arp_halt_gdb",
4630 .mode = COMMAND_EXEC,
4631 .jim_handler = jim_target_halt_gdb,
4632 .help = "used internally for reset processing to halt GDB",
4635 .name = "arp_poll",
4636 .mode = COMMAND_EXEC,
4637 .jim_handler = jim_target_poll,
4638 .help = "used internally for reset processing",
4641 .name = "arp_reset",
4642 .mode = COMMAND_EXEC,
4643 .jim_handler = jim_target_reset,
4644 .help = "used internally for reset processing",
4647 .name = "arp_halt",
4648 .mode = COMMAND_EXEC,
4649 .jim_handler = jim_target_halt,
4650 .help = "used internally for reset processing",
4653 .name = "arp_waitstate",
4654 .mode = COMMAND_EXEC,
4655 .jim_handler = jim_target_wait_state,
4656 .help = "used internally for reset processing",
4659 .name = "invoke-event",
4660 .mode = COMMAND_EXEC,
4661 .jim_handler = jim_target_invoke_event,
4662 .help = "invoke handler for specified event",
4663 .usage = "event_name",
4665 COMMAND_REGISTRATION_DONE
4668 static int target_create(Jim_GetOptInfo *goi)
4670 Jim_Obj *new_cmd;
4671 Jim_Cmd *cmd;
4672 const char *cp;
4673 char *cp2;
4674 int e;
4675 int x;
4676 struct target *target;
4677 struct command_context *cmd_ctx;
4679 cmd_ctx = current_command_context(goi->interp);
4680 assert (cmd_ctx != NULL);
4682 if (goi->argc < 3) {
4683 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4684 return JIM_ERR;
4687 /* COMMAND */
4688 Jim_GetOpt_Obj(goi, &new_cmd);
4689 /* does this command exist? */
4690 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4691 if (cmd) {
4692 cp = Jim_GetString(new_cmd, NULL);
4693 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
4694 return JIM_ERR;
4697 /* TYPE */
4698 e = Jim_GetOpt_String(goi, &cp2, NULL);
4699 cp = cp2;
4700 /* now does target type exist */
4701 for (x = 0 ; target_types[x] ; x++) {
4702 if (0 == strcmp(cp, target_types[x]->name)) {
4703 /* found */
4704 break;
4707 if (target_types[x] == NULL) {
4708 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
4709 for (x = 0 ; target_types[x] ; x++) {
4710 if (target_types[x + 1]) {
4711 Jim_AppendStrings(goi->interp,
4712 Jim_GetResult(goi->interp),
4713 target_types[x]->name,
4714 ", ", NULL);
4715 } else {
4716 Jim_AppendStrings(goi->interp,
4717 Jim_GetResult(goi->interp),
4718 " or ",
4719 target_types[x]->name,NULL);
4722 return JIM_ERR;
4725 /* Create it */
4726 target = calloc(1,sizeof(struct target));
4727 /* set target number */
4728 target->target_number = new_target_number();
4730 /* allocate memory for each unique target type */
4731 target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4733 memcpy(target->type, target_types[x], sizeof(struct target_type));
4735 /* will be set by "-endian" */
4736 target->endianness = TARGET_ENDIAN_UNKNOWN;
4738 /* default to first core, override with -coreid */
4739 target->coreid = 0;
4741 target->working_area = 0x0;
4742 target->working_area_size = 0x0;
4743 target->working_areas = NULL;
4744 target->backup_working_area = 0;
4746 target->state = TARGET_UNKNOWN;
4747 target->debug_reason = DBG_REASON_UNDEFINED;
4748 target->reg_cache = NULL;
4749 target->breakpoints = NULL;
4750 target->watchpoints = NULL;
4751 target->next = NULL;
4752 target->arch_info = NULL;
4754 target->display = 1;
4756 target->halt_issued = false;
4758 /* initialize trace information */
4759 target->trace_info = malloc(sizeof(struct trace));
4760 target->trace_info->num_trace_points = 0;
4761 target->trace_info->trace_points_size = 0;
4762 target->trace_info->trace_points = NULL;
4763 target->trace_info->trace_history_size = 0;
4764 target->trace_info->trace_history = NULL;
4765 target->trace_info->trace_history_pos = 0;
4766 target->trace_info->trace_history_overflowed = 0;
4768 target->dbgmsg = NULL;
4769 target->dbg_msg_enabled = 0;
4771 target->endianness = TARGET_ENDIAN_UNKNOWN;
4773 target->rtos = NULL;
4774 target->rtos_auto_detect = false;
4776 /* Do the rest as "configure" options */
4777 goi->isconfigure = 1;
4778 e = target_configure(goi, target);
4780 if (target->tap == NULL)
4782 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4783 e = JIM_ERR;
4786 if (e != JIM_OK) {
4787 free(target->type);
4788 free(target);
4789 return e;
4792 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4793 /* default endian to little if not specified */
4794 target->endianness = TARGET_LITTLE_ENDIAN;
4797 /* incase variant is not set */
4798 if (!target->variant)
4799 target->variant = strdup("");
4801 cp = Jim_GetString(new_cmd, NULL);
4802 target->cmd_name = strdup(cp);
4804 /* create the target specific commands */
4805 if (target->type->commands) {
4806 e = register_commands(cmd_ctx, NULL, target->type->commands);
4807 if (ERROR_OK != e)
4808 LOG_ERROR("unable to register '%s' commands", cp);
4810 if (target->type->target_create) {
4811 (*(target->type->target_create))(target, goi->interp);
4814 /* append to end of list */
4816 struct target **tpp;
4817 tpp = &(all_targets);
4818 while (*tpp) {
4819 tpp = &((*tpp)->next);
4821 *tpp = target;
4824 /* now - create the new target name command */
4825 const const struct command_registration target_subcommands[] = {
4827 .chain = target_instance_command_handlers,
4830 .chain = target->type->commands,
4832 COMMAND_REGISTRATION_DONE
4834 const const struct command_registration target_commands[] = {
4836 .name = cp,
4837 .mode = COMMAND_ANY,
4838 .help = "target command group",
4839 .chain = target_subcommands,
4841 COMMAND_REGISTRATION_DONE
4843 e = register_commands(cmd_ctx, NULL, target_commands);
4844 if (ERROR_OK != e)
4845 return JIM_ERR;
4847 struct command *c = command_find_in_context(cmd_ctx, cp);
4848 assert(c);
4849 command_set_handler_data(c, target);
4851 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
4854 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4856 if (argc != 1)
4858 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4859 return JIM_ERR;
4861 struct command_context *cmd_ctx = current_command_context(interp);
4862 assert (cmd_ctx != NULL);
4864 Jim_SetResultString(interp, get_current_target(cmd_ctx)->cmd_name, -1);
4865 return JIM_OK;
4868 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4870 if (argc != 1)
4872 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4873 return JIM_ERR;
4875 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4876 for (unsigned x = 0; NULL != target_types[x]; x++)
4878 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4879 Jim_NewStringObj(interp, target_types[x]->name, -1));
4881 return JIM_OK;
4884 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4886 if (argc != 1)
4888 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4889 return JIM_ERR;
4891 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4892 struct target *target = all_targets;
4893 while (target)
4895 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4896 Jim_NewStringObj(interp, target_name(target), -1));
4897 target = target->next;
4899 return JIM_OK;
4902 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4904 int i;
4905 const char *targetname;
4906 int retval,len;
4907 struct target *target;
4908 struct target_list *head, *curr, *new;
4909 curr = (struct target_list*) NULL;
4910 head = (struct target_list*) NULL;
4911 new = (struct target_list*) NULL;
4913 retval = 0;
4914 LOG_DEBUG("%d",argc);
4915 /* argv[1] = target to associate in smp
4916 * argv[2] = target to assoicate in smp
4917 * argv[3] ...
4920 for(i=1;i<argc;i++)
4923 targetname = Jim_GetString(argv[i], &len);
4924 target = get_target(targetname);
4925 LOG_DEBUG("%s ",targetname);
4926 if (target)
4928 new=malloc(sizeof(struct target_list));
4929 new->target = target;
4930 new->next = (struct target_list*)NULL;
4931 if (head == (struct target_list*)NULL)
4933 head = new;
4934 curr = head;
4936 else
4938 curr->next = new;
4939 curr = new;
4943 /* now parse the list of cpu and put the target in smp mode*/
4944 curr=head;
4946 while(curr!=(struct target_list *)NULL)
4948 target=curr->target;
4949 target->smp = 1;
4950 target->head = head;
4951 curr=curr->next;
4953 return retval;
4957 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4959 Jim_GetOptInfo goi;
4960 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4961 if (goi.argc < 3)
4963 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4964 "<name> <target_type> [<target_options> ...]");
4965 return JIM_ERR;
4967 return target_create(&goi);
4970 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4972 Jim_GetOptInfo goi;
4973 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4975 /* It's OK to remove this mechanism sometime after August 2010 or so */
4976 LOG_WARNING("don't use numbers as target identifiers; use names");
4977 if (goi.argc != 1)
4979 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
4980 return JIM_ERR;
4982 jim_wide w;
4983 int e = Jim_GetOpt_Wide(&goi, &w);
4984 if (e != JIM_OK)
4985 return JIM_ERR;
4987 struct target *target;
4988 for (target = all_targets; NULL != target; target = target->next)
4990 if (target->target_number != w)
4991 continue;
4993 Jim_SetResultString(goi.interp, target_name(target), -1);
4994 return JIM_OK;
4997 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
4998 Jim_SetResultFormatted(goi.interp,
4999 "Target: number %#s does not exist", wObj);
5000 Jim_FreeNewObj(interp, wObj);
5002 return JIM_ERR;
5005 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5007 if (argc != 1)
5009 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
5010 return JIM_ERR;
5012 unsigned count = 0;
5013 struct target *target = all_targets;
5014 while (NULL != target)
5016 target = target->next;
5017 count++;
5019 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
5020 return JIM_OK;
5023 static const struct command_registration target_subcommand_handlers[] = {
5025 .name = "init",
5026 .mode = COMMAND_CONFIG,
5027 .handler = handle_target_init_command,
5028 .help = "initialize targets",
5031 .name = "create",
5032 /* REVISIT this should be COMMAND_CONFIG ... */
5033 .mode = COMMAND_ANY,
5034 .jim_handler = jim_target_create,
5035 .usage = "name type '-chain-position' name [options ...]",
5036 .help = "Creates and selects a new target",
5039 .name = "current",
5040 .mode = COMMAND_ANY,
5041 .jim_handler = jim_target_current,
5042 .help = "Returns the currently selected target",
5045 .name = "types",
5046 .mode = COMMAND_ANY,
5047 .jim_handler = jim_target_types,
5048 .help = "Returns the available target types as "
5049 "a list of strings",
5052 .name = "names",
5053 .mode = COMMAND_ANY,
5054 .jim_handler = jim_target_names,
5055 .help = "Returns the names of all targets as a list of strings",
5058 .name = "number",
5059 .mode = COMMAND_ANY,
5060 .jim_handler = jim_target_number,
5061 .usage = "number",
5062 .help = "Returns the name of the numbered target "
5063 "(DEPRECATED)",
5066 .name = "count",
5067 .mode = COMMAND_ANY,
5068 .jim_handler = jim_target_count,
5069 .help = "Returns the number of targets as an integer "
5070 "(DEPRECATED)",
5073 .name = "smp",
5074 .mode = COMMAND_ANY,
5075 .jim_handler = jim_target_smp,
5076 .usage = "targetname1 targetname2 ...",
5077 .help = "gather several target in a smp list"
5080 COMMAND_REGISTRATION_DONE
5083 struct FastLoad
5085 uint32_t address;
5086 uint8_t *data;
5087 int length;
5091 static int fastload_num;
5092 static struct FastLoad *fastload;
5094 static void free_fastload(void)
5096 if (fastload != NULL)
5098 int i;
5099 for (i = 0; i < fastload_num; i++)
5101 if (fastload[i].data)
5102 free(fastload[i].data);
5104 free(fastload);
5105 fastload = NULL;
5112 COMMAND_HANDLER(handle_fast_load_image_command)
5114 uint8_t *buffer;
5115 size_t buf_cnt;
5116 uint32_t image_size;
5117 uint32_t min_address = 0;
5118 uint32_t max_address = 0xffffffff;
5119 int i;
5121 struct image image;
5123 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5124 &image, &min_address, &max_address);
5125 if (ERROR_OK != retval)
5126 return retval;
5128 struct duration bench;
5129 duration_start(&bench);
5131 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5132 if (retval != ERROR_OK)
5134 return retval;
5137 image_size = 0x0;
5138 retval = ERROR_OK;
5139 fastload_num = image.num_sections;
5140 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
5141 if (fastload == NULL)
5143 command_print(CMD_CTX, "out of memory");
5144 image_close(&image);
5145 return ERROR_FAIL;
5147 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5148 for (i = 0; i < image.num_sections; i++)
5150 buffer = malloc(image.sections[i].size);
5151 if (buffer == NULL)
5153 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5154 (int)(image.sections[i].size));
5155 retval = ERROR_FAIL;
5156 break;
5159 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
5161 free(buffer);
5162 break;
5165 uint32_t offset = 0;
5166 uint32_t length = buf_cnt;
5169 /* DANGER!!! beware of unsigned comparision here!!! */
5171 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
5172 (image.sections[i].base_address < max_address))
5174 if (image.sections[i].base_address < min_address)
5176 /* clip addresses below */
5177 offset += min_address-image.sections[i].base_address;
5178 length -= offset;
5181 if (image.sections[i].base_address + buf_cnt > max_address)
5183 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5186 fastload[i].address = image.sections[i].base_address + offset;
5187 fastload[i].data = malloc(length);
5188 if (fastload[i].data == NULL)
5190 free(buffer);
5191 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5192 length);
5193 retval = ERROR_FAIL;
5194 break;
5196 memcpy(fastload[i].data, buffer + offset, length);
5197 fastload[i].length = length;
5199 image_size += length;
5200 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5201 (unsigned int)length,
5202 ((unsigned int)(image.sections[i].base_address + offset)));
5205 free(buffer);
5208 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
5210 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5211 "in %fs (%0.3f KiB/s)", image_size,
5212 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5214 command_print(CMD_CTX,
5215 "WARNING: image has not been loaded to target!"
5216 "You can issue a 'fast_load' to finish loading.");
5219 image_close(&image);
5221 if (retval != ERROR_OK)
5223 free_fastload();
5226 return retval;
5229 COMMAND_HANDLER(handle_fast_load_command)
5231 if (CMD_ARGC > 0)
5232 return ERROR_COMMAND_SYNTAX_ERROR;
5233 if (fastload == NULL)
5235 LOG_ERROR("No image in memory");
5236 return ERROR_FAIL;
5238 int i;
5239 int ms = timeval_ms();
5240 int size = 0;
5241 int retval = ERROR_OK;
5242 for (i = 0; i < fastload_num;i++)
5244 struct target *target = get_current_target(CMD_CTX);
5245 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5246 (unsigned int)(fastload[i].address),
5247 (unsigned int)(fastload[i].length));
5248 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5249 if (retval != ERROR_OK)
5251 break;
5253 size += fastload[i].length;
5255 if (retval == ERROR_OK)
5257 int after = timeval_ms();
5258 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5260 return retval;
5263 static const struct command_registration target_command_handlers[] = {
5265 .name = "targets",
5266 .handler = handle_targets_command,
5267 .mode = COMMAND_ANY,
5268 .help = "change current default target (one parameter) "
5269 "or prints table of all targets (no parameters)",
5270 .usage = "[target]",
5273 .name = "target",
5274 .mode = COMMAND_CONFIG,
5275 .help = "configure target",
5277 .chain = target_subcommand_handlers,
5279 COMMAND_REGISTRATION_DONE
5282 int target_register_commands(struct command_context *cmd_ctx)
5284 return register_commands(cmd_ctx, NULL, target_command_handlers);
5287 static bool target_reset_nag = true;
5289 bool get_target_reset_nag(void)
5291 return target_reset_nag;
5294 COMMAND_HANDLER(handle_target_reset_nag)
5296 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5297 &target_reset_nag, "Nag after each reset about options to improve "
5298 "performance");
5301 static const struct command_registration target_exec_command_handlers[] = {
5303 .name = "fast_load_image",
5304 .handler = handle_fast_load_image_command,
5305 .mode = COMMAND_ANY,
5306 .help = "Load image into server memory for later use by "
5307 "fast_load; primarily for profiling",
5308 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5309 "[min_address [max_length]]",
5312 .name = "fast_load",
5313 .handler = handle_fast_load_command,
5314 .mode = COMMAND_EXEC,
5315 .help = "loads active fast load image to current target "
5316 "- mainly for profiling purposes",
5319 .name = "profile",
5320 .handler = handle_profile_command,
5321 .mode = COMMAND_EXEC,
5322 .help = "profiling samples the CPU PC",
5324 /** @todo don't register virt2phys() unless target supports it */
5326 .name = "virt2phys",
5327 .handler = handle_virt2phys_command,
5328 .mode = COMMAND_ANY,
5329 .help = "translate a virtual address into a physical address",
5330 .usage = "virtual_address",
5333 .name = "reg",
5334 .handler = handle_reg_command,
5335 .mode = COMMAND_EXEC,
5336 .help = "display or set a register; with no arguments, "
5337 "displays all registers and their values",
5338 .usage = "[(register_name|register_number) [value]]",
5341 .name = "poll",
5342 .handler = handle_poll_command,
5343 .mode = COMMAND_EXEC,
5344 .help = "poll target state; or reconfigure background polling",
5345 .usage = "['on'|'off']",
5348 .name = "wait_halt",
5349 .handler = handle_wait_halt_command,
5350 .mode = COMMAND_EXEC,
5351 .help = "wait up to the specified number of milliseconds "
5352 "(default 5) for a previously requested halt",
5353 .usage = "[milliseconds]",
5356 .name = "halt",
5357 .handler = handle_halt_command,
5358 .mode = COMMAND_EXEC,
5359 .help = "request target to halt, then wait up to the specified"
5360 "number of milliseconds (default 5) for it to complete",
5361 .usage = "[milliseconds]",
5364 .name = "resume",
5365 .handler = handle_resume_command,
5366 .mode = COMMAND_EXEC,
5367 .help = "resume target execution from current PC or address",
5368 .usage = "[address]",
5371 .name = "reset",
5372 .handler = handle_reset_command,
5373 .mode = COMMAND_EXEC,
5374 .usage = "[run|halt|init]",
5375 .help = "Reset all targets into the specified mode."
5376 "Default reset mode is run, if not given.",
5379 .name = "soft_reset_halt",
5380 .handler = handle_soft_reset_halt_command,
5381 .mode = COMMAND_EXEC,
5382 .help = "halt the target and do a soft reset",
5385 .name = "step",
5386 .handler = handle_step_command,
5387 .mode = COMMAND_EXEC,
5388 .help = "step one instruction from current PC or address",
5389 .usage = "[address]",
5392 .name = "mdw",
5393 .handler = handle_md_command,
5394 .mode = COMMAND_EXEC,
5395 .help = "display memory words",
5396 .usage = "['phys'] address [count]",
5399 .name = "mdh",
5400 .handler = handle_md_command,
5401 .mode = COMMAND_EXEC,
5402 .help = "display memory half-words",
5403 .usage = "['phys'] address [count]",
5406 .name = "mdb",
5407 .handler = handle_md_command,
5408 .mode = COMMAND_EXEC,
5409 .help = "display memory bytes",
5410 .usage = "['phys'] address [count]",
5413 .name = "mww",
5414 .handler = handle_mw_command,
5415 .mode = COMMAND_EXEC,
5416 .help = "write memory word",
5417 .usage = "['phys'] address value [count]",
5420 .name = "mwh",
5421 .handler = handle_mw_command,
5422 .mode = COMMAND_EXEC,
5423 .help = "write memory half-word",
5424 .usage = "['phys'] address value [count]",
5427 .name = "mwb",
5428 .handler = handle_mw_command,
5429 .mode = COMMAND_EXEC,
5430 .help = "write memory byte",
5431 .usage = "['phys'] address value [count]",
5434 .name = "bp",
5435 .handler = handle_bp_command,
5436 .mode = COMMAND_EXEC,
5437 .help = "list or set hardware or software breakpoint",
5438 .usage = "[address length ['hw']]",
5441 .name = "rbp",
5442 .handler = handle_rbp_command,
5443 .mode = COMMAND_EXEC,
5444 .help = "remove breakpoint",
5445 .usage = "address",
5448 .name = "wp",
5449 .handler = handle_wp_command,
5450 .mode = COMMAND_EXEC,
5451 .help = "list (no params) or create watchpoints",
5452 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5455 .name = "rwp",
5456 .handler = handle_rwp_command,
5457 .mode = COMMAND_EXEC,
5458 .help = "remove watchpoint",
5459 .usage = "address",
5462 .name = "load_image",
5463 .handler = handle_load_image_command,
5464 .mode = COMMAND_EXEC,
5465 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5466 "[min_address] [max_length]",
5469 .name = "dump_image",
5470 .handler = handle_dump_image_command,
5471 .mode = COMMAND_EXEC,
5472 .usage = "filename address size",
5475 .name = "verify_image",
5476 .handler = handle_verify_image_command,
5477 .mode = COMMAND_EXEC,
5478 .usage = "filename [offset [type]]",
5481 .name = "test_image",
5482 .handler = handle_test_image_command,
5483 .mode = COMMAND_EXEC,
5484 .usage = "filename [offset [type]]",
5487 .name = "mem2array",
5488 .mode = COMMAND_EXEC,
5489 .jim_handler = jim_mem2array,
5490 .help = "read 8/16/32 bit memory and return as a TCL array "
5491 "for script processing",
5492 .usage = "arrayname bitwidth address count",
5495 .name = "array2mem",
5496 .mode = COMMAND_EXEC,
5497 .jim_handler = jim_array2mem,
5498 .help = "convert a TCL array to memory locations "
5499 "and write the 8/16/32 bit values",
5500 .usage = "arrayname bitwidth address count",
5503 .name = "reset_nag",
5504 .handler = handle_target_reset_nag,
5505 .mode = COMMAND_ANY,
5506 .help = "Nag after each reset about options that could have been "
5507 "enabled to improve performance. ",
5508 .usage = "['enable'|'disable']",
5510 COMMAND_REGISTRATION_DONE
5512 static int target_register_user_commands(struct command_context *cmd_ctx)
5514 int retval = ERROR_OK;
5515 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
5516 return retval;
5518 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
5519 return retval;
5522 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);