1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
5 * Copyright (C) 2007-2010 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
8 * Copyright (C) 2008, Duane Ellis *
9 * openocd@duaneeellis.com *
11 * Copyright (C) 2008 by Spencer Oliver *
12 * spen@spen-soft.co.uk *
14 * Copyright (C) 2008 by Rick Altherr *
15 * kc8apf@kc8apf.net> *
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. *
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. *
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 ***************************************************************************/
36 #include <helper/time_support.h>
37 #include <jtag/jtag.h>
38 #include <flash/nor/core.h>
41 #include "target_type.h"
42 #include "target_request.h"
43 #include "breakpoints.h"
49 static int target_read_buffer_default(struct target *target, uint32_t address,
50 uint32_t size, uint8_t *buffer);
51 static int target_write_buffer_default(struct target *target, uint32_t address,
52 uint32_t size, uint8_t *buffer);
53 static int target_array2mem(Jim_Interp *interp, struct target *target,
54 int argc, Jim_Obj *const *argv);
55 static int target_mem2array(Jim_Interp *interp, struct target *target,
56 int argc, Jim_Obj *const *argv);
57 static int target_register_user_commands(struct command_context *cmd_ctx);
60 extern struct target_type arm7tdmi_target;
61 extern struct target_type arm720t_target;
62 extern struct target_type arm9tdmi_target;
63 extern struct target_type arm920t_target;
64 extern struct target_type arm966e_target;
65 extern struct target_type arm946e_target;
66 extern struct target_type arm926ejs_target;
67 extern struct target_type fa526_target;
68 extern struct target_type feroceon_target;
69 extern struct target_type dragonite_target;
70 extern struct target_type xscale_target;
71 extern struct target_type cortexm3_target;
72 extern struct target_type cortexa8_target;
73 extern struct target_type cortexa9_target;
74 extern struct target_type arm11_target;
75 extern struct target_type mips_m4k_target;
76 extern struct target_type avr_target;
77 extern struct target_type dsp563xx_target;
78 extern struct target_type testee_target;
79 extern struct target_type avr32_ap7k_target;
81 static struct target_type *target_types[] =
106 struct target *all_targets = NULL;
107 static struct target_event_callback *target_event_callbacks = NULL;
108 static struct target_timer_callback *target_timer_callbacks = NULL;
109 static const int polling_interval = 100;
111 static const Jim_Nvp nvp_assert[] = {
112 { .name = "assert", NVP_ASSERT },
113 { .name = "deassert", NVP_DEASSERT },
114 { .name = "T", NVP_ASSERT },
115 { .name = "F", NVP_DEASSERT },
116 { .name = "t", NVP_ASSERT },
117 { .name = "f", NVP_DEASSERT },
118 { .name = NULL, .value = -1 }
121 static const Jim_Nvp nvp_error_target[] = {
122 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
123 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
124 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
125 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
126 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
127 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
128 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
129 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
130 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
131 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
132 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
133 { .value = -1, .name = NULL }
136 static const char *target_strerror_safe(int err)
140 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
141 if (n->name == NULL) {
148 static const Jim_Nvp nvp_target_event[] = {
149 { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
150 { .value = TARGET_EVENT_OLD_pre_resume , .name = "old-pre_resume" },
152 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
153 { .value = TARGET_EVENT_HALTED, .name = "halted" },
154 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
155 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
156 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
158 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
159 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
161 /* historical name */
163 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
165 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
166 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
167 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
168 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
169 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
170 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
171 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
172 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
173 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
174 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
175 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
177 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
178 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
180 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
181 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
183 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
184 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
186 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
187 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
189 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
190 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
192 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
193 { .value = TARGET_EVENT_RESUMED , .name = "resume-ok" },
194 { .value = TARGET_EVENT_RESUME_END , .name = "resume-end" },
196 { .name = NULL, .value = -1 }
199 static const Jim_Nvp nvp_target_state[] = {
200 { .name = "unknown", .value = TARGET_UNKNOWN },
201 { .name = "running", .value = TARGET_RUNNING },
202 { .name = "halted", .value = TARGET_HALTED },
203 { .name = "reset", .value = TARGET_RESET },
204 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
205 { .name = NULL, .value = -1 },
208 static const Jim_Nvp nvp_target_debug_reason [] = {
209 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
210 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
211 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
212 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
213 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
214 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
215 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
216 { .name = NULL, .value = -1 },
219 static const Jim_Nvp nvp_target_endian[] = {
220 { .name = "big", .value = TARGET_BIG_ENDIAN },
221 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
222 { .name = "be", .value = TARGET_BIG_ENDIAN },
223 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
224 { .name = NULL, .value = -1 },
227 static const Jim_Nvp nvp_reset_modes[] = {
228 { .name = "unknown", .value = RESET_UNKNOWN },
229 { .name = "run" , .value = RESET_RUN },
230 { .name = "halt" , .value = RESET_HALT },
231 { .name = "init" , .value = RESET_INIT },
232 { .name = NULL , .value = -1 },
235 const char *debug_reason_name(struct target *t)
239 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
240 t->debug_reason)->name;
242 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
243 cp = "(*BUG*unknown*BUG*)";
249 target_state_name( struct target *t )
252 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
254 LOG_ERROR("Invalid target state: %d", (int)(t->state));
255 cp = "(*BUG*unknown*BUG*)";
260 /* determine the number of the new target */
261 static int new_target_number(void)
266 /* number is 0 based */
270 if (x < t->target_number) {
271 x = t->target_number;
278 /* read a uint32_t from a buffer in target memory endianness */
279 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
281 if (target->endianness == TARGET_LITTLE_ENDIAN)
282 return le_to_h_u32(buffer);
284 return be_to_h_u32(buffer);
287 /* read a uint24_t from a buffer in target memory endianness */
288 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
290 if (target->endianness == TARGET_LITTLE_ENDIAN)
291 return le_to_h_u24(buffer);
293 return be_to_h_u24(buffer);
296 /* read a uint16_t from a buffer in target memory endianness */
297 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
299 if (target->endianness == TARGET_LITTLE_ENDIAN)
300 return le_to_h_u16(buffer);
302 return be_to_h_u16(buffer);
305 /* read a uint8_t from a buffer in target memory endianness */
306 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
308 return *buffer & 0x0ff;
311 /* write a uint32_t to a buffer in target memory endianness */
312 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
314 if (target->endianness == TARGET_LITTLE_ENDIAN)
315 h_u32_to_le(buffer, value);
317 h_u32_to_be(buffer, value);
320 /* write a uint24_t to a buffer in target memory endianness */
321 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
323 if (target->endianness == TARGET_LITTLE_ENDIAN)
324 h_u24_to_le(buffer, value);
326 h_u24_to_be(buffer, value);
329 /* write a uint16_t to a buffer in target memory endianness */
330 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
332 if (target->endianness == TARGET_LITTLE_ENDIAN)
333 h_u16_to_le(buffer, value);
335 h_u16_to_be(buffer, value);
338 /* write a uint8_t to a buffer in target memory endianness */
339 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
344 /* return a pointer to a configured target; id is name or number */
345 struct target *get_target(const char *id)
347 struct target *target;
349 /* try as tcltarget name */
350 for (target = all_targets; target; target = target->next) {
351 if (target->cmd_name == NULL)
353 if (strcmp(id, target->cmd_name) == 0)
357 /* It's OK to remove this fallback sometime after August 2010 or so */
359 /* no match, try as number */
361 if (parse_uint(id, &num) != ERROR_OK)
364 for (target = all_targets; target; target = target->next) {
365 if (target->target_number == (int)num) {
366 LOG_WARNING("use '%s' as target identifier, not '%u'",
367 target->cmd_name, num);
375 /* returns a pointer to the n-th configured target */
376 static struct target *get_target_by_num(int num)
378 struct target *target = all_targets;
381 if (target->target_number == num) {
384 target = target->next;
390 struct target* get_current_target(struct command_context *cmd_ctx)
392 struct target *target = get_target_by_num(cmd_ctx->current_target);
396 LOG_ERROR("BUG: current_target out of bounds");
403 int target_poll(struct target *target)
407 /* We can't poll until after examine */
408 if (!target_was_examined(target))
410 /* Fail silently lest we pollute the log */
414 retval = target->type->poll(target);
415 if (retval != ERROR_OK)
418 if (target->halt_issued)
420 if (target->state == TARGET_HALTED)
422 target->halt_issued = false;
425 long long t = timeval_ms() - target->halt_issued_time;
428 target->halt_issued = false;
429 LOG_INFO("Halt timed out, wake up GDB.");
430 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
438 int target_halt(struct target *target)
441 /* We can't poll until after examine */
442 if (!target_was_examined(target))
444 LOG_ERROR("Target not examined yet");
448 retval = target->type->halt(target);
449 if (retval != ERROR_OK)
452 target->halt_issued = true;
453 target->halt_issued_time = timeval_ms();
459 * Make the target (re)start executing using its saved execution
460 * context (possibly with some modifications).
462 * @param target Which target should start executing.
463 * @param current True to use the target's saved program counter instead
464 * of the address parameter
465 * @param address Optionally used as the program counter.
466 * @param handle_breakpoints True iff breakpoints at the resumption PC
467 * should be skipped. (For example, maybe execution was stopped by
468 * such a breakpoint, in which case it would be counterprodutive to
470 * @param debug_execution False if all working areas allocated by OpenOCD
471 * should be released and/or restored to their original contents.
472 * (This would for example be true to run some downloaded "helper"
473 * algorithm code, which resides in one such working buffer and uses
474 * another for data storage.)
476 * @todo Resolve the ambiguity about what the "debug_execution" flag
477 * signifies. For example, Target implementations don't agree on how
478 * it relates to invalidation of the register cache, or to whether
479 * breakpoints and watchpoints should be enabled. (It would seem wrong
480 * to enable breakpoints when running downloaded "helper" algorithms
481 * (debug_execution true), since the breakpoints would be set to match
482 * target firmware being debugged, not the helper algorithm.... and
483 * enabling them could cause such helpers to malfunction (for example,
484 * by overwriting data with a breakpoint instruction. On the other
485 * hand the infrastructure for running such helpers might use this
486 * procedure but rely on hardware breakpoint to detect termination.)
488 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
492 /* We can't poll until after examine */
493 if (!target_was_examined(target))
495 LOG_ERROR("Target not examined yet");
499 /* note that resume *must* be asynchronous. The CPU can halt before
500 * we poll. The CPU can even halt at the current PC as a result of
501 * a software breakpoint being inserted by (a bug?) the application.
503 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
509 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
514 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
515 if (n->name == NULL) {
516 LOG_ERROR("invalid reset mode");
520 /* disable polling during reset to make reset event scripts
521 * more predictable, i.e. dr/irscan & pathmove in events will
522 * not have JTAG operations injected into the middle of a sequence.
524 bool save_poll = jtag_poll_get_enabled();
526 jtag_poll_set_enabled(false);
528 sprintf(buf, "ocd_process_reset %s", n->name);
529 retval = Jim_Eval(cmd_ctx->interp, buf);
531 jtag_poll_set_enabled(save_poll);
533 if (retval != JIM_OK) {
534 Jim_MakeErrorMessage(cmd_ctx->interp);
535 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
539 /* We want any events to be processed before the prompt */
540 retval = target_call_timer_callbacks_now();
542 struct target *target;
543 for (target = all_targets; target; target = target->next) {
544 target->type->check_reset(target);
550 static int identity_virt2phys(struct target *target,
551 uint32_t virtual, uint32_t *physical)
557 static int no_mmu(struct target *target, int *enabled)
563 static int default_examine(struct target *target)
565 target_set_examined(target);
569 /* no check by default */
570 static int default_check_reset(struct target *target)
575 int target_examine_one(struct target *target)
577 return target->type->examine(target);
580 static int jtag_enable_callback(enum jtag_event event, void *priv)
582 struct target *target = priv;
584 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
587 jtag_unregister_event_callback(jtag_enable_callback, target);
588 return target_examine_one(target);
592 /* Targets that correctly implement init + examine, i.e.
593 * no communication with target during init:
597 int target_examine(void)
599 int retval = ERROR_OK;
600 struct target *target;
602 for (target = all_targets; target; target = target->next)
604 /* defer examination, but don't skip it */
605 if (!target->tap->enabled) {
606 jtag_register_event_callback(jtag_enable_callback,
610 if ((retval = target_examine_one(target)) != ERROR_OK)
615 const char *target_type_name(struct target *target)
617 return target->type->name;
620 static int target_write_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
622 if (!target_was_examined(target))
624 LOG_ERROR("Target not examined yet");
627 return target->type->write_memory_imp(target, address, size, count, buffer);
630 static int target_read_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
632 if (!target_was_examined(target))
634 LOG_ERROR("Target not examined yet");
637 return target->type->read_memory_imp(target, address, size, count, buffer);
640 static int target_soft_reset_halt_imp(struct target *target)
642 if (!target_was_examined(target))
644 LOG_ERROR("Target not examined yet");
647 if (!target->type->soft_reset_halt_imp) {
648 LOG_ERROR("Target %s does not support soft_reset_halt",
649 target_name(target));
652 return target->type->soft_reset_halt_imp(target);
656 * Downloads a target-specific native code algorithm to the target,
657 * and executes it. * Note that some targets may need to set up, enable,
658 * and tear down a breakpoint (hard or * soft) to detect algorithm
659 * termination, while others may support lower overhead schemes where
660 * soft breakpoints embedded in the algorithm automatically terminate the
663 * @param target used to run the algorithm
664 * @param arch_info target-specific description of the algorithm.
666 int target_run_algorithm(struct target *target,
667 int num_mem_params, struct mem_param *mem_params,
668 int num_reg_params, struct reg_param *reg_param,
669 uint32_t entry_point, uint32_t exit_point,
670 int timeout_ms, void *arch_info)
672 int retval = ERROR_FAIL;
674 if (!target_was_examined(target))
676 LOG_ERROR("Target not examined yet");
679 if (!target->type->run_algorithm) {
680 LOG_ERROR("Target type '%s' does not support %s",
681 target_type_name(target), __func__);
685 target->running_alg = true;
686 retval = target->type->run_algorithm(target,
687 num_mem_params, mem_params,
688 num_reg_params, reg_param,
689 entry_point, exit_point, timeout_ms, arch_info);
690 target->running_alg = false;
697 int target_read_memory(struct target *target,
698 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
700 return target->type->read_memory(target, address, size, count, buffer);
703 static int target_read_phys_memory(struct target *target,
704 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
706 return target->type->read_phys_memory(target, address, size, count, buffer);
709 int target_write_memory(struct target *target,
710 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
712 return target->type->write_memory(target, address, size, count, buffer);
715 static int target_write_phys_memory(struct target *target,
716 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
718 return target->type->write_phys_memory(target, address, size, count, buffer);
721 int target_bulk_write_memory(struct target *target,
722 uint32_t address, uint32_t count, uint8_t *buffer)
724 return target->type->bulk_write_memory(target, address, count, buffer);
727 int target_add_breakpoint(struct target *target,
728 struct breakpoint *breakpoint)
730 if (target->state != TARGET_HALTED) {
731 LOG_WARNING("target %s is not halted", target->cmd_name);
732 return ERROR_TARGET_NOT_HALTED;
734 return target->type->add_breakpoint(target, breakpoint);
736 int target_remove_breakpoint(struct target *target,
737 struct breakpoint *breakpoint)
739 return target->type->remove_breakpoint(target, breakpoint);
742 int target_add_watchpoint(struct target *target,
743 struct watchpoint *watchpoint)
745 if (target->state != TARGET_HALTED) {
746 LOG_WARNING("target %s is not halted", target->cmd_name);
747 return ERROR_TARGET_NOT_HALTED;
749 return target->type->add_watchpoint(target, watchpoint);
751 int target_remove_watchpoint(struct target *target,
752 struct watchpoint *watchpoint)
754 return target->type->remove_watchpoint(target, watchpoint);
757 int target_get_gdb_reg_list(struct target *target,
758 struct reg **reg_list[], int *reg_list_size)
760 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
762 int target_step(struct target *target,
763 int current, uint32_t address, int handle_breakpoints)
765 return target->type->step(target, current, address, handle_breakpoints);
770 * Reset the @c examined flag for the given target.
771 * Pure paranoia -- targets are zeroed on allocation.
773 static void target_reset_examined(struct target *target)
775 target->examined = false;
779 err_read_phys_memory(struct target *target, uint32_t address,
780 uint32_t size, uint32_t count, uint8_t *buffer)
782 LOG_ERROR("Not implemented: %s", __func__);
787 err_write_phys_memory(struct target *target, uint32_t address,
788 uint32_t size, uint32_t count, uint8_t *buffer)
790 LOG_ERROR("Not implemented: %s", __func__);
794 static int handle_target(void *priv);
796 static int target_init_one(struct command_context *cmd_ctx,
797 struct target *target)
799 target_reset_examined(target);
801 struct target_type *type = target->type;
802 if (type->examine == NULL)
803 type->examine = default_examine;
805 if (type->check_reset== NULL)
806 type->check_reset = default_check_reset;
808 int retval = type->init_target(cmd_ctx, target);
809 if (ERROR_OK != retval)
811 LOG_ERROR("target '%s' init failed", target_name(target));
816 * @todo get rid of those *memory_imp() methods, now that all
817 * callers are using target_*_memory() accessors ... and make
818 * sure the "physical" paths handle the same issues.
820 /* a non-invasive way(in terms of patches) to add some code that
821 * runs before the type->write/read_memory implementation
823 type->write_memory_imp = target->type->write_memory;
824 type->write_memory = target_write_memory_imp;
826 type->read_memory_imp = target->type->read_memory;
827 type->read_memory = target_read_memory_imp;
829 type->soft_reset_halt_imp = target->type->soft_reset_halt;
830 type->soft_reset_halt = target_soft_reset_halt_imp;
832 /* Sanity-check MMU support ... stub in what we must, to help
833 * implement it in stages, but warn if we need to do so.
837 if (type->write_phys_memory == NULL)
839 LOG_ERROR("type '%s' is missing write_phys_memory",
841 type->write_phys_memory = err_write_phys_memory;
843 if (type->read_phys_memory == NULL)
845 LOG_ERROR("type '%s' is missing read_phys_memory",
847 type->read_phys_memory = err_read_phys_memory;
849 if (type->virt2phys == NULL)
851 LOG_ERROR("type '%s' is missing virt2phys", type->name);
852 type->virt2phys = identity_virt2phys;
857 /* Make sure no-MMU targets all behave the same: make no
858 * distinction between physical and virtual addresses, and
859 * ensure that virt2phys() is always an identity mapping.
861 if (type->write_phys_memory || type->read_phys_memory
864 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
868 type->write_phys_memory = type->write_memory;
869 type->read_phys_memory = type->read_memory;
870 type->virt2phys = identity_virt2phys;
873 if (target->type->read_buffer == NULL)
874 target->type->read_buffer = target_read_buffer_default;
876 if (target->type->write_buffer == NULL)
877 target->type->write_buffer = target_write_buffer_default;
882 static int target_init(struct command_context *cmd_ctx)
884 struct target *target;
887 for (target = all_targets; target; target = target->next)
889 retval = target_init_one(cmd_ctx, target);
890 if (ERROR_OK != retval)
897 retval = target_register_user_commands(cmd_ctx);
898 if (ERROR_OK != retval)
901 retval = target_register_timer_callback(&handle_target,
902 polling_interval, 1, cmd_ctx->interp);
903 if (ERROR_OK != retval)
909 COMMAND_HANDLER(handle_target_init_command)
912 return ERROR_COMMAND_SYNTAX_ERROR;
914 static bool target_initialized = false;
915 if (target_initialized)
917 LOG_INFO("'target init' has already been called");
920 target_initialized = true;
922 LOG_DEBUG("Initializing targets...");
923 return target_init(CMD_CTX);
926 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
928 struct target_event_callback **callbacks_p = &target_event_callbacks;
930 if (callback == NULL)
932 return ERROR_INVALID_ARGUMENTS;
937 while ((*callbacks_p)->next)
938 callbacks_p = &((*callbacks_p)->next);
939 callbacks_p = &((*callbacks_p)->next);
942 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
943 (*callbacks_p)->callback = callback;
944 (*callbacks_p)->priv = priv;
945 (*callbacks_p)->next = NULL;
950 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
952 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
955 if (callback == NULL)
957 return ERROR_INVALID_ARGUMENTS;
962 while ((*callbacks_p)->next)
963 callbacks_p = &((*callbacks_p)->next);
964 callbacks_p = &((*callbacks_p)->next);
967 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
968 (*callbacks_p)->callback = callback;
969 (*callbacks_p)->periodic = periodic;
970 (*callbacks_p)->time_ms = time_ms;
972 gettimeofday(&now, NULL);
973 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
974 time_ms -= (time_ms % 1000);
975 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
976 if ((*callbacks_p)->when.tv_usec > 1000000)
978 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
979 (*callbacks_p)->when.tv_sec += 1;
982 (*callbacks_p)->priv = priv;
983 (*callbacks_p)->next = NULL;
988 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
990 struct target_event_callback **p = &target_event_callbacks;
991 struct target_event_callback *c = target_event_callbacks;
993 if (callback == NULL)
995 return ERROR_INVALID_ARGUMENTS;
1000 struct target_event_callback *next = c->next;
1001 if ((c->callback == callback) && (c->priv == priv))
1015 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1017 struct target_timer_callback **p = &target_timer_callbacks;
1018 struct target_timer_callback *c = target_timer_callbacks;
1020 if (callback == NULL)
1022 return ERROR_INVALID_ARGUMENTS;
1027 struct target_timer_callback *next = c->next;
1028 if ((c->callback == callback) && (c->priv == priv))
1042 int target_call_event_callbacks(struct target *target, enum target_event event)
1044 struct target_event_callback *callback = target_event_callbacks;
1045 struct target_event_callback *next_callback;
1047 if (event == TARGET_EVENT_HALTED)
1049 /* execute early halted first */
1050 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1053 LOG_DEBUG("target event %i (%s)",
1055 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1057 target_handle_event(target, event);
1061 next_callback = callback->next;
1062 callback->callback(target, event, callback->priv);
1063 callback = next_callback;
1069 static int target_timer_callback_periodic_restart(
1070 struct target_timer_callback *cb, struct timeval *now)
1072 int time_ms = cb->time_ms;
1073 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1074 time_ms -= (time_ms % 1000);
1075 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1076 if (cb->when.tv_usec > 1000000)
1078 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1079 cb->when.tv_sec += 1;
1084 static int target_call_timer_callback(struct target_timer_callback *cb,
1085 struct timeval *now)
1087 cb->callback(cb->priv);
1090 return target_timer_callback_periodic_restart(cb, now);
1092 return target_unregister_timer_callback(cb->callback, cb->priv);
1095 static int target_call_timer_callbacks_check_time(int checktime)
1100 gettimeofday(&now, NULL);
1102 struct target_timer_callback *callback = target_timer_callbacks;
1105 // cleaning up may unregister and free this callback
1106 struct target_timer_callback *next_callback = callback->next;
1108 bool call_it = callback->callback &&
1109 ((!checktime && callback->periodic) ||
1110 now.tv_sec > callback->when.tv_sec ||
1111 (now.tv_sec == callback->when.tv_sec &&
1112 now.tv_usec >= callback->when.tv_usec));
1116 int retval = target_call_timer_callback(callback, &now);
1117 if (retval != ERROR_OK)
1121 callback = next_callback;
1127 int target_call_timer_callbacks(void)
1129 return target_call_timer_callbacks_check_time(1);
1132 /* invoke periodic callbacks immediately */
1133 int target_call_timer_callbacks_now(void)
1135 return target_call_timer_callbacks_check_time(0);
1138 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1140 struct working_area *c = target->working_areas;
1141 struct working_area *new_wa = NULL;
1143 /* Reevaluate working area address based on MMU state*/
1144 if (target->working_areas == NULL)
1149 retval = target->type->mmu(target, &enabled);
1150 if (retval != ERROR_OK)
1156 if (target->working_area_phys_spec) {
1157 LOG_DEBUG("MMU disabled, using physical "
1158 "address for working memory 0x%08x",
1159 (unsigned)target->working_area_phys);
1160 target->working_area = target->working_area_phys;
1162 LOG_ERROR("No working memory available. "
1163 "Specify -work-area-phys to target.");
1164 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1167 if (target->working_area_virt_spec) {
1168 LOG_DEBUG("MMU enabled, using virtual "
1169 "address for working memory 0x%08x",
1170 (unsigned)target->working_area_virt);
1171 target->working_area = target->working_area_virt;
1173 LOG_ERROR("No working memory available. "
1174 "Specify -work-area-virt to target.");
1175 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1180 /* only allocate multiples of 4 byte */
1183 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1184 size = (size + 3) & (~3);
1187 /* see if there's already a matching working area */
1190 if ((c->free) && (c->size == size))
1198 /* if not, allocate a new one */
1201 struct working_area **p = &target->working_areas;
1202 uint32_t first_free = target->working_area;
1203 uint32_t free_size = target->working_area_size;
1205 c = target->working_areas;
1208 first_free += c->size;
1209 free_size -= c->size;
1214 if (free_size < size)
1216 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1219 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1221 new_wa = malloc(sizeof(struct working_area));
1222 new_wa->next = NULL;
1223 new_wa->size = size;
1224 new_wa->address = first_free;
1226 if (target->backup_working_area)
1229 new_wa->backup = malloc(new_wa->size);
1230 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1232 free(new_wa->backup);
1239 new_wa->backup = NULL;
1242 /* put new entry in list */
1246 /* mark as used, and return the new (reused) area */
1247 new_wa->free = false;
1251 new_wa->user = area;
1256 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1260 retval = target_alloc_working_area_try(target, size, area);
1261 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1263 LOG_WARNING("not enough working area available(requested %u)", (unsigned)(size));
1269 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1274 if (restore && target->backup_working_area)
1277 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1283 /* mark user pointer invalid */
1290 int target_free_working_area(struct target *target, struct working_area *area)
1292 return target_free_working_area_restore(target, area, 1);
1295 /* free resources and restore memory, if restoring memory fails,
1296 * free up resources anyway
1298 static void target_free_all_working_areas_restore(struct target *target, int restore)
1300 struct working_area *c = target->working_areas;
1304 struct working_area *next = c->next;
1305 target_free_working_area_restore(target, c, restore);
1315 target->working_areas = NULL;
1318 void target_free_all_working_areas(struct target *target)
1320 target_free_all_working_areas_restore(target, 1);
1323 int target_arch_state(struct target *target)
1328 LOG_USER("No target has been configured");
1332 LOG_USER("target state: %s", target_state_name( target ));
1334 if (target->state != TARGET_HALTED)
1337 retval = target->type->arch_state(target);
1341 /* Single aligned words are guaranteed to use 16 or 32 bit access
1342 * mode respectively, otherwise data is handled as quickly as
1345 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1347 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1348 (int)size, (unsigned)address);
1350 if (!target_was_examined(target))
1352 LOG_ERROR("Target not examined yet");
1360 if ((address + size - 1) < address)
1362 /* GDB can request this when e.g. PC is 0xfffffffc*/
1363 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1369 return target->type->write_buffer(target, address, size, buffer);
1372 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1374 int retval = ERROR_OK;
1376 if (((address % 2) == 0) && (size == 2))
1378 return target_write_memory(target, address, 2, 1, buffer);
1381 /* handle unaligned head bytes */
1384 uint32_t unaligned = 4 - (address % 4);
1386 if (unaligned > size)
1389 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1392 buffer += unaligned;
1393 address += unaligned;
1397 /* handle aligned words */
1400 int aligned = size - (size % 4);
1402 /* use bulk writes above a certain limit. This may have to be changed */
1405 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1410 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1419 /* handle tail writes of less than 4 bytes */
1422 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1429 /* Single aligned words are guaranteed to use 16 or 32 bit access
1430 * mode respectively, otherwise data is handled as quickly as
1433 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1435 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1436 (int)size, (unsigned)address);
1438 if (!target_was_examined(target))
1440 LOG_ERROR("Target not examined yet");
1448 if ((address + size - 1) < address)
1450 /* GDB can request this when e.g. PC is 0xfffffffc*/
1451 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1457 return target->type->read_buffer(target, address, size, buffer);
1460 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1462 int retval = ERROR_OK;
1464 if (((address % 2) == 0) && (size == 2))
1466 return target_read_memory(target, address, 2, 1, buffer);
1469 /* handle unaligned head bytes */
1472 uint32_t unaligned = 4 - (address % 4);
1474 if (unaligned > size)
1477 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1480 buffer += unaligned;
1481 address += unaligned;
1485 /* handle aligned words */
1488 int aligned = size - (size % 4);
1490 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1498 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1501 int aligned = size - (size%2);
1502 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1503 if (retval != ERROR_OK)
1510 /* handle tail writes of less than 4 bytes */
1513 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1520 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1525 uint32_t checksum = 0;
1526 if (!target_was_examined(target))
1528 LOG_ERROR("Target not examined yet");
1532 if ((retval = target->type->checksum_memory(target, address,
1533 size, &checksum)) != ERROR_OK)
1535 buffer = malloc(size);
1538 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1539 return ERROR_INVALID_ARGUMENTS;
1541 retval = target_read_buffer(target, address, size, buffer);
1542 if (retval != ERROR_OK)
1548 /* convert to target endianness */
1549 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1551 uint32_t target_data;
1552 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1553 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1556 retval = image_calculate_checksum(buffer, size, &checksum);
1565 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1568 if (!target_was_examined(target))
1570 LOG_ERROR("Target not examined yet");
1574 if (target->type->blank_check_memory == 0)
1575 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1577 retval = target->type->blank_check_memory(target, address, size, blank);
1582 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1584 uint8_t value_buf[4];
1585 if (!target_was_examined(target))
1587 LOG_ERROR("Target not examined yet");
1591 int retval = target_read_memory(target, address, 4, 1, value_buf);
1593 if (retval == ERROR_OK)
1595 *value = target_buffer_get_u32(target, value_buf);
1596 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1603 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1610 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1612 uint8_t value_buf[2];
1613 if (!target_was_examined(target))
1615 LOG_ERROR("Target not examined yet");
1619 int retval = target_read_memory(target, address, 2, 1, value_buf);
1621 if (retval == ERROR_OK)
1623 *value = target_buffer_get_u16(target, value_buf);
1624 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1631 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1638 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1640 int retval = target_read_memory(target, address, 1, 1, value);
1641 if (!target_was_examined(target))
1643 LOG_ERROR("Target not examined yet");
1647 if (retval == ERROR_OK)
1649 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1656 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1663 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1666 uint8_t value_buf[4];
1667 if (!target_was_examined(target))
1669 LOG_ERROR("Target not examined yet");
1673 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1677 target_buffer_set_u32(target, value_buf, value);
1678 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1680 LOG_DEBUG("failed: %i", retval);
1686 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1689 uint8_t value_buf[2];
1690 if (!target_was_examined(target))
1692 LOG_ERROR("Target not examined yet");
1696 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1700 target_buffer_set_u16(target, value_buf, value);
1701 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1703 LOG_DEBUG("failed: %i", retval);
1709 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1712 if (!target_was_examined(target))
1714 LOG_ERROR("Target not examined yet");
1718 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1721 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1723 LOG_DEBUG("failed: %i", retval);
1729 COMMAND_HANDLER(handle_targets_command)
1731 struct target *target = all_targets;
1735 target = get_target(CMD_ARGV[0]);
1736 if (target == NULL) {
1737 command_print(CMD_CTX,"Target: %s is unknown, try one of:\n", CMD_ARGV[0]);
1740 if (!target->tap->enabled) {
1741 command_print(CMD_CTX,"Target: TAP %s is disabled, "
1742 "can't be the current target\n",
1743 target->tap->dotted_name);
1747 CMD_CTX->current_target = target->target_number;
1752 target = all_targets;
1753 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
1754 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
1760 if (target->tap->enabled)
1761 state = target_state_name( target );
1763 state = "tap-disabled";
1765 if (CMD_CTX->current_target == target->target_number)
1768 /* keep columns lined up to match the headers above */
1769 command_print(CMD_CTX, "%2d%c %-18s %-10s %-6s %-18s %s",
1770 target->target_number,
1772 target_name(target),
1773 target_type_name(target),
1774 Jim_Nvp_value2name_simple(nvp_target_endian,
1775 target->endianness)->name,
1776 target->tap->dotted_name,
1778 target = target->next;
1784 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1786 static int powerDropout;
1787 static int srstAsserted;
1789 static int runPowerRestore;
1790 static int runPowerDropout;
1791 static int runSrstAsserted;
1792 static int runSrstDeasserted;
1794 static int sense_handler(void)
1796 static int prevSrstAsserted = 0;
1797 static int prevPowerdropout = 0;
1800 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1804 powerRestored = prevPowerdropout && !powerDropout;
1807 runPowerRestore = 1;
1810 long long current = timeval_ms();
1811 static long long lastPower = 0;
1812 int waitMore = lastPower + 2000 > current;
1813 if (powerDropout && !waitMore)
1815 runPowerDropout = 1;
1816 lastPower = current;
1819 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1823 srstDeasserted = prevSrstAsserted && !srstAsserted;
1825 static long long lastSrst = 0;
1826 waitMore = lastSrst + 2000 > current;
1827 if (srstDeasserted && !waitMore)
1829 runSrstDeasserted = 1;
1833 if (!prevSrstAsserted && srstAsserted)
1835 runSrstAsserted = 1;
1838 prevSrstAsserted = srstAsserted;
1839 prevPowerdropout = powerDropout;
1841 if (srstDeasserted || powerRestored)
1843 /* Other than logging the event we can't do anything here.
1844 * Issuing a reset is a particularly bad idea as we might
1845 * be inside a reset already.
1852 static int backoff_times = 0;
1853 static int backoff_count = 0;
1855 /* process target state changes */
1856 static int handle_target(void *priv)
1858 Jim_Interp *interp = (Jim_Interp *)priv;
1859 int retval = ERROR_OK;
1861 if (!is_jtag_poll_safe())
1863 /* polling is disabled currently */
1867 /* we do not want to recurse here... */
1868 static int recursive = 0;
1873 /* danger! running these procedures can trigger srst assertions and power dropouts.
1874 * We need to avoid an infinite loop/recursion here and we do that by
1875 * clearing the flags after running these events.
1877 int did_something = 0;
1878 if (runSrstAsserted)
1880 LOG_INFO("srst asserted detected, running srst_asserted proc.");
1881 Jim_Eval(interp, "srst_asserted");
1884 if (runSrstDeasserted)
1886 Jim_Eval(interp, "srst_deasserted");
1889 if (runPowerDropout)
1891 LOG_INFO("Power dropout detected, running power_dropout proc.");
1892 Jim_Eval(interp, "power_dropout");
1895 if (runPowerRestore)
1897 Jim_Eval(interp, "power_restore");
1903 /* clear detect flags */
1907 /* clear action flags */
1909 runSrstAsserted = 0;
1910 runSrstDeasserted = 0;
1911 runPowerRestore = 0;
1912 runPowerDropout = 0;
1917 if (backoff_times > backoff_count)
1919 /* do not poll this time as we failed previously */
1925 /* Poll targets for state changes unless that's globally disabled.
1926 * Skip targets that are currently disabled.
1928 for (struct target *target = all_targets;
1929 is_jtag_poll_safe() && target;
1930 target = target->next)
1932 if (!target->tap->enabled)
1935 /* only poll target if we've got power and srst isn't asserted */
1936 if (!powerDropout && !srstAsserted)
1938 /* polling may fail silently until the target has been examined */
1939 if ((retval = target_poll(target)) != ERROR_OK)
1941 /* 100ms polling interval. Increase interval between polling up to 5000ms */
1942 if (backoff_times * polling_interval < 5000)
1947 LOG_USER("Polling target failed, GDB will be halted. Polling again in %dms", backoff_times * polling_interval);
1949 /* Tell GDB to halt the debugger. This allows the user to
1950 * run monitor commands to handle the situation.
1952 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1955 /* Since we succeeded, we reset backoff count */
1956 if (backoff_times > 0)
1958 LOG_USER("Polling succeeded again");
1967 COMMAND_HANDLER(handle_reg_command)
1969 struct target *target;
1970 struct reg *reg = NULL;
1976 target = get_current_target(CMD_CTX);
1978 /* list all available registers for the current target */
1981 struct reg_cache *cache = target->reg_cache;
1988 command_print(CMD_CTX, "===== %s", cache->name);
1990 for (i = 0, reg = cache->reg_list;
1991 i < cache->num_regs;
1992 i++, reg++, count++)
1994 /* only print cached values if they are valid */
1996 value = buf_to_str(reg->value,
1998 command_print(CMD_CTX,
1999 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2007 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2012 cache = cache->next;
2018 /* access a single register by its ordinal number */
2019 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9'))
2022 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2024 struct reg_cache *cache = target->reg_cache;
2029 for (i = 0; i < cache->num_regs; i++)
2033 reg = &cache->reg_list[i];
2039 cache = cache->next;
2044 command_print(CMD_CTX, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
2047 } else /* access a single register by its name */
2049 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2053 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2058 /* display a register */
2059 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0') && (CMD_ARGV[1][0] <= '9'))))
2061 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2064 if (reg->valid == 0)
2066 reg->type->get(reg);
2068 value = buf_to_str(reg->value, reg->size, 16);
2069 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2074 /* set register value */
2077 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2078 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2080 reg->type->set(reg, buf);
2082 value = buf_to_str(reg->value, reg->size, 16);
2083 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2091 command_print(CMD_CTX, "usage: reg <#|name> [value]");
2096 COMMAND_HANDLER(handle_poll_command)
2098 int retval = ERROR_OK;
2099 struct target *target = get_current_target(CMD_CTX);
2103 command_print(CMD_CTX, "background polling: %s",
2104 jtag_poll_get_enabled() ? "on" : "off");
2105 command_print(CMD_CTX, "TAP: %s (%s)",
2106 target->tap->dotted_name,
2107 target->tap->enabled ? "enabled" : "disabled");
2108 if (!target->tap->enabled)
2110 if ((retval = target_poll(target)) != ERROR_OK)
2112 if ((retval = target_arch_state(target)) != ERROR_OK)
2115 else if (CMD_ARGC == 1)
2118 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2119 jtag_poll_set_enabled(enable);
2123 return ERROR_COMMAND_SYNTAX_ERROR;
2129 COMMAND_HANDLER(handle_wait_halt_command)
2132 return ERROR_COMMAND_SYNTAX_ERROR;
2137 int retval = parse_uint(CMD_ARGV[0], &ms);
2138 if (ERROR_OK != retval)
2140 command_print(CMD_CTX, "usage: %s [seconds]", CMD_NAME);
2141 return ERROR_COMMAND_SYNTAX_ERROR;
2143 // convert seconds (given) to milliseconds (needed)
2147 struct target *target = get_current_target(CMD_CTX);
2148 return target_wait_state(target, TARGET_HALTED, ms);
2151 /* wait for target state to change. The trick here is to have a low
2152 * latency for short waits and not to suck up all the CPU time
2155 * After 500ms, keep_alive() is invoked
2157 int target_wait_state(struct target *target, enum target_state state, int ms)
2160 long long then = 0, cur;
2165 if ((retval = target_poll(target)) != ERROR_OK)
2167 if (target->state == state)
2175 then = timeval_ms();
2176 LOG_DEBUG("waiting for target %s...",
2177 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2185 if ((cur-then) > ms)
2187 LOG_ERROR("timed out while waiting for target %s",
2188 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2196 COMMAND_HANDLER(handle_halt_command)
2200 struct target *target = get_current_target(CMD_CTX);
2201 int retval = target_halt(target);
2202 if (ERROR_OK != retval)
2207 unsigned wait_local;
2208 retval = parse_uint(CMD_ARGV[0], &wait_local);
2209 if (ERROR_OK != retval)
2210 return ERROR_COMMAND_SYNTAX_ERROR;
2215 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2218 COMMAND_HANDLER(handle_soft_reset_halt_command)
2220 struct target *target = get_current_target(CMD_CTX);
2222 LOG_USER("requesting target halt and executing a soft reset");
2224 target->type->soft_reset_halt(target);
2229 COMMAND_HANDLER(handle_reset_command)
2232 return ERROR_COMMAND_SYNTAX_ERROR;
2234 enum target_reset_mode reset_mode = RESET_RUN;
2238 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2239 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2240 return ERROR_COMMAND_SYNTAX_ERROR;
2242 reset_mode = n->value;
2245 /* reset *all* targets */
2246 return target_process_reset(CMD_CTX, reset_mode);
2250 COMMAND_HANDLER(handle_resume_command)
2254 return ERROR_COMMAND_SYNTAX_ERROR;
2256 struct target *target = get_current_target(CMD_CTX);
2257 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2259 /* with no CMD_ARGV, resume from current pc, addr = 0,
2260 * with one arguments, addr = CMD_ARGV[0],
2261 * handle breakpoints, not debugging */
2265 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2269 return target_resume(target, current, addr, 1, 0);
2272 COMMAND_HANDLER(handle_step_command)
2275 return ERROR_COMMAND_SYNTAX_ERROR;
2279 /* with no CMD_ARGV, step from current pc, addr = 0,
2280 * with one argument addr = CMD_ARGV[0],
2281 * handle breakpoints, debugging */
2286 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2290 struct target *target = get_current_target(CMD_CTX);
2292 return target->type->step(target, current_pc, addr, 1);
2295 static void handle_md_output(struct command_context *cmd_ctx,
2296 struct target *target, uint32_t address, unsigned size,
2297 unsigned count, const uint8_t *buffer)
2299 const unsigned line_bytecnt = 32;
2300 unsigned line_modulo = line_bytecnt / size;
2302 char output[line_bytecnt * 4 + 1];
2303 unsigned output_len = 0;
2305 const char *value_fmt;
2307 case 4: value_fmt = "%8.8x "; break;
2308 case 2: value_fmt = "%4.4x "; break;
2309 case 1: value_fmt = "%2.2x "; break;
2311 /* "can't happen", caller checked */
2312 LOG_ERROR("invalid memory read size: %u", size);
2316 for (unsigned i = 0; i < count; i++)
2318 if (i % line_modulo == 0)
2320 output_len += snprintf(output + output_len,
2321 sizeof(output) - output_len,
2323 (unsigned)(address + (i*size)));
2327 const uint8_t *value_ptr = buffer + i * size;
2329 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2330 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2331 case 1: value = *value_ptr;
2333 output_len += snprintf(output + output_len,
2334 sizeof(output) - output_len,
2337 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2339 command_print(cmd_ctx, "%s", output);
2345 COMMAND_HANDLER(handle_md_command)
2348 return ERROR_COMMAND_SYNTAX_ERROR;
2351 switch (CMD_NAME[2]) {
2352 case 'w': size = 4; break;
2353 case 'h': size = 2; break;
2354 case 'b': size = 1; break;
2355 default: return ERROR_COMMAND_SYNTAX_ERROR;
2358 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2359 int (*fn)(struct target *target,
2360 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2365 fn=target_read_phys_memory;
2368 fn=target_read_memory;
2370 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2372 return ERROR_COMMAND_SYNTAX_ERROR;
2376 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2380 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2382 uint8_t *buffer = calloc(count, size);
2384 struct target *target = get_current_target(CMD_CTX);
2385 int retval = fn(target, address, size, count, buffer);
2386 if (ERROR_OK == retval)
2387 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2394 typedef int (*target_write_fn)(struct target *target,
2395 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2397 static int target_write_memory_fast(struct target *target,
2398 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
2400 return target_write_buffer(target, address, size * count, buffer);
2403 static int target_fill_mem(struct target *target,
2412 /* We have to write in reasonably large chunks to be able
2413 * to fill large memory areas with any sane speed */
2414 const unsigned chunk_size = 16384;
2415 uint8_t *target_buf = malloc(chunk_size * data_size);
2416 if (target_buf == NULL)
2418 LOG_ERROR("Out of memory");
2422 for (unsigned i = 0; i < chunk_size; i ++)
2427 target_buffer_set_u32(target, target_buf + i*data_size, b);
2430 target_buffer_set_u16(target, target_buf + i*data_size, b);
2433 target_buffer_set_u8(target, target_buf + i*data_size, b);
2440 int retval = ERROR_OK;
2442 for (unsigned x = 0; x < c; x += chunk_size)
2446 if (current > chunk_size)
2448 current = chunk_size;
2450 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2451 if (retval != ERROR_OK)
2455 /* avoid GDB timeouts */
2464 COMMAND_HANDLER(handle_mw_command)
2468 return ERROR_COMMAND_SYNTAX_ERROR;
2470 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2476 fn=target_write_phys_memory;
2479 fn = target_write_memory_fast;
2481 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2482 return ERROR_COMMAND_SYNTAX_ERROR;
2485 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2488 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2492 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2494 struct target *target = get_current_target(CMD_CTX);
2496 switch (CMD_NAME[2])
2508 return ERROR_COMMAND_SYNTAX_ERROR;
2511 return target_fill_mem(target, address, fn, wordsize, value, count);
2514 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2515 uint32_t *min_address, uint32_t *max_address)
2517 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2518 return ERROR_COMMAND_SYNTAX_ERROR;
2520 /* a base address isn't always necessary,
2521 * default to 0x0 (i.e. don't relocate) */
2525 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2526 image->base_address = addr;
2527 image->base_address_set = 1;
2530 image->base_address_set = 0;
2532 image->start_address_set = 0;
2536 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2540 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2541 // use size (given) to find max (required)
2542 *max_address += *min_address;
2545 if (*min_address > *max_address)
2546 return ERROR_COMMAND_SYNTAX_ERROR;
2551 COMMAND_HANDLER(handle_load_image_command)
2555 uint32_t image_size;
2556 uint32_t min_address = 0;
2557 uint32_t max_address = 0xffffffff;
2561 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2562 &image, &min_address, &max_address);
2563 if (ERROR_OK != retval)
2566 struct target *target = get_current_target(CMD_CTX);
2568 struct duration bench;
2569 duration_start(&bench);
2571 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2578 for (i = 0; i < image.num_sections; i++)
2580 buffer = malloc(image.sections[i].size);
2583 command_print(CMD_CTX,
2584 "error allocating buffer for section (%d bytes)",
2585 (int)(image.sections[i].size));
2589 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2595 uint32_t offset = 0;
2596 uint32_t length = buf_cnt;
2598 /* DANGER!!! beware of unsigned comparision here!!! */
2600 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2601 (image.sections[i].base_address < max_address))
2603 if (image.sections[i].base_address < min_address)
2605 /* clip addresses below */
2606 offset += min_address-image.sections[i].base_address;
2610 if (image.sections[i].base_address + buf_cnt > max_address)
2612 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2615 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2620 image_size += length;
2621 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2622 (unsigned int)length,
2623 image.sections[i].base_address + offset);
2629 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2631 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2632 "in %fs (%0.3f KiB/s)", image_size,
2633 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2636 image_close(&image);
2642 COMMAND_HANDLER(handle_dump_image_command)
2644 struct fileio fileio;
2645 uint8_t buffer[560];
2646 int retval, retvaltemp;
2647 uint32_t address, size;
2648 struct duration bench;
2649 struct target *target = get_current_target(CMD_CTX);
2652 return ERROR_COMMAND_SYNTAX_ERROR;
2654 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2655 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2657 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2658 if (retval != ERROR_OK)
2661 duration_start(&bench);
2666 size_t size_written;
2667 uint32_t this_run_size = (size > 560) ? 560 : size;
2668 retval = target_read_buffer(target, address, this_run_size, buffer);
2669 if (retval != ERROR_OK)
2674 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2675 if (retval != ERROR_OK)
2680 size -= this_run_size;
2681 address += this_run_size;
2684 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2687 retval = fileio_size(&fileio, &filesize);
2688 if (retval != ERROR_OK)
2690 command_print(CMD_CTX,
2691 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
2692 duration_elapsed(&bench), duration_kbps(&bench, filesize));
2695 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2701 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2705 uint32_t image_size;
2708 uint32_t checksum = 0;
2709 uint32_t mem_checksum = 0;
2713 struct target *target = get_current_target(CMD_CTX);
2717 return ERROR_COMMAND_SYNTAX_ERROR;
2722 LOG_ERROR("no target selected");
2726 struct duration bench;
2727 duration_start(&bench);
2732 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2733 image.base_address = addr;
2734 image.base_address_set = 1;
2738 image.base_address_set = 0;
2739 image.base_address = 0x0;
2742 image.start_address_set = 0;
2744 if ((retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL)) != ERROR_OK)
2752 for (i = 0; i < image.num_sections; i++)
2754 buffer = malloc(image.sections[i].size);
2757 command_print(CMD_CTX,
2758 "error allocating buffer for section (%d bytes)",
2759 (int)(image.sections[i].size));
2762 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2770 /* calculate checksum of image */
2771 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
2772 if (retval != ERROR_OK)
2778 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2779 if (retval != ERROR_OK)
2785 if (checksum != mem_checksum)
2787 /* failed crc checksum, fall back to a binary compare */
2792 LOG_ERROR("checksum mismatch - attempting binary compare");
2795 data = (uint8_t*)malloc(buf_cnt);
2797 /* Can we use 32bit word accesses? */
2799 int count = buf_cnt;
2800 if ((count % 4) == 0)
2805 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2806 if (retval == ERROR_OK)
2809 for (t = 0; t < buf_cnt; t++)
2811 if (data[t] != buffer[t])
2813 command_print(CMD_CTX,
2814 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
2816 (unsigned)(t + image.sections[i].base_address),
2821 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
2834 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
2835 image.sections[i].base_address,
2840 image_size += buf_cnt;
2844 command_print(CMD_CTX, "No more differences found.");
2849 retval = ERROR_FAIL;
2851 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2853 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
2854 "in %fs (%0.3f KiB/s)", image_size,
2855 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2858 image_close(&image);
2863 COMMAND_HANDLER(handle_verify_image_command)
2865 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2868 COMMAND_HANDLER(handle_test_image_command)
2870 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2873 static int handle_bp_command_list(struct command_context *cmd_ctx)
2875 struct target *target = get_current_target(cmd_ctx);
2876 struct breakpoint *breakpoint = target->breakpoints;
2879 if (breakpoint->type == BKPT_SOFT)
2881 char* buf = buf_to_str(breakpoint->orig_instr,
2882 breakpoint->length, 16);
2883 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2884 breakpoint->address,
2886 breakpoint->set, buf);
2891 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2892 breakpoint->address,
2893 breakpoint->length, breakpoint->set);
2896 breakpoint = breakpoint->next;
2901 static int handle_bp_command_set(struct command_context *cmd_ctx,
2902 uint32_t addr, uint32_t length, int hw)
2904 struct target *target = get_current_target(cmd_ctx);
2905 int retval = breakpoint_add(target, addr, length, hw);
2906 if (ERROR_OK == retval)
2907 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2909 LOG_ERROR("Failure setting breakpoint");
2913 COMMAND_HANDLER(handle_bp_command)
2916 return handle_bp_command_list(CMD_CTX);
2918 if (CMD_ARGC < 2 || CMD_ARGC > 3)
2920 command_print(CMD_CTX, "usage: bp <address> <length> ['hw']");
2921 return ERROR_COMMAND_SYNTAX_ERROR;
2925 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2927 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2932 if (strcmp(CMD_ARGV[2], "hw") == 0)
2935 return ERROR_COMMAND_SYNTAX_ERROR;
2938 return handle_bp_command_set(CMD_CTX, addr, length, hw);
2941 COMMAND_HANDLER(handle_rbp_command)
2944 return ERROR_COMMAND_SYNTAX_ERROR;
2947 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2949 struct target *target = get_current_target(CMD_CTX);
2950 breakpoint_remove(target, addr);
2955 COMMAND_HANDLER(handle_wp_command)
2957 struct target *target = get_current_target(CMD_CTX);
2961 struct watchpoint *watchpoint = target->watchpoints;
2965 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
2966 ", len: 0x%8.8" PRIx32
2967 ", r/w/a: %i, value: 0x%8.8" PRIx32
2968 ", mask: 0x%8.8" PRIx32,
2969 watchpoint->address,
2971 (int)watchpoint->rw,
2974 watchpoint = watchpoint->next;
2979 enum watchpoint_rw type = WPT_ACCESS;
2981 uint32_t length = 0;
2982 uint32_t data_value = 0x0;
2983 uint32_t data_mask = 0xffffffff;
2988 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
2991 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
2994 switch (CMD_ARGV[2][0])
3006 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3007 return ERROR_COMMAND_SYNTAX_ERROR;
3011 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3012 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3016 command_print(CMD_CTX, "usage: wp [address length "
3017 "[(r|w|a) [value [mask]]]]");
3018 return ERROR_COMMAND_SYNTAX_ERROR;
3021 int retval = watchpoint_add(target, addr, length, type,
3022 data_value, data_mask);
3023 if (ERROR_OK != retval)
3024 LOG_ERROR("Failure setting watchpoints");
3029 COMMAND_HANDLER(handle_rwp_command)
3032 return ERROR_COMMAND_SYNTAX_ERROR;
3035 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3037 struct target *target = get_current_target(CMD_CTX);
3038 watchpoint_remove(target, addr);
3045 * Translate a virtual address to a physical address.
3047 * The low-level target implementation must have logged a detailed error
3048 * which is forwarded to telnet/GDB session.
3050 COMMAND_HANDLER(handle_virt2phys_command)
3053 return ERROR_COMMAND_SYNTAX_ERROR;
3056 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3059 struct target *target = get_current_target(CMD_CTX);
3060 int retval = target->type->virt2phys(target, va, &pa);
3061 if (retval == ERROR_OK)
3062 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3067 static void writeData(FILE *f, const void *data, size_t len)
3069 size_t written = fwrite(data, 1, len, f);
3071 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3074 static void writeLong(FILE *f, int l)
3077 for (i = 0; i < 4; i++)
3079 char c = (l >> (i*8))&0xff;
3080 writeData(f, &c, 1);
3085 static void writeString(FILE *f, char *s)
3087 writeData(f, s, strlen(s));
3090 /* Dump a gmon.out histogram file. */
3091 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3094 FILE *f = fopen(filename, "w");
3097 writeString(f, "gmon");
3098 writeLong(f, 0x00000001); /* Version */
3099 writeLong(f, 0); /* padding */
3100 writeLong(f, 0); /* padding */
3101 writeLong(f, 0); /* padding */
3103 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3104 writeData(f, &zero, 1);
3106 /* figure out bucket size */
3107 uint32_t min = samples[0];
3108 uint32_t max = samples[0];
3109 for (i = 0; i < sampleNum; i++)
3111 if (min > samples[i])
3115 if (max < samples[i])
3121 int addressSpace = (max-min + 1);
3123 static const uint32_t maxBuckets = 16 * 1024; /* maximum buckets. */
3124 uint32_t length = addressSpace;
3125 if (length > maxBuckets)
3127 length = maxBuckets;
3129 int *buckets = malloc(sizeof(int)*length);
3130 if (buckets == NULL)
3135 memset(buckets, 0, sizeof(int)*length);
3136 for (i = 0; i < sampleNum;i++)
3138 uint32_t address = samples[i];
3139 long long a = address-min;
3140 long long b = length-1;
3141 long long c = addressSpace-1;
3142 int index_t = (a*b)/c; /* danger!!!! int32 overflows */
3146 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3147 writeLong(f, min); /* low_pc */
3148 writeLong(f, max); /* high_pc */
3149 writeLong(f, length); /* # of samples */
3150 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3151 writeString(f, "seconds");
3152 for (i = 0; i < (15-strlen("seconds")); i++)
3153 writeData(f, &zero, 1);
3154 writeString(f, "s");
3156 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3158 char *data = malloc(2*length);
3161 for (i = 0; i < length;i++)
3170 data[i*2 + 1]=(val >> 8)&0xff;
3173 writeData(f, data, length * 2);
3183 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3184 * which will be used as a random sampling of PC */
3185 COMMAND_HANDLER(handle_profile_command)
3187 struct target *target = get_current_target(CMD_CTX);
3188 struct timeval timeout, now;
3190 gettimeofday(&timeout, NULL);
3193 return ERROR_COMMAND_SYNTAX_ERROR;
3196 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3198 timeval_add_time(&timeout, offset, 0);
3201 * @todo: Some cores let us sample the PC without the
3202 * annoying halt/resume step; for example, ARMv7 PCSR.
3203 * Provide a way to use that more efficient mechanism.
3206 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3208 static const int maxSample = 10000;
3209 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3210 if (samples == NULL)
3214 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3215 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3220 target_poll(target);
3221 if (target->state == TARGET_HALTED)
3223 uint32_t t=*((uint32_t *)reg->value);
3224 samples[numSamples++]=t;
3225 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3226 target_poll(target);
3227 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3228 } else if (target->state == TARGET_RUNNING)
3230 /* We want to quickly sample the PC. */
3231 if ((retval = target_halt(target)) != ERROR_OK)
3238 command_print(CMD_CTX, "Target not halted or running");
3242 if (retval != ERROR_OK)
3247 gettimeofday(&now, NULL);
3248 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3250 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3251 if ((retval = target_poll(target)) != ERROR_OK)
3256 if (target->state == TARGET_HALTED)
3258 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3260 if ((retval = target_poll(target)) != ERROR_OK)
3265 writeGmon(samples, numSamples, CMD_ARGV[1]);
3266 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3275 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3278 Jim_Obj *nameObjPtr, *valObjPtr;
3281 namebuf = alloc_printf("%s(%d)", varname, idx);
3285 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3286 valObjPtr = Jim_NewIntObj(interp, val);
3287 if (!nameObjPtr || !valObjPtr)
3293 Jim_IncrRefCount(nameObjPtr);
3294 Jim_IncrRefCount(valObjPtr);
3295 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3296 Jim_DecrRefCount(interp, nameObjPtr);
3297 Jim_DecrRefCount(interp, valObjPtr);
3299 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3303 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3305 struct command_context *context;
3306 struct target *target;
3308 context = current_command_context(interp);
3309 assert (context != NULL);
3311 target = get_current_target(context);
3314 LOG_ERROR("mem2array: no current target");
3318 return target_mem2array(interp, target, argc-1, argv + 1);
3321 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3329 const char *varname;
3333 /* argv[1] = name of array to receive the data
3334 * argv[2] = desired width
3335 * argv[3] = memory address
3336 * argv[4] = count of times to read
3339 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3342 varname = Jim_GetString(argv[0], &len);
3343 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3345 e = Jim_GetLong(interp, argv[1], &l);
3351 e = Jim_GetLong(interp, argv[2], &l);
3356 e = Jim_GetLong(interp, argv[3], &l);
3372 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3373 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3377 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3378 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3381 if ((addr + (len * width)) < addr) {
3382 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3383 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3386 /* absurd transfer size? */
3388 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3389 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3394 ((width == 2) && ((addr & 1) == 0)) ||
3395 ((width == 4) && ((addr & 3) == 0))) {
3399 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3400 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3403 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3412 size_t buffersize = 4096;
3413 uint8_t *buffer = malloc(buffersize);
3420 /* Slurp... in buffer size chunks */
3422 count = len; /* in objects.. */
3423 if (count > (buffersize/width)) {
3424 count = (buffersize/width);
3427 retval = target_read_memory(target, addr, width, count, buffer);
3428 if (retval != ERROR_OK) {
3430 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3434 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3435 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3439 v = 0; /* shut up gcc */
3440 for (i = 0 ;i < count ;i++, n++) {
3443 v = target_buffer_get_u32(target, &buffer[i*width]);
3446 v = target_buffer_get_u16(target, &buffer[i*width]);
3449 v = buffer[i] & 0x0ff;
3452 new_int_array_element(interp, varname, n, v);
3460 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3465 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3468 Jim_Obj *nameObjPtr, *valObjPtr;
3472 namebuf = alloc_printf("%s(%d)", varname, idx);
3476 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3483 Jim_IncrRefCount(nameObjPtr);
3484 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3485 Jim_DecrRefCount(interp, nameObjPtr);
3487 if (valObjPtr == NULL)
3490 result = Jim_GetLong(interp, valObjPtr, &l);
3491 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3496 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3498 struct command_context *context;
3499 struct target *target;
3501 context = current_command_context(interp);
3502 assert (context != NULL);
3504 target = get_current_target(context);
3505 if (target == NULL) {
3506 LOG_ERROR("array2mem: no current target");
3510 return target_array2mem(interp,target, argc-1, argv + 1);
3513 static int target_array2mem(Jim_Interp *interp, struct target *target,
3514 int argc, Jim_Obj *const *argv)
3522 const char *varname;
3526 /* argv[1] = name of array to get the data
3527 * argv[2] = desired width
3528 * argv[3] = memory address
3529 * argv[4] = count to write
3532 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3535 varname = Jim_GetString(argv[0], &len);
3536 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3538 e = Jim_GetLong(interp, argv[1], &l);
3544 e = Jim_GetLong(interp, argv[2], &l);
3549 e = Jim_GetLong(interp, argv[3], &l);
3565 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3566 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3570 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3571 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3574 if ((addr + (len * width)) < addr) {
3575 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3576 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3579 /* absurd transfer size? */
3581 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3582 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3587 ((width == 2) && ((addr & 1) == 0)) ||
3588 ((width == 4) && ((addr & 3) == 0))) {
3592 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3593 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3596 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3607 size_t buffersize = 4096;
3608 uint8_t *buffer = malloc(buffersize);
3613 /* Slurp... in buffer size chunks */
3615 count = len; /* in objects.. */
3616 if (count > (buffersize/width)) {
3617 count = (buffersize/width);
3620 v = 0; /* shut up gcc */
3621 for (i = 0 ;i < count ;i++, n++) {
3622 get_int_array_element(interp, varname, n, &v);
3625 target_buffer_set_u32(target, &buffer[i*width], v);
3628 target_buffer_set_u16(target, &buffer[i*width], v);
3631 buffer[i] = v & 0x0ff;
3637 retval = target_write_memory(target, addr, width, count, buffer);
3638 if (retval != ERROR_OK) {
3640 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3644 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3645 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3653 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3658 /* FIX? should we propagate errors here rather than printing them
3661 void target_handle_event(struct target *target, enum target_event e)
3663 struct target_event_action *teap;
3665 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3666 if (teap->event == e) {
3667 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3668 target->target_number,
3669 target_name(target),
3670 target_type_name(target),
3672 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3673 Jim_GetString(teap->body, NULL));
3674 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK)
3676 Jim_MakeErrorMessage(teap->interp);
3677 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
3684 * Returns true only if the target has a handler for the specified event.
3686 bool target_has_event_action(struct target *target, enum target_event event)
3688 struct target_event_action *teap;
3690 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3691 if (teap->event == event)
3697 enum target_cfg_param {
3700 TCFG_WORK_AREA_VIRT,
3701 TCFG_WORK_AREA_PHYS,
3702 TCFG_WORK_AREA_SIZE,
3703 TCFG_WORK_AREA_BACKUP,
3707 TCFG_CHAIN_POSITION,
3710 static Jim_Nvp nvp_config_opts[] = {
3711 { .name = "-type", .value = TCFG_TYPE },
3712 { .name = "-event", .value = TCFG_EVENT },
3713 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3714 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3715 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3716 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3717 { .name = "-endian" , .value = TCFG_ENDIAN },
3718 { .name = "-variant", .value = TCFG_VARIANT },
3719 { .name = "-coreid", .value = TCFG_COREID },
3720 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3721 { .name = NULL, .value = -1 }
3724 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3732 /* parse config or cget options ... */
3733 while (goi->argc > 0) {
3734 Jim_SetEmptyResult(goi->interp);
3735 /* Jim_GetOpt_Debug(goi); */
3737 if (target->type->target_jim_configure) {
3738 /* target defines a configure function */
3739 /* target gets first dibs on parameters */
3740 e = (*(target->type->target_jim_configure))(target, goi);
3749 /* otherwise we 'continue' below */
3751 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3753 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3759 if (goi->isconfigure) {
3760 Jim_SetResultFormatted(goi->interp,
3761 "not settable: %s", n->name);
3765 if (goi->argc != 0) {
3766 Jim_WrongNumArgs(goi->interp,
3767 goi->argc, goi->argv,
3772 Jim_SetResultString(goi->interp,
3773 target_type_name(target), -1);
3777 if (goi->argc == 0) {
3778 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3782 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3784 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3788 if (goi->isconfigure) {
3789 if (goi->argc != 1) {
3790 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3794 if (goi->argc != 0) {
3795 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3801 struct target_event_action *teap;
3803 teap = target->event_action;
3804 /* replace existing? */
3806 if (teap->event == (enum target_event)n->value) {
3812 if (goi->isconfigure) {
3813 bool replace = true;
3816 teap = calloc(1, sizeof(*teap));
3819 teap->event = n->value;
3820 teap->interp = goi->interp;
3821 Jim_GetOpt_Obj(goi, &o);
3823 Jim_DecrRefCount(teap->interp, teap->body);
3825 teap->body = Jim_DuplicateObj(goi->interp, o);
3828 * Tcl/TK - "tk events" have a nice feature.
3829 * See the "BIND" command.
3830 * We should support that here.
3831 * You can specify %X and %Y in the event code.
3832 * The idea is: %T - target name.
3833 * The idea is: %N - target number
3834 * The idea is: %E - event name.
3836 Jim_IncrRefCount(teap->body);
3840 /* add to head of event list */
3841 teap->next = target->event_action;
3842 target->event_action = teap;
3844 Jim_SetEmptyResult(goi->interp);
3848 Jim_SetEmptyResult(goi->interp);
3850 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3857 case TCFG_WORK_AREA_VIRT:
3858 if (goi->isconfigure) {
3859 target_free_all_working_areas(target);
3860 e = Jim_GetOpt_Wide(goi, &w);
3864 target->working_area_virt = w;
3865 target->working_area_virt_spec = true;
3867 if (goi->argc != 0) {
3871 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3875 case TCFG_WORK_AREA_PHYS:
3876 if (goi->isconfigure) {
3877 target_free_all_working_areas(target);
3878 e = Jim_GetOpt_Wide(goi, &w);
3882 target->working_area_phys = w;
3883 target->working_area_phys_spec = true;
3885 if (goi->argc != 0) {
3889 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3893 case TCFG_WORK_AREA_SIZE:
3894 if (goi->isconfigure) {
3895 target_free_all_working_areas(target);
3896 e = Jim_GetOpt_Wide(goi, &w);
3900 target->working_area_size = w;
3902 if (goi->argc != 0) {
3906 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3910 case TCFG_WORK_AREA_BACKUP:
3911 if (goi->isconfigure) {
3912 target_free_all_working_areas(target);
3913 e = Jim_GetOpt_Wide(goi, &w);
3917 /* make this exactly 1 or 0 */
3918 target->backup_working_area = (!!w);
3920 if (goi->argc != 0) {
3924 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3925 /* loop for more e*/
3929 if (goi->isconfigure) {
3930 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3932 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3935 target->endianness = n->value;
3937 if (goi->argc != 0) {
3941 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3942 if (n->name == NULL) {
3943 target->endianness = TARGET_LITTLE_ENDIAN;
3944 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3946 Jim_SetResultString(goi->interp, n->name, -1);
3951 if (goi->isconfigure) {
3952 if (goi->argc < 1) {
3953 Jim_SetResultFormatted(goi->interp,
3958 if (target->variant) {
3959 free((void *)(target->variant));
3961 e = Jim_GetOpt_String(goi, &cp, NULL);
3962 target->variant = strdup(cp);
3964 if (goi->argc != 0) {
3968 Jim_SetResultString(goi->interp, target->variant,-1);
3973 if (goi->isconfigure) {
3974 e = Jim_GetOpt_Wide(goi, &w);
3978 target->coreid = (int)w;
3980 if (goi->argc != 0) {
3984 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3988 case TCFG_CHAIN_POSITION:
3989 if (goi->isconfigure) {
3991 struct jtag_tap *tap;
3992 target_free_all_working_areas(target);
3993 e = Jim_GetOpt_Obj(goi, &o_t);
3997 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4001 /* make this exactly 1 or 0 */
4004 if (goi->argc != 0) {
4008 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4009 /* loop for more e*/
4012 } /* while (goi->argc) */
4015 /* done - we return */
4020 jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4024 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4025 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4026 int need_args = 1 + goi.isconfigure;
4027 if (goi.argc < need_args)
4029 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4031 ? "missing: -option VALUE ..."
4032 : "missing: -option ...");
4035 struct target *target = Jim_CmdPrivData(goi.interp);
4036 return target_configure(&goi, target);
4039 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4041 const char *cmd_name = Jim_GetString(argv[0], NULL);
4044 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4046 if (goi.argc < 2 || goi.argc > 4)
4048 Jim_SetResultFormatted(goi.interp,
4049 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4054 fn = target_write_memory_fast;
4057 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4060 struct Jim_Obj *obj;
4061 e = Jim_GetOpt_Obj(&goi, &obj);
4065 fn = target_write_phys_memory;
4069 e = Jim_GetOpt_Wide(&goi, &a);
4074 e = Jim_GetOpt_Wide(&goi, &b);
4081 e = Jim_GetOpt_Wide(&goi, &c);
4086 /* all args must be consumed */
4092 struct target *target = Jim_CmdPrivData(goi.interp);
4094 if (strcasecmp(cmd_name, "mww") == 0) {
4097 else if (strcasecmp(cmd_name, "mwh") == 0) {
4100 else if (strcasecmp(cmd_name, "mwb") == 0) {
4103 LOG_ERROR("command '%s' unknown: ", cmd_name);
4107 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4110 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4112 const char *cmd_name = Jim_GetString(argv[0], NULL);
4115 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4117 if ((goi.argc < 1) || (goi.argc > 3))
4119 Jim_SetResultFormatted(goi.interp,
4120 "usage: %s [phys] <address> [<count>]", cmd_name);
4124 int (*fn)(struct target *target,
4125 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4126 fn=target_read_memory;
4129 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4132 struct Jim_Obj *obj;
4133 e = Jim_GetOpt_Obj(&goi, &obj);
4137 fn=target_read_phys_memory;
4141 e = Jim_GetOpt_Wide(&goi, &a);
4146 if (goi.argc == 1) {
4147 e = Jim_GetOpt_Wide(&goi, &c);
4155 /* all args must be consumed */
4161 jim_wide b = 1; /* shut up gcc */
4162 if (strcasecmp(cmd_name, "mdw") == 0)
4164 else if (strcasecmp(cmd_name, "mdh") == 0)
4166 else if (strcasecmp(cmd_name, "mdb") == 0)
4169 LOG_ERROR("command '%s' unknown: ", cmd_name);
4173 /* convert count to "bytes" */
4176 struct target *target = Jim_CmdPrivData(goi.interp);
4177 uint8_t target_buf[32];
4184 e = fn(target, a, b, y / b, target_buf);
4185 if (e != ERROR_OK) {
4187 snprintf(tmp, sizeof(tmp), "%08lx", (long)a);
4188 Jim_SetResultFormatted(interp, "error reading target @ 0x%s", tmp);
4192 command_print(NULL, "0x%08x ", (int)(a));
4195 for (x = 0; x < 16 && x < y; x += 4)
4197 z = target_buffer_get_u32(target, &(target_buf[ x ]));
4198 command_print(NULL, "%08x ", (int)(z));
4200 for (; (x < 16) ; x += 4) {
4201 command_print(NULL, " ");
4205 for (x = 0; x < 16 && x < y; x += 2)
4207 z = target_buffer_get_u16(target, &(target_buf[ x ]));
4208 command_print(NULL, "%04x ", (int)(z));
4210 for (; (x < 16) ; x += 2) {
4211 command_print(NULL, " ");
4216 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4217 z = target_buffer_get_u8(target, &(target_buf[ x ]));
4218 command_print(NULL, "%02x ", (int)(z));
4220 for (; (x < 16) ; x += 1) {
4221 command_print(NULL, " ");
4225 /* ascii-ify the bytes */
4226 for (x = 0 ; x < y ; x++) {
4227 if ((target_buf[x] >= 0x20) &&
4228 (target_buf[x] <= 0x7e)) {
4232 target_buf[x] = '.';
4237 target_buf[x] = ' ';
4242 /* print - with a newline */
4243 command_print(NULL, "%s\n", target_buf);
4251 static int jim_target_mem2array(Jim_Interp *interp,
4252 int argc, Jim_Obj *const *argv)
4254 struct target *target = Jim_CmdPrivData(interp);
4255 return target_mem2array(interp, target, argc - 1, argv + 1);
4258 static int jim_target_array2mem(Jim_Interp *interp,
4259 int argc, Jim_Obj *const *argv)
4261 struct target *target = Jim_CmdPrivData(interp);
4262 return target_array2mem(interp, target, argc - 1, argv + 1);
4265 static int jim_target_tap_disabled(Jim_Interp *interp)
4267 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4271 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4275 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4278 struct target *target = Jim_CmdPrivData(interp);
4279 if (!target->tap->enabled)
4280 return jim_target_tap_disabled(interp);
4282 int e = target->type->examine(target);
4290 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4294 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4297 struct target *target = Jim_CmdPrivData(interp);
4299 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4305 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4309 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4312 struct target *target = Jim_CmdPrivData(interp);
4313 if (!target->tap->enabled)
4314 return jim_target_tap_disabled(interp);
4317 if (!(target_was_examined(target))) {
4318 e = ERROR_TARGET_NOT_EXAMINED;
4320 e = target->type->poll(target);
4329 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4332 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4336 Jim_WrongNumArgs(interp, 0, argv,
4337 "([tT]|[fF]|assert|deassert) BOOL");
4342 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4345 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4348 /* the halt or not param */
4350 e = Jim_GetOpt_Wide(&goi, &a);
4354 struct target *target = Jim_CmdPrivData(goi.interp);
4355 if (!target->tap->enabled)
4356 return jim_target_tap_disabled(interp);
4357 if (!(target_was_examined(target)))
4359 LOG_ERROR("Target not examined yet");
4360 return ERROR_TARGET_NOT_EXAMINED;
4362 if (!target->type->assert_reset || !target->type->deassert_reset)
4364 Jim_SetResultFormatted(interp,
4365 "No target-specific reset for %s",
4366 target_name(target));
4369 /* determine if we should halt or not. */
4370 target->reset_halt = !!a;
4371 /* When this happens - all workareas are invalid. */
4372 target_free_all_working_areas_restore(target, 0);
4375 if (n->value == NVP_ASSERT) {
4376 e = target->type->assert_reset(target);
4378 e = target->type->deassert_reset(target);
4380 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4383 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4386 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4389 struct target *target = Jim_CmdPrivData(interp);
4390 if (!target->tap->enabled)
4391 return jim_target_tap_disabled(interp);
4392 int e = target->type->halt(target);
4393 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4396 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4399 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4401 /* params: <name> statename timeoutmsecs */
4404 const char *cmd_name = Jim_GetString(argv[0], NULL);
4405 Jim_SetResultFormatted(goi.interp,
4406 "%s <state_name> <timeout_in_msec>", cmd_name);
4411 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4413 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4417 e = Jim_GetOpt_Wide(&goi, &a);
4421 struct target *target = Jim_CmdPrivData(interp);
4422 if (!target->tap->enabled)
4423 return jim_target_tap_disabled(interp);
4425 e = target_wait_state(target, n->value, a);
4428 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4429 Jim_SetResultFormatted(goi.interp,
4430 "target: %s wait %s fails (%#s) %s",
4431 target_name(target), n->name,
4432 eObj, target_strerror_safe(e));
4433 Jim_FreeNewObj(interp, eObj);
4438 /* List for human, Events defined for this target.
4439 * scripts/programs should use 'name cget -event NAME'
4441 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4443 struct command_context *cmd_ctx = current_command_context(interp);
4444 assert (cmd_ctx != NULL);
4446 struct target *target = Jim_CmdPrivData(interp);
4447 struct target_event_action *teap = target->event_action;
4448 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4449 target->target_number,
4450 target_name(target));
4451 command_print(cmd_ctx, "%-25s | Body", "Event");
4452 command_print(cmd_ctx, "------------------------- | "
4453 "----------------------------------------");
4456 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4457 command_print(cmd_ctx, "%-25s | %s",
4458 opt->name, Jim_GetString(teap->body, NULL));
4461 command_print(cmd_ctx, "***END***");
4464 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4468 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4471 struct target *target = Jim_CmdPrivData(interp);
4472 Jim_SetResultString(interp, target_state_name(target), -1);
4475 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4478 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4481 const char *cmd_name = Jim_GetString(argv[0], NULL);
4482 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4486 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4489 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4492 struct target *target = Jim_CmdPrivData(interp);
4493 target_handle_event(target, n->value);
4497 static const struct command_registration target_instance_command_handlers[] = {
4499 .name = "configure",
4500 .mode = COMMAND_CONFIG,
4501 .jim_handler = jim_target_configure,
4502 .help = "configure a new target for use",
4503 .usage = "[target_attribute ...]",
4507 .mode = COMMAND_ANY,
4508 .jim_handler = jim_target_configure,
4509 .help = "returns the specified target attribute",
4510 .usage = "target_attribute",
4514 .mode = COMMAND_EXEC,
4515 .jim_handler = jim_target_mw,
4516 .help = "Write 32-bit word(s) to target memory",
4517 .usage = "address data [count]",
4521 .mode = COMMAND_EXEC,
4522 .jim_handler = jim_target_mw,
4523 .help = "Write 16-bit half-word(s) to target memory",
4524 .usage = "address data [count]",
4528 .mode = COMMAND_EXEC,
4529 .jim_handler = jim_target_mw,
4530 .help = "Write byte(s) to target memory",
4531 .usage = "address data [count]",
4535 .mode = COMMAND_EXEC,
4536 .jim_handler = jim_target_md,
4537 .help = "Display target memory as 32-bit words",
4538 .usage = "address [count]",
4542 .mode = COMMAND_EXEC,
4543 .jim_handler = jim_target_md,
4544 .help = "Display target memory as 16-bit half-words",
4545 .usage = "address [count]",
4549 .mode = COMMAND_EXEC,
4550 .jim_handler = jim_target_md,
4551 .help = "Display target memory as 8-bit bytes",
4552 .usage = "address [count]",
4555 .name = "array2mem",
4556 .mode = COMMAND_EXEC,
4557 .jim_handler = jim_target_array2mem,
4558 .help = "Writes Tcl array of 8/16/32 bit numbers "
4560 .usage = "arrayname bitwidth address count",
4563 .name = "mem2array",
4564 .mode = COMMAND_EXEC,
4565 .jim_handler = jim_target_mem2array,
4566 .help = "Loads Tcl array of 8/16/32 bit numbers "
4567 "from target memory",
4568 .usage = "arrayname bitwidth address count",
4571 .name = "eventlist",
4572 .mode = COMMAND_EXEC,
4573 .jim_handler = jim_target_event_list,
4574 .help = "displays a table of events defined for this target",
4578 .mode = COMMAND_EXEC,
4579 .jim_handler = jim_target_current_state,
4580 .help = "displays the current state of this target",
4583 .name = "arp_examine",
4584 .mode = COMMAND_EXEC,
4585 .jim_handler = jim_target_examine,
4586 .help = "used internally for reset processing",
4589 .name = "arp_halt_gdb",
4590 .mode = COMMAND_EXEC,
4591 .jim_handler = jim_target_halt_gdb,
4592 .help = "used internally for reset processing to halt GDB",
4596 .mode = COMMAND_EXEC,
4597 .jim_handler = jim_target_poll,
4598 .help = "used internally for reset processing",
4601 .name = "arp_reset",
4602 .mode = COMMAND_EXEC,
4603 .jim_handler = jim_target_reset,
4604 .help = "used internally for reset processing",
4608 .mode = COMMAND_EXEC,
4609 .jim_handler = jim_target_halt,
4610 .help = "used internally for reset processing",
4613 .name = "arp_waitstate",
4614 .mode = COMMAND_EXEC,
4615 .jim_handler = jim_target_wait_state,
4616 .help = "used internally for reset processing",
4619 .name = "invoke-event",
4620 .mode = COMMAND_EXEC,
4621 .jim_handler = jim_target_invoke_event,
4622 .help = "invoke handler for specified event",
4623 .usage = "event_name",
4625 COMMAND_REGISTRATION_DONE
4628 static int target_create(Jim_GetOptInfo *goi)
4636 struct target *target;
4637 struct command_context *cmd_ctx;
4639 cmd_ctx = current_command_context(goi->interp);
4640 assert (cmd_ctx != NULL);
4642 if (goi->argc < 3) {
4643 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4648 Jim_GetOpt_Obj(goi, &new_cmd);
4649 /* does this command exist? */
4650 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4652 cp = Jim_GetString(new_cmd, NULL);
4653 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
4658 e = Jim_GetOpt_String(goi, &cp2, NULL);
4660 /* now does target type exist */
4661 for (x = 0 ; target_types[x] ; x++) {
4662 if (0 == strcmp(cp, target_types[x]->name)) {
4667 if (target_types[x] == NULL) {
4668 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
4669 for (x = 0 ; target_types[x] ; x++) {
4670 if (target_types[x + 1]) {
4671 Jim_AppendStrings(goi->interp,
4672 Jim_GetResult(goi->interp),
4673 target_types[x]->name,
4676 Jim_AppendStrings(goi->interp,
4677 Jim_GetResult(goi->interp),
4679 target_types[x]->name,NULL);
4686 target = calloc(1,sizeof(struct target));
4687 /* set target number */
4688 target->target_number = new_target_number();
4690 /* allocate memory for each unique target type */
4691 target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4693 memcpy(target->type, target_types[x], sizeof(struct target_type));
4695 /* will be set by "-endian" */
4696 target->endianness = TARGET_ENDIAN_UNKNOWN;
4698 /* default to first core, override with -coreid */
4701 target->working_area = 0x0;
4702 target->working_area_size = 0x0;
4703 target->working_areas = NULL;
4704 target->backup_working_area = 0;
4706 target->state = TARGET_UNKNOWN;
4707 target->debug_reason = DBG_REASON_UNDEFINED;
4708 target->reg_cache = NULL;
4709 target->breakpoints = NULL;
4710 target->watchpoints = NULL;
4711 target->next = NULL;
4712 target->arch_info = NULL;
4714 target->display = 1;
4716 target->halt_issued = false;
4718 /* initialize trace information */
4719 target->trace_info = malloc(sizeof(struct trace));
4720 target->trace_info->num_trace_points = 0;
4721 target->trace_info->trace_points_size = 0;
4722 target->trace_info->trace_points = NULL;
4723 target->trace_info->trace_history_size = 0;
4724 target->trace_info->trace_history = NULL;
4725 target->trace_info->trace_history_pos = 0;
4726 target->trace_info->trace_history_overflowed = 0;
4728 target->dbgmsg = NULL;
4729 target->dbg_msg_enabled = 0;
4731 target->endianness = TARGET_ENDIAN_UNKNOWN;
4733 /* Do the rest as "configure" options */
4734 goi->isconfigure = 1;
4735 e = target_configure(goi, target);
4737 if (target->tap == NULL)
4739 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4749 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4750 /* default endian to little if not specified */
4751 target->endianness = TARGET_LITTLE_ENDIAN;
4754 /* incase variant is not set */
4755 if (!target->variant)
4756 target->variant = strdup("");
4758 cp = Jim_GetString(new_cmd, NULL);
4759 target->cmd_name = strdup(cp);
4761 /* create the target specific commands */
4762 if (target->type->commands) {
4763 e = register_commands(cmd_ctx, NULL, target->type->commands);
4765 LOG_ERROR("unable to register '%s' commands", cp);
4767 if (target->type->target_create) {
4768 (*(target->type->target_create))(target, goi->interp);
4771 /* append to end of list */
4773 struct target **tpp;
4774 tpp = &(all_targets);
4776 tpp = &((*tpp)->next);
4781 /* now - create the new target name command */
4782 const const struct command_registration target_subcommands[] = {
4784 .chain = target_instance_command_handlers,
4787 .chain = target->type->commands,
4789 COMMAND_REGISTRATION_DONE
4791 const const struct command_registration target_commands[] = {
4794 .mode = COMMAND_ANY,
4795 .help = "target command group",
4796 .chain = target_subcommands,
4798 COMMAND_REGISTRATION_DONE
4800 e = register_commands(cmd_ctx, NULL, target_commands);
4804 struct command *c = command_find_in_context(cmd_ctx, cp);
4806 command_set_handler_data(c, target);
4808 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
4811 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4815 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4818 struct command_context *cmd_ctx = current_command_context(interp);
4819 assert (cmd_ctx != NULL);
4821 Jim_SetResultString(interp, get_current_target(cmd_ctx)->cmd_name, -1);
4825 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4829 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4832 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4833 for (unsigned x = 0; NULL != target_types[x]; x++)
4835 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4836 Jim_NewStringObj(interp, target_types[x]->name, -1));
4841 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4845 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4848 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4849 struct target *target = all_targets;
4852 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4853 Jim_NewStringObj(interp, target_name(target), -1));
4854 target = target->next;
4859 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4862 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4865 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4866 "<name> <target_type> [<target_options> ...]");
4869 return target_create(&goi);
4872 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4875 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4877 /* It's OK to remove this mechanism sometime after August 2010 or so */
4878 LOG_WARNING("don't use numbers as target identifiers; use names");
4881 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
4885 int e = Jim_GetOpt_Wide(&goi, &w);
4889 struct target *target;
4890 for (target = all_targets; NULL != target; target = target->next)
4892 if (target->target_number != w)
4895 Jim_SetResultString(goi.interp, target_name(target), -1);
4899 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
4900 Jim_SetResultFormatted(goi.interp,
4901 "Target: number %#s does not exist", wObj);
4902 Jim_FreeNewObj(interp, wObj);
4907 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4911 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
4915 struct target *target = all_targets;
4916 while (NULL != target)
4918 target = target->next;
4921 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
4925 static const struct command_registration target_subcommand_handlers[] = {
4928 .mode = COMMAND_CONFIG,
4929 .handler = handle_target_init_command,
4930 .help = "initialize targets",
4934 /* REVISIT this should be COMMAND_CONFIG ... */
4935 .mode = COMMAND_ANY,
4936 .jim_handler = jim_target_create,
4937 .usage = "name type '-chain-position' name [options ...]",
4938 .help = "Creates and selects a new target",
4942 .mode = COMMAND_ANY,
4943 .jim_handler = jim_target_current,
4944 .help = "Returns the currently selected target",
4948 .mode = COMMAND_ANY,
4949 .jim_handler = jim_target_types,
4950 .help = "Returns the available target types as "
4951 "a list of strings",
4955 .mode = COMMAND_ANY,
4956 .jim_handler = jim_target_names,
4957 .help = "Returns the names of all targets as a list of strings",
4961 .mode = COMMAND_ANY,
4962 .jim_handler = jim_target_number,
4964 .help = "Returns the name of the numbered target "
4969 .mode = COMMAND_ANY,
4970 .jim_handler = jim_target_count,
4971 .help = "Returns the number of targets as an integer "
4974 COMMAND_REGISTRATION_DONE
4985 static int fastload_num;
4986 static struct FastLoad *fastload;
4988 static void free_fastload(void)
4990 if (fastload != NULL)
4993 for (i = 0; i < fastload_num; i++)
4995 if (fastload[i].data)
4996 free(fastload[i].data);
5006 COMMAND_HANDLER(handle_fast_load_image_command)
5010 uint32_t image_size;
5011 uint32_t min_address = 0;
5012 uint32_t max_address = 0xffffffff;
5017 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5018 &image, &min_address, &max_address);
5019 if (ERROR_OK != retval)
5022 struct duration bench;
5023 duration_start(&bench);
5025 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5026 if (retval != ERROR_OK)
5033 fastload_num = image.num_sections;
5034 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
5035 if (fastload == NULL)
5037 command_print(CMD_CTX, "out of memory");
5038 image_close(&image);
5041 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5042 for (i = 0; i < image.num_sections; i++)
5044 buffer = malloc(image.sections[i].size);
5047 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5048 (int)(image.sections[i].size));
5049 retval = ERROR_FAIL;
5053 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
5059 uint32_t offset = 0;
5060 uint32_t length = buf_cnt;
5063 /* DANGER!!! beware of unsigned comparision here!!! */
5065 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
5066 (image.sections[i].base_address < max_address))
5068 if (image.sections[i].base_address < min_address)
5070 /* clip addresses below */
5071 offset += min_address-image.sections[i].base_address;
5075 if (image.sections[i].base_address + buf_cnt > max_address)
5077 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5080 fastload[i].address = image.sections[i].base_address + offset;
5081 fastload[i].data = malloc(length);
5082 if (fastload[i].data == NULL)
5085 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5087 retval = ERROR_FAIL;
5090 memcpy(fastload[i].data, buffer + offset, length);
5091 fastload[i].length = length;
5093 image_size += length;
5094 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5095 (unsigned int)length,
5096 ((unsigned int)(image.sections[i].base_address + offset)));
5102 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
5104 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5105 "in %fs (%0.3f KiB/s)", image_size,
5106 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5108 command_print(CMD_CTX,
5109 "WARNING: image has not been loaded to target!"
5110 "You can issue a 'fast_load' to finish loading.");
5113 image_close(&image);
5115 if (retval != ERROR_OK)
5123 COMMAND_HANDLER(handle_fast_load_command)
5126 return ERROR_COMMAND_SYNTAX_ERROR;
5127 if (fastload == NULL)
5129 LOG_ERROR("No image in memory");
5133 int ms = timeval_ms();
5135 int retval = ERROR_OK;
5136 for (i = 0; i < fastload_num;i++)
5138 struct target *target = get_current_target(CMD_CTX);
5139 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5140 (unsigned int)(fastload[i].address),
5141 (unsigned int)(fastload[i].length));
5142 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5143 if (retval != ERROR_OK)
5147 size += fastload[i].length;
5149 if (retval == ERROR_OK)
5151 int after = timeval_ms();
5152 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5157 static const struct command_registration target_command_handlers[] = {
5160 .handler = handle_targets_command,
5161 .mode = COMMAND_ANY,
5162 .help = "change current default target (one parameter) "
5163 "or prints table of all targets (no parameters)",
5164 .usage = "[target]",
5168 .mode = COMMAND_CONFIG,
5169 .help = "configure target",
5171 .chain = target_subcommand_handlers,
5173 COMMAND_REGISTRATION_DONE
5176 int target_register_commands(struct command_context *cmd_ctx)
5178 return register_commands(cmd_ctx, NULL, target_command_handlers);
5181 static bool target_reset_nag = true;
5183 bool get_target_reset_nag(void)
5185 return target_reset_nag;
5188 COMMAND_HANDLER(handle_target_reset_nag)
5190 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5191 &target_reset_nag, "Nag after each reset about options to improve "
5195 static const struct command_registration target_exec_command_handlers[] = {
5197 .name = "fast_load_image",
5198 .handler = handle_fast_load_image_command,
5199 .mode = COMMAND_ANY,
5200 .help = "Load image into server memory for later use by "
5201 "fast_load; primarily for profiling",
5202 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5203 "[min_address [max_length]]",
5206 .name = "fast_load",
5207 .handler = handle_fast_load_command,
5208 .mode = COMMAND_EXEC,
5209 .help = "loads active fast load image to current target "
5210 "- mainly for profiling purposes",
5214 .handler = handle_profile_command,
5215 .mode = COMMAND_EXEC,
5216 .help = "profiling samples the CPU PC",
5218 /** @todo don't register virt2phys() unless target supports it */
5220 .name = "virt2phys",
5221 .handler = handle_virt2phys_command,
5222 .mode = COMMAND_ANY,
5223 .help = "translate a virtual address into a physical address",
5224 .usage = "virtual_address",
5228 .handler = handle_reg_command,
5229 .mode = COMMAND_EXEC,
5230 .help = "display or set a register; with no arguments, "
5231 "displays all registers and their values",
5232 .usage = "[(register_name|register_number) [value]]",
5236 .handler = handle_poll_command,
5237 .mode = COMMAND_EXEC,
5238 .help = "poll target state; or reconfigure background polling",
5239 .usage = "['on'|'off']",
5242 .name = "wait_halt",
5243 .handler = handle_wait_halt_command,
5244 .mode = COMMAND_EXEC,
5245 .help = "wait up to the specified number of milliseconds "
5246 "(default 5) for a previously requested halt",
5247 .usage = "[milliseconds]",
5251 .handler = handle_halt_command,
5252 .mode = COMMAND_EXEC,
5253 .help = "request target to halt, then wait up to the specified"
5254 "number of milliseconds (default 5) for it to complete",
5255 .usage = "[milliseconds]",
5259 .handler = handle_resume_command,
5260 .mode = COMMAND_EXEC,
5261 .help = "resume target execution from current PC or address",
5262 .usage = "[address]",
5266 .handler = handle_reset_command,
5267 .mode = COMMAND_EXEC,
5268 .usage = "[run|halt|init]",
5269 .help = "Reset all targets into the specified mode."
5270 "Default reset mode is run, if not given.",
5273 .name = "soft_reset_halt",
5274 .handler = handle_soft_reset_halt_command,
5275 .mode = COMMAND_EXEC,
5276 .help = "halt the target and do a soft reset",
5280 .handler = handle_step_command,
5281 .mode = COMMAND_EXEC,
5282 .help = "step one instruction from current PC or address",
5283 .usage = "[address]",
5287 .handler = handle_md_command,
5288 .mode = COMMAND_EXEC,
5289 .help = "display memory words",
5290 .usage = "['phys'] address [count]",
5294 .handler = handle_md_command,
5295 .mode = COMMAND_EXEC,
5296 .help = "display memory half-words",
5297 .usage = "['phys'] address [count]",
5301 .handler = handle_md_command,
5302 .mode = COMMAND_EXEC,
5303 .help = "display memory bytes",
5304 .usage = "['phys'] address [count]",
5308 .handler = handle_mw_command,
5309 .mode = COMMAND_EXEC,
5310 .help = "write memory word",
5311 .usage = "['phys'] address value [count]",
5315 .handler = handle_mw_command,
5316 .mode = COMMAND_EXEC,
5317 .help = "write memory half-word",
5318 .usage = "['phys'] address value [count]",
5322 .handler = handle_mw_command,
5323 .mode = COMMAND_EXEC,
5324 .help = "write memory byte",
5325 .usage = "['phys'] address value [count]",
5329 .handler = handle_bp_command,
5330 .mode = COMMAND_EXEC,
5331 .help = "list or set hardware or software breakpoint",
5332 .usage = "[address length ['hw']]",
5336 .handler = handle_rbp_command,
5337 .mode = COMMAND_EXEC,
5338 .help = "remove breakpoint",
5343 .handler = handle_wp_command,
5344 .mode = COMMAND_EXEC,
5345 .help = "list (no params) or create watchpoints",
5346 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5350 .handler = handle_rwp_command,
5351 .mode = COMMAND_EXEC,
5352 .help = "remove watchpoint",
5356 .name = "load_image",
5357 .handler = handle_load_image_command,
5358 .mode = COMMAND_EXEC,
5359 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5360 "[min_address] [max_length]",
5363 .name = "dump_image",
5364 .handler = handle_dump_image_command,
5365 .mode = COMMAND_EXEC,
5366 .usage = "filename address size",
5369 .name = "verify_image",
5370 .handler = handle_verify_image_command,
5371 .mode = COMMAND_EXEC,
5372 .usage = "filename [offset [type]]",
5375 .name = "test_image",
5376 .handler = handle_test_image_command,
5377 .mode = COMMAND_EXEC,
5378 .usage = "filename [offset [type]]",
5381 .name = "mem2array",
5382 .mode = COMMAND_EXEC,
5383 .jim_handler = jim_mem2array,
5384 .help = "read 8/16/32 bit memory and return as a TCL array "
5385 "for script processing",
5386 .usage = "arrayname bitwidth address count",
5389 .name = "array2mem",
5390 .mode = COMMAND_EXEC,
5391 .jim_handler = jim_array2mem,
5392 .help = "convert a TCL array to memory locations "
5393 "and write the 8/16/32 bit values",
5394 .usage = "arrayname bitwidth address count",
5397 .name = "reset_nag",
5398 .handler = handle_target_reset_nag,
5399 .mode = COMMAND_ANY,
5400 .help = "Nag after each reset about options that could have been "
5401 "enabled to improve performance. ",
5402 .usage = "['enable'|'disable']",
5404 COMMAND_REGISTRATION_DONE
5406 static int target_register_user_commands(struct command_context *cmd_ctx)
5408 int retval = ERROR_OK;
5409 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
5412 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
5416 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);