simplify and unconfuse target_run_algorithm()
[openocd/ellerodev.git] / src / target / target.c
blob75c41d381f700e7a83e67d9d628d87edfc7d443d
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);
54 /* targets */
55 extern struct target_type arm7tdmi_target;
56 extern struct target_type arm720t_target;
57 extern struct target_type arm9tdmi_target;
58 extern struct target_type arm920t_target;
59 extern struct target_type arm966e_target;
60 extern struct target_type arm926ejs_target;
61 extern struct target_type fa526_target;
62 extern struct target_type feroceon_target;
63 extern struct target_type dragonite_target;
64 extern struct target_type xscale_target;
65 extern struct target_type cortexm3_target;
66 extern struct target_type cortexa8_target;
67 extern struct target_type arm11_target;
68 extern struct target_type mips_m4k_target;
69 extern struct target_type avr_target;
70 extern struct target_type dsp563xx_target;
71 extern struct target_type testee_target;
73 struct target_type *target_types[] =
75 &arm7tdmi_target,
76 &arm9tdmi_target,
77 &arm920t_target,
78 &arm720t_target,
79 &arm966e_target,
80 &arm926ejs_target,
81 &fa526_target,
82 &feroceon_target,
83 &dragonite_target,
84 &xscale_target,
85 &cortexm3_target,
86 &cortexa8_target,
87 &arm11_target,
88 &mips_m4k_target,
89 &avr_target,
90 &dsp563xx_target,
91 &testee_target,
92 NULL,
95 struct target *all_targets = NULL;
96 struct target_event_callback *target_event_callbacks = NULL;
97 struct target_timer_callback *target_timer_callbacks = NULL;
99 static const Jim_Nvp nvp_assert[] = {
100 { .name = "assert", NVP_ASSERT },
101 { .name = "deassert", NVP_DEASSERT },
102 { .name = "T", NVP_ASSERT },
103 { .name = "F", NVP_DEASSERT },
104 { .name = "t", NVP_ASSERT },
105 { .name = "f", NVP_DEASSERT },
106 { .name = NULL, .value = -1 }
109 static const Jim_Nvp nvp_error_target[] = {
110 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
111 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
112 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
113 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
114 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
115 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
116 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
117 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
118 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
119 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
120 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
121 { .value = -1, .name = NULL }
124 const char *target_strerror_safe(int err)
126 const Jim_Nvp *n;
128 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
129 if (n->name == NULL) {
130 return "unknown";
131 } else {
132 return n->name;
136 static const Jim_Nvp nvp_target_event[] = {
137 { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
138 { .value = TARGET_EVENT_OLD_pre_resume , .name = "old-pre_resume" },
140 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
141 { .value = TARGET_EVENT_HALTED, .name = "halted" },
142 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
143 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
144 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
146 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
147 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
149 /* historical name */
151 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
153 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
154 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
155 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
156 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
157 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
158 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
159 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
160 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
161 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
162 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
163 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
165 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
166 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
168 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
169 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
171 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
172 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
174 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
175 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
177 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
178 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
180 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
181 { .value = TARGET_EVENT_RESUMED , .name = "resume-ok" },
182 { .value = TARGET_EVENT_RESUME_END , .name = "resume-end" },
184 { .name = NULL, .value = -1 }
187 static const Jim_Nvp nvp_target_state[] = {
188 { .name = "unknown", .value = TARGET_UNKNOWN },
189 { .name = "running", .value = TARGET_RUNNING },
190 { .name = "halted", .value = TARGET_HALTED },
191 { .name = "reset", .value = TARGET_RESET },
192 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
193 { .name = NULL, .value = -1 },
196 static const Jim_Nvp nvp_target_debug_reason [] = {
197 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
198 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
199 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
200 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
201 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
202 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
203 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
204 { .name = NULL, .value = -1 },
207 static const Jim_Nvp nvp_target_endian[] = {
208 { .name = "big", .value = TARGET_BIG_ENDIAN },
209 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
210 { .name = "be", .value = TARGET_BIG_ENDIAN },
211 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
212 { .name = NULL, .value = -1 },
215 static const Jim_Nvp nvp_reset_modes[] = {
216 { .name = "unknown", .value = RESET_UNKNOWN },
217 { .name = "run" , .value = RESET_RUN },
218 { .name = "halt" , .value = RESET_HALT },
219 { .name = "init" , .value = RESET_INIT },
220 { .name = NULL , .value = -1 },
223 const char *debug_reason_name(struct target *t)
225 const char *cp;
227 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
228 t->debug_reason)->name;
229 if (!cp) {
230 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
231 cp = "(*BUG*unknown*BUG*)";
233 return cp;
236 const char *
237 target_state_name( struct target *t )
239 const char *cp;
240 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
241 if( !cp ){
242 LOG_ERROR("Invalid target state: %d", (int)(t->state));
243 cp = "(*BUG*unknown*BUG*)";
245 return cp;
248 /* determine the number of the new target */
249 static int new_target_number(void)
251 struct target *t;
252 int x;
254 /* number is 0 based */
255 x = -1;
256 t = all_targets;
257 while (t) {
258 if (x < t->target_number) {
259 x = t->target_number;
261 t = t->next;
263 return x + 1;
266 /* read a uint32_t from a buffer in target memory endianness */
267 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
269 if (target->endianness == TARGET_LITTLE_ENDIAN)
270 return le_to_h_u32(buffer);
271 else
272 return be_to_h_u32(buffer);
275 /* read a uint16_t from a buffer in target memory endianness */
276 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
278 if (target->endianness == TARGET_LITTLE_ENDIAN)
279 return le_to_h_u16(buffer);
280 else
281 return be_to_h_u16(buffer);
284 /* read a uint8_t from a buffer in target memory endianness */
285 uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
287 return *buffer & 0x0ff;
290 /* write a uint32_t to a buffer in target memory endianness */
291 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
293 if (target->endianness == TARGET_LITTLE_ENDIAN)
294 h_u32_to_le(buffer, value);
295 else
296 h_u32_to_be(buffer, value);
299 /* write a uint16_t to a buffer in target memory endianness */
300 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
302 if (target->endianness == TARGET_LITTLE_ENDIAN)
303 h_u16_to_le(buffer, value);
304 else
305 h_u16_to_be(buffer, value);
308 /* write a uint8_t to a buffer in target memory endianness */
309 void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
311 *buffer = value;
314 /* return a pointer to a configured target; id is name or number */
315 struct target *get_target(const char *id)
317 struct target *target;
319 /* try as tcltarget name */
320 for (target = all_targets; target; target = target->next) {
321 if (target->cmd_name == NULL)
322 continue;
323 if (strcmp(id, target->cmd_name) == 0)
324 return target;
327 /* It's OK to remove this fallback sometime after August 2010 or so */
329 /* no match, try as number */
330 unsigned num;
331 if (parse_uint(id, &num) != ERROR_OK)
332 return NULL;
334 for (target = all_targets; target; target = target->next) {
335 if (target->target_number == (int)num) {
336 LOG_WARNING("use '%s' as target identifier, not '%u'",
337 target->cmd_name, num);
338 return target;
342 return NULL;
345 /* returns a pointer to the n-th configured target */
346 static struct target *get_target_by_num(int num)
348 struct target *target = all_targets;
350 while (target) {
351 if (target->target_number == num) {
352 return target;
354 target = target->next;
357 return NULL;
360 struct target* get_current_target(struct command_context *cmd_ctx)
362 struct target *target = get_target_by_num(cmd_ctx->current_target);
364 if (target == NULL)
366 LOG_ERROR("BUG: current_target out of bounds");
367 exit(-1);
370 return target;
373 int target_poll(struct target *target)
375 int retval;
377 /* We can't poll until after examine */
378 if (!target_was_examined(target))
380 /* Fail silently lest we pollute the log */
381 return ERROR_FAIL;
384 retval = target->type->poll(target);
385 if (retval != ERROR_OK)
386 return retval;
388 if (target->halt_issued)
390 if (target->state == TARGET_HALTED)
392 target->halt_issued = false;
393 } else
395 long long t = timeval_ms() - target->halt_issued_time;
396 if (t>1000)
398 target->halt_issued = false;
399 LOG_INFO("Halt timed out, wake up GDB.");
400 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
405 return ERROR_OK;
408 int target_halt(struct target *target)
410 int retval;
411 /* We can't poll until after examine */
412 if (!target_was_examined(target))
414 LOG_ERROR("Target not examined yet");
415 return ERROR_FAIL;
418 retval = target->type->halt(target);
419 if (retval != ERROR_OK)
420 return retval;
422 target->halt_issued = true;
423 target->halt_issued_time = timeval_ms();
425 return ERROR_OK;
429 * Make the target (re)start executing using its saved execution
430 * context (possibly with some modifications).
432 * @param target Which target should start executing.
433 * @param current True to use the target's saved program counter instead
434 * of the address parameter
435 * @param address Optionally used as the program counter.
436 * @param handle_breakpoints True iff breakpoints at the resumption PC
437 * should be skipped. (For example, maybe execution was stopped by
438 * such a breakpoint, in which case it would be counterprodutive to
439 * let it re-trigger.
440 * @param debug_execution False if all working areas allocated by OpenOCD
441 * should be released and/or restored to their original contents.
442 * (This would for example be true to run some downloaded "helper"
443 * algorithm code, which resides in one such working buffer and uses
444 * another for data storage.)
446 * @todo Resolve the ambiguity about what the "debug_execution" flag
447 * signifies. For example, Target implementations don't agree on how
448 * it relates to invalidation of the register cache, or to whether
449 * breakpoints and watchpoints should be enabled. (It would seem wrong
450 * to enable breakpoints when running downloaded "helper" algorithms
451 * (debug_execution true), since the breakpoints would be set to match
452 * target firmware being debugged, not the helper algorithm.... and
453 * enabling them could cause such helpers to malfunction (for example,
454 * by overwriting data with a breakpoint instruction. On the other
455 * hand the infrastructure for running such helpers might use this
456 * procedure but rely on hardware breakpoint to detect termination.)
458 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
460 int retval;
462 /* We can't poll until after examine */
463 if (!target_was_examined(target))
465 LOG_ERROR("Target not examined yet");
466 return ERROR_FAIL;
469 /* note that resume *must* be asynchronous. The CPU can halt before
470 * we poll. The CPU can even halt at the current PC as a result of
471 * a software breakpoint being inserted by (a bug?) the application.
473 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
474 return retval;
476 /* Invalidate any cached protect/erase/... flash status, since
477 * almost all targets will now be able modify the flash by
478 * themselves. We want flash drivers and infrastructure to
479 * be able to rely on (non-invalidated) cached state.
481 * REVISIT do the same for NAND ; maybe other flash flavors too...
483 nor_resume(target);
484 return retval;
487 int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
489 char buf[100];
490 int retval;
491 Jim_Nvp *n;
492 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
493 if (n->name == NULL) {
494 LOG_ERROR("invalid reset mode");
495 return ERROR_FAIL;
498 /* disable polling during reset to make reset event scripts
499 * more predictable, i.e. dr/irscan & pathmove in events will
500 * not have JTAG operations injected into the middle of a sequence.
502 bool save_poll = jtag_poll_get_enabled();
504 jtag_poll_set_enabled(false);
506 sprintf(buf, "ocd_process_reset %s", n->name);
507 retval = Jim_Eval(cmd_ctx->interp, buf);
509 jtag_poll_set_enabled(save_poll);
511 if (retval != JIM_OK) {
512 Jim_PrintErrorMessage(cmd_ctx->interp);
513 return ERROR_FAIL;
516 /* We want any events to be processed before the prompt */
517 retval = target_call_timer_callbacks_now();
519 struct target *target;
520 for (target = all_targets; target; target = target->next) {
521 target->type->check_reset(target);
524 return retval;
527 static int identity_virt2phys(struct target *target,
528 uint32_t virtual, uint32_t *physical)
530 *physical = virtual;
531 return ERROR_OK;
534 static int no_mmu(struct target *target, int *enabled)
536 *enabled = 0;
537 return ERROR_OK;
540 static int default_examine(struct target *target)
542 target_set_examined(target);
543 return ERROR_OK;
546 /* no check by default */
547 static int default_check_reset(struct target *target)
549 return ERROR_OK;
552 int target_examine_one(struct target *target)
554 return target->type->examine(target);
557 static int jtag_enable_callback(enum jtag_event event, void *priv)
559 struct target *target = priv;
561 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
562 return ERROR_OK;
564 jtag_unregister_event_callback(jtag_enable_callback, target);
565 return target_examine_one(target);
569 /* Targets that correctly implement init + examine, i.e.
570 * no communication with target during init:
572 * XScale
574 int target_examine(void)
576 int retval = ERROR_OK;
577 struct target *target;
579 for (target = all_targets; target; target = target->next)
581 /* defer examination, but don't skip it */
582 if (!target->tap->enabled) {
583 jtag_register_event_callback(jtag_enable_callback,
584 target);
585 continue;
587 if ((retval = target_examine_one(target)) != ERROR_OK)
588 return retval;
590 return retval;
592 const char *target_type_name(struct target *target)
594 return target->type->name;
597 static int target_write_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
599 if (!target_was_examined(target))
601 LOG_ERROR("Target not examined yet");
602 return ERROR_FAIL;
604 return target->type->write_memory_imp(target, address, size, count, buffer);
607 static int target_read_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
609 if (!target_was_examined(target))
611 LOG_ERROR("Target not examined yet");
612 return ERROR_FAIL;
614 return target->type->read_memory_imp(target, address, size, count, buffer);
617 static int target_soft_reset_halt_imp(struct target *target)
619 if (!target_was_examined(target))
621 LOG_ERROR("Target not examined yet");
622 return ERROR_FAIL;
624 if (!target->type->soft_reset_halt_imp) {
625 LOG_ERROR("Target %s does not support soft_reset_halt",
626 target_name(target));
627 return ERROR_FAIL;
629 return target->type->soft_reset_halt_imp(target);
633 * Downloads a target-specific native code algorithm to the target,
634 * and executes it. * Note that some targets may need to set up, enable,
635 * and tear down a breakpoint (hard or * soft) to detect algorithm
636 * termination, while others may support lower overhead schemes where
637 * soft breakpoints embedded in the algorithm automatically terminate the
638 * algorithm.
640 * @param target used to run the algorithm
641 * @param arch_info target-specific description of the algorithm.
643 int target_run_algorithm(struct target *target,
644 int num_mem_params, struct mem_param *mem_params,
645 int num_reg_params, struct reg_param *reg_param,
646 uint32_t entry_point, uint32_t exit_point,
647 int timeout_ms, void *arch_info)
649 int retval = ERROR_FAIL;
651 if (!target_was_examined(target))
653 LOG_ERROR("Target not examined yet");
654 goto done;
656 if (target->type->run_algorithm) {
657 LOG_ERROR("Target type '%s' does not support %s",
658 target_type_name(target), __func__);
659 goto done;
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);
667 done:
668 return retval;
672 int target_read_memory(struct target *target,
673 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
675 return target->type->read_memory(target, address, size, count, buffer);
678 int target_read_phys_memory(struct target *target,
679 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
681 return target->type->read_phys_memory(target, address, size, count, buffer);
684 int target_write_memory(struct target *target,
685 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
687 return target->type->write_memory(target, address, size, count, buffer);
690 int target_write_phys_memory(struct target *target,
691 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
693 return target->type->write_phys_memory(target, address, size, count, buffer);
696 int target_bulk_write_memory(struct target *target,
697 uint32_t address, uint32_t count, uint8_t *buffer)
699 return target->type->bulk_write_memory(target, address, count, buffer);
702 int target_add_breakpoint(struct target *target,
703 struct breakpoint *breakpoint)
705 if (target->state != TARGET_HALTED) {
706 LOG_WARNING("target %s is not halted", target->cmd_name);
707 return ERROR_TARGET_NOT_HALTED;
709 return target->type->add_breakpoint(target, breakpoint);
711 int target_remove_breakpoint(struct target *target,
712 struct breakpoint *breakpoint)
714 return target->type->remove_breakpoint(target, breakpoint);
717 int target_add_watchpoint(struct target *target,
718 struct watchpoint *watchpoint)
720 if (target->state != TARGET_HALTED) {
721 LOG_WARNING("target %s is not halted", target->cmd_name);
722 return ERROR_TARGET_NOT_HALTED;
724 return target->type->add_watchpoint(target, watchpoint);
726 int target_remove_watchpoint(struct target *target,
727 struct watchpoint *watchpoint)
729 return target->type->remove_watchpoint(target, watchpoint);
732 int target_get_gdb_reg_list(struct target *target,
733 struct reg **reg_list[], int *reg_list_size)
735 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
737 int target_step(struct target *target,
738 int current, uint32_t address, int handle_breakpoints)
740 return target->type->step(target, current, address, handle_breakpoints);
745 * Reset the @c examined flag for the given target.
746 * Pure paranoia -- targets are zeroed on allocation.
748 static void target_reset_examined(struct target *target)
750 target->examined = false;
753 static int
754 err_read_phys_memory(struct target *target, uint32_t address,
755 uint32_t size, uint32_t count, uint8_t *buffer)
757 LOG_ERROR("Not implemented: %s", __func__);
758 return ERROR_FAIL;
761 static int
762 err_write_phys_memory(struct target *target, uint32_t address,
763 uint32_t size, uint32_t count, uint8_t *buffer)
765 LOG_ERROR("Not implemented: %s", __func__);
766 return ERROR_FAIL;
769 static int handle_target(void *priv);
771 static int target_init_one(struct command_context *cmd_ctx,
772 struct target *target)
774 target_reset_examined(target);
776 struct target_type *type = target->type;
777 if (type->examine == NULL)
778 type->examine = default_examine;
780 if (type->check_reset== NULL)
781 type->check_reset = default_check_reset;
783 int retval = type->init_target(cmd_ctx, target);
784 if (ERROR_OK != retval)
786 LOG_ERROR("target '%s' init failed", target_name(target));
787 return retval;
791 * @todo get rid of those *memory_imp() methods, now that all
792 * callers are using target_*_memory() accessors ... and make
793 * sure the "physical" paths handle the same issues.
795 /* a non-invasive way(in terms of patches) to add some code that
796 * runs before the type->write/read_memory implementation
798 type->write_memory_imp = target->type->write_memory;
799 type->write_memory = target_write_memory_imp;
801 type->read_memory_imp = target->type->read_memory;
802 type->read_memory = target_read_memory_imp;
804 type->soft_reset_halt_imp = target->type->soft_reset_halt;
805 type->soft_reset_halt = target_soft_reset_halt_imp;
807 /* Sanity-check MMU support ... stub in what we must, to help
808 * implement it in stages, but warn if we need to do so.
810 if (type->mmu)
812 if (type->write_phys_memory == NULL)
814 LOG_ERROR("type '%s' is missing write_phys_memory",
815 type->name);
816 type->write_phys_memory = err_write_phys_memory;
818 if (type->read_phys_memory == NULL)
820 LOG_ERROR("type '%s' is missing read_phys_memory",
821 type->name);
822 type->read_phys_memory = err_read_phys_memory;
824 if (type->virt2phys == NULL)
826 LOG_ERROR("type '%s' is missing virt2phys", type->name);
827 type->virt2phys = identity_virt2phys;
830 else
832 /* Make sure no-MMU targets all behave the same: make no
833 * distinction between physical and virtual addresses, and
834 * ensure that virt2phys() is always an identity mapping.
836 if (type->write_phys_memory || type->read_phys_memory
837 || type->virt2phys)
839 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
842 type->mmu = no_mmu;
843 type->write_phys_memory = type->write_memory;
844 type->read_phys_memory = type->read_memory;
845 type->virt2phys = identity_virt2phys;
847 return ERROR_OK;
850 int target_init(struct command_context *cmd_ctx)
852 struct target *target;
853 int retval;
855 for (target = all_targets; target; target = target->next)
857 retval = target_init_one(cmd_ctx, target);
858 if (ERROR_OK != retval)
859 return retval;
862 if (!all_targets)
863 return ERROR_OK;
865 retval = target_register_user_commands(cmd_ctx);
866 if (ERROR_OK != retval)
867 return retval;
869 retval = target_register_timer_callback(&handle_target,
870 100, 1, cmd_ctx->interp);
871 if (ERROR_OK != retval)
872 return retval;
874 return ERROR_OK;
877 COMMAND_HANDLER(handle_target_init_command)
879 if (CMD_ARGC != 0)
880 return ERROR_COMMAND_SYNTAX_ERROR;
882 static bool target_initialized = false;
883 if (target_initialized)
885 LOG_INFO("'target init' has already been called");
886 return ERROR_OK;
888 target_initialized = true;
890 LOG_DEBUG("Initializing targets...");
891 return target_init(CMD_CTX);
894 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
896 struct target_event_callback **callbacks_p = &target_event_callbacks;
898 if (callback == NULL)
900 return ERROR_INVALID_ARGUMENTS;
903 if (*callbacks_p)
905 while ((*callbacks_p)->next)
906 callbacks_p = &((*callbacks_p)->next);
907 callbacks_p = &((*callbacks_p)->next);
910 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
911 (*callbacks_p)->callback = callback;
912 (*callbacks_p)->priv = priv;
913 (*callbacks_p)->next = NULL;
915 return ERROR_OK;
918 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
920 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
921 struct timeval now;
923 if (callback == NULL)
925 return ERROR_INVALID_ARGUMENTS;
928 if (*callbacks_p)
930 while ((*callbacks_p)->next)
931 callbacks_p = &((*callbacks_p)->next);
932 callbacks_p = &((*callbacks_p)->next);
935 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
936 (*callbacks_p)->callback = callback;
937 (*callbacks_p)->periodic = periodic;
938 (*callbacks_p)->time_ms = time_ms;
940 gettimeofday(&now, NULL);
941 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
942 time_ms -= (time_ms % 1000);
943 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
944 if ((*callbacks_p)->when.tv_usec > 1000000)
946 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
947 (*callbacks_p)->when.tv_sec += 1;
950 (*callbacks_p)->priv = priv;
951 (*callbacks_p)->next = NULL;
953 return ERROR_OK;
956 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
958 struct target_event_callback **p = &target_event_callbacks;
959 struct target_event_callback *c = target_event_callbacks;
961 if (callback == NULL)
963 return ERROR_INVALID_ARGUMENTS;
966 while (c)
968 struct target_event_callback *next = c->next;
969 if ((c->callback == callback) && (c->priv == priv))
971 *p = next;
972 free(c);
973 return ERROR_OK;
975 else
976 p = &(c->next);
977 c = next;
980 return ERROR_OK;
983 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
985 struct target_timer_callback **p = &target_timer_callbacks;
986 struct target_timer_callback *c = target_timer_callbacks;
988 if (callback == NULL)
990 return ERROR_INVALID_ARGUMENTS;
993 while (c)
995 struct target_timer_callback *next = c->next;
996 if ((c->callback == callback) && (c->priv == priv))
998 *p = next;
999 free(c);
1000 return ERROR_OK;
1002 else
1003 p = &(c->next);
1004 c = next;
1007 return ERROR_OK;
1010 int target_call_event_callbacks(struct target *target, enum target_event event)
1012 struct target_event_callback *callback = target_event_callbacks;
1013 struct target_event_callback *next_callback;
1015 if (event == TARGET_EVENT_HALTED)
1017 /* execute early halted first */
1018 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1021 LOG_DEBUG("target event %i (%s)",
1022 event,
1023 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1025 target_handle_event(target, event);
1027 while (callback)
1029 next_callback = callback->next;
1030 callback->callback(target, event, callback->priv);
1031 callback = next_callback;
1034 return ERROR_OK;
1037 static int target_timer_callback_periodic_restart(
1038 struct target_timer_callback *cb, struct timeval *now)
1040 int time_ms = cb->time_ms;
1041 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1042 time_ms -= (time_ms % 1000);
1043 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1044 if (cb->when.tv_usec > 1000000)
1046 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1047 cb->when.tv_sec += 1;
1049 return ERROR_OK;
1052 static int target_call_timer_callback(struct target_timer_callback *cb,
1053 struct timeval *now)
1055 cb->callback(cb->priv);
1057 if (cb->periodic)
1058 return target_timer_callback_periodic_restart(cb, now);
1060 return target_unregister_timer_callback(cb->callback, cb->priv);
1063 static int target_call_timer_callbacks_check_time(int checktime)
1065 keep_alive();
1067 struct timeval now;
1068 gettimeofday(&now, NULL);
1070 struct target_timer_callback *callback = target_timer_callbacks;
1071 while (callback)
1073 // cleaning up may unregister and free this callback
1074 struct target_timer_callback *next_callback = callback->next;
1076 bool call_it = callback->callback &&
1077 ((!checktime && callback->periodic) ||
1078 now.tv_sec > callback->when.tv_sec ||
1079 (now.tv_sec == callback->when.tv_sec &&
1080 now.tv_usec >= callback->when.tv_usec));
1082 if (call_it)
1084 int retval = target_call_timer_callback(callback, &now);
1085 if (retval != ERROR_OK)
1086 return retval;
1089 callback = next_callback;
1092 return ERROR_OK;
1095 int target_call_timer_callbacks(void)
1097 return target_call_timer_callbacks_check_time(1);
1100 /* invoke periodic callbacks immediately */
1101 int target_call_timer_callbacks_now(void)
1103 return target_call_timer_callbacks_check_time(0);
1106 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1108 struct working_area *c = target->working_areas;
1109 struct working_area *new_wa = NULL;
1111 /* Reevaluate working area address based on MMU state*/
1112 if (target->working_areas == NULL)
1114 int retval;
1115 int enabled;
1117 retval = target->type->mmu(target, &enabled);
1118 if (retval != ERROR_OK)
1120 return retval;
1123 if (!enabled) {
1124 if (target->working_area_phys_spec) {
1125 LOG_DEBUG("MMU disabled, using physical "
1126 "address for working memory 0x%08x",
1127 (unsigned)target->working_area_phys);
1128 target->working_area = target->working_area_phys;
1129 } else {
1130 LOG_ERROR("No working memory available. "
1131 "Specify -work-area-phys to target.");
1132 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1134 } else {
1135 if (target->working_area_virt_spec) {
1136 LOG_DEBUG("MMU enabled, using virtual "
1137 "address for working memory 0x%08x",
1138 (unsigned)target->working_area_virt);
1139 target->working_area = target->working_area_virt;
1140 } else {
1141 LOG_ERROR("No working memory available. "
1142 "Specify -work-area-virt to target.");
1143 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1148 /* only allocate multiples of 4 byte */
1149 if (size % 4)
1151 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1152 size = (size + 3) & (~3);
1155 /* see if there's already a matching working area */
1156 while (c)
1158 if ((c->free) && (c->size == size))
1160 new_wa = c;
1161 break;
1163 c = c->next;
1166 /* if not, allocate a new one */
1167 if (!new_wa)
1169 struct working_area **p = &target->working_areas;
1170 uint32_t first_free = target->working_area;
1171 uint32_t free_size = target->working_area_size;
1173 c = target->working_areas;
1174 while (c)
1176 first_free += c->size;
1177 free_size -= c->size;
1178 p = &c->next;
1179 c = c->next;
1182 if (free_size < size)
1184 LOG_WARNING("not enough working area available(requested %u, free %u)",
1185 (unsigned)(size), (unsigned)(free_size));
1186 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1189 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1191 new_wa = malloc(sizeof(struct working_area));
1192 new_wa->next = NULL;
1193 new_wa->size = size;
1194 new_wa->address = first_free;
1196 if (target->backup_working_area)
1198 int retval;
1199 new_wa->backup = malloc(new_wa->size);
1200 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1202 free(new_wa->backup);
1203 free(new_wa);
1204 return retval;
1207 else
1209 new_wa->backup = NULL;
1212 /* put new entry in list */
1213 *p = new_wa;
1216 /* mark as used, and return the new (reused) area */
1217 new_wa->free = 0;
1218 *area = new_wa;
1220 /* user pointer */
1221 new_wa->user = area;
1223 return ERROR_OK;
1226 int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1228 if (area->free)
1229 return ERROR_OK;
1231 if (restore && target->backup_working_area)
1233 int retval;
1234 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1235 return retval;
1238 area->free = 1;
1240 /* mark user pointer invalid */
1241 *area->user = NULL;
1242 area->user = NULL;
1244 return ERROR_OK;
1247 int target_free_working_area(struct target *target, struct working_area *area)
1249 return target_free_working_area_restore(target, area, 1);
1252 /* free resources and restore memory, if restoring memory fails,
1253 * free up resources anyway
1255 void target_free_all_working_areas_restore(struct target *target, int restore)
1257 struct working_area *c = target->working_areas;
1259 while (c)
1261 struct working_area *next = c->next;
1262 target_free_working_area_restore(target, c, restore);
1264 if (c->backup)
1265 free(c->backup);
1267 free(c);
1269 c = next;
1272 target->working_areas = NULL;
1275 void target_free_all_working_areas(struct target *target)
1277 target_free_all_working_areas_restore(target, 1);
1280 int target_arch_state(struct target *target)
1282 int retval;
1283 if (target == NULL)
1285 LOG_USER("No target has been configured");
1286 return ERROR_OK;
1289 LOG_USER("target state: %s", target_state_name( target ));
1291 if (target->state != TARGET_HALTED)
1292 return ERROR_OK;
1294 retval = target->type->arch_state(target);
1295 return retval;
1298 /* Single aligned words are guaranteed to use 16 or 32 bit access
1299 * mode respectively, otherwise data is handled as quickly as
1300 * possible
1302 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1304 int retval;
1305 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1306 (int)size, (unsigned)address);
1308 if (!target_was_examined(target))
1310 LOG_ERROR("Target not examined yet");
1311 return ERROR_FAIL;
1314 if (size == 0) {
1315 return ERROR_OK;
1318 if ((address + size - 1) < address)
1320 /* GDB can request this when e.g. PC is 0xfffffffc*/
1321 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1322 (unsigned)address,
1323 (unsigned)size);
1324 return ERROR_FAIL;
1327 if (((address % 2) == 0) && (size == 2))
1329 return target_write_memory(target, address, 2, 1, buffer);
1332 /* handle unaligned head bytes */
1333 if (address % 4)
1335 uint32_t unaligned = 4 - (address % 4);
1337 if (unaligned > size)
1338 unaligned = size;
1340 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1341 return retval;
1343 buffer += unaligned;
1344 address += unaligned;
1345 size -= unaligned;
1348 /* handle aligned words */
1349 if (size >= 4)
1351 int aligned = size - (size % 4);
1353 /* use bulk writes above a certain limit. This may have to be changed */
1354 if (aligned > 128)
1356 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1357 return retval;
1359 else
1361 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1362 return retval;
1365 buffer += aligned;
1366 address += aligned;
1367 size -= aligned;
1370 /* handle tail writes of less than 4 bytes */
1371 if (size > 0)
1373 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1374 return retval;
1377 return ERROR_OK;
1380 /* Single aligned words are guaranteed to use 16 or 32 bit access
1381 * mode respectively, otherwise data is handled as quickly as
1382 * possible
1384 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1386 int retval;
1387 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1388 (int)size, (unsigned)address);
1390 if (!target_was_examined(target))
1392 LOG_ERROR("Target not examined yet");
1393 return ERROR_FAIL;
1396 if (size == 0) {
1397 return ERROR_OK;
1400 if ((address + size - 1) < address)
1402 /* GDB can request this when e.g. PC is 0xfffffffc*/
1403 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1404 address,
1405 size);
1406 return ERROR_FAIL;
1409 if (((address % 2) == 0) && (size == 2))
1411 return target_read_memory(target, address, 2, 1, buffer);
1414 /* handle unaligned head bytes */
1415 if (address % 4)
1417 uint32_t unaligned = 4 - (address % 4);
1419 if (unaligned > size)
1420 unaligned = size;
1422 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1423 return retval;
1425 buffer += unaligned;
1426 address += unaligned;
1427 size -= unaligned;
1430 /* handle aligned words */
1431 if (size >= 4)
1433 int aligned = size - (size % 4);
1435 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1436 return retval;
1438 buffer += aligned;
1439 address += aligned;
1440 size -= aligned;
1443 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1444 if(size >=2)
1446 int aligned = size - (size%2);
1447 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1448 if (retval != ERROR_OK)
1449 return retval;
1451 buffer += aligned;
1452 address += aligned;
1453 size -= aligned;
1455 /* handle tail writes of less than 4 bytes */
1456 if (size > 0)
1458 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1459 return retval;
1462 return ERROR_OK;
1465 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1467 uint8_t *buffer;
1468 int retval;
1469 uint32_t i;
1470 uint32_t checksum = 0;
1471 if (!target_was_examined(target))
1473 LOG_ERROR("Target not examined yet");
1474 return ERROR_FAIL;
1477 if ((retval = target->type->checksum_memory(target, address,
1478 size, &checksum)) != ERROR_OK)
1480 buffer = malloc(size);
1481 if (buffer == NULL)
1483 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1484 return ERROR_INVALID_ARGUMENTS;
1486 retval = target_read_buffer(target, address, size, buffer);
1487 if (retval != ERROR_OK)
1489 free(buffer);
1490 return retval;
1493 /* convert to target endianess */
1494 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1496 uint32_t target_data;
1497 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1498 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1501 retval = image_calculate_checksum(buffer, size, &checksum);
1502 free(buffer);
1505 *crc = checksum;
1507 return retval;
1510 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1512 int retval;
1513 if (!target_was_examined(target))
1515 LOG_ERROR("Target not examined yet");
1516 return ERROR_FAIL;
1519 if (target->type->blank_check_memory == 0)
1520 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1522 retval = target->type->blank_check_memory(target, address, size, blank);
1524 return retval;
1527 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1529 uint8_t value_buf[4];
1530 if (!target_was_examined(target))
1532 LOG_ERROR("Target not examined yet");
1533 return ERROR_FAIL;
1536 int retval = target_read_memory(target, address, 4, 1, value_buf);
1538 if (retval == ERROR_OK)
1540 *value = target_buffer_get_u32(target, value_buf);
1541 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1542 address,
1543 *value);
1545 else
1547 *value = 0x0;
1548 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1549 address);
1552 return retval;
1555 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1557 uint8_t value_buf[2];
1558 if (!target_was_examined(target))
1560 LOG_ERROR("Target not examined yet");
1561 return ERROR_FAIL;
1564 int retval = target_read_memory(target, address, 2, 1, value_buf);
1566 if (retval == ERROR_OK)
1568 *value = target_buffer_get_u16(target, value_buf);
1569 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1570 address,
1571 *value);
1573 else
1575 *value = 0x0;
1576 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1577 address);
1580 return retval;
1583 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1585 int retval = target_read_memory(target, address, 1, 1, value);
1586 if (!target_was_examined(target))
1588 LOG_ERROR("Target not examined yet");
1589 return ERROR_FAIL;
1592 if (retval == ERROR_OK)
1594 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1595 address,
1596 *value);
1598 else
1600 *value = 0x0;
1601 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1602 address);
1605 return retval;
1608 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1610 int retval;
1611 uint8_t value_buf[4];
1612 if (!target_was_examined(target))
1614 LOG_ERROR("Target not examined yet");
1615 return ERROR_FAIL;
1618 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1619 address,
1620 value);
1622 target_buffer_set_u32(target, value_buf, value);
1623 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1625 LOG_DEBUG("failed: %i", retval);
1628 return retval;
1631 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1633 int retval;
1634 uint8_t value_buf[2];
1635 if (!target_was_examined(target))
1637 LOG_ERROR("Target not examined yet");
1638 return ERROR_FAIL;
1641 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1642 address,
1643 value);
1645 target_buffer_set_u16(target, value_buf, value);
1646 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1648 LOG_DEBUG("failed: %i", retval);
1651 return retval;
1654 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1656 int retval;
1657 if (!target_was_examined(target))
1659 LOG_ERROR("Target not examined yet");
1660 return ERROR_FAIL;
1663 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1664 address, value);
1666 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1668 LOG_DEBUG("failed: %i", retval);
1671 return retval;
1674 COMMAND_HANDLER(handle_targets_command)
1676 struct target *target = all_targets;
1678 if (CMD_ARGC == 1)
1680 target = get_target(CMD_ARGV[0]);
1681 if (target == NULL) {
1682 command_print(CMD_CTX,"Target: %s is unknown, try one of:\n", CMD_ARGV[0]);
1683 goto DumpTargets;
1685 if (!target->tap->enabled) {
1686 command_print(CMD_CTX,"Target: TAP %s is disabled, "
1687 "can't be the current target\n",
1688 target->tap->dotted_name);
1689 return ERROR_FAIL;
1692 CMD_CTX->current_target = target->target_number;
1693 return ERROR_OK;
1695 DumpTargets:
1697 target = all_targets;
1698 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
1699 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
1700 while (target)
1702 const char *state;
1703 char marker = ' ';
1705 if (target->tap->enabled)
1706 state = target_state_name( target );
1707 else
1708 state = "tap-disabled";
1710 if (CMD_CTX->current_target == target->target_number)
1711 marker = '*';
1713 /* keep columns lined up to match the headers above */
1714 command_print(CMD_CTX, "%2d%c %-18s %-10s %-6s %-18s %s",
1715 target->target_number,
1716 marker,
1717 target_name(target),
1718 target_type_name(target),
1719 Jim_Nvp_value2name_simple(nvp_target_endian,
1720 target->endianness)->name,
1721 target->tap->dotted_name,
1722 state);
1723 target = target->next;
1726 return ERROR_OK;
1729 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1731 static int powerDropout;
1732 static int srstAsserted;
1734 static int runPowerRestore;
1735 static int runPowerDropout;
1736 static int runSrstAsserted;
1737 static int runSrstDeasserted;
1739 static int sense_handler(void)
1741 static int prevSrstAsserted = 0;
1742 static int prevPowerdropout = 0;
1744 int retval;
1745 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1746 return retval;
1748 int powerRestored;
1749 powerRestored = prevPowerdropout && !powerDropout;
1750 if (powerRestored)
1752 runPowerRestore = 1;
1755 long long current = timeval_ms();
1756 static long long lastPower = 0;
1757 int waitMore = lastPower + 2000 > current;
1758 if (powerDropout && !waitMore)
1760 runPowerDropout = 1;
1761 lastPower = current;
1764 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1765 return retval;
1767 int srstDeasserted;
1768 srstDeasserted = prevSrstAsserted && !srstAsserted;
1770 static long long lastSrst = 0;
1771 waitMore = lastSrst + 2000 > current;
1772 if (srstDeasserted && !waitMore)
1774 runSrstDeasserted = 1;
1775 lastSrst = current;
1778 if (!prevSrstAsserted && srstAsserted)
1780 runSrstAsserted = 1;
1783 prevSrstAsserted = srstAsserted;
1784 prevPowerdropout = powerDropout;
1786 if (srstDeasserted || powerRestored)
1788 /* Other than logging the event we can't do anything here.
1789 * Issuing a reset is a particularly bad idea as we might
1790 * be inside a reset already.
1794 return ERROR_OK;
1797 /* process target state changes */
1798 static int handle_target(void *priv)
1800 Jim_Interp *interp = (Jim_Interp *)priv;
1801 int retval = ERROR_OK;
1803 if (!is_jtag_poll_safe())
1805 /* polling is disabled currently */
1806 return ERROR_OK;
1809 /* we do not want to recurse here... */
1810 static int recursive = 0;
1811 if (! recursive)
1813 recursive = 1;
1814 sense_handler();
1815 /* danger! running these procedures can trigger srst assertions and power dropouts.
1816 * We need to avoid an infinite loop/recursion here and we do that by
1817 * clearing the flags after running these events.
1819 int did_something = 0;
1820 if (runSrstAsserted)
1822 LOG_INFO("srst asserted detected, running srst_asserted proc.");
1823 Jim_Eval(interp, "srst_asserted");
1824 did_something = 1;
1826 if (runSrstDeasserted)
1828 Jim_Eval(interp, "srst_deasserted");
1829 did_something = 1;
1831 if (runPowerDropout)
1833 LOG_INFO("Power dropout detected, running power_dropout proc.");
1834 Jim_Eval(interp, "power_dropout");
1835 did_something = 1;
1837 if (runPowerRestore)
1839 Jim_Eval(interp, "power_restore");
1840 did_something = 1;
1843 if (did_something)
1845 /* clear detect flags */
1846 sense_handler();
1849 /* clear action flags */
1851 runSrstAsserted = 0;
1852 runSrstDeasserted = 0;
1853 runPowerRestore = 0;
1854 runPowerDropout = 0;
1856 recursive = 0;
1859 /* Poll targets for state changes unless that's globally disabled.
1860 * Skip targets that are currently disabled.
1862 for (struct target *target = all_targets;
1863 is_jtag_poll_safe() && target;
1864 target = target->next)
1866 if (!target->tap->enabled)
1867 continue;
1869 /* only poll target if we've got power and srst isn't asserted */
1870 if (!powerDropout && !srstAsserted)
1872 /* polling may fail silently until the target has been examined */
1873 if ((retval = target_poll(target)) != ERROR_OK)
1875 /* FIX!!!!! If we add a LOG_INFO() here to output a line in GDB
1876 * *why* we are aborting GDB, then we'll spam telnet when the
1877 * poll is failing persistently.
1879 * If we could implement an event that detected the
1880 * target going from non-pollable to pollable, we could issue
1881 * an error only upon the transition.
1883 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1884 return retval;
1889 return retval;
1892 COMMAND_HANDLER(handle_reg_command)
1894 struct target *target;
1895 struct reg *reg = NULL;
1896 unsigned count = 0;
1897 char *value;
1899 LOG_DEBUG("-");
1901 target = get_current_target(CMD_CTX);
1903 /* list all available registers for the current target */
1904 if (CMD_ARGC == 0)
1906 struct reg_cache *cache = target->reg_cache;
1908 count = 0;
1909 while (cache)
1911 unsigned i;
1913 command_print(CMD_CTX, "===== %s", cache->name);
1915 for (i = 0, reg = cache->reg_list;
1916 i < cache->num_regs;
1917 i++, reg++, count++)
1919 /* only print cached values if they are valid */
1920 if (reg->valid) {
1921 value = buf_to_str(reg->value,
1922 reg->size, 16);
1923 command_print(CMD_CTX,
1924 "(%i) %s (/%" PRIu32 "): 0x%s%s",
1925 count, reg->name,
1926 reg->size, value,
1927 reg->dirty
1928 ? " (dirty)"
1929 : "");
1930 free(value);
1931 } else {
1932 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
1933 count, reg->name,
1934 reg->size) ;
1937 cache = cache->next;
1940 return ERROR_OK;
1943 /* access a single register by its ordinal number */
1944 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9'))
1946 unsigned num;
1947 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
1949 struct reg_cache *cache = target->reg_cache;
1950 count = 0;
1951 while (cache)
1953 unsigned i;
1954 for (i = 0; i < cache->num_regs; i++)
1956 if (count++ == num)
1958 reg = &cache->reg_list[i];
1959 break;
1962 if (reg)
1963 break;
1964 cache = cache->next;
1967 if (!reg)
1969 command_print(CMD_CTX, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1970 return ERROR_OK;
1972 } else /* access a single register by its name */
1974 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
1976 if (!reg)
1978 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
1979 return ERROR_OK;
1983 /* display a register */
1984 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0') && (CMD_ARGV[1][0] <= '9'))))
1986 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
1987 reg->valid = 0;
1989 if (reg->valid == 0)
1991 reg->type->get(reg);
1993 value = buf_to_str(reg->value, reg->size, 16);
1994 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1995 free(value);
1996 return ERROR_OK;
1999 /* set register value */
2000 if (CMD_ARGC == 2)
2002 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2003 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2005 reg->type->set(reg, buf);
2007 value = buf_to_str(reg->value, reg->size, 16);
2008 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2009 free(value);
2011 free(buf);
2013 return ERROR_OK;
2016 command_print(CMD_CTX, "usage: reg <#|name> [value]");
2018 return ERROR_OK;
2021 COMMAND_HANDLER(handle_poll_command)
2023 int retval = ERROR_OK;
2024 struct target *target = get_current_target(CMD_CTX);
2026 if (CMD_ARGC == 0)
2028 command_print(CMD_CTX, "background polling: %s",
2029 jtag_poll_get_enabled() ? "on" : "off");
2030 command_print(CMD_CTX, "TAP: %s (%s)",
2031 target->tap->dotted_name,
2032 target->tap->enabled ? "enabled" : "disabled");
2033 if (!target->tap->enabled)
2034 return ERROR_OK;
2035 if ((retval = target_poll(target)) != ERROR_OK)
2036 return retval;
2037 if ((retval = target_arch_state(target)) != ERROR_OK)
2038 return retval;
2040 else if (CMD_ARGC == 1)
2042 bool enable;
2043 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2044 jtag_poll_set_enabled(enable);
2046 else
2048 return ERROR_COMMAND_SYNTAX_ERROR;
2051 return retval;
2054 COMMAND_HANDLER(handle_wait_halt_command)
2056 if (CMD_ARGC > 1)
2057 return ERROR_COMMAND_SYNTAX_ERROR;
2059 unsigned ms = 5000;
2060 if (1 == CMD_ARGC)
2062 int retval = parse_uint(CMD_ARGV[0], &ms);
2063 if (ERROR_OK != retval)
2065 command_print(CMD_CTX, "usage: %s [seconds]", CMD_NAME);
2066 return ERROR_COMMAND_SYNTAX_ERROR;
2068 // convert seconds (given) to milliseconds (needed)
2069 ms *= 1000;
2072 struct target *target = get_current_target(CMD_CTX);
2073 return target_wait_state(target, TARGET_HALTED, ms);
2076 /* wait for target state to change. The trick here is to have a low
2077 * latency for short waits and not to suck up all the CPU time
2078 * on longer waits.
2080 * After 500ms, keep_alive() is invoked
2082 int target_wait_state(struct target *target, enum target_state state, int ms)
2084 int retval;
2085 long long then = 0, cur;
2086 int once = 1;
2088 for (;;)
2090 if ((retval = target_poll(target)) != ERROR_OK)
2091 return retval;
2092 if (target->state == state)
2094 break;
2096 cur = timeval_ms();
2097 if (once)
2099 once = 0;
2100 then = timeval_ms();
2101 LOG_DEBUG("waiting for target %s...",
2102 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2105 if (cur-then > 500)
2107 keep_alive();
2110 if ((cur-then) > ms)
2112 LOG_ERROR("timed out while waiting for target %s",
2113 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2114 return ERROR_FAIL;
2118 return ERROR_OK;
2121 COMMAND_HANDLER(handle_halt_command)
2123 LOG_DEBUG("-");
2125 struct target *target = get_current_target(CMD_CTX);
2126 int retval = target_halt(target);
2127 if (ERROR_OK != retval)
2128 return retval;
2130 if (CMD_ARGC == 1)
2132 unsigned wait;
2133 retval = parse_uint(CMD_ARGV[0], &wait);
2134 if (ERROR_OK != retval)
2135 return ERROR_COMMAND_SYNTAX_ERROR;
2136 if (!wait)
2137 return ERROR_OK;
2140 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2143 COMMAND_HANDLER(handle_soft_reset_halt_command)
2145 struct target *target = get_current_target(CMD_CTX);
2147 LOG_USER("requesting target halt and executing a soft reset");
2149 target->type->soft_reset_halt(target);
2151 return ERROR_OK;
2154 COMMAND_HANDLER(handle_reset_command)
2156 if (CMD_ARGC > 1)
2157 return ERROR_COMMAND_SYNTAX_ERROR;
2159 enum target_reset_mode reset_mode = RESET_RUN;
2160 if (CMD_ARGC == 1)
2162 const Jim_Nvp *n;
2163 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2164 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2165 return ERROR_COMMAND_SYNTAX_ERROR;
2167 reset_mode = n->value;
2170 /* reset *all* targets */
2171 return target_process_reset(CMD_CTX, reset_mode);
2175 COMMAND_HANDLER(handle_resume_command)
2177 int current = 1;
2178 if (CMD_ARGC > 1)
2179 return ERROR_COMMAND_SYNTAX_ERROR;
2181 struct target *target = get_current_target(CMD_CTX);
2182 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2184 /* with no CMD_ARGV, resume from current pc, addr = 0,
2185 * with one arguments, addr = CMD_ARGV[0],
2186 * handle breakpoints, not debugging */
2187 uint32_t addr = 0;
2188 if (CMD_ARGC == 1)
2190 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2191 current = 0;
2194 return target_resume(target, current, addr, 1, 0);
2197 COMMAND_HANDLER(handle_step_command)
2199 if (CMD_ARGC > 1)
2200 return ERROR_COMMAND_SYNTAX_ERROR;
2202 LOG_DEBUG("-");
2204 /* with no CMD_ARGV, step from current pc, addr = 0,
2205 * with one argument addr = CMD_ARGV[0],
2206 * handle breakpoints, debugging */
2207 uint32_t addr = 0;
2208 int current_pc = 1;
2209 if (CMD_ARGC == 1)
2211 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2212 current_pc = 0;
2215 struct target *target = get_current_target(CMD_CTX);
2217 return target->type->step(target, current_pc, addr, 1);
2220 static void handle_md_output(struct command_context *cmd_ctx,
2221 struct target *target, uint32_t address, unsigned size,
2222 unsigned count, const uint8_t *buffer)
2224 const unsigned line_bytecnt = 32;
2225 unsigned line_modulo = line_bytecnt / size;
2227 char output[line_bytecnt * 4 + 1];
2228 unsigned output_len = 0;
2230 const char *value_fmt;
2231 switch (size) {
2232 case 4: value_fmt = "%8.8x "; break;
2233 case 2: value_fmt = "%4.4x "; break;
2234 case 1: value_fmt = "%2.2x "; break;
2235 default:
2236 /* "can't happen", caller checked */
2237 LOG_ERROR("invalid memory read size: %u", size);
2238 return;
2241 for (unsigned i = 0; i < count; i++)
2243 if (i % line_modulo == 0)
2245 output_len += snprintf(output + output_len,
2246 sizeof(output) - output_len,
2247 "0x%8.8x: ",
2248 (unsigned)(address + (i*size)));
2251 uint32_t value = 0;
2252 const uint8_t *value_ptr = buffer + i * size;
2253 switch (size) {
2254 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2255 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2256 case 1: value = *value_ptr;
2258 output_len += snprintf(output + output_len,
2259 sizeof(output) - output_len,
2260 value_fmt, value);
2262 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2264 command_print(cmd_ctx, "%s", output);
2265 output_len = 0;
2270 COMMAND_HANDLER(handle_md_command)
2272 if (CMD_ARGC < 1)
2273 return ERROR_COMMAND_SYNTAX_ERROR;
2275 unsigned size = 0;
2276 switch (CMD_NAME[2]) {
2277 case 'w': size = 4; break;
2278 case 'h': size = 2; break;
2279 case 'b': size = 1; break;
2280 default: return ERROR_COMMAND_SYNTAX_ERROR;
2283 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2284 int (*fn)(struct target *target,
2285 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2286 if (physical)
2288 CMD_ARGC--;
2289 CMD_ARGV++;
2290 fn=target_read_phys_memory;
2291 } else
2293 fn=target_read_memory;
2295 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2297 return ERROR_COMMAND_SYNTAX_ERROR;
2300 uint32_t address;
2301 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2303 unsigned count = 1;
2304 if (CMD_ARGC == 2)
2305 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2307 uint8_t *buffer = calloc(count, size);
2309 struct target *target = get_current_target(CMD_CTX);
2310 int retval = fn(target, address, size, count, buffer);
2311 if (ERROR_OK == retval)
2312 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2314 free(buffer);
2316 return retval;
2319 typedef int (*target_write_fn)(struct target *target,
2320 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2322 static int target_write_memory_fast(struct target *target,
2323 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
2325 return target_write_buffer(target, address, size * count, buffer);
2328 static int target_fill_mem(struct target *target,
2329 uint32_t address,
2330 target_write_fn fn,
2331 unsigned data_size,
2332 /* value */
2333 uint32_t b,
2334 /* count */
2335 unsigned c)
2337 /* We have to write in reasonably large chunks to be able
2338 * to fill large memory areas with any sane speed */
2339 const unsigned chunk_size = 16384;
2340 uint8_t *target_buf = malloc(chunk_size * data_size);
2341 if (target_buf == NULL)
2343 LOG_ERROR("Out of memory");
2344 return ERROR_FAIL;
2347 for (unsigned i = 0; i < chunk_size; i ++)
2349 switch (data_size)
2351 case 4:
2352 target_buffer_set_u32(target, target_buf + i*data_size, b);
2353 break;
2354 case 2:
2355 target_buffer_set_u16(target, target_buf + i*data_size, b);
2356 break;
2357 case 1:
2358 target_buffer_set_u8(target, target_buf + i*data_size, b);
2359 break;
2360 default:
2361 exit(-1);
2365 int retval = ERROR_OK;
2367 for (unsigned x = 0; x < c; x += chunk_size)
2369 unsigned current;
2370 current = c - x;
2371 if (current > chunk_size)
2373 current = chunk_size;
2375 int retval = fn(target, address + x * data_size, data_size, current, target_buf);
2376 if (retval != ERROR_OK)
2378 break;
2380 /* avoid GDB timeouts */
2381 keep_alive();
2383 free(target_buf);
2385 return retval;
2389 COMMAND_HANDLER(handle_mw_command)
2391 if (CMD_ARGC < 2)
2393 return ERROR_COMMAND_SYNTAX_ERROR;
2395 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2396 target_write_fn fn;
2397 if (physical)
2399 CMD_ARGC--;
2400 CMD_ARGV++;
2401 fn=target_write_phys_memory;
2402 } else
2404 fn = target_write_memory_fast;
2406 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2407 return ERROR_COMMAND_SYNTAX_ERROR;
2409 uint32_t address;
2410 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2412 uint32_t value;
2413 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2415 unsigned count = 1;
2416 if (CMD_ARGC == 3)
2417 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2419 struct target *target = get_current_target(CMD_CTX);
2420 unsigned wordsize;
2421 switch (CMD_NAME[2])
2423 case 'w':
2424 wordsize = 4;
2425 break;
2426 case 'h':
2427 wordsize = 2;
2428 break;
2429 case 'b':
2430 wordsize = 1;
2431 break;
2432 default:
2433 return ERROR_COMMAND_SYNTAX_ERROR;
2436 return target_fill_mem(target, address, fn, wordsize, value, count);
2439 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2440 uint32_t *min_address, uint32_t *max_address)
2442 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2443 return ERROR_COMMAND_SYNTAX_ERROR;
2445 /* a base address isn't always necessary,
2446 * default to 0x0 (i.e. don't relocate) */
2447 if (CMD_ARGC >= 2)
2449 uint32_t addr;
2450 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2451 image->base_address = addr;
2452 image->base_address_set = 1;
2454 else
2455 image->base_address_set = 0;
2457 image->start_address_set = 0;
2459 if (CMD_ARGC >= 4)
2461 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2463 if (CMD_ARGC == 5)
2465 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2466 // use size (given) to find max (required)
2467 *max_address += *min_address;
2470 if (*min_address > *max_address)
2471 return ERROR_COMMAND_SYNTAX_ERROR;
2473 return ERROR_OK;
2476 COMMAND_HANDLER(handle_load_image_command)
2478 uint8_t *buffer;
2479 size_t buf_cnt;
2480 uint32_t image_size;
2481 uint32_t min_address = 0;
2482 uint32_t max_address = 0xffffffff;
2483 int i;
2484 struct image image;
2486 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2487 &image, &min_address, &max_address);
2488 if (ERROR_OK != retval)
2489 return retval;
2491 struct target *target = get_current_target(CMD_CTX);
2493 struct duration bench;
2494 duration_start(&bench);
2496 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2498 return ERROR_OK;
2501 image_size = 0x0;
2502 retval = ERROR_OK;
2503 for (i = 0; i < image.num_sections; i++)
2505 buffer = malloc(image.sections[i].size);
2506 if (buffer == NULL)
2508 command_print(CMD_CTX,
2509 "error allocating buffer for section (%d bytes)",
2510 (int)(image.sections[i].size));
2511 break;
2514 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2516 free(buffer);
2517 break;
2520 uint32_t offset = 0;
2521 uint32_t length = buf_cnt;
2523 /* DANGER!!! beware of unsigned comparision here!!! */
2525 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2526 (image.sections[i].base_address < max_address))
2528 if (image.sections[i].base_address < min_address)
2530 /* clip addresses below */
2531 offset += min_address-image.sections[i].base_address;
2532 length -= offset;
2535 if (image.sections[i].base_address + buf_cnt > max_address)
2537 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2540 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2542 free(buffer);
2543 break;
2545 image_size += length;
2546 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2547 (unsigned int)length,
2548 image.sections[i].base_address + offset);
2551 free(buffer);
2554 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2556 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2557 "in %fs (%0.3f kb/s)", image_size,
2558 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2561 image_close(&image);
2563 return retval;
2567 COMMAND_HANDLER(handle_dump_image_command)
2569 struct fileio fileio;
2571 uint8_t buffer[560];
2572 int retvaltemp;
2575 struct target *target = get_current_target(CMD_CTX);
2577 if (CMD_ARGC != 3)
2579 command_print(CMD_CTX, "usage: dump_image <filename> <address> <size>");
2580 return ERROR_OK;
2583 uint32_t address;
2584 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2585 uint32_t size;
2586 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2588 if (fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2590 return ERROR_OK;
2593 struct duration bench;
2594 duration_start(&bench);
2596 int retval = ERROR_OK;
2597 while (size > 0)
2599 size_t size_written;
2600 uint32_t this_run_size = (size > 560) ? 560 : size;
2601 retval = target_read_buffer(target, address, this_run_size, buffer);
2602 if (retval != ERROR_OK)
2604 break;
2607 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2608 if (retval != ERROR_OK)
2610 break;
2613 size -= this_run_size;
2614 address += this_run_size;
2617 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2618 return retvaltemp;
2620 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2622 command_print(CMD_CTX,
2623 "dumped %ld bytes in %fs (%0.3f kb/s)", (long)fileio.size,
2624 duration_elapsed(&bench), duration_kbps(&bench, fileio.size));
2627 return retval;
2630 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2632 uint8_t *buffer;
2633 size_t buf_cnt;
2634 uint32_t image_size;
2635 int i;
2636 int retval;
2637 uint32_t checksum = 0;
2638 uint32_t mem_checksum = 0;
2640 struct image image;
2642 struct target *target = get_current_target(CMD_CTX);
2644 if (CMD_ARGC < 1)
2646 return ERROR_COMMAND_SYNTAX_ERROR;
2649 if (!target)
2651 LOG_ERROR("no target selected");
2652 return ERROR_FAIL;
2655 struct duration bench;
2656 duration_start(&bench);
2658 if (CMD_ARGC >= 2)
2660 uint32_t addr;
2661 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2662 image.base_address = addr;
2663 image.base_address_set = 1;
2665 else
2667 image.base_address_set = 0;
2668 image.base_address = 0x0;
2671 image.start_address_set = 0;
2673 if ((retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL)) != ERROR_OK)
2675 return retval;
2678 image_size = 0x0;
2679 retval = ERROR_OK;
2680 for (i = 0; i < image.num_sections; i++)
2682 buffer = malloc(image.sections[i].size);
2683 if (buffer == NULL)
2685 command_print(CMD_CTX,
2686 "error allocating buffer for section (%d bytes)",
2687 (int)(image.sections[i].size));
2688 break;
2690 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2692 free(buffer);
2693 break;
2696 if (verify)
2698 /* calculate checksum of image */
2699 image_calculate_checksum(buffer, buf_cnt, &checksum);
2701 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2702 if (retval != ERROR_OK)
2704 free(buffer);
2705 break;
2708 if (checksum != mem_checksum)
2710 /* failed crc checksum, fall back to a binary compare */
2711 uint8_t *data;
2713 command_print(CMD_CTX, "checksum mismatch - attempting binary compare");
2715 data = (uint8_t*)malloc(buf_cnt);
2717 /* Can we use 32bit word accesses? */
2718 int size = 1;
2719 int count = buf_cnt;
2720 if ((count % 4) == 0)
2722 size *= 4;
2723 count /= 4;
2725 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2726 if (retval == ERROR_OK)
2728 uint32_t t;
2729 for (t = 0; t < buf_cnt; t++)
2731 if (data[t] != buffer[t])
2733 command_print(CMD_CTX,
2734 "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n",
2735 (unsigned)(t + image.sections[i].base_address),
2736 data[t],
2737 buffer[t]);
2738 free(data);
2739 free(buffer);
2740 retval = ERROR_FAIL;
2741 goto done;
2743 if ((t%16384) == 0)
2745 keep_alive();
2750 free(data);
2752 } else
2754 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
2755 image.sections[i].base_address,
2756 buf_cnt);
2759 free(buffer);
2760 image_size += buf_cnt;
2762 done:
2763 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2765 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
2766 "in %fs (%0.3f kb/s)", image_size,
2767 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2770 image_close(&image);
2772 return retval;
2775 COMMAND_HANDLER(handle_verify_image_command)
2777 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2780 COMMAND_HANDLER(handle_test_image_command)
2782 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2785 static int handle_bp_command_list(struct command_context *cmd_ctx)
2787 struct target *target = get_current_target(cmd_ctx);
2788 struct breakpoint *breakpoint = target->breakpoints;
2789 while (breakpoint)
2791 if (breakpoint->type == BKPT_SOFT)
2793 char* buf = buf_to_str(breakpoint->orig_instr,
2794 breakpoint->length, 16);
2795 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2796 breakpoint->address,
2797 breakpoint->length,
2798 breakpoint->set, buf);
2799 free(buf);
2801 else
2803 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2804 breakpoint->address,
2805 breakpoint->length, breakpoint->set);
2808 breakpoint = breakpoint->next;
2810 return ERROR_OK;
2813 static int handle_bp_command_set(struct command_context *cmd_ctx,
2814 uint32_t addr, uint32_t length, int hw)
2816 struct target *target = get_current_target(cmd_ctx);
2817 int retval = breakpoint_add(target, addr, length, hw);
2818 if (ERROR_OK == retval)
2819 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2820 else
2821 LOG_ERROR("Failure setting breakpoint");
2822 return retval;
2825 COMMAND_HANDLER(handle_bp_command)
2827 if (CMD_ARGC == 0)
2828 return handle_bp_command_list(CMD_CTX);
2830 if (CMD_ARGC < 2 || CMD_ARGC > 3)
2832 command_print(CMD_CTX, "usage: bp <address> <length> ['hw']");
2833 return ERROR_COMMAND_SYNTAX_ERROR;
2836 uint32_t addr;
2837 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2838 uint32_t length;
2839 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2841 int hw = BKPT_SOFT;
2842 if (CMD_ARGC == 3)
2844 if (strcmp(CMD_ARGV[2], "hw") == 0)
2845 hw = BKPT_HARD;
2846 else
2847 return ERROR_COMMAND_SYNTAX_ERROR;
2850 return handle_bp_command_set(CMD_CTX, addr, length, hw);
2853 COMMAND_HANDLER(handle_rbp_command)
2855 if (CMD_ARGC != 1)
2856 return ERROR_COMMAND_SYNTAX_ERROR;
2858 uint32_t addr;
2859 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2861 struct target *target = get_current_target(CMD_CTX);
2862 breakpoint_remove(target, addr);
2864 return ERROR_OK;
2867 COMMAND_HANDLER(handle_wp_command)
2869 struct target *target = get_current_target(CMD_CTX);
2871 if (CMD_ARGC == 0)
2873 struct watchpoint *watchpoint = target->watchpoints;
2875 while (watchpoint)
2877 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
2878 ", len: 0x%8.8" PRIx32
2879 ", r/w/a: %i, value: 0x%8.8" PRIx32
2880 ", mask: 0x%8.8" PRIx32,
2881 watchpoint->address,
2882 watchpoint->length,
2883 (int)watchpoint->rw,
2884 watchpoint->value,
2885 watchpoint->mask);
2886 watchpoint = watchpoint->next;
2888 return ERROR_OK;
2891 enum watchpoint_rw type = WPT_ACCESS;
2892 uint32_t addr = 0;
2893 uint32_t length = 0;
2894 uint32_t data_value = 0x0;
2895 uint32_t data_mask = 0xffffffff;
2897 switch (CMD_ARGC)
2899 case 5:
2900 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
2901 // fall through
2902 case 4:
2903 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
2904 // fall through
2905 case 3:
2906 switch (CMD_ARGV[2][0])
2908 case 'r':
2909 type = WPT_READ;
2910 break;
2911 case 'w':
2912 type = WPT_WRITE;
2913 break;
2914 case 'a':
2915 type = WPT_ACCESS;
2916 break;
2917 default:
2918 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
2919 return ERROR_COMMAND_SYNTAX_ERROR;
2921 // fall through
2922 case 2:
2923 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2924 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2925 break;
2927 default:
2928 command_print(CMD_CTX, "usage: wp [address length "
2929 "[(r|w|a) [value [mask]]]]");
2930 return ERROR_COMMAND_SYNTAX_ERROR;
2933 int retval = watchpoint_add(target, addr, length, type,
2934 data_value, data_mask);
2935 if (ERROR_OK != retval)
2936 LOG_ERROR("Failure setting watchpoints");
2938 return retval;
2941 COMMAND_HANDLER(handle_rwp_command)
2943 if (CMD_ARGC != 1)
2944 return ERROR_COMMAND_SYNTAX_ERROR;
2946 uint32_t addr;
2947 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2949 struct target *target = get_current_target(CMD_CTX);
2950 watchpoint_remove(target, addr);
2952 return ERROR_OK;
2957 * Translate a virtual address to a physical address.
2959 * The low-level target implementation must have logged a detailed error
2960 * which is forwarded to telnet/GDB session.
2962 COMMAND_HANDLER(handle_virt2phys_command)
2964 if (CMD_ARGC != 1)
2965 return ERROR_COMMAND_SYNTAX_ERROR;
2967 uint32_t va;
2968 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
2969 uint32_t pa;
2971 struct target *target = get_current_target(CMD_CTX);
2972 int retval = target->type->virt2phys(target, va, &pa);
2973 if (retval == ERROR_OK)
2974 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
2976 return retval;
2979 static void writeData(FILE *f, const void *data, size_t len)
2981 size_t written = fwrite(data, 1, len, f);
2982 if (written != len)
2983 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
2986 static void writeLong(FILE *f, int l)
2988 int i;
2989 for (i = 0; i < 4; i++)
2991 char c = (l >> (i*8))&0xff;
2992 writeData(f, &c, 1);
2997 static void writeString(FILE *f, char *s)
2999 writeData(f, s, strlen(s));
3002 /* Dump a gmon.out histogram file. */
3003 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3005 uint32_t i;
3006 FILE *f = fopen(filename, "w");
3007 if (f == NULL)
3008 return;
3009 writeString(f, "gmon");
3010 writeLong(f, 0x00000001); /* Version */
3011 writeLong(f, 0); /* padding */
3012 writeLong(f, 0); /* padding */
3013 writeLong(f, 0); /* padding */
3015 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3016 writeData(f, &zero, 1);
3018 /* figure out bucket size */
3019 uint32_t min = samples[0];
3020 uint32_t max = samples[0];
3021 for (i = 0; i < sampleNum; i++)
3023 if (min > samples[i])
3025 min = samples[i];
3027 if (max < samples[i])
3029 max = samples[i];
3033 int addressSpace = (max-min + 1);
3035 static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
3036 uint32_t length = addressSpace;
3037 if (length > maxBuckets)
3039 length = maxBuckets;
3041 int *buckets = malloc(sizeof(int)*length);
3042 if (buckets == NULL)
3044 fclose(f);
3045 return;
3047 memset(buckets, 0, sizeof(int)*length);
3048 for (i = 0; i < sampleNum;i++)
3050 uint32_t address = samples[i];
3051 long long a = address-min;
3052 long long b = length-1;
3053 long long c = addressSpace-1;
3054 int index = (a*b)/c; /* danger!!!! int32 overflows */
3055 buckets[index]++;
3058 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3059 writeLong(f, min); /* low_pc */
3060 writeLong(f, max); /* high_pc */
3061 writeLong(f, length); /* # of samples */
3062 writeLong(f, 64000000); /* 64MHz */
3063 writeString(f, "seconds");
3064 for (i = 0; i < (15-strlen("seconds")); i++)
3065 writeData(f, &zero, 1);
3066 writeString(f, "s");
3068 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3070 char *data = malloc(2*length);
3071 if (data != NULL)
3073 for (i = 0; i < length;i++)
3075 int val;
3076 val = buckets[i];
3077 if (val > 65535)
3079 val = 65535;
3081 data[i*2]=val&0xff;
3082 data[i*2 + 1]=(val >> 8)&0xff;
3084 free(buckets);
3085 writeData(f, data, length * 2);
3086 free(data);
3087 } else
3089 free(buckets);
3092 fclose(f);
3095 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3096 * which will be used as a random sampling of PC */
3097 COMMAND_HANDLER(handle_profile_command)
3099 struct target *target = get_current_target(CMD_CTX);
3100 struct timeval timeout, now;
3102 gettimeofday(&timeout, NULL);
3103 if (CMD_ARGC != 2)
3105 return ERROR_COMMAND_SYNTAX_ERROR;
3107 unsigned offset;
3108 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3110 timeval_add_time(&timeout, offset, 0);
3113 * @todo: Some cores let us sample the PC without the
3114 * annoying halt/resume step; for example, ARMv7 PCSR.
3115 * Provide a way to use that more efficient mechanism.
3118 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3120 static const int maxSample = 10000;
3121 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3122 if (samples == NULL)
3123 return ERROR_OK;
3125 int numSamples = 0;
3126 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3127 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3129 for (;;)
3131 int retval;
3132 target_poll(target);
3133 if (target->state == TARGET_HALTED)
3135 uint32_t t=*((uint32_t *)reg->value);
3136 samples[numSamples++]=t;
3137 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3138 target_poll(target);
3139 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3140 } else if (target->state == TARGET_RUNNING)
3142 /* We want to quickly sample the PC. */
3143 if ((retval = target_halt(target)) != ERROR_OK)
3145 free(samples);
3146 return retval;
3148 } else
3150 command_print(CMD_CTX, "Target not halted or running");
3151 retval = ERROR_OK;
3152 break;
3154 if (retval != ERROR_OK)
3156 break;
3159 gettimeofday(&now, NULL);
3160 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3162 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3163 if ((retval = target_poll(target)) != ERROR_OK)
3165 free(samples);
3166 return retval;
3168 if (target->state == TARGET_HALTED)
3170 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3172 if ((retval = target_poll(target)) != ERROR_OK)
3174 free(samples);
3175 return retval;
3177 writeGmon(samples, numSamples, CMD_ARGV[1]);
3178 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3179 break;
3182 free(samples);
3184 return ERROR_OK;
3187 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3189 char *namebuf;
3190 Jim_Obj *nameObjPtr, *valObjPtr;
3191 int result;
3193 namebuf = alloc_printf("%s(%d)", varname, idx);
3194 if (!namebuf)
3195 return JIM_ERR;
3197 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3198 valObjPtr = Jim_NewIntObj(interp, val);
3199 if (!nameObjPtr || !valObjPtr)
3201 free(namebuf);
3202 return JIM_ERR;
3205 Jim_IncrRefCount(nameObjPtr);
3206 Jim_IncrRefCount(valObjPtr);
3207 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3208 Jim_DecrRefCount(interp, nameObjPtr);
3209 Jim_DecrRefCount(interp, valObjPtr);
3210 free(namebuf);
3211 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3212 return result;
3215 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3217 struct command_context *context;
3218 struct target *target;
3220 context = Jim_GetAssocData(interp, "context");
3221 if (context == NULL)
3223 LOG_ERROR("mem2array: no command context");
3224 return JIM_ERR;
3226 target = get_current_target(context);
3227 if (target == NULL)
3229 LOG_ERROR("mem2array: no current target");
3230 return JIM_ERR;
3233 return target_mem2array(interp, target, argc-1, argv + 1);
3236 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3238 long l;
3239 uint32_t width;
3240 int len;
3241 uint32_t addr;
3242 uint32_t count;
3243 uint32_t v;
3244 const char *varname;
3245 int n, e, retval;
3246 uint32_t i;
3248 /* argv[1] = name of array to receive the data
3249 * argv[2] = desired width
3250 * argv[3] = memory address
3251 * argv[4] = count of times to read
3253 if (argc != 4) {
3254 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3255 return JIM_ERR;
3257 varname = Jim_GetString(argv[0], &len);
3258 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3260 e = Jim_GetLong(interp, argv[1], &l);
3261 width = l;
3262 if (e != JIM_OK) {
3263 return e;
3266 e = Jim_GetLong(interp, argv[2], &l);
3267 addr = l;
3268 if (e != JIM_OK) {
3269 return e;
3271 e = Jim_GetLong(interp, argv[3], &l);
3272 len = l;
3273 if (e != JIM_OK) {
3274 return e;
3276 switch (width) {
3277 case 8:
3278 width = 1;
3279 break;
3280 case 16:
3281 width = 2;
3282 break;
3283 case 32:
3284 width = 4;
3285 break;
3286 default:
3287 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3288 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3289 return JIM_ERR;
3291 if (len == 0) {
3292 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3293 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3294 return JIM_ERR;
3296 if ((addr + (len * width)) < addr) {
3297 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3298 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3299 return JIM_ERR;
3301 /* absurd transfer size? */
3302 if (len > 65536) {
3303 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3304 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3305 return JIM_ERR;
3308 if ((width == 1) ||
3309 ((width == 2) && ((addr & 1) == 0)) ||
3310 ((width == 4) && ((addr & 3) == 0))) {
3311 /* all is well */
3312 } else {
3313 char buf[100];
3314 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3315 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3316 addr,
3317 width);
3318 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3319 return JIM_ERR;
3322 /* Transfer loop */
3324 /* index counter */
3325 n = 0;
3327 size_t buffersize = 4096;
3328 uint8_t *buffer = malloc(buffersize);
3329 if (buffer == NULL)
3330 return JIM_ERR;
3332 /* assume ok */
3333 e = JIM_OK;
3334 while (len) {
3335 /* Slurp... in buffer size chunks */
3337 count = len; /* in objects.. */
3338 if (count > (buffersize/width)) {
3339 count = (buffersize/width);
3342 retval = target_read_memory(target, addr, width, count, buffer);
3343 if (retval != ERROR_OK) {
3344 /* BOO !*/
3345 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3346 (unsigned int)addr,
3347 (int)width,
3348 (int)count);
3349 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3350 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3351 e = JIM_ERR;
3352 len = 0;
3353 } else {
3354 v = 0; /* shut up gcc */
3355 for (i = 0 ;i < count ;i++, n++) {
3356 switch (width) {
3357 case 4:
3358 v = target_buffer_get_u32(target, &buffer[i*width]);
3359 break;
3360 case 2:
3361 v = target_buffer_get_u16(target, &buffer[i*width]);
3362 break;
3363 case 1:
3364 v = buffer[i] & 0x0ff;
3365 break;
3367 new_int_array_element(interp, varname, n, v);
3369 len -= count;
3373 free(buffer);
3375 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3377 return JIM_OK;
3380 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3382 char *namebuf;
3383 Jim_Obj *nameObjPtr, *valObjPtr;
3384 int result;
3385 long l;
3387 namebuf = alloc_printf("%s(%d)", varname, idx);
3388 if (!namebuf)
3389 return JIM_ERR;
3391 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3392 if (!nameObjPtr)
3394 free(namebuf);
3395 return JIM_ERR;
3398 Jim_IncrRefCount(nameObjPtr);
3399 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3400 Jim_DecrRefCount(interp, nameObjPtr);
3401 free(namebuf);
3402 if (valObjPtr == NULL)
3403 return JIM_ERR;
3405 result = Jim_GetLong(interp, valObjPtr, &l);
3406 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3407 *val = l;
3408 return result;
3411 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3413 struct command_context *context;
3414 struct target *target;
3416 context = Jim_GetAssocData(interp, "context");
3417 if (context == NULL) {
3418 LOG_ERROR("array2mem: no command context");
3419 return JIM_ERR;
3421 target = get_current_target(context);
3422 if (target == NULL) {
3423 LOG_ERROR("array2mem: no current target");
3424 return JIM_ERR;
3427 return target_array2mem(interp,target, argc-1, argv + 1);
3430 static int target_array2mem(Jim_Interp *interp, struct target *target,
3431 int argc, Jim_Obj *const *argv)
3433 long l;
3434 uint32_t width;
3435 int len;
3436 uint32_t addr;
3437 uint32_t count;
3438 uint32_t v;
3439 const char *varname;
3440 int n, e, retval;
3441 uint32_t i;
3443 /* argv[1] = name of array to get the data
3444 * argv[2] = desired width
3445 * argv[3] = memory address
3446 * argv[4] = count to write
3448 if (argc != 4) {
3449 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3450 return JIM_ERR;
3452 varname = Jim_GetString(argv[0], &len);
3453 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3455 e = Jim_GetLong(interp, argv[1], &l);
3456 width = l;
3457 if (e != JIM_OK) {
3458 return e;
3461 e = Jim_GetLong(interp, argv[2], &l);
3462 addr = l;
3463 if (e != JIM_OK) {
3464 return e;
3466 e = Jim_GetLong(interp, argv[3], &l);
3467 len = l;
3468 if (e != JIM_OK) {
3469 return e;
3471 switch (width) {
3472 case 8:
3473 width = 1;
3474 break;
3475 case 16:
3476 width = 2;
3477 break;
3478 case 32:
3479 width = 4;
3480 break;
3481 default:
3482 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3483 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3484 return JIM_ERR;
3486 if (len == 0) {
3487 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3488 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3489 return JIM_ERR;
3491 if ((addr + (len * width)) < addr) {
3492 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3493 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3494 return JIM_ERR;
3496 /* absurd transfer size? */
3497 if (len > 65536) {
3498 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3499 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3500 return JIM_ERR;
3503 if ((width == 1) ||
3504 ((width == 2) && ((addr & 1) == 0)) ||
3505 ((width == 4) && ((addr & 3) == 0))) {
3506 /* all is well */
3507 } else {
3508 char buf[100];
3509 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3510 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3511 (unsigned int)addr,
3512 (int)width);
3513 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3514 return JIM_ERR;
3517 /* Transfer loop */
3519 /* index counter */
3520 n = 0;
3521 /* assume ok */
3522 e = JIM_OK;
3524 size_t buffersize = 4096;
3525 uint8_t *buffer = malloc(buffersize);
3526 if (buffer == NULL)
3527 return JIM_ERR;
3529 while (len) {
3530 /* Slurp... in buffer size chunks */
3532 count = len; /* in objects.. */
3533 if (count > (buffersize/width)) {
3534 count = (buffersize/width);
3537 v = 0; /* shut up gcc */
3538 for (i = 0 ;i < count ;i++, n++) {
3539 get_int_array_element(interp, varname, n, &v);
3540 switch (width) {
3541 case 4:
3542 target_buffer_set_u32(target, &buffer[i*width], v);
3543 break;
3544 case 2:
3545 target_buffer_set_u16(target, &buffer[i*width], v);
3546 break;
3547 case 1:
3548 buffer[i] = v & 0x0ff;
3549 break;
3552 len -= count;
3554 retval = target_write_memory(target, addr, width, count, buffer);
3555 if (retval != ERROR_OK) {
3556 /* BOO !*/
3557 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3558 (unsigned int)addr,
3559 (int)width,
3560 (int)count);
3561 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3562 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3563 e = JIM_ERR;
3564 len = 0;
3568 free(buffer);
3570 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3572 return JIM_OK;
3575 void target_all_handle_event(enum target_event e)
3577 struct target *target;
3579 LOG_DEBUG("**all*targets: event: %d, %s",
3580 (int)e,
3581 Jim_Nvp_value2name_simple(nvp_target_event, e)->name);
3583 target = all_targets;
3584 while (target) {
3585 target_handle_event(target, e);
3586 target = target->next;
3591 /* FIX? should we propagate errors here rather than printing them
3592 * and continuing?
3594 void target_handle_event(struct target *target, enum target_event e)
3596 struct target_event_action *teap;
3598 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3599 if (teap->event == e) {
3600 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3601 target->target_number,
3602 target_name(target),
3603 target_type_name(target),
3605 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3606 Jim_GetString(teap->body, NULL));
3607 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK)
3609 Jim_PrintErrorMessage(teap->interp);
3616 * Returns true only if the target has a handler for the specified event.
3618 bool target_has_event_action(struct target *target, enum target_event event)
3620 struct target_event_action *teap;
3622 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3623 if (teap->event == event)
3624 return true;
3626 return false;
3629 enum target_cfg_param {
3630 TCFG_TYPE,
3631 TCFG_EVENT,
3632 TCFG_WORK_AREA_VIRT,
3633 TCFG_WORK_AREA_PHYS,
3634 TCFG_WORK_AREA_SIZE,
3635 TCFG_WORK_AREA_BACKUP,
3636 TCFG_ENDIAN,
3637 TCFG_VARIANT,
3638 TCFG_CHAIN_POSITION,
3641 static Jim_Nvp nvp_config_opts[] = {
3642 { .name = "-type", .value = TCFG_TYPE },
3643 { .name = "-event", .value = TCFG_EVENT },
3644 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3645 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3646 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3647 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3648 { .name = "-endian" , .value = TCFG_ENDIAN },
3649 { .name = "-variant", .value = TCFG_VARIANT },
3650 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3652 { .name = NULL, .value = -1 }
3655 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3657 Jim_Nvp *n;
3658 Jim_Obj *o;
3659 jim_wide w;
3660 char *cp;
3661 int e;
3663 /* parse config or cget options ... */
3664 while (goi->argc > 0) {
3665 Jim_SetEmptyResult(goi->interp);
3666 /* Jim_GetOpt_Debug(goi); */
3668 if (target->type->target_jim_configure) {
3669 /* target defines a configure function */
3670 /* target gets first dibs on parameters */
3671 e = (*(target->type->target_jim_configure))(target, goi);
3672 if (e == JIM_OK) {
3673 /* more? */
3674 continue;
3676 if (e == JIM_ERR) {
3677 /* An error */
3678 return e;
3680 /* otherwise we 'continue' below */
3682 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3683 if (e != JIM_OK) {
3684 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3685 return e;
3687 switch (n->value) {
3688 case TCFG_TYPE:
3689 /* not setable */
3690 if (goi->isconfigure) {
3691 Jim_SetResult_sprintf(goi->interp,
3692 "not settable: %s", n->name);
3693 return JIM_ERR;
3694 } else {
3695 no_params:
3696 if (goi->argc != 0) {
3697 Jim_WrongNumArgs(goi->interp,
3698 goi->argc, goi->argv,
3699 "NO PARAMS");
3700 return JIM_ERR;
3703 Jim_SetResultString(goi->interp,
3704 target_type_name(target), -1);
3705 /* loop for more */
3706 break;
3707 case TCFG_EVENT:
3708 if (goi->argc == 0) {
3709 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3710 return JIM_ERR;
3713 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3714 if (e != JIM_OK) {
3715 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3716 return e;
3719 if (goi->isconfigure) {
3720 if (goi->argc != 1) {
3721 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3722 return JIM_ERR;
3724 } else {
3725 if (goi->argc != 0) {
3726 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3727 return JIM_ERR;
3732 struct target_event_action *teap;
3734 teap = target->event_action;
3735 /* replace existing? */
3736 while (teap) {
3737 if (teap->event == (enum target_event)n->value) {
3738 break;
3740 teap = teap->next;
3743 if (goi->isconfigure) {
3744 bool replace = true;
3745 if (teap == NULL) {
3746 /* create new */
3747 teap = calloc(1, sizeof(*teap));
3748 replace = false;
3750 teap->event = n->value;
3751 teap->interp = goi->interp;
3752 Jim_GetOpt_Obj(goi, &o);
3753 if (teap->body) {
3754 Jim_DecrRefCount(teap->interp, teap->body);
3756 teap->body = Jim_DuplicateObj(goi->interp, o);
3758 * FIXME:
3759 * Tcl/TK - "tk events" have a nice feature.
3760 * See the "BIND" command.
3761 * We should support that here.
3762 * You can specify %X and %Y in the event code.
3763 * The idea is: %T - target name.
3764 * The idea is: %N - target number
3765 * The idea is: %E - event name.
3767 Jim_IncrRefCount(teap->body);
3769 if (!replace)
3771 /* add to head of event list */
3772 teap->next = target->event_action;
3773 target->event_action = teap;
3775 Jim_SetEmptyResult(goi->interp);
3776 } else {
3777 /* get */
3778 if (teap == NULL) {
3779 Jim_SetEmptyResult(goi->interp);
3780 } else {
3781 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3785 /* loop for more */
3786 break;
3788 case TCFG_WORK_AREA_VIRT:
3789 if (goi->isconfigure) {
3790 target_free_all_working_areas(target);
3791 e = Jim_GetOpt_Wide(goi, &w);
3792 if (e != JIM_OK) {
3793 return e;
3795 target->working_area_virt = w;
3796 target->working_area_virt_spec = true;
3797 } else {
3798 if (goi->argc != 0) {
3799 goto no_params;
3802 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3803 /* loop for more */
3804 break;
3806 case TCFG_WORK_AREA_PHYS:
3807 if (goi->isconfigure) {
3808 target_free_all_working_areas(target);
3809 e = Jim_GetOpt_Wide(goi, &w);
3810 if (e != JIM_OK) {
3811 return e;
3813 target->working_area_phys = w;
3814 target->working_area_phys_spec = true;
3815 } else {
3816 if (goi->argc != 0) {
3817 goto no_params;
3820 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3821 /* loop for more */
3822 break;
3824 case TCFG_WORK_AREA_SIZE:
3825 if (goi->isconfigure) {
3826 target_free_all_working_areas(target);
3827 e = Jim_GetOpt_Wide(goi, &w);
3828 if (e != JIM_OK) {
3829 return e;
3831 target->working_area_size = w;
3832 } else {
3833 if (goi->argc != 0) {
3834 goto no_params;
3837 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3838 /* loop for more */
3839 break;
3841 case TCFG_WORK_AREA_BACKUP:
3842 if (goi->isconfigure) {
3843 target_free_all_working_areas(target);
3844 e = Jim_GetOpt_Wide(goi, &w);
3845 if (e != JIM_OK) {
3846 return e;
3848 /* make this exactly 1 or 0 */
3849 target->backup_working_area = (!!w);
3850 } else {
3851 if (goi->argc != 0) {
3852 goto no_params;
3855 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3856 /* loop for more e*/
3857 break;
3859 case TCFG_ENDIAN:
3860 if (goi->isconfigure) {
3861 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3862 if (e != JIM_OK) {
3863 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3864 return e;
3866 target->endianness = n->value;
3867 } else {
3868 if (goi->argc != 0) {
3869 goto no_params;
3872 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3873 if (n->name == NULL) {
3874 target->endianness = TARGET_LITTLE_ENDIAN;
3875 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3877 Jim_SetResultString(goi->interp, n->name, -1);
3878 /* loop for more */
3879 break;
3881 case TCFG_VARIANT:
3882 if (goi->isconfigure) {
3883 if (goi->argc < 1) {
3884 Jim_SetResult_sprintf(goi->interp,
3885 "%s ?STRING?",
3886 n->name);
3887 return JIM_ERR;
3889 if (target->variant) {
3890 free((void *)(target->variant));
3892 e = Jim_GetOpt_String(goi, &cp, NULL);
3893 target->variant = strdup(cp);
3894 } else {
3895 if (goi->argc != 0) {
3896 goto no_params;
3899 Jim_SetResultString(goi->interp, target->variant,-1);
3900 /* loop for more */
3901 break;
3902 case TCFG_CHAIN_POSITION:
3903 if (goi->isconfigure) {
3904 Jim_Obj *o;
3905 struct jtag_tap *tap;
3906 target_free_all_working_areas(target);
3907 e = Jim_GetOpt_Obj(goi, &o);
3908 if (e != JIM_OK) {
3909 return e;
3911 tap = jtag_tap_by_jim_obj(goi->interp, o);
3912 if (tap == NULL) {
3913 return JIM_ERR;
3915 /* make this exactly 1 or 0 */
3916 target->tap = tap;
3917 } else {
3918 if (goi->argc != 0) {
3919 goto no_params;
3922 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
3923 /* loop for more e*/
3924 break;
3926 } /* while (goi->argc) */
3929 /* done - we return */
3930 return JIM_OK;
3933 static int
3934 jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3936 Jim_GetOptInfo goi;
3938 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3939 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
3940 int need_args = 1 + goi.isconfigure;
3941 if (goi.argc < need_args)
3943 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
3944 goi.isconfigure
3945 ? "missing: -option VALUE ..."
3946 : "missing: -option ...");
3947 return JIM_ERR;
3949 struct target *target = Jim_CmdPrivData(goi.interp);
3950 return target_configure(&goi, target);
3953 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3955 const char *cmd_name = Jim_GetString(argv[0], NULL);
3957 Jim_GetOptInfo goi;
3958 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3960 /* danger! goi.argc will be modified below! */
3961 argc = goi.argc;
3963 if (argc != 2 && argc != 3)
3965 Jim_SetResult_sprintf(goi.interp,
3966 "usage: %s <address> <data> [<count>]", cmd_name);
3967 return JIM_ERR;
3971 jim_wide a;
3972 int e = Jim_GetOpt_Wide(&goi, &a);
3973 if (e != JIM_OK)
3974 return e;
3976 jim_wide b;
3977 e = Jim_GetOpt_Wide(&goi, &b);
3978 if (e != JIM_OK)
3979 return e;
3981 jim_wide c = 1;
3982 if (argc == 3)
3984 e = Jim_GetOpt_Wide(&goi, &c);
3985 if (e != JIM_OK)
3986 return e;
3989 struct target *target = Jim_CmdPrivData(goi.interp);
3990 unsigned data_size;
3991 if (strcasecmp(cmd_name, "mww") == 0) {
3992 data_size = 4;
3994 else if (strcasecmp(cmd_name, "mwh") == 0) {
3995 data_size = 2;
3997 else if (strcasecmp(cmd_name, "mwb") == 0) {
3998 data_size = 1;
3999 } else {
4000 LOG_ERROR("command '%s' unknown: ", cmd_name);
4001 return JIM_ERR;
4004 return (target_fill_mem(target, a, target_write_memory_fast, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4007 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4009 const char *cmd_name = Jim_GetString(argv[0], NULL);
4011 Jim_GetOptInfo goi;
4012 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4014 /* danger! goi.argc will be modified below! */
4015 argc = goi.argc;
4017 if ((argc != 1) && (argc != 2))
4019 Jim_SetResult_sprintf(goi.interp,
4020 "usage: %s <address> [<count>]", cmd_name);
4021 return JIM_ERR;
4024 jim_wide a;
4025 int e = Jim_GetOpt_Wide(&goi, &a);
4026 if (e != JIM_OK) {
4027 return JIM_ERR;
4029 jim_wide c;
4030 if (argc == 2) {
4031 e = Jim_GetOpt_Wide(&goi, &c);
4032 if (e != JIM_OK) {
4033 return JIM_ERR;
4035 } else {
4036 c = 1;
4038 jim_wide b = 1; /* shut up gcc */
4039 if (strcasecmp(cmd_name, "mdw") == 0)
4040 b = 4;
4041 else if (strcasecmp(cmd_name, "mdh") == 0)
4042 b = 2;
4043 else if (strcasecmp(cmd_name, "mdb") == 0)
4044 b = 1;
4045 else {
4046 LOG_ERROR("command '%s' unknown: ", cmd_name);
4047 return JIM_ERR;
4050 /* convert count to "bytes" */
4051 c = c * b;
4053 struct target *target = Jim_CmdPrivData(goi.interp);
4054 uint8_t target_buf[32];
4055 jim_wide x, y, z;
4056 while (c > 0) {
4057 y = c;
4058 if (y > 16) {
4059 y = 16;
4061 e = target_read_memory(target, a, b, y / b, target_buf);
4062 if (e != ERROR_OK) {
4063 Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
4064 return JIM_ERR;
4067 Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
4068 switch (b) {
4069 case 4:
4070 for (x = 0; x < 16 && x < y; x += 4)
4072 z = target_buffer_get_u32(target, &(target_buf[ x ]));
4073 Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
4075 for (; (x < 16) ; x += 4) {
4076 Jim_fprintf(interp, interp->cookie_stdout, " ");
4078 break;
4079 case 2:
4080 for (x = 0; x < 16 && x < y; x += 2)
4082 z = target_buffer_get_u16(target, &(target_buf[ x ]));
4083 Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
4085 for (; (x < 16) ; x += 2) {
4086 Jim_fprintf(interp, interp->cookie_stdout, " ");
4088 break;
4089 case 1:
4090 default:
4091 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4092 z = target_buffer_get_u8(target, &(target_buf[ x ]));
4093 Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
4095 for (; (x < 16) ; x += 1) {
4096 Jim_fprintf(interp, interp->cookie_stdout, " ");
4098 break;
4100 /* ascii-ify the bytes */
4101 for (x = 0 ; x < y ; x++) {
4102 if ((target_buf[x] >= 0x20) &&
4103 (target_buf[x] <= 0x7e)) {
4104 /* good */
4105 } else {
4106 /* smack it */
4107 target_buf[x] = '.';
4110 /* space pad */
4111 while (x < 16) {
4112 target_buf[x] = ' ';
4113 x++;
4115 /* terminate */
4116 target_buf[16] = 0;
4117 /* print - with a newline */
4118 Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
4119 /* NEXT... */
4120 c -= 16;
4121 a += 16;
4123 return JIM_OK;
4126 static int jim_target_mem2array(Jim_Interp *interp,
4127 int argc, Jim_Obj *const *argv)
4129 struct target *target = Jim_CmdPrivData(interp);
4130 return target_mem2array(interp, target, argc - 1, argv + 1);
4133 static int jim_target_array2mem(Jim_Interp *interp,
4134 int argc, Jim_Obj *const *argv)
4136 struct target *target = Jim_CmdPrivData(interp);
4137 return target_array2mem(interp, target, argc - 1, argv + 1);
4140 static int jim_target_tap_disabled(Jim_Interp *interp)
4142 Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4143 return JIM_ERR;
4146 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4148 if (argc != 1)
4150 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4151 return JIM_ERR;
4153 struct target *target = Jim_CmdPrivData(interp);
4154 if (!target->tap->enabled)
4155 return jim_target_tap_disabled(interp);
4157 int e = target->type->examine(target);
4158 if (e != ERROR_OK)
4160 Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
4161 return JIM_ERR;
4163 return JIM_OK;
4166 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4168 if (argc != 1)
4170 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4171 return JIM_ERR;
4173 struct target *target = Jim_CmdPrivData(interp);
4175 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4176 return JIM_ERR;
4178 return JIM_OK;
4181 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4183 if (argc != 1)
4185 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4186 return JIM_ERR;
4188 struct target *target = Jim_CmdPrivData(interp);
4189 if (!target->tap->enabled)
4190 return jim_target_tap_disabled(interp);
4192 int e;
4193 if (!(target_was_examined(target))) {
4194 e = ERROR_TARGET_NOT_EXAMINED;
4195 } else {
4196 e = target->type->poll(target);
4198 if (e != ERROR_OK)
4200 Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4201 return JIM_ERR;
4203 return JIM_OK;
4206 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4208 Jim_GetOptInfo goi;
4209 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4211 if (goi.argc != 2)
4213 Jim_WrongNumArgs(interp, 0, argv,
4214 "([tT]|[fF]|assert|deassert) BOOL");
4215 return JIM_ERR;
4218 Jim_Nvp *n;
4219 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4220 if (e != JIM_OK)
4222 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4223 return e;
4225 /* the halt or not param */
4226 jim_wide a;
4227 e = Jim_GetOpt_Wide(&goi, &a);
4228 if (e != JIM_OK)
4229 return e;
4231 struct target *target = Jim_CmdPrivData(goi.interp);
4232 if (!target->tap->enabled)
4233 return jim_target_tap_disabled(interp);
4234 if (!(target_was_examined(target)))
4236 LOG_ERROR("Target not examined yet");
4237 return ERROR_TARGET_NOT_EXAMINED;
4239 if (!target->type->assert_reset || !target->type->deassert_reset)
4241 Jim_SetResult_sprintf(interp,
4242 "No target-specific reset for %s",
4243 target_name(target));
4244 return JIM_ERR;
4246 /* determine if we should halt or not. */
4247 target->reset_halt = !!a;
4248 /* When this happens - all workareas are invalid. */
4249 target_free_all_working_areas_restore(target, 0);
4251 /* do the assert */
4252 if (n->value == NVP_ASSERT) {
4253 e = target->type->assert_reset(target);
4254 } else {
4255 e = target->type->deassert_reset(target);
4257 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4260 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4262 if (argc != 1) {
4263 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4264 return JIM_ERR;
4266 struct target *target = Jim_CmdPrivData(interp);
4267 if (!target->tap->enabled)
4268 return jim_target_tap_disabled(interp);
4269 int e = target->type->halt(target);
4270 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4273 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4275 Jim_GetOptInfo goi;
4276 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4278 /* params: <name> statename timeoutmsecs */
4279 if (goi.argc != 2)
4281 const char *cmd_name = Jim_GetString(argv[0], NULL);
4282 Jim_SetResult_sprintf(goi.interp,
4283 "%s <state_name> <timeout_in_msec>", cmd_name);
4284 return JIM_ERR;
4287 Jim_Nvp *n;
4288 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4289 if (e != JIM_OK) {
4290 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4291 return e;
4293 jim_wide a;
4294 e = Jim_GetOpt_Wide(&goi, &a);
4295 if (e != JIM_OK) {
4296 return e;
4298 struct target *target = Jim_CmdPrivData(interp);
4299 if (!target->tap->enabled)
4300 return jim_target_tap_disabled(interp);
4302 e = target_wait_state(target, n->value, a);
4303 if (e != ERROR_OK)
4305 Jim_SetResult_sprintf(goi.interp,
4306 "target: %s wait %s fails (%d) %s",
4307 target_name(target), n->name,
4308 e, target_strerror_safe(e));
4309 return JIM_ERR;
4311 return JIM_OK;
4313 /* List for human, Events defined for this target.
4314 * scripts/programs should use 'name cget -event NAME'
4316 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4318 struct command_context *cmd_ctx = Jim_GetAssocData(interp, "context");
4319 struct target *target = Jim_CmdPrivData(interp);
4320 struct target_event_action *teap = target->event_action;
4321 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4322 target->target_number,
4323 target_name(target));
4324 command_print(cmd_ctx, "%-25s | Body", "Event");
4325 command_print(cmd_ctx, "------------------------- | "
4326 "----------------------------------------");
4327 while (teap)
4329 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4330 command_print(cmd_ctx, "%-25s | %s",
4331 opt->name, Jim_GetString(teap->body, NULL));
4332 teap = teap->next;
4334 command_print(cmd_ctx, "***END***");
4335 return JIM_OK;
4337 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4339 if (argc != 1)
4341 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4342 return JIM_ERR;
4344 struct target *target = Jim_CmdPrivData(interp);
4345 Jim_SetResultString(interp, target_state_name(target), -1);
4346 return JIM_OK;
4348 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4350 Jim_GetOptInfo goi;
4351 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4352 if (goi.argc != 1)
4354 const char *cmd_name = Jim_GetString(argv[0], NULL);
4355 Jim_SetResult_sprintf(goi.interp, "%s <eventname>", cmd_name);
4356 return JIM_ERR;
4358 Jim_Nvp *n;
4359 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4360 if (e != JIM_OK)
4362 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4363 return e;
4365 struct target *target = Jim_CmdPrivData(interp);
4366 target_handle_event(target, n->value);
4367 return JIM_OK;
4370 static const struct command_registration target_instance_command_handlers[] = {
4372 .name = "configure",
4373 .mode = COMMAND_CONFIG,
4374 .jim_handler = jim_target_configure,
4375 .help = "configure a new target for use",
4376 .usage = "[target_attribute ...]",
4379 .name = "cget",
4380 .mode = COMMAND_ANY,
4381 .jim_handler = jim_target_configure,
4382 .help = "returns the specified target attribute",
4383 .usage = "target_attribute",
4386 .name = "mww",
4387 .mode = COMMAND_EXEC,
4388 .jim_handler = jim_target_mw,
4389 .help = "Write 32-bit word(s) to target memory",
4390 .usage = "address data [count]",
4393 .name = "mwh",
4394 .mode = COMMAND_EXEC,
4395 .jim_handler = jim_target_mw,
4396 .help = "Write 16-bit half-word(s) to target memory",
4397 .usage = "address data [count]",
4400 .name = "mwb",
4401 .mode = COMMAND_EXEC,
4402 .jim_handler = jim_target_mw,
4403 .help = "Write byte(s) to target memory",
4404 .usage = "address data [count]",
4407 .name = "mdw",
4408 .mode = COMMAND_EXEC,
4409 .jim_handler = jim_target_md,
4410 .help = "Display target memory as 32-bit words",
4411 .usage = "address [count]",
4414 .name = "mdh",
4415 .mode = COMMAND_EXEC,
4416 .jim_handler = jim_target_md,
4417 .help = "Display target memory as 16-bit half-words",
4418 .usage = "address [count]",
4421 .name = "mdb",
4422 .mode = COMMAND_EXEC,
4423 .jim_handler = jim_target_md,
4424 .help = "Display target memory as 8-bit bytes",
4425 .usage = "address [count]",
4428 .name = "array2mem",
4429 .mode = COMMAND_EXEC,
4430 .jim_handler = jim_target_array2mem,
4431 .help = "Writes Tcl array of 8/16/32 bit numbers "
4432 "to target memory",
4433 .usage = "arrayname bitwidth address count",
4436 .name = "mem2array",
4437 .mode = COMMAND_EXEC,
4438 .jim_handler = jim_target_mem2array,
4439 .help = "Loads Tcl array of 8/16/32 bit numbers "
4440 "from target memory",
4441 .usage = "arrayname bitwidth address count",
4444 .name = "eventlist",
4445 .mode = COMMAND_EXEC,
4446 .jim_handler = jim_target_event_list,
4447 .help = "displays a table of events defined for this target",
4450 .name = "curstate",
4451 .mode = COMMAND_EXEC,
4452 .jim_handler = jim_target_current_state,
4453 .help = "displays the current state of this target",
4456 .name = "arp_examine",
4457 .mode = COMMAND_EXEC,
4458 .jim_handler = jim_target_examine,
4459 .help = "used internally for reset processing",
4462 .name = "arp_halt_gdb",
4463 .mode = COMMAND_EXEC,
4464 .jim_handler = jim_target_halt_gdb,
4465 .help = "used internally for reset processing to halt GDB",
4468 .name = "arp_poll",
4469 .mode = COMMAND_EXEC,
4470 .jim_handler = jim_target_poll,
4471 .help = "used internally for reset processing",
4474 .name = "arp_reset",
4475 .mode = COMMAND_EXEC,
4476 .jim_handler = jim_target_reset,
4477 .help = "used internally for reset processing",
4480 .name = "arp_halt",
4481 .mode = COMMAND_EXEC,
4482 .jim_handler = jim_target_halt,
4483 .help = "used internally for reset processing",
4486 .name = "arp_waitstate",
4487 .mode = COMMAND_EXEC,
4488 .jim_handler = jim_target_wait_state,
4489 .help = "used internally for reset processing",
4492 .name = "invoke-event",
4493 .mode = COMMAND_EXEC,
4494 .jim_handler = jim_target_invoke_event,
4495 .help = "invoke handler for specified event",
4496 .usage = "event_name",
4498 COMMAND_REGISTRATION_DONE
4501 static int target_create(Jim_GetOptInfo *goi)
4503 Jim_Obj *new_cmd;
4504 Jim_Cmd *cmd;
4505 const char *cp;
4506 char *cp2;
4507 int e;
4508 int x;
4509 struct target *target;
4510 struct command_context *cmd_ctx;
4512 cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4513 if (goi->argc < 3) {
4514 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4515 return JIM_ERR;
4518 /* COMMAND */
4519 Jim_GetOpt_Obj(goi, &new_cmd);
4520 /* does this command exist? */
4521 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4522 if (cmd) {
4523 cp = Jim_GetString(new_cmd, NULL);
4524 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4525 return JIM_ERR;
4528 /* TYPE */
4529 e = Jim_GetOpt_String(goi, &cp2, NULL);
4530 cp = cp2;
4531 /* now does target type exist */
4532 for (x = 0 ; target_types[x] ; x++) {
4533 if (0 == strcmp(cp, target_types[x]->name)) {
4534 /* found */
4535 break;
4538 if (target_types[x] == NULL) {
4539 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4540 for (x = 0 ; target_types[x] ; x++) {
4541 if (target_types[x + 1]) {
4542 Jim_AppendStrings(goi->interp,
4543 Jim_GetResult(goi->interp),
4544 target_types[x]->name,
4545 ", ", NULL);
4546 } else {
4547 Jim_AppendStrings(goi->interp,
4548 Jim_GetResult(goi->interp),
4549 " or ",
4550 target_types[x]->name,NULL);
4553 return JIM_ERR;
4556 /* Create it */
4557 target = calloc(1,sizeof(struct target));
4558 /* set target number */
4559 target->target_number = new_target_number();
4561 /* allocate memory for each unique target type */
4562 target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4564 memcpy(target->type, target_types[x], sizeof(struct target_type));
4566 /* will be set by "-endian" */
4567 target->endianness = TARGET_ENDIAN_UNKNOWN;
4569 target->working_area = 0x0;
4570 target->working_area_size = 0x0;
4571 target->working_areas = NULL;
4572 target->backup_working_area = 0;
4574 target->state = TARGET_UNKNOWN;
4575 target->debug_reason = DBG_REASON_UNDEFINED;
4576 target->reg_cache = NULL;
4577 target->breakpoints = NULL;
4578 target->watchpoints = NULL;
4579 target->next = NULL;
4580 target->arch_info = NULL;
4582 target->display = 1;
4584 target->halt_issued = false;
4586 /* initialize trace information */
4587 target->trace_info = malloc(sizeof(struct trace));
4588 target->trace_info->num_trace_points = 0;
4589 target->trace_info->trace_points_size = 0;
4590 target->trace_info->trace_points = NULL;
4591 target->trace_info->trace_history_size = 0;
4592 target->trace_info->trace_history = NULL;
4593 target->trace_info->trace_history_pos = 0;
4594 target->trace_info->trace_history_overflowed = 0;
4596 target->dbgmsg = NULL;
4597 target->dbg_msg_enabled = 0;
4599 target->endianness = TARGET_ENDIAN_UNKNOWN;
4601 /* Do the rest as "configure" options */
4602 goi->isconfigure = 1;
4603 e = target_configure(goi, target);
4605 if (target->tap == NULL)
4607 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4608 e = JIM_ERR;
4611 if (e != JIM_OK) {
4612 free(target->type);
4613 free(target);
4614 return e;
4617 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4618 /* default endian to little if not specified */
4619 target->endianness = TARGET_LITTLE_ENDIAN;
4622 /* incase variant is not set */
4623 if (!target->variant)
4624 target->variant = strdup("");
4626 cp = Jim_GetString(new_cmd, NULL);
4627 target->cmd_name = strdup(cp);
4629 /* create the target specific commands */
4630 if (target->type->commands) {
4631 e = register_commands(cmd_ctx, NULL, target->type->commands);
4632 if (ERROR_OK != e)
4633 LOG_ERROR("unable to register '%s' commands", cp);
4635 if (target->type->target_create) {
4636 (*(target->type->target_create))(target, goi->interp);
4639 /* append to end of list */
4641 struct target **tpp;
4642 tpp = &(all_targets);
4643 while (*tpp) {
4644 tpp = &((*tpp)->next);
4646 *tpp = target;
4649 /* now - create the new target name command */
4650 const const struct command_registration target_subcommands[] = {
4652 .chain = target_instance_command_handlers,
4655 .chain = target->type->commands,
4657 COMMAND_REGISTRATION_DONE
4659 const const struct command_registration target_commands[] = {
4661 .name = cp,
4662 .mode = COMMAND_ANY,
4663 .help = "target command group",
4664 .chain = target_subcommands,
4666 COMMAND_REGISTRATION_DONE
4668 e = register_commands(cmd_ctx, NULL, target_commands);
4669 if (ERROR_OK != e)
4670 return JIM_ERR;
4672 struct command *c = command_find_in_context(cmd_ctx, cp);
4673 assert(c);
4674 command_set_handler_data(c, target);
4676 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
4679 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4681 if (argc != 1)
4683 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4684 return JIM_ERR;
4686 struct command_context *cmd_ctx = Jim_GetAssocData(interp, "context");
4687 Jim_SetResultString(interp, get_current_target(cmd_ctx)->cmd_name, -1);
4688 return JIM_OK;
4691 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4693 if (argc != 1)
4695 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4696 return JIM_ERR;
4698 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4699 for (unsigned x = 0; NULL != target_types[x]; x++)
4701 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4702 Jim_NewStringObj(interp, target_types[x]->name, -1));
4704 return JIM_OK;
4707 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4709 if (argc != 1)
4711 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4712 return JIM_ERR;
4714 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4715 struct target *target = all_targets;
4716 while (target)
4718 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4719 Jim_NewStringObj(interp, target_name(target), -1));
4720 target = target->next;
4722 return JIM_OK;
4725 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4727 Jim_GetOptInfo goi;
4728 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4729 if (goi.argc < 3)
4731 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4732 "<name> <target_type> [<target_options> ...]");
4733 return JIM_ERR;
4735 return target_create(&goi);
4738 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4740 Jim_GetOptInfo goi;
4741 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4743 /* It's OK to remove this mechanism sometime after August 2010 or so */
4744 LOG_WARNING("don't use numbers as target identifiers; use names");
4745 if (goi.argc != 1)
4747 Jim_SetResult_sprintf(goi.interp, "usage: target number <number>");
4748 return JIM_ERR;
4750 jim_wide w;
4751 int e = Jim_GetOpt_Wide(&goi, &w);
4752 if (e != JIM_OK)
4753 return JIM_ERR;
4755 struct target *target;
4756 for (target = all_targets; NULL != target; target = target->next)
4758 if (target->target_number != w)
4759 continue;
4761 Jim_SetResultString(goi.interp, target_name(target), -1);
4762 return JIM_OK;
4764 Jim_SetResult_sprintf(goi.interp,
4765 "Target: number %d does not exist", (int)(w));
4766 return JIM_ERR;
4769 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4771 if (argc != 1)
4773 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
4774 return JIM_ERR;
4776 unsigned count = 0;
4777 struct target *target = all_targets;
4778 while (NULL != target)
4780 target = target->next;
4781 count++;
4783 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
4784 return JIM_OK;
4787 static const struct command_registration target_subcommand_handlers[] = {
4789 .name = "init",
4790 .mode = COMMAND_CONFIG,
4791 .handler = handle_target_init_command,
4792 .help = "initialize targets",
4795 .name = "create",
4796 /* REVISIT this should be COMMAND_CONFIG ... */
4797 .mode = COMMAND_ANY,
4798 .jim_handler = jim_target_create,
4799 .usage = "name type '-chain-position' name [options ...]",
4800 .help = "Creates and selects a new target",
4803 .name = "current",
4804 .mode = COMMAND_ANY,
4805 .jim_handler = jim_target_current,
4806 .help = "Returns the currently selected target",
4809 .name = "types",
4810 .mode = COMMAND_ANY,
4811 .jim_handler = jim_target_types,
4812 .help = "Returns the available target types as "
4813 "a list of strings",
4816 .name = "names",
4817 .mode = COMMAND_ANY,
4818 .jim_handler = jim_target_names,
4819 .help = "Returns the names of all targets as a list of strings",
4822 .name = "number",
4823 .mode = COMMAND_ANY,
4824 .jim_handler = jim_target_number,
4825 .usage = "number",
4826 .help = "Returns the name of the numbered target "
4827 "(DEPRECATED)",
4830 .name = "count",
4831 .mode = COMMAND_ANY,
4832 .jim_handler = jim_target_count,
4833 .help = "Returns the number of targets as an integer "
4834 "(DEPRECATED)",
4836 COMMAND_REGISTRATION_DONE
4839 struct FastLoad
4841 uint32_t address;
4842 uint8_t *data;
4843 int length;
4847 static int fastload_num;
4848 static struct FastLoad *fastload;
4850 static void free_fastload(void)
4852 if (fastload != NULL)
4854 int i;
4855 for (i = 0; i < fastload_num; i++)
4857 if (fastload[i].data)
4858 free(fastload[i].data);
4860 free(fastload);
4861 fastload = NULL;
4868 COMMAND_HANDLER(handle_fast_load_image_command)
4870 uint8_t *buffer;
4871 size_t buf_cnt;
4872 uint32_t image_size;
4873 uint32_t min_address = 0;
4874 uint32_t max_address = 0xffffffff;
4875 int i;
4877 struct image image;
4879 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
4880 &image, &min_address, &max_address);
4881 if (ERROR_OK != retval)
4882 return retval;
4884 struct duration bench;
4885 duration_start(&bench);
4887 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
4889 return ERROR_OK;
4892 image_size = 0x0;
4893 retval = ERROR_OK;
4894 fastload_num = image.num_sections;
4895 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4896 if (fastload == NULL)
4898 image_close(&image);
4899 return ERROR_FAIL;
4901 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4902 for (i = 0; i < image.num_sections; i++)
4904 buffer = malloc(image.sections[i].size);
4905 if (buffer == NULL)
4907 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
4908 (int)(image.sections[i].size));
4909 break;
4912 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4914 free(buffer);
4915 break;
4918 uint32_t offset = 0;
4919 uint32_t length = buf_cnt;
4922 /* DANGER!!! beware of unsigned comparision here!!! */
4924 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4925 (image.sections[i].base_address < max_address))
4927 if (image.sections[i].base_address < min_address)
4929 /* clip addresses below */
4930 offset += min_address-image.sections[i].base_address;
4931 length -= offset;
4934 if (image.sections[i].base_address + buf_cnt > max_address)
4936 length -= (image.sections[i].base_address + buf_cnt)-max_address;
4939 fastload[i].address = image.sections[i].base_address + offset;
4940 fastload[i].data = malloc(length);
4941 if (fastload[i].data == NULL)
4943 free(buffer);
4944 break;
4946 memcpy(fastload[i].data, buffer + offset, length);
4947 fastload[i].length = length;
4949 image_size += length;
4950 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
4951 (unsigned int)length,
4952 ((unsigned int)(image.sections[i].base_address + offset)));
4955 free(buffer);
4958 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
4960 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
4961 "in %fs (%0.3f kb/s)", image_size,
4962 duration_elapsed(&bench), duration_kbps(&bench, image_size));
4964 command_print(CMD_CTX,
4965 "WARNING: image has not been loaded to target!"
4966 "You can issue a 'fast_load' to finish loading.");
4969 image_close(&image);
4971 if (retval != ERROR_OK)
4973 free_fastload();
4976 return retval;
4979 COMMAND_HANDLER(handle_fast_load_command)
4981 if (CMD_ARGC > 0)
4982 return ERROR_COMMAND_SYNTAX_ERROR;
4983 if (fastload == NULL)
4985 LOG_ERROR("No image in memory");
4986 return ERROR_FAIL;
4988 int i;
4989 int ms = timeval_ms();
4990 int size = 0;
4991 int retval = ERROR_OK;
4992 for (i = 0; i < fastload_num;i++)
4994 struct target *target = get_current_target(CMD_CTX);
4995 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
4996 (unsigned int)(fastload[i].address),
4997 (unsigned int)(fastload[i].length));
4998 if (retval == ERROR_OK)
5000 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5002 size += fastload[i].length;
5004 int after = timeval_ms();
5005 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5006 return retval;
5009 static const struct command_registration target_command_handlers[] = {
5011 .name = "targets",
5012 .handler = handle_targets_command,
5013 .mode = COMMAND_ANY,
5014 .help = "change current default target (one parameter) "
5015 "or prints table of all targets (no parameters)",
5016 .usage = "[target]",
5019 .name = "target",
5020 .mode = COMMAND_CONFIG,
5021 .help = "configure target",
5023 .chain = target_subcommand_handlers,
5025 COMMAND_REGISTRATION_DONE
5028 int target_register_commands(struct command_context *cmd_ctx)
5030 return register_commands(cmd_ctx, NULL, target_command_handlers);
5033 static bool target_reset_nag = true;
5035 bool get_target_reset_nag(void)
5037 return target_reset_nag;
5040 COMMAND_HANDLER(handle_target_reset_nag)
5042 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5043 &target_reset_nag, "Nag after each reset about options to improve "
5044 "performance");
5047 static const struct command_registration target_exec_command_handlers[] = {
5049 .name = "fast_load_image",
5050 .handler = handle_fast_load_image_command,
5051 .mode = COMMAND_ANY,
5052 .help = "Load image into server memory for later use by "
5053 "fast_load; primarily for profiling",
5054 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5055 "[min_address [max_length]]",
5058 .name = "fast_load",
5059 .handler = handle_fast_load_command,
5060 .mode = COMMAND_EXEC,
5061 .help = "loads active fast load image to current target "
5062 "- mainly for profiling purposes",
5065 .name = "profile",
5066 .handler = handle_profile_command,
5067 .mode = COMMAND_EXEC,
5068 .help = "profiling samples the CPU PC",
5070 /** @todo don't register virt2phys() unless target supports it */
5072 .name = "virt2phys",
5073 .handler = handle_virt2phys_command,
5074 .mode = COMMAND_ANY,
5075 .help = "translate a virtual address into a physical address",
5076 .usage = "virtual_address",
5079 .name = "reg",
5080 .handler = handle_reg_command,
5081 .mode = COMMAND_EXEC,
5082 .help = "display or set a register; with no arguments, "
5083 "displays all registers and their values",
5084 .usage = "[(register_name|register_number) [value]]",
5087 .name = "poll",
5088 .handler = handle_poll_command,
5089 .mode = COMMAND_EXEC,
5090 .help = "poll target state; or reconfigure background polling",
5091 .usage = "['on'|'off']",
5094 .name = "wait_halt",
5095 .handler = handle_wait_halt_command,
5096 .mode = COMMAND_EXEC,
5097 .help = "wait up to the specified number of milliseconds "
5098 "(default 5) for a previously requested halt",
5099 .usage = "[milliseconds]",
5102 .name = "halt",
5103 .handler = handle_halt_command,
5104 .mode = COMMAND_EXEC,
5105 .help = "request target to halt, then wait up to the specified"
5106 "number of milliseconds (default 5) for it to complete",
5107 .usage = "[milliseconds]",
5110 .name = "resume",
5111 .handler = handle_resume_command,
5112 .mode = COMMAND_EXEC,
5113 .help = "resume target execution from current PC or address",
5114 .usage = "[address]",
5117 .name = "reset",
5118 .handler = handle_reset_command,
5119 .mode = COMMAND_EXEC,
5120 .usage = "[run|halt|init]",
5121 .help = "Reset all targets into the specified mode."
5122 "Default reset mode is run, if not given.",
5125 .name = "soft_reset_halt",
5126 .handler = handle_soft_reset_halt_command,
5127 .mode = COMMAND_EXEC,
5128 .help = "halt the target and do a soft reset",
5131 .name = "step",
5132 .handler = handle_step_command,
5133 .mode = COMMAND_EXEC,
5134 .help = "step one instruction from current PC or address",
5135 .usage = "[address]",
5138 .name = "mdw",
5139 .handler = handle_md_command,
5140 .mode = COMMAND_EXEC,
5141 .help = "display memory words",
5142 .usage = "['phys'] address [count]",
5145 .name = "mdh",
5146 .handler = handle_md_command,
5147 .mode = COMMAND_EXEC,
5148 .help = "display memory half-words",
5149 .usage = "['phys'] address [count]",
5152 .name = "mdb",
5153 .handler = handle_md_command,
5154 .mode = COMMAND_EXEC,
5155 .help = "display memory bytes",
5156 .usage = "['phys'] address [count]",
5159 .name = "mww",
5160 .handler = handle_mw_command,
5161 .mode = COMMAND_EXEC,
5162 .help = "write memory word",
5163 .usage = "['phys'] address value [count]",
5166 .name = "mwh",
5167 .handler = handle_mw_command,
5168 .mode = COMMAND_EXEC,
5169 .help = "write memory half-word",
5170 .usage = "['phys'] address value [count]",
5173 .name = "mwb",
5174 .handler = handle_mw_command,
5175 .mode = COMMAND_EXEC,
5176 .help = "write memory byte",
5177 .usage = "['phys'] address value [count]",
5180 .name = "bp",
5181 .handler = handle_bp_command,
5182 .mode = COMMAND_EXEC,
5183 .help = "list or set hardware or software breakpoint",
5184 .usage = "[address length ['hw']]",
5187 .name = "rbp",
5188 .handler = handle_rbp_command,
5189 .mode = COMMAND_EXEC,
5190 .help = "remove breakpoint",
5191 .usage = "address",
5194 .name = "wp",
5195 .handler = handle_wp_command,
5196 .mode = COMMAND_EXEC,
5197 .help = "list (no params) or create watchpoints",
5198 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5201 .name = "rwp",
5202 .handler = handle_rwp_command,
5203 .mode = COMMAND_EXEC,
5204 .help = "remove watchpoint",
5205 .usage = "address",
5208 .name = "load_image",
5209 .handler = handle_load_image_command,
5210 .mode = COMMAND_EXEC,
5211 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5212 "[min_address] [max_length]",
5215 .name = "dump_image",
5216 .handler = handle_dump_image_command,
5217 .mode = COMMAND_EXEC,
5218 .usage = "filename address size",
5221 .name = "verify_image",
5222 .handler = handle_verify_image_command,
5223 .mode = COMMAND_EXEC,
5224 .usage = "filename [offset [type]]",
5227 .name = "test_image",
5228 .handler = handle_test_image_command,
5229 .mode = COMMAND_EXEC,
5230 .usage = "filename [offset [type]]",
5233 .name = "ocd_mem2array",
5234 .mode = COMMAND_EXEC,
5235 .jim_handler = jim_mem2array,
5236 .help = "read 8/16/32 bit memory and return as a TCL array "
5237 "for script processing",
5238 .usage = "arrayname bitwidth address count",
5241 .name = "ocd_array2mem",
5242 .mode = COMMAND_EXEC,
5243 .jim_handler = jim_array2mem,
5244 .help = "convert a TCL array to memory locations "
5245 "and write the 8/16/32 bit values",
5246 .usage = "arrayname bitwidth address count",
5249 .name = "reset_nag",
5250 .handler = handle_target_reset_nag,
5251 .mode = COMMAND_ANY,
5252 .help = "Nag after each reset about options that could have been "
5253 "enabled to improve performance. ",
5254 .usage = "['enable'|'disable']",
5256 COMMAND_REGISTRATION_DONE
5258 int target_register_user_commands(struct command_context *cmd_ctx)
5260 int retval = ERROR_OK;
5261 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
5262 return retval;
5264 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
5265 return retval;
5268 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);