NOR: invalidate cached state on target resume
[openocd/ellerodev.git] / src / target / target.c
blob1eb14352aeacd13c57370185904e09d9137af9a7
1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
4 * *
5 * Copyright (C) 2007-2009 Ø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);
632 static int target_run_algorithm_imp(struct target *target, int num_mem_params, struct mem_param *mem_params, int num_reg_params, struct reg_param *reg_param, uint32_t entry_point, uint32_t exit_point, int timeout_ms, void *arch_info)
634 if (!target_was_examined(target))
636 LOG_ERROR("Target not examined yet");
637 return ERROR_FAIL;
639 return target->type->run_algorithm_imp(target, num_mem_params, mem_params, num_reg_params, reg_param, entry_point, exit_point, timeout_ms, arch_info);
642 int target_read_memory(struct target *target,
643 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
645 return target->type->read_memory(target, address, size, count, buffer);
648 int target_read_phys_memory(struct target *target,
649 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
651 return target->type->read_phys_memory(target, address, size, count, buffer);
654 int target_write_memory(struct target *target,
655 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
657 return target->type->write_memory(target, address, size, count, buffer);
660 int target_write_phys_memory(struct target *target,
661 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
663 return target->type->write_phys_memory(target, address, size, count, buffer);
666 int target_bulk_write_memory(struct target *target,
667 uint32_t address, uint32_t count, uint8_t *buffer)
669 return target->type->bulk_write_memory(target, address, count, buffer);
672 int target_add_breakpoint(struct target *target,
673 struct breakpoint *breakpoint)
675 if (target->state != TARGET_HALTED) {
676 LOG_WARNING("target %s is not halted", target->cmd_name);
677 return ERROR_TARGET_NOT_HALTED;
679 return target->type->add_breakpoint(target, breakpoint);
681 int target_remove_breakpoint(struct target *target,
682 struct breakpoint *breakpoint)
684 return target->type->remove_breakpoint(target, breakpoint);
687 int target_add_watchpoint(struct target *target,
688 struct watchpoint *watchpoint)
690 if (target->state != TARGET_HALTED) {
691 LOG_WARNING("target %s is not halted", target->cmd_name);
692 return ERROR_TARGET_NOT_HALTED;
694 return target->type->add_watchpoint(target, watchpoint);
696 int target_remove_watchpoint(struct target *target,
697 struct watchpoint *watchpoint)
699 return target->type->remove_watchpoint(target, watchpoint);
702 int target_get_gdb_reg_list(struct target *target,
703 struct reg **reg_list[], int *reg_list_size)
705 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
707 int target_step(struct target *target,
708 int current, uint32_t address, int handle_breakpoints)
710 return target->type->step(target, current, address, handle_breakpoints);
714 int target_run_algorithm(struct target *target,
715 int num_mem_params, struct mem_param *mem_params,
716 int num_reg_params, struct reg_param *reg_param,
717 uint32_t entry_point, uint32_t exit_point,
718 int timeout_ms, void *arch_info)
720 return target->type->run_algorithm(target,
721 num_mem_params, mem_params, num_reg_params, reg_param,
722 entry_point, exit_point, timeout_ms, arch_info);
726 * Reset the @c examined flag for the given target.
727 * Pure paranoia -- targets are zeroed on allocation.
729 static void target_reset_examined(struct target *target)
731 target->examined = false;
734 static int
735 err_read_phys_memory(struct target *target, uint32_t address,
736 uint32_t size, uint32_t count, uint8_t *buffer)
738 LOG_ERROR("Not implemented: %s", __func__);
739 return ERROR_FAIL;
742 static int
743 err_write_phys_memory(struct target *target, uint32_t address,
744 uint32_t size, uint32_t count, uint8_t *buffer)
746 LOG_ERROR("Not implemented: %s", __func__);
747 return ERROR_FAIL;
750 static int handle_target(void *priv);
752 static int target_init_one(struct command_context *cmd_ctx,
753 struct target *target)
755 target_reset_examined(target);
757 struct target_type *type = target->type;
758 if (type->examine == NULL)
759 type->examine = default_examine;
761 if (type->check_reset== NULL)
762 type->check_reset = default_check_reset;
764 int retval = type->init_target(cmd_ctx, target);
765 if (ERROR_OK != retval)
767 LOG_ERROR("target '%s' init failed", target_name(target));
768 return retval;
772 * @todo get rid of those *memory_imp() methods, now that all
773 * callers are using target_*_memory() accessors ... and make
774 * sure the "physical" paths handle the same issues.
776 /* a non-invasive way(in terms of patches) to add some code that
777 * runs before the type->write/read_memory implementation
779 type->write_memory_imp = target->type->write_memory;
780 type->write_memory = target_write_memory_imp;
782 type->read_memory_imp = target->type->read_memory;
783 type->read_memory = target_read_memory_imp;
785 type->soft_reset_halt_imp = target->type->soft_reset_halt;
786 type->soft_reset_halt = target_soft_reset_halt_imp;
788 type->run_algorithm_imp = target->type->run_algorithm;
789 type->run_algorithm = target_run_algorithm_imp;
791 /* Sanity-check MMU support ... stub in what we must, to help
792 * implement it in stages, but warn if we need to do so.
794 if (type->mmu)
796 if (type->write_phys_memory == NULL)
798 LOG_ERROR("type '%s' is missing write_phys_memory",
799 type->name);
800 type->write_phys_memory = err_write_phys_memory;
802 if (type->read_phys_memory == NULL)
804 LOG_ERROR("type '%s' is missing read_phys_memory",
805 type->name);
806 type->read_phys_memory = err_read_phys_memory;
808 if (type->virt2phys == NULL)
810 LOG_ERROR("type '%s' is missing virt2phys", type->name);
811 type->virt2phys = identity_virt2phys;
814 else
816 /* Make sure no-MMU targets all behave the same: make no
817 * distinction between physical and virtual addresses, and
818 * ensure that virt2phys() is always an identity mapping.
820 if (type->write_phys_memory || type->read_phys_memory
821 || type->virt2phys)
823 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
826 type->mmu = no_mmu;
827 type->write_phys_memory = type->write_memory;
828 type->read_phys_memory = type->read_memory;
829 type->virt2phys = identity_virt2phys;
831 return ERROR_OK;
834 int target_init(struct command_context *cmd_ctx)
836 struct target *target;
837 int retval;
839 for (target = all_targets; target; target = target->next)
841 retval = target_init_one(cmd_ctx, target);
842 if (ERROR_OK != retval)
843 return retval;
846 if (!all_targets)
847 return ERROR_OK;
849 retval = target_register_user_commands(cmd_ctx);
850 if (ERROR_OK != retval)
851 return retval;
853 retval = target_register_timer_callback(&handle_target,
854 100, 1, cmd_ctx->interp);
855 if (ERROR_OK != retval)
856 return retval;
858 return ERROR_OK;
861 COMMAND_HANDLER(handle_target_init_command)
863 if (CMD_ARGC != 0)
864 return ERROR_COMMAND_SYNTAX_ERROR;
866 static bool target_initialized = false;
867 if (target_initialized)
869 LOG_INFO("'target init' has already been called");
870 return ERROR_OK;
872 target_initialized = true;
874 LOG_DEBUG("Initializing targets...");
875 return target_init(CMD_CTX);
878 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
880 struct target_event_callback **callbacks_p = &target_event_callbacks;
882 if (callback == NULL)
884 return ERROR_INVALID_ARGUMENTS;
887 if (*callbacks_p)
889 while ((*callbacks_p)->next)
890 callbacks_p = &((*callbacks_p)->next);
891 callbacks_p = &((*callbacks_p)->next);
894 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
895 (*callbacks_p)->callback = callback;
896 (*callbacks_p)->priv = priv;
897 (*callbacks_p)->next = NULL;
899 return ERROR_OK;
902 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
904 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
905 struct timeval now;
907 if (callback == NULL)
909 return ERROR_INVALID_ARGUMENTS;
912 if (*callbacks_p)
914 while ((*callbacks_p)->next)
915 callbacks_p = &((*callbacks_p)->next);
916 callbacks_p = &((*callbacks_p)->next);
919 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
920 (*callbacks_p)->callback = callback;
921 (*callbacks_p)->periodic = periodic;
922 (*callbacks_p)->time_ms = time_ms;
924 gettimeofday(&now, NULL);
925 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
926 time_ms -= (time_ms % 1000);
927 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
928 if ((*callbacks_p)->when.tv_usec > 1000000)
930 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
931 (*callbacks_p)->when.tv_sec += 1;
934 (*callbacks_p)->priv = priv;
935 (*callbacks_p)->next = NULL;
937 return ERROR_OK;
940 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
942 struct target_event_callback **p = &target_event_callbacks;
943 struct target_event_callback *c = target_event_callbacks;
945 if (callback == NULL)
947 return ERROR_INVALID_ARGUMENTS;
950 while (c)
952 struct target_event_callback *next = c->next;
953 if ((c->callback == callback) && (c->priv == priv))
955 *p = next;
956 free(c);
957 return ERROR_OK;
959 else
960 p = &(c->next);
961 c = next;
964 return ERROR_OK;
967 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
969 struct target_timer_callback **p = &target_timer_callbacks;
970 struct target_timer_callback *c = target_timer_callbacks;
972 if (callback == NULL)
974 return ERROR_INVALID_ARGUMENTS;
977 while (c)
979 struct target_timer_callback *next = c->next;
980 if ((c->callback == callback) && (c->priv == priv))
982 *p = next;
983 free(c);
984 return ERROR_OK;
986 else
987 p = &(c->next);
988 c = next;
991 return ERROR_OK;
994 int target_call_event_callbacks(struct target *target, enum target_event event)
996 struct target_event_callback *callback = target_event_callbacks;
997 struct target_event_callback *next_callback;
999 if (event == TARGET_EVENT_HALTED)
1001 /* execute early halted first */
1002 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1005 LOG_DEBUG("target event %i (%s)",
1006 event,
1007 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1009 target_handle_event(target, event);
1011 while (callback)
1013 next_callback = callback->next;
1014 callback->callback(target, event, callback->priv);
1015 callback = next_callback;
1018 return ERROR_OK;
1021 static int target_timer_callback_periodic_restart(
1022 struct target_timer_callback *cb, struct timeval *now)
1024 int time_ms = cb->time_ms;
1025 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1026 time_ms -= (time_ms % 1000);
1027 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1028 if (cb->when.tv_usec > 1000000)
1030 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1031 cb->when.tv_sec += 1;
1033 return ERROR_OK;
1036 static int target_call_timer_callback(struct target_timer_callback *cb,
1037 struct timeval *now)
1039 cb->callback(cb->priv);
1041 if (cb->periodic)
1042 return target_timer_callback_periodic_restart(cb, now);
1044 return target_unregister_timer_callback(cb->callback, cb->priv);
1047 static int target_call_timer_callbacks_check_time(int checktime)
1049 keep_alive();
1051 struct timeval now;
1052 gettimeofday(&now, NULL);
1054 struct target_timer_callback *callback = target_timer_callbacks;
1055 while (callback)
1057 // cleaning up may unregister and free this callback
1058 struct target_timer_callback *next_callback = callback->next;
1060 bool call_it = callback->callback &&
1061 ((!checktime && callback->periodic) ||
1062 now.tv_sec > callback->when.tv_sec ||
1063 (now.tv_sec == callback->when.tv_sec &&
1064 now.tv_usec >= callback->when.tv_usec));
1066 if (call_it)
1068 int retval = target_call_timer_callback(callback, &now);
1069 if (retval != ERROR_OK)
1070 return retval;
1073 callback = next_callback;
1076 return ERROR_OK;
1079 int target_call_timer_callbacks(void)
1081 return target_call_timer_callbacks_check_time(1);
1084 /* invoke periodic callbacks immediately */
1085 int target_call_timer_callbacks_now(void)
1087 return target_call_timer_callbacks_check_time(0);
1090 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1092 struct working_area *c = target->working_areas;
1093 struct working_area *new_wa = NULL;
1095 /* Reevaluate working area address based on MMU state*/
1096 if (target->working_areas == NULL)
1098 int retval;
1099 int enabled;
1101 retval = target->type->mmu(target, &enabled);
1102 if (retval != ERROR_OK)
1104 return retval;
1107 if (!enabled) {
1108 if (target->working_area_phys_spec) {
1109 LOG_DEBUG("MMU disabled, using physical "
1110 "address for working memory 0x%08x",
1111 (unsigned)target->working_area_phys);
1112 target->working_area = target->working_area_phys;
1113 } else {
1114 LOG_ERROR("No working memory available. "
1115 "Specify -work-area-phys to target.");
1116 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1118 } else {
1119 if (target->working_area_virt_spec) {
1120 LOG_DEBUG("MMU enabled, using virtual "
1121 "address for working memory 0x%08x",
1122 (unsigned)target->working_area_virt);
1123 target->working_area = target->working_area_virt;
1124 } else {
1125 LOG_ERROR("No working memory available. "
1126 "Specify -work-area-virt to target.");
1127 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1132 /* only allocate multiples of 4 byte */
1133 if (size % 4)
1135 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1136 size = (size + 3) & (~3);
1139 /* see if there's already a matching working area */
1140 while (c)
1142 if ((c->free) && (c->size == size))
1144 new_wa = c;
1145 break;
1147 c = c->next;
1150 /* if not, allocate a new one */
1151 if (!new_wa)
1153 struct working_area **p = &target->working_areas;
1154 uint32_t first_free = target->working_area;
1155 uint32_t free_size = target->working_area_size;
1157 c = target->working_areas;
1158 while (c)
1160 first_free += c->size;
1161 free_size -= c->size;
1162 p = &c->next;
1163 c = c->next;
1166 if (free_size < size)
1168 LOG_WARNING("not enough working area available(requested %u, free %u)",
1169 (unsigned)(size), (unsigned)(free_size));
1170 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1173 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1175 new_wa = malloc(sizeof(struct working_area));
1176 new_wa->next = NULL;
1177 new_wa->size = size;
1178 new_wa->address = first_free;
1180 if (target->backup_working_area)
1182 int retval;
1183 new_wa->backup = malloc(new_wa->size);
1184 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1186 free(new_wa->backup);
1187 free(new_wa);
1188 return retval;
1191 else
1193 new_wa->backup = NULL;
1196 /* put new entry in list */
1197 *p = new_wa;
1200 /* mark as used, and return the new (reused) area */
1201 new_wa->free = 0;
1202 *area = new_wa;
1204 /* user pointer */
1205 new_wa->user = area;
1207 return ERROR_OK;
1210 int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1212 if (area->free)
1213 return ERROR_OK;
1215 if (restore && target->backup_working_area)
1217 int retval;
1218 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1219 return retval;
1222 area->free = 1;
1224 /* mark user pointer invalid */
1225 *area->user = NULL;
1226 area->user = NULL;
1228 return ERROR_OK;
1231 int target_free_working_area(struct target *target, struct working_area *area)
1233 return target_free_working_area_restore(target, area, 1);
1236 /* free resources and restore memory, if restoring memory fails,
1237 * free up resources anyway
1239 void target_free_all_working_areas_restore(struct target *target, int restore)
1241 struct working_area *c = target->working_areas;
1243 while (c)
1245 struct working_area *next = c->next;
1246 target_free_working_area_restore(target, c, restore);
1248 if (c->backup)
1249 free(c->backup);
1251 free(c);
1253 c = next;
1256 target->working_areas = NULL;
1259 void target_free_all_working_areas(struct target *target)
1261 target_free_all_working_areas_restore(target, 1);
1264 int target_arch_state(struct target *target)
1266 int retval;
1267 if (target == NULL)
1269 LOG_USER("No target has been configured");
1270 return ERROR_OK;
1273 LOG_USER("target state: %s", target_state_name( target ));
1275 if (target->state != TARGET_HALTED)
1276 return ERROR_OK;
1278 retval = target->type->arch_state(target);
1279 return retval;
1282 /* Single aligned words are guaranteed to use 16 or 32 bit access
1283 * mode respectively, otherwise data is handled as quickly as
1284 * possible
1286 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1288 int retval;
1289 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1290 (int)size, (unsigned)address);
1292 if (!target_was_examined(target))
1294 LOG_ERROR("Target not examined yet");
1295 return ERROR_FAIL;
1298 if (size == 0) {
1299 return ERROR_OK;
1302 if ((address + size - 1) < address)
1304 /* GDB can request this when e.g. PC is 0xfffffffc*/
1305 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1306 (unsigned)address,
1307 (unsigned)size);
1308 return ERROR_FAIL;
1311 if (((address % 2) == 0) && (size == 2))
1313 return target_write_memory(target, address, 2, 1, buffer);
1316 /* handle unaligned head bytes */
1317 if (address % 4)
1319 uint32_t unaligned = 4 - (address % 4);
1321 if (unaligned > size)
1322 unaligned = size;
1324 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1325 return retval;
1327 buffer += unaligned;
1328 address += unaligned;
1329 size -= unaligned;
1332 /* handle aligned words */
1333 if (size >= 4)
1335 int aligned = size - (size % 4);
1337 /* use bulk writes above a certain limit. This may have to be changed */
1338 if (aligned > 128)
1340 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1341 return retval;
1343 else
1345 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1346 return retval;
1349 buffer += aligned;
1350 address += aligned;
1351 size -= aligned;
1354 /* handle tail writes of less than 4 bytes */
1355 if (size > 0)
1357 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1358 return retval;
1361 return ERROR_OK;
1364 /* Single aligned words are guaranteed to use 16 or 32 bit access
1365 * mode respectively, otherwise data is handled as quickly as
1366 * possible
1368 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1370 int retval;
1371 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1372 (int)size, (unsigned)address);
1374 if (!target_was_examined(target))
1376 LOG_ERROR("Target not examined yet");
1377 return ERROR_FAIL;
1380 if (size == 0) {
1381 return ERROR_OK;
1384 if ((address + size - 1) < address)
1386 /* GDB can request this when e.g. PC is 0xfffffffc*/
1387 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1388 address,
1389 size);
1390 return ERROR_FAIL;
1393 if (((address % 2) == 0) && (size == 2))
1395 return target_read_memory(target, address, 2, 1, buffer);
1398 /* handle unaligned head bytes */
1399 if (address % 4)
1401 uint32_t unaligned = 4 - (address % 4);
1403 if (unaligned > size)
1404 unaligned = size;
1406 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1407 return retval;
1409 buffer += unaligned;
1410 address += unaligned;
1411 size -= unaligned;
1414 /* handle aligned words */
1415 if (size >= 4)
1417 int aligned = size - (size % 4);
1419 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1420 return retval;
1422 buffer += aligned;
1423 address += aligned;
1424 size -= aligned;
1427 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1428 if(size >=2)
1430 int aligned = size - (size%2);
1431 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1432 if (retval != ERROR_OK)
1433 return retval;
1435 buffer += aligned;
1436 address += aligned;
1437 size -= aligned;
1439 /* handle tail writes of less than 4 bytes */
1440 if (size > 0)
1442 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1443 return retval;
1446 return ERROR_OK;
1449 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1451 uint8_t *buffer;
1452 int retval;
1453 uint32_t i;
1454 uint32_t checksum = 0;
1455 if (!target_was_examined(target))
1457 LOG_ERROR("Target not examined yet");
1458 return ERROR_FAIL;
1461 if ((retval = target->type->checksum_memory(target, address,
1462 size, &checksum)) != ERROR_OK)
1464 buffer = malloc(size);
1465 if (buffer == NULL)
1467 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1468 return ERROR_INVALID_ARGUMENTS;
1470 retval = target_read_buffer(target, address, size, buffer);
1471 if (retval != ERROR_OK)
1473 free(buffer);
1474 return retval;
1477 /* convert to target endianess */
1478 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1480 uint32_t target_data;
1481 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1482 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1485 retval = image_calculate_checksum(buffer, size, &checksum);
1486 free(buffer);
1489 *crc = checksum;
1491 return retval;
1494 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1496 int retval;
1497 if (!target_was_examined(target))
1499 LOG_ERROR("Target not examined yet");
1500 return ERROR_FAIL;
1503 if (target->type->blank_check_memory == 0)
1504 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1506 retval = target->type->blank_check_memory(target, address, size, blank);
1508 return retval;
1511 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1513 uint8_t value_buf[4];
1514 if (!target_was_examined(target))
1516 LOG_ERROR("Target not examined yet");
1517 return ERROR_FAIL;
1520 int retval = target_read_memory(target, address, 4, 1, value_buf);
1522 if (retval == ERROR_OK)
1524 *value = target_buffer_get_u32(target, value_buf);
1525 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1526 address,
1527 *value);
1529 else
1531 *value = 0x0;
1532 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1533 address);
1536 return retval;
1539 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1541 uint8_t value_buf[2];
1542 if (!target_was_examined(target))
1544 LOG_ERROR("Target not examined yet");
1545 return ERROR_FAIL;
1548 int retval = target_read_memory(target, address, 2, 1, value_buf);
1550 if (retval == ERROR_OK)
1552 *value = target_buffer_get_u16(target, value_buf);
1553 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1554 address,
1555 *value);
1557 else
1559 *value = 0x0;
1560 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1561 address);
1564 return retval;
1567 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1569 int retval = target_read_memory(target, address, 1, 1, value);
1570 if (!target_was_examined(target))
1572 LOG_ERROR("Target not examined yet");
1573 return ERROR_FAIL;
1576 if (retval == ERROR_OK)
1578 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1579 address,
1580 *value);
1582 else
1584 *value = 0x0;
1585 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1586 address);
1589 return retval;
1592 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1594 int retval;
1595 uint8_t value_buf[4];
1596 if (!target_was_examined(target))
1598 LOG_ERROR("Target not examined yet");
1599 return ERROR_FAIL;
1602 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1603 address,
1604 value);
1606 target_buffer_set_u32(target, value_buf, value);
1607 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1609 LOG_DEBUG("failed: %i", retval);
1612 return retval;
1615 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1617 int retval;
1618 uint8_t value_buf[2];
1619 if (!target_was_examined(target))
1621 LOG_ERROR("Target not examined yet");
1622 return ERROR_FAIL;
1625 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1626 address,
1627 value);
1629 target_buffer_set_u16(target, value_buf, value);
1630 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1632 LOG_DEBUG("failed: %i", retval);
1635 return retval;
1638 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1640 int retval;
1641 if (!target_was_examined(target))
1643 LOG_ERROR("Target not examined yet");
1644 return ERROR_FAIL;
1647 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1648 address, value);
1650 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1652 LOG_DEBUG("failed: %i", retval);
1655 return retval;
1658 COMMAND_HANDLER(handle_targets_command)
1660 struct target *target = all_targets;
1662 if (CMD_ARGC == 1)
1664 target = get_target(CMD_ARGV[0]);
1665 if (target == NULL) {
1666 command_print(CMD_CTX,"Target: %s is unknown, try one of:\n", CMD_ARGV[0]);
1667 goto DumpTargets;
1669 if (!target->tap->enabled) {
1670 command_print(CMD_CTX,"Target: TAP %s is disabled, "
1671 "can't be the current target\n",
1672 target->tap->dotted_name);
1673 return ERROR_FAIL;
1676 CMD_CTX->current_target = target->target_number;
1677 return ERROR_OK;
1679 DumpTargets:
1681 target = all_targets;
1682 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
1683 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
1684 while (target)
1686 const char *state;
1687 char marker = ' ';
1689 if (target->tap->enabled)
1690 state = target_state_name( target );
1691 else
1692 state = "tap-disabled";
1694 if (CMD_CTX->current_target == target->target_number)
1695 marker = '*';
1697 /* keep columns lined up to match the headers above */
1698 command_print(CMD_CTX, "%2d%c %-18s %-10s %-6s %-18s %s",
1699 target->target_number,
1700 marker,
1701 target_name(target),
1702 target_type_name(target),
1703 Jim_Nvp_value2name_simple(nvp_target_endian,
1704 target->endianness)->name,
1705 target->tap->dotted_name,
1706 state);
1707 target = target->next;
1710 return ERROR_OK;
1713 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1715 static int powerDropout;
1716 static int srstAsserted;
1718 static int runPowerRestore;
1719 static int runPowerDropout;
1720 static int runSrstAsserted;
1721 static int runSrstDeasserted;
1723 static int sense_handler(void)
1725 static int prevSrstAsserted = 0;
1726 static int prevPowerdropout = 0;
1728 int retval;
1729 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1730 return retval;
1732 int powerRestored;
1733 powerRestored = prevPowerdropout && !powerDropout;
1734 if (powerRestored)
1736 runPowerRestore = 1;
1739 long long current = timeval_ms();
1740 static long long lastPower = 0;
1741 int waitMore = lastPower + 2000 > current;
1742 if (powerDropout && !waitMore)
1744 runPowerDropout = 1;
1745 lastPower = current;
1748 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1749 return retval;
1751 int srstDeasserted;
1752 srstDeasserted = prevSrstAsserted && !srstAsserted;
1754 static long long lastSrst = 0;
1755 waitMore = lastSrst + 2000 > current;
1756 if (srstDeasserted && !waitMore)
1758 runSrstDeasserted = 1;
1759 lastSrst = current;
1762 if (!prevSrstAsserted && srstAsserted)
1764 runSrstAsserted = 1;
1767 prevSrstAsserted = srstAsserted;
1768 prevPowerdropout = powerDropout;
1770 if (srstDeasserted || powerRestored)
1772 /* Other than logging the event we can't do anything here.
1773 * Issuing a reset is a particularly bad idea as we might
1774 * be inside a reset already.
1778 return ERROR_OK;
1781 /* process target state changes */
1782 static int handle_target(void *priv)
1784 Jim_Interp *interp = (Jim_Interp *)priv;
1785 int retval = ERROR_OK;
1787 /* we do not want to recurse here... */
1788 static int recursive = 0;
1789 if (! recursive)
1791 recursive = 1;
1792 sense_handler();
1793 /* danger! running these procedures can trigger srst assertions and power dropouts.
1794 * We need to avoid an infinite loop/recursion here and we do that by
1795 * clearing the flags after running these events.
1797 int did_something = 0;
1798 if (runSrstAsserted)
1800 LOG_INFO("srst asserted detected, running srst_asserted proc.");
1801 Jim_Eval(interp, "srst_asserted");
1802 did_something = 1;
1804 if (runSrstDeasserted)
1806 Jim_Eval(interp, "srst_deasserted");
1807 did_something = 1;
1809 if (runPowerDropout)
1811 LOG_INFO("Power dropout detected, running power_dropout proc.");
1812 Jim_Eval(interp, "power_dropout");
1813 did_something = 1;
1815 if (runPowerRestore)
1817 Jim_Eval(interp, "power_restore");
1818 did_something = 1;
1821 if (did_something)
1823 /* clear detect flags */
1824 sense_handler();
1827 /* clear action flags */
1829 runSrstAsserted = 0;
1830 runSrstDeasserted = 0;
1831 runPowerRestore = 0;
1832 runPowerDropout = 0;
1834 recursive = 0;
1837 /* Poll targets for state changes unless that's globally disabled.
1838 * Skip targets that are currently disabled.
1840 for (struct target *target = all_targets;
1841 is_jtag_poll_safe() && target;
1842 target = target->next)
1844 if (!target->tap->enabled)
1845 continue;
1847 /* only poll target if we've got power and srst isn't asserted */
1848 if (!powerDropout && !srstAsserted)
1850 /* polling may fail silently until the target has been examined */
1851 if ((retval = target_poll(target)) != ERROR_OK)
1853 /* FIX!!!!! If we add a LOG_INFO() here to output a line in GDB
1854 * *why* we are aborting GDB, then we'll spam telnet when the
1855 * poll is failing persistently.
1857 * If we could implement an event that detected the
1858 * target going from non-pollable to pollable, we could issue
1859 * an error only upon the transition.
1861 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1862 return retval;
1867 return retval;
1870 COMMAND_HANDLER(handle_reg_command)
1872 struct target *target;
1873 struct reg *reg = NULL;
1874 unsigned count = 0;
1875 char *value;
1877 LOG_DEBUG("-");
1879 target = get_current_target(CMD_CTX);
1881 /* list all available registers for the current target */
1882 if (CMD_ARGC == 0)
1884 struct reg_cache *cache = target->reg_cache;
1886 count = 0;
1887 while (cache)
1889 unsigned i;
1891 command_print(CMD_CTX, "===== %s", cache->name);
1893 for (i = 0, reg = cache->reg_list;
1894 i < cache->num_regs;
1895 i++, reg++, count++)
1897 /* only print cached values if they are valid */
1898 if (reg->valid) {
1899 value = buf_to_str(reg->value,
1900 reg->size, 16);
1901 command_print(CMD_CTX,
1902 "(%i) %s (/%" PRIu32 "): 0x%s%s",
1903 count, reg->name,
1904 reg->size, value,
1905 reg->dirty
1906 ? " (dirty)"
1907 : "");
1908 free(value);
1909 } else {
1910 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
1911 count, reg->name,
1912 reg->size) ;
1915 cache = cache->next;
1918 return ERROR_OK;
1921 /* access a single register by its ordinal number */
1922 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9'))
1924 unsigned num;
1925 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
1927 struct reg_cache *cache = target->reg_cache;
1928 count = 0;
1929 while (cache)
1931 unsigned i;
1932 for (i = 0; i < cache->num_regs; i++)
1934 if (count++ == num)
1936 reg = &cache->reg_list[i];
1937 break;
1940 if (reg)
1941 break;
1942 cache = cache->next;
1945 if (!reg)
1947 command_print(CMD_CTX, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1948 return ERROR_OK;
1950 } else /* access a single register by its name */
1952 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
1954 if (!reg)
1956 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
1957 return ERROR_OK;
1961 /* display a register */
1962 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0') && (CMD_ARGV[1][0] <= '9'))))
1964 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
1965 reg->valid = 0;
1967 if (reg->valid == 0)
1969 reg->type->get(reg);
1971 value = buf_to_str(reg->value, reg->size, 16);
1972 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1973 free(value);
1974 return ERROR_OK;
1977 /* set register value */
1978 if (CMD_ARGC == 2)
1980 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
1981 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
1983 reg->type->set(reg, buf);
1985 value = buf_to_str(reg->value, reg->size, 16);
1986 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1987 free(value);
1989 free(buf);
1991 return ERROR_OK;
1994 command_print(CMD_CTX, "usage: reg <#|name> [value]");
1996 return ERROR_OK;
1999 COMMAND_HANDLER(handle_poll_command)
2001 int retval = ERROR_OK;
2002 struct target *target = get_current_target(CMD_CTX);
2004 if (CMD_ARGC == 0)
2006 command_print(CMD_CTX, "background polling: %s",
2007 jtag_poll_get_enabled() ? "on" : "off");
2008 command_print(CMD_CTX, "TAP: %s (%s)",
2009 target->tap->dotted_name,
2010 target->tap->enabled ? "enabled" : "disabled");
2011 if (!target->tap->enabled)
2012 return ERROR_OK;
2013 if ((retval = target_poll(target)) != ERROR_OK)
2014 return retval;
2015 if ((retval = target_arch_state(target)) != ERROR_OK)
2016 return retval;
2018 else if (CMD_ARGC == 1)
2020 bool enable;
2021 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2022 jtag_poll_set_enabled(enable);
2024 else
2026 return ERROR_COMMAND_SYNTAX_ERROR;
2029 return retval;
2032 COMMAND_HANDLER(handle_wait_halt_command)
2034 if (CMD_ARGC > 1)
2035 return ERROR_COMMAND_SYNTAX_ERROR;
2037 unsigned ms = 5000;
2038 if (1 == CMD_ARGC)
2040 int retval = parse_uint(CMD_ARGV[0], &ms);
2041 if (ERROR_OK != retval)
2043 command_print(CMD_CTX, "usage: %s [seconds]", CMD_NAME);
2044 return ERROR_COMMAND_SYNTAX_ERROR;
2046 // convert seconds (given) to milliseconds (needed)
2047 ms *= 1000;
2050 struct target *target = get_current_target(CMD_CTX);
2051 return target_wait_state(target, TARGET_HALTED, ms);
2054 /* wait for target state to change. The trick here is to have a low
2055 * latency for short waits and not to suck up all the CPU time
2056 * on longer waits.
2058 * After 500ms, keep_alive() is invoked
2060 int target_wait_state(struct target *target, enum target_state state, int ms)
2062 int retval;
2063 long long then = 0, cur;
2064 int once = 1;
2066 for (;;)
2068 if ((retval = target_poll(target)) != ERROR_OK)
2069 return retval;
2070 if (target->state == state)
2072 break;
2074 cur = timeval_ms();
2075 if (once)
2077 once = 0;
2078 then = timeval_ms();
2079 LOG_DEBUG("waiting for target %s...",
2080 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2083 if (cur-then > 500)
2085 keep_alive();
2088 if ((cur-then) > ms)
2090 LOG_ERROR("timed out while waiting for target %s",
2091 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2092 return ERROR_FAIL;
2096 return ERROR_OK;
2099 COMMAND_HANDLER(handle_halt_command)
2101 LOG_DEBUG("-");
2103 struct target *target = get_current_target(CMD_CTX);
2104 int retval = target_halt(target);
2105 if (ERROR_OK != retval)
2106 return retval;
2108 if (CMD_ARGC == 1)
2110 unsigned wait;
2111 retval = parse_uint(CMD_ARGV[0], &wait);
2112 if (ERROR_OK != retval)
2113 return ERROR_COMMAND_SYNTAX_ERROR;
2114 if (!wait)
2115 return ERROR_OK;
2118 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2121 COMMAND_HANDLER(handle_soft_reset_halt_command)
2123 struct target *target = get_current_target(CMD_CTX);
2125 LOG_USER("requesting target halt and executing a soft reset");
2127 target->type->soft_reset_halt(target);
2129 return ERROR_OK;
2132 COMMAND_HANDLER(handle_reset_command)
2134 if (CMD_ARGC > 1)
2135 return ERROR_COMMAND_SYNTAX_ERROR;
2137 enum target_reset_mode reset_mode = RESET_RUN;
2138 if (CMD_ARGC == 1)
2140 const Jim_Nvp *n;
2141 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2142 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2143 return ERROR_COMMAND_SYNTAX_ERROR;
2145 reset_mode = n->value;
2148 /* reset *all* targets */
2149 return target_process_reset(CMD_CTX, reset_mode);
2153 COMMAND_HANDLER(handle_resume_command)
2155 int current = 1;
2156 if (CMD_ARGC > 1)
2157 return ERROR_COMMAND_SYNTAX_ERROR;
2159 struct target *target = get_current_target(CMD_CTX);
2160 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2162 /* with no CMD_ARGV, resume from current pc, addr = 0,
2163 * with one arguments, addr = CMD_ARGV[0],
2164 * handle breakpoints, not debugging */
2165 uint32_t addr = 0;
2166 if (CMD_ARGC == 1)
2168 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2169 current = 0;
2172 return target_resume(target, current, addr, 1, 0);
2175 COMMAND_HANDLER(handle_step_command)
2177 if (CMD_ARGC > 1)
2178 return ERROR_COMMAND_SYNTAX_ERROR;
2180 LOG_DEBUG("-");
2182 /* with no CMD_ARGV, step from current pc, addr = 0,
2183 * with one argument addr = CMD_ARGV[0],
2184 * handle breakpoints, debugging */
2185 uint32_t addr = 0;
2186 int current_pc = 1;
2187 if (CMD_ARGC == 1)
2189 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2190 current_pc = 0;
2193 struct target *target = get_current_target(CMD_CTX);
2195 return target->type->step(target, current_pc, addr, 1);
2198 static void handle_md_output(struct command_context *cmd_ctx,
2199 struct target *target, uint32_t address, unsigned size,
2200 unsigned count, const uint8_t *buffer)
2202 const unsigned line_bytecnt = 32;
2203 unsigned line_modulo = line_bytecnt / size;
2205 char output[line_bytecnt * 4 + 1];
2206 unsigned output_len = 0;
2208 const char *value_fmt;
2209 switch (size) {
2210 case 4: value_fmt = "%8.8x "; break;
2211 case 2: value_fmt = "%4.4x "; break;
2212 case 1: value_fmt = "%2.2x "; break;
2213 default:
2214 /* "can't happen", caller checked */
2215 LOG_ERROR("invalid memory read size: %u", size);
2216 return;
2219 for (unsigned i = 0; i < count; i++)
2221 if (i % line_modulo == 0)
2223 output_len += snprintf(output + output_len,
2224 sizeof(output) - output_len,
2225 "0x%8.8x: ",
2226 (unsigned)(address + (i*size)));
2229 uint32_t value = 0;
2230 const uint8_t *value_ptr = buffer + i * size;
2231 switch (size) {
2232 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2233 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2234 case 1: value = *value_ptr;
2236 output_len += snprintf(output + output_len,
2237 sizeof(output) - output_len,
2238 value_fmt, value);
2240 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2242 command_print(cmd_ctx, "%s", output);
2243 output_len = 0;
2248 COMMAND_HANDLER(handle_md_command)
2250 if (CMD_ARGC < 1)
2251 return ERROR_COMMAND_SYNTAX_ERROR;
2253 unsigned size = 0;
2254 switch (CMD_NAME[2]) {
2255 case 'w': size = 4; break;
2256 case 'h': size = 2; break;
2257 case 'b': size = 1; break;
2258 default: return ERROR_COMMAND_SYNTAX_ERROR;
2261 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2262 int (*fn)(struct target *target,
2263 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2264 if (physical)
2266 CMD_ARGC--;
2267 CMD_ARGV++;
2268 fn=target_read_phys_memory;
2269 } else
2271 fn=target_read_memory;
2273 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2275 return ERROR_COMMAND_SYNTAX_ERROR;
2278 uint32_t address;
2279 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2281 unsigned count = 1;
2282 if (CMD_ARGC == 2)
2283 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2285 uint8_t *buffer = calloc(count, size);
2287 struct target *target = get_current_target(CMD_CTX);
2288 int retval = fn(target, address, size, count, buffer);
2289 if (ERROR_OK == retval)
2290 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2292 free(buffer);
2294 return retval;
2297 COMMAND_HANDLER(handle_mw_command)
2299 if (CMD_ARGC < 2)
2301 return ERROR_COMMAND_SYNTAX_ERROR;
2303 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2304 int (*fn)(struct target *target,
2305 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2306 if (physical)
2308 CMD_ARGC--;
2309 CMD_ARGV++;
2310 fn=target_write_phys_memory;
2311 } else
2313 fn=target_write_memory;
2315 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2316 return ERROR_COMMAND_SYNTAX_ERROR;
2318 uint32_t address;
2319 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2321 uint32_t value;
2322 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2324 unsigned count = 1;
2325 if (CMD_ARGC == 3)
2326 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2328 struct target *target = get_current_target(CMD_CTX);
2329 unsigned wordsize;
2330 uint8_t value_buf[4];
2331 switch (CMD_NAME[2])
2333 case 'w':
2334 wordsize = 4;
2335 target_buffer_set_u32(target, value_buf, value);
2336 break;
2337 case 'h':
2338 wordsize = 2;
2339 target_buffer_set_u16(target, value_buf, value);
2340 break;
2341 case 'b':
2342 wordsize = 1;
2343 value_buf[0] = value;
2344 break;
2345 default:
2346 return ERROR_COMMAND_SYNTAX_ERROR;
2348 for (unsigned i = 0; i < count; i++)
2350 int retval = fn(target,
2351 address + i * wordsize, wordsize, 1, value_buf);
2352 if (ERROR_OK != retval)
2353 return retval;
2354 keep_alive();
2357 return ERROR_OK;
2361 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2362 uint32_t *min_address, uint32_t *max_address)
2364 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2365 return ERROR_COMMAND_SYNTAX_ERROR;
2367 /* a base address isn't always necessary,
2368 * default to 0x0 (i.e. don't relocate) */
2369 if (CMD_ARGC >= 2)
2371 uint32_t addr;
2372 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2373 image->base_address = addr;
2374 image->base_address_set = 1;
2376 else
2377 image->base_address_set = 0;
2379 image->start_address_set = 0;
2381 if (CMD_ARGC >= 4)
2383 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2385 if (CMD_ARGC == 5)
2387 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2388 // use size (given) to find max (required)
2389 *max_address += *min_address;
2392 if (*min_address > *max_address)
2393 return ERROR_COMMAND_SYNTAX_ERROR;
2395 return ERROR_OK;
2398 COMMAND_HANDLER(handle_load_image_command)
2400 uint8_t *buffer;
2401 size_t buf_cnt;
2402 uint32_t image_size;
2403 uint32_t min_address = 0;
2404 uint32_t max_address = 0xffffffff;
2405 int i;
2406 struct image image;
2408 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2409 &image, &min_address, &max_address);
2410 if (ERROR_OK != retval)
2411 return retval;
2413 struct target *target = get_current_target(CMD_CTX);
2415 struct duration bench;
2416 duration_start(&bench);
2418 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2420 return ERROR_OK;
2423 image_size = 0x0;
2424 retval = ERROR_OK;
2425 for (i = 0; i < image.num_sections; i++)
2427 buffer = malloc(image.sections[i].size);
2428 if (buffer == NULL)
2430 command_print(CMD_CTX,
2431 "error allocating buffer for section (%d bytes)",
2432 (int)(image.sections[i].size));
2433 break;
2436 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2438 free(buffer);
2439 break;
2442 uint32_t offset = 0;
2443 uint32_t length = buf_cnt;
2445 /* DANGER!!! beware of unsigned comparision here!!! */
2447 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2448 (image.sections[i].base_address < max_address))
2450 if (image.sections[i].base_address < min_address)
2452 /* clip addresses below */
2453 offset += min_address-image.sections[i].base_address;
2454 length -= offset;
2457 if (image.sections[i].base_address + buf_cnt > max_address)
2459 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2462 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2464 free(buffer);
2465 break;
2467 image_size += length;
2468 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2469 (unsigned int)length,
2470 image.sections[i].base_address + offset);
2473 free(buffer);
2476 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2478 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2479 "in %fs (%0.3f kb/s)", image_size,
2480 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2483 image_close(&image);
2485 return retval;
2489 COMMAND_HANDLER(handle_dump_image_command)
2491 struct fileio fileio;
2493 uint8_t buffer[560];
2494 int retvaltemp;
2497 struct target *target = get_current_target(CMD_CTX);
2499 if (CMD_ARGC != 3)
2501 command_print(CMD_CTX, "usage: dump_image <filename> <address> <size>");
2502 return ERROR_OK;
2505 uint32_t address;
2506 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2507 uint32_t size;
2508 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2510 if (fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2512 return ERROR_OK;
2515 struct duration bench;
2516 duration_start(&bench);
2518 int retval = ERROR_OK;
2519 while (size > 0)
2521 size_t size_written;
2522 uint32_t this_run_size = (size > 560) ? 560 : size;
2523 retval = target_read_buffer(target, address, this_run_size, buffer);
2524 if (retval != ERROR_OK)
2526 break;
2529 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2530 if (retval != ERROR_OK)
2532 break;
2535 size -= this_run_size;
2536 address += this_run_size;
2539 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2540 return retvaltemp;
2542 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2544 command_print(CMD_CTX,
2545 "dumped %ld bytes in %fs (%0.3f kb/s)", (long)fileio.size,
2546 duration_elapsed(&bench), duration_kbps(&bench, fileio.size));
2549 return retval;
2552 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2554 uint8_t *buffer;
2555 size_t buf_cnt;
2556 uint32_t image_size;
2557 int i;
2558 int retval;
2559 uint32_t checksum = 0;
2560 uint32_t mem_checksum = 0;
2562 struct image image;
2564 struct target *target = get_current_target(CMD_CTX);
2566 if (CMD_ARGC < 1)
2568 return ERROR_COMMAND_SYNTAX_ERROR;
2571 if (!target)
2573 LOG_ERROR("no target selected");
2574 return ERROR_FAIL;
2577 struct duration bench;
2578 duration_start(&bench);
2580 if (CMD_ARGC >= 2)
2582 uint32_t addr;
2583 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2584 image.base_address = addr;
2585 image.base_address_set = 1;
2587 else
2589 image.base_address_set = 0;
2590 image.base_address = 0x0;
2593 image.start_address_set = 0;
2595 if ((retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL)) != ERROR_OK)
2597 return retval;
2600 image_size = 0x0;
2601 retval = ERROR_OK;
2602 for (i = 0; i < image.num_sections; i++)
2604 buffer = malloc(image.sections[i].size);
2605 if (buffer == NULL)
2607 command_print(CMD_CTX,
2608 "error allocating buffer for section (%d bytes)",
2609 (int)(image.sections[i].size));
2610 break;
2612 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2614 free(buffer);
2615 break;
2618 if (verify)
2620 /* calculate checksum of image */
2621 image_calculate_checksum(buffer, buf_cnt, &checksum);
2623 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2624 if (retval != ERROR_OK)
2626 free(buffer);
2627 break;
2630 if (checksum != mem_checksum)
2632 /* failed crc checksum, fall back to a binary compare */
2633 uint8_t *data;
2635 command_print(CMD_CTX, "checksum mismatch - attempting binary compare");
2637 data = (uint8_t*)malloc(buf_cnt);
2639 /* Can we use 32bit word accesses? */
2640 int size = 1;
2641 int count = buf_cnt;
2642 if ((count % 4) == 0)
2644 size *= 4;
2645 count /= 4;
2647 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2648 if (retval == ERROR_OK)
2650 uint32_t t;
2651 for (t = 0; t < buf_cnt; t++)
2653 if (data[t] != buffer[t])
2655 command_print(CMD_CTX,
2656 "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n",
2657 (unsigned)(t + image.sections[i].base_address),
2658 data[t],
2659 buffer[t]);
2660 free(data);
2661 free(buffer);
2662 retval = ERROR_FAIL;
2663 goto done;
2665 if ((t%16384) == 0)
2667 keep_alive();
2672 free(data);
2674 } else
2676 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
2677 image.sections[i].base_address,
2678 buf_cnt);
2681 free(buffer);
2682 image_size += buf_cnt;
2684 done:
2685 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2687 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
2688 "in %fs (%0.3f kb/s)", image_size,
2689 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2692 image_close(&image);
2694 return retval;
2697 COMMAND_HANDLER(handle_verify_image_command)
2699 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2702 COMMAND_HANDLER(handle_test_image_command)
2704 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2707 static int handle_bp_command_list(struct command_context *cmd_ctx)
2709 struct target *target = get_current_target(cmd_ctx);
2710 struct breakpoint *breakpoint = target->breakpoints;
2711 while (breakpoint)
2713 if (breakpoint->type == BKPT_SOFT)
2715 char* buf = buf_to_str(breakpoint->orig_instr,
2716 breakpoint->length, 16);
2717 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2718 breakpoint->address,
2719 breakpoint->length,
2720 breakpoint->set, buf);
2721 free(buf);
2723 else
2725 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2726 breakpoint->address,
2727 breakpoint->length, breakpoint->set);
2730 breakpoint = breakpoint->next;
2732 return ERROR_OK;
2735 static int handle_bp_command_set(struct command_context *cmd_ctx,
2736 uint32_t addr, uint32_t length, int hw)
2738 struct target *target = get_current_target(cmd_ctx);
2739 int retval = breakpoint_add(target, addr, length, hw);
2740 if (ERROR_OK == retval)
2741 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2742 else
2743 LOG_ERROR("Failure setting breakpoint");
2744 return retval;
2747 COMMAND_HANDLER(handle_bp_command)
2749 if (CMD_ARGC == 0)
2750 return handle_bp_command_list(CMD_CTX);
2752 if (CMD_ARGC < 2 || CMD_ARGC > 3)
2754 command_print(CMD_CTX, "usage: bp <address> <length> ['hw']");
2755 return ERROR_COMMAND_SYNTAX_ERROR;
2758 uint32_t addr;
2759 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2760 uint32_t length;
2761 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2763 int hw = BKPT_SOFT;
2764 if (CMD_ARGC == 3)
2766 if (strcmp(CMD_ARGV[2], "hw") == 0)
2767 hw = BKPT_HARD;
2768 else
2769 return ERROR_COMMAND_SYNTAX_ERROR;
2772 return handle_bp_command_set(CMD_CTX, addr, length, hw);
2775 COMMAND_HANDLER(handle_rbp_command)
2777 if (CMD_ARGC != 1)
2778 return ERROR_COMMAND_SYNTAX_ERROR;
2780 uint32_t addr;
2781 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2783 struct target *target = get_current_target(CMD_CTX);
2784 breakpoint_remove(target, addr);
2786 return ERROR_OK;
2789 COMMAND_HANDLER(handle_wp_command)
2791 struct target *target = get_current_target(CMD_CTX);
2793 if (CMD_ARGC == 0)
2795 struct watchpoint *watchpoint = target->watchpoints;
2797 while (watchpoint)
2799 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
2800 ", len: 0x%8.8" PRIx32
2801 ", r/w/a: %i, value: 0x%8.8" PRIx32
2802 ", mask: 0x%8.8" PRIx32,
2803 watchpoint->address,
2804 watchpoint->length,
2805 (int)watchpoint->rw,
2806 watchpoint->value,
2807 watchpoint->mask);
2808 watchpoint = watchpoint->next;
2810 return ERROR_OK;
2813 enum watchpoint_rw type = WPT_ACCESS;
2814 uint32_t addr = 0;
2815 uint32_t length = 0;
2816 uint32_t data_value = 0x0;
2817 uint32_t data_mask = 0xffffffff;
2819 switch (CMD_ARGC)
2821 case 5:
2822 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
2823 // fall through
2824 case 4:
2825 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
2826 // fall through
2827 case 3:
2828 switch (CMD_ARGV[2][0])
2830 case 'r':
2831 type = WPT_READ;
2832 break;
2833 case 'w':
2834 type = WPT_WRITE;
2835 break;
2836 case 'a':
2837 type = WPT_ACCESS;
2838 break;
2839 default:
2840 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
2841 return ERROR_COMMAND_SYNTAX_ERROR;
2843 // fall through
2844 case 2:
2845 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2846 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2847 break;
2849 default:
2850 command_print(CMD_CTX, "usage: wp [address length "
2851 "[(r|w|a) [value [mask]]]]");
2852 return ERROR_COMMAND_SYNTAX_ERROR;
2855 int retval = watchpoint_add(target, addr, length, type,
2856 data_value, data_mask);
2857 if (ERROR_OK != retval)
2858 LOG_ERROR("Failure setting watchpoints");
2860 return retval;
2863 COMMAND_HANDLER(handle_rwp_command)
2865 if (CMD_ARGC != 1)
2866 return ERROR_COMMAND_SYNTAX_ERROR;
2868 uint32_t addr;
2869 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2871 struct target *target = get_current_target(CMD_CTX);
2872 watchpoint_remove(target, addr);
2874 return ERROR_OK;
2879 * Translate a virtual address to a physical address.
2881 * The low-level target implementation must have logged a detailed error
2882 * which is forwarded to telnet/GDB session.
2884 COMMAND_HANDLER(handle_virt2phys_command)
2886 if (CMD_ARGC != 1)
2887 return ERROR_COMMAND_SYNTAX_ERROR;
2889 uint32_t va;
2890 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
2891 uint32_t pa;
2893 struct target *target = get_current_target(CMD_CTX);
2894 int retval = target->type->virt2phys(target, va, &pa);
2895 if (retval == ERROR_OK)
2896 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
2898 return retval;
2901 static void writeData(FILE *f, const void *data, size_t len)
2903 size_t written = fwrite(data, 1, len, f);
2904 if (written != len)
2905 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
2908 static void writeLong(FILE *f, int l)
2910 int i;
2911 for (i = 0; i < 4; i++)
2913 char c = (l >> (i*8))&0xff;
2914 writeData(f, &c, 1);
2919 static void writeString(FILE *f, char *s)
2921 writeData(f, s, strlen(s));
2924 /* Dump a gmon.out histogram file. */
2925 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
2927 uint32_t i;
2928 FILE *f = fopen(filename, "w");
2929 if (f == NULL)
2930 return;
2931 writeString(f, "gmon");
2932 writeLong(f, 0x00000001); /* Version */
2933 writeLong(f, 0); /* padding */
2934 writeLong(f, 0); /* padding */
2935 writeLong(f, 0); /* padding */
2937 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
2938 writeData(f, &zero, 1);
2940 /* figure out bucket size */
2941 uint32_t min = samples[0];
2942 uint32_t max = samples[0];
2943 for (i = 0; i < sampleNum; i++)
2945 if (min > samples[i])
2947 min = samples[i];
2949 if (max < samples[i])
2951 max = samples[i];
2955 int addressSpace = (max-min + 1);
2957 static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
2958 uint32_t length = addressSpace;
2959 if (length > maxBuckets)
2961 length = maxBuckets;
2963 int *buckets = malloc(sizeof(int)*length);
2964 if (buckets == NULL)
2966 fclose(f);
2967 return;
2969 memset(buckets, 0, sizeof(int)*length);
2970 for (i = 0; i < sampleNum;i++)
2972 uint32_t address = samples[i];
2973 long long a = address-min;
2974 long long b = length-1;
2975 long long c = addressSpace-1;
2976 int index = (a*b)/c; /* danger!!!! int32 overflows */
2977 buckets[index]++;
2980 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
2981 writeLong(f, min); /* low_pc */
2982 writeLong(f, max); /* high_pc */
2983 writeLong(f, length); /* # of samples */
2984 writeLong(f, 64000000); /* 64MHz */
2985 writeString(f, "seconds");
2986 for (i = 0; i < (15-strlen("seconds")); i++)
2987 writeData(f, &zero, 1);
2988 writeString(f, "s");
2990 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
2992 char *data = malloc(2*length);
2993 if (data != NULL)
2995 for (i = 0; i < length;i++)
2997 int val;
2998 val = buckets[i];
2999 if (val > 65535)
3001 val = 65535;
3003 data[i*2]=val&0xff;
3004 data[i*2 + 1]=(val >> 8)&0xff;
3006 free(buckets);
3007 writeData(f, data, length * 2);
3008 free(data);
3009 } else
3011 free(buckets);
3014 fclose(f);
3017 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3018 * which will be used as a random sampling of PC */
3019 COMMAND_HANDLER(handle_profile_command)
3021 struct target *target = get_current_target(CMD_CTX);
3022 struct timeval timeout, now;
3024 gettimeofday(&timeout, NULL);
3025 if (CMD_ARGC != 2)
3027 return ERROR_COMMAND_SYNTAX_ERROR;
3029 unsigned offset;
3030 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3032 timeval_add_time(&timeout, offset, 0);
3035 * @todo: Some cores let us sample the PC without the
3036 * annoying halt/resume step; for example, ARMv7 PCSR.
3037 * Provide a way to use that more efficient mechanism.
3040 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3042 static const int maxSample = 10000;
3043 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3044 if (samples == NULL)
3045 return ERROR_OK;
3047 int numSamples = 0;
3048 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3049 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3051 for (;;)
3053 int retval;
3054 target_poll(target);
3055 if (target->state == TARGET_HALTED)
3057 uint32_t t=*((uint32_t *)reg->value);
3058 samples[numSamples++]=t;
3059 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3060 target_poll(target);
3061 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3062 } else if (target->state == TARGET_RUNNING)
3064 /* We want to quickly sample the PC. */
3065 if ((retval = target_halt(target)) != ERROR_OK)
3067 free(samples);
3068 return retval;
3070 } else
3072 command_print(CMD_CTX, "Target not halted or running");
3073 retval = ERROR_OK;
3074 break;
3076 if (retval != ERROR_OK)
3078 break;
3081 gettimeofday(&now, NULL);
3082 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3084 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3085 if ((retval = target_poll(target)) != ERROR_OK)
3087 free(samples);
3088 return retval;
3090 if (target->state == TARGET_HALTED)
3092 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3094 if ((retval = target_poll(target)) != ERROR_OK)
3096 free(samples);
3097 return retval;
3099 writeGmon(samples, numSamples, CMD_ARGV[1]);
3100 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3101 break;
3104 free(samples);
3106 return ERROR_OK;
3109 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3111 char *namebuf;
3112 Jim_Obj *nameObjPtr, *valObjPtr;
3113 int result;
3115 namebuf = alloc_printf("%s(%d)", varname, idx);
3116 if (!namebuf)
3117 return JIM_ERR;
3119 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3120 valObjPtr = Jim_NewIntObj(interp, val);
3121 if (!nameObjPtr || !valObjPtr)
3123 free(namebuf);
3124 return JIM_ERR;
3127 Jim_IncrRefCount(nameObjPtr);
3128 Jim_IncrRefCount(valObjPtr);
3129 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3130 Jim_DecrRefCount(interp, nameObjPtr);
3131 Jim_DecrRefCount(interp, valObjPtr);
3132 free(namebuf);
3133 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3134 return result;
3137 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3139 struct command_context *context;
3140 struct target *target;
3142 context = Jim_GetAssocData(interp, "context");
3143 if (context == NULL)
3145 LOG_ERROR("mem2array: no command context");
3146 return JIM_ERR;
3148 target = get_current_target(context);
3149 if (target == NULL)
3151 LOG_ERROR("mem2array: no current target");
3152 return JIM_ERR;
3155 return target_mem2array(interp, target, argc-1, argv + 1);
3158 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3160 long l;
3161 uint32_t width;
3162 int len;
3163 uint32_t addr;
3164 uint32_t count;
3165 uint32_t v;
3166 const char *varname;
3167 int n, e, retval;
3168 uint32_t i;
3170 /* argv[1] = name of array to receive the data
3171 * argv[2] = desired width
3172 * argv[3] = memory address
3173 * argv[4] = count of times to read
3175 if (argc != 4) {
3176 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3177 return JIM_ERR;
3179 varname = Jim_GetString(argv[0], &len);
3180 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3182 e = Jim_GetLong(interp, argv[1], &l);
3183 width = l;
3184 if (e != JIM_OK) {
3185 return e;
3188 e = Jim_GetLong(interp, argv[2], &l);
3189 addr = l;
3190 if (e != JIM_OK) {
3191 return e;
3193 e = Jim_GetLong(interp, argv[3], &l);
3194 len = l;
3195 if (e != JIM_OK) {
3196 return e;
3198 switch (width) {
3199 case 8:
3200 width = 1;
3201 break;
3202 case 16:
3203 width = 2;
3204 break;
3205 case 32:
3206 width = 4;
3207 break;
3208 default:
3209 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3210 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3211 return JIM_ERR;
3213 if (len == 0) {
3214 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3215 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3216 return JIM_ERR;
3218 if ((addr + (len * width)) < addr) {
3219 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3220 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3221 return JIM_ERR;
3223 /* absurd transfer size? */
3224 if (len > 65536) {
3225 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3226 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3227 return JIM_ERR;
3230 if ((width == 1) ||
3231 ((width == 2) && ((addr & 1) == 0)) ||
3232 ((width == 4) && ((addr & 3) == 0))) {
3233 /* all is well */
3234 } else {
3235 char buf[100];
3236 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3237 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3238 addr,
3239 width);
3240 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3241 return JIM_ERR;
3244 /* Transfer loop */
3246 /* index counter */
3247 n = 0;
3249 size_t buffersize = 4096;
3250 uint8_t *buffer = malloc(buffersize);
3251 if (buffer == NULL)
3252 return JIM_ERR;
3254 /* assume ok */
3255 e = JIM_OK;
3256 while (len) {
3257 /* Slurp... in buffer size chunks */
3259 count = len; /* in objects.. */
3260 if (count > (buffersize/width)) {
3261 count = (buffersize/width);
3264 retval = target_read_memory(target, addr, width, count, buffer);
3265 if (retval != ERROR_OK) {
3266 /* BOO !*/
3267 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3268 (unsigned int)addr,
3269 (int)width,
3270 (int)count);
3271 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3272 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3273 e = JIM_ERR;
3274 len = 0;
3275 } else {
3276 v = 0; /* shut up gcc */
3277 for (i = 0 ;i < count ;i++, n++) {
3278 switch (width) {
3279 case 4:
3280 v = target_buffer_get_u32(target, &buffer[i*width]);
3281 break;
3282 case 2:
3283 v = target_buffer_get_u16(target, &buffer[i*width]);
3284 break;
3285 case 1:
3286 v = buffer[i] & 0x0ff;
3287 break;
3289 new_int_array_element(interp, varname, n, v);
3291 len -= count;
3295 free(buffer);
3297 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3299 return JIM_OK;
3302 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3304 char *namebuf;
3305 Jim_Obj *nameObjPtr, *valObjPtr;
3306 int result;
3307 long l;
3309 namebuf = alloc_printf("%s(%d)", varname, idx);
3310 if (!namebuf)
3311 return JIM_ERR;
3313 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3314 if (!nameObjPtr)
3316 free(namebuf);
3317 return JIM_ERR;
3320 Jim_IncrRefCount(nameObjPtr);
3321 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3322 Jim_DecrRefCount(interp, nameObjPtr);
3323 free(namebuf);
3324 if (valObjPtr == NULL)
3325 return JIM_ERR;
3327 result = Jim_GetLong(interp, valObjPtr, &l);
3328 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3329 *val = l;
3330 return result;
3333 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3335 struct command_context *context;
3336 struct target *target;
3338 context = Jim_GetAssocData(interp, "context");
3339 if (context == NULL) {
3340 LOG_ERROR("array2mem: no command context");
3341 return JIM_ERR;
3343 target = get_current_target(context);
3344 if (target == NULL) {
3345 LOG_ERROR("array2mem: no current target");
3346 return JIM_ERR;
3349 return target_array2mem(interp,target, argc-1, argv + 1);
3352 static int target_array2mem(Jim_Interp *interp, struct target *target,
3353 int argc, Jim_Obj *const *argv)
3355 long l;
3356 uint32_t width;
3357 int len;
3358 uint32_t addr;
3359 uint32_t count;
3360 uint32_t v;
3361 const char *varname;
3362 int n, e, retval;
3363 uint32_t i;
3365 /* argv[1] = name of array to get the data
3366 * argv[2] = desired width
3367 * argv[3] = memory address
3368 * argv[4] = count to write
3370 if (argc != 4) {
3371 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3372 return JIM_ERR;
3374 varname = Jim_GetString(argv[0], &len);
3375 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3377 e = Jim_GetLong(interp, argv[1], &l);
3378 width = l;
3379 if (e != JIM_OK) {
3380 return e;
3383 e = Jim_GetLong(interp, argv[2], &l);
3384 addr = l;
3385 if (e != JIM_OK) {
3386 return e;
3388 e = Jim_GetLong(interp, argv[3], &l);
3389 len = l;
3390 if (e != JIM_OK) {
3391 return e;
3393 switch (width) {
3394 case 8:
3395 width = 1;
3396 break;
3397 case 16:
3398 width = 2;
3399 break;
3400 case 32:
3401 width = 4;
3402 break;
3403 default:
3404 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3405 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3406 return JIM_ERR;
3408 if (len == 0) {
3409 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3410 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3411 return JIM_ERR;
3413 if ((addr + (len * width)) < addr) {
3414 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3415 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3416 return JIM_ERR;
3418 /* absurd transfer size? */
3419 if (len > 65536) {
3420 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3421 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3422 return JIM_ERR;
3425 if ((width == 1) ||
3426 ((width == 2) && ((addr & 1) == 0)) ||
3427 ((width == 4) && ((addr & 3) == 0))) {
3428 /* all is well */
3429 } else {
3430 char buf[100];
3431 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3432 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3433 (unsigned int)addr,
3434 (int)width);
3435 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3436 return JIM_ERR;
3439 /* Transfer loop */
3441 /* index counter */
3442 n = 0;
3443 /* assume ok */
3444 e = JIM_OK;
3446 size_t buffersize = 4096;
3447 uint8_t *buffer = malloc(buffersize);
3448 if (buffer == NULL)
3449 return JIM_ERR;
3451 while (len) {
3452 /* Slurp... in buffer size chunks */
3454 count = len; /* in objects.. */
3455 if (count > (buffersize/width)) {
3456 count = (buffersize/width);
3459 v = 0; /* shut up gcc */
3460 for (i = 0 ;i < count ;i++, n++) {
3461 get_int_array_element(interp, varname, n, &v);
3462 switch (width) {
3463 case 4:
3464 target_buffer_set_u32(target, &buffer[i*width], v);
3465 break;
3466 case 2:
3467 target_buffer_set_u16(target, &buffer[i*width], v);
3468 break;
3469 case 1:
3470 buffer[i] = v & 0x0ff;
3471 break;
3474 len -= count;
3476 retval = target_write_memory(target, addr, width, count, buffer);
3477 if (retval != ERROR_OK) {
3478 /* BOO !*/
3479 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3480 (unsigned int)addr,
3481 (int)width,
3482 (int)count);
3483 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3484 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3485 e = JIM_ERR;
3486 len = 0;
3490 free(buffer);
3492 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3494 return JIM_OK;
3497 void target_all_handle_event(enum target_event e)
3499 struct target *target;
3501 LOG_DEBUG("**all*targets: event: %d, %s",
3502 (int)e,
3503 Jim_Nvp_value2name_simple(nvp_target_event, e)->name);
3505 target = all_targets;
3506 while (target) {
3507 target_handle_event(target, e);
3508 target = target->next;
3513 /* FIX? should we propagate errors here rather than printing them
3514 * and continuing?
3516 void target_handle_event(struct target *target, enum target_event e)
3518 struct target_event_action *teap;
3520 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3521 if (teap->event == e) {
3522 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3523 target->target_number,
3524 target_name(target),
3525 target_type_name(target),
3527 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3528 Jim_GetString(teap->body, NULL));
3529 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK)
3531 Jim_PrintErrorMessage(teap->interp);
3538 * Returns true only if the target has a handler for the specified event.
3540 bool target_has_event_action(struct target *target, enum target_event event)
3542 struct target_event_action *teap;
3544 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3545 if (teap->event == event)
3546 return true;
3548 return false;
3551 enum target_cfg_param {
3552 TCFG_TYPE,
3553 TCFG_EVENT,
3554 TCFG_WORK_AREA_VIRT,
3555 TCFG_WORK_AREA_PHYS,
3556 TCFG_WORK_AREA_SIZE,
3557 TCFG_WORK_AREA_BACKUP,
3558 TCFG_ENDIAN,
3559 TCFG_VARIANT,
3560 TCFG_CHAIN_POSITION,
3563 static Jim_Nvp nvp_config_opts[] = {
3564 { .name = "-type", .value = TCFG_TYPE },
3565 { .name = "-event", .value = TCFG_EVENT },
3566 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3567 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3568 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3569 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3570 { .name = "-endian" , .value = TCFG_ENDIAN },
3571 { .name = "-variant", .value = TCFG_VARIANT },
3572 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3574 { .name = NULL, .value = -1 }
3577 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3579 Jim_Nvp *n;
3580 Jim_Obj *o;
3581 jim_wide w;
3582 char *cp;
3583 int e;
3585 /* parse config or cget options ... */
3586 while (goi->argc > 0) {
3587 Jim_SetEmptyResult(goi->interp);
3588 /* Jim_GetOpt_Debug(goi); */
3590 if (target->type->target_jim_configure) {
3591 /* target defines a configure function */
3592 /* target gets first dibs on parameters */
3593 e = (*(target->type->target_jim_configure))(target, goi);
3594 if (e == JIM_OK) {
3595 /* more? */
3596 continue;
3598 if (e == JIM_ERR) {
3599 /* An error */
3600 return e;
3602 /* otherwise we 'continue' below */
3604 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3605 if (e != JIM_OK) {
3606 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3607 return e;
3609 switch (n->value) {
3610 case TCFG_TYPE:
3611 /* not setable */
3612 if (goi->isconfigure) {
3613 Jim_SetResult_sprintf(goi->interp,
3614 "not settable: %s", n->name);
3615 return JIM_ERR;
3616 } else {
3617 no_params:
3618 if (goi->argc != 0) {
3619 Jim_WrongNumArgs(goi->interp,
3620 goi->argc, goi->argv,
3621 "NO PARAMS");
3622 return JIM_ERR;
3625 Jim_SetResultString(goi->interp,
3626 target_type_name(target), -1);
3627 /* loop for more */
3628 break;
3629 case TCFG_EVENT:
3630 if (goi->argc == 0) {
3631 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3632 return JIM_ERR;
3635 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3636 if (e != JIM_OK) {
3637 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3638 return e;
3641 if (goi->isconfigure) {
3642 if (goi->argc != 1) {
3643 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3644 return JIM_ERR;
3646 } else {
3647 if (goi->argc != 0) {
3648 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3649 return JIM_ERR;
3654 struct target_event_action *teap;
3656 teap = target->event_action;
3657 /* replace existing? */
3658 while (teap) {
3659 if (teap->event == (enum target_event)n->value) {
3660 break;
3662 teap = teap->next;
3665 if (goi->isconfigure) {
3666 bool replace = true;
3667 if (teap == NULL) {
3668 /* create new */
3669 teap = calloc(1, sizeof(*teap));
3670 replace = false;
3672 teap->event = n->value;
3673 teap->interp = goi->interp;
3674 Jim_GetOpt_Obj(goi, &o);
3675 if (teap->body) {
3676 Jim_DecrRefCount(teap->interp, teap->body);
3678 teap->body = Jim_DuplicateObj(goi->interp, o);
3680 * FIXME:
3681 * Tcl/TK - "tk events" have a nice feature.
3682 * See the "BIND" command.
3683 * We should support that here.
3684 * You can specify %X and %Y in the event code.
3685 * The idea is: %T - target name.
3686 * The idea is: %N - target number
3687 * The idea is: %E - event name.
3689 Jim_IncrRefCount(teap->body);
3691 if (!replace)
3693 /* add to head of event list */
3694 teap->next = target->event_action;
3695 target->event_action = teap;
3697 Jim_SetEmptyResult(goi->interp);
3698 } else {
3699 /* get */
3700 if (teap == NULL) {
3701 Jim_SetEmptyResult(goi->interp);
3702 } else {
3703 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3707 /* loop for more */
3708 break;
3710 case TCFG_WORK_AREA_VIRT:
3711 if (goi->isconfigure) {
3712 target_free_all_working_areas(target);
3713 e = Jim_GetOpt_Wide(goi, &w);
3714 if (e != JIM_OK) {
3715 return e;
3717 target->working_area_virt = w;
3718 target->working_area_virt_spec = true;
3719 } else {
3720 if (goi->argc != 0) {
3721 goto no_params;
3724 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3725 /* loop for more */
3726 break;
3728 case TCFG_WORK_AREA_PHYS:
3729 if (goi->isconfigure) {
3730 target_free_all_working_areas(target);
3731 e = Jim_GetOpt_Wide(goi, &w);
3732 if (e != JIM_OK) {
3733 return e;
3735 target->working_area_phys = w;
3736 target->working_area_phys_spec = true;
3737 } else {
3738 if (goi->argc != 0) {
3739 goto no_params;
3742 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3743 /* loop for more */
3744 break;
3746 case TCFG_WORK_AREA_SIZE:
3747 if (goi->isconfigure) {
3748 target_free_all_working_areas(target);
3749 e = Jim_GetOpt_Wide(goi, &w);
3750 if (e != JIM_OK) {
3751 return e;
3753 target->working_area_size = w;
3754 } else {
3755 if (goi->argc != 0) {
3756 goto no_params;
3759 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3760 /* loop for more */
3761 break;
3763 case TCFG_WORK_AREA_BACKUP:
3764 if (goi->isconfigure) {
3765 target_free_all_working_areas(target);
3766 e = Jim_GetOpt_Wide(goi, &w);
3767 if (e != JIM_OK) {
3768 return e;
3770 /* make this exactly 1 or 0 */
3771 target->backup_working_area = (!!w);
3772 } else {
3773 if (goi->argc != 0) {
3774 goto no_params;
3777 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3778 /* loop for more e*/
3779 break;
3781 case TCFG_ENDIAN:
3782 if (goi->isconfigure) {
3783 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3784 if (e != JIM_OK) {
3785 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3786 return e;
3788 target->endianness = n->value;
3789 } else {
3790 if (goi->argc != 0) {
3791 goto no_params;
3794 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3795 if (n->name == NULL) {
3796 target->endianness = TARGET_LITTLE_ENDIAN;
3797 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3799 Jim_SetResultString(goi->interp, n->name, -1);
3800 /* loop for more */
3801 break;
3803 case TCFG_VARIANT:
3804 if (goi->isconfigure) {
3805 if (goi->argc < 1) {
3806 Jim_SetResult_sprintf(goi->interp,
3807 "%s ?STRING?",
3808 n->name);
3809 return JIM_ERR;
3811 if (target->variant) {
3812 free((void *)(target->variant));
3814 e = Jim_GetOpt_String(goi, &cp, NULL);
3815 target->variant = strdup(cp);
3816 } else {
3817 if (goi->argc != 0) {
3818 goto no_params;
3821 Jim_SetResultString(goi->interp, target->variant,-1);
3822 /* loop for more */
3823 break;
3824 case TCFG_CHAIN_POSITION:
3825 if (goi->isconfigure) {
3826 Jim_Obj *o;
3827 struct jtag_tap *tap;
3828 target_free_all_working_areas(target);
3829 e = Jim_GetOpt_Obj(goi, &o);
3830 if (e != JIM_OK) {
3831 return e;
3833 tap = jtag_tap_by_jim_obj(goi->interp, o);
3834 if (tap == NULL) {
3835 return JIM_ERR;
3837 /* make this exactly 1 or 0 */
3838 target->tap = tap;
3839 } else {
3840 if (goi->argc != 0) {
3841 goto no_params;
3844 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
3845 /* loop for more e*/
3846 break;
3848 } /* while (goi->argc) */
3851 /* done - we return */
3852 return JIM_OK;
3855 static int
3856 jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3858 Jim_GetOptInfo goi;
3860 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3861 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
3862 int need_args = 1 + goi.isconfigure;
3863 if (goi.argc < need_args)
3865 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
3866 goi.isconfigure
3867 ? "missing: -option VALUE ..."
3868 : "missing: -option ...");
3869 return JIM_ERR;
3871 struct target *target = Jim_CmdPrivData(goi.interp);
3872 return target_configure(&goi, target);
3875 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3877 const char *cmd_name = Jim_GetString(argv[0], NULL);
3879 Jim_GetOptInfo goi;
3880 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3882 if (goi.argc != 2 && goi.argc != 3)
3884 Jim_SetResult_sprintf(goi.interp,
3885 "usage: %s <address> <data> [<count>]", cmd_name);
3886 return JIM_ERR;
3889 jim_wide a;
3890 int e = Jim_GetOpt_Wide(&goi, &a);
3891 if (e != JIM_OK)
3892 return e;
3894 jim_wide b;
3895 e = Jim_GetOpt_Wide(&goi, &b);
3896 if (e != JIM_OK)
3897 return e;
3899 jim_wide c = 1;
3900 if (goi.argc == 3)
3902 e = Jim_GetOpt_Wide(&goi, &c);
3903 if (e != JIM_OK)
3904 return e;
3907 struct target *target = Jim_CmdPrivData(goi.interp);
3908 uint8_t target_buf[32];
3909 if (strcasecmp(cmd_name, "mww") == 0) {
3910 target_buffer_set_u32(target, target_buf, b);
3911 b = 4;
3913 else if (strcasecmp(cmd_name, "mwh") == 0) {
3914 target_buffer_set_u16(target, target_buf, b);
3915 b = 2;
3917 else if (strcasecmp(cmd_name, "mwb") == 0) {
3918 target_buffer_set_u8(target, target_buf, b);
3919 b = 1;
3920 } else {
3921 LOG_ERROR("command '%s' unknown: ", cmd_name);
3922 return JIM_ERR;
3925 for (jim_wide x = 0; x < c; x++)
3927 e = target_write_memory(target, a, b, 1, target_buf);
3928 if (e != ERROR_OK)
3930 Jim_SetResult_sprintf(interp,
3931 "Error writing @ 0x%08x: %d\n", (int)(a), e);
3932 return JIM_ERR;
3934 /* b = width */
3935 a = a + b;
3937 return JIM_OK;
3940 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3942 const char *cmd_name = Jim_GetString(argv[0], NULL);
3944 Jim_GetOptInfo goi;
3945 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3947 if ((goi.argc == 2) || (goi.argc == 3))
3949 Jim_SetResult_sprintf(goi.interp,
3950 "usage: %s <address> [<count>]", cmd_name);
3951 return JIM_ERR;
3954 jim_wide a;
3955 int e = Jim_GetOpt_Wide(&goi, &a);
3956 if (e != JIM_OK) {
3957 return JIM_ERR;
3959 jim_wide c;
3960 if (goi.argc) {
3961 e = Jim_GetOpt_Wide(&goi, &c);
3962 if (e != JIM_OK) {
3963 return JIM_ERR;
3965 } else {
3966 c = 1;
3968 jim_wide b = 1; /* shut up gcc */
3969 if (strcasecmp(cmd_name, "mdw") == 0)
3970 b = 4;
3971 else if (strcasecmp(cmd_name, "mdh") == 0)
3972 b = 2;
3973 else if (strcasecmp(cmd_name, "mdb") == 0)
3974 b = 1;
3975 else {
3976 LOG_ERROR("command '%s' unknown: ", cmd_name);
3977 return JIM_ERR;
3980 /* convert count to "bytes" */
3981 c = c * b;
3983 struct target *target = Jim_CmdPrivData(goi.interp);
3984 uint8_t target_buf[32];
3985 jim_wide x, y, z;
3986 while (c > 0) {
3987 y = c;
3988 if (y > 16) {
3989 y = 16;
3991 e = target_read_memory(target, a, b, y / b, target_buf);
3992 if (e != ERROR_OK) {
3993 Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
3994 return JIM_ERR;
3997 Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
3998 switch (b) {
3999 case 4:
4000 for (x = 0; x < 16 && x < y; x += 4)
4002 z = target_buffer_get_u32(target, &(target_buf[ x * 4 ]));
4003 Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
4005 for (; (x < 16) ; x += 4) {
4006 Jim_fprintf(interp, interp->cookie_stdout, " ");
4008 break;
4009 case 2:
4010 for (x = 0; x < 16 && x < y; x += 2)
4012 z = target_buffer_get_u16(target, &(target_buf[ x * 2 ]));
4013 Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
4015 for (; (x < 16) ; x += 2) {
4016 Jim_fprintf(interp, interp->cookie_stdout, " ");
4018 break;
4019 case 1:
4020 default:
4021 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4022 z = target_buffer_get_u8(target, &(target_buf[ x * 4 ]));
4023 Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
4025 for (; (x < 16) ; x += 1) {
4026 Jim_fprintf(interp, interp->cookie_stdout, " ");
4028 break;
4030 /* ascii-ify the bytes */
4031 for (x = 0 ; x < y ; x++) {
4032 if ((target_buf[x] >= 0x20) &&
4033 (target_buf[x] <= 0x7e)) {
4034 /* good */
4035 } else {
4036 /* smack it */
4037 target_buf[x] = '.';
4040 /* space pad */
4041 while (x < 16) {
4042 target_buf[x] = ' ';
4043 x++;
4045 /* terminate */
4046 target_buf[16] = 0;
4047 /* print - with a newline */
4048 Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
4049 /* NEXT... */
4050 c -= 16;
4051 a += 16;
4053 return JIM_OK;
4056 static int jim_target_mem2array(Jim_Interp *interp,
4057 int argc, Jim_Obj *const *argv)
4059 struct target *target = Jim_CmdPrivData(interp);
4060 return target_mem2array(interp, target, argc - 1, argv + 1);
4063 static int jim_target_array2mem(Jim_Interp *interp,
4064 int argc, Jim_Obj *const *argv)
4066 struct target *target = Jim_CmdPrivData(interp);
4067 return target_array2mem(interp, target, argc - 1, argv + 1);
4070 static int jim_target_tap_disabled(Jim_Interp *interp)
4072 Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4073 return JIM_ERR;
4076 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4078 if (argc != 1)
4080 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4081 return JIM_ERR;
4083 struct target *target = Jim_CmdPrivData(interp);
4084 if (!target->tap->enabled)
4085 return jim_target_tap_disabled(interp);
4087 int e = target->type->examine(target);
4088 if (e != ERROR_OK)
4090 Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
4091 return JIM_ERR;
4093 return JIM_OK;
4096 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4098 if (argc != 1)
4100 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4101 return JIM_ERR;
4103 struct target *target = Jim_CmdPrivData(interp);
4105 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4106 return JIM_ERR;
4108 return JIM_OK;
4111 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4113 if (argc != 1)
4115 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4116 return JIM_ERR;
4118 struct target *target = Jim_CmdPrivData(interp);
4119 if (!target->tap->enabled)
4120 return jim_target_tap_disabled(interp);
4122 int e;
4123 if (!(target_was_examined(target))) {
4124 e = ERROR_TARGET_NOT_EXAMINED;
4125 } else {
4126 e = target->type->poll(target);
4128 if (e != ERROR_OK)
4130 Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4131 return JIM_ERR;
4133 return JIM_OK;
4136 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4138 Jim_GetOptInfo goi;
4139 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4141 if (goi.argc != 2)
4143 Jim_WrongNumArgs(interp, 0, argv,
4144 "([tT]|[fF]|assert|deassert) BOOL");
4145 return JIM_ERR;
4148 Jim_Nvp *n;
4149 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4150 if (e != JIM_OK)
4152 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4153 return e;
4155 /* the halt or not param */
4156 jim_wide a;
4157 e = Jim_GetOpt_Wide(&goi, &a);
4158 if (e != JIM_OK)
4159 return e;
4161 struct target *target = Jim_CmdPrivData(goi.interp);
4162 if (!target->tap->enabled)
4163 return jim_target_tap_disabled(interp);
4164 if (!(target_was_examined(target)))
4166 LOG_ERROR("Target not examined yet");
4167 return ERROR_TARGET_NOT_EXAMINED;
4169 if (!target->type->assert_reset || !target->type->deassert_reset)
4171 Jim_SetResult_sprintf(interp,
4172 "No target-specific reset for %s",
4173 target_name(target));
4174 return JIM_ERR;
4176 /* determine if we should halt or not. */
4177 target->reset_halt = !!a;
4178 /* When this happens - all workareas are invalid. */
4179 target_free_all_working_areas_restore(target, 0);
4181 /* do the assert */
4182 if (n->value == NVP_ASSERT) {
4183 e = target->type->assert_reset(target);
4184 } else {
4185 e = target->type->deassert_reset(target);
4187 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4190 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4192 if (argc != 1) {
4193 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4194 return JIM_ERR;
4196 struct target *target = Jim_CmdPrivData(interp);
4197 if (!target->tap->enabled)
4198 return jim_target_tap_disabled(interp);
4199 int e = target->type->halt(target);
4200 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4203 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4205 Jim_GetOptInfo goi;
4206 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4208 /* params: <name> statename timeoutmsecs */
4209 if (goi.argc != 2)
4211 const char *cmd_name = Jim_GetString(argv[0], NULL);
4212 Jim_SetResult_sprintf(goi.interp,
4213 "%s <state_name> <timeout_in_msec>", cmd_name);
4214 return JIM_ERR;
4217 Jim_Nvp *n;
4218 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4219 if (e != JIM_OK) {
4220 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4221 return e;
4223 jim_wide a;
4224 e = Jim_GetOpt_Wide(&goi, &a);
4225 if (e != JIM_OK) {
4226 return e;
4228 struct target *target = Jim_CmdPrivData(interp);
4229 if (!target->tap->enabled)
4230 return jim_target_tap_disabled(interp);
4232 e = target_wait_state(target, n->value, a);
4233 if (e != ERROR_OK)
4235 Jim_SetResult_sprintf(goi.interp,
4236 "target: %s wait %s fails (%d) %s",
4237 target_name(target), n->name,
4238 e, target_strerror_safe(e));
4239 return JIM_ERR;
4241 return JIM_OK;
4243 /* List for human, Events defined for this target.
4244 * scripts/programs should use 'name cget -event NAME'
4246 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4248 struct command_context *cmd_ctx = Jim_GetAssocData(interp, "context");
4249 struct target *target = Jim_CmdPrivData(interp);
4250 struct target_event_action *teap = target->event_action;
4251 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4252 target->target_number,
4253 target_name(target));
4254 command_print(cmd_ctx, "%-25s | Body", "Event");
4255 command_print(cmd_ctx, "------------------------- | "
4256 "----------------------------------------");
4257 while (teap)
4259 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4260 command_print(cmd_ctx, "%-25s | %s",
4261 opt->name, Jim_GetString(teap->body, NULL));
4262 teap = teap->next;
4264 command_print(cmd_ctx, "***END***");
4265 return JIM_OK;
4267 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4269 if (argc != 1)
4271 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4272 return JIM_ERR;
4274 struct target *target = Jim_CmdPrivData(interp);
4275 Jim_SetResultString(interp, target_state_name(target), -1);
4276 return JIM_OK;
4278 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4280 Jim_GetOptInfo goi;
4281 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4282 if (goi.argc != 1)
4284 const char *cmd_name = Jim_GetString(argv[0], NULL);
4285 Jim_SetResult_sprintf(goi.interp, "%s <eventname>", cmd_name);
4286 return JIM_ERR;
4288 Jim_Nvp *n;
4289 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4290 if (e != JIM_OK)
4292 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4293 return e;
4295 struct target *target = Jim_CmdPrivData(interp);
4296 target_handle_event(target, n->value);
4297 return JIM_OK;
4300 static const struct command_registration target_instance_command_handlers[] = {
4302 .name = "configure",
4303 .mode = COMMAND_CONFIG,
4304 .jim_handler = jim_target_configure,
4305 .help = "configure a new target for use",
4306 .usage = "[target_attribute ...]",
4309 .name = "cget",
4310 .mode = COMMAND_ANY,
4311 .jim_handler = jim_target_configure,
4312 .help = "returns the specified target attribute",
4313 .usage = "target_attribute",
4316 .name = "mww",
4317 .mode = COMMAND_EXEC,
4318 .jim_handler = jim_target_mw,
4319 .help = "Write 32-bit word(s) to target memory",
4320 .usage = "address data [count]",
4323 .name = "mwh",
4324 .mode = COMMAND_EXEC,
4325 .jim_handler = jim_target_mw,
4326 .help = "Write 16-bit half-word(s) to target memory",
4327 .usage = "address data [count]",
4330 .name = "mwb",
4331 .mode = COMMAND_EXEC,
4332 .jim_handler = jim_target_mw,
4333 .help = "Write byte(s) to target memory",
4334 .usage = "address data [count]",
4337 .name = "mdw",
4338 .mode = COMMAND_EXEC,
4339 .jim_handler = jim_target_md,
4340 .help = "Display target memory as 32-bit words",
4341 .usage = "address [count]",
4344 .name = "mdh",
4345 .mode = COMMAND_EXEC,
4346 .jim_handler = jim_target_md,
4347 .help = "Display target memory as 16-bit half-words",
4348 .usage = "address [count]",
4351 .name = "mdb",
4352 .mode = COMMAND_EXEC,
4353 .jim_handler = jim_target_md,
4354 .help = "Display target memory as 8-bit bytes",
4355 .usage = "address [count]",
4358 .name = "array2mem",
4359 .mode = COMMAND_EXEC,
4360 .jim_handler = jim_target_array2mem,
4361 .help = "Writes Tcl array of 8/16/32 bit numbers "
4362 "to target memory",
4363 .usage = "arrayname bitwidth address count",
4366 .name = "mem2array",
4367 .mode = COMMAND_EXEC,
4368 .jim_handler = jim_target_mem2array,
4369 .help = "Loads Tcl array of 8/16/32 bit numbers "
4370 "from target memory",
4371 .usage = "arrayname bitwidth address count",
4374 .name = "eventlist",
4375 .mode = COMMAND_EXEC,
4376 .jim_handler = jim_target_event_list,
4377 .help = "displays a table of events defined for this target",
4380 .name = "curstate",
4381 .mode = COMMAND_EXEC,
4382 .jim_handler = jim_target_current_state,
4383 .help = "displays the current state of this target",
4386 .name = "arp_examine",
4387 .mode = COMMAND_EXEC,
4388 .jim_handler = jim_target_examine,
4389 .help = "used internally for reset processing",
4392 .name = "arp_halt_gdb",
4393 .mode = COMMAND_EXEC,
4394 .jim_handler = jim_target_halt_gdb,
4395 .help = "used internally for reset processing to halt GDB",
4398 .name = "arp_poll",
4399 .mode = COMMAND_EXEC,
4400 .jim_handler = jim_target_poll,
4401 .help = "used internally for reset processing",
4404 .name = "arp_reset",
4405 .mode = COMMAND_EXEC,
4406 .jim_handler = jim_target_reset,
4407 .help = "used internally for reset processing",
4410 .name = "arp_halt",
4411 .mode = COMMAND_EXEC,
4412 .jim_handler = jim_target_halt,
4413 .help = "used internally for reset processing",
4416 .name = "arp_waitstate",
4417 .mode = COMMAND_EXEC,
4418 .jim_handler = jim_target_wait_state,
4419 .help = "used internally for reset processing",
4422 .name = "invoke-event",
4423 .mode = COMMAND_EXEC,
4424 .jim_handler = jim_target_invoke_event,
4425 .help = "invoke handler for specified event",
4426 .usage = "event_name",
4428 COMMAND_REGISTRATION_DONE
4431 static int target_create(Jim_GetOptInfo *goi)
4433 Jim_Obj *new_cmd;
4434 Jim_Cmd *cmd;
4435 const char *cp;
4436 char *cp2;
4437 int e;
4438 int x;
4439 struct target *target;
4440 struct command_context *cmd_ctx;
4442 cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4443 if (goi->argc < 3) {
4444 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4445 return JIM_ERR;
4448 /* COMMAND */
4449 Jim_GetOpt_Obj(goi, &new_cmd);
4450 /* does this command exist? */
4451 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4452 if (cmd) {
4453 cp = Jim_GetString(new_cmd, NULL);
4454 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4455 return JIM_ERR;
4458 /* TYPE */
4459 e = Jim_GetOpt_String(goi, &cp2, NULL);
4460 cp = cp2;
4461 /* now does target type exist */
4462 for (x = 0 ; target_types[x] ; x++) {
4463 if (0 == strcmp(cp, target_types[x]->name)) {
4464 /* found */
4465 break;
4468 if (target_types[x] == NULL) {
4469 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4470 for (x = 0 ; target_types[x] ; x++) {
4471 if (target_types[x + 1]) {
4472 Jim_AppendStrings(goi->interp,
4473 Jim_GetResult(goi->interp),
4474 target_types[x]->name,
4475 ", ", NULL);
4476 } else {
4477 Jim_AppendStrings(goi->interp,
4478 Jim_GetResult(goi->interp),
4479 " or ",
4480 target_types[x]->name,NULL);
4483 return JIM_ERR;
4486 /* Create it */
4487 target = calloc(1,sizeof(struct target));
4488 /* set target number */
4489 target->target_number = new_target_number();
4491 /* allocate memory for each unique target type */
4492 target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4494 memcpy(target->type, target_types[x], sizeof(struct target_type));
4496 /* will be set by "-endian" */
4497 target->endianness = TARGET_ENDIAN_UNKNOWN;
4499 target->working_area = 0x0;
4500 target->working_area_size = 0x0;
4501 target->working_areas = NULL;
4502 target->backup_working_area = 0;
4504 target->state = TARGET_UNKNOWN;
4505 target->debug_reason = DBG_REASON_UNDEFINED;
4506 target->reg_cache = NULL;
4507 target->breakpoints = NULL;
4508 target->watchpoints = NULL;
4509 target->next = NULL;
4510 target->arch_info = NULL;
4512 target->display = 1;
4514 target->halt_issued = false;
4516 /* initialize trace information */
4517 target->trace_info = malloc(sizeof(struct trace));
4518 target->trace_info->num_trace_points = 0;
4519 target->trace_info->trace_points_size = 0;
4520 target->trace_info->trace_points = NULL;
4521 target->trace_info->trace_history_size = 0;
4522 target->trace_info->trace_history = NULL;
4523 target->trace_info->trace_history_pos = 0;
4524 target->trace_info->trace_history_overflowed = 0;
4526 target->dbgmsg = NULL;
4527 target->dbg_msg_enabled = 0;
4529 target->endianness = TARGET_ENDIAN_UNKNOWN;
4531 /* Do the rest as "configure" options */
4532 goi->isconfigure = 1;
4533 e = target_configure(goi, target);
4535 if (target->tap == NULL)
4537 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4538 e = JIM_ERR;
4541 if (e != JIM_OK) {
4542 free(target->type);
4543 free(target);
4544 return e;
4547 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4548 /* default endian to little if not specified */
4549 target->endianness = TARGET_LITTLE_ENDIAN;
4552 /* incase variant is not set */
4553 if (!target->variant)
4554 target->variant = strdup("");
4556 cp = Jim_GetString(new_cmd, NULL);
4557 target->cmd_name = strdup(cp);
4559 /* create the target specific commands */
4560 if (target->type->commands) {
4561 e = register_commands(cmd_ctx, NULL, target->type->commands);
4562 if (ERROR_OK != e)
4563 LOG_ERROR("unable to register '%s' commands", cp);
4565 if (target->type->target_create) {
4566 (*(target->type->target_create))(target, goi->interp);
4569 /* append to end of list */
4571 struct target **tpp;
4572 tpp = &(all_targets);
4573 while (*tpp) {
4574 tpp = &((*tpp)->next);
4576 *tpp = target;
4579 /* now - create the new target name command */
4580 const const struct command_registration target_subcommands[] = {
4582 .chain = target_instance_command_handlers,
4585 .chain = target->type->commands,
4587 COMMAND_REGISTRATION_DONE
4589 const const struct command_registration target_commands[] = {
4591 .name = cp,
4592 .mode = COMMAND_ANY,
4593 .help = "target command group",
4594 .chain = target_subcommands,
4596 COMMAND_REGISTRATION_DONE
4598 e = register_commands(cmd_ctx, NULL, target_commands);
4599 if (ERROR_OK != e)
4600 return JIM_ERR;
4602 struct command *c = command_find_in_context(cmd_ctx, cp);
4603 assert(c);
4604 command_set_handler_data(c, target);
4606 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
4609 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4611 if (argc != 1)
4613 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4614 return JIM_ERR;
4616 struct command_context *cmd_ctx = Jim_GetAssocData(interp, "context");
4617 Jim_SetResultString(interp, get_current_target(cmd_ctx)->cmd_name, -1);
4618 return JIM_OK;
4621 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4623 if (argc != 1)
4625 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4626 return JIM_ERR;
4628 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4629 for (unsigned x = 0; NULL != target_types[x]; x++)
4631 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4632 Jim_NewStringObj(interp, target_types[x]->name, -1));
4634 return JIM_OK;
4637 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4639 if (argc != 1)
4641 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4642 return JIM_ERR;
4644 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4645 struct target *target = all_targets;
4646 while (target)
4648 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4649 Jim_NewStringObj(interp, target_name(target), -1));
4650 target = target->next;
4652 return JIM_OK;
4655 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4657 Jim_GetOptInfo goi;
4658 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4659 if (goi.argc < 3)
4661 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4662 "<name> <target_type> [<target_options> ...]");
4663 return JIM_ERR;
4665 return target_create(&goi);
4668 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4670 Jim_GetOptInfo goi;
4671 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4673 /* It's OK to remove this mechanism sometime after August 2010 or so */
4674 LOG_WARNING("don't use numbers as target identifiers; use names");
4675 if (goi.argc != 1)
4677 Jim_SetResult_sprintf(goi.interp, "usage: target number <number>");
4678 return JIM_ERR;
4680 jim_wide w;
4681 int e = Jim_GetOpt_Wide(&goi, &w);
4682 if (e != JIM_OK)
4683 return JIM_ERR;
4685 struct target *target;
4686 for (target = all_targets; NULL != target; target = target->next)
4688 if (target->target_number != w)
4689 continue;
4691 Jim_SetResultString(goi.interp, target_name(target), -1);
4692 return JIM_OK;
4694 Jim_SetResult_sprintf(goi.interp,
4695 "Target: number %d does not exist", (int)(w));
4696 return JIM_ERR;
4699 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4701 if (argc != 1)
4703 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
4704 return JIM_ERR;
4706 unsigned count = 0;
4707 struct target *target = all_targets;
4708 while (NULL != target)
4710 target = target->next;
4711 count++;
4713 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
4714 return JIM_OK;
4717 static const struct command_registration target_subcommand_handlers[] = {
4719 .name = "init",
4720 .mode = COMMAND_CONFIG,
4721 .handler = handle_target_init_command,
4722 .help = "initialize targets",
4725 .name = "create",
4726 /* REVISIT this should be COMMAND_CONFIG ... */
4727 .mode = COMMAND_ANY,
4728 .jim_handler = jim_target_create,
4729 .usage = "name type '-chain-position' name [options ...]",
4730 .help = "Creates and selects a new target",
4733 .name = "current",
4734 .mode = COMMAND_ANY,
4735 .jim_handler = jim_target_current,
4736 .help = "Returns the currently selected target",
4739 .name = "types",
4740 .mode = COMMAND_ANY,
4741 .jim_handler = jim_target_types,
4742 .help = "Returns the available target types as "
4743 "a list of strings",
4746 .name = "names",
4747 .mode = COMMAND_ANY,
4748 .jim_handler = jim_target_names,
4749 .help = "Returns the names of all targets as a list of strings",
4752 .name = "number",
4753 .mode = COMMAND_ANY,
4754 .jim_handler = jim_target_number,
4755 .usage = "number",
4756 .help = "Returns the name of the numbered target "
4757 "(DEPRECATED)",
4760 .name = "count",
4761 .mode = COMMAND_ANY,
4762 .jim_handler = jim_target_count,
4763 .help = "Returns the number of targets as an integer "
4764 "(DEPRECATED)",
4766 COMMAND_REGISTRATION_DONE
4769 struct FastLoad
4771 uint32_t address;
4772 uint8_t *data;
4773 int length;
4777 static int fastload_num;
4778 static struct FastLoad *fastload;
4780 static void free_fastload(void)
4782 if (fastload != NULL)
4784 int i;
4785 for (i = 0; i < fastload_num; i++)
4787 if (fastload[i].data)
4788 free(fastload[i].data);
4790 free(fastload);
4791 fastload = NULL;
4798 COMMAND_HANDLER(handle_fast_load_image_command)
4800 uint8_t *buffer;
4801 size_t buf_cnt;
4802 uint32_t image_size;
4803 uint32_t min_address = 0;
4804 uint32_t max_address = 0xffffffff;
4805 int i;
4807 struct image image;
4809 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
4810 &image, &min_address, &max_address);
4811 if (ERROR_OK != retval)
4812 return retval;
4814 struct duration bench;
4815 duration_start(&bench);
4817 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
4819 return ERROR_OK;
4822 image_size = 0x0;
4823 retval = ERROR_OK;
4824 fastload_num = image.num_sections;
4825 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4826 if (fastload == NULL)
4828 image_close(&image);
4829 return ERROR_FAIL;
4831 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4832 for (i = 0; i < image.num_sections; i++)
4834 buffer = malloc(image.sections[i].size);
4835 if (buffer == NULL)
4837 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
4838 (int)(image.sections[i].size));
4839 break;
4842 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4844 free(buffer);
4845 break;
4848 uint32_t offset = 0;
4849 uint32_t length = buf_cnt;
4852 /* DANGER!!! beware of unsigned comparision here!!! */
4854 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4855 (image.sections[i].base_address < max_address))
4857 if (image.sections[i].base_address < min_address)
4859 /* clip addresses below */
4860 offset += min_address-image.sections[i].base_address;
4861 length -= offset;
4864 if (image.sections[i].base_address + buf_cnt > max_address)
4866 length -= (image.sections[i].base_address + buf_cnt)-max_address;
4869 fastload[i].address = image.sections[i].base_address + offset;
4870 fastload[i].data = malloc(length);
4871 if (fastload[i].data == NULL)
4873 free(buffer);
4874 break;
4876 memcpy(fastload[i].data, buffer + offset, length);
4877 fastload[i].length = length;
4879 image_size += length;
4880 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
4881 (unsigned int)length,
4882 ((unsigned int)(image.sections[i].base_address + offset)));
4885 free(buffer);
4888 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
4890 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
4891 "in %fs (%0.3f kb/s)", image_size,
4892 duration_elapsed(&bench), duration_kbps(&bench, image_size));
4894 command_print(CMD_CTX,
4895 "WARNING: image has not been loaded to target!"
4896 "You can issue a 'fast_load' to finish loading.");
4899 image_close(&image);
4901 if (retval != ERROR_OK)
4903 free_fastload();
4906 return retval;
4909 COMMAND_HANDLER(handle_fast_load_command)
4911 if (CMD_ARGC > 0)
4912 return ERROR_COMMAND_SYNTAX_ERROR;
4913 if (fastload == NULL)
4915 LOG_ERROR("No image in memory");
4916 return ERROR_FAIL;
4918 int i;
4919 int ms = timeval_ms();
4920 int size = 0;
4921 int retval = ERROR_OK;
4922 for (i = 0; i < fastload_num;i++)
4924 struct target *target = get_current_target(CMD_CTX);
4925 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
4926 (unsigned int)(fastload[i].address),
4927 (unsigned int)(fastload[i].length));
4928 if (retval == ERROR_OK)
4930 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
4932 size += fastload[i].length;
4934 int after = timeval_ms();
4935 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
4936 return retval;
4939 static const struct command_registration target_command_handlers[] = {
4941 .name = "targets",
4942 .handler = handle_targets_command,
4943 .mode = COMMAND_ANY,
4944 .help = "change current default target (one parameter) "
4945 "or prints table of all targets (no parameters)",
4946 .usage = "[target]",
4949 .name = "target",
4950 .mode = COMMAND_CONFIG,
4951 .help = "configure target",
4953 .chain = target_subcommand_handlers,
4955 COMMAND_REGISTRATION_DONE
4958 int target_register_commands(struct command_context *cmd_ctx)
4960 return register_commands(cmd_ctx, NULL, target_command_handlers);
4963 static bool target_reset_nag = true;
4965 bool get_target_reset_nag(void)
4967 return target_reset_nag;
4970 COMMAND_HANDLER(handle_target_reset_nag)
4972 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
4973 &target_reset_nag, "Nag after each reset about options to improve "
4974 "performance");
4977 static const struct command_registration target_exec_command_handlers[] = {
4979 .name = "fast_load_image",
4980 .handler = handle_fast_load_image_command,
4981 .mode = COMMAND_ANY,
4982 .help = "Load image into server memory for later use by "
4983 "fast_load; primarily for profiling",
4984 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
4985 "[min_address [max_length]]",
4988 .name = "fast_load",
4989 .handler = handle_fast_load_command,
4990 .mode = COMMAND_EXEC,
4991 .help = "loads active fast load image to current target "
4992 "- mainly for profiling purposes",
4995 .name = "profile",
4996 .handler = handle_profile_command,
4997 .mode = COMMAND_EXEC,
4998 .help = "profiling samples the CPU PC",
5000 /** @todo don't register virt2phys() unless target supports it */
5002 .name = "virt2phys",
5003 .handler = handle_virt2phys_command,
5004 .mode = COMMAND_ANY,
5005 .help = "translate a virtual address into a physical address",
5006 .usage = "virtual_address",
5009 .name = "reg",
5010 .handler = handle_reg_command,
5011 .mode = COMMAND_EXEC,
5012 .help = "display or set a register; with no arguments, "
5013 "displays all registers and their values",
5014 .usage = "[(register_name|register_number) [value]]",
5017 .name = "poll",
5018 .handler = handle_poll_command,
5019 .mode = COMMAND_EXEC,
5020 .help = "poll target state; or reconfigure background polling",
5021 .usage = "['on'|'off']",
5024 .name = "wait_halt",
5025 .handler = handle_wait_halt_command,
5026 .mode = COMMAND_EXEC,
5027 .help = "wait up to the specified number of milliseconds "
5028 "(default 5) for a previously requested halt",
5029 .usage = "[milliseconds]",
5032 .name = "halt",
5033 .handler = handle_halt_command,
5034 .mode = COMMAND_EXEC,
5035 .help = "request target to halt, then wait up to the specified"
5036 "number of milliseconds (default 5) for it to complete",
5037 .usage = "[milliseconds]",
5040 .name = "resume",
5041 .handler = handle_resume_command,
5042 .mode = COMMAND_EXEC,
5043 .help = "resume target execution from current PC or address",
5044 .usage = "[address]",
5047 .name = "reset",
5048 .handler = handle_reset_command,
5049 .mode = COMMAND_EXEC,
5050 .usage = "[run|halt|init]",
5051 .help = "Reset all targets into the specified mode."
5052 "Default reset mode is run, if not given.",
5055 .name = "soft_reset_halt",
5056 .handler = handle_soft_reset_halt_command,
5057 .mode = COMMAND_EXEC,
5058 .help = "halt the target and do a soft reset",
5061 .name = "step",
5062 .handler = handle_step_command,
5063 .mode = COMMAND_EXEC,
5064 .help = "step one instruction from current PC or address",
5065 .usage = "[address]",
5068 .name = "mdw",
5069 .handler = handle_md_command,
5070 .mode = COMMAND_EXEC,
5071 .help = "display memory words",
5072 .usage = "['phys'] address [count]",
5075 .name = "mdh",
5076 .handler = handle_md_command,
5077 .mode = COMMAND_EXEC,
5078 .help = "display memory half-words",
5079 .usage = "['phys'] address [count]",
5082 .name = "mdb",
5083 .handler = handle_md_command,
5084 .mode = COMMAND_EXEC,
5085 .help = "display memory bytes",
5086 .usage = "['phys'] address [count]",
5089 .name = "mww",
5090 .handler = handle_mw_command,
5091 .mode = COMMAND_EXEC,
5092 .help = "write memory word",
5093 .usage = "['phys'] address value [count]",
5096 .name = "mwh",
5097 .handler = handle_mw_command,
5098 .mode = COMMAND_EXEC,
5099 .help = "write memory half-word",
5100 .usage = "['phys'] address value [count]",
5103 .name = "mwb",
5104 .handler = handle_mw_command,
5105 .mode = COMMAND_EXEC,
5106 .help = "write memory byte",
5107 .usage = "['phys'] address value [count]",
5110 .name = "bp",
5111 .handler = handle_bp_command,
5112 .mode = COMMAND_EXEC,
5113 .help = "list or set hardware or software breakpoint",
5114 .usage = "[address length ['hw']]",
5117 .name = "rbp",
5118 .handler = handle_rbp_command,
5119 .mode = COMMAND_EXEC,
5120 .help = "remove breakpoint",
5121 .usage = "address",
5124 .name = "wp",
5125 .handler = handle_wp_command,
5126 .mode = COMMAND_EXEC,
5127 .help = "list (no params) or create watchpoints",
5128 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5131 .name = "rwp",
5132 .handler = handle_rwp_command,
5133 .mode = COMMAND_EXEC,
5134 .help = "remove watchpoint",
5135 .usage = "address",
5138 .name = "load_image",
5139 .handler = handle_load_image_command,
5140 .mode = COMMAND_EXEC,
5141 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5142 "[min_address] [max_length]",
5145 .name = "dump_image",
5146 .handler = handle_dump_image_command,
5147 .mode = COMMAND_EXEC,
5148 .usage = "filename address size",
5151 .name = "verify_image",
5152 .handler = handle_verify_image_command,
5153 .mode = COMMAND_EXEC,
5154 .usage = "filename [offset [type]]",
5157 .name = "test_image",
5158 .handler = handle_test_image_command,
5159 .mode = COMMAND_EXEC,
5160 .usage = "filename [offset [type]]",
5163 .name = "ocd_mem2array",
5164 .mode = COMMAND_EXEC,
5165 .jim_handler = jim_mem2array,
5166 .help = "read 8/16/32 bit memory and return as a TCL array "
5167 "for script processing",
5168 .usage = "arrayname bitwidth address count",
5171 .name = "ocd_array2mem",
5172 .mode = COMMAND_EXEC,
5173 .jim_handler = jim_array2mem,
5174 .help = "convert a TCL array to memory locations "
5175 "and write the 8/16/32 bit values",
5176 .usage = "arrayname bitwidth address count",
5179 .name = "reset_nag",
5180 .handler = handle_target_reset_nag,
5181 .mode = COMMAND_ANY,
5182 .help = "Nag after each reset about options that could have been "
5183 "enabled to improve performance. ",
5184 .usage = "['enable'|'disable']",
5186 COMMAND_REGISTRATION_DONE
5188 int target_register_user_commands(struct command_context *cmd_ctx)
5190 int retval = ERROR_OK;
5191 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
5192 return retval;
5194 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
5195 return retval;
5198 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);