profile: use 100Hz as a default sampling frequency
[openocd/ntfreak.git] / src / target / target.c
blob5cff9d081ad27cecb6c0069780553ab8fbeb80b9
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 * This program is free software; you can redistribute it and/or modify *
18 * it under the terms of the GNU General Public License as published by *
19 * the Free Software Foundation; either version 2 of the License, or *
20 * (at your option) any later version. *
21 * *
22 * This program is distributed in the hope that it will be useful, *
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
25 * GNU General Public License for more details. *
26 * *
27 * You should have received a copy of the GNU General Public License *
28 * along with this program; if not, write to the *
29 * Free Software Foundation, Inc., *
30 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
31 ***************************************************************************/
32 #ifdef HAVE_CONFIG_H
33 #include "config.h"
34 #endif
36 #include <helper/time_support.h>
37 #include <jtag/jtag.h>
38 #include <flash/nor/core.h>
40 #include "target.h"
41 #include "target_type.h"
42 #include "target_request.h"
43 #include "breakpoints.h"
44 #include "register.h"
45 #include "trace.h"
46 #include "image.h"
49 static int target_array2mem(Jim_Interp *interp, struct target *target,
50 int argc, Jim_Obj *const *argv);
51 static int target_mem2array(Jim_Interp *interp, struct target *target,
52 int argc, Jim_Obj *const *argv);
53 static int target_register_user_commands(struct command_context *cmd_ctx);
55 /* targets */
56 extern struct target_type arm7tdmi_target;
57 extern struct target_type arm720t_target;
58 extern struct target_type arm9tdmi_target;
59 extern struct target_type arm920t_target;
60 extern struct target_type arm966e_target;
61 extern struct target_type arm946e_target;
62 extern struct target_type arm926ejs_target;
63 extern struct target_type fa526_target;
64 extern struct target_type feroceon_target;
65 extern struct target_type dragonite_target;
66 extern struct target_type xscale_target;
67 extern struct target_type cortexm3_target;
68 extern struct target_type cortexa8_target;
69 extern struct target_type arm11_target;
70 extern struct target_type mips_m4k_target;
71 extern struct target_type avr_target;
72 extern struct target_type dsp563xx_target;
73 extern struct target_type testee_target;
74 extern struct target_type avr32_ap7k_target;
76 static struct target_type *target_types[] =
78 &arm7tdmi_target,
79 &arm9tdmi_target,
80 &arm920t_target,
81 &arm720t_target,
82 &arm966e_target,
83 &arm946e_target,
84 &arm926ejs_target,
85 &fa526_target,
86 &feroceon_target,
87 &dragonite_target,
88 &xscale_target,
89 &cortexm3_target,
90 &cortexa8_target,
91 &arm11_target,
92 &mips_m4k_target,
93 &avr_target,
94 &dsp563xx_target,
95 &testee_target,
96 &avr32_ap7k_target,
97 NULL,
100 struct target *all_targets = NULL;
101 static struct target_event_callback *target_event_callbacks = NULL;
102 static struct target_timer_callback *target_timer_callbacks = NULL;
103 static const int polling_interval = 100;
105 static const Jim_Nvp nvp_assert[] = {
106 { .name = "assert", NVP_ASSERT },
107 { .name = "deassert", NVP_DEASSERT },
108 { .name = "T", NVP_ASSERT },
109 { .name = "F", NVP_DEASSERT },
110 { .name = "t", NVP_ASSERT },
111 { .name = "f", NVP_DEASSERT },
112 { .name = NULL, .value = -1 }
115 static const Jim_Nvp nvp_error_target[] = {
116 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
117 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
118 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
119 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
120 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
121 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
122 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
123 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
124 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
125 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
126 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
127 { .value = -1, .name = NULL }
130 static const char *target_strerror_safe(int err)
132 const Jim_Nvp *n;
134 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
135 if (n->name == NULL) {
136 return "unknown";
137 } else {
138 return n->name;
142 static const Jim_Nvp nvp_target_event[] = {
143 { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
144 { .value = TARGET_EVENT_OLD_pre_resume , .name = "old-pre_resume" },
146 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
147 { .value = TARGET_EVENT_HALTED, .name = "halted" },
148 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
149 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
150 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
152 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
153 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
155 /* historical name */
157 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
159 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
160 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
161 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
162 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
163 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
164 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
165 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
166 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
167 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
168 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
169 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
171 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
172 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
174 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
175 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
177 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
178 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
180 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
181 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
183 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
184 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
186 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
187 { .value = TARGET_EVENT_RESUMED , .name = "resume-ok" },
188 { .value = TARGET_EVENT_RESUME_END , .name = "resume-end" },
190 { .name = NULL, .value = -1 }
193 static const Jim_Nvp nvp_target_state[] = {
194 { .name = "unknown", .value = TARGET_UNKNOWN },
195 { .name = "running", .value = TARGET_RUNNING },
196 { .name = "halted", .value = TARGET_HALTED },
197 { .name = "reset", .value = TARGET_RESET },
198 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
199 { .name = NULL, .value = -1 },
202 static const Jim_Nvp nvp_target_debug_reason [] = {
203 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
204 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
205 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
206 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
207 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
208 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
209 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
210 { .name = NULL, .value = -1 },
213 static const Jim_Nvp nvp_target_endian[] = {
214 { .name = "big", .value = TARGET_BIG_ENDIAN },
215 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
216 { .name = "be", .value = TARGET_BIG_ENDIAN },
217 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
218 { .name = NULL, .value = -1 },
221 static const Jim_Nvp nvp_reset_modes[] = {
222 { .name = "unknown", .value = RESET_UNKNOWN },
223 { .name = "run" , .value = RESET_RUN },
224 { .name = "halt" , .value = RESET_HALT },
225 { .name = "init" , .value = RESET_INIT },
226 { .name = NULL , .value = -1 },
229 const char *debug_reason_name(struct target *t)
231 const char *cp;
233 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
234 t->debug_reason)->name;
235 if (!cp) {
236 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
237 cp = "(*BUG*unknown*BUG*)";
239 return cp;
242 const char *
243 target_state_name( struct target *t )
245 const char *cp;
246 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
247 if( !cp ){
248 LOG_ERROR("Invalid target state: %d", (int)(t->state));
249 cp = "(*BUG*unknown*BUG*)";
251 return cp;
254 /* determine the number of the new target */
255 static int new_target_number(void)
257 struct target *t;
258 int x;
260 /* number is 0 based */
261 x = -1;
262 t = all_targets;
263 while (t) {
264 if (x < t->target_number) {
265 x = t->target_number;
267 t = t->next;
269 return x + 1;
272 /* read a uint32_t from a buffer in target memory endianness */
273 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
275 if (target->endianness == TARGET_LITTLE_ENDIAN)
276 return le_to_h_u32(buffer);
277 else
278 return be_to_h_u32(buffer);
281 /* read a uint16_t from a buffer in target memory endianness */
282 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
284 if (target->endianness == TARGET_LITTLE_ENDIAN)
285 return le_to_h_u16(buffer);
286 else
287 return be_to_h_u16(buffer);
290 /* read a uint8_t from a buffer in target memory endianness */
291 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
293 return *buffer & 0x0ff;
296 /* write a uint32_t to a buffer in target memory endianness */
297 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
299 if (target->endianness == TARGET_LITTLE_ENDIAN)
300 h_u32_to_le(buffer, value);
301 else
302 h_u32_to_be(buffer, value);
305 /* write a uint16_t to a buffer in target memory endianness */
306 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
308 if (target->endianness == TARGET_LITTLE_ENDIAN)
309 h_u16_to_le(buffer, value);
310 else
311 h_u16_to_be(buffer, value);
314 /* write a uint8_t to a buffer in target memory endianness */
315 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
317 *buffer = value;
320 /* return a pointer to a configured target; id is name or number */
321 struct target *get_target(const char *id)
323 struct target *target;
325 /* try as tcltarget name */
326 for (target = all_targets; target; target = target->next) {
327 if (target->cmd_name == NULL)
328 continue;
329 if (strcmp(id, target->cmd_name) == 0)
330 return target;
333 /* It's OK to remove this fallback sometime after August 2010 or so */
335 /* no match, try as number */
336 unsigned num;
337 if (parse_uint(id, &num) != ERROR_OK)
338 return NULL;
340 for (target = all_targets; target; target = target->next) {
341 if (target->target_number == (int)num) {
342 LOG_WARNING("use '%s' as target identifier, not '%u'",
343 target->cmd_name, num);
344 return target;
348 return NULL;
351 /* returns a pointer to the n-th configured target */
352 static struct target *get_target_by_num(int num)
354 struct target *target = all_targets;
356 while (target) {
357 if (target->target_number == num) {
358 return target;
360 target = target->next;
363 return NULL;
366 struct target* get_current_target(struct command_context *cmd_ctx)
368 struct target *target = get_target_by_num(cmd_ctx->current_target);
370 if (target == NULL)
372 LOG_ERROR("BUG: current_target out of bounds");
373 exit(-1);
376 return target;
379 int target_poll(struct target *target)
381 int retval;
383 /* We can't poll until after examine */
384 if (!target_was_examined(target))
386 /* Fail silently lest we pollute the log */
387 return ERROR_FAIL;
390 retval = target->type->poll(target);
391 if (retval != ERROR_OK)
392 return retval;
394 if (target->halt_issued)
396 if (target->state == TARGET_HALTED)
398 target->halt_issued = false;
399 } else
401 long long t = timeval_ms() - target->halt_issued_time;
402 if (t>1000)
404 target->halt_issued = false;
405 LOG_INFO("Halt timed out, wake up GDB.");
406 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
411 return ERROR_OK;
414 int target_halt(struct target *target)
416 int retval;
417 /* We can't poll until after examine */
418 if (!target_was_examined(target))
420 LOG_ERROR("Target not examined yet");
421 return ERROR_FAIL;
424 retval = target->type->halt(target);
425 if (retval != ERROR_OK)
426 return retval;
428 target->halt_issued = true;
429 target->halt_issued_time = timeval_ms();
431 return ERROR_OK;
435 * Make the target (re)start executing using its saved execution
436 * context (possibly with some modifications).
438 * @param target Which target should start executing.
439 * @param current True to use the target's saved program counter instead
440 * of the address parameter
441 * @param address Optionally used as the program counter.
442 * @param handle_breakpoints True iff breakpoints at the resumption PC
443 * should be skipped. (For example, maybe execution was stopped by
444 * such a breakpoint, in which case it would be counterprodutive to
445 * let it re-trigger.
446 * @param debug_execution False if all working areas allocated by OpenOCD
447 * should be released and/or restored to their original contents.
448 * (This would for example be true to run some downloaded "helper"
449 * algorithm code, which resides in one such working buffer and uses
450 * another for data storage.)
452 * @todo Resolve the ambiguity about what the "debug_execution" flag
453 * signifies. For example, Target implementations don't agree on how
454 * it relates to invalidation of the register cache, or to whether
455 * breakpoints and watchpoints should be enabled. (It would seem wrong
456 * to enable breakpoints when running downloaded "helper" algorithms
457 * (debug_execution true), since the breakpoints would be set to match
458 * target firmware being debugged, not the helper algorithm.... and
459 * enabling them could cause such helpers to malfunction (for example,
460 * by overwriting data with a breakpoint instruction. On the other
461 * hand the infrastructure for running such helpers might use this
462 * procedure but rely on hardware breakpoint to detect termination.)
464 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
466 int retval;
468 /* We can't poll until after examine */
469 if (!target_was_examined(target))
471 LOG_ERROR("Target not examined yet");
472 return ERROR_FAIL;
475 /* note that resume *must* be asynchronous. The CPU can halt before
476 * we poll. The CPU can even halt at the current PC as a result of
477 * a software breakpoint being inserted by (a bug?) the application.
479 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
480 return retval;
482 return retval;
485 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
487 char buf[100];
488 int retval;
489 Jim_Nvp *n;
490 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
491 if (n->name == NULL) {
492 LOG_ERROR("invalid reset mode");
493 return ERROR_FAIL;
496 /* disable polling during reset to make reset event scripts
497 * more predictable, i.e. dr/irscan & pathmove in events will
498 * not have JTAG operations injected into the middle of a sequence.
500 bool save_poll = jtag_poll_get_enabled();
502 jtag_poll_set_enabled(false);
504 sprintf(buf, "ocd_process_reset %s", n->name);
505 retval = Jim_Eval(cmd_ctx->interp, buf);
507 jtag_poll_set_enabled(save_poll);
509 if (retval != JIM_OK) {
510 Jim_MakeErrorMessage(cmd_ctx->interp);
511 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
512 return ERROR_FAIL;
515 /* We want any events to be processed before the prompt */
516 retval = target_call_timer_callbacks_now();
518 struct target *target;
519 for (target = all_targets; target; target = target->next) {
520 target->type->check_reset(target);
523 return retval;
526 static int identity_virt2phys(struct target *target,
527 uint32_t virtual, uint32_t *physical)
529 *physical = virtual;
530 return ERROR_OK;
533 static int no_mmu(struct target *target, int *enabled)
535 *enabled = 0;
536 return ERROR_OK;
539 static int default_examine(struct target *target)
541 target_set_examined(target);
542 return ERROR_OK;
545 /* no check by default */
546 static int default_check_reset(struct target *target)
548 return ERROR_OK;
551 int target_examine_one(struct target *target)
553 return target->type->examine(target);
556 static int jtag_enable_callback(enum jtag_event event, void *priv)
558 struct target *target = priv;
560 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
561 return ERROR_OK;
563 jtag_unregister_event_callback(jtag_enable_callback, target);
564 return target_examine_one(target);
568 /* Targets that correctly implement init + examine, i.e.
569 * no communication with target during init:
571 * XScale
573 int target_examine(void)
575 int retval = ERROR_OK;
576 struct target *target;
578 for (target = all_targets; target; target = target->next)
580 /* defer examination, but don't skip it */
581 if (!target->tap->enabled) {
582 jtag_register_event_callback(jtag_enable_callback,
583 target);
584 continue;
586 if ((retval = target_examine_one(target)) != ERROR_OK)
587 return retval;
589 return retval;
591 const char *target_type_name(struct target *target)
593 return target->type->name;
596 static int target_write_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
598 if (!target_was_examined(target))
600 LOG_ERROR("Target not examined yet");
601 return ERROR_FAIL;
603 return target->type->write_memory_imp(target, address, size, count, buffer);
606 static int target_read_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
608 if (!target_was_examined(target))
610 LOG_ERROR("Target not examined yet");
611 return ERROR_FAIL;
613 return target->type->read_memory_imp(target, address, size, count, buffer);
616 static int target_soft_reset_halt_imp(struct target *target)
618 if (!target_was_examined(target))
620 LOG_ERROR("Target not examined yet");
621 return ERROR_FAIL;
623 if (!target->type->soft_reset_halt_imp) {
624 LOG_ERROR("Target %s does not support soft_reset_halt",
625 target_name(target));
626 return ERROR_FAIL;
628 return target->type->soft_reset_halt_imp(target);
632 * Downloads a target-specific native code algorithm to the target,
633 * and executes it. * Note that some targets may need to set up, enable,
634 * and tear down a breakpoint (hard or * soft) to detect algorithm
635 * termination, while others may support lower overhead schemes where
636 * soft breakpoints embedded in the algorithm automatically terminate the
637 * algorithm.
639 * @param target used to run the algorithm
640 * @param arch_info target-specific description of the algorithm.
642 int target_run_algorithm(struct target *target,
643 int num_mem_params, struct mem_param *mem_params,
644 int num_reg_params, struct reg_param *reg_param,
645 uint32_t entry_point, uint32_t exit_point,
646 int timeout_ms, void *arch_info)
648 int retval = ERROR_FAIL;
650 if (!target_was_examined(target))
652 LOG_ERROR("Target not examined yet");
653 goto done;
655 if (!target->type->run_algorithm) {
656 LOG_ERROR("Target type '%s' does not support %s",
657 target_type_name(target), __func__);
658 goto done;
661 target->running_alg = true;
662 retval = target->type->run_algorithm(target,
663 num_mem_params, mem_params,
664 num_reg_params, reg_param,
665 entry_point, exit_point, timeout_ms, arch_info);
666 target->running_alg = false;
668 done:
669 return retval;
673 int target_read_memory(struct target *target,
674 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
676 return target->type->read_memory(target, address, size, count, buffer);
679 static int target_read_phys_memory(struct target *target,
680 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
682 return target->type->read_phys_memory(target, address, size, count, buffer);
685 int target_write_memory(struct target *target,
686 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
688 return target->type->write_memory(target, address, size, count, buffer);
691 static int target_write_phys_memory(struct target *target,
692 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
694 return target->type->write_phys_memory(target, address, size, count, buffer);
697 int target_bulk_write_memory(struct target *target,
698 uint32_t address, uint32_t count, uint8_t *buffer)
700 return target->type->bulk_write_memory(target, address, count, buffer);
703 int target_add_breakpoint(struct target *target,
704 struct breakpoint *breakpoint)
706 if (target->state != TARGET_HALTED) {
707 LOG_WARNING("target %s is not halted", target->cmd_name);
708 return ERROR_TARGET_NOT_HALTED;
710 return target->type->add_breakpoint(target, breakpoint);
712 int target_remove_breakpoint(struct target *target,
713 struct breakpoint *breakpoint)
715 return target->type->remove_breakpoint(target, breakpoint);
718 int target_add_watchpoint(struct target *target,
719 struct watchpoint *watchpoint)
721 if (target->state != TARGET_HALTED) {
722 LOG_WARNING("target %s is not halted", target->cmd_name);
723 return ERROR_TARGET_NOT_HALTED;
725 return target->type->add_watchpoint(target, watchpoint);
727 int target_remove_watchpoint(struct target *target,
728 struct watchpoint *watchpoint)
730 return target->type->remove_watchpoint(target, watchpoint);
733 int target_get_gdb_reg_list(struct target *target,
734 struct reg **reg_list[], int *reg_list_size)
736 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
738 int target_step(struct target *target,
739 int current, uint32_t address, int handle_breakpoints)
741 return target->type->step(target, current, address, handle_breakpoints);
746 * Reset the @c examined flag for the given target.
747 * Pure paranoia -- targets are zeroed on allocation.
749 static void target_reset_examined(struct target *target)
751 target->examined = false;
754 static int
755 err_read_phys_memory(struct target *target, uint32_t address,
756 uint32_t size, uint32_t count, uint8_t *buffer)
758 LOG_ERROR("Not implemented: %s", __func__);
759 return ERROR_FAIL;
762 static int
763 err_write_phys_memory(struct target *target, uint32_t address,
764 uint32_t size, uint32_t count, uint8_t *buffer)
766 LOG_ERROR("Not implemented: %s", __func__);
767 return ERROR_FAIL;
770 static int handle_target(void *priv);
772 static int target_init_one(struct command_context *cmd_ctx,
773 struct target *target)
775 target_reset_examined(target);
777 struct target_type *type = target->type;
778 if (type->examine == NULL)
779 type->examine = default_examine;
781 if (type->check_reset== NULL)
782 type->check_reset = default_check_reset;
784 int retval = type->init_target(cmd_ctx, target);
785 if (ERROR_OK != retval)
787 LOG_ERROR("target '%s' init failed", target_name(target));
788 return retval;
792 * @todo get rid of those *memory_imp() methods, now that all
793 * callers are using target_*_memory() accessors ... and make
794 * sure the "physical" paths handle the same issues.
796 /* a non-invasive way(in terms of patches) to add some code that
797 * runs before the type->write/read_memory implementation
799 type->write_memory_imp = target->type->write_memory;
800 type->write_memory = target_write_memory_imp;
802 type->read_memory_imp = target->type->read_memory;
803 type->read_memory = target_read_memory_imp;
805 type->soft_reset_halt_imp = target->type->soft_reset_halt;
806 type->soft_reset_halt = target_soft_reset_halt_imp;
808 /* Sanity-check MMU support ... stub in what we must, to help
809 * implement it in stages, but warn if we need to do so.
811 if (type->mmu)
813 if (type->write_phys_memory == NULL)
815 LOG_ERROR("type '%s' is missing write_phys_memory",
816 type->name);
817 type->write_phys_memory = err_write_phys_memory;
819 if (type->read_phys_memory == NULL)
821 LOG_ERROR("type '%s' is missing read_phys_memory",
822 type->name);
823 type->read_phys_memory = err_read_phys_memory;
825 if (type->virt2phys == NULL)
827 LOG_ERROR("type '%s' is missing virt2phys", type->name);
828 type->virt2phys = identity_virt2phys;
831 else
833 /* Make sure no-MMU targets all behave the same: make no
834 * distinction between physical and virtual addresses, and
835 * ensure that virt2phys() is always an identity mapping.
837 if (type->write_phys_memory || type->read_phys_memory
838 || type->virt2phys)
840 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
843 type->mmu = no_mmu;
844 type->write_phys_memory = type->write_memory;
845 type->read_phys_memory = type->read_memory;
846 type->virt2phys = identity_virt2phys;
848 return ERROR_OK;
851 static int target_init(struct command_context *cmd_ctx)
853 struct target *target;
854 int retval;
856 for (target = all_targets; target; target = target->next)
858 retval = target_init_one(cmd_ctx, target);
859 if (ERROR_OK != retval)
860 return retval;
863 if (!all_targets)
864 return ERROR_OK;
866 retval = target_register_user_commands(cmd_ctx);
867 if (ERROR_OK != retval)
868 return retval;
870 retval = target_register_timer_callback(&handle_target,
871 polling_interval, 1, cmd_ctx->interp);
872 if (ERROR_OK != retval)
873 return retval;
875 return ERROR_OK;
878 COMMAND_HANDLER(handle_target_init_command)
880 if (CMD_ARGC != 0)
881 return ERROR_COMMAND_SYNTAX_ERROR;
883 static bool target_initialized = false;
884 if (target_initialized)
886 LOG_INFO("'target init' has already been called");
887 return ERROR_OK;
889 target_initialized = true;
891 LOG_DEBUG("Initializing targets...");
892 return target_init(CMD_CTX);
895 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
897 struct target_event_callback **callbacks_p = &target_event_callbacks;
899 if (callback == NULL)
901 return ERROR_INVALID_ARGUMENTS;
904 if (*callbacks_p)
906 while ((*callbacks_p)->next)
907 callbacks_p = &((*callbacks_p)->next);
908 callbacks_p = &((*callbacks_p)->next);
911 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
912 (*callbacks_p)->callback = callback;
913 (*callbacks_p)->priv = priv;
914 (*callbacks_p)->next = NULL;
916 return ERROR_OK;
919 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
921 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
922 struct timeval now;
924 if (callback == NULL)
926 return ERROR_INVALID_ARGUMENTS;
929 if (*callbacks_p)
931 while ((*callbacks_p)->next)
932 callbacks_p = &((*callbacks_p)->next);
933 callbacks_p = &((*callbacks_p)->next);
936 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
937 (*callbacks_p)->callback = callback;
938 (*callbacks_p)->periodic = periodic;
939 (*callbacks_p)->time_ms = time_ms;
941 gettimeofday(&now, NULL);
942 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
943 time_ms -= (time_ms % 1000);
944 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
945 if ((*callbacks_p)->when.tv_usec > 1000000)
947 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
948 (*callbacks_p)->when.tv_sec += 1;
951 (*callbacks_p)->priv = priv;
952 (*callbacks_p)->next = NULL;
954 return ERROR_OK;
957 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
959 struct target_event_callback **p = &target_event_callbacks;
960 struct target_event_callback *c = target_event_callbacks;
962 if (callback == NULL)
964 return ERROR_INVALID_ARGUMENTS;
967 while (c)
969 struct target_event_callback *next = c->next;
970 if ((c->callback == callback) && (c->priv == priv))
972 *p = next;
973 free(c);
974 return ERROR_OK;
976 else
977 p = &(c->next);
978 c = next;
981 return ERROR_OK;
984 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
986 struct target_timer_callback **p = &target_timer_callbacks;
987 struct target_timer_callback *c = target_timer_callbacks;
989 if (callback == NULL)
991 return ERROR_INVALID_ARGUMENTS;
994 while (c)
996 struct target_timer_callback *next = c->next;
997 if ((c->callback == callback) && (c->priv == priv))
999 *p = next;
1000 free(c);
1001 return ERROR_OK;
1003 else
1004 p = &(c->next);
1005 c = next;
1008 return ERROR_OK;
1011 int target_call_event_callbacks(struct target *target, enum target_event event)
1013 struct target_event_callback *callback = target_event_callbacks;
1014 struct target_event_callback *next_callback;
1016 if (event == TARGET_EVENT_HALTED)
1018 /* execute early halted first */
1019 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1022 LOG_DEBUG("target event %i (%s)",
1023 event,
1024 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1026 target_handle_event(target, event);
1028 while (callback)
1030 next_callback = callback->next;
1031 callback->callback(target, event, callback->priv);
1032 callback = next_callback;
1035 return ERROR_OK;
1038 static int target_timer_callback_periodic_restart(
1039 struct target_timer_callback *cb, struct timeval *now)
1041 int time_ms = cb->time_ms;
1042 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1043 time_ms -= (time_ms % 1000);
1044 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1045 if (cb->when.tv_usec > 1000000)
1047 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1048 cb->when.tv_sec += 1;
1050 return ERROR_OK;
1053 static int target_call_timer_callback(struct target_timer_callback *cb,
1054 struct timeval *now)
1056 cb->callback(cb->priv);
1058 if (cb->periodic)
1059 return target_timer_callback_periodic_restart(cb, now);
1061 return target_unregister_timer_callback(cb->callback, cb->priv);
1064 static int target_call_timer_callbacks_check_time(int checktime)
1066 keep_alive();
1068 struct timeval now;
1069 gettimeofday(&now, NULL);
1071 struct target_timer_callback *callback = target_timer_callbacks;
1072 while (callback)
1074 // cleaning up may unregister and free this callback
1075 struct target_timer_callback *next_callback = callback->next;
1077 bool call_it = callback->callback &&
1078 ((!checktime && callback->periodic) ||
1079 now.tv_sec > callback->when.tv_sec ||
1080 (now.tv_sec == callback->when.tv_sec &&
1081 now.tv_usec >= callback->when.tv_usec));
1083 if (call_it)
1085 int retval = target_call_timer_callback(callback, &now);
1086 if (retval != ERROR_OK)
1087 return retval;
1090 callback = next_callback;
1093 return ERROR_OK;
1096 int target_call_timer_callbacks(void)
1098 return target_call_timer_callbacks_check_time(1);
1101 /* invoke periodic callbacks immediately */
1102 int target_call_timer_callbacks_now(void)
1104 return target_call_timer_callbacks_check_time(0);
1107 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1109 struct working_area *c = target->working_areas;
1110 struct working_area *new_wa = NULL;
1112 /* Reevaluate working area address based on MMU state*/
1113 if (target->working_areas == NULL)
1115 int retval;
1116 int enabled;
1118 retval = target->type->mmu(target, &enabled);
1119 if (retval != ERROR_OK)
1121 return retval;
1124 if (!enabled) {
1125 if (target->working_area_phys_spec) {
1126 LOG_DEBUG("MMU disabled, using physical "
1127 "address for working memory 0x%08x",
1128 (unsigned)target->working_area_phys);
1129 target->working_area = target->working_area_phys;
1130 } else {
1131 LOG_ERROR("No working memory available. "
1132 "Specify -work-area-phys to target.");
1133 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1135 } else {
1136 if (target->working_area_virt_spec) {
1137 LOG_DEBUG("MMU enabled, using virtual "
1138 "address for working memory 0x%08x",
1139 (unsigned)target->working_area_virt);
1140 target->working_area = target->working_area_virt;
1141 } else {
1142 LOG_ERROR("No working memory available. "
1143 "Specify -work-area-virt to target.");
1144 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1149 /* only allocate multiples of 4 byte */
1150 if (size % 4)
1152 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1153 size = (size + 3) & (~3);
1156 /* see if there's already a matching working area */
1157 while (c)
1159 if ((c->free) && (c->size == size))
1161 new_wa = c;
1162 break;
1164 c = c->next;
1167 /* if not, allocate a new one */
1168 if (!new_wa)
1170 struct working_area **p = &target->working_areas;
1171 uint32_t first_free = target->working_area;
1172 uint32_t free_size = target->working_area_size;
1174 c = target->working_areas;
1175 while (c)
1177 first_free += c->size;
1178 free_size -= c->size;
1179 p = &c->next;
1180 c = c->next;
1183 if (free_size < size)
1185 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1188 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1190 new_wa = malloc(sizeof(struct working_area));
1191 new_wa->next = NULL;
1192 new_wa->size = size;
1193 new_wa->address = first_free;
1195 if (target->backup_working_area)
1197 int retval;
1198 new_wa->backup = malloc(new_wa->size);
1199 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1201 free(new_wa->backup);
1202 free(new_wa);
1203 return retval;
1206 else
1208 new_wa->backup = NULL;
1211 /* put new entry in list */
1212 *p = new_wa;
1215 /* mark as used, and return the new (reused) area */
1216 new_wa->free = 0;
1217 *area = new_wa;
1219 /* user pointer */
1220 new_wa->user = area;
1222 return ERROR_OK;
1225 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1227 int retval;
1229 retval = target_alloc_working_area_try(target, size, area);
1230 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1232 LOG_WARNING("not enough working area available(requested %u)", (unsigned)(size));
1234 return retval;
1238 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1240 if (area->free)
1241 return ERROR_OK;
1243 if (restore && target->backup_working_area)
1245 int retval;
1246 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1247 return retval;
1250 area->free = 1;
1252 /* mark user pointer invalid */
1253 *area->user = NULL;
1254 area->user = NULL;
1256 return ERROR_OK;
1259 int target_free_working_area(struct target *target, struct working_area *area)
1261 return target_free_working_area_restore(target, area, 1);
1264 /* free resources and restore memory, if restoring memory fails,
1265 * free up resources anyway
1267 static void target_free_all_working_areas_restore(struct target *target, int restore)
1269 struct working_area *c = target->working_areas;
1271 while (c)
1273 struct working_area *next = c->next;
1274 target_free_working_area_restore(target, c, restore);
1276 if (c->backup)
1277 free(c->backup);
1279 free(c);
1281 c = next;
1284 target->working_areas = NULL;
1287 void target_free_all_working_areas(struct target *target)
1289 target_free_all_working_areas_restore(target, 1);
1292 int target_arch_state(struct target *target)
1294 int retval;
1295 if (target == NULL)
1297 LOG_USER("No target has been configured");
1298 return ERROR_OK;
1301 LOG_USER("target state: %s", target_state_name( target ));
1303 if (target->state != TARGET_HALTED)
1304 return ERROR_OK;
1306 retval = target->type->arch_state(target);
1307 return retval;
1310 /* Single aligned words are guaranteed to use 16 or 32 bit access
1311 * mode respectively, otherwise data is handled as quickly as
1312 * possible
1314 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1316 int retval;
1317 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1318 (int)size, (unsigned)address);
1320 if (!target_was_examined(target))
1322 LOG_ERROR("Target not examined yet");
1323 return ERROR_FAIL;
1326 if (size == 0) {
1327 return ERROR_OK;
1330 if ((address + size - 1) < address)
1332 /* GDB can request this when e.g. PC is 0xfffffffc*/
1333 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1334 (unsigned)address,
1335 (unsigned)size);
1336 return ERROR_FAIL;
1339 if (((address % 2) == 0) && (size == 2))
1341 return target_write_memory(target, address, 2, 1, buffer);
1344 /* handle unaligned head bytes */
1345 if (address % 4)
1347 uint32_t unaligned = 4 - (address % 4);
1349 if (unaligned > size)
1350 unaligned = size;
1352 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1353 return retval;
1355 buffer += unaligned;
1356 address += unaligned;
1357 size -= unaligned;
1360 /* handle aligned words */
1361 if (size >= 4)
1363 int aligned = size - (size % 4);
1365 /* use bulk writes above a certain limit. This may have to be changed */
1366 if (aligned > 128)
1368 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1369 return retval;
1371 else
1373 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1374 return retval;
1377 buffer += aligned;
1378 address += aligned;
1379 size -= aligned;
1382 /* handle tail writes of less than 4 bytes */
1383 if (size > 0)
1385 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1386 return retval;
1389 return ERROR_OK;
1392 /* Single aligned words are guaranteed to use 16 or 32 bit access
1393 * mode respectively, otherwise data is handled as quickly as
1394 * possible
1396 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1398 int retval;
1399 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1400 (int)size, (unsigned)address);
1402 if (!target_was_examined(target))
1404 LOG_ERROR("Target not examined yet");
1405 return ERROR_FAIL;
1408 if (size == 0) {
1409 return ERROR_OK;
1412 if ((address + size - 1) < address)
1414 /* GDB can request this when e.g. PC is 0xfffffffc*/
1415 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1416 address,
1417 size);
1418 return ERROR_FAIL;
1421 if (((address % 2) == 0) && (size == 2))
1423 return target_read_memory(target, address, 2, 1, buffer);
1426 /* handle unaligned head bytes */
1427 if (address % 4)
1429 uint32_t unaligned = 4 - (address % 4);
1431 if (unaligned > size)
1432 unaligned = size;
1434 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1435 return retval;
1437 buffer += unaligned;
1438 address += unaligned;
1439 size -= unaligned;
1442 /* handle aligned words */
1443 if (size >= 4)
1445 int aligned = size - (size % 4);
1447 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1448 return retval;
1450 buffer += aligned;
1451 address += aligned;
1452 size -= aligned;
1455 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1456 if(size >=2)
1458 int aligned = size - (size%2);
1459 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1460 if (retval != ERROR_OK)
1461 return retval;
1463 buffer += aligned;
1464 address += aligned;
1465 size -= aligned;
1467 /* handle tail writes of less than 4 bytes */
1468 if (size > 0)
1470 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1471 return retval;
1474 return ERROR_OK;
1477 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1479 uint8_t *buffer;
1480 int retval;
1481 uint32_t i;
1482 uint32_t checksum = 0;
1483 if (!target_was_examined(target))
1485 LOG_ERROR("Target not examined yet");
1486 return ERROR_FAIL;
1489 if ((retval = target->type->checksum_memory(target, address,
1490 size, &checksum)) != ERROR_OK)
1492 buffer = malloc(size);
1493 if (buffer == NULL)
1495 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1496 return ERROR_INVALID_ARGUMENTS;
1498 retval = target_read_buffer(target, address, size, buffer);
1499 if (retval != ERROR_OK)
1501 free(buffer);
1502 return retval;
1505 /* convert to target endianess */
1506 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1508 uint32_t target_data;
1509 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1510 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1513 retval = image_calculate_checksum(buffer, size, &checksum);
1514 free(buffer);
1517 *crc = checksum;
1519 return retval;
1522 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1524 int retval;
1525 if (!target_was_examined(target))
1527 LOG_ERROR("Target not examined yet");
1528 return ERROR_FAIL;
1531 if (target->type->blank_check_memory == 0)
1532 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1534 retval = target->type->blank_check_memory(target, address, size, blank);
1536 return retval;
1539 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1541 uint8_t value_buf[4];
1542 if (!target_was_examined(target))
1544 LOG_ERROR("Target not examined yet");
1545 return ERROR_FAIL;
1548 int retval = target_read_memory(target, address, 4, 1, value_buf);
1550 if (retval == ERROR_OK)
1552 *value = target_buffer_get_u32(target, value_buf);
1553 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1554 address,
1555 *value);
1557 else
1559 *value = 0x0;
1560 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1561 address);
1564 return retval;
1567 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1569 uint8_t value_buf[2];
1570 if (!target_was_examined(target))
1572 LOG_ERROR("Target not examined yet");
1573 return ERROR_FAIL;
1576 int retval = target_read_memory(target, address, 2, 1, value_buf);
1578 if (retval == ERROR_OK)
1580 *value = target_buffer_get_u16(target, value_buf);
1581 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1582 address,
1583 *value);
1585 else
1587 *value = 0x0;
1588 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1589 address);
1592 return retval;
1595 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1597 int retval = target_read_memory(target, address, 1, 1, value);
1598 if (!target_was_examined(target))
1600 LOG_ERROR("Target not examined yet");
1601 return ERROR_FAIL;
1604 if (retval == ERROR_OK)
1606 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1607 address,
1608 *value);
1610 else
1612 *value = 0x0;
1613 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1614 address);
1617 return retval;
1620 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1622 int retval;
1623 uint8_t value_buf[4];
1624 if (!target_was_examined(target))
1626 LOG_ERROR("Target not examined yet");
1627 return ERROR_FAIL;
1630 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1631 address,
1632 value);
1634 target_buffer_set_u32(target, value_buf, value);
1635 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1637 LOG_DEBUG("failed: %i", retval);
1640 return retval;
1643 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1645 int retval;
1646 uint8_t value_buf[2];
1647 if (!target_was_examined(target))
1649 LOG_ERROR("Target not examined yet");
1650 return ERROR_FAIL;
1653 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1654 address,
1655 value);
1657 target_buffer_set_u16(target, value_buf, value);
1658 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1660 LOG_DEBUG("failed: %i", retval);
1663 return retval;
1666 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1668 int retval;
1669 if (!target_was_examined(target))
1671 LOG_ERROR("Target not examined yet");
1672 return ERROR_FAIL;
1675 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1676 address, value);
1678 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1680 LOG_DEBUG("failed: %i", retval);
1683 return retval;
1686 COMMAND_HANDLER(handle_targets_command)
1688 struct target *target = all_targets;
1690 if (CMD_ARGC == 1)
1692 target = get_target(CMD_ARGV[0]);
1693 if (target == NULL) {
1694 command_print(CMD_CTX,"Target: %s is unknown, try one of:\n", CMD_ARGV[0]);
1695 goto DumpTargets;
1697 if (!target->tap->enabled) {
1698 command_print(CMD_CTX,"Target: TAP %s is disabled, "
1699 "can't be the current target\n",
1700 target->tap->dotted_name);
1701 return ERROR_FAIL;
1704 CMD_CTX->current_target = target->target_number;
1705 return ERROR_OK;
1707 DumpTargets:
1709 target = all_targets;
1710 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
1711 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
1712 while (target)
1714 const char *state;
1715 char marker = ' ';
1717 if (target->tap->enabled)
1718 state = target_state_name( target );
1719 else
1720 state = "tap-disabled";
1722 if (CMD_CTX->current_target == target->target_number)
1723 marker = '*';
1725 /* keep columns lined up to match the headers above */
1726 command_print(CMD_CTX, "%2d%c %-18s %-10s %-6s %-18s %s",
1727 target->target_number,
1728 marker,
1729 target_name(target),
1730 target_type_name(target),
1731 Jim_Nvp_value2name_simple(nvp_target_endian,
1732 target->endianness)->name,
1733 target->tap->dotted_name,
1734 state);
1735 target = target->next;
1738 return ERROR_OK;
1741 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1743 static int powerDropout;
1744 static int srstAsserted;
1746 static int runPowerRestore;
1747 static int runPowerDropout;
1748 static int runSrstAsserted;
1749 static int runSrstDeasserted;
1751 static int sense_handler(void)
1753 static int prevSrstAsserted = 0;
1754 static int prevPowerdropout = 0;
1756 int retval;
1757 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1758 return retval;
1760 int powerRestored;
1761 powerRestored = prevPowerdropout && !powerDropout;
1762 if (powerRestored)
1764 runPowerRestore = 1;
1767 long long current = timeval_ms();
1768 static long long lastPower = 0;
1769 int waitMore = lastPower + 2000 > current;
1770 if (powerDropout && !waitMore)
1772 runPowerDropout = 1;
1773 lastPower = current;
1776 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1777 return retval;
1779 int srstDeasserted;
1780 srstDeasserted = prevSrstAsserted && !srstAsserted;
1782 static long long lastSrst = 0;
1783 waitMore = lastSrst + 2000 > current;
1784 if (srstDeasserted && !waitMore)
1786 runSrstDeasserted = 1;
1787 lastSrst = current;
1790 if (!prevSrstAsserted && srstAsserted)
1792 runSrstAsserted = 1;
1795 prevSrstAsserted = srstAsserted;
1796 prevPowerdropout = powerDropout;
1798 if (srstDeasserted || powerRestored)
1800 /* Other than logging the event we can't do anything here.
1801 * Issuing a reset is a particularly bad idea as we might
1802 * be inside a reset already.
1806 return ERROR_OK;
1809 static int backoff_times = 0;
1810 static int backoff_count = 0;
1812 /* process target state changes */
1813 static int handle_target(void *priv)
1815 Jim_Interp *interp = (Jim_Interp *)priv;
1816 int retval = ERROR_OK;
1818 if (!is_jtag_poll_safe())
1820 /* polling is disabled currently */
1821 return ERROR_OK;
1824 /* we do not want to recurse here... */
1825 static int recursive = 0;
1826 if (! recursive)
1828 recursive = 1;
1829 sense_handler();
1830 /* danger! running these procedures can trigger srst assertions and power dropouts.
1831 * We need to avoid an infinite loop/recursion here and we do that by
1832 * clearing the flags after running these events.
1834 int did_something = 0;
1835 if (runSrstAsserted)
1837 LOG_INFO("srst asserted detected, running srst_asserted proc.");
1838 Jim_Eval(interp, "srst_asserted");
1839 did_something = 1;
1841 if (runSrstDeasserted)
1843 Jim_Eval(interp, "srst_deasserted");
1844 did_something = 1;
1846 if (runPowerDropout)
1848 LOG_INFO("Power dropout detected, running power_dropout proc.");
1849 Jim_Eval(interp, "power_dropout");
1850 did_something = 1;
1852 if (runPowerRestore)
1854 Jim_Eval(interp, "power_restore");
1855 did_something = 1;
1858 if (did_something)
1860 /* clear detect flags */
1861 sense_handler();
1864 /* clear action flags */
1866 runSrstAsserted = 0;
1867 runSrstDeasserted = 0;
1868 runPowerRestore = 0;
1869 runPowerDropout = 0;
1871 recursive = 0;
1874 if (backoff_times > backoff_count)
1876 /* do not poll this time as we failed previously */
1877 backoff_count++;
1878 return ERROR_OK;
1880 backoff_count = 0;
1882 /* Poll targets for state changes unless that's globally disabled.
1883 * Skip targets that are currently disabled.
1885 for (struct target *target = all_targets;
1886 is_jtag_poll_safe() && target;
1887 target = target->next)
1889 if (!target->tap->enabled)
1890 continue;
1892 /* only poll target if we've got power and srst isn't asserted */
1893 if (!powerDropout && !srstAsserted)
1895 /* polling may fail silently until the target has been examined */
1896 if ((retval = target_poll(target)) != ERROR_OK)
1898 /* 100ms polling interval. Increase interval between polling up to 5000ms */
1899 if (backoff_times * polling_interval < 5000)
1901 backoff_times *= 2;
1902 backoff_times++;
1904 LOG_USER("Polling target failed, GDB will be halted. Polling again in %dms", backoff_times * polling_interval);
1906 /* Tell GDB to halt the debugger. This allows the user to
1907 * run monitor commands to handle the situation.
1909 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1910 return retval;
1912 /* Since we succeeded, we reset backoff count */
1913 if (backoff_times > 0)
1915 LOG_USER("Polling succeeded again");
1917 backoff_times = 0;
1921 return retval;
1924 COMMAND_HANDLER(handle_reg_command)
1926 struct target *target;
1927 struct reg *reg = NULL;
1928 unsigned count = 0;
1929 char *value;
1931 LOG_DEBUG("-");
1933 target = get_current_target(CMD_CTX);
1935 /* list all available registers for the current target */
1936 if (CMD_ARGC == 0)
1938 struct reg_cache *cache = target->reg_cache;
1940 count = 0;
1941 while (cache)
1943 unsigned i;
1945 command_print(CMD_CTX, "===== %s", cache->name);
1947 for (i = 0, reg = cache->reg_list;
1948 i < cache->num_regs;
1949 i++, reg++, count++)
1951 /* only print cached values if they are valid */
1952 if (reg->valid) {
1953 value = buf_to_str(reg->value,
1954 reg->size, 16);
1955 command_print(CMD_CTX,
1956 "(%i) %s (/%" PRIu32 "): 0x%s%s",
1957 count, reg->name,
1958 reg->size, value,
1959 reg->dirty
1960 ? " (dirty)"
1961 : "");
1962 free(value);
1963 } else {
1964 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
1965 count, reg->name,
1966 reg->size) ;
1969 cache = cache->next;
1972 return ERROR_OK;
1975 /* access a single register by its ordinal number */
1976 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9'))
1978 unsigned num;
1979 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
1981 struct reg_cache *cache = target->reg_cache;
1982 count = 0;
1983 while (cache)
1985 unsigned i;
1986 for (i = 0; i < cache->num_regs; i++)
1988 if (count++ == num)
1990 reg = &cache->reg_list[i];
1991 break;
1994 if (reg)
1995 break;
1996 cache = cache->next;
1999 if (!reg)
2001 command_print(CMD_CTX, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
2002 return ERROR_OK;
2004 } else /* access a single register by its name */
2006 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2008 if (!reg)
2010 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2011 return ERROR_OK;
2015 /* display a register */
2016 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0') && (CMD_ARGV[1][0] <= '9'))))
2018 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2019 reg->valid = 0;
2021 if (reg->valid == 0)
2023 reg->type->get(reg);
2025 value = buf_to_str(reg->value, reg->size, 16);
2026 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2027 free(value);
2028 return ERROR_OK;
2031 /* set register value */
2032 if (CMD_ARGC == 2)
2034 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2035 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2037 reg->type->set(reg, buf);
2039 value = buf_to_str(reg->value, reg->size, 16);
2040 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2041 free(value);
2043 free(buf);
2045 return ERROR_OK;
2048 command_print(CMD_CTX, "usage: reg <#|name> [value]");
2050 return ERROR_OK;
2053 COMMAND_HANDLER(handle_poll_command)
2055 int retval = ERROR_OK;
2056 struct target *target = get_current_target(CMD_CTX);
2058 if (CMD_ARGC == 0)
2060 command_print(CMD_CTX, "background polling: %s",
2061 jtag_poll_get_enabled() ? "on" : "off");
2062 command_print(CMD_CTX, "TAP: %s (%s)",
2063 target->tap->dotted_name,
2064 target->tap->enabled ? "enabled" : "disabled");
2065 if (!target->tap->enabled)
2066 return ERROR_OK;
2067 if ((retval = target_poll(target)) != ERROR_OK)
2068 return retval;
2069 if ((retval = target_arch_state(target)) != ERROR_OK)
2070 return retval;
2072 else if (CMD_ARGC == 1)
2074 bool enable;
2075 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2076 jtag_poll_set_enabled(enable);
2078 else
2080 return ERROR_COMMAND_SYNTAX_ERROR;
2083 return retval;
2086 COMMAND_HANDLER(handle_wait_halt_command)
2088 if (CMD_ARGC > 1)
2089 return ERROR_COMMAND_SYNTAX_ERROR;
2091 unsigned ms = 5000;
2092 if (1 == CMD_ARGC)
2094 int retval = parse_uint(CMD_ARGV[0], &ms);
2095 if (ERROR_OK != retval)
2097 command_print(CMD_CTX, "usage: %s [seconds]", CMD_NAME);
2098 return ERROR_COMMAND_SYNTAX_ERROR;
2100 // convert seconds (given) to milliseconds (needed)
2101 ms *= 1000;
2104 struct target *target = get_current_target(CMD_CTX);
2105 return target_wait_state(target, TARGET_HALTED, ms);
2108 /* wait for target state to change. The trick here is to have a low
2109 * latency for short waits and not to suck up all the CPU time
2110 * on longer waits.
2112 * After 500ms, keep_alive() is invoked
2114 int target_wait_state(struct target *target, enum target_state state, int ms)
2116 int retval;
2117 long long then = 0, cur;
2118 int once = 1;
2120 for (;;)
2122 if ((retval = target_poll(target)) != ERROR_OK)
2123 return retval;
2124 if (target->state == state)
2126 break;
2128 cur = timeval_ms();
2129 if (once)
2131 once = 0;
2132 then = timeval_ms();
2133 LOG_DEBUG("waiting for target %s...",
2134 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2137 if (cur-then > 500)
2139 keep_alive();
2142 if ((cur-then) > ms)
2144 LOG_ERROR("timed out while waiting for target %s",
2145 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2146 return ERROR_FAIL;
2150 return ERROR_OK;
2153 COMMAND_HANDLER(handle_halt_command)
2155 LOG_DEBUG("-");
2157 struct target *target = get_current_target(CMD_CTX);
2158 int retval = target_halt(target);
2159 if (ERROR_OK != retval)
2160 return retval;
2162 if (CMD_ARGC == 1)
2164 unsigned wait_local;
2165 retval = parse_uint(CMD_ARGV[0], &wait_local);
2166 if (ERROR_OK != retval)
2167 return ERROR_COMMAND_SYNTAX_ERROR;
2168 if (!wait_local)
2169 return ERROR_OK;
2172 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2175 COMMAND_HANDLER(handle_soft_reset_halt_command)
2177 struct target *target = get_current_target(CMD_CTX);
2179 LOG_USER("requesting target halt and executing a soft reset");
2181 target->type->soft_reset_halt(target);
2183 return ERROR_OK;
2186 COMMAND_HANDLER(handle_reset_command)
2188 if (CMD_ARGC > 1)
2189 return ERROR_COMMAND_SYNTAX_ERROR;
2191 enum target_reset_mode reset_mode = RESET_RUN;
2192 if (CMD_ARGC == 1)
2194 const Jim_Nvp *n;
2195 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2196 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2197 return ERROR_COMMAND_SYNTAX_ERROR;
2199 reset_mode = n->value;
2202 /* reset *all* targets */
2203 return target_process_reset(CMD_CTX, reset_mode);
2207 COMMAND_HANDLER(handle_resume_command)
2209 int current = 1;
2210 if (CMD_ARGC > 1)
2211 return ERROR_COMMAND_SYNTAX_ERROR;
2213 struct target *target = get_current_target(CMD_CTX);
2214 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2216 /* with no CMD_ARGV, resume from current pc, addr = 0,
2217 * with one arguments, addr = CMD_ARGV[0],
2218 * handle breakpoints, not debugging */
2219 uint32_t addr = 0;
2220 if (CMD_ARGC == 1)
2222 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2223 current = 0;
2226 return target_resume(target, current, addr, 1, 0);
2229 COMMAND_HANDLER(handle_step_command)
2231 if (CMD_ARGC > 1)
2232 return ERROR_COMMAND_SYNTAX_ERROR;
2234 LOG_DEBUG("-");
2236 /* with no CMD_ARGV, step from current pc, addr = 0,
2237 * with one argument addr = CMD_ARGV[0],
2238 * handle breakpoints, debugging */
2239 uint32_t addr = 0;
2240 int current_pc = 1;
2241 if (CMD_ARGC == 1)
2243 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2244 current_pc = 0;
2247 struct target *target = get_current_target(CMD_CTX);
2249 return target->type->step(target, current_pc, addr, 1);
2252 static void handle_md_output(struct command_context *cmd_ctx,
2253 struct target *target, uint32_t address, unsigned size,
2254 unsigned count, const uint8_t *buffer)
2256 const unsigned line_bytecnt = 32;
2257 unsigned line_modulo = line_bytecnt / size;
2259 char output[line_bytecnt * 4 + 1];
2260 unsigned output_len = 0;
2262 const char *value_fmt;
2263 switch (size) {
2264 case 4: value_fmt = "%8.8x "; break;
2265 case 2: value_fmt = "%4.4x "; break;
2266 case 1: value_fmt = "%2.2x "; break;
2267 default:
2268 /* "can't happen", caller checked */
2269 LOG_ERROR("invalid memory read size: %u", size);
2270 return;
2273 for (unsigned i = 0; i < count; i++)
2275 if (i % line_modulo == 0)
2277 output_len += snprintf(output + output_len,
2278 sizeof(output) - output_len,
2279 "0x%8.8x: ",
2280 (unsigned)(address + (i*size)));
2283 uint32_t value = 0;
2284 const uint8_t *value_ptr = buffer + i * size;
2285 switch (size) {
2286 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2287 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2288 case 1: value = *value_ptr;
2290 output_len += snprintf(output + output_len,
2291 sizeof(output) - output_len,
2292 value_fmt, value);
2294 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2296 command_print(cmd_ctx, "%s", output);
2297 output_len = 0;
2302 COMMAND_HANDLER(handle_md_command)
2304 if (CMD_ARGC < 1)
2305 return ERROR_COMMAND_SYNTAX_ERROR;
2307 unsigned size = 0;
2308 switch (CMD_NAME[2]) {
2309 case 'w': size = 4; break;
2310 case 'h': size = 2; break;
2311 case 'b': size = 1; break;
2312 default: return ERROR_COMMAND_SYNTAX_ERROR;
2315 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2316 int (*fn)(struct target *target,
2317 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2318 if (physical)
2320 CMD_ARGC--;
2321 CMD_ARGV++;
2322 fn=target_read_phys_memory;
2323 } else
2325 fn=target_read_memory;
2327 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2329 return ERROR_COMMAND_SYNTAX_ERROR;
2332 uint32_t address;
2333 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2335 unsigned count = 1;
2336 if (CMD_ARGC == 2)
2337 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2339 uint8_t *buffer = calloc(count, size);
2341 struct target *target = get_current_target(CMD_CTX);
2342 int retval = fn(target, address, size, count, buffer);
2343 if (ERROR_OK == retval)
2344 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2346 free(buffer);
2348 return retval;
2351 typedef int (*target_write_fn)(struct target *target,
2352 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2354 static int target_write_memory_fast(struct target *target,
2355 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
2357 return target_write_buffer(target, address, size * count, buffer);
2360 static int target_fill_mem(struct target *target,
2361 uint32_t address,
2362 target_write_fn fn,
2363 unsigned data_size,
2364 /* value */
2365 uint32_t b,
2366 /* count */
2367 unsigned c)
2369 /* We have to write in reasonably large chunks to be able
2370 * to fill large memory areas with any sane speed */
2371 const unsigned chunk_size = 16384;
2372 uint8_t *target_buf = malloc(chunk_size * data_size);
2373 if (target_buf == NULL)
2375 LOG_ERROR("Out of memory");
2376 return ERROR_FAIL;
2379 for (unsigned i = 0; i < chunk_size; i ++)
2381 switch (data_size)
2383 case 4:
2384 target_buffer_set_u32(target, target_buf + i*data_size, b);
2385 break;
2386 case 2:
2387 target_buffer_set_u16(target, target_buf + i*data_size, b);
2388 break;
2389 case 1:
2390 target_buffer_set_u8(target, target_buf + i*data_size, b);
2391 break;
2392 default:
2393 exit(-1);
2397 int retval = ERROR_OK;
2399 for (unsigned x = 0; x < c; x += chunk_size)
2401 unsigned current;
2402 current = c - x;
2403 if (current > chunk_size)
2405 current = chunk_size;
2407 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2408 if (retval != ERROR_OK)
2410 break;
2412 /* avoid GDB timeouts */
2413 keep_alive();
2415 free(target_buf);
2417 return retval;
2421 COMMAND_HANDLER(handle_mw_command)
2423 if (CMD_ARGC < 2)
2425 return ERROR_COMMAND_SYNTAX_ERROR;
2427 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2428 target_write_fn fn;
2429 if (physical)
2431 CMD_ARGC--;
2432 CMD_ARGV++;
2433 fn=target_write_phys_memory;
2434 } else
2436 fn = target_write_memory_fast;
2438 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2439 return ERROR_COMMAND_SYNTAX_ERROR;
2441 uint32_t address;
2442 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2444 uint32_t value;
2445 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2447 unsigned count = 1;
2448 if (CMD_ARGC == 3)
2449 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2451 struct target *target = get_current_target(CMD_CTX);
2452 unsigned wordsize;
2453 switch (CMD_NAME[2])
2455 case 'w':
2456 wordsize = 4;
2457 break;
2458 case 'h':
2459 wordsize = 2;
2460 break;
2461 case 'b':
2462 wordsize = 1;
2463 break;
2464 default:
2465 return ERROR_COMMAND_SYNTAX_ERROR;
2468 return target_fill_mem(target, address, fn, wordsize, value, count);
2471 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2472 uint32_t *min_address, uint32_t *max_address)
2474 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2475 return ERROR_COMMAND_SYNTAX_ERROR;
2477 /* a base address isn't always necessary,
2478 * default to 0x0 (i.e. don't relocate) */
2479 if (CMD_ARGC >= 2)
2481 uint32_t addr;
2482 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2483 image->base_address = addr;
2484 image->base_address_set = 1;
2486 else
2487 image->base_address_set = 0;
2489 image->start_address_set = 0;
2491 if (CMD_ARGC >= 4)
2493 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2495 if (CMD_ARGC == 5)
2497 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2498 // use size (given) to find max (required)
2499 *max_address += *min_address;
2502 if (*min_address > *max_address)
2503 return ERROR_COMMAND_SYNTAX_ERROR;
2505 return ERROR_OK;
2508 COMMAND_HANDLER(handle_load_image_command)
2510 uint8_t *buffer;
2511 size_t buf_cnt;
2512 uint32_t image_size;
2513 uint32_t min_address = 0;
2514 uint32_t max_address = 0xffffffff;
2515 int i;
2516 struct image image;
2518 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2519 &image, &min_address, &max_address);
2520 if (ERROR_OK != retval)
2521 return retval;
2523 struct target *target = get_current_target(CMD_CTX);
2525 struct duration bench;
2526 duration_start(&bench);
2528 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2530 return ERROR_OK;
2533 image_size = 0x0;
2534 retval = ERROR_OK;
2535 for (i = 0; i < image.num_sections; i++)
2537 buffer = malloc(image.sections[i].size);
2538 if (buffer == NULL)
2540 command_print(CMD_CTX,
2541 "error allocating buffer for section (%d bytes)",
2542 (int)(image.sections[i].size));
2543 break;
2546 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2548 free(buffer);
2549 break;
2552 uint32_t offset = 0;
2553 uint32_t length = buf_cnt;
2555 /* DANGER!!! beware of unsigned comparision here!!! */
2557 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2558 (image.sections[i].base_address < max_address))
2560 if (image.sections[i].base_address < min_address)
2562 /* clip addresses below */
2563 offset += min_address-image.sections[i].base_address;
2564 length -= offset;
2567 if (image.sections[i].base_address + buf_cnt > max_address)
2569 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2572 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2574 free(buffer);
2575 break;
2577 image_size += length;
2578 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2579 (unsigned int)length,
2580 image.sections[i].base_address + offset);
2583 free(buffer);
2586 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2588 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2589 "in %fs (%0.3f KiB/s)", image_size,
2590 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2593 image_close(&image);
2595 return retval;
2599 COMMAND_HANDLER(handle_dump_image_command)
2601 struct fileio fileio;
2602 uint8_t buffer[560];
2603 int retval, retvaltemp;
2604 uint32_t address, size;
2605 struct duration bench;
2606 struct target *target = get_current_target(CMD_CTX);
2608 if (CMD_ARGC != 3)
2609 return ERROR_COMMAND_SYNTAX_ERROR;
2611 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2612 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2614 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2615 if (retval != ERROR_OK)
2616 return retval;
2618 duration_start(&bench);
2620 retval = ERROR_OK;
2621 while (size > 0)
2623 size_t size_written;
2624 uint32_t this_run_size = (size > 560) ? 560 : size;
2625 retval = target_read_buffer(target, address, this_run_size, buffer);
2626 if (retval != ERROR_OK)
2628 break;
2631 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2632 if (retval != ERROR_OK)
2634 break;
2637 size -= this_run_size;
2638 address += this_run_size;
2641 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2643 int filesize;
2644 retval = fileio_size(&fileio, &filesize);
2645 if (retval != ERROR_OK)
2646 return retval;
2647 command_print(CMD_CTX,
2648 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
2649 duration_elapsed(&bench), duration_kbps(&bench, filesize));
2652 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2653 return retvaltemp;
2655 return retval;
2658 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2660 uint8_t *buffer;
2661 size_t buf_cnt;
2662 uint32_t image_size;
2663 int i;
2664 int retval;
2665 uint32_t checksum = 0;
2666 uint32_t mem_checksum = 0;
2668 struct image image;
2670 struct target *target = get_current_target(CMD_CTX);
2672 if (CMD_ARGC < 1)
2674 return ERROR_COMMAND_SYNTAX_ERROR;
2677 if (!target)
2679 LOG_ERROR("no target selected");
2680 return ERROR_FAIL;
2683 struct duration bench;
2684 duration_start(&bench);
2686 if (CMD_ARGC >= 2)
2688 uint32_t addr;
2689 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2690 image.base_address = addr;
2691 image.base_address_set = 1;
2693 else
2695 image.base_address_set = 0;
2696 image.base_address = 0x0;
2699 image.start_address_set = 0;
2701 if ((retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL)) != ERROR_OK)
2703 return retval;
2706 image_size = 0x0;
2707 int diffs = 0;
2708 retval = ERROR_OK;
2709 for (i = 0; i < image.num_sections; i++)
2711 buffer = malloc(image.sections[i].size);
2712 if (buffer == NULL)
2714 command_print(CMD_CTX,
2715 "error allocating buffer for section (%d bytes)",
2716 (int)(image.sections[i].size));
2717 break;
2719 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2721 free(buffer);
2722 break;
2725 if (verify)
2727 /* calculate checksum of image */
2728 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
2729 if (retval != ERROR_OK)
2731 free(buffer);
2732 break;
2735 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2736 if (retval != ERROR_OK)
2738 free(buffer);
2739 break;
2742 if (checksum != mem_checksum)
2744 /* failed crc checksum, fall back to a binary compare */
2745 uint8_t *data;
2747 if (diffs == 0)
2749 LOG_ERROR("checksum mismatch - attempting binary compare");
2752 data = (uint8_t*)malloc(buf_cnt);
2754 /* Can we use 32bit word accesses? */
2755 int size = 1;
2756 int count = buf_cnt;
2757 if ((count % 4) == 0)
2759 size *= 4;
2760 count /= 4;
2762 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2763 if (retval == ERROR_OK)
2765 uint32_t t;
2766 for (t = 0; t < buf_cnt; t++)
2768 if (data[t] != buffer[t])
2770 command_print(CMD_CTX,
2771 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
2772 diffs,
2773 (unsigned)(t + image.sections[i].base_address),
2774 data[t],
2775 buffer[t]);
2776 if (diffs++ >= 127)
2778 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
2779 free(data);
2780 free(buffer);
2781 goto done;
2784 keep_alive();
2787 free(data);
2789 } else
2791 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
2792 image.sections[i].base_address,
2793 buf_cnt);
2796 free(buffer);
2797 image_size += buf_cnt;
2799 if (diffs > 0)
2801 command_print(CMD_CTX, "No more differences found.");
2803 done:
2804 if (diffs > 0)
2806 retval = ERROR_FAIL;
2808 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2810 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
2811 "in %fs (%0.3f KiB/s)", image_size,
2812 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2815 image_close(&image);
2817 return retval;
2820 COMMAND_HANDLER(handle_verify_image_command)
2822 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2825 COMMAND_HANDLER(handle_test_image_command)
2827 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2830 static int handle_bp_command_list(struct command_context *cmd_ctx)
2832 struct target *target = get_current_target(cmd_ctx);
2833 struct breakpoint *breakpoint = target->breakpoints;
2834 while (breakpoint)
2836 if (breakpoint->type == BKPT_SOFT)
2838 char* buf = buf_to_str(breakpoint->orig_instr,
2839 breakpoint->length, 16);
2840 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2841 breakpoint->address,
2842 breakpoint->length,
2843 breakpoint->set, buf);
2844 free(buf);
2846 else
2848 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2849 breakpoint->address,
2850 breakpoint->length, breakpoint->set);
2853 breakpoint = breakpoint->next;
2855 return ERROR_OK;
2858 static int handle_bp_command_set(struct command_context *cmd_ctx,
2859 uint32_t addr, uint32_t length, int hw)
2861 struct target *target = get_current_target(cmd_ctx);
2862 int retval = breakpoint_add(target, addr, length, hw);
2863 if (ERROR_OK == retval)
2864 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2865 else
2866 LOG_ERROR("Failure setting breakpoint");
2867 return retval;
2870 COMMAND_HANDLER(handle_bp_command)
2872 if (CMD_ARGC == 0)
2873 return handle_bp_command_list(CMD_CTX);
2875 if (CMD_ARGC < 2 || CMD_ARGC > 3)
2877 command_print(CMD_CTX, "usage: bp <address> <length> ['hw']");
2878 return ERROR_COMMAND_SYNTAX_ERROR;
2881 uint32_t addr;
2882 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2883 uint32_t length;
2884 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2886 int hw = BKPT_SOFT;
2887 if (CMD_ARGC == 3)
2889 if (strcmp(CMD_ARGV[2], "hw") == 0)
2890 hw = BKPT_HARD;
2891 else
2892 return ERROR_COMMAND_SYNTAX_ERROR;
2895 return handle_bp_command_set(CMD_CTX, addr, length, hw);
2898 COMMAND_HANDLER(handle_rbp_command)
2900 if (CMD_ARGC != 1)
2901 return ERROR_COMMAND_SYNTAX_ERROR;
2903 uint32_t addr;
2904 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2906 struct target *target = get_current_target(CMD_CTX);
2907 breakpoint_remove(target, addr);
2909 return ERROR_OK;
2912 COMMAND_HANDLER(handle_wp_command)
2914 struct target *target = get_current_target(CMD_CTX);
2916 if (CMD_ARGC == 0)
2918 struct watchpoint *watchpoint = target->watchpoints;
2920 while (watchpoint)
2922 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
2923 ", len: 0x%8.8" PRIx32
2924 ", r/w/a: %i, value: 0x%8.8" PRIx32
2925 ", mask: 0x%8.8" PRIx32,
2926 watchpoint->address,
2927 watchpoint->length,
2928 (int)watchpoint->rw,
2929 watchpoint->value,
2930 watchpoint->mask);
2931 watchpoint = watchpoint->next;
2933 return ERROR_OK;
2936 enum watchpoint_rw type = WPT_ACCESS;
2937 uint32_t addr = 0;
2938 uint32_t length = 0;
2939 uint32_t data_value = 0x0;
2940 uint32_t data_mask = 0xffffffff;
2942 switch (CMD_ARGC)
2944 case 5:
2945 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
2946 // fall through
2947 case 4:
2948 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
2949 // fall through
2950 case 3:
2951 switch (CMD_ARGV[2][0])
2953 case 'r':
2954 type = WPT_READ;
2955 break;
2956 case 'w':
2957 type = WPT_WRITE;
2958 break;
2959 case 'a':
2960 type = WPT_ACCESS;
2961 break;
2962 default:
2963 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
2964 return ERROR_COMMAND_SYNTAX_ERROR;
2966 // fall through
2967 case 2:
2968 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2969 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2970 break;
2972 default:
2973 command_print(CMD_CTX, "usage: wp [address length "
2974 "[(r|w|a) [value [mask]]]]");
2975 return ERROR_COMMAND_SYNTAX_ERROR;
2978 int retval = watchpoint_add(target, addr, length, type,
2979 data_value, data_mask);
2980 if (ERROR_OK != retval)
2981 LOG_ERROR("Failure setting watchpoints");
2983 return retval;
2986 COMMAND_HANDLER(handle_rwp_command)
2988 if (CMD_ARGC != 1)
2989 return ERROR_COMMAND_SYNTAX_ERROR;
2991 uint32_t addr;
2992 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2994 struct target *target = get_current_target(CMD_CTX);
2995 watchpoint_remove(target, addr);
2997 return ERROR_OK;
3002 * Translate a virtual address to a physical address.
3004 * The low-level target implementation must have logged a detailed error
3005 * which is forwarded to telnet/GDB session.
3007 COMMAND_HANDLER(handle_virt2phys_command)
3009 if (CMD_ARGC != 1)
3010 return ERROR_COMMAND_SYNTAX_ERROR;
3012 uint32_t va;
3013 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3014 uint32_t pa;
3016 struct target *target = get_current_target(CMD_CTX);
3017 int retval = target->type->virt2phys(target, va, &pa);
3018 if (retval == ERROR_OK)
3019 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3021 return retval;
3024 static void writeData(FILE *f, const void *data, size_t len)
3026 size_t written = fwrite(data, 1, len, f);
3027 if (written != len)
3028 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3031 static void writeLong(FILE *f, int l)
3033 int i;
3034 for (i = 0; i < 4; i++)
3036 char c = (l >> (i*8))&0xff;
3037 writeData(f, &c, 1);
3042 static void writeString(FILE *f, char *s)
3044 writeData(f, s, strlen(s));
3047 /* Dump a gmon.out histogram file. */
3048 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3050 uint32_t i;
3051 FILE *f = fopen(filename, "w");
3052 if (f == NULL)
3053 return;
3054 writeString(f, "gmon");
3055 writeLong(f, 0x00000001); /* Version */
3056 writeLong(f, 0); /* padding */
3057 writeLong(f, 0); /* padding */
3058 writeLong(f, 0); /* padding */
3060 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3061 writeData(f, &zero, 1);
3063 /* figure out bucket size */
3064 uint32_t min = samples[0];
3065 uint32_t max = samples[0];
3066 for (i = 0; i < sampleNum; i++)
3068 if (min > samples[i])
3070 min = samples[i];
3072 if (max < samples[i])
3074 max = samples[i];
3078 int addressSpace = (max-min + 1);
3080 static const uint32_t maxBuckets = 16 * 1024; /* maximum buckets. */
3081 uint32_t length = addressSpace;
3082 if (length > maxBuckets)
3084 length = maxBuckets;
3086 int *buckets = malloc(sizeof(int)*length);
3087 if (buckets == NULL)
3089 fclose(f);
3090 return;
3092 memset(buckets, 0, sizeof(int)*length);
3093 for (i = 0; i < sampleNum;i++)
3095 uint32_t address = samples[i];
3096 long long a = address-min;
3097 long long b = length-1;
3098 long long c = addressSpace-1;
3099 int index_t = (a*b)/c; /* danger!!!! int32 overflows */
3100 buckets[index_t]++;
3103 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3104 writeLong(f, min); /* low_pc */
3105 writeLong(f, max); /* high_pc */
3106 writeLong(f, length); /* # of samples */
3107 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3108 writeString(f, "seconds");
3109 for (i = 0; i < (15-strlen("seconds")); i++)
3110 writeData(f, &zero, 1);
3111 writeString(f, "s");
3113 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3115 char *data = malloc(2*length);
3116 if (data != NULL)
3118 for (i = 0; i < length;i++)
3120 int val;
3121 val = buckets[i];
3122 if (val > 65535)
3124 val = 65535;
3126 data[i*2]=val&0xff;
3127 data[i*2 + 1]=(val >> 8)&0xff;
3129 free(buckets);
3130 writeData(f, data, length * 2);
3131 free(data);
3132 } else
3134 free(buckets);
3137 fclose(f);
3140 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3141 * which will be used as a random sampling of PC */
3142 COMMAND_HANDLER(handle_profile_command)
3144 struct target *target = get_current_target(CMD_CTX);
3145 struct timeval timeout, now;
3147 gettimeofday(&timeout, NULL);
3148 if (CMD_ARGC != 2)
3150 return ERROR_COMMAND_SYNTAX_ERROR;
3152 unsigned offset;
3153 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3155 timeval_add_time(&timeout, offset, 0);
3158 * @todo: Some cores let us sample the PC without the
3159 * annoying halt/resume step; for example, ARMv7 PCSR.
3160 * Provide a way to use that more efficient mechanism.
3163 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3165 static const int maxSample = 10000;
3166 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3167 if (samples == NULL)
3168 return ERROR_OK;
3170 int numSamples = 0;
3171 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3172 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3174 for (;;)
3176 int retval;
3177 target_poll(target);
3178 if (target->state == TARGET_HALTED)
3180 uint32_t t=*((uint32_t *)reg->value);
3181 samples[numSamples++]=t;
3182 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3183 target_poll(target);
3184 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3185 } else if (target->state == TARGET_RUNNING)
3187 /* We want to quickly sample the PC. */
3188 if ((retval = target_halt(target)) != ERROR_OK)
3190 free(samples);
3191 return retval;
3193 } else
3195 command_print(CMD_CTX, "Target not halted or running");
3196 retval = ERROR_OK;
3197 break;
3199 if (retval != ERROR_OK)
3201 break;
3204 gettimeofday(&now, NULL);
3205 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3207 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3208 if ((retval = target_poll(target)) != ERROR_OK)
3210 free(samples);
3211 return retval;
3213 if (target->state == TARGET_HALTED)
3215 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3217 if ((retval = target_poll(target)) != ERROR_OK)
3219 free(samples);
3220 return retval;
3222 writeGmon(samples, numSamples, CMD_ARGV[1]);
3223 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3224 break;
3227 free(samples);
3229 return ERROR_OK;
3232 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3234 char *namebuf;
3235 Jim_Obj *nameObjPtr, *valObjPtr;
3236 int result;
3238 namebuf = alloc_printf("%s(%d)", varname, idx);
3239 if (!namebuf)
3240 return JIM_ERR;
3242 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3243 valObjPtr = Jim_NewIntObj(interp, val);
3244 if (!nameObjPtr || !valObjPtr)
3246 free(namebuf);
3247 return JIM_ERR;
3250 Jim_IncrRefCount(nameObjPtr);
3251 Jim_IncrRefCount(valObjPtr);
3252 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3253 Jim_DecrRefCount(interp, nameObjPtr);
3254 Jim_DecrRefCount(interp, valObjPtr);
3255 free(namebuf);
3256 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3257 return result;
3260 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3262 struct command_context *context;
3263 struct target *target;
3265 context = current_command_context(interp);
3266 assert (context != NULL);
3268 target = get_current_target(context);
3269 if (target == NULL)
3271 LOG_ERROR("mem2array: no current target");
3272 return JIM_ERR;
3275 return target_mem2array(interp, target, argc-1, argv + 1);
3278 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3280 long l;
3281 uint32_t width;
3282 int len;
3283 uint32_t addr;
3284 uint32_t count;
3285 uint32_t v;
3286 const char *varname;
3287 int n, e, retval;
3288 uint32_t i;
3290 /* argv[1] = name of array to receive the data
3291 * argv[2] = desired width
3292 * argv[3] = memory address
3293 * argv[4] = count of times to read
3295 if (argc != 4) {
3296 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3297 return JIM_ERR;
3299 varname = Jim_GetString(argv[0], &len);
3300 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3302 e = Jim_GetLong(interp, argv[1], &l);
3303 width = l;
3304 if (e != JIM_OK) {
3305 return e;
3308 e = Jim_GetLong(interp, argv[2], &l);
3309 addr = l;
3310 if (e != JIM_OK) {
3311 return e;
3313 e = Jim_GetLong(interp, argv[3], &l);
3314 len = l;
3315 if (e != JIM_OK) {
3316 return e;
3318 switch (width) {
3319 case 8:
3320 width = 1;
3321 break;
3322 case 16:
3323 width = 2;
3324 break;
3325 case 32:
3326 width = 4;
3327 break;
3328 default:
3329 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3330 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3331 return JIM_ERR;
3333 if (len == 0) {
3334 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3335 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3336 return JIM_ERR;
3338 if ((addr + (len * width)) < addr) {
3339 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3340 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3341 return JIM_ERR;
3343 /* absurd transfer size? */
3344 if (len > 65536) {
3345 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3346 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3347 return JIM_ERR;
3350 if ((width == 1) ||
3351 ((width == 2) && ((addr & 1) == 0)) ||
3352 ((width == 4) && ((addr & 3) == 0))) {
3353 /* all is well */
3354 } else {
3355 char buf[100];
3356 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3357 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3358 addr,
3359 width);
3360 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3361 return JIM_ERR;
3364 /* Transfer loop */
3366 /* index counter */
3367 n = 0;
3369 size_t buffersize = 4096;
3370 uint8_t *buffer = malloc(buffersize);
3371 if (buffer == NULL)
3372 return JIM_ERR;
3374 /* assume ok */
3375 e = JIM_OK;
3376 while (len) {
3377 /* Slurp... in buffer size chunks */
3379 count = len; /* in objects.. */
3380 if (count > (buffersize/width)) {
3381 count = (buffersize/width);
3384 retval = target_read_memory(target, addr, width, count, buffer);
3385 if (retval != ERROR_OK) {
3386 /* BOO !*/
3387 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3388 (unsigned int)addr,
3389 (int)width,
3390 (int)count);
3391 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3392 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3393 e = JIM_ERR;
3394 len = 0;
3395 } else {
3396 v = 0; /* shut up gcc */
3397 for (i = 0 ;i < count ;i++, n++) {
3398 switch (width) {
3399 case 4:
3400 v = target_buffer_get_u32(target, &buffer[i*width]);
3401 break;
3402 case 2:
3403 v = target_buffer_get_u16(target, &buffer[i*width]);
3404 break;
3405 case 1:
3406 v = buffer[i] & 0x0ff;
3407 break;
3409 new_int_array_element(interp, varname, n, v);
3411 len -= count;
3415 free(buffer);
3417 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3419 return JIM_OK;
3422 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3424 char *namebuf;
3425 Jim_Obj *nameObjPtr, *valObjPtr;
3426 int result;
3427 long l;
3429 namebuf = alloc_printf("%s(%d)", varname, idx);
3430 if (!namebuf)
3431 return JIM_ERR;
3433 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3434 if (!nameObjPtr)
3436 free(namebuf);
3437 return JIM_ERR;
3440 Jim_IncrRefCount(nameObjPtr);
3441 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3442 Jim_DecrRefCount(interp, nameObjPtr);
3443 free(namebuf);
3444 if (valObjPtr == NULL)
3445 return JIM_ERR;
3447 result = Jim_GetLong(interp, valObjPtr, &l);
3448 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3449 *val = l;
3450 return result;
3453 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3455 struct command_context *context;
3456 struct target *target;
3458 context = current_command_context(interp);
3459 assert (context != NULL);
3461 target = get_current_target(context);
3462 if (target == NULL) {
3463 LOG_ERROR("array2mem: no current target");
3464 return JIM_ERR;
3467 return target_array2mem(interp,target, argc-1, argv + 1);
3470 static int target_array2mem(Jim_Interp *interp, struct target *target,
3471 int argc, Jim_Obj *const *argv)
3473 long l;
3474 uint32_t width;
3475 int len;
3476 uint32_t addr;
3477 uint32_t count;
3478 uint32_t v;
3479 const char *varname;
3480 int n, e, retval;
3481 uint32_t i;
3483 /* argv[1] = name of array to get the data
3484 * argv[2] = desired width
3485 * argv[3] = memory address
3486 * argv[4] = count to write
3488 if (argc != 4) {
3489 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3490 return JIM_ERR;
3492 varname = Jim_GetString(argv[0], &len);
3493 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3495 e = Jim_GetLong(interp, argv[1], &l);
3496 width = l;
3497 if (e != JIM_OK) {
3498 return e;
3501 e = Jim_GetLong(interp, argv[2], &l);
3502 addr = l;
3503 if (e != JIM_OK) {
3504 return e;
3506 e = Jim_GetLong(interp, argv[3], &l);
3507 len = l;
3508 if (e != JIM_OK) {
3509 return e;
3511 switch (width) {
3512 case 8:
3513 width = 1;
3514 break;
3515 case 16:
3516 width = 2;
3517 break;
3518 case 32:
3519 width = 4;
3520 break;
3521 default:
3522 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3523 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3524 return JIM_ERR;
3526 if (len == 0) {
3527 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3528 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3529 return JIM_ERR;
3531 if ((addr + (len * width)) < addr) {
3532 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3533 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3534 return JIM_ERR;
3536 /* absurd transfer size? */
3537 if (len > 65536) {
3538 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3539 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3540 return JIM_ERR;
3543 if ((width == 1) ||
3544 ((width == 2) && ((addr & 1) == 0)) ||
3545 ((width == 4) && ((addr & 3) == 0))) {
3546 /* all is well */
3547 } else {
3548 char buf[100];
3549 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3550 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3551 (unsigned int)addr,
3552 (int)width);
3553 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3554 return JIM_ERR;
3557 /* Transfer loop */
3559 /* index counter */
3560 n = 0;
3561 /* assume ok */
3562 e = JIM_OK;
3564 size_t buffersize = 4096;
3565 uint8_t *buffer = malloc(buffersize);
3566 if (buffer == NULL)
3567 return JIM_ERR;
3569 while (len) {
3570 /* Slurp... in buffer size chunks */
3572 count = len; /* in objects.. */
3573 if (count > (buffersize/width)) {
3574 count = (buffersize/width);
3577 v = 0; /* shut up gcc */
3578 for (i = 0 ;i < count ;i++, n++) {
3579 get_int_array_element(interp, varname, n, &v);
3580 switch (width) {
3581 case 4:
3582 target_buffer_set_u32(target, &buffer[i*width], v);
3583 break;
3584 case 2:
3585 target_buffer_set_u16(target, &buffer[i*width], v);
3586 break;
3587 case 1:
3588 buffer[i] = v & 0x0ff;
3589 break;
3592 len -= count;
3594 retval = target_write_memory(target, addr, width, count, buffer);
3595 if (retval != ERROR_OK) {
3596 /* BOO !*/
3597 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3598 (unsigned int)addr,
3599 (int)width,
3600 (int)count);
3601 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3602 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3603 e = JIM_ERR;
3604 len = 0;
3608 free(buffer);
3610 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3612 return JIM_OK;
3615 /* FIX? should we propagate errors here rather than printing them
3616 * and continuing?
3618 void target_handle_event(struct target *target, enum target_event e)
3620 struct target_event_action *teap;
3622 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3623 if (teap->event == e) {
3624 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3625 target->target_number,
3626 target_name(target),
3627 target_type_name(target),
3629 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3630 Jim_GetString(teap->body, NULL));
3631 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK)
3633 Jim_MakeErrorMessage(teap->interp);
3634 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
3641 * Returns true only if the target has a handler for the specified event.
3643 bool target_has_event_action(struct target *target, enum target_event event)
3645 struct target_event_action *teap;
3647 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3648 if (teap->event == event)
3649 return true;
3651 return false;
3654 enum target_cfg_param {
3655 TCFG_TYPE,
3656 TCFG_EVENT,
3657 TCFG_WORK_AREA_VIRT,
3658 TCFG_WORK_AREA_PHYS,
3659 TCFG_WORK_AREA_SIZE,
3660 TCFG_WORK_AREA_BACKUP,
3661 TCFG_ENDIAN,
3662 TCFG_VARIANT,
3663 TCFG_CHAIN_POSITION,
3666 static Jim_Nvp nvp_config_opts[] = {
3667 { .name = "-type", .value = TCFG_TYPE },
3668 { .name = "-event", .value = TCFG_EVENT },
3669 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3670 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3671 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3672 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3673 { .name = "-endian" , .value = TCFG_ENDIAN },
3674 { .name = "-variant", .value = TCFG_VARIANT },
3675 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3677 { .name = NULL, .value = -1 }
3680 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3682 Jim_Nvp *n;
3683 Jim_Obj *o;
3684 jim_wide w;
3685 char *cp;
3686 int e;
3688 /* parse config or cget options ... */
3689 while (goi->argc > 0) {
3690 Jim_SetEmptyResult(goi->interp);
3691 /* Jim_GetOpt_Debug(goi); */
3693 if (target->type->target_jim_configure) {
3694 /* target defines a configure function */
3695 /* target gets first dibs on parameters */
3696 e = (*(target->type->target_jim_configure))(target, goi);
3697 if (e == JIM_OK) {
3698 /* more? */
3699 continue;
3701 if (e == JIM_ERR) {
3702 /* An error */
3703 return e;
3705 /* otherwise we 'continue' below */
3707 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3708 if (e != JIM_OK) {
3709 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3710 return e;
3712 switch (n->value) {
3713 case TCFG_TYPE:
3714 /* not setable */
3715 if (goi->isconfigure) {
3716 Jim_SetResultFormatted(goi->interp,
3717 "not settable: %s", n->name);
3718 return JIM_ERR;
3719 } else {
3720 no_params:
3721 if (goi->argc != 0) {
3722 Jim_WrongNumArgs(goi->interp,
3723 goi->argc, goi->argv,
3724 "NO PARAMS");
3725 return JIM_ERR;
3728 Jim_SetResultString(goi->interp,
3729 target_type_name(target), -1);
3730 /* loop for more */
3731 break;
3732 case TCFG_EVENT:
3733 if (goi->argc == 0) {
3734 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3735 return JIM_ERR;
3738 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3739 if (e != JIM_OK) {
3740 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3741 return e;
3744 if (goi->isconfigure) {
3745 if (goi->argc != 1) {
3746 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3747 return JIM_ERR;
3749 } else {
3750 if (goi->argc != 0) {
3751 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3752 return JIM_ERR;
3757 struct target_event_action *teap;
3759 teap = target->event_action;
3760 /* replace existing? */
3761 while (teap) {
3762 if (teap->event == (enum target_event)n->value) {
3763 break;
3765 teap = teap->next;
3768 if (goi->isconfigure) {
3769 bool replace = true;
3770 if (teap == NULL) {
3771 /* create new */
3772 teap = calloc(1, sizeof(*teap));
3773 replace = false;
3775 teap->event = n->value;
3776 teap->interp = goi->interp;
3777 Jim_GetOpt_Obj(goi, &o);
3778 if (teap->body) {
3779 Jim_DecrRefCount(teap->interp, teap->body);
3781 teap->body = Jim_DuplicateObj(goi->interp, o);
3783 * FIXME:
3784 * Tcl/TK - "tk events" have a nice feature.
3785 * See the "BIND" command.
3786 * We should support that here.
3787 * You can specify %X and %Y in the event code.
3788 * The idea is: %T - target name.
3789 * The idea is: %N - target number
3790 * The idea is: %E - event name.
3792 Jim_IncrRefCount(teap->body);
3794 if (!replace)
3796 /* add to head of event list */
3797 teap->next = target->event_action;
3798 target->event_action = teap;
3800 Jim_SetEmptyResult(goi->interp);
3801 } else {
3802 /* get */
3803 if (teap == NULL) {
3804 Jim_SetEmptyResult(goi->interp);
3805 } else {
3806 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3810 /* loop for more */
3811 break;
3813 case TCFG_WORK_AREA_VIRT:
3814 if (goi->isconfigure) {
3815 target_free_all_working_areas(target);
3816 e = Jim_GetOpt_Wide(goi, &w);
3817 if (e != JIM_OK) {
3818 return e;
3820 target->working_area_virt = w;
3821 target->working_area_virt_spec = true;
3822 } else {
3823 if (goi->argc != 0) {
3824 goto no_params;
3827 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3828 /* loop for more */
3829 break;
3831 case TCFG_WORK_AREA_PHYS:
3832 if (goi->isconfigure) {
3833 target_free_all_working_areas(target);
3834 e = Jim_GetOpt_Wide(goi, &w);
3835 if (e != JIM_OK) {
3836 return e;
3838 target->working_area_phys = w;
3839 target->working_area_phys_spec = true;
3840 } else {
3841 if (goi->argc != 0) {
3842 goto no_params;
3845 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3846 /* loop for more */
3847 break;
3849 case TCFG_WORK_AREA_SIZE:
3850 if (goi->isconfigure) {
3851 target_free_all_working_areas(target);
3852 e = Jim_GetOpt_Wide(goi, &w);
3853 if (e != JIM_OK) {
3854 return e;
3856 target->working_area_size = w;
3857 } else {
3858 if (goi->argc != 0) {
3859 goto no_params;
3862 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3863 /* loop for more */
3864 break;
3866 case TCFG_WORK_AREA_BACKUP:
3867 if (goi->isconfigure) {
3868 target_free_all_working_areas(target);
3869 e = Jim_GetOpt_Wide(goi, &w);
3870 if (e != JIM_OK) {
3871 return e;
3873 /* make this exactly 1 or 0 */
3874 target->backup_working_area = (!!w);
3875 } else {
3876 if (goi->argc != 0) {
3877 goto no_params;
3880 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3881 /* loop for more e*/
3882 break;
3884 case TCFG_ENDIAN:
3885 if (goi->isconfigure) {
3886 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3887 if (e != JIM_OK) {
3888 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3889 return e;
3891 target->endianness = n->value;
3892 } else {
3893 if (goi->argc != 0) {
3894 goto no_params;
3897 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3898 if (n->name == NULL) {
3899 target->endianness = TARGET_LITTLE_ENDIAN;
3900 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3902 Jim_SetResultString(goi->interp, n->name, -1);
3903 /* loop for more */
3904 break;
3906 case TCFG_VARIANT:
3907 if (goi->isconfigure) {
3908 if (goi->argc < 1) {
3909 Jim_SetResultFormatted(goi->interp,
3910 "%s ?STRING?",
3911 n->name);
3912 return JIM_ERR;
3914 if (target->variant) {
3915 free((void *)(target->variant));
3917 e = Jim_GetOpt_String(goi, &cp, NULL);
3918 target->variant = strdup(cp);
3919 } else {
3920 if (goi->argc != 0) {
3921 goto no_params;
3924 Jim_SetResultString(goi->interp, target->variant,-1);
3925 /* loop for more */
3926 break;
3927 case TCFG_CHAIN_POSITION:
3928 if (goi->isconfigure) {
3929 Jim_Obj *o_t;
3930 struct jtag_tap *tap;
3931 target_free_all_working_areas(target);
3932 e = Jim_GetOpt_Obj(goi, &o_t);
3933 if (e != JIM_OK) {
3934 return e;
3936 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
3937 if (tap == NULL) {
3938 return JIM_ERR;
3940 /* make this exactly 1 or 0 */
3941 target->tap = tap;
3942 } else {
3943 if (goi->argc != 0) {
3944 goto no_params;
3947 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
3948 /* loop for more e*/
3949 break;
3951 } /* while (goi->argc) */
3954 /* done - we return */
3955 return JIM_OK;
3958 static int
3959 jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3961 Jim_GetOptInfo goi;
3963 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3964 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
3965 int need_args = 1 + goi.isconfigure;
3966 if (goi.argc < need_args)
3968 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
3969 goi.isconfigure
3970 ? "missing: -option VALUE ..."
3971 : "missing: -option ...");
3972 return JIM_ERR;
3974 struct target *target = Jim_CmdPrivData(goi.interp);
3975 return target_configure(&goi, target);
3978 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3980 const char *cmd_name = Jim_GetString(argv[0], NULL);
3982 Jim_GetOptInfo goi;
3983 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3985 if (goi.argc < 2 || goi.argc > 4)
3987 Jim_SetResultFormatted(goi.interp,
3988 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
3989 return JIM_ERR;
3992 target_write_fn fn;
3993 fn = target_write_memory_fast;
3995 int e;
3996 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
3998 /* consume it */
3999 struct Jim_Obj *obj;
4000 e = Jim_GetOpt_Obj(&goi, &obj);
4001 if (e != JIM_OK)
4002 return e;
4004 fn = target_write_phys_memory;
4007 jim_wide a;
4008 e = Jim_GetOpt_Wide(&goi, &a);
4009 if (e != JIM_OK)
4010 return e;
4012 jim_wide b;
4013 e = Jim_GetOpt_Wide(&goi, &b);
4014 if (e != JIM_OK)
4015 return e;
4017 jim_wide c = 1;
4018 if (goi.argc == 1)
4020 e = Jim_GetOpt_Wide(&goi, &c);
4021 if (e != JIM_OK)
4022 return e;
4025 /* all args must be consumed */
4026 if (goi.argc != 0)
4028 return JIM_ERR;
4031 struct target *target = Jim_CmdPrivData(goi.interp);
4032 unsigned data_size;
4033 if (strcasecmp(cmd_name, "mww") == 0) {
4034 data_size = 4;
4036 else if (strcasecmp(cmd_name, "mwh") == 0) {
4037 data_size = 2;
4039 else if (strcasecmp(cmd_name, "mwb") == 0) {
4040 data_size = 1;
4041 } else {
4042 LOG_ERROR("command '%s' unknown: ", cmd_name);
4043 return JIM_ERR;
4046 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4049 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4051 const char *cmd_name = Jim_GetString(argv[0], NULL);
4053 Jim_GetOptInfo goi;
4054 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4056 if ((goi.argc < 1) || (goi.argc > 3))
4058 Jim_SetResultFormatted(goi.interp,
4059 "usage: %s [phys] <address> [<count>]", cmd_name);
4060 return JIM_ERR;
4063 int (*fn)(struct target *target,
4064 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4065 fn=target_read_memory;
4067 int e;
4068 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4070 /* consume it */
4071 struct Jim_Obj *obj;
4072 e = Jim_GetOpt_Obj(&goi, &obj);
4073 if (e != JIM_OK)
4074 return e;
4076 fn=target_read_phys_memory;
4079 jim_wide a;
4080 e = Jim_GetOpt_Wide(&goi, &a);
4081 if (e != JIM_OK) {
4082 return JIM_ERR;
4084 jim_wide c;
4085 if (goi.argc == 1) {
4086 e = Jim_GetOpt_Wide(&goi, &c);
4087 if (e != JIM_OK) {
4088 return JIM_ERR;
4090 } else {
4091 c = 1;
4094 /* all args must be consumed */
4095 if (goi.argc != 0)
4097 return JIM_ERR;
4100 jim_wide b = 1; /* shut up gcc */
4101 if (strcasecmp(cmd_name, "mdw") == 0)
4102 b = 4;
4103 else if (strcasecmp(cmd_name, "mdh") == 0)
4104 b = 2;
4105 else if (strcasecmp(cmd_name, "mdb") == 0)
4106 b = 1;
4107 else {
4108 LOG_ERROR("command '%s' unknown: ", cmd_name);
4109 return JIM_ERR;
4112 /* convert count to "bytes" */
4113 c = c * b;
4115 struct target *target = Jim_CmdPrivData(goi.interp);
4116 uint8_t target_buf[32];
4117 jim_wide x, y, z;
4118 while (c > 0) {
4119 y = c;
4120 if (y > 16) {
4121 y = 16;
4123 e = fn(target, a, b, y / b, target_buf);
4124 if (e != ERROR_OK) {
4125 char tmp[10];
4126 snprintf(tmp, sizeof(tmp), "%08lx", (long)a);
4127 Jim_SetResultFormatted(interp, "error reading target @ 0x%s", tmp);
4128 return JIM_ERR;
4131 command_print(NULL, "0x%08x ", (int)(a));
4132 switch (b) {
4133 case 4:
4134 for (x = 0; x < 16 && x < y; x += 4)
4136 z = target_buffer_get_u32(target, &(target_buf[ x ]));
4137 command_print(NULL, "%08x ", (int)(z));
4139 for (; (x < 16) ; x += 4) {
4140 command_print(NULL, " ");
4142 break;
4143 case 2:
4144 for (x = 0; x < 16 && x < y; x += 2)
4146 z = target_buffer_get_u16(target, &(target_buf[ x ]));
4147 command_print(NULL, "%04x ", (int)(z));
4149 for (; (x < 16) ; x += 2) {
4150 command_print(NULL, " ");
4152 break;
4153 case 1:
4154 default:
4155 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4156 z = target_buffer_get_u8(target, &(target_buf[ x ]));
4157 command_print(NULL, "%02x ", (int)(z));
4159 for (; (x < 16) ; x += 1) {
4160 command_print(NULL, " ");
4162 break;
4164 /* ascii-ify the bytes */
4165 for (x = 0 ; x < y ; x++) {
4166 if ((target_buf[x] >= 0x20) &&
4167 (target_buf[x] <= 0x7e)) {
4168 /* good */
4169 } else {
4170 /* smack it */
4171 target_buf[x] = '.';
4174 /* space pad */
4175 while (x < 16) {
4176 target_buf[x] = ' ';
4177 x++;
4179 /* terminate */
4180 target_buf[16] = 0;
4181 /* print - with a newline */
4182 command_print(NULL, "%s\n", target_buf);
4183 /* NEXT... */
4184 c -= 16;
4185 a += 16;
4187 return JIM_OK;
4190 static int jim_target_mem2array(Jim_Interp *interp,
4191 int argc, Jim_Obj *const *argv)
4193 struct target *target = Jim_CmdPrivData(interp);
4194 return target_mem2array(interp, target, argc - 1, argv + 1);
4197 static int jim_target_array2mem(Jim_Interp *interp,
4198 int argc, Jim_Obj *const *argv)
4200 struct target *target = Jim_CmdPrivData(interp);
4201 return target_array2mem(interp, target, argc - 1, argv + 1);
4204 static int jim_target_tap_disabled(Jim_Interp *interp)
4206 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4207 return JIM_ERR;
4210 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4212 if (argc != 1)
4214 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4215 return JIM_ERR;
4217 struct target *target = Jim_CmdPrivData(interp);
4218 if (!target->tap->enabled)
4219 return jim_target_tap_disabled(interp);
4221 int e = target->type->examine(target);
4222 if (e != ERROR_OK)
4224 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4225 Jim_SetResultFormatted(interp, "examine-fails: %#s", eObj);
4226 Jim_FreeNewObj(interp, eObj);
4227 return JIM_ERR;
4229 return JIM_OK;
4232 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4234 if (argc != 1)
4236 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4237 return JIM_ERR;
4239 struct target *target = Jim_CmdPrivData(interp);
4241 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4242 return JIM_ERR;
4244 return JIM_OK;
4247 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4249 if (argc != 1)
4251 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4252 return JIM_ERR;
4254 struct target *target = Jim_CmdPrivData(interp);
4255 if (!target->tap->enabled)
4256 return jim_target_tap_disabled(interp);
4258 int e;
4259 if (!(target_was_examined(target))) {
4260 e = ERROR_TARGET_NOT_EXAMINED;
4261 } else {
4262 e = target->type->poll(target);
4264 if (e != ERROR_OK)
4266 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4267 Jim_SetResultFormatted(interp, "poll-fails: %#s", eObj);
4268 Jim_FreeNewObj(interp, eObj);
4269 return JIM_ERR;
4271 return JIM_OK;
4274 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4276 Jim_GetOptInfo goi;
4277 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4279 if (goi.argc != 2)
4281 Jim_WrongNumArgs(interp, 0, argv,
4282 "([tT]|[fF]|assert|deassert) BOOL");
4283 return JIM_ERR;
4286 Jim_Nvp *n;
4287 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4288 if (e != JIM_OK)
4290 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4291 return e;
4293 /* the halt or not param */
4294 jim_wide a;
4295 e = Jim_GetOpt_Wide(&goi, &a);
4296 if (e != JIM_OK)
4297 return e;
4299 struct target *target = Jim_CmdPrivData(goi.interp);
4300 if (!target->tap->enabled)
4301 return jim_target_tap_disabled(interp);
4302 if (!(target_was_examined(target)))
4304 LOG_ERROR("Target not examined yet");
4305 return ERROR_TARGET_NOT_EXAMINED;
4307 if (!target->type->assert_reset || !target->type->deassert_reset)
4309 Jim_SetResultFormatted(interp,
4310 "No target-specific reset for %s",
4311 target_name(target));
4312 return JIM_ERR;
4314 /* determine if we should halt or not. */
4315 target->reset_halt = !!a;
4316 /* When this happens - all workareas are invalid. */
4317 target_free_all_working_areas_restore(target, 0);
4319 /* do the assert */
4320 if (n->value == NVP_ASSERT) {
4321 e = target->type->assert_reset(target);
4322 } else {
4323 e = target->type->deassert_reset(target);
4325 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4328 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4330 if (argc != 1) {
4331 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4332 return JIM_ERR;
4334 struct target *target = Jim_CmdPrivData(interp);
4335 if (!target->tap->enabled)
4336 return jim_target_tap_disabled(interp);
4337 int e = target->type->halt(target);
4338 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4341 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4343 Jim_GetOptInfo goi;
4344 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4346 /* params: <name> statename timeoutmsecs */
4347 if (goi.argc != 2)
4349 const char *cmd_name = Jim_GetString(argv[0], NULL);
4350 Jim_SetResultFormatted(goi.interp,
4351 "%s <state_name> <timeout_in_msec>", cmd_name);
4352 return JIM_ERR;
4355 Jim_Nvp *n;
4356 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4357 if (e != JIM_OK) {
4358 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4359 return e;
4361 jim_wide a;
4362 e = Jim_GetOpt_Wide(&goi, &a);
4363 if (e != JIM_OK) {
4364 return e;
4366 struct target *target = Jim_CmdPrivData(interp);
4367 if (!target->tap->enabled)
4368 return jim_target_tap_disabled(interp);
4370 e = target_wait_state(target, n->value, a);
4371 if (e != ERROR_OK)
4373 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4374 Jim_SetResultFormatted(goi.interp,
4375 "target: %s wait %s fails (%#s) %s",
4376 target_name(target), n->name,
4377 eObj, target_strerror_safe(e));
4378 Jim_FreeNewObj(interp, eObj);
4379 return JIM_ERR;
4381 return JIM_OK;
4383 /* List for human, Events defined for this target.
4384 * scripts/programs should use 'name cget -event NAME'
4386 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4388 struct command_context *cmd_ctx = current_command_context(interp);
4389 assert (cmd_ctx != NULL);
4391 struct target *target = Jim_CmdPrivData(interp);
4392 struct target_event_action *teap = target->event_action;
4393 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4394 target->target_number,
4395 target_name(target));
4396 command_print(cmd_ctx, "%-25s | Body", "Event");
4397 command_print(cmd_ctx, "------------------------- | "
4398 "----------------------------------------");
4399 while (teap)
4401 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4402 command_print(cmd_ctx, "%-25s | %s",
4403 opt->name, Jim_GetString(teap->body, NULL));
4404 teap = teap->next;
4406 command_print(cmd_ctx, "***END***");
4407 return JIM_OK;
4409 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4411 if (argc != 1)
4413 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4414 return JIM_ERR;
4416 struct target *target = Jim_CmdPrivData(interp);
4417 Jim_SetResultString(interp, target_state_name(target), -1);
4418 return JIM_OK;
4420 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4422 Jim_GetOptInfo goi;
4423 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4424 if (goi.argc != 1)
4426 const char *cmd_name = Jim_GetString(argv[0], NULL);
4427 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4428 return JIM_ERR;
4430 Jim_Nvp *n;
4431 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4432 if (e != JIM_OK)
4434 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4435 return e;
4437 struct target *target = Jim_CmdPrivData(interp);
4438 target_handle_event(target, n->value);
4439 return JIM_OK;
4442 static const struct command_registration target_instance_command_handlers[] = {
4444 .name = "configure",
4445 .mode = COMMAND_CONFIG,
4446 .jim_handler = jim_target_configure,
4447 .help = "configure a new target for use",
4448 .usage = "[target_attribute ...]",
4451 .name = "cget",
4452 .mode = COMMAND_ANY,
4453 .jim_handler = jim_target_configure,
4454 .help = "returns the specified target attribute",
4455 .usage = "target_attribute",
4458 .name = "mww",
4459 .mode = COMMAND_EXEC,
4460 .jim_handler = jim_target_mw,
4461 .help = "Write 32-bit word(s) to target memory",
4462 .usage = "address data [count]",
4465 .name = "mwh",
4466 .mode = COMMAND_EXEC,
4467 .jim_handler = jim_target_mw,
4468 .help = "Write 16-bit half-word(s) to target memory",
4469 .usage = "address data [count]",
4472 .name = "mwb",
4473 .mode = COMMAND_EXEC,
4474 .jim_handler = jim_target_mw,
4475 .help = "Write byte(s) to target memory",
4476 .usage = "address data [count]",
4479 .name = "mdw",
4480 .mode = COMMAND_EXEC,
4481 .jim_handler = jim_target_md,
4482 .help = "Display target memory as 32-bit words",
4483 .usage = "address [count]",
4486 .name = "mdh",
4487 .mode = COMMAND_EXEC,
4488 .jim_handler = jim_target_md,
4489 .help = "Display target memory as 16-bit half-words",
4490 .usage = "address [count]",
4493 .name = "mdb",
4494 .mode = COMMAND_EXEC,
4495 .jim_handler = jim_target_md,
4496 .help = "Display target memory as 8-bit bytes",
4497 .usage = "address [count]",
4500 .name = "array2mem",
4501 .mode = COMMAND_EXEC,
4502 .jim_handler = jim_target_array2mem,
4503 .help = "Writes Tcl array of 8/16/32 bit numbers "
4504 "to target memory",
4505 .usage = "arrayname bitwidth address count",
4508 .name = "mem2array",
4509 .mode = COMMAND_EXEC,
4510 .jim_handler = jim_target_mem2array,
4511 .help = "Loads Tcl array of 8/16/32 bit numbers "
4512 "from target memory",
4513 .usage = "arrayname bitwidth address count",
4516 .name = "eventlist",
4517 .mode = COMMAND_EXEC,
4518 .jim_handler = jim_target_event_list,
4519 .help = "displays a table of events defined for this target",
4522 .name = "curstate",
4523 .mode = COMMAND_EXEC,
4524 .jim_handler = jim_target_current_state,
4525 .help = "displays the current state of this target",
4528 .name = "arp_examine",
4529 .mode = COMMAND_EXEC,
4530 .jim_handler = jim_target_examine,
4531 .help = "used internally for reset processing",
4534 .name = "arp_halt_gdb",
4535 .mode = COMMAND_EXEC,
4536 .jim_handler = jim_target_halt_gdb,
4537 .help = "used internally for reset processing to halt GDB",
4540 .name = "arp_poll",
4541 .mode = COMMAND_EXEC,
4542 .jim_handler = jim_target_poll,
4543 .help = "used internally for reset processing",
4546 .name = "arp_reset",
4547 .mode = COMMAND_EXEC,
4548 .jim_handler = jim_target_reset,
4549 .help = "used internally for reset processing",
4552 .name = "arp_halt",
4553 .mode = COMMAND_EXEC,
4554 .jim_handler = jim_target_halt,
4555 .help = "used internally for reset processing",
4558 .name = "arp_waitstate",
4559 .mode = COMMAND_EXEC,
4560 .jim_handler = jim_target_wait_state,
4561 .help = "used internally for reset processing",
4564 .name = "invoke-event",
4565 .mode = COMMAND_EXEC,
4566 .jim_handler = jim_target_invoke_event,
4567 .help = "invoke handler for specified event",
4568 .usage = "event_name",
4570 COMMAND_REGISTRATION_DONE
4573 static int target_create(Jim_GetOptInfo *goi)
4575 Jim_Obj *new_cmd;
4576 Jim_Cmd *cmd;
4577 const char *cp;
4578 char *cp2;
4579 int e;
4580 int x;
4581 struct target *target;
4582 struct command_context *cmd_ctx;
4584 cmd_ctx = current_command_context(goi->interp);
4585 assert (cmd_ctx != NULL);
4587 if (goi->argc < 3) {
4588 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4589 return JIM_ERR;
4592 /* COMMAND */
4593 Jim_GetOpt_Obj(goi, &new_cmd);
4594 /* does this command exist? */
4595 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4596 if (cmd) {
4597 cp = Jim_GetString(new_cmd, NULL);
4598 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
4599 return JIM_ERR;
4602 /* TYPE */
4603 e = Jim_GetOpt_String(goi, &cp2, NULL);
4604 cp = cp2;
4605 /* now does target type exist */
4606 for (x = 0 ; target_types[x] ; x++) {
4607 if (0 == strcmp(cp, target_types[x]->name)) {
4608 /* found */
4609 break;
4612 if (target_types[x] == NULL) {
4613 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
4614 for (x = 0 ; target_types[x] ; x++) {
4615 if (target_types[x + 1]) {
4616 Jim_AppendStrings(goi->interp,
4617 Jim_GetResult(goi->interp),
4618 target_types[x]->name,
4619 ", ", NULL);
4620 } else {
4621 Jim_AppendStrings(goi->interp,
4622 Jim_GetResult(goi->interp),
4623 " or ",
4624 target_types[x]->name,NULL);
4627 return JIM_ERR;
4630 /* Create it */
4631 target = calloc(1,sizeof(struct target));
4632 /* set target number */
4633 target->target_number = new_target_number();
4635 /* allocate memory for each unique target type */
4636 target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4638 memcpy(target->type, target_types[x], sizeof(struct target_type));
4640 /* will be set by "-endian" */
4641 target->endianness = TARGET_ENDIAN_UNKNOWN;
4643 target->working_area = 0x0;
4644 target->working_area_size = 0x0;
4645 target->working_areas = NULL;
4646 target->backup_working_area = 0;
4648 target->state = TARGET_UNKNOWN;
4649 target->debug_reason = DBG_REASON_UNDEFINED;
4650 target->reg_cache = NULL;
4651 target->breakpoints = NULL;
4652 target->watchpoints = NULL;
4653 target->next = NULL;
4654 target->arch_info = NULL;
4656 target->display = 1;
4658 target->halt_issued = false;
4660 /* initialize trace information */
4661 target->trace_info = malloc(sizeof(struct trace));
4662 target->trace_info->num_trace_points = 0;
4663 target->trace_info->trace_points_size = 0;
4664 target->trace_info->trace_points = NULL;
4665 target->trace_info->trace_history_size = 0;
4666 target->trace_info->trace_history = NULL;
4667 target->trace_info->trace_history_pos = 0;
4668 target->trace_info->trace_history_overflowed = 0;
4670 target->dbgmsg = NULL;
4671 target->dbg_msg_enabled = 0;
4673 target->endianness = TARGET_ENDIAN_UNKNOWN;
4675 /* Do the rest as "configure" options */
4676 goi->isconfigure = 1;
4677 e = target_configure(goi, target);
4679 if (target->tap == NULL)
4681 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4682 e = JIM_ERR;
4685 if (e != JIM_OK) {
4686 free(target->type);
4687 free(target);
4688 return e;
4691 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4692 /* default endian to little if not specified */
4693 target->endianness = TARGET_LITTLE_ENDIAN;
4696 /* incase variant is not set */
4697 if (!target->variant)
4698 target->variant = strdup("");
4700 cp = Jim_GetString(new_cmd, NULL);
4701 target->cmd_name = strdup(cp);
4703 /* create the target specific commands */
4704 if (target->type->commands) {
4705 e = register_commands(cmd_ctx, NULL, target->type->commands);
4706 if (ERROR_OK != e)
4707 LOG_ERROR("unable to register '%s' commands", cp);
4709 if (target->type->target_create) {
4710 (*(target->type->target_create))(target, goi->interp);
4713 /* append to end of list */
4715 struct target **tpp;
4716 tpp = &(all_targets);
4717 while (*tpp) {
4718 tpp = &((*tpp)->next);
4720 *tpp = target;
4723 /* now - create the new target name command */
4724 const const struct command_registration target_subcommands[] = {
4726 .chain = target_instance_command_handlers,
4729 .chain = target->type->commands,
4731 COMMAND_REGISTRATION_DONE
4733 const const struct command_registration target_commands[] = {
4735 .name = cp,
4736 .mode = COMMAND_ANY,
4737 .help = "target command group",
4738 .chain = target_subcommands,
4740 COMMAND_REGISTRATION_DONE
4742 e = register_commands(cmd_ctx, NULL, target_commands);
4743 if (ERROR_OK != e)
4744 return JIM_ERR;
4746 struct command *c = command_find_in_context(cmd_ctx, cp);
4747 assert(c);
4748 command_set_handler_data(c, target);
4750 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
4753 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4755 if (argc != 1)
4757 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4758 return JIM_ERR;
4760 struct command_context *cmd_ctx = current_command_context(interp);
4761 assert (cmd_ctx != NULL);
4763 Jim_SetResultString(interp, get_current_target(cmd_ctx)->cmd_name, -1);
4764 return JIM_OK;
4767 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4769 if (argc != 1)
4771 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4772 return JIM_ERR;
4774 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4775 for (unsigned x = 0; NULL != target_types[x]; x++)
4777 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4778 Jim_NewStringObj(interp, target_types[x]->name, -1));
4780 return JIM_OK;
4783 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4785 if (argc != 1)
4787 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4788 return JIM_ERR;
4790 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4791 struct target *target = all_targets;
4792 while (target)
4794 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4795 Jim_NewStringObj(interp, target_name(target), -1));
4796 target = target->next;
4798 return JIM_OK;
4801 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4803 Jim_GetOptInfo goi;
4804 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4805 if (goi.argc < 3)
4807 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4808 "<name> <target_type> [<target_options> ...]");
4809 return JIM_ERR;
4811 return target_create(&goi);
4814 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4816 Jim_GetOptInfo goi;
4817 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4819 /* It's OK to remove this mechanism sometime after August 2010 or so */
4820 LOG_WARNING("don't use numbers as target identifiers; use names");
4821 if (goi.argc != 1)
4823 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
4824 return JIM_ERR;
4826 jim_wide w;
4827 int e = Jim_GetOpt_Wide(&goi, &w);
4828 if (e != JIM_OK)
4829 return JIM_ERR;
4831 struct target *target;
4832 for (target = all_targets; NULL != target; target = target->next)
4834 if (target->target_number != w)
4835 continue;
4837 Jim_SetResultString(goi.interp, target_name(target), -1);
4838 return JIM_OK;
4841 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
4842 Jim_SetResultFormatted(goi.interp,
4843 "Target: number %#s does not exist", wObj);
4844 Jim_FreeNewObj(interp, wObj);
4846 return JIM_ERR;
4849 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4851 if (argc != 1)
4853 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
4854 return JIM_ERR;
4856 unsigned count = 0;
4857 struct target *target = all_targets;
4858 while (NULL != target)
4860 target = target->next;
4861 count++;
4863 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
4864 return JIM_OK;
4867 static const struct command_registration target_subcommand_handlers[] = {
4869 .name = "init",
4870 .mode = COMMAND_CONFIG,
4871 .handler = handle_target_init_command,
4872 .help = "initialize targets",
4875 .name = "create",
4876 /* REVISIT this should be COMMAND_CONFIG ... */
4877 .mode = COMMAND_ANY,
4878 .jim_handler = jim_target_create,
4879 .usage = "name type '-chain-position' name [options ...]",
4880 .help = "Creates and selects a new target",
4883 .name = "current",
4884 .mode = COMMAND_ANY,
4885 .jim_handler = jim_target_current,
4886 .help = "Returns the currently selected target",
4889 .name = "types",
4890 .mode = COMMAND_ANY,
4891 .jim_handler = jim_target_types,
4892 .help = "Returns the available target types as "
4893 "a list of strings",
4896 .name = "names",
4897 .mode = COMMAND_ANY,
4898 .jim_handler = jim_target_names,
4899 .help = "Returns the names of all targets as a list of strings",
4902 .name = "number",
4903 .mode = COMMAND_ANY,
4904 .jim_handler = jim_target_number,
4905 .usage = "number",
4906 .help = "Returns the name of the numbered target "
4907 "(DEPRECATED)",
4910 .name = "count",
4911 .mode = COMMAND_ANY,
4912 .jim_handler = jim_target_count,
4913 .help = "Returns the number of targets as an integer "
4914 "(DEPRECATED)",
4916 COMMAND_REGISTRATION_DONE
4919 struct FastLoad
4921 uint32_t address;
4922 uint8_t *data;
4923 int length;
4927 static int fastload_num;
4928 static struct FastLoad *fastload;
4930 static void free_fastload(void)
4932 if (fastload != NULL)
4934 int i;
4935 for (i = 0; i < fastload_num; i++)
4937 if (fastload[i].data)
4938 free(fastload[i].data);
4940 free(fastload);
4941 fastload = NULL;
4948 COMMAND_HANDLER(handle_fast_load_image_command)
4950 uint8_t *buffer;
4951 size_t buf_cnt;
4952 uint32_t image_size;
4953 uint32_t min_address = 0;
4954 uint32_t max_address = 0xffffffff;
4955 int i;
4957 struct image image;
4959 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
4960 &image, &min_address, &max_address);
4961 if (ERROR_OK != retval)
4962 return retval;
4964 struct duration bench;
4965 duration_start(&bench);
4967 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
4968 if (retval != ERROR_OK)
4970 return retval;
4973 image_size = 0x0;
4974 retval = ERROR_OK;
4975 fastload_num = image.num_sections;
4976 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4977 if (fastload == NULL)
4979 command_print(CMD_CTX, "out of memory");
4980 image_close(&image);
4981 return ERROR_FAIL;
4983 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4984 for (i = 0; i < image.num_sections; i++)
4986 buffer = malloc(image.sections[i].size);
4987 if (buffer == NULL)
4989 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
4990 (int)(image.sections[i].size));
4991 retval = ERROR_FAIL;
4992 break;
4995 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4997 free(buffer);
4998 break;
5001 uint32_t offset = 0;
5002 uint32_t length = buf_cnt;
5005 /* DANGER!!! beware of unsigned comparision here!!! */
5007 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
5008 (image.sections[i].base_address < max_address))
5010 if (image.sections[i].base_address < min_address)
5012 /* clip addresses below */
5013 offset += min_address-image.sections[i].base_address;
5014 length -= offset;
5017 if (image.sections[i].base_address + buf_cnt > max_address)
5019 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5022 fastload[i].address = image.sections[i].base_address + offset;
5023 fastload[i].data = malloc(length);
5024 if (fastload[i].data == NULL)
5026 free(buffer);
5027 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5028 length);
5029 retval = ERROR_FAIL;
5030 break;
5032 memcpy(fastload[i].data, buffer + offset, length);
5033 fastload[i].length = length;
5035 image_size += length;
5036 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5037 (unsigned int)length,
5038 ((unsigned int)(image.sections[i].base_address + offset)));
5041 free(buffer);
5044 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
5046 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5047 "in %fs (%0.3f KiB/s)", image_size,
5048 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5050 command_print(CMD_CTX,
5051 "WARNING: image has not been loaded to target!"
5052 "You can issue a 'fast_load' to finish loading.");
5055 image_close(&image);
5057 if (retval != ERROR_OK)
5059 free_fastload();
5062 return retval;
5065 COMMAND_HANDLER(handle_fast_load_command)
5067 if (CMD_ARGC > 0)
5068 return ERROR_COMMAND_SYNTAX_ERROR;
5069 if (fastload == NULL)
5071 LOG_ERROR("No image in memory");
5072 return ERROR_FAIL;
5074 int i;
5075 int ms = timeval_ms();
5076 int size = 0;
5077 int retval = ERROR_OK;
5078 for (i = 0; i < fastload_num;i++)
5080 struct target *target = get_current_target(CMD_CTX);
5081 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5082 (unsigned int)(fastload[i].address),
5083 (unsigned int)(fastload[i].length));
5084 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5085 if (retval != ERROR_OK)
5087 break;
5089 size += fastload[i].length;
5091 if (retval == ERROR_OK)
5093 int after = timeval_ms();
5094 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5096 return retval;
5099 static const struct command_registration target_command_handlers[] = {
5101 .name = "targets",
5102 .handler = handle_targets_command,
5103 .mode = COMMAND_ANY,
5104 .help = "change current default target (one parameter) "
5105 "or prints table of all targets (no parameters)",
5106 .usage = "[target]",
5109 .name = "target",
5110 .mode = COMMAND_CONFIG,
5111 .help = "configure target",
5113 .chain = target_subcommand_handlers,
5115 COMMAND_REGISTRATION_DONE
5118 int target_register_commands(struct command_context *cmd_ctx)
5120 return register_commands(cmd_ctx, NULL, target_command_handlers);
5123 static bool target_reset_nag = true;
5125 bool get_target_reset_nag(void)
5127 return target_reset_nag;
5130 COMMAND_HANDLER(handle_target_reset_nag)
5132 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5133 &target_reset_nag, "Nag after each reset about options to improve "
5134 "performance");
5137 static const struct command_registration target_exec_command_handlers[] = {
5139 .name = "fast_load_image",
5140 .handler = handle_fast_load_image_command,
5141 .mode = COMMAND_ANY,
5142 .help = "Load image into server memory for later use by "
5143 "fast_load; primarily for profiling",
5144 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5145 "[min_address [max_length]]",
5148 .name = "fast_load",
5149 .handler = handle_fast_load_command,
5150 .mode = COMMAND_EXEC,
5151 .help = "loads active fast load image to current target "
5152 "- mainly for profiling purposes",
5155 .name = "profile",
5156 .handler = handle_profile_command,
5157 .mode = COMMAND_EXEC,
5158 .help = "profiling samples the CPU PC",
5160 /** @todo don't register virt2phys() unless target supports it */
5162 .name = "virt2phys",
5163 .handler = handle_virt2phys_command,
5164 .mode = COMMAND_ANY,
5165 .help = "translate a virtual address into a physical address",
5166 .usage = "virtual_address",
5169 .name = "reg",
5170 .handler = handle_reg_command,
5171 .mode = COMMAND_EXEC,
5172 .help = "display or set a register; with no arguments, "
5173 "displays all registers and their values",
5174 .usage = "[(register_name|register_number) [value]]",
5177 .name = "poll",
5178 .handler = handle_poll_command,
5179 .mode = COMMAND_EXEC,
5180 .help = "poll target state; or reconfigure background polling",
5181 .usage = "['on'|'off']",
5184 .name = "wait_halt",
5185 .handler = handle_wait_halt_command,
5186 .mode = COMMAND_EXEC,
5187 .help = "wait up to the specified number of milliseconds "
5188 "(default 5) for a previously requested halt",
5189 .usage = "[milliseconds]",
5192 .name = "halt",
5193 .handler = handle_halt_command,
5194 .mode = COMMAND_EXEC,
5195 .help = "request target to halt, then wait up to the specified"
5196 "number of milliseconds (default 5) for it to complete",
5197 .usage = "[milliseconds]",
5200 .name = "resume",
5201 .handler = handle_resume_command,
5202 .mode = COMMAND_EXEC,
5203 .help = "resume target execution from current PC or address",
5204 .usage = "[address]",
5207 .name = "reset",
5208 .handler = handle_reset_command,
5209 .mode = COMMAND_EXEC,
5210 .usage = "[run|halt|init]",
5211 .help = "Reset all targets into the specified mode."
5212 "Default reset mode is run, if not given.",
5215 .name = "soft_reset_halt",
5216 .handler = handle_soft_reset_halt_command,
5217 .mode = COMMAND_EXEC,
5218 .help = "halt the target and do a soft reset",
5221 .name = "step",
5222 .handler = handle_step_command,
5223 .mode = COMMAND_EXEC,
5224 .help = "step one instruction from current PC or address",
5225 .usage = "[address]",
5228 .name = "mdw",
5229 .handler = handle_md_command,
5230 .mode = COMMAND_EXEC,
5231 .help = "display memory words",
5232 .usage = "['phys'] address [count]",
5235 .name = "mdh",
5236 .handler = handle_md_command,
5237 .mode = COMMAND_EXEC,
5238 .help = "display memory half-words",
5239 .usage = "['phys'] address [count]",
5242 .name = "mdb",
5243 .handler = handle_md_command,
5244 .mode = COMMAND_EXEC,
5245 .help = "display memory bytes",
5246 .usage = "['phys'] address [count]",
5249 .name = "mww",
5250 .handler = handle_mw_command,
5251 .mode = COMMAND_EXEC,
5252 .help = "write memory word",
5253 .usage = "['phys'] address value [count]",
5256 .name = "mwh",
5257 .handler = handle_mw_command,
5258 .mode = COMMAND_EXEC,
5259 .help = "write memory half-word",
5260 .usage = "['phys'] address value [count]",
5263 .name = "mwb",
5264 .handler = handle_mw_command,
5265 .mode = COMMAND_EXEC,
5266 .help = "write memory byte",
5267 .usage = "['phys'] address value [count]",
5270 .name = "bp",
5271 .handler = handle_bp_command,
5272 .mode = COMMAND_EXEC,
5273 .help = "list or set hardware or software breakpoint",
5274 .usage = "[address length ['hw']]",
5277 .name = "rbp",
5278 .handler = handle_rbp_command,
5279 .mode = COMMAND_EXEC,
5280 .help = "remove breakpoint",
5281 .usage = "address",
5284 .name = "wp",
5285 .handler = handle_wp_command,
5286 .mode = COMMAND_EXEC,
5287 .help = "list (no params) or create watchpoints",
5288 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5291 .name = "rwp",
5292 .handler = handle_rwp_command,
5293 .mode = COMMAND_EXEC,
5294 .help = "remove watchpoint",
5295 .usage = "address",
5298 .name = "load_image",
5299 .handler = handle_load_image_command,
5300 .mode = COMMAND_EXEC,
5301 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5302 "[min_address] [max_length]",
5305 .name = "dump_image",
5306 .handler = handle_dump_image_command,
5307 .mode = COMMAND_EXEC,
5308 .usage = "filename address size",
5311 .name = "verify_image",
5312 .handler = handle_verify_image_command,
5313 .mode = COMMAND_EXEC,
5314 .usage = "filename [offset [type]]",
5317 .name = "test_image",
5318 .handler = handle_test_image_command,
5319 .mode = COMMAND_EXEC,
5320 .usage = "filename [offset [type]]",
5323 .name = "mem2array",
5324 .mode = COMMAND_EXEC,
5325 .jim_handler = jim_mem2array,
5326 .help = "read 8/16/32 bit memory and return as a TCL array "
5327 "for script processing",
5328 .usage = "arrayname bitwidth address count",
5331 .name = "array2mem",
5332 .mode = COMMAND_EXEC,
5333 .jim_handler = jim_array2mem,
5334 .help = "convert a TCL array to memory locations "
5335 "and write the 8/16/32 bit values",
5336 .usage = "arrayname bitwidth address count",
5339 .name = "reset_nag",
5340 .handler = handle_target_reset_nag,
5341 .mode = COMMAND_ANY,
5342 .help = "Nag after each reset about options that could have been "
5343 "enabled to improve performance. ",
5344 .usage = "['enable'|'disable']",
5346 COMMAND_REGISTRATION_DONE
5348 static int target_register_user_commands(struct command_context *cmd_ctx)
5350 int retval = ERROR_OK;
5351 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
5352 return retval;
5354 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
5355 return retval;
5358 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);