1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
5 * Copyright (C) 2007-2009 Ø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 ***************************************************************************/
37 #include "target_type.h"
38 #include "target_request.h"
39 #include "breakpoints.h"
40 #include "time_support.h"
47 static int target_array2mem(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv);
48 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv);
51 extern struct target_type arm7tdmi_target;
52 extern struct target_type arm720t_target;
53 extern struct target_type arm9tdmi_target;
54 extern struct target_type arm920t_target;
55 extern struct target_type arm966e_target;
56 extern struct target_type arm926ejs_target;
57 extern struct target_type fa526_target;
58 extern struct target_type feroceon_target;
59 extern struct target_type dragonite_target;
60 extern struct target_type xscale_target;
61 extern struct target_type cortexm3_target;
62 extern struct target_type cortexa8_target;
63 extern struct target_type arm11_target;
64 extern struct target_type mips_m4k_target;
65 extern struct target_type avr_target;
66 extern struct target_type testee_target;
68 struct target_type *target_types[] =
89 struct target *all_targets = NULL;
90 struct target_event_callback *target_event_callbacks = NULL;
91 struct target_timer_callback *target_timer_callbacks = NULL;
93 const Jim_Nvp nvp_assert[] = {
94 { .name = "assert", NVP_ASSERT },
95 { .name = "deassert", NVP_DEASSERT },
96 { .name = "T", NVP_ASSERT },
97 { .name = "F", NVP_DEASSERT },
98 { .name = "t", NVP_ASSERT },
99 { .name = "f", NVP_DEASSERT },
100 { .name = NULL, .value = -1 }
103 const Jim_Nvp nvp_error_target[] = {
104 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
105 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
106 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
107 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
108 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
109 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
110 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
111 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
112 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
113 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
114 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
115 { .value = -1, .name = NULL }
118 const char *target_strerror_safe(int err)
122 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
123 if (n->name == NULL) {
130 static const Jim_Nvp nvp_target_event[] = {
131 { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
132 { .value = TARGET_EVENT_OLD_pre_resume , .name = "old-pre_resume" },
134 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
135 { .value = TARGET_EVENT_HALTED, .name = "halted" },
136 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
137 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
138 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
140 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
141 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
143 /* historical name */
145 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
147 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
148 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
149 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
150 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
151 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
152 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
153 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
154 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
155 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
156 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
157 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
159 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
160 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
162 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
163 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
165 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
166 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
168 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
169 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
171 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
172 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
174 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
175 { .value = TARGET_EVENT_RESUMED , .name = "resume-ok" },
176 { .value = TARGET_EVENT_RESUME_END , .name = "resume-end" },
178 { .name = NULL, .value = -1 }
181 const Jim_Nvp nvp_target_state[] = {
182 { .name = "unknown", .value = TARGET_UNKNOWN },
183 { .name = "running", .value = TARGET_RUNNING },
184 { .name = "halted", .value = TARGET_HALTED },
185 { .name = "reset", .value = TARGET_RESET },
186 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
187 { .name = NULL, .value = -1 },
190 const Jim_Nvp nvp_target_debug_reason [] = {
191 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
192 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
193 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
194 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
195 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
196 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
197 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
198 { .name = NULL, .value = -1 },
201 const Jim_Nvp nvp_target_endian[] = {
202 { .name = "big", .value = TARGET_BIG_ENDIAN },
203 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
204 { .name = "be", .value = TARGET_BIG_ENDIAN },
205 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
206 { .name = NULL, .value = -1 },
209 const Jim_Nvp nvp_reset_modes[] = {
210 { .name = "unknown", .value = RESET_UNKNOWN },
211 { .name = "run" , .value = RESET_RUN },
212 { .name = "halt" , .value = RESET_HALT },
213 { .name = "init" , .value = RESET_INIT },
214 { .name = NULL , .value = -1 },
218 target_state_name( struct target *t )
221 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
223 LOG_ERROR("Invalid target state: %d", (int)(t->state));
224 cp = "(*BUG*unknown*BUG*)";
229 /* determine the number of the new target */
230 static int new_target_number(void)
235 /* number is 0 based */
239 if (x < t->target_number) {
240 x = t->target_number;
247 /* read a uint32_t from a buffer in target memory endianness */
248 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
250 if (target->endianness == TARGET_LITTLE_ENDIAN)
251 return le_to_h_u32(buffer);
253 return be_to_h_u32(buffer);
256 /* read a uint16_t from a buffer in target memory endianness */
257 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
259 if (target->endianness == TARGET_LITTLE_ENDIAN)
260 return le_to_h_u16(buffer);
262 return be_to_h_u16(buffer);
265 /* read a uint8_t from a buffer in target memory endianness */
266 uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
268 return *buffer & 0x0ff;
271 /* write a uint32_t to a buffer in target memory endianness */
272 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
274 if (target->endianness == TARGET_LITTLE_ENDIAN)
275 h_u32_to_le(buffer, value);
277 h_u32_to_be(buffer, value);
280 /* write a uint16_t to a buffer in target memory endianness */
281 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
283 if (target->endianness == TARGET_LITTLE_ENDIAN)
284 h_u16_to_le(buffer, value);
286 h_u16_to_be(buffer, value);
289 /* write a uint8_t to a buffer in target memory endianness */
290 void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
295 /* return a pointer to a configured target; id is name or number */
296 struct target *get_target(const char *id)
298 struct target *target;
300 /* try as tcltarget name */
301 for (target = all_targets; target; target = target->next) {
302 if (target->cmd_name == NULL)
304 if (strcmp(id, target->cmd_name) == 0)
308 /* It's OK to remove this fallback sometime after August 2010 or so */
310 /* no match, try as number */
312 if (parse_uint(id, &num) != ERROR_OK)
315 for (target = all_targets; target; target = target->next) {
316 if (target->target_number == (int)num) {
317 LOG_WARNING("use '%s' as target identifier, not '%u'",
318 target->cmd_name, num);
326 /* returns a pointer to the n-th configured target */
327 static struct target *get_target_by_num(int num)
329 struct target *target = all_targets;
332 if (target->target_number == num) {
335 target = target->next;
341 struct target* get_current_target(struct command_context *cmd_ctx)
343 struct target *target = get_target_by_num(cmd_ctx->current_target);
347 LOG_ERROR("BUG: current_target out of bounds");
354 int target_poll(struct target *target)
358 /* We can't poll until after examine */
359 if (!target_was_examined(target))
361 /* Fail silently lest we pollute the log */
365 retval = target->type->poll(target);
366 if (retval != ERROR_OK)
369 if (target->halt_issued)
371 if (target->state == TARGET_HALTED)
373 target->halt_issued = false;
376 long long t = timeval_ms() - target->halt_issued_time;
379 target->halt_issued = false;
380 LOG_INFO("Halt timed out, wake up GDB.");
381 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
389 int target_halt(struct target *target)
392 /* We can't poll until after examine */
393 if (!target_was_examined(target))
395 LOG_ERROR("Target not examined yet");
399 retval = target->type->halt(target);
400 if (retval != ERROR_OK)
403 target->halt_issued = true;
404 target->halt_issued_time = timeval_ms();
409 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
413 /* We can't poll until after examine */
414 if (!target_was_examined(target))
416 LOG_ERROR("Target not examined yet");
420 /* note that resume *must* be asynchronous. The CPU can halt before we poll. The CPU can
421 * even halt at the current PC as a result of a software breakpoint being inserted by (a bug?)
424 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
430 int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
435 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
436 if (n->name == NULL) {
437 LOG_ERROR("invalid reset mode");
441 /* disable polling during reset to make reset event scripts
442 * more predictable, i.e. dr/irscan & pathmove in events will
443 * not have JTAG operations injected into the middle of a sequence.
445 bool save_poll = jtag_poll_get_enabled();
447 jtag_poll_set_enabled(false);
449 sprintf(buf, "ocd_process_reset %s", n->name);
450 retval = Jim_Eval(cmd_ctx->interp, buf);
452 jtag_poll_set_enabled(save_poll);
454 if (retval != JIM_OK) {
455 Jim_PrintErrorMessage(cmd_ctx->interp);
459 /* We want any events to be processed before the prompt */
460 retval = target_call_timer_callbacks_now();
465 static int identity_virt2phys(struct target *target,
466 uint32_t virtual, uint32_t *physical)
472 static int no_mmu(struct target *target, int *enabled)
478 static int default_examine(struct target *target)
480 target_set_examined(target);
484 int target_examine_one(struct target *target)
486 return target->type->examine(target);
489 static int jtag_enable_callback(enum jtag_event event, void *priv)
491 struct target *target = priv;
493 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
496 jtag_unregister_event_callback(jtag_enable_callback, target);
497 return target_examine_one(target);
501 /* Targets that correctly implement init + examine, i.e.
502 * no communication with target during init:
506 int target_examine(void)
508 int retval = ERROR_OK;
509 struct target *target;
511 for (target = all_targets; target; target = target->next)
513 /* defer examination, but don't skip it */
514 if (!target->tap->enabled) {
515 jtag_register_event_callback(jtag_enable_callback,
519 if ((retval = target_examine_one(target)) != ERROR_OK)
524 const char *target_type_name(struct target *target)
526 return target->type->name;
529 static int target_write_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
531 if (!target_was_examined(target))
533 LOG_ERROR("Target not examined yet");
536 return target->type->write_memory_imp(target, address, size, count, buffer);
539 static int target_read_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
541 if (!target_was_examined(target))
543 LOG_ERROR("Target not examined yet");
546 return target->type->read_memory_imp(target, address, size, count, buffer);
549 static int target_soft_reset_halt_imp(struct target *target)
551 if (!target_was_examined(target))
553 LOG_ERROR("Target not examined yet");
556 if (!target->type->soft_reset_halt_imp) {
557 LOG_ERROR("Target %s does not support soft_reset_halt",
558 target_name(target));
561 return target->type->soft_reset_halt_imp(target);
564 static int target_run_algorithm_imp(struct target *target, int num_mem_params, struct mem_param *mem_params, int num_reg_params, struct reg_param *reg_param, uint32_t entry_point, uint32_t exit_point, int timeout_ms, void *arch_info)
566 if (!target_was_examined(target))
568 LOG_ERROR("Target not examined yet");
571 return target->type->run_algorithm_imp(target, num_mem_params, mem_params, num_reg_params, reg_param, entry_point, exit_point, timeout_ms, arch_info);
574 int target_read_memory(struct target *target,
575 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
577 return target->type->read_memory(target, address, size, count, buffer);
580 int target_read_phys_memory(struct target *target,
581 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
583 return target->type->read_phys_memory(target, address, size, count, buffer);
586 int target_write_memory(struct target *target,
587 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
589 return target->type->write_memory(target, address, size, count, buffer);
592 int target_write_phys_memory(struct target *target,
593 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
595 return target->type->write_phys_memory(target, address, size, count, buffer);
598 int target_bulk_write_memory(struct target *target,
599 uint32_t address, uint32_t count, uint8_t *buffer)
601 return target->type->bulk_write_memory(target, address, count, buffer);
604 int target_add_breakpoint(struct target *target,
605 struct breakpoint *breakpoint)
607 if (target->state != TARGET_HALTED) {
608 LOG_WARNING("target %s is not halted", target->cmd_name);
609 return ERROR_TARGET_NOT_HALTED;
611 return target->type->add_breakpoint(target, breakpoint);
613 int target_remove_breakpoint(struct target *target,
614 struct breakpoint *breakpoint)
616 return target->type->remove_breakpoint(target, breakpoint);
619 int target_add_watchpoint(struct target *target,
620 struct watchpoint *watchpoint)
622 if (target->state != TARGET_HALTED) {
623 LOG_WARNING("target %s is not halted", target->cmd_name);
624 return ERROR_TARGET_NOT_HALTED;
626 return target->type->add_watchpoint(target, watchpoint);
628 int target_remove_watchpoint(struct target *target,
629 struct watchpoint *watchpoint)
631 return target->type->remove_watchpoint(target, watchpoint);
634 int target_get_gdb_reg_list(struct target *target,
635 struct reg **reg_list[], int *reg_list_size)
637 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
639 int target_step(struct target *target,
640 int current, uint32_t address, int handle_breakpoints)
642 return target->type->step(target, current, address, handle_breakpoints);
646 int target_run_algorithm(struct target *target,
647 int num_mem_params, struct mem_param *mem_params,
648 int num_reg_params, struct reg_param *reg_param,
649 uint32_t entry_point, uint32_t exit_point,
650 int timeout_ms, void *arch_info)
652 return target->type->run_algorithm(target,
653 num_mem_params, mem_params, num_reg_params, reg_param,
654 entry_point, exit_point, timeout_ms, arch_info);
658 * Reset the @c examined flag for the given target.
659 * Pure paranoia -- targets are zeroed on allocation.
661 static void target_reset_examined(struct target *target)
663 target->examined = false;
667 err_read_phys_memory(struct target *target, uint32_t address,
668 uint32_t size, uint32_t count, uint8_t *buffer)
670 LOG_ERROR("Not implemented: %s", __func__);
675 err_write_phys_memory(struct target *target, uint32_t address,
676 uint32_t size, uint32_t count, uint8_t *buffer)
678 LOG_ERROR("Not implemented: %s", __func__);
682 static int handle_target(void *priv);
684 int target_init(struct command_context *cmd_ctx)
686 struct target *target;
689 for (target = all_targets; target; target = target->next) {
690 struct target_type *type = target->type;
692 target_reset_examined(target);
693 if (target->type->examine == NULL)
695 target->type->examine = default_examine;
698 if ((retval = target->type->init_target(cmd_ctx, target)) != ERROR_OK)
700 LOG_ERROR("target '%s' init failed", target_name(target));
706 * @todo get rid of those *memory_imp() methods, now that all
707 * callers are using target_*_memory() accessors ... and make
708 * sure the "physical" paths handle the same issues.
711 /* a non-invasive way(in terms of patches) to add some code that
712 * runs before the type->write/read_memory implementation
714 target->type->write_memory_imp = target->type->write_memory;
715 target->type->write_memory = target_write_memory_imp;
716 target->type->read_memory_imp = target->type->read_memory;
717 target->type->read_memory = target_read_memory_imp;
718 target->type->soft_reset_halt_imp = target->type->soft_reset_halt;
719 target->type->soft_reset_halt = target_soft_reset_halt_imp;
720 target->type->run_algorithm_imp = target->type->run_algorithm;
721 target->type->run_algorithm = target_run_algorithm_imp;
723 /* Sanity-check MMU support ... stub in what we must, to help
724 * implement it in stages, but warn if we need to do so.
727 if (type->write_phys_memory == NULL) {
728 LOG_ERROR("type '%s' is missing %s",
730 "write_phys_memory");
731 type->write_phys_memory = err_write_phys_memory;
733 if (type->read_phys_memory == NULL) {
734 LOG_ERROR("type '%s' is missing %s",
737 type->read_phys_memory = err_read_phys_memory;
739 if (type->virt2phys == NULL) {
740 LOG_ERROR("type '%s' is missing %s",
743 type->virt2phys = identity_virt2phys;
746 /* Make sure no-MMU targets all behave the same: make no
747 * distinction between physical and virtual addresses, and
748 * ensure that virt2phys() is always an identity mapping.
751 if (type->write_phys_memory
752 || type->read_phys_memory
754 LOG_WARNING("type '%s' has broken MMU hooks",
758 type->write_phys_memory = type->write_memory;
759 type->read_phys_memory = type->read_memory;
760 type->virt2phys = identity_virt2phys;
766 if ((retval = target_register_user_commands(cmd_ctx)) != ERROR_OK)
768 if ((retval = target_register_timer_callback(&handle_target, 100, 1, cmd_ctx->interp)) != ERROR_OK)
775 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
777 struct target_event_callback **callbacks_p = &target_event_callbacks;
779 if (callback == NULL)
781 return ERROR_INVALID_ARGUMENTS;
786 while ((*callbacks_p)->next)
787 callbacks_p = &((*callbacks_p)->next);
788 callbacks_p = &((*callbacks_p)->next);
791 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
792 (*callbacks_p)->callback = callback;
793 (*callbacks_p)->priv = priv;
794 (*callbacks_p)->next = NULL;
799 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
801 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
804 if (callback == NULL)
806 return ERROR_INVALID_ARGUMENTS;
811 while ((*callbacks_p)->next)
812 callbacks_p = &((*callbacks_p)->next);
813 callbacks_p = &((*callbacks_p)->next);
816 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
817 (*callbacks_p)->callback = callback;
818 (*callbacks_p)->periodic = periodic;
819 (*callbacks_p)->time_ms = time_ms;
821 gettimeofday(&now, NULL);
822 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
823 time_ms -= (time_ms % 1000);
824 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
825 if ((*callbacks_p)->when.tv_usec > 1000000)
827 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
828 (*callbacks_p)->when.tv_sec += 1;
831 (*callbacks_p)->priv = priv;
832 (*callbacks_p)->next = NULL;
837 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
839 struct target_event_callback **p = &target_event_callbacks;
840 struct target_event_callback *c = target_event_callbacks;
842 if (callback == NULL)
844 return ERROR_INVALID_ARGUMENTS;
849 struct target_event_callback *next = c->next;
850 if ((c->callback == callback) && (c->priv == priv))
864 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
866 struct target_timer_callback **p = &target_timer_callbacks;
867 struct target_timer_callback *c = target_timer_callbacks;
869 if (callback == NULL)
871 return ERROR_INVALID_ARGUMENTS;
876 struct target_timer_callback *next = c->next;
877 if ((c->callback == callback) && (c->priv == priv))
891 int target_call_event_callbacks(struct target *target, enum target_event event)
893 struct target_event_callback *callback = target_event_callbacks;
894 struct target_event_callback *next_callback;
896 if (event == TARGET_EVENT_HALTED)
898 /* execute early halted first */
899 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
902 LOG_DEBUG("target event %i (%s)",
904 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
906 target_handle_event(target, event);
910 next_callback = callback->next;
911 callback->callback(target, event, callback->priv);
912 callback = next_callback;
918 static int target_timer_callback_periodic_restart(
919 struct target_timer_callback *cb, struct timeval *now)
921 int time_ms = cb->time_ms;
922 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
923 time_ms -= (time_ms % 1000);
924 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
925 if (cb->when.tv_usec > 1000000)
927 cb->when.tv_usec = cb->when.tv_usec - 1000000;
928 cb->when.tv_sec += 1;
933 static int target_call_timer_callback(struct target_timer_callback *cb,
936 cb->callback(cb->priv);
939 return target_timer_callback_periodic_restart(cb, now);
941 return target_unregister_timer_callback(cb->callback, cb->priv);
944 static int target_call_timer_callbacks_check_time(int checktime)
949 gettimeofday(&now, NULL);
951 struct target_timer_callback *callback = target_timer_callbacks;
954 // cleaning up may unregister and free this callback
955 struct target_timer_callback *next_callback = callback->next;
957 bool call_it = callback->callback &&
958 ((!checktime && callback->periodic) ||
959 now.tv_sec > callback->when.tv_sec ||
960 (now.tv_sec == callback->when.tv_sec &&
961 now.tv_usec >= callback->when.tv_usec));
965 int retval = target_call_timer_callback(callback, &now);
966 if (retval != ERROR_OK)
970 callback = next_callback;
976 int target_call_timer_callbacks(void)
978 return target_call_timer_callbacks_check_time(1);
981 /* invoke periodic callbacks immediately */
982 int target_call_timer_callbacks_now(void)
984 return target_call_timer_callbacks_check_time(0);
987 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
989 struct working_area *c = target->working_areas;
990 struct working_area *new_wa = NULL;
992 /* Reevaluate working area address based on MMU state*/
993 if (target->working_areas == NULL)
998 retval = target->type->mmu(target, &enabled);
999 if (retval != ERROR_OK)
1005 if (target->working_area_phys_spec) {
1006 LOG_DEBUG("MMU disabled, using physical "
1007 "address for working memory 0x%08x",
1008 (unsigned)target->working_area_phys);
1009 target->working_area = target->working_area_phys;
1011 LOG_ERROR("No working memory available. "
1012 "Specify -work-area-phys to target.");
1013 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1016 if (target->working_area_virt_spec) {
1017 LOG_DEBUG("MMU enabled, using virtual "
1018 "address for working memory 0x%08x",
1019 (unsigned)target->working_area_virt);
1020 target->working_area = target->working_area_virt;
1022 LOG_ERROR("No working memory available. "
1023 "Specify -work-area-virt to target.");
1024 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1029 /* only allocate multiples of 4 byte */
1032 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1033 size = (size + 3) & (~3);
1036 /* see if there's already a matching working area */
1039 if ((c->free) && (c->size == size))
1047 /* if not, allocate a new one */
1050 struct working_area **p = &target->working_areas;
1051 uint32_t first_free = target->working_area;
1052 uint32_t free_size = target->working_area_size;
1054 c = target->working_areas;
1057 first_free += c->size;
1058 free_size -= c->size;
1063 if (free_size < size)
1065 LOG_WARNING("not enough working area available(requested %u, free %u)",
1066 (unsigned)(size), (unsigned)(free_size));
1067 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1070 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1072 new_wa = malloc(sizeof(struct working_area));
1073 new_wa->next = NULL;
1074 new_wa->size = size;
1075 new_wa->address = first_free;
1077 if (target->backup_working_area)
1080 new_wa->backup = malloc(new_wa->size);
1081 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1083 free(new_wa->backup);
1090 new_wa->backup = NULL;
1093 /* put new entry in list */
1097 /* mark as used, and return the new (reused) area */
1102 new_wa->user = area;
1107 int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1112 if (restore && target->backup_working_area)
1115 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1121 /* mark user pointer invalid */
1128 int target_free_working_area(struct target *target, struct working_area *area)
1130 return target_free_working_area_restore(target, area, 1);
1133 /* free resources and restore memory, if restoring memory fails,
1134 * free up resources anyway
1136 void target_free_all_working_areas_restore(struct target *target, int restore)
1138 struct working_area *c = target->working_areas;
1142 struct working_area *next = c->next;
1143 target_free_working_area_restore(target, c, restore);
1153 target->working_areas = NULL;
1156 void target_free_all_working_areas(struct target *target)
1158 target_free_all_working_areas_restore(target, 1);
1161 int target_arch_state(struct target *target)
1166 LOG_USER("No target has been configured");
1170 LOG_USER("target state: %s", target_state_name( target ));
1172 if (target->state != TARGET_HALTED)
1175 retval = target->type->arch_state(target);
1179 /* Single aligned words are guaranteed to use 16 or 32 bit access
1180 * mode respectively, otherwise data is handled as quickly as
1183 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1186 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1187 (int)size, (unsigned)address);
1189 if (!target_was_examined(target))
1191 LOG_ERROR("Target not examined yet");
1199 if ((address + size - 1) < address)
1201 /* GDB can request this when e.g. PC is 0xfffffffc*/
1202 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1208 if (((address % 2) == 0) && (size == 2))
1210 return target_write_memory(target, address, 2, 1, buffer);
1213 /* handle unaligned head bytes */
1216 uint32_t unaligned = 4 - (address % 4);
1218 if (unaligned > size)
1221 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1224 buffer += unaligned;
1225 address += unaligned;
1229 /* handle aligned words */
1232 int aligned = size - (size % 4);
1234 /* use bulk writes above a certain limit. This may have to be changed */
1237 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1242 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1251 /* handle tail writes of less than 4 bytes */
1254 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1261 /* Single aligned words are guaranteed to use 16 or 32 bit access
1262 * mode respectively, otherwise data is handled as quickly as
1265 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1268 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1269 (int)size, (unsigned)address);
1271 if (!target_was_examined(target))
1273 LOG_ERROR("Target not examined yet");
1281 if ((address + size - 1) < address)
1283 /* GDB can request this when e.g. PC is 0xfffffffc*/
1284 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1290 if (((address % 2) == 0) && (size == 2))
1292 return target_read_memory(target, address, 2, 1, buffer);
1295 /* handle unaligned head bytes */
1298 uint32_t unaligned = 4 - (address % 4);
1300 if (unaligned > size)
1303 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1306 buffer += unaligned;
1307 address += unaligned;
1311 /* handle aligned words */
1314 int aligned = size - (size % 4);
1316 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1324 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1327 int aligned = size - (size%2);
1328 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1329 if (retval != ERROR_OK)
1336 /* handle tail writes of less than 4 bytes */
1339 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1346 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1351 uint32_t checksum = 0;
1352 if (!target_was_examined(target))
1354 LOG_ERROR("Target not examined yet");
1358 if ((retval = target->type->checksum_memory(target, address,
1359 size, &checksum)) != ERROR_OK)
1361 buffer = malloc(size);
1364 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1365 return ERROR_INVALID_ARGUMENTS;
1367 retval = target_read_buffer(target, address, size, buffer);
1368 if (retval != ERROR_OK)
1374 /* convert to target endianess */
1375 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1377 uint32_t target_data;
1378 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1379 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1382 retval = image_calculate_checksum(buffer, size, &checksum);
1391 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1394 if (!target_was_examined(target))
1396 LOG_ERROR("Target not examined yet");
1400 if (target->type->blank_check_memory == 0)
1401 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1403 retval = target->type->blank_check_memory(target, address, size, blank);
1408 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1410 uint8_t value_buf[4];
1411 if (!target_was_examined(target))
1413 LOG_ERROR("Target not examined yet");
1417 int retval = target_read_memory(target, address, 4, 1, value_buf);
1419 if (retval == ERROR_OK)
1421 *value = target_buffer_get_u32(target, value_buf);
1422 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1429 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1436 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1438 uint8_t value_buf[2];
1439 if (!target_was_examined(target))
1441 LOG_ERROR("Target not examined yet");
1445 int retval = target_read_memory(target, address, 2, 1, value_buf);
1447 if (retval == ERROR_OK)
1449 *value = target_buffer_get_u16(target, value_buf);
1450 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1457 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1464 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1466 int retval = target_read_memory(target, address, 1, 1, value);
1467 if (!target_was_examined(target))
1469 LOG_ERROR("Target not examined yet");
1473 if (retval == ERROR_OK)
1475 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1482 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1489 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1492 uint8_t value_buf[4];
1493 if (!target_was_examined(target))
1495 LOG_ERROR("Target not examined yet");
1499 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1503 target_buffer_set_u32(target, value_buf, value);
1504 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1506 LOG_DEBUG("failed: %i", retval);
1512 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1515 uint8_t value_buf[2];
1516 if (!target_was_examined(target))
1518 LOG_ERROR("Target not examined yet");
1522 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1526 target_buffer_set_u16(target, value_buf, value);
1527 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1529 LOG_DEBUG("failed: %i", retval);
1535 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1538 if (!target_was_examined(target))
1540 LOG_ERROR("Target not examined yet");
1544 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1547 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1549 LOG_DEBUG("failed: %i", retval);
1555 COMMAND_HANDLER(handle_targets_command)
1557 struct target *target = all_targets;
1561 target = get_target(CMD_ARGV[0]);
1562 if (target == NULL) {
1563 command_print(CMD_CTX,"Target: %s is unknown, try one of:\n", CMD_ARGV[0]);
1566 if (!target->tap->enabled) {
1567 command_print(CMD_CTX,"Target: TAP %s is disabled, "
1568 "can't be the current target\n",
1569 target->tap->dotted_name);
1573 CMD_CTX->current_target = target->target_number;
1578 target = all_targets;
1579 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
1580 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
1586 if (target->tap->enabled)
1587 state = target_state_name( target );
1589 state = "tap-disabled";
1591 if (CMD_CTX->current_target == target->target_number)
1594 /* keep columns lined up to match the headers above */
1595 command_print(CMD_CTX, "%2d%c %-18s %-10s %-6s %-18s %s",
1596 target->target_number,
1598 target_name(target),
1599 target_type_name(target),
1600 Jim_Nvp_value2name_simple(nvp_target_endian,
1601 target->endianness)->name,
1602 target->tap->dotted_name,
1604 target = target->next;
1610 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1612 static int powerDropout;
1613 static int srstAsserted;
1615 static int runPowerRestore;
1616 static int runPowerDropout;
1617 static int runSrstAsserted;
1618 static int runSrstDeasserted;
1620 static int sense_handler(void)
1622 static int prevSrstAsserted = 0;
1623 static int prevPowerdropout = 0;
1626 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1630 powerRestored = prevPowerdropout && !powerDropout;
1633 runPowerRestore = 1;
1636 long long current = timeval_ms();
1637 static long long lastPower = 0;
1638 int waitMore = lastPower + 2000 > current;
1639 if (powerDropout && !waitMore)
1641 runPowerDropout = 1;
1642 lastPower = current;
1645 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1649 srstDeasserted = prevSrstAsserted && !srstAsserted;
1651 static long long lastSrst = 0;
1652 waitMore = lastSrst + 2000 > current;
1653 if (srstDeasserted && !waitMore)
1655 runSrstDeasserted = 1;
1659 if (!prevSrstAsserted && srstAsserted)
1661 runSrstAsserted = 1;
1664 prevSrstAsserted = srstAsserted;
1665 prevPowerdropout = powerDropout;
1667 if (srstDeasserted || powerRestored)
1669 /* Other than logging the event we can't do anything here.
1670 * Issuing a reset is a particularly bad idea as we might
1671 * be inside a reset already.
1678 static void target_call_event_callbacks_all(enum target_event e) {
1679 struct target *target;
1680 target = all_targets;
1682 target_call_event_callbacks(target, e);
1683 target = target->next;
1687 /* process target state changes */
1688 static int handle_target(void *priv)
1690 Jim_Interp *interp = (Jim_Interp *)priv;
1691 int retval = ERROR_OK;
1693 /* we do not want to recurse here... */
1694 static int recursive = 0;
1699 /* danger! running these procedures can trigger srst assertions and power dropouts.
1700 * We need to avoid an infinite loop/recursion here and we do that by
1701 * clearing the flags after running these events.
1703 int did_something = 0;
1704 if (runSrstAsserted)
1706 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1707 Jim_Eval(interp, "srst_asserted");
1710 if (runSrstDeasserted)
1712 Jim_Eval(interp, "srst_deasserted");
1715 if (runPowerDropout)
1717 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1718 Jim_Eval(interp, "power_dropout");
1721 if (runPowerRestore)
1723 Jim_Eval(interp, "power_restore");
1729 /* clear detect flags */
1733 /* clear action flags */
1735 runSrstAsserted = 0;
1736 runSrstDeasserted = 0;
1737 runPowerRestore = 0;
1738 runPowerDropout = 0;
1743 /* Poll targets for state changes unless that's globally disabled.
1744 * Skip targets that are currently disabled.
1746 for (struct target *target = all_targets;
1747 is_jtag_poll_safe() && target;
1748 target = target->next)
1750 if (!target->tap->enabled)
1753 /* only poll target if we've got power and srst isn't asserted */
1754 if (!powerDropout && !srstAsserted)
1756 /* polling may fail silently until the target has been examined */
1757 if ((retval = target_poll(target)) != ERROR_OK)
1759 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1768 COMMAND_HANDLER(handle_reg_command)
1770 struct target *target;
1771 struct reg *reg = NULL;
1777 target = get_current_target(CMD_CTX);
1779 /* list all available registers for the current target */
1782 struct reg_cache *cache = target->reg_cache;
1789 command_print(CMD_CTX, "===== %s", cache->name);
1791 for (i = 0, reg = cache->reg_list;
1792 i < cache->num_regs;
1793 i++, reg++, count++)
1795 /* only print cached values if they are valid */
1797 value = buf_to_str(reg->value,
1799 command_print(CMD_CTX,
1800 "(%i) %s (/%" PRIu32 "): 0x%s%s",
1808 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
1813 cache = cache->next;
1819 /* access a single register by its ordinal number */
1820 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9'))
1823 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
1825 struct reg_cache *cache = target->reg_cache;
1830 for (i = 0; i < cache->num_regs; i++)
1834 reg = &cache->reg_list[i];
1840 cache = cache->next;
1845 command_print(CMD_CTX, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1848 } else /* access a single register by its name */
1850 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
1854 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
1859 /* display a register */
1860 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0') && (CMD_ARGV[1][0] <= '9'))))
1862 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
1865 if (reg->valid == 0)
1867 reg->type->get(reg);
1869 value = buf_to_str(reg->value, reg->size, 16);
1870 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1875 /* set register value */
1878 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
1879 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
1881 reg->type->set(reg, buf);
1883 value = buf_to_str(reg->value, reg->size, 16);
1884 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1892 command_print(CMD_CTX, "usage: reg <#|name> [value]");
1897 COMMAND_HANDLER(handle_poll_command)
1899 int retval = ERROR_OK;
1900 struct target *target = get_current_target(CMD_CTX);
1904 command_print(CMD_CTX, "background polling: %s",
1905 jtag_poll_get_enabled() ? "on" : "off");
1906 command_print(CMD_CTX, "TAP: %s (%s)",
1907 target->tap->dotted_name,
1908 target->tap->enabled ? "enabled" : "disabled");
1909 if (!target->tap->enabled)
1911 if ((retval = target_poll(target)) != ERROR_OK)
1913 if ((retval = target_arch_state(target)) != ERROR_OK)
1916 else if (CMD_ARGC == 1)
1919 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
1920 jtag_poll_set_enabled(enable);
1924 return ERROR_COMMAND_SYNTAX_ERROR;
1930 COMMAND_HANDLER(handle_wait_halt_command)
1933 return ERROR_COMMAND_SYNTAX_ERROR;
1938 int retval = parse_uint(CMD_ARGV[0], &ms);
1939 if (ERROR_OK != retval)
1941 command_print(CMD_CTX, "usage: %s [seconds]", CMD_NAME);
1942 return ERROR_COMMAND_SYNTAX_ERROR;
1944 // convert seconds (given) to milliseconds (needed)
1948 struct target *target = get_current_target(CMD_CTX);
1949 return target_wait_state(target, TARGET_HALTED, ms);
1952 /* wait for target state to change. The trick here is to have a low
1953 * latency for short waits and not to suck up all the CPU time
1956 * After 500ms, keep_alive() is invoked
1958 int target_wait_state(struct target *target, enum target_state state, int ms)
1961 long long then = 0, cur;
1966 if ((retval = target_poll(target)) != ERROR_OK)
1968 if (target->state == state)
1976 then = timeval_ms();
1977 LOG_DEBUG("waiting for target %s...",
1978 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
1986 if ((cur-then) > ms)
1988 LOG_ERROR("timed out while waiting for target %s",
1989 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
1997 COMMAND_HANDLER(handle_halt_command)
2001 struct target *target = get_current_target(CMD_CTX);
2002 int retval = target_halt(target);
2003 if (ERROR_OK != retval)
2009 retval = parse_uint(CMD_ARGV[0], &wait);
2010 if (ERROR_OK != retval)
2011 return ERROR_COMMAND_SYNTAX_ERROR;
2016 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2019 COMMAND_HANDLER(handle_soft_reset_halt_command)
2021 struct target *target = get_current_target(CMD_CTX);
2023 LOG_USER("requesting target halt and executing a soft reset");
2025 target->type->soft_reset_halt(target);
2030 COMMAND_HANDLER(handle_reset_command)
2033 return ERROR_COMMAND_SYNTAX_ERROR;
2035 enum target_reset_mode reset_mode = RESET_RUN;
2039 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2040 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2041 return ERROR_COMMAND_SYNTAX_ERROR;
2043 reset_mode = n->value;
2046 /* reset *all* targets */
2047 return target_process_reset(CMD_CTX, reset_mode);
2051 COMMAND_HANDLER(handle_resume_command)
2055 return ERROR_COMMAND_SYNTAX_ERROR;
2057 struct target *target = get_current_target(CMD_CTX);
2058 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2060 /* with no CMD_ARGV, resume from current pc, addr = 0,
2061 * with one arguments, addr = CMD_ARGV[0],
2062 * handle breakpoints, not debugging */
2066 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2070 return target_resume(target, current, addr, 1, 0);
2073 COMMAND_HANDLER(handle_step_command)
2076 return ERROR_COMMAND_SYNTAX_ERROR;
2080 /* with no CMD_ARGV, step from current pc, addr = 0,
2081 * with one argument addr = CMD_ARGV[0],
2082 * handle breakpoints, debugging */
2087 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2091 struct target *target = get_current_target(CMD_CTX);
2093 return target->type->step(target, current_pc, addr, 1);
2096 static void handle_md_output(struct command_context *cmd_ctx,
2097 struct target *target, uint32_t address, unsigned size,
2098 unsigned count, const uint8_t *buffer)
2100 const unsigned line_bytecnt = 32;
2101 unsigned line_modulo = line_bytecnt / size;
2103 char output[line_bytecnt * 4 + 1];
2104 unsigned output_len = 0;
2106 const char *value_fmt;
2108 case 4: value_fmt = "%8.8x "; break;
2109 case 2: value_fmt = "%4.2x "; break;
2110 case 1: value_fmt = "%2.2x "; break;
2112 LOG_ERROR("invalid memory read size: %u", size);
2116 for (unsigned i = 0; i < count; i++)
2118 if (i % line_modulo == 0)
2120 output_len += snprintf(output + output_len,
2121 sizeof(output) - output_len,
2123 (unsigned)(address + (i*size)));
2127 const uint8_t *value_ptr = buffer + i * size;
2129 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2130 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2131 case 1: value = *value_ptr;
2133 output_len += snprintf(output + output_len,
2134 sizeof(output) - output_len,
2137 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2139 command_print(cmd_ctx, "%s", output);
2145 COMMAND_HANDLER(handle_md_command)
2148 return ERROR_COMMAND_SYNTAX_ERROR;
2151 switch (CMD_NAME[2]) {
2152 case 'w': size = 4; break;
2153 case 'h': size = 2; break;
2154 case 'b': size = 1; break;
2155 default: return ERROR_COMMAND_SYNTAX_ERROR;
2158 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2159 int (*fn)(struct target *target,
2160 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2165 fn=target_read_phys_memory;
2168 fn=target_read_memory;
2170 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2172 return ERROR_COMMAND_SYNTAX_ERROR;
2176 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2180 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2182 uint8_t *buffer = calloc(count, size);
2184 struct target *target = get_current_target(CMD_CTX);
2185 int retval = fn(target, address, size, count, buffer);
2186 if (ERROR_OK == retval)
2187 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2194 COMMAND_HANDLER(handle_mw_command)
2198 return ERROR_COMMAND_SYNTAX_ERROR;
2200 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2201 int (*fn)(struct target *target,
2202 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2207 fn=target_write_phys_memory;
2210 fn=target_write_memory;
2212 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2213 return ERROR_COMMAND_SYNTAX_ERROR;
2216 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2219 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2223 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2225 struct target *target = get_current_target(CMD_CTX);
2227 uint8_t value_buf[4];
2228 switch (CMD_NAME[2])
2232 target_buffer_set_u32(target, value_buf, value);
2236 target_buffer_set_u16(target, value_buf, value);
2240 value_buf[0] = value;
2243 return ERROR_COMMAND_SYNTAX_ERROR;
2245 for (unsigned i = 0; i < count; i++)
2247 int retval = fn(target,
2248 address + i * wordsize, wordsize, 1, value_buf);
2249 if (ERROR_OK != retval)
2258 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2259 uint32_t *min_address, uint32_t *max_address)
2261 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2262 return ERROR_COMMAND_SYNTAX_ERROR;
2264 /* a base address isn't always necessary,
2265 * default to 0x0 (i.e. don't relocate) */
2269 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2270 image->base_address = addr;
2271 image->base_address_set = 1;
2274 image->base_address_set = 0;
2276 image->start_address_set = 0;
2280 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2284 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2285 // use size (given) to find max (required)
2286 *max_address += *min_address;
2289 if (*min_address > *max_address)
2290 return ERROR_COMMAND_SYNTAX_ERROR;
2295 COMMAND_HANDLER(handle_load_image_command)
2299 uint32_t image_size;
2300 uint32_t min_address = 0;
2301 uint32_t max_address = 0xffffffff;
2305 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2306 &image, &min_address, &max_address);
2307 if (ERROR_OK != retval)
2310 struct target *target = get_current_target(CMD_CTX);
2312 struct duration bench;
2313 duration_start(&bench);
2315 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2322 for (i = 0; i < image.num_sections; i++)
2324 buffer = malloc(image.sections[i].size);
2327 command_print(CMD_CTX,
2328 "error allocating buffer for section (%d bytes)",
2329 (int)(image.sections[i].size));
2333 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2339 uint32_t offset = 0;
2340 uint32_t length = buf_cnt;
2342 /* DANGER!!! beware of unsigned comparision here!!! */
2344 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2345 (image.sections[i].base_address < max_address))
2347 if (image.sections[i].base_address < min_address)
2349 /* clip addresses below */
2350 offset += min_address-image.sections[i].base_address;
2354 if (image.sections[i].base_address + buf_cnt > max_address)
2356 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2359 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2364 image_size += length;
2365 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2366 (unsigned int)length,
2367 image.sections[i].base_address + offset);
2373 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2375 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2376 "in %fs (%0.3f kb/s)", image_size,
2377 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2380 image_close(&image);
2386 COMMAND_HANDLER(handle_dump_image_command)
2388 struct fileio fileio;
2390 uint8_t buffer[560];
2394 struct target *target = get_current_target(CMD_CTX);
2398 command_print(CMD_CTX, "usage: dump_image <filename> <address> <size>");
2403 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2405 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2407 if (fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2412 struct duration bench;
2413 duration_start(&bench);
2415 int retval = ERROR_OK;
2418 size_t size_written;
2419 uint32_t this_run_size = (size > 560) ? 560 : size;
2420 retval = target_read_buffer(target, address, this_run_size, buffer);
2421 if (retval != ERROR_OK)
2426 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2427 if (retval != ERROR_OK)
2432 size -= this_run_size;
2433 address += this_run_size;
2436 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2439 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2441 command_print(CMD_CTX,
2442 "dumped %zu bytes in %fs (%0.3f kb/s)", fileio.size,
2443 duration_elapsed(&bench), duration_kbps(&bench, fileio.size));
2449 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2453 uint32_t image_size;
2456 uint32_t checksum = 0;
2457 uint32_t mem_checksum = 0;
2461 struct target *target = get_current_target(CMD_CTX);
2465 return ERROR_COMMAND_SYNTAX_ERROR;
2470 LOG_ERROR("no target selected");
2474 struct duration bench;
2475 duration_start(&bench);
2480 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2481 image.base_address = addr;
2482 image.base_address_set = 1;
2486 image.base_address_set = 0;
2487 image.base_address = 0x0;
2490 image.start_address_set = 0;
2492 if ((retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL)) != ERROR_OK)
2499 for (i = 0; i < image.num_sections; i++)
2501 buffer = malloc(image.sections[i].size);
2504 command_print(CMD_CTX,
2505 "error allocating buffer for section (%d bytes)",
2506 (int)(image.sections[i].size));
2509 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2517 /* calculate checksum of image */
2518 image_calculate_checksum(buffer, buf_cnt, &checksum);
2520 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2521 if (retval != ERROR_OK)
2527 if (checksum != mem_checksum)
2529 /* failed crc checksum, fall back to a binary compare */
2532 command_print(CMD_CTX, "checksum mismatch - attempting binary compare");
2534 data = (uint8_t*)malloc(buf_cnt);
2536 /* Can we use 32bit word accesses? */
2538 int count = buf_cnt;
2539 if ((count % 4) == 0)
2544 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2545 if (retval == ERROR_OK)
2548 for (t = 0; t < buf_cnt; t++)
2550 if (data[t] != buffer[t])
2552 command_print(CMD_CTX,
2553 "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n",
2554 (unsigned)(t + image.sections[i].base_address),
2559 retval = ERROR_FAIL;
2573 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
2574 image.sections[i].base_address,
2579 image_size += buf_cnt;
2582 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2584 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
2585 "in %fs (%0.3f kb/s)", image_size,
2586 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2589 image_close(&image);
2594 COMMAND_HANDLER(handle_verify_image_command)
2596 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2599 COMMAND_HANDLER(handle_test_image_command)
2601 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2604 static int handle_bp_command_list(struct command_context *cmd_ctx)
2606 struct target *target = get_current_target(cmd_ctx);
2607 struct breakpoint *breakpoint = target->breakpoints;
2610 if (breakpoint->type == BKPT_SOFT)
2612 char* buf = buf_to_str(breakpoint->orig_instr,
2613 breakpoint->length, 16);
2614 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2615 breakpoint->address,
2617 breakpoint->set, buf);
2622 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2623 breakpoint->address,
2624 breakpoint->length, breakpoint->set);
2627 breakpoint = breakpoint->next;
2632 static int handle_bp_command_set(struct command_context *cmd_ctx,
2633 uint32_t addr, uint32_t length, int hw)
2635 struct target *target = get_current_target(cmd_ctx);
2636 int retval = breakpoint_add(target, addr, length, hw);
2637 if (ERROR_OK == retval)
2638 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2640 LOG_ERROR("Failure setting breakpoint");
2644 COMMAND_HANDLER(handle_bp_command)
2647 return handle_bp_command_list(CMD_CTX);
2649 if (CMD_ARGC < 2 || CMD_ARGC > 3)
2651 command_print(CMD_CTX, "usage: bp <address> <length> ['hw']");
2652 return ERROR_COMMAND_SYNTAX_ERROR;
2656 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2658 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2663 if (strcmp(CMD_ARGV[2], "hw") == 0)
2666 return ERROR_COMMAND_SYNTAX_ERROR;
2669 return handle_bp_command_set(CMD_CTX, addr, length, hw);
2672 COMMAND_HANDLER(handle_rbp_command)
2675 return ERROR_COMMAND_SYNTAX_ERROR;
2678 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2680 struct target *target = get_current_target(CMD_CTX);
2681 breakpoint_remove(target, addr);
2686 COMMAND_HANDLER(handle_wp_command)
2688 struct target *target = get_current_target(CMD_CTX);
2692 struct watchpoint *watchpoint = target->watchpoints;
2696 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
2697 ", len: 0x%8.8" PRIx32
2698 ", r/w/a: %i, value: 0x%8.8" PRIx32
2699 ", mask: 0x%8.8" PRIx32,
2700 watchpoint->address,
2702 (int)watchpoint->rw,
2705 watchpoint = watchpoint->next;
2710 enum watchpoint_rw type = WPT_ACCESS;
2712 uint32_t length = 0;
2713 uint32_t data_value = 0x0;
2714 uint32_t data_mask = 0xffffffff;
2719 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
2722 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
2725 switch (CMD_ARGV[2][0])
2737 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
2738 return ERROR_COMMAND_SYNTAX_ERROR;
2742 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2743 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2747 command_print(CMD_CTX, "usage: wp [address length "
2748 "[(r|w|a) [value [mask]]]]");
2749 return ERROR_COMMAND_SYNTAX_ERROR;
2752 int retval = watchpoint_add(target, addr, length, type,
2753 data_value, data_mask);
2754 if (ERROR_OK != retval)
2755 LOG_ERROR("Failure setting watchpoints");
2760 COMMAND_HANDLER(handle_rwp_command)
2763 return ERROR_COMMAND_SYNTAX_ERROR;
2766 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2768 struct target *target = get_current_target(CMD_CTX);
2769 watchpoint_remove(target, addr);
2776 * Translate a virtual address to a physical address.
2778 * The low-level target implementation must have logged a detailed error
2779 * which is forwarded to telnet/GDB session.
2781 COMMAND_HANDLER(handle_virt2phys_command)
2784 return ERROR_COMMAND_SYNTAX_ERROR;
2787 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
2790 struct target *target = get_current_target(CMD_CTX);
2791 int retval = target->type->virt2phys(target, va, &pa);
2792 if (retval == ERROR_OK)
2793 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
2798 static void writeData(FILE *f, const void *data, size_t len)
2800 size_t written = fwrite(data, 1, len, f);
2802 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
2805 static void writeLong(FILE *f, int l)
2808 for (i = 0; i < 4; i++)
2810 char c = (l >> (i*8))&0xff;
2811 writeData(f, &c, 1);
2816 static void writeString(FILE *f, char *s)
2818 writeData(f, s, strlen(s));
2821 /* Dump a gmon.out histogram file. */
2822 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
2825 FILE *f = fopen(filename, "w");
2828 writeString(f, "gmon");
2829 writeLong(f, 0x00000001); /* Version */
2830 writeLong(f, 0); /* padding */
2831 writeLong(f, 0); /* padding */
2832 writeLong(f, 0); /* padding */
2834 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
2835 writeData(f, &zero, 1);
2837 /* figure out bucket size */
2838 uint32_t min = samples[0];
2839 uint32_t max = samples[0];
2840 for (i = 0; i < sampleNum; i++)
2842 if (min > samples[i])
2846 if (max < samples[i])
2852 int addressSpace = (max-min + 1);
2854 static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
2855 uint32_t length = addressSpace;
2856 if (length > maxBuckets)
2858 length = maxBuckets;
2860 int *buckets = malloc(sizeof(int)*length);
2861 if (buckets == NULL)
2866 memset(buckets, 0, sizeof(int)*length);
2867 for (i = 0; i < sampleNum;i++)
2869 uint32_t address = samples[i];
2870 long long a = address-min;
2871 long long b = length-1;
2872 long long c = addressSpace-1;
2873 int index = (a*b)/c; /* danger!!!! int32 overflows */
2877 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
2878 writeLong(f, min); /* low_pc */
2879 writeLong(f, max); /* high_pc */
2880 writeLong(f, length); /* # of samples */
2881 writeLong(f, 64000000); /* 64MHz */
2882 writeString(f, "seconds");
2883 for (i = 0; i < (15-strlen("seconds")); i++)
2884 writeData(f, &zero, 1);
2885 writeString(f, "s");
2887 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
2889 char *data = malloc(2*length);
2892 for (i = 0; i < length;i++)
2901 data[i*2 + 1]=(val >> 8)&0xff;
2904 writeData(f, data, length * 2);
2914 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
2915 COMMAND_HANDLER(handle_profile_command)
2917 struct target *target = get_current_target(CMD_CTX);
2918 struct timeval timeout, now;
2920 gettimeofday(&timeout, NULL);
2923 return ERROR_COMMAND_SYNTAX_ERROR;
2926 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
2928 timeval_add_time(&timeout, offset, 0);
2930 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
2932 static const int maxSample = 10000;
2933 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
2934 if (samples == NULL)
2938 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2939 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
2944 target_poll(target);
2945 if (target->state == TARGET_HALTED)
2947 uint32_t t=*((uint32_t *)reg->value);
2948 samples[numSamples++]=t;
2949 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
2950 target_poll(target);
2951 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2952 } else if (target->state == TARGET_RUNNING)
2954 /* We want to quickly sample the PC. */
2955 if ((retval = target_halt(target)) != ERROR_OK)
2962 command_print(CMD_CTX, "Target not halted or running");
2966 if (retval != ERROR_OK)
2971 gettimeofday(&now, NULL);
2972 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
2974 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
2975 if ((retval = target_poll(target)) != ERROR_OK)
2980 if (target->state == TARGET_HALTED)
2982 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
2984 if ((retval = target_poll(target)) != ERROR_OK)
2989 writeGmon(samples, numSamples, CMD_ARGV[1]);
2990 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
2999 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3002 Jim_Obj *nameObjPtr, *valObjPtr;
3005 namebuf = alloc_printf("%s(%d)", varname, idx);
3009 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3010 valObjPtr = Jim_NewIntObj(interp, val);
3011 if (!nameObjPtr || !valObjPtr)
3017 Jim_IncrRefCount(nameObjPtr);
3018 Jim_IncrRefCount(valObjPtr);
3019 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3020 Jim_DecrRefCount(interp, nameObjPtr);
3021 Jim_DecrRefCount(interp, valObjPtr);
3023 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3027 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3029 struct command_context *context;
3030 struct target *target;
3032 context = Jim_GetAssocData(interp, "context");
3033 if (context == NULL)
3035 LOG_ERROR("mem2array: no command context");
3038 target = get_current_target(context);
3041 LOG_ERROR("mem2array: no current target");
3045 return target_mem2array(interp, target, argc-1, argv + 1);
3048 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3056 const char *varname;
3060 /* argv[1] = name of array to receive the data
3061 * argv[2] = desired width
3062 * argv[3] = memory address
3063 * argv[4] = count of times to read
3066 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3069 varname = Jim_GetString(argv[0], &len);
3070 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3072 e = Jim_GetLong(interp, argv[1], &l);
3078 e = Jim_GetLong(interp, argv[2], &l);
3083 e = Jim_GetLong(interp, argv[3], &l);
3099 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3100 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3104 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3105 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3108 if ((addr + (len * width)) < addr) {
3109 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3110 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3113 /* absurd transfer size? */
3115 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3116 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3121 ((width == 2) && ((addr & 1) == 0)) ||
3122 ((width == 4) && ((addr & 3) == 0))) {
3126 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3127 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3130 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3139 size_t buffersize = 4096;
3140 uint8_t *buffer = malloc(buffersize);
3147 /* Slurp... in buffer size chunks */
3149 count = len; /* in objects.. */
3150 if (count > (buffersize/width)) {
3151 count = (buffersize/width);
3154 retval = target_read_memory(target, addr, width, count, buffer);
3155 if (retval != ERROR_OK) {
3157 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3161 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3162 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3166 v = 0; /* shut up gcc */
3167 for (i = 0 ;i < count ;i++, n++) {
3170 v = target_buffer_get_u32(target, &buffer[i*width]);
3173 v = target_buffer_get_u16(target, &buffer[i*width]);
3176 v = buffer[i] & 0x0ff;
3179 new_int_array_element(interp, varname, n, v);
3187 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3192 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3195 Jim_Obj *nameObjPtr, *valObjPtr;
3199 namebuf = alloc_printf("%s(%d)", varname, idx);
3203 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3210 Jim_IncrRefCount(nameObjPtr);
3211 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3212 Jim_DecrRefCount(interp, nameObjPtr);
3214 if (valObjPtr == NULL)
3217 result = Jim_GetLong(interp, valObjPtr, &l);
3218 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3223 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3225 struct command_context *context;
3226 struct target *target;
3228 context = Jim_GetAssocData(interp, "context");
3229 if (context == NULL) {
3230 LOG_ERROR("array2mem: no command context");
3233 target = get_current_target(context);
3234 if (target == NULL) {
3235 LOG_ERROR("array2mem: no current target");
3239 return target_array2mem(interp,target, argc-1, argv + 1);
3241 static int target_array2mem(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3249 const char *varname;
3253 /* argv[1] = name of array to get the data
3254 * argv[2] = desired width
3255 * argv[3] = memory address
3256 * argv[4] = count to write
3259 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3262 varname = Jim_GetString(argv[0], &len);
3263 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3265 e = Jim_GetLong(interp, argv[1], &l);
3271 e = Jim_GetLong(interp, argv[2], &l);
3276 e = Jim_GetLong(interp, argv[3], &l);
3292 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3293 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3297 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3298 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3301 if ((addr + (len * width)) < addr) {
3302 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3303 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3306 /* absurd transfer size? */
3308 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3309 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3314 ((width == 2) && ((addr & 1) == 0)) ||
3315 ((width == 4) && ((addr & 3) == 0))) {
3319 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3320 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3323 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3334 size_t buffersize = 4096;
3335 uint8_t *buffer = malloc(buffersize);
3340 /* Slurp... in buffer size chunks */
3342 count = len; /* in objects.. */
3343 if (count > (buffersize/width)) {
3344 count = (buffersize/width);
3347 v = 0; /* shut up gcc */
3348 for (i = 0 ;i < count ;i++, n++) {
3349 get_int_array_element(interp, varname, n, &v);
3352 target_buffer_set_u32(target, &buffer[i*width], v);
3355 target_buffer_set_u16(target, &buffer[i*width], v);
3358 buffer[i] = v & 0x0ff;
3364 retval = target_write_memory(target, addr, width, count, buffer);
3365 if (retval != ERROR_OK) {
3367 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3371 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3372 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3380 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3385 void target_all_handle_event(enum target_event e)
3387 struct target *target;
3389 LOG_DEBUG("**all*targets: event: %d, %s",
3391 Jim_Nvp_value2name_simple(nvp_target_event, e)->name);
3393 target = all_targets;
3395 target_handle_event(target, e);
3396 target = target->next;
3401 /* FIX? should we propagate errors here rather than printing them
3404 void target_handle_event(struct target *target, enum target_event e)
3406 struct target_event_action *teap;
3408 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3409 if (teap->event == e) {
3410 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3411 target->target_number,
3412 target_name(target),
3413 target_type_name(target),
3415 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3416 Jim_GetString(teap->body, NULL));
3417 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK)
3419 Jim_PrintErrorMessage(teap->interp);
3426 * Returns true only if the target has a handler for the specified event.
3428 bool target_has_event_action(struct target *target, enum target_event event)
3430 struct target_event_action *teap;
3432 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3433 if (teap->event == event)
3439 enum target_cfg_param {
3442 TCFG_WORK_AREA_VIRT,
3443 TCFG_WORK_AREA_PHYS,
3444 TCFG_WORK_AREA_SIZE,
3445 TCFG_WORK_AREA_BACKUP,
3448 TCFG_CHAIN_POSITION,
3451 static Jim_Nvp nvp_config_opts[] = {
3452 { .name = "-type", .value = TCFG_TYPE },
3453 { .name = "-event", .value = TCFG_EVENT },
3454 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3455 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3456 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3457 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3458 { .name = "-endian" , .value = TCFG_ENDIAN },
3459 { .name = "-variant", .value = TCFG_VARIANT },
3460 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3462 { .name = NULL, .value = -1 }
3465 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3473 /* parse config or cget options ... */
3474 while (goi->argc > 0) {
3475 Jim_SetEmptyResult(goi->interp);
3476 /* Jim_GetOpt_Debug(goi); */
3478 if (target->type->target_jim_configure) {
3479 /* target defines a configure function */
3480 /* target gets first dibs on parameters */
3481 e = (*(target->type->target_jim_configure))(target, goi);
3490 /* otherwise we 'continue' below */
3492 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3494 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3500 if (goi->isconfigure) {
3501 Jim_SetResult_sprintf(goi->interp,
3502 "not settable: %s", n->name);
3506 if (goi->argc != 0) {
3507 Jim_WrongNumArgs(goi->interp,
3508 goi->argc, goi->argv,
3513 Jim_SetResultString(goi->interp,
3514 target_type_name(target), -1);
3518 if (goi->argc == 0) {
3519 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3523 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3525 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3529 if (goi->isconfigure) {
3530 if (goi->argc != 1) {
3531 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3535 if (goi->argc != 0) {
3536 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3542 struct target_event_action *teap;
3544 teap = target->event_action;
3545 /* replace existing? */
3547 if (teap->event == (enum target_event)n->value) {
3553 if (goi->isconfigure) {
3554 bool replace = true;
3557 teap = calloc(1, sizeof(*teap));
3560 teap->event = n->value;
3561 teap->interp = goi->interp;
3562 Jim_GetOpt_Obj(goi, &o);
3564 Jim_DecrRefCount(teap->interp, teap->body);
3566 teap->body = Jim_DuplicateObj(goi->interp, o);
3569 * Tcl/TK - "tk events" have a nice feature.
3570 * See the "BIND" command.
3571 * We should support that here.
3572 * You can specify %X and %Y in the event code.
3573 * The idea is: %T - target name.
3574 * The idea is: %N - target number
3575 * The idea is: %E - event name.
3577 Jim_IncrRefCount(teap->body);
3581 /* add to head of event list */
3582 teap->next = target->event_action;
3583 target->event_action = teap;
3585 Jim_SetEmptyResult(goi->interp);
3589 Jim_SetEmptyResult(goi->interp);
3591 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3598 case TCFG_WORK_AREA_VIRT:
3599 if (goi->isconfigure) {
3600 target_free_all_working_areas(target);
3601 e = Jim_GetOpt_Wide(goi, &w);
3605 target->working_area_virt = w;
3606 target->working_area_virt_spec = true;
3608 if (goi->argc != 0) {
3612 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3616 case TCFG_WORK_AREA_PHYS:
3617 if (goi->isconfigure) {
3618 target_free_all_working_areas(target);
3619 e = Jim_GetOpt_Wide(goi, &w);
3623 target->working_area_phys = w;
3624 target->working_area_phys_spec = true;
3626 if (goi->argc != 0) {
3630 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3634 case TCFG_WORK_AREA_SIZE:
3635 if (goi->isconfigure) {
3636 target_free_all_working_areas(target);
3637 e = Jim_GetOpt_Wide(goi, &w);
3641 target->working_area_size = w;
3643 if (goi->argc != 0) {
3647 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3651 case TCFG_WORK_AREA_BACKUP:
3652 if (goi->isconfigure) {
3653 target_free_all_working_areas(target);
3654 e = Jim_GetOpt_Wide(goi, &w);
3658 /* make this exactly 1 or 0 */
3659 target->backup_working_area = (!!w);
3661 if (goi->argc != 0) {
3665 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3666 /* loop for more e*/
3670 if (goi->isconfigure) {
3671 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3673 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3676 target->endianness = n->value;
3678 if (goi->argc != 0) {
3682 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3683 if (n->name == NULL) {
3684 target->endianness = TARGET_LITTLE_ENDIAN;
3685 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3687 Jim_SetResultString(goi->interp, n->name, -1);
3692 if (goi->isconfigure) {
3693 if (goi->argc < 1) {
3694 Jim_SetResult_sprintf(goi->interp,
3699 if (target->variant) {
3700 free((void *)(target->variant));
3702 e = Jim_GetOpt_String(goi, &cp, NULL);
3703 target->variant = strdup(cp);
3705 if (goi->argc != 0) {
3709 Jim_SetResultString(goi->interp, target->variant,-1);
3712 case TCFG_CHAIN_POSITION:
3713 if (goi->isconfigure) {
3715 struct jtag_tap *tap;
3716 target_free_all_working_areas(target);
3717 e = Jim_GetOpt_Obj(goi, &o);
3721 tap = jtag_tap_by_jim_obj(goi->interp, o);
3725 /* make this exactly 1 or 0 */
3728 if (goi->argc != 0) {
3732 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
3733 /* loop for more e*/
3736 } /* while (goi->argc) */
3739 /* done - we return */
3743 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3746 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3747 goi.isconfigure = strcmp(Jim_GetString(argv[0], NULL), "configure") == 0;
3748 int need_args = 1 + goi.isconfigure;
3749 if (goi.argc < need_args)
3751 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
3753 ? "missing: -option VALUE ..."
3754 : "missing: -option ...");
3757 struct target *target = Jim_CmdPrivData(goi.interp);
3758 return target_configure(&goi, target);
3761 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3763 const char *cmd_name = Jim_GetString(argv[0], NULL);
3766 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3768 if (goi.argc != 2 && goi.argc != 3)
3770 Jim_SetResult_sprintf(goi.interp,
3771 "usage: %s <address> <data> [<count>]", cmd_name);
3776 int e = Jim_GetOpt_Wide(&goi, &a);
3781 e = Jim_GetOpt_Wide(&goi, &b);
3788 e = Jim_GetOpt_Wide(&goi, &c);
3793 struct target *target = Jim_CmdPrivData(goi.interp);
3794 uint8_t target_buf[32];
3795 if (strcasecmp(cmd_name, "mww") == 0) {
3796 target_buffer_set_u32(target, target_buf, b);
3799 else if (strcasecmp(cmd_name, "mwh") == 0) {
3800 target_buffer_set_u16(target, target_buf, b);
3803 else if (strcasecmp(cmd_name, "mwb") == 0) {
3804 target_buffer_set_u8(target, target_buf, b);
3807 LOG_ERROR("command '%s' unknown: ", cmd_name);
3811 for (jim_wide x = 0; x < c; x++)
3813 e = target_write_memory(target, a, b, 1, target_buf);
3816 Jim_SetResult_sprintf(interp,
3817 "Error writing @ 0x%08x: %d\n", (int)(a), e);
3826 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3828 const char *cmd_name = Jim_GetString(argv[0], NULL);
3831 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3833 if ((goi.argc == 2) || (goi.argc == 3))
3835 Jim_SetResult_sprintf(goi.interp,
3836 "usage: %s <address> [<count>]", cmd_name);
3841 int e = Jim_GetOpt_Wide(&goi, &a);
3847 e = Jim_GetOpt_Wide(&goi, &c);
3854 jim_wide b = 1; /* shut up gcc */
3855 if (strcasecmp(cmd_name, "mdw") == 0)
3857 else if (strcasecmp(cmd_name, "mdh") == 0)
3859 else if (strcasecmp(cmd_name, "mdb") == 0)
3862 LOG_ERROR("command '%s' unknown: ", cmd_name);
3866 /* convert count to "bytes" */
3869 struct target *target = Jim_CmdPrivData(goi.interp);
3870 uint8_t target_buf[32];
3877 e = target_read_memory(target, a, b, y / b, target_buf);
3878 if (e != ERROR_OK) {
3879 Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
3883 Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
3886 for (x = 0; x < 16 && x < y; x += 4)
3888 z = target_buffer_get_u32(target, &(target_buf[ x * 4 ]));
3889 Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
3891 for (; (x < 16) ; x += 4) {
3892 Jim_fprintf(interp, interp->cookie_stdout, " ");
3896 for (x = 0; x < 16 && x < y; x += 2)
3898 z = target_buffer_get_u16(target, &(target_buf[ x * 2 ]));
3899 Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
3901 for (; (x < 16) ; x += 2) {
3902 Jim_fprintf(interp, interp->cookie_stdout, " ");
3907 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
3908 z = target_buffer_get_u8(target, &(target_buf[ x * 4 ]));
3909 Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
3911 for (; (x < 16) ; x += 1) {
3912 Jim_fprintf(interp, interp->cookie_stdout, " ");
3916 /* ascii-ify the bytes */
3917 for (x = 0 ; x < y ; x++) {
3918 if ((target_buf[x] >= 0x20) &&
3919 (target_buf[x] <= 0x7e)) {
3923 target_buf[x] = '.';
3928 target_buf[x] = ' ';
3933 /* print - with a newline */
3934 Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
3942 static int jim_target_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3944 struct target *target = Jim_CmdPrivData(interp);
3945 return target_mem2array(interp, target, argc - 1, argv + 1);
3948 static int jim_target_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3950 struct target *target = Jim_CmdPrivData(interp);
3951 return target_array2mem(interp, target, argc - 1, argv + 1);
3954 static int jim_target_tap_disabled(Jim_Interp *interp)
3956 Jim_SetResult_sprintf(interp, "[TAP is disabled]");
3960 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3964 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
3967 struct target *target = Jim_CmdPrivData(interp);
3968 if (!target->tap->enabled)
3969 return jim_target_tap_disabled(interp);
3971 int e = target->type->examine(target);
3974 Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
3980 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3984 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
3987 struct target *target = Jim_CmdPrivData(interp);
3988 if (!target->tap->enabled)
3989 return jim_target_tap_disabled(interp);
3992 if (!(target_was_examined(target))) {
3993 e = ERROR_TARGET_NOT_EXAMINED;
3995 e = target->type->poll(target);
3999 Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4005 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4008 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4012 Jim_WrongNumArgs(interp, 0, argv,
4013 "([tT]|[fF]|assert|deassert) BOOL");
4018 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4021 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4024 /* the halt or not param */
4026 e = Jim_GetOpt_Wide(&goi, &a);
4030 struct target *target = Jim_CmdPrivData(goi.interp);
4031 if (!target->tap->enabled)
4032 return jim_target_tap_disabled(interp);
4033 if (!target->type->assert_reset || !target->type->deassert_reset)
4035 Jim_SetResult_sprintf(interp,
4036 "No target-specific reset for %s",
4037 target_name(target));
4040 /* determine if we should halt or not. */
4041 target->reset_halt = !!a;
4042 /* When this happens - all workareas are invalid. */
4043 target_free_all_working_areas_restore(target, 0);
4046 if (n->value == NVP_ASSERT) {
4047 e = target->type->assert_reset(target);
4049 e = target->type->deassert_reset(target);
4051 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4054 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4057 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4060 struct target *target = Jim_CmdPrivData(interp);
4061 if (!target->tap->enabled)
4062 return jim_target_tap_disabled(interp);
4063 int e = target->type->halt(target);
4064 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4067 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4070 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4072 /* params: <name> statename timeoutmsecs */
4075 const char *cmd_name = Jim_GetString(argv[0], NULL);
4076 Jim_SetResult_sprintf(goi.interp,
4077 "%s <state_name> <timeout_in_msec>", cmd_name);
4082 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4084 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4088 e = Jim_GetOpt_Wide(&goi, &a);
4092 struct target *target = Jim_CmdPrivData(interp);
4093 if (!target->tap->enabled)
4094 return jim_target_tap_disabled(interp);
4096 e = target_wait_state(target, n->value, a);
4099 Jim_SetResult_sprintf(goi.interp,
4100 "target: %s wait %s fails (%d) %s",
4101 target_name(target), n->name,
4102 e, target_strerror_safe(e));
4107 /* List for human, Events defined for this target.
4108 * scripts/programs should use 'name cget -event NAME'
4110 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4112 struct command_context *cmd_ctx = Jim_GetAssocData(interp, "context");
4113 struct target *target = Jim_CmdPrivData(interp);
4114 struct target_event_action *teap = target->event_action;
4115 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4116 target->target_number,
4117 target_name(target));
4118 command_print(cmd_ctx, "%-25s | Body", "Event");
4119 command_print(cmd_ctx, "------------------------- | "
4120 "----------------------------------------");
4123 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4124 command_print(cmd_ctx, "%-25s | %s",
4125 opt->name, Jim_GetString(teap->body, NULL));
4128 command_print(cmd_ctx, "***END***");
4131 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4135 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4138 struct target *target = Jim_CmdPrivData(interp);
4139 Jim_SetResultString(interp, target_state_name(target), -1);
4142 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4145 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4148 const char *cmd_name = Jim_GetString(argv[0], NULL);
4149 Jim_SetResult_sprintf(goi.interp, "%s <eventname>", cmd_name);
4153 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4156 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4159 struct target *target = Jim_CmdPrivData(interp);
4160 target_handle_event(target, n->value);
4164 static const struct command_registration target_instance_command_handlers[] = {
4166 .name = "configure",
4167 .mode = COMMAND_CONFIG,
4168 .jim_handler = &jim_target_configure,
4169 .usage = "[<target_options> ...]",
4170 .help = "configure a new target for use",
4174 .mode = COMMAND_ANY,
4175 .jim_handler = &jim_target_configure,
4176 .usage = "<target_type> [<target_options> ...]",
4177 .help = "configure a new target for use",
4181 .mode = COMMAND_EXEC,
4182 .jim_handler = &jim_target_mw,
4183 .usage = "<address> <data> [<count>]",
4184 .help = "Write 32-bit word(s) to target memory",
4188 .mode = COMMAND_EXEC,
4189 .jim_handler = &jim_target_mw,
4190 .usage = "<address> <data> [<count>]",
4191 .help = "Write 16-bit half-word(s) to target memory",
4195 .mode = COMMAND_EXEC,
4196 .jim_handler = &jim_target_mw,
4197 .usage = "<address> <data> [<count>]",
4198 .help = "Write byte(s) to target memory",
4202 .mode = COMMAND_EXEC,
4203 .jim_handler = &jim_target_md,
4204 .usage = "<address> [<count>]",
4205 .help = "Display target memory as 32-bit words",
4209 .mode = COMMAND_EXEC,
4210 .jim_handler = &jim_target_md,
4211 .usage = "<address> [<count>]",
4212 .help = "Display target memory as 16-bit half-words",
4216 .mode = COMMAND_EXEC,
4217 .jim_handler = &jim_target_md,
4218 .usage = "<address> [<count>]",
4219 .help = "Display target memory as 8-bit bytes",
4222 .name = "array2mem",
4223 .mode = COMMAND_EXEC,
4224 .jim_handler = &jim_target_array2mem,
4227 .name = "mem2array",
4228 .mode = COMMAND_EXEC,
4229 .jim_handler = &jim_target_mem2array,
4232 .name = "eventlist",
4233 .mode = COMMAND_EXEC,
4234 .jim_handler = &jim_target_event_list,
4238 .mode = COMMAND_EXEC,
4239 .jim_handler = &jim_target_current_state,
4242 .name = "arp_examine",
4243 .mode = COMMAND_EXEC,
4244 .jim_handler = &jim_target_examine,
4248 .mode = COMMAND_EXEC,
4249 .jim_handler = &jim_target_poll,
4252 .name = "arp_reset",
4253 .mode = COMMAND_EXEC,
4254 .jim_handler = &jim_target_reset,
4258 .mode = COMMAND_EXEC,
4259 .jim_handler = &jim_target_halt,
4262 .name = "arp_waitstate",
4263 .mode = COMMAND_EXEC,
4264 .jim_handler = &jim_target_wait_state,
4267 .name = "invoke-event",
4268 .mode = COMMAND_EXEC,
4269 .jim_handler = &jim_target_invoke_event,
4271 COMMAND_REGISTRATION_DONE
4274 static int target_create(Jim_GetOptInfo *goi)
4282 struct target *target;
4283 struct command_context *cmd_ctx;
4285 cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4286 if (goi->argc < 3) {
4287 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4292 Jim_GetOpt_Obj(goi, &new_cmd);
4293 /* does this command exist? */
4294 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4296 cp = Jim_GetString(new_cmd, NULL);
4297 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4302 e = Jim_GetOpt_String(goi, &cp2, NULL);
4304 /* now does target type exist */
4305 for (x = 0 ; target_types[x] ; x++) {
4306 if (0 == strcmp(cp, target_types[x]->name)) {
4311 if (target_types[x] == NULL) {
4312 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4313 for (x = 0 ; target_types[x] ; x++) {
4314 if (target_types[x + 1]) {
4315 Jim_AppendStrings(goi->interp,
4316 Jim_GetResult(goi->interp),
4317 target_types[x]->name,
4320 Jim_AppendStrings(goi->interp,
4321 Jim_GetResult(goi->interp),
4323 target_types[x]->name,NULL);
4330 target = calloc(1,sizeof(struct target));
4331 /* set target number */
4332 target->target_number = new_target_number();
4334 /* allocate memory for each unique target type */
4335 target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4337 memcpy(target->type, target_types[x], sizeof(struct target_type));
4339 /* will be set by "-endian" */
4340 target->endianness = TARGET_ENDIAN_UNKNOWN;
4342 target->working_area = 0x0;
4343 target->working_area_size = 0x0;
4344 target->working_areas = NULL;
4345 target->backup_working_area = 0;
4347 target->state = TARGET_UNKNOWN;
4348 target->debug_reason = DBG_REASON_UNDEFINED;
4349 target->reg_cache = NULL;
4350 target->breakpoints = NULL;
4351 target->watchpoints = NULL;
4352 target->next = NULL;
4353 target->arch_info = NULL;
4355 target->display = 1;
4357 target->halt_issued = false;
4359 /* initialize trace information */
4360 target->trace_info = malloc(sizeof(struct trace));
4361 target->trace_info->num_trace_points = 0;
4362 target->trace_info->trace_points_size = 0;
4363 target->trace_info->trace_points = NULL;
4364 target->trace_info->trace_history_size = 0;
4365 target->trace_info->trace_history = NULL;
4366 target->trace_info->trace_history_pos = 0;
4367 target->trace_info->trace_history_overflowed = 0;
4369 target->dbgmsg = NULL;
4370 target->dbg_msg_enabled = 0;
4372 target->endianness = TARGET_ENDIAN_UNKNOWN;
4374 /* Do the rest as "configure" options */
4375 goi->isconfigure = 1;
4376 e = target_configure(goi, target);
4378 if (target->tap == NULL)
4380 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4390 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4391 /* default endian to little if not specified */
4392 target->endianness = TARGET_LITTLE_ENDIAN;
4395 /* incase variant is not set */
4396 if (!target->variant)
4397 target->variant = strdup("");
4399 cp = Jim_GetString(new_cmd, NULL);
4400 target->cmd_name = strdup(cp);
4402 /* create the target specific commands */
4403 if (target->type->commands) {
4404 e = register_commands(cmd_ctx, NULL, target->type->commands);
4406 LOG_ERROR("unable to register '%s' commands", cp);
4408 if (target->type->target_create) {
4409 (*(target->type->target_create))(target, goi->interp);
4412 /* append to end of list */
4414 struct target **tpp;
4415 tpp = &(all_targets);
4417 tpp = &((*tpp)->next);
4422 /* now - create the new target name command */
4423 const const struct command_registration target_subcommands[] = {
4425 .chain = target_instance_command_handlers,
4428 .chain = target->type->commands,
4430 COMMAND_REGISTRATION_DONE
4432 const const struct command_registration target_commands[] = {
4435 .mode = COMMAND_ANY,
4436 .help = "target command group",
4437 .chain = target_subcommands,
4439 COMMAND_REGISTRATION_DONE
4441 e = register_commands(cmd_ctx, NULL, target_commands);
4445 struct command *c = command_find_in_context(cmd_ctx, cp);
4447 command_set_handler_data(c, target);
4449 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
4452 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4456 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4459 struct command_context *cmd_ctx = Jim_GetAssocData(interp, "context");
4460 Jim_SetResultString(interp, get_current_target(cmd_ctx)->cmd_name, -1);
4464 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4468 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4471 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4472 for (unsigned x = 0; NULL != target_types[x]; x++)
4474 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4475 Jim_NewStringObj(interp, target_types[x]->name, -1));
4480 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4484 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4487 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4488 struct target *target = all_targets;
4491 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4492 Jim_NewStringObj(interp, target_name(target), -1));
4493 target = target->next;
4498 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4501 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4504 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4505 "<name> <target_type> [<target_options> ...]");
4508 return target_create(&goi);
4511 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4514 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4516 /* It's OK to remove this mechanism sometime after August 2010 or so */
4517 LOG_WARNING("don't use numbers as target identifiers; use names");
4520 Jim_SetResult_sprintf(goi.interp, "usage: target number <number>");
4524 int e = Jim_GetOpt_Wide(&goi, &w);
4528 struct target *target;
4529 for (target = all_targets; NULL != target; target = target->next)
4531 if (target->target_number != w)
4534 Jim_SetResultString(goi.interp, target_name(target), -1);
4537 Jim_SetResult_sprintf(goi.interp,
4538 "Target: number %d does not exist", (int)(w));
4542 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4546 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
4550 struct target *target = all_targets;
4551 while (NULL != target)
4553 target = target->next;
4556 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
4560 static const struct command_registration target_subcommand_handlers[] = {
4563 .mode = COMMAND_ANY,
4564 .jim_handler = &jim_target_create,
4565 .usage = "<name> <type> ...",
4566 .help = "Returns the currently selected target",
4570 .mode = COMMAND_ANY,
4571 .jim_handler = &jim_target_current,
4572 .help = "Returns the currently selected target",
4576 .mode = COMMAND_ANY,
4577 .jim_handler = &jim_target_types,
4578 .help = "Returns the available target types as a list of strings",
4582 .mode = COMMAND_ANY,
4583 .jim_handler = &jim_target_names,
4584 .help = "Returns the names of all targets as a list of strings",
4588 .mode = COMMAND_ANY,
4589 .jim_handler = &jim_target_number,
4590 .usage = "<number>",
4591 .help = "Returns the name of target <n>",
4595 .mode = COMMAND_ANY,
4596 .jim_handler = &jim_target_count,
4597 .help = "Returns the number of targets as an integer",
4599 COMMAND_REGISTRATION_DONE
4611 static int fastload_num;
4612 static struct FastLoad *fastload;
4614 static void free_fastload(void)
4616 if (fastload != NULL)
4619 for (i = 0; i < fastload_num; i++)
4621 if (fastload[i].data)
4622 free(fastload[i].data);
4632 COMMAND_HANDLER(handle_fast_load_image_command)
4636 uint32_t image_size;
4637 uint32_t min_address = 0;
4638 uint32_t max_address = 0xffffffff;
4643 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
4644 &image, &min_address, &max_address);
4645 if (ERROR_OK != retval)
4648 struct duration bench;
4649 duration_start(&bench);
4651 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
4658 fastload_num = image.num_sections;
4659 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4660 if (fastload == NULL)
4662 image_close(&image);
4665 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4666 for (i = 0; i < image.num_sections; i++)
4668 buffer = malloc(image.sections[i].size);
4671 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
4672 (int)(image.sections[i].size));
4676 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4682 uint32_t offset = 0;
4683 uint32_t length = buf_cnt;
4686 /* DANGER!!! beware of unsigned comparision here!!! */
4688 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4689 (image.sections[i].base_address < max_address))
4691 if (image.sections[i].base_address < min_address)
4693 /* clip addresses below */
4694 offset += min_address-image.sections[i].base_address;
4698 if (image.sections[i].base_address + buf_cnt > max_address)
4700 length -= (image.sections[i].base_address + buf_cnt)-max_address;
4703 fastload[i].address = image.sections[i].base_address + offset;
4704 fastload[i].data = malloc(length);
4705 if (fastload[i].data == NULL)
4710 memcpy(fastload[i].data, buffer + offset, length);
4711 fastload[i].length = length;
4713 image_size += length;
4714 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
4715 (unsigned int)length,
4716 ((unsigned int)(image.sections[i].base_address + offset)));
4722 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
4724 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
4725 "in %fs (%0.3f kb/s)", image_size,
4726 duration_elapsed(&bench), duration_kbps(&bench, image_size));
4728 command_print(CMD_CTX,
4729 "WARNING: image has not been loaded to target!"
4730 "You can issue a 'fast_load' to finish loading.");
4733 image_close(&image);
4735 if (retval != ERROR_OK)
4743 COMMAND_HANDLER(handle_fast_load_command)
4746 return ERROR_COMMAND_SYNTAX_ERROR;
4747 if (fastload == NULL)
4749 LOG_ERROR("No image in memory");
4753 int ms = timeval_ms();
4755 int retval = ERROR_OK;
4756 for (i = 0; i < fastload_num;i++)
4758 struct target *target = get_current_target(CMD_CTX);
4759 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
4760 (unsigned int)(fastload[i].address),
4761 (unsigned int)(fastload[i].length));
4762 if (retval == ERROR_OK)
4764 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
4766 size += fastload[i].length;
4768 int after = timeval_ms();
4769 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
4773 static const struct command_registration target_command_handlers[] = {
4776 .handler = &handle_targets_command,
4777 .mode = COMMAND_ANY,
4778 .help = "change current command line target (one parameter) "
4779 "or list targets (no parameters)",
4780 .usage = "[<new_current_target>]",
4784 .mode = COMMAND_CONFIG,
4785 .help = "configure target",
4787 .chain = target_subcommand_handlers,
4789 COMMAND_REGISTRATION_DONE
4792 int target_register_commands(struct command_context *cmd_ctx)
4794 return register_commands(cmd_ctx, NULL, target_command_handlers);
4797 static const struct command_registration target_exec_command_handlers[] = {
4799 .name = "fast_load_image",
4800 .handler = &handle_fast_load_image_command,
4801 .mode = COMMAND_ANY,
4802 .help = "Load image into memory, mainly for profiling purposes",
4803 .usage = "<file> <address> ['bin'|'ihex'|'elf'|'s19'] "
4804 "[min_address] [max_length]",
4807 .name = "fast_load",
4808 .handler = &handle_fast_load_command,
4809 .mode = COMMAND_ANY,
4810 .help = "loads active fast load image to current target "
4811 "- mainly for profiling purposes",
4815 .handler = &handle_profile_command,
4816 .mode = COMMAND_EXEC,
4817 .help = "profiling samples the CPU PC",
4819 /** @todo don't register virt2phys() unless target supports it */
4821 .name = "virt2phys",
4822 .handler = &handle_virt2phys_command,
4823 .mode = COMMAND_ANY,
4824 .help = "translate a virtual address into a physical address",
4829 .handler = &handle_reg_command,
4830 .mode = COMMAND_EXEC,
4831 .help = "display or set a register",
4836 .handler = &handle_poll_command,
4837 .mode = COMMAND_EXEC,
4838 .help = "poll target state",
4841 .name = "wait_halt",
4842 .handler = &handle_wait_halt_command,
4843 .mode = COMMAND_EXEC,
4844 .help = "wait for target halt",
4845 .usage = "[time (s)]",
4849 .handler = &handle_halt_command,
4850 .mode = COMMAND_EXEC,
4851 .help = "halt target",
4855 .handler = &handle_resume_command,
4856 .mode = COMMAND_EXEC,
4857 .help = "resume target",
4858 .usage = "[<address>]",
4862 .handler = &handle_reset_command,
4863 .mode = COMMAND_EXEC,
4864 .usage = "[run|halt|init]",
4865 .help = "Reset all targets into the specified mode."
4866 "Default reset mode is run, if not given.",
4869 .name = "soft_reset_halt",
4870 .handler = &handle_soft_reset_halt_command,
4871 .mode = COMMAND_EXEC,
4872 .help = "halt the target and do a soft reset",
4877 .handler = &handle_step_command,
4878 .mode = COMMAND_EXEC,
4879 .help = "step one instruction from current PC or [addr]",
4880 .usage = "[<address>]",
4885 .handler = &handle_md_command,
4886 .mode = COMMAND_EXEC,
4887 .help = "display memory words",
4888 .usage = "[phys] <addr> [count]",
4892 .handler = &handle_md_command,
4893 .mode = COMMAND_EXEC,
4894 .help = "display memory half-words",
4895 .usage = "[phys] <addr> [count]",
4899 .handler = &handle_md_command,
4900 .mode = COMMAND_EXEC,
4901 .help = "display memory bytes",
4902 .usage = "[phys] <addr> [count]",
4907 .handler = &handle_mw_command,
4908 .mode = COMMAND_EXEC,
4909 .help = "write memory word",
4910 .usage = "[phys] <addr> <value> [count]",
4914 .handler = &handle_mw_command,
4915 .mode = COMMAND_EXEC,
4916 .help = "write memory half-word",
4917 .usage = "[phys] <addr> <value> [count]",
4921 .handler = &handle_mw_command,
4922 .mode = COMMAND_EXEC,
4923 .help = "write memory byte",
4924 .usage = "[phys] <addr> <value> [count]",
4929 .handler = &handle_bp_command,
4930 .mode = COMMAND_EXEC,
4931 .help = "list or set breakpoint",
4932 .usage = "[<address> <length> [hw]]",
4936 .handler = &handle_rbp_command,
4937 .mode = COMMAND_EXEC,
4938 .help = "remove breakpoint",
4939 .usage = "<address>",
4944 .handler = &handle_wp_command,
4945 .mode = COMMAND_EXEC,
4946 .help = "list or set watchpoint",
4947 .usage = "[<address> <length> <r/w/a> [value] [mask]]",
4951 .handler = &handle_rwp_command,
4952 .mode = COMMAND_EXEC,
4953 .help = "remove watchpoint",
4954 .usage = "<address>",
4958 .name = "load_image",
4959 .handler = &handle_load_image_command,
4960 .mode = COMMAND_EXEC,
4961 .usage = "<file> <address> ['bin'|'ihex'|'elf'|'s19'] "
4962 "[min_address] [max_length]",
4965 .name = "dump_image",
4966 .handler = &handle_dump_image_command,
4967 .mode = COMMAND_EXEC,
4968 .usage = "<file> <address> <size>",
4971 .name = "verify_image",
4972 .handler = &handle_verify_image_command,
4973 .mode = COMMAND_EXEC,
4974 .usage = "<file> [offset] [type]",
4977 .name = "test_image",
4978 .handler = &handle_test_image_command,
4979 .mode = COMMAND_EXEC,
4980 .usage = "<file> [offset] [type]",
4983 .name = "ocd_mem2array",
4984 .mode = COMMAND_EXEC,
4985 .jim_handler = &jim_mem2array,
4986 .help = "read memory and return as a TCL array "
4987 "for script processing",
4988 .usage = "<arrayname> <width=32|16|8> <address> <count>",
4991 .name = "ocd_array2mem",
4992 .mode = COMMAND_EXEC,
4993 .jim_handler = &jim_array2mem,
4994 .help = "convert a TCL array to memory locations "
4995 "and write the values",
4996 .usage = "<arrayname> <width=32|16|8> <address> <count>",
4998 COMMAND_REGISTRATION_DONE
5000 int target_register_user_commands(struct command_context *cmd_ctx)
5002 int retval = ERROR_OK;
5003 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
5006 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
5010 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);