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 jim_mcrmrc(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
49 static int target_array2mem(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv);
50 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv);
53 extern struct target_type arm7tdmi_target;
54 extern struct target_type arm720t_target;
55 extern struct target_type arm9tdmi_target;
56 extern struct target_type arm920t_target;
57 extern struct target_type arm966e_target;
58 extern struct target_type arm926ejs_target;
59 extern struct target_type fa526_target;
60 extern struct target_type feroceon_target;
61 extern struct target_type dragonite_target;
62 extern struct target_type xscale_target;
63 extern struct target_type cortexm3_target;
64 extern struct target_type cortexa8_target;
65 extern struct target_type arm11_target;
66 extern struct target_type mips_m4k_target;
67 extern struct target_type avr_target;
69 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_POST, .name = "reset-assert-post" },
149 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
150 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
151 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
152 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
153 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
154 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
155 { .value = TARGET_EVENT_RESET_INIT , .name = "reset-init" },
156 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
158 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
159 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
161 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
162 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
164 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
165 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
167 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
168 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
170 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
171 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
173 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
174 { .value = TARGET_EVENT_RESUMED , .name = "resume-ok" },
175 { .value = TARGET_EVENT_RESUME_END , .name = "resume-end" },
177 { .name = NULL, .value = -1 }
180 const Jim_Nvp nvp_target_state[] = {
181 { .name = "unknown", .value = TARGET_UNKNOWN },
182 { .name = "running", .value = TARGET_RUNNING },
183 { .name = "halted", .value = TARGET_HALTED },
184 { .name = "reset", .value = TARGET_RESET },
185 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
186 { .name = NULL, .value = -1 },
189 const Jim_Nvp nvp_target_debug_reason [] = {
190 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
191 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
192 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
193 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
194 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
195 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
196 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
197 { .name = NULL, .value = -1 },
200 const Jim_Nvp nvp_target_endian[] = {
201 { .name = "big", .value = TARGET_BIG_ENDIAN },
202 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
203 { .name = "be", .value = TARGET_BIG_ENDIAN },
204 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
205 { .name = NULL, .value = -1 },
208 const Jim_Nvp nvp_reset_modes[] = {
209 { .name = "unknown", .value = RESET_UNKNOWN },
210 { .name = "run" , .value = RESET_RUN },
211 { .name = "halt" , .value = RESET_HALT },
212 { .name = "init" , .value = RESET_INIT },
213 { .name = NULL , .value = -1 },
217 target_state_name( struct target *t )
220 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
222 LOG_ERROR("Invalid target state: %d", (int)(t->state));
223 cp = "(*BUG*unknown*BUG*)";
228 /* determine the number of the new target */
229 static int new_target_number(void)
234 /* number is 0 based */
238 if (x < t->target_number) {
239 x = t->target_number;
246 /* read a uint32_t from a buffer in target memory endianness */
247 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
249 if (target->endianness == TARGET_LITTLE_ENDIAN)
250 return le_to_h_u32(buffer);
252 return be_to_h_u32(buffer);
255 /* read a uint16_t from a buffer in target memory endianness */
256 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
258 if (target->endianness == TARGET_LITTLE_ENDIAN)
259 return le_to_h_u16(buffer);
261 return be_to_h_u16(buffer);
264 /* read a uint8_t from a buffer in target memory endianness */
265 uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
267 return *buffer & 0x0ff;
270 /* write a uint32_t to a buffer in target memory endianness */
271 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
273 if (target->endianness == TARGET_LITTLE_ENDIAN)
274 h_u32_to_le(buffer, value);
276 h_u32_to_be(buffer, value);
279 /* write a uint16_t to a buffer in target memory endianness */
280 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
282 if (target->endianness == TARGET_LITTLE_ENDIAN)
283 h_u16_to_le(buffer, value);
285 h_u16_to_be(buffer, value);
288 /* write a uint8_t to a buffer in target memory endianness */
289 void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
294 /* return a pointer to a configured target; id is name or number */
295 struct target *get_target(const char *id)
297 struct target *target;
299 /* try as tcltarget name */
300 for (target = all_targets; target; target = target->next) {
301 if (target->cmd_name == NULL)
303 if (strcmp(id, target->cmd_name) == 0)
307 /* It's OK to remove this fallback sometime after August 2010 or so */
309 /* no match, try as number */
311 if (parse_uint(id, &num) != ERROR_OK)
314 for (target = all_targets; target; target = target->next) {
315 if (target->target_number == (int)num) {
316 LOG_WARNING("use '%s' as target identifier, not '%u'",
317 target->cmd_name, num);
325 /* returns a pointer to the n-th configured target */
326 static struct target *get_target_by_num(int num)
328 struct target *target = all_targets;
331 if (target->target_number == num) {
334 target = target->next;
340 struct target* get_current_target(struct command_context *cmd_ctx)
342 struct target *target = get_target_by_num(cmd_ctx->current_target);
346 LOG_ERROR("BUG: current_target out of bounds");
353 int target_poll(struct target *target)
357 /* We can't poll until after examine */
358 if (!target_was_examined(target))
360 /* Fail silently lest we pollute the log */
364 retval = target->type->poll(target);
365 if (retval != ERROR_OK)
368 if (target->halt_issued)
370 if (target->state == TARGET_HALTED)
372 target->halt_issued = false;
375 long long t = timeval_ms() - target->halt_issued_time;
378 target->halt_issued = false;
379 LOG_INFO("Halt timed out, wake up GDB.");
380 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
388 int target_halt(struct target *target)
391 /* We can't poll until after examine */
392 if (!target_was_examined(target))
394 LOG_ERROR("Target not examined yet");
398 retval = target->type->halt(target);
399 if (retval != ERROR_OK)
402 target->halt_issued = true;
403 target->halt_issued_time = timeval_ms();
408 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
412 /* We can't poll until after examine */
413 if (!target_was_examined(target))
415 LOG_ERROR("Target not examined yet");
419 /* note that resume *must* be asynchronous. The CPU can halt before we poll. The CPU can
420 * even halt at the current PC as a result of a software breakpoint being inserted by (a bug?)
423 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
429 int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
434 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
435 if (n->name == NULL) {
436 LOG_ERROR("invalid reset mode");
440 /* disable polling during reset to make reset event scripts
441 * more predictable, i.e. dr/irscan & pathmove in events will
442 * not have JTAG operations injected into the middle of a sequence.
444 bool save_poll = jtag_poll_get_enabled();
446 jtag_poll_set_enabled(false);
448 sprintf(buf, "ocd_process_reset %s", n->name);
449 retval = Jim_Eval(interp, buf);
451 jtag_poll_set_enabled(save_poll);
453 if (retval != JIM_OK) {
454 Jim_PrintErrorMessage(interp);
458 /* We want any events to be processed before the prompt */
459 retval = target_call_timer_callbacks_now();
464 static int identity_virt2phys(struct target *target,
465 uint32_t virtual, uint32_t *physical)
471 static int no_mmu(struct target *target, int *enabled)
477 static int default_examine(struct target *target)
479 target_set_examined(target);
483 int target_examine_one(struct target *target)
485 return target->type->examine(target);
488 static int jtag_enable_callback(enum jtag_event event, void *priv)
490 struct target *target = priv;
492 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
495 jtag_unregister_event_callback(jtag_enable_callback, target);
496 return target_examine_one(target);
500 /* Targets that correctly implement init + examine, i.e.
501 * no communication with target during init:
505 int target_examine(void)
507 int retval = ERROR_OK;
508 struct target *target;
510 for (target = all_targets; target; target = target->next)
512 /* defer examination, but don't skip it */
513 if (!target->tap->enabled) {
514 jtag_register_event_callback(jtag_enable_callback,
518 if ((retval = target_examine_one(target)) != ERROR_OK)
523 const char *target_get_name(struct target *target)
525 return target->type->name;
528 static int target_write_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
530 if (!target_was_examined(target))
532 LOG_ERROR("Target not examined yet");
535 return target->type->write_memory_imp(target, address, size, count, buffer);
538 static int target_read_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
540 if (!target_was_examined(target))
542 LOG_ERROR("Target not examined yet");
545 return target->type->read_memory_imp(target, address, size, count, buffer);
548 static int target_soft_reset_halt_imp(struct target *target)
550 if (!target_was_examined(target))
552 LOG_ERROR("Target not examined yet");
555 if (!target->type->soft_reset_halt_imp) {
556 LOG_ERROR("Target %s does not support soft_reset_halt",
560 return target->type->soft_reset_halt_imp(target);
563 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)
565 if (!target_was_examined(target))
567 LOG_ERROR("Target not examined yet");
570 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);
573 int target_read_memory(struct target *target,
574 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
576 return target->type->read_memory(target, address, size, count, buffer);
579 int target_read_phys_memory(struct target *target,
580 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
582 return target->type->read_phys_memory(target, address, size, count, buffer);
585 int target_write_memory(struct target *target,
586 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
588 return target->type->write_memory(target, address, size, count, buffer);
591 int target_write_phys_memory(struct target *target,
592 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
594 return target->type->write_phys_memory(target, address, size, count, buffer);
597 int target_bulk_write_memory(struct target *target,
598 uint32_t address, uint32_t count, uint8_t *buffer)
600 return target->type->bulk_write_memory(target, address, count, buffer);
603 int target_add_breakpoint(struct target *target,
604 struct breakpoint *breakpoint)
606 return target->type->add_breakpoint(target, breakpoint);
608 int target_remove_breakpoint(struct target *target,
609 struct breakpoint *breakpoint)
611 return target->type->remove_breakpoint(target, breakpoint);
614 int target_add_watchpoint(struct target *target,
615 struct watchpoint *watchpoint)
617 return target->type->add_watchpoint(target, watchpoint);
619 int target_remove_watchpoint(struct target *target,
620 struct watchpoint *watchpoint)
622 return target->type->remove_watchpoint(target, watchpoint);
625 int target_get_gdb_reg_list(struct target *target,
626 struct reg **reg_list[], int *reg_list_size)
628 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
630 int target_step(struct target *target,
631 int current, uint32_t address, int handle_breakpoints)
633 return target->type->step(target, current, address, handle_breakpoints);
637 int target_run_algorithm(struct target *target,
638 int num_mem_params, struct mem_param *mem_params,
639 int num_reg_params, struct reg_param *reg_param,
640 uint32_t entry_point, uint32_t exit_point,
641 int timeout_ms, void *arch_info)
643 return target->type->run_algorithm(target,
644 num_mem_params, mem_params, num_reg_params, reg_param,
645 entry_point, exit_point, timeout_ms, arch_info);
649 * Reset the @c examined flag for the given target.
650 * Pure paranoia -- targets are zeroed on allocation.
652 static void target_reset_examined(struct target *target)
654 target->examined = false;
659 static int default_mrc(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t *value)
661 LOG_ERROR("Not implemented: %s", __func__);
665 static int default_mcr(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t value)
667 LOG_ERROR("Not implemented: %s", __func__);
671 static int arm_cp_check(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm)
674 if (!target_was_examined(target))
676 LOG_ERROR("Target not examined yet");
680 if ((cpnum <0) || (cpnum > 15))
682 LOG_ERROR("Illegal co-processor %d", cpnum);
688 LOG_ERROR("Illegal op1");
694 LOG_ERROR("Illegal op2");
700 LOG_ERROR("Illegal CRn");
706 LOG_ERROR("Illegal CRm");
713 int target_mrc(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t *value)
717 retval = arm_cp_check(target, cpnum, op1, op2, CRn, CRm);
718 if (retval != ERROR_OK)
721 return target->type->mrc(target, cpnum, op1, op2, CRn, CRm, value);
724 int target_mcr(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t value)
728 retval = arm_cp_check(target, cpnum, op1, op2, CRn, CRm);
729 if (retval != ERROR_OK)
732 return target->type->mcr(target, cpnum, op1, op2, CRn, CRm, value);
736 err_read_phys_memory(struct target *target, uint32_t address,
737 uint32_t size, uint32_t count, uint8_t *buffer)
739 LOG_ERROR("Not implemented: %s", __func__);
744 err_write_phys_memory(struct target *target, uint32_t address,
745 uint32_t size, uint32_t count, uint8_t *buffer)
747 LOG_ERROR("Not implemented: %s", __func__);
751 int target_init(struct command_context *cmd_ctx)
753 struct target *target;
756 for (target = all_targets; target; target = target->next) {
757 struct target_type *type = target->type;
759 target_reset_examined(target);
760 if (target->type->examine == NULL)
762 target->type->examine = default_examine;
765 if ((retval = target->type->init_target(cmd_ctx, target)) != ERROR_OK)
767 LOG_ERROR("target '%s' init failed", target_get_name(target));
772 * @todo MCR/MRC are ARM-specific; don't require them in
773 * all targets, or for ARMs without coprocessors.
775 if (target->type->mcr == NULL)
777 target->type->mcr = default_mcr;
780 /* FIX! multiple targets will generally register global commands
781 * multiple times. Only register this one if *one* of the
782 * targets need the command. Hmm... make it a command on the
783 * Jim Tcl target object?
785 register_jim(cmd_ctx, "mcr", jim_mcrmrc, "write coprocessor <cpnum> <op1> <op2> <CRn> <CRm> <value>");
788 if (target->type->mrc == NULL)
790 target->type->mrc = default_mrc;
793 register_jim(cmd_ctx, "mrc", jim_mcrmrc, "read coprocessor <cpnum> <op1> <op2> <CRn> <CRm>");
798 * @todo get rid of those *memory_imp() methods, now that all
799 * callers are using target_*_memory() accessors ... and make
800 * sure the "physical" paths handle the same issues.
803 /* a non-invasive way(in terms of patches) to add some code that
804 * runs before the type->write/read_memory implementation
806 target->type->write_memory_imp = target->type->write_memory;
807 target->type->write_memory = target_write_memory_imp;
808 target->type->read_memory_imp = target->type->read_memory;
809 target->type->read_memory = target_read_memory_imp;
810 target->type->soft_reset_halt_imp = target->type->soft_reset_halt;
811 target->type->soft_reset_halt = target_soft_reset_halt_imp;
812 target->type->run_algorithm_imp = target->type->run_algorithm;
813 target->type->run_algorithm = target_run_algorithm_imp;
815 /* Sanity-check MMU support ... stub in what we must, to help
816 * implement it in stages, but warn if we need to do so.
819 if (type->write_phys_memory == NULL) {
820 LOG_ERROR("type '%s' is missing %s",
822 "write_phys_memory");
823 type->write_phys_memory = err_write_phys_memory;
825 if (type->read_phys_memory == NULL) {
826 LOG_ERROR("type '%s' is missing %s",
829 type->read_phys_memory = err_read_phys_memory;
831 if (type->virt2phys == NULL) {
832 LOG_ERROR("type '%s' is missing %s",
835 type->virt2phys = identity_virt2phys;
838 /* Make sure no-MMU targets all behave the same: make no
839 * distinction between physical and virtual addresses, and
840 * ensure that virt2phys() is always an identity mapping.
843 if (type->write_phys_memory
844 || type->read_phys_memory
846 LOG_WARNING("type '%s' has broken MMU hooks",
850 type->write_phys_memory = type->write_memory;
851 type->read_phys_memory = type->read_memory;
852 type->virt2phys = identity_virt2phys;
858 if ((retval = target_register_user_commands(cmd_ctx)) != ERROR_OK)
860 if ((retval = target_register_timer_callback(handle_target, 100, 1, NULL)) != ERROR_OK)
867 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
869 struct target_event_callback **callbacks_p = &target_event_callbacks;
871 if (callback == NULL)
873 return ERROR_INVALID_ARGUMENTS;
878 while ((*callbacks_p)->next)
879 callbacks_p = &((*callbacks_p)->next);
880 callbacks_p = &((*callbacks_p)->next);
883 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
884 (*callbacks_p)->callback = callback;
885 (*callbacks_p)->priv = priv;
886 (*callbacks_p)->next = NULL;
891 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
893 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
896 if (callback == NULL)
898 return ERROR_INVALID_ARGUMENTS;
903 while ((*callbacks_p)->next)
904 callbacks_p = &((*callbacks_p)->next);
905 callbacks_p = &((*callbacks_p)->next);
908 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
909 (*callbacks_p)->callback = callback;
910 (*callbacks_p)->periodic = periodic;
911 (*callbacks_p)->time_ms = time_ms;
913 gettimeofday(&now, NULL);
914 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
915 time_ms -= (time_ms % 1000);
916 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
917 if ((*callbacks_p)->when.tv_usec > 1000000)
919 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
920 (*callbacks_p)->when.tv_sec += 1;
923 (*callbacks_p)->priv = priv;
924 (*callbacks_p)->next = NULL;
929 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
931 struct target_event_callback **p = &target_event_callbacks;
932 struct target_event_callback *c = target_event_callbacks;
934 if (callback == NULL)
936 return ERROR_INVALID_ARGUMENTS;
941 struct target_event_callback *next = c->next;
942 if ((c->callback == callback) && (c->priv == priv))
956 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
958 struct target_timer_callback **p = &target_timer_callbacks;
959 struct target_timer_callback *c = target_timer_callbacks;
961 if (callback == NULL)
963 return ERROR_INVALID_ARGUMENTS;
968 struct target_timer_callback *next = c->next;
969 if ((c->callback == callback) && (c->priv == priv))
983 int target_call_event_callbacks(struct target *target, enum target_event event)
985 struct target_event_callback *callback = target_event_callbacks;
986 struct target_event_callback *next_callback;
988 if (event == TARGET_EVENT_HALTED)
990 /* execute early halted first */
991 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
994 LOG_DEBUG("target event %i (%s)",
996 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
998 target_handle_event(target, event);
1002 next_callback = callback->next;
1003 callback->callback(target, event, callback->priv);
1004 callback = next_callback;
1010 static int target_timer_callback_periodic_restart(
1011 struct target_timer_callback *cb, struct timeval *now)
1013 int time_ms = cb->time_ms;
1014 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1015 time_ms -= (time_ms % 1000);
1016 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1017 if (cb->when.tv_usec > 1000000)
1019 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1020 cb->when.tv_sec += 1;
1025 static int target_call_timer_callback(struct target_timer_callback *cb,
1026 struct timeval *now)
1028 cb->callback(cb->priv);
1031 return target_timer_callback_periodic_restart(cb, now);
1033 return target_unregister_timer_callback(cb->callback, cb->priv);
1036 static int target_call_timer_callbacks_check_time(int checktime)
1041 gettimeofday(&now, NULL);
1043 struct target_timer_callback *callback = target_timer_callbacks;
1046 // cleaning up may unregister and free this callback
1047 struct target_timer_callback *next_callback = callback->next;
1049 bool call_it = callback->callback &&
1050 ((!checktime && callback->periodic) ||
1051 now.tv_sec > callback->when.tv_sec ||
1052 (now.tv_sec == callback->when.tv_sec &&
1053 now.tv_usec >= callback->when.tv_usec));
1057 int retval = target_call_timer_callback(callback, &now);
1058 if (retval != ERROR_OK)
1062 callback = next_callback;
1068 int target_call_timer_callbacks(void)
1070 return target_call_timer_callbacks_check_time(1);
1073 /* invoke periodic callbacks immediately */
1074 int target_call_timer_callbacks_now(void)
1076 return target_call_timer_callbacks_check_time(0);
1079 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1081 struct working_area *c = target->working_areas;
1082 struct working_area *new_wa = NULL;
1084 /* Reevaluate working area address based on MMU state*/
1085 if (target->working_areas == NULL)
1090 retval = target->type->mmu(target, &enabled);
1091 if (retval != ERROR_OK)
1097 if (target->working_area_phys_spec) {
1098 LOG_DEBUG("MMU disabled, using physical "
1099 "address for working memory 0x%08x",
1100 (unsigned)target->working_area_phys);
1101 target->working_area = target->working_area_phys;
1103 LOG_ERROR("No working memory available. "
1104 "Specify -work-area-phys to target.");
1105 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1108 if (target->working_area_virt_spec) {
1109 LOG_DEBUG("MMU enabled, using virtual "
1110 "address for working memory 0x%08x",
1111 (unsigned)target->working_area_virt);
1112 target->working_area = target->working_area_virt;
1114 LOG_ERROR("No working memory available. "
1115 "Specify -work-area-virt to target.");
1116 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1121 /* only allocate multiples of 4 byte */
1124 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1125 size = (size + 3) & (~3);
1128 /* see if there's already a matching working area */
1131 if ((c->free) && (c->size == size))
1139 /* if not, allocate a new one */
1142 struct working_area **p = &target->working_areas;
1143 uint32_t first_free = target->working_area;
1144 uint32_t free_size = target->working_area_size;
1146 c = target->working_areas;
1149 first_free += c->size;
1150 free_size -= c->size;
1155 if (free_size < size)
1157 LOG_WARNING("not enough working area available(requested %u, free %u)",
1158 (unsigned)(size), (unsigned)(free_size));
1159 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1162 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1164 new_wa = malloc(sizeof(struct working_area));
1165 new_wa->next = NULL;
1166 new_wa->size = size;
1167 new_wa->address = first_free;
1169 if (target->backup_working_area)
1172 new_wa->backup = malloc(new_wa->size);
1173 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1175 free(new_wa->backup);
1182 new_wa->backup = NULL;
1185 /* put new entry in list */
1189 /* mark as used, and return the new (reused) area */
1194 new_wa->user = area;
1199 int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1204 if (restore && target->backup_working_area)
1207 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1213 /* mark user pointer invalid */
1220 int target_free_working_area(struct target *target, struct working_area *area)
1222 return target_free_working_area_restore(target, area, 1);
1225 /* free resources and restore memory, if restoring memory fails,
1226 * free up resources anyway
1228 void target_free_all_working_areas_restore(struct target *target, int restore)
1230 struct working_area *c = target->working_areas;
1234 struct working_area *next = c->next;
1235 target_free_working_area_restore(target, c, restore);
1245 target->working_areas = NULL;
1248 void target_free_all_working_areas(struct target *target)
1250 target_free_all_working_areas_restore(target, 1);
1253 int target_arch_state(struct target *target)
1258 LOG_USER("No target has been configured");
1262 LOG_USER("target state: %s", target_state_name( target ));
1264 if (target->state != TARGET_HALTED)
1267 retval = target->type->arch_state(target);
1271 /* Single aligned words are guaranteed to use 16 or 32 bit access
1272 * mode respectively, otherwise data is handled as quickly as
1275 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1278 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1279 (int)size, (unsigned)address);
1281 if (!target_was_examined(target))
1283 LOG_ERROR("Target not examined yet");
1291 if ((address + size - 1) < address)
1293 /* GDB can request this when e.g. PC is 0xfffffffc*/
1294 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1300 if (((address % 2) == 0) && (size == 2))
1302 return target_write_memory(target, address, 2, 1, buffer);
1305 /* handle unaligned head bytes */
1308 uint32_t unaligned = 4 - (address % 4);
1310 if (unaligned > size)
1313 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1316 buffer += unaligned;
1317 address += unaligned;
1321 /* handle aligned words */
1324 int aligned = size - (size % 4);
1326 /* use bulk writes above a certain limit. This may have to be changed */
1329 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1334 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1343 /* handle tail writes of less than 4 bytes */
1346 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1353 /* Single aligned words are guaranteed to use 16 or 32 bit access
1354 * mode respectively, otherwise data is handled as quickly as
1357 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1360 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1361 (int)size, (unsigned)address);
1363 if (!target_was_examined(target))
1365 LOG_ERROR("Target not examined yet");
1373 if ((address + size - 1) < address)
1375 /* GDB can request this when e.g. PC is 0xfffffffc*/
1376 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1382 if (((address % 2) == 0) && (size == 2))
1384 return target_read_memory(target, address, 2, 1, buffer);
1387 /* handle unaligned head bytes */
1390 uint32_t unaligned = 4 - (address % 4);
1392 if (unaligned > size)
1395 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1398 buffer += unaligned;
1399 address += unaligned;
1403 /* handle aligned words */
1406 int aligned = size - (size % 4);
1408 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1416 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1419 int aligned = size - (size%2);
1420 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1421 if (retval != ERROR_OK)
1428 /* handle tail writes of less than 4 bytes */
1431 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1438 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1443 uint32_t checksum = 0;
1444 if (!target_was_examined(target))
1446 LOG_ERROR("Target not examined yet");
1450 if ((retval = target->type->checksum_memory(target, address,
1451 size, &checksum)) != ERROR_OK)
1453 buffer = malloc(size);
1456 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1457 return ERROR_INVALID_ARGUMENTS;
1459 retval = target_read_buffer(target, address, size, buffer);
1460 if (retval != ERROR_OK)
1466 /* convert to target endianess */
1467 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1469 uint32_t target_data;
1470 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1471 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1474 retval = image_calculate_checksum(buffer, size, &checksum);
1483 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1486 if (!target_was_examined(target))
1488 LOG_ERROR("Target not examined yet");
1492 if (target->type->blank_check_memory == 0)
1493 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1495 retval = target->type->blank_check_memory(target, address, size, blank);
1500 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1502 uint8_t value_buf[4];
1503 if (!target_was_examined(target))
1505 LOG_ERROR("Target not examined yet");
1509 int retval = target_read_memory(target, address, 4, 1, value_buf);
1511 if (retval == ERROR_OK)
1513 *value = target_buffer_get_u32(target, value_buf);
1514 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1521 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1528 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1530 uint8_t value_buf[2];
1531 if (!target_was_examined(target))
1533 LOG_ERROR("Target not examined yet");
1537 int retval = target_read_memory(target, address, 2, 1, value_buf);
1539 if (retval == ERROR_OK)
1541 *value = target_buffer_get_u16(target, value_buf);
1542 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1549 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1556 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1558 int retval = target_read_memory(target, address, 1, 1, value);
1559 if (!target_was_examined(target))
1561 LOG_ERROR("Target not examined yet");
1565 if (retval == ERROR_OK)
1567 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1574 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1581 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1584 uint8_t value_buf[4];
1585 if (!target_was_examined(target))
1587 LOG_ERROR("Target not examined yet");
1591 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1595 target_buffer_set_u32(target, value_buf, value);
1596 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1598 LOG_DEBUG("failed: %i", retval);
1604 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1607 uint8_t value_buf[2];
1608 if (!target_was_examined(target))
1610 LOG_ERROR("Target not examined yet");
1614 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1618 target_buffer_set_u16(target, value_buf, value);
1619 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1621 LOG_DEBUG("failed: %i", retval);
1627 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1630 if (!target_was_examined(target))
1632 LOG_ERROR("Target not examined yet");
1636 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1639 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1641 LOG_DEBUG("failed: %i", retval);
1647 COMMAND_HANDLER(handle_targets_command)
1649 struct target *target = all_targets;
1653 target = get_target(args[0]);
1654 if (target == NULL) {
1655 command_print(cmd_ctx,"Target: %s is unknown, try one of:\n", args[0]);
1658 if (!target->tap->enabled) {
1659 command_print(cmd_ctx,"Target: TAP %s is disabled, "
1660 "can't be the current target\n",
1661 target->tap->dotted_name);
1665 cmd_ctx->current_target = target->target_number;
1670 target = all_targets;
1671 command_print(cmd_ctx, " TargetName Type Endian TapName State ");
1672 command_print(cmd_ctx, "-- ------------------ ---------- ------ ------------------ ------------");
1678 if (target->tap->enabled)
1679 state = target_state_name( target );
1681 state = "tap-disabled";
1683 if (cmd_ctx->current_target == target->target_number)
1686 /* keep columns lined up to match the headers above */
1687 command_print(cmd_ctx, "%2d%c %-18s %-10s %-6s %-18s %s",
1688 target->target_number,
1691 target_get_name(target),
1692 Jim_Nvp_value2name_simple(nvp_target_endian,
1693 target->endianness)->name,
1694 target->tap->dotted_name,
1696 target = target->next;
1702 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1704 static int powerDropout;
1705 static int srstAsserted;
1707 static int runPowerRestore;
1708 static int runPowerDropout;
1709 static int runSrstAsserted;
1710 static int runSrstDeasserted;
1712 static int sense_handler(void)
1714 static int prevSrstAsserted = 0;
1715 static int prevPowerdropout = 0;
1718 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1722 powerRestored = prevPowerdropout && !powerDropout;
1725 runPowerRestore = 1;
1728 long long current = timeval_ms();
1729 static long long lastPower = 0;
1730 int waitMore = lastPower + 2000 > current;
1731 if (powerDropout && !waitMore)
1733 runPowerDropout = 1;
1734 lastPower = current;
1737 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1741 srstDeasserted = prevSrstAsserted && !srstAsserted;
1743 static long long lastSrst = 0;
1744 waitMore = lastSrst + 2000 > current;
1745 if (srstDeasserted && !waitMore)
1747 runSrstDeasserted = 1;
1751 if (!prevSrstAsserted && srstAsserted)
1753 runSrstAsserted = 1;
1756 prevSrstAsserted = srstAsserted;
1757 prevPowerdropout = powerDropout;
1759 if (srstDeasserted || powerRestored)
1761 /* Other than logging the event we can't do anything here.
1762 * Issuing a reset is a particularly bad idea as we might
1763 * be inside a reset already.
1770 static void target_call_event_callbacks_all(enum target_event e) {
1771 struct target *target;
1772 target = all_targets;
1774 target_call_event_callbacks(target, e);
1775 target = target->next;
1779 /* process target state changes */
1780 int handle_target(void *priv)
1782 int retval = ERROR_OK;
1784 /* we do not want to recurse here... */
1785 static int recursive = 0;
1790 /* danger! running these procedures can trigger srst assertions and power dropouts.
1791 * We need to avoid an infinite loop/recursion here and we do that by
1792 * clearing the flags after running these events.
1794 int did_something = 0;
1795 if (runSrstAsserted)
1797 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1798 Jim_Eval(interp, "srst_asserted");
1801 if (runSrstDeasserted)
1803 Jim_Eval(interp, "srst_deasserted");
1806 if (runPowerDropout)
1808 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1809 Jim_Eval(interp, "power_dropout");
1812 if (runPowerRestore)
1814 Jim_Eval(interp, "power_restore");
1820 /* clear detect flags */
1824 /* clear action flags */
1826 runSrstAsserted = 0;
1827 runSrstDeasserted = 0;
1828 runPowerRestore = 0;
1829 runPowerDropout = 0;
1834 /* Poll targets for state changes unless that's globally disabled.
1835 * Skip targets that are currently disabled.
1837 for (struct target *target = all_targets;
1838 is_jtag_poll_safe() && target;
1839 target = target->next)
1841 if (!target->tap->enabled)
1844 /* only poll target if we've got power and srst isn't asserted */
1845 if (!powerDropout && !srstAsserted)
1847 /* polling may fail silently until the target has been examined */
1848 if ((retval = target_poll(target)) != ERROR_OK)
1850 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1859 COMMAND_HANDLER(handle_reg_command)
1861 struct target *target;
1862 struct reg *reg = NULL;
1868 target = get_current_target(cmd_ctx);
1870 /* list all available registers for the current target */
1873 struct reg_cache *cache = target->reg_cache;
1880 command_print(cmd_ctx, "===== %s", cache->name);
1882 for (i = 0, reg = cache->reg_list;
1883 i < cache->num_regs;
1884 i++, reg++, count++)
1886 /* only print cached values if they are valid */
1888 value = buf_to_str(reg->value,
1890 command_print(cmd_ctx,
1891 "(%i) %s (/%" PRIu32 "): 0x%s%s",
1899 command_print(cmd_ctx, "(%i) %s (/%" PRIu32 ")",
1904 cache = cache->next;
1910 /* access a single register by its ordinal number */
1911 if ((args[0][0] >= '0') && (args[0][0] <= '9'))
1914 COMMAND_PARSE_NUMBER(uint, args[0], num);
1916 struct reg_cache *cache = target->reg_cache;
1921 for (i = 0; i < cache->num_regs; i++)
1923 if (count++ == (int)num)
1925 reg = &cache->reg_list[i];
1931 cache = cache->next;
1936 command_print(cmd_ctx, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1939 } else /* access a single register by its name */
1941 reg = register_get_by_name(target->reg_cache, args[0], 1);
1945 command_print(cmd_ctx, "register %s not found in current target", args[0]);
1950 /* display a register */
1951 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((args[1][0] >= '0') && (args[1][0] <= '9'))))
1953 if ((CMD_ARGC == 2) && (strcmp(args[1], "force") == 0))
1956 if (reg->valid == 0)
1958 reg->type->get(reg);
1960 value = buf_to_str(reg->value, reg->size, 16);
1961 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1966 /* set register value */
1969 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
1970 str_to_buf(args[1], strlen(args[1]), buf, reg->size, 0);
1972 reg->type->set(reg, buf);
1974 value = buf_to_str(reg->value, reg->size, 16);
1975 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1983 command_print(cmd_ctx, "usage: reg <#|name> [value]");
1988 COMMAND_HANDLER(handle_poll_command)
1990 int retval = ERROR_OK;
1991 struct target *target = get_current_target(cmd_ctx);
1995 command_print(cmd_ctx, "background polling: %s",
1996 jtag_poll_get_enabled() ? "on" : "off");
1997 command_print(cmd_ctx, "TAP: %s (%s)",
1998 target->tap->dotted_name,
1999 target->tap->enabled ? "enabled" : "disabled");
2000 if (!target->tap->enabled)
2002 if ((retval = target_poll(target)) != ERROR_OK)
2004 if ((retval = target_arch_state(target)) != ERROR_OK)
2008 else if (CMD_ARGC == 1)
2010 if (strcmp(args[0], "on") == 0)
2012 jtag_poll_set_enabled(true);
2014 else if (strcmp(args[0], "off") == 0)
2016 jtag_poll_set_enabled(false);
2020 command_print(cmd_ctx, "arg is \"on\" or \"off\"");
2024 return ERROR_COMMAND_SYNTAX_ERROR;
2030 COMMAND_HANDLER(handle_wait_halt_command)
2033 return ERROR_COMMAND_SYNTAX_ERROR;
2038 int retval = parse_uint(args[0], &ms);
2039 if (ERROR_OK != retval)
2041 command_print(cmd_ctx, "usage: %s [seconds]", CMD_NAME);
2042 return ERROR_COMMAND_SYNTAX_ERROR;
2044 // convert seconds (given) to milliseconds (needed)
2048 struct target *target = get_current_target(cmd_ctx);
2049 return target_wait_state(target, TARGET_HALTED, ms);
2052 /* wait for target state to change. The trick here is to have a low
2053 * latency for short waits and not to suck up all the CPU time
2056 * After 500ms, keep_alive() is invoked
2058 int target_wait_state(struct target *target, enum target_state state, int ms)
2061 long long then = 0, cur;
2066 if ((retval = target_poll(target)) != ERROR_OK)
2068 if (target->state == state)
2076 then = timeval_ms();
2077 LOG_DEBUG("waiting for target %s...",
2078 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2086 if ((cur-then) > ms)
2088 LOG_ERROR("timed out while waiting for target %s",
2089 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2097 COMMAND_HANDLER(handle_halt_command)
2101 struct target *target = get_current_target(cmd_ctx);
2102 int retval = target_halt(target);
2103 if (ERROR_OK != retval)
2109 retval = parse_uint(args[0], &wait);
2110 if (ERROR_OK != retval)
2111 return ERROR_COMMAND_SYNTAX_ERROR;
2116 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2119 COMMAND_HANDLER(handle_soft_reset_halt_command)
2121 struct target *target = get_current_target(cmd_ctx);
2123 LOG_USER("requesting target halt and executing a soft reset");
2125 target->type->soft_reset_halt(target);
2130 COMMAND_HANDLER(handle_reset_command)
2133 return ERROR_COMMAND_SYNTAX_ERROR;
2135 enum target_reset_mode reset_mode = RESET_RUN;
2139 n = Jim_Nvp_name2value_simple(nvp_reset_modes, args[0]);
2140 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2141 return ERROR_COMMAND_SYNTAX_ERROR;
2143 reset_mode = n->value;
2146 /* reset *all* targets */
2147 return target_process_reset(cmd_ctx, reset_mode);
2151 COMMAND_HANDLER(handle_resume_command)
2155 return ERROR_COMMAND_SYNTAX_ERROR;
2157 struct target *target = get_current_target(cmd_ctx);
2158 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2160 /* with no args, resume from current pc, addr = 0,
2161 * with one arguments, addr = args[0],
2162 * handle breakpoints, not debugging */
2166 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2170 return target_resume(target, current, addr, 1, 0);
2173 COMMAND_HANDLER(handle_step_command)
2176 return ERROR_COMMAND_SYNTAX_ERROR;
2180 /* with no args, step from current pc, addr = 0,
2181 * with one argument addr = args[0],
2182 * handle breakpoints, debugging */
2187 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2191 struct target *target = get_current_target(cmd_ctx);
2193 return target->type->step(target, current_pc, addr, 1);
2196 static void handle_md_output(struct command_context *cmd_ctx,
2197 struct target *target, uint32_t address, unsigned size,
2198 unsigned count, const uint8_t *buffer)
2200 const unsigned line_bytecnt = 32;
2201 unsigned line_modulo = line_bytecnt / size;
2203 char output[line_bytecnt * 4 + 1];
2204 unsigned output_len = 0;
2206 const char *value_fmt;
2208 case 4: value_fmt = "%8.8x "; break;
2209 case 2: value_fmt = "%4.2x "; break;
2210 case 1: value_fmt = "%2.2x "; break;
2212 LOG_ERROR("invalid memory read size: %u", size);
2216 for (unsigned i = 0; i < count; i++)
2218 if (i % line_modulo == 0)
2220 output_len += snprintf(output + output_len,
2221 sizeof(output) - output_len,
2223 (unsigned)(address + (i*size)));
2227 const uint8_t *value_ptr = buffer + i * size;
2229 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2230 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2231 case 1: value = *value_ptr;
2233 output_len += snprintf(output + output_len,
2234 sizeof(output) - output_len,
2237 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2239 command_print(cmd_ctx, "%s", output);
2245 COMMAND_HANDLER(handle_md_command)
2248 return ERROR_COMMAND_SYNTAX_ERROR;
2251 const char *cmd_name = CMD_NAME;
2252 switch (cmd_name[6]) {
2253 case 'w': size = 4; break;
2254 case 'h': size = 2; break;
2255 case 'b': size = 1; break;
2256 default: return ERROR_COMMAND_SYNTAX_ERROR;
2259 bool physical=strcmp(args[0], "phys")==0;
2260 int (*fn)(struct target *target,
2261 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2266 fn=target_read_phys_memory;
2269 fn=target_read_memory;
2271 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2273 return ERROR_COMMAND_SYNTAX_ERROR;
2277 COMMAND_PARSE_NUMBER(u32, args[0], address);
2281 COMMAND_PARSE_NUMBER(uint, args[1], count);
2283 uint8_t *buffer = calloc(count, size);
2285 struct target *target = get_current_target(cmd_ctx);
2286 int retval = fn(target, address, size, count, buffer);
2287 if (ERROR_OK == retval)
2288 handle_md_output(cmd_ctx, target, address, size, count, buffer);
2295 COMMAND_HANDLER(handle_mw_command)
2299 return ERROR_COMMAND_SYNTAX_ERROR;
2301 bool physical=strcmp(args[0], "phys")==0;
2302 int (*fn)(struct target *target,
2303 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2304 const char *cmd_name = CMD_NAME;
2309 fn=target_write_phys_memory;
2312 fn=target_write_memory;
2314 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2315 return ERROR_COMMAND_SYNTAX_ERROR;
2318 COMMAND_PARSE_NUMBER(u32, args[0], address);
2321 COMMAND_PARSE_NUMBER(u32, args[1], value);
2325 COMMAND_PARSE_NUMBER(uint, args[2], count);
2327 struct target *target = get_current_target(cmd_ctx);
2329 uint8_t value_buf[4];
2330 switch (cmd_name[6])
2334 target_buffer_set_u32(target, value_buf, value);
2338 target_buffer_set_u16(target, value_buf, value);
2342 value_buf[0] = value;
2345 return ERROR_COMMAND_SYNTAX_ERROR;
2347 for (unsigned i = 0; i < count; i++)
2349 int retval = fn(target,
2350 address + i * wordsize, wordsize, 1, value_buf);
2351 if (ERROR_OK != retval)
2360 static COMMAND_HELPER(parse_load_image_command_args, struct image *image,
2361 uint32_t *min_address, uint32_t *max_address)
2363 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2364 return ERROR_COMMAND_SYNTAX_ERROR;
2366 /* a base address isn't always necessary,
2367 * default to 0x0 (i.e. don't relocate) */
2371 COMMAND_PARSE_NUMBER(u32, args[1], addr);
2372 image->base_address = addr;
2373 image->base_address_set = 1;
2376 image->base_address_set = 0;
2378 image->start_address_set = 0;
2382 COMMAND_PARSE_NUMBER(u32, args[3], *min_address);
2386 COMMAND_PARSE_NUMBER(u32, args[4], *max_address);
2387 // use size (given) to find max (required)
2388 *max_address += *min_address;
2391 if (*min_address > *max_address)
2392 return ERROR_COMMAND_SYNTAX_ERROR;
2397 COMMAND_HANDLER(handle_load_image_command)
2401 uint32_t image_size;
2402 uint32_t min_address = 0;
2403 uint32_t max_address = 0xffffffff;
2407 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_args,
2408 &image, &min_address, &max_address);
2409 if (ERROR_OK != retval)
2412 struct target *target = get_current_target(cmd_ctx);
2414 struct duration bench;
2415 duration_start(&bench);
2417 if (image_open(&image, args[0], (CMD_ARGC >= 3) ? args[2] : NULL) != ERROR_OK)
2424 for (i = 0; i < image.num_sections; i++)
2426 buffer = malloc(image.sections[i].size);
2429 command_print(cmd_ctx,
2430 "error allocating buffer for section (%d bytes)",
2431 (int)(image.sections[i].size));
2435 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2441 uint32_t offset = 0;
2442 uint32_t length = buf_cnt;
2444 /* DANGER!!! beware of unsigned comparision here!!! */
2446 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2447 (image.sections[i].base_address < max_address))
2449 if (image.sections[i].base_address < min_address)
2451 /* clip addresses below */
2452 offset += min_address-image.sections[i].base_address;
2456 if (image.sections[i].base_address + buf_cnt > max_address)
2458 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2461 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2466 image_size += length;
2467 command_print(cmd_ctx, "%u bytes written at address 0x%8.8" PRIx32 "",
2468 (unsigned int)length,
2469 image.sections[i].base_address + offset);
2475 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2477 command_print(cmd_ctx, "downloaded %" PRIu32 " bytes "
2478 "in %fs (%0.3f kb/s)", image_size,
2479 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2482 image_close(&image);
2488 COMMAND_HANDLER(handle_dump_image_command)
2490 struct fileio fileio;
2492 uint8_t buffer[560];
2496 struct target *target = get_current_target(cmd_ctx);
2500 command_print(cmd_ctx, "usage: dump_image <filename> <address> <size>");
2505 COMMAND_PARSE_NUMBER(u32, args[1], address);
2507 COMMAND_PARSE_NUMBER(u32, args[2], size);
2509 if (fileio_open(&fileio, args[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2514 struct duration bench;
2515 duration_start(&bench);
2517 int retval = ERROR_OK;
2520 size_t size_written;
2521 uint32_t this_run_size = (size > 560) ? 560 : size;
2522 retval = target_read_buffer(target, address, this_run_size, buffer);
2523 if (retval != ERROR_OK)
2528 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2529 if (retval != ERROR_OK)
2534 size -= this_run_size;
2535 address += this_run_size;
2538 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2541 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2543 command_print(cmd_ctx,
2544 "dumped %zu bytes in %fs (%0.3f kb/s)", fileio.size,
2545 duration_elapsed(&bench), duration_kbps(&bench, fileio.size));
2551 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2555 uint32_t image_size;
2558 uint32_t checksum = 0;
2559 uint32_t mem_checksum = 0;
2563 struct target *target = get_current_target(cmd_ctx);
2567 return ERROR_COMMAND_SYNTAX_ERROR;
2572 LOG_ERROR("no target selected");
2576 struct duration bench;
2577 duration_start(&bench);
2582 COMMAND_PARSE_NUMBER(u32, args[1], addr);
2583 image.base_address = addr;
2584 image.base_address_set = 1;
2588 image.base_address_set = 0;
2589 image.base_address = 0x0;
2592 image.start_address_set = 0;
2594 if ((retval = image_open(&image, args[0], (CMD_ARGC == 3) ? args[2] : NULL)) != ERROR_OK)
2601 for (i = 0; i < image.num_sections; i++)
2603 buffer = malloc(image.sections[i].size);
2606 command_print(cmd_ctx,
2607 "error allocating buffer for section (%d bytes)",
2608 (int)(image.sections[i].size));
2611 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2619 /* calculate checksum of image */
2620 image_calculate_checksum(buffer, buf_cnt, &checksum);
2622 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2623 if (retval != ERROR_OK)
2629 if (checksum != mem_checksum)
2631 /* failed crc checksum, fall back to a binary compare */
2634 command_print(cmd_ctx, "checksum mismatch - attempting binary compare");
2636 data = (uint8_t*)malloc(buf_cnt);
2638 /* Can we use 32bit word accesses? */
2640 int count = buf_cnt;
2641 if ((count % 4) == 0)
2646 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2647 if (retval == ERROR_OK)
2650 for (t = 0; t < buf_cnt; t++)
2652 if (data[t] != buffer[t])
2654 command_print(cmd_ctx,
2655 "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n",
2656 (unsigned)(t + image.sections[i].base_address),
2661 retval = ERROR_FAIL;
2675 command_print(cmd_ctx, "address 0x%08" PRIx32 " length 0x%08zx",
2676 image.sections[i].base_address,
2681 image_size += buf_cnt;
2684 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2686 command_print(cmd_ctx, "verified %" PRIu32 " bytes "
2687 "in %fs (%0.3f kb/s)", image_size,
2688 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2691 image_close(&image);
2696 COMMAND_HANDLER(handle_verify_image_command)
2698 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2701 COMMAND_HANDLER(handle_test_image_command)
2703 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2706 static int handle_bp_command_list(struct command_context *cmd_ctx)
2708 struct target *target = get_current_target(cmd_ctx);
2709 struct breakpoint *breakpoint = target->breakpoints;
2712 if (breakpoint->type == BKPT_SOFT)
2714 char* buf = buf_to_str(breakpoint->orig_instr,
2715 breakpoint->length, 16);
2716 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2717 breakpoint->address,
2719 breakpoint->set, buf);
2724 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2725 breakpoint->address,
2726 breakpoint->length, breakpoint->set);
2729 breakpoint = breakpoint->next;
2734 static int handle_bp_command_set(struct command_context *cmd_ctx,
2735 uint32_t addr, uint32_t length, int hw)
2737 struct target *target = get_current_target(cmd_ctx);
2738 int retval = breakpoint_add(target, addr, length, hw);
2739 if (ERROR_OK == retval)
2740 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2742 LOG_ERROR("Failure setting breakpoint");
2746 COMMAND_HANDLER(handle_bp_command)
2749 return handle_bp_command_list(cmd_ctx);
2751 if (CMD_ARGC < 2 || CMD_ARGC > 3)
2753 command_print(cmd_ctx, "usage: bp <address> <length> ['hw']");
2754 return ERROR_COMMAND_SYNTAX_ERROR;
2758 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2760 COMMAND_PARSE_NUMBER(u32, args[1], length);
2765 if (strcmp(args[2], "hw") == 0)
2768 return ERROR_COMMAND_SYNTAX_ERROR;
2771 return handle_bp_command_set(cmd_ctx, addr, length, hw);
2774 COMMAND_HANDLER(handle_rbp_command)
2777 return ERROR_COMMAND_SYNTAX_ERROR;
2780 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2782 struct target *target = get_current_target(cmd_ctx);
2783 breakpoint_remove(target, addr);
2788 COMMAND_HANDLER(handle_wp_command)
2790 struct target *target = get_current_target(cmd_ctx);
2794 struct watchpoint *watchpoint = target->watchpoints;
2798 command_print(cmd_ctx, "address: 0x%8.8" PRIx32
2799 ", len: 0x%8.8" PRIx32
2800 ", r/w/a: %i, value: 0x%8.8" PRIx32
2801 ", mask: 0x%8.8" PRIx32,
2802 watchpoint->address,
2804 (int)watchpoint->rw,
2807 watchpoint = watchpoint->next;
2812 enum watchpoint_rw type = WPT_ACCESS;
2814 uint32_t length = 0;
2815 uint32_t data_value = 0x0;
2816 uint32_t data_mask = 0xffffffff;
2821 COMMAND_PARSE_NUMBER(u32, args[4], data_mask);
2824 COMMAND_PARSE_NUMBER(u32, args[3], data_value);
2839 LOG_ERROR("invalid watchpoint mode ('%c')", args[2][0]);
2840 return ERROR_COMMAND_SYNTAX_ERROR;
2844 COMMAND_PARSE_NUMBER(u32, args[1], length);
2845 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2849 command_print(cmd_ctx, "usage: wp [address length "
2850 "[(r|w|a) [value [mask]]]]");
2851 return ERROR_COMMAND_SYNTAX_ERROR;
2854 int retval = watchpoint_add(target, addr, length, type,
2855 data_value, data_mask);
2856 if (ERROR_OK != retval)
2857 LOG_ERROR("Failure setting watchpoints");
2862 COMMAND_HANDLER(handle_rwp_command)
2865 return ERROR_COMMAND_SYNTAX_ERROR;
2868 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2870 struct target *target = get_current_target(cmd_ctx);
2871 watchpoint_remove(target, addr);
2878 * Translate a virtual address to a physical address.
2880 * The low-level target implementation must have logged a detailed error
2881 * which is forwarded to telnet/GDB session.
2883 COMMAND_HANDLER(handle_virt2phys_command)
2886 return ERROR_COMMAND_SYNTAX_ERROR;
2889 COMMAND_PARSE_NUMBER(u32, args[0], va);
2892 struct target *target = get_current_target(cmd_ctx);
2893 int retval = target->type->virt2phys(target, va, &pa);
2894 if (retval == ERROR_OK)
2895 command_print(cmd_ctx, "Physical address 0x%08" PRIx32 "", pa);
2900 static void writeData(FILE *f, const void *data, size_t len)
2902 size_t written = fwrite(data, 1, len, f);
2904 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
2907 static void writeLong(FILE *f, int l)
2910 for (i = 0; i < 4; i++)
2912 char c = (l >> (i*8))&0xff;
2913 writeData(f, &c, 1);
2918 static void writeString(FILE *f, char *s)
2920 writeData(f, s, strlen(s));
2923 /* Dump a gmon.out histogram file. */
2924 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
2927 FILE *f = fopen(filename, "w");
2930 writeString(f, "gmon");
2931 writeLong(f, 0x00000001); /* Version */
2932 writeLong(f, 0); /* padding */
2933 writeLong(f, 0); /* padding */
2934 writeLong(f, 0); /* padding */
2936 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
2937 writeData(f, &zero, 1);
2939 /* figure out bucket size */
2940 uint32_t min = samples[0];
2941 uint32_t max = samples[0];
2942 for (i = 0; i < sampleNum; i++)
2944 if (min > samples[i])
2948 if (max < samples[i])
2954 int addressSpace = (max-min + 1);
2956 static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
2957 uint32_t length = addressSpace;
2958 if (length > maxBuckets)
2960 length = maxBuckets;
2962 int *buckets = malloc(sizeof(int)*length);
2963 if (buckets == NULL)
2968 memset(buckets, 0, sizeof(int)*length);
2969 for (i = 0; i < sampleNum;i++)
2971 uint32_t address = samples[i];
2972 long long a = address-min;
2973 long long b = length-1;
2974 long long c = addressSpace-1;
2975 int index = (a*b)/c; /* danger!!!! int32 overflows */
2979 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
2980 writeLong(f, min); /* low_pc */
2981 writeLong(f, max); /* high_pc */
2982 writeLong(f, length); /* # of samples */
2983 writeLong(f, 64000000); /* 64MHz */
2984 writeString(f, "seconds");
2985 for (i = 0; i < (15-strlen("seconds")); i++)
2986 writeData(f, &zero, 1);
2987 writeString(f, "s");
2989 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
2991 char *data = malloc(2*length);
2994 for (i = 0; i < length;i++)
3003 data[i*2 + 1]=(val >> 8)&0xff;
3006 writeData(f, data, length * 2);
3016 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
3017 COMMAND_HANDLER(handle_profile_command)
3019 struct target *target = get_current_target(cmd_ctx);
3020 struct timeval timeout, now;
3022 gettimeofday(&timeout, NULL);
3025 return ERROR_COMMAND_SYNTAX_ERROR;
3028 COMMAND_PARSE_NUMBER(uint, args[0], offset);
3030 timeval_add_time(&timeout, offset, 0);
3032 command_print(cmd_ctx, "Starting profiling. Halting and resuming the target as often as we can...");
3034 static const int maxSample = 10000;
3035 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3036 if (samples == NULL)
3040 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3041 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3046 target_poll(target);
3047 if (target->state == TARGET_HALTED)
3049 uint32_t t=*((uint32_t *)reg->value);
3050 samples[numSamples++]=t;
3051 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3052 target_poll(target);
3053 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3054 } else if (target->state == TARGET_RUNNING)
3056 /* We want to quickly sample the PC. */
3057 if ((retval = target_halt(target)) != ERROR_OK)
3064 command_print(cmd_ctx, "Target not halted or running");
3068 if (retval != ERROR_OK)
3073 gettimeofday(&now, NULL);
3074 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3076 command_print(cmd_ctx, "Profiling completed. %d samples.", numSamples);
3077 if ((retval = target_poll(target)) != ERROR_OK)
3082 if (target->state == TARGET_HALTED)
3084 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3086 if ((retval = target_poll(target)) != ERROR_OK)
3091 writeGmon(samples, numSamples, args[1]);
3092 command_print(cmd_ctx, "Wrote %s", args[1]);
3101 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3104 Jim_Obj *nameObjPtr, *valObjPtr;
3107 namebuf = alloc_printf("%s(%d)", varname, idx);
3111 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3112 valObjPtr = Jim_NewIntObj(interp, val);
3113 if (!nameObjPtr || !valObjPtr)
3119 Jim_IncrRefCount(nameObjPtr);
3120 Jim_IncrRefCount(valObjPtr);
3121 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3122 Jim_DecrRefCount(interp, nameObjPtr);
3123 Jim_DecrRefCount(interp, valObjPtr);
3125 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3129 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3131 struct command_context *context;
3132 struct target *target;
3134 context = Jim_GetAssocData(interp, "context");
3135 if (context == NULL)
3137 LOG_ERROR("mem2array: no command context");
3140 target = get_current_target(context);
3143 LOG_ERROR("mem2array: no current target");
3147 return target_mem2array(interp, target, argc-1, argv + 1);
3150 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3158 const char *varname;
3159 uint8_t buffer[4096];
3163 /* argv[1] = name of array to receive the data
3164 * argv[2] = desired width
3165 * argv[3] = memory address
3166 * argv[4] = count of times to read
3169 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3172 varname = Jim_GetString(argv[0], &len);
3173 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3175 e = Jim_GetLong(interp, argv[1], &l);
3181 e = Jim_GetLong(interp, argv[2], &l);
3186 e = Jim_GetLong(interp, argv[3], &l);
3202 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3203 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3207 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3208 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3211 if ((addr + (len * width)) < addr) {
3212 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3213 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3216 /* absurd transfer size? */
3218 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3219 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3224 ((width == 2) && ((addr & 1) == 0)) ||
3225 ((width == 4) && ((addr & 3) == 0))) {
3229 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3230 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3233 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3244 /* Slurp... in buffer size chunks */
3246 count = len; /* in objects.. */
3247 if (count > (sizeof(buffer)/width)) {
3248 count = (sizeof(buffer)/width);
3251 retval = target_read_memory(target, addr, width, count, buffer);
3252 if (retval != ERROR_OK) {
3254 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3258 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3259 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3263 v = 0; /* shut up gcc */
3264 for (i = 0 ;i < count ;i++, n++) {
3267 v = target_buffer_get_u32(target, &buffer[i*width]);
3270 v = target_buffer_get_u16(target, &buffer[i*width]);
3273 v = buffer[i] & 0x0ff;
3276 new_int_array_element(interp, varname, n, v);
3282 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3287 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3290 Jim_Obj *nameObjPtr, *valObjPtr;
3294 namebuf = alloc_printf("%s(%d)", varname, idx);
3298 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3305 Jim_IncrRefCount(nameObjPtr);
3306 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3307 Jim_DecrRefCount(interp, nameObjPtr);
3309 if (valObjPtr == NULL)
3312 result = Jim_GetLong(interp, valObjPtr, &l);
3313 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3318 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3320 struct command_context *context;
3321 struct target *target;
3323 context = Jim_GetAssocData(interp, "context");
3324 if (context == NULL) {
3325 LOG_ERROR("array2mem: no command context");
3328 target = get_current_target(context);
3329 if (target == NULL) {
3330 LOG_ERROR("array2mem: no current target");
3334 return target_array2mem(interp,target, argc-1, argv + 1);
3336 static int target_array2mem(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3344 const char *varname;
3345 uint8_t buffer[4096];
3349 /* argv[1] = name of array to get the data
3350 * argv[2] = desired width
3351 * argv[3] = memory address
3352 * argv[4] = count to write
3355 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3358 varname = Jim_GetString(argv[0], &len);
3359 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3361 e = Jim_GetLong(interp, argv[1], &l);
3367 e = Jim_GetLong(interp, argv[2], &l);
3372 e = Jim_GetLong(interp, argv[3], &l);
3388 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3389 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3393 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3394 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3397 if ((addr + (len * width)) < addr) {
3398 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3399 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3402 /* absurd transfer size? */
3404 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3405 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3410 ((width == 2) && ((addr & 1) == 0)) ||
3411 ((width == 4) && ((addr & 3) == 0))) {
3415 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3416 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3419 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3430 /* Slurp... in buffer size chunks */
3432 count = len; /* in objects.. */
3433 if (count > (sizeof(buffer)/width)) {
3434 count = (sizeof(buffer)/width);
3437 v = 0; /* shut up gcc */
3438 for (i = 0 ;i < count ;i++, n++) {
3439 get_int_array_element(interp, varname, n, &v);
3442 target_buffer_set_u32(target, &buffer[i*width], v);
3445 target_buffer_set_u16(target, &buffer[i*width], v);
3448 buffer[i] = v & 0x0ff;
3454 retval = target_write_memory(target, addr, width, count, buffer);
3455 if (retval != ERROR_OK) {
3457 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3461 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3462 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3468 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3473 void target_all_handle_event(enum target_event e)
3475 struct target *target;
3477 LOG_DEBUG("**all*targets: event: %d, %s",
3479 Jim_Nvp_value2name_simple(nvp_target_event, e)->name);
3481 target = all_targets;
3483 target_handle_event(target, e);
3484 target = target->next;
3489 /* FIX? should we propagate errors here rather than printing them
3492 void target_handle_event(struct target *target, enum target_event e)
3494 struct target_event_action *teap;
3496 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3497 if (teap->event == e) {
3498 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3499 target->target_number,
3501 target_get_name(target),
3503 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3504 Jim_GetString(teap->body, NULL));
3505 if (Jim_EvalObj(interp, teap->body) != JIM_OK)
3507 Jim_PrintErrorMessage(interp);
3513 enum target_cfg_param {
3516 TCFG_WORK_AREA_VIRT,
3517 TCFG_WORK_AREA_PHYS,
3518 TCFG_WORK_AREA_SIZE,
3519 TCFG_WORK_AREA_BACKUP,
3522 TCFG_CHAIN_POSITION,
3525 static Jim_Nvp nvp_config_opts[] = {
3526 { .name = "-type", .value = TCFG_TYPE },
3527 { .name = "-event", .value = TCFG_EVENT },
3528 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3529 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3530 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3531 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3532 { .name = "-endian" , .value = TCFG_ENDIAN },
3533 { .name = "-variant", .value = TCFG_VARIANT },
3534 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3536 { .name = NULL, .value = -1 }
3539 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3547 /* parse config or cget options ... */
3548 while (goi->argc > 0) {
3549 Jim_SetEmptyResult(goi->interp);
3550 /* Jim_GetOpt_Debug(goi); */
3552 if (target->type->target_jim_configure) {
3553 /* target defines a configure function */
3554 /* target gets first dibs on parameters */
3555 e = (*(target->type->target_jim_configure))(target, goi);
3564 /* otherwise we 'continue' below */
3566 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3568 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3574 if (goi->isconfigure) {
3575 Jim_SetResult_sprintf(goi->interp, "not setable: %s", n->name);
3579 if (goi->argc != 0) {
3580 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "NO PARAMS");
3584 Jim_SetResultString(goi->interp, target_get_name(target), -1);
3588 if (goi->argc == 0) {
3589 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3593 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3595 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3599 if (goi->isconfigure) {
3600 if (goi->argc != 1) {
3601 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3605 if (goi->argc != 0) {
3606 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3612 struct target_event_action *teap;
3614 teap = target->event_action;
3615 /* replace existing? */
3617 if (teap->event == (enum target_event)n->value) {
3623 if (goi->isconfigure) {
3624 bool replace = true;
3627 teap = calloc(1, sizeof(*teap));
3630 teap->event = n->value;
3631 Jim_GetOpt_Obj(goi, &o);
3633 Jim_DecrRefCount(interp, teap->body);
3635 teap->body = Jim_DuplicateObj(goi->interp, o);
3638 * Tcl/TK - "tk events" have a nice feature.
3639 * See the "BIND" command.
3640 * We should support that here.
3641 * You can specify %X and %Y in the event code.
3642 * The idea is: %T - target name.
3643 * The idea is: %N - target number
3644 * The idea is: %E - event name.
3646 Jim_IncrRefCount(teap->body);
3650 /* add to head of event list */
3651 teap->next = target->event_action;
3652 target->event_action = teap;
3654 Jim_SetEmptyResult(goi->interp);
3658 Jim_SetEmptyResult(goi->interp);
3660 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3667 case TCFG_WORK_AREA_VIRT:
3668 if (goi->isconfigure) {
3669 target_free_all_working_areas(target);
3670 e = Jim_GetOpt_Wide(goi, &w);
3674 target->working_area_virt = w;
3675 target->working_area_virt_spec = true;
3677 if (goi->argc != 0) {
3681 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3685 case TCFG_WORK_AREA_PHYS:
3686 if (goi->isconfigure) {
3687 target_free_all_working_areas(target);
3688 e = Jim_GetOpt_Wide(goi, &w);
3692 target->working_area_phys = w;
3693 target->working_area_phys_spec = true;
3695 if (goi->argc != 0) {
3699 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3703 case TCFG_WORK_AREA_SIZE:
3704 if (goi->isconfigure) {
3705 target_free_all_working_areas(target);
3706 e = Jim_GetOpt_Wide(goi, &w);
3710 target->working_area_size = w;
3712 if (goi->argc != 0) {
3716 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3720 case TCFG_WORK_AREA_BACKUP:
3721 if (goi->isconfigure) {
3722 target_free_all_working_areas(target);
3723 e = Jim_GetOpt_Wide(goi, &w);
3727 /* make this exactly 1 or 0 */
3728 target->backup_working_area = (!!w);
3730 if (goi->argc != 0) {
3734 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3735 /* loop for more e*/
3739 if (goi->isconfigure) {
3740 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3742 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3745 target->endianness = n->value;
3747 if (goi->argc != 0) {
3751 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3752 if (n->name == NULL) {
3753 target->endianness = TARGET_LITTLE_ENDIAN;
3754 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3756 Jim_SetResultString(goi->interp, n->name, -1);
3761 if (goi->isconfigure) {
3762 if (goi->argc < 1) {
3763 Jim_SetResult_sprintf(goi->interp,
3768 if (target->variant) {
3769 free((void *)(target->variant));
3771 e = Jim_GetOpt_String(goi, &cp, NULL);
3772 target->variant = strdup(cp);
3774 if (goi->argc != 0) {
3778 Jim_SetResultString(goi->interp, target->variant,-1);
3781 case TCFG_CHAIN_POSITION:
3782 if (goi->isconfigure) {
3784 struct jtag_tap *tap;
3785 target_free_all_working_areas(target);
3786 e = Jim_GetOpt_Obj(goi, &o);
3790 tap = jtag_tap_by_jim_obj(goi->interp, o);
3794 /* make this exactly 1 or 0 */
3797 if (goi->argc != 0) {
3801 Jim_SetResultString(interp, target->tap->dotted_name, -1);
3802 /* loop for more e*/
3805 } /* while (goi->argc) */
3808 /* done - we return */
3812 /** this is the 'tcl' handler for the target specific command */
3813 static int tcl_target_func(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3818 uint8_t target_buf[32];
3820 struct target *target;
3821 struct command_context *cmd_ctx;
3828 TS_CMD_MWW, TS_CMD_MWH, TS_CMD_MWB,
3829 TS_CMD_MDW, TS_CMD_MDH, TS_CMD_MDB,
3830 TS_CMD_MRW, TS_CMD_MRH, TS_CMD_MRB,
3831 TS_CMD_MEM2ARRAY, TS_CMD_ARRAY2MEM,
3839 TS_CMD_INVOKE_EVENT,
3842 static const Jim_Nvp target_options[] = {
3843 { .name = "configure", .value = TS_CMD_CONFIGURE },
3844 { .name = "cget", .value = TS_CMD_CGET },
3845 { .name = "mww", .value = TS_CMD_MWW },
3846 { .name = "mwh", .value = TS_CMD_MWH },
3847 { .name = "mwb", .value = TS_CMD_MWB },
3848 { .name = "mdw", .value = TS_CMD_MDW },
3849 { .name = "mdh", .value = TS_CMD_MDH },
3850 { .name = "mdb", .value = TS_CMD_MDB },
3851 { .name = "mem2array", .value = TS_CMD_MEM2ARRAY },
3852 { .name = "array2mem", .value = TS_CMD_ARRAY2MEM },
3853 { .name = "eventlist", .value = TS_CMD_EVENTLIST },
3854 { .name = "curstate", .value = TS_CMD_CURSTATE },
3856 { .name = "arp_examine", .value = TS_CMD_EXAMINE },
3857 { .name = "arp_poll", .value = TS_CMD_POLL },
3858 { .name = "arp_reset", .value = TS_CMD_RESET },
3859 { .name = "arp_halt", .value = TS_CMD_HALT },
3860 { .name = "arp_waitstate", .value = TS_CMD_WAITSTATE },
3861 { .name = "invoke-event", .value = TS_CMD_INVOKE_EVENT },
3863 { .name = NULL, .value = -1 },
3866 /* go past the "command" */
3867 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
3869 target = Jim_CmdPrivData(goi.interp);
3870 cmd_ctx = Jim_GetAssocData(goi.interp, "context");
3872 /* commands here are in an NVP table */
3873 e = Jim_GetOpt_Nvp(&goi, target_options, &n);
3875 Jim_GetOpt_NvpUnknown(&goi, target_options, 0);
3878 /* Assume blank result */
3879 Jim_SetEmptyResult(goi.interp);
3882 case TS_CMD_CONFIGURE:
3884 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "missing: -option VALUE ...");
3887 goi.isconfigure = 1;
3888 return target_configure(&goi, target);
3890 // some things take params
3892 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "missing: ?-option?");
3895 goi.isconfigure = 0;
3896 return target_configure(&goi, target);
3904 * argv[3] = optional count.
3907 if ((goi.argc == 2) || (goi.argc == 3)) {
3911 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR DATA [COUNT]", n->name);
3915 e = Jim_GetOpt_Wide(&goi, &a);
3920 e = Jim_GetOpt_Wide(&goi, &b);
3924 if (goi.argc == 3) {
3925 e = Jim_GetOpt_Wide(&goi, &c);
3935 target_buffer_set_u32(target, target_buf, b);
3939 target_buffer_set_u16(target, target_buf, b);
3943 target_buffer_set_u8(target, target_buf, b);
3947 for (x = 0 ; x < c ; x++) {
3948 e = target_write_memory(target, a, b, 1, target_buf);
3949 if (e != ERROR_OK) {
3950 Jim_SetResult_sprintf(interp, "Error writing @ 0x%08x: %d\n", (int)(a), e);
3963 /* argv[0] = command
3965 * argv[2] = optional count
3967 if ((goi.argc == 2) || (goi.argc == 3)) {
3968 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR [COUNT]", n->name);
3971 e = Jim_GetOpt_Wide(&goi, &a);
3976 e = Jim_GetOpt_Wide(&goi, &c);
3983 b = 1; /* shut up gcc */
3996 /* convert to "bytes" */
3998 /* count is now in 'BYTES' */
4004 e = target_read_memory(target, a, b, y / b, target_buf);
4005 if (e != ERROR_OK) {
4006 Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
4010 Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
4013 for (x = 0 ; (x < 16) && (x < y) ; x += 4) {
4014 z = target_buffer_get_u32(target, &(target_buf[ x * 4 ]));
4015 Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
4017 for (; (x < 16) ; x += 4) {
4018 Jim_fprintf(interp, interp->cookie_stdout, " ");
4022 for (x = 0 ; (x < 16) && (x < y) ; x += 2) {
4023 z = target_buffer_get_u16(target, &(target_buf[ x * 2 ]));
4024 Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
4026 for (; (x < 16) ; x += 2) {
4027 Jim_fprintf(interp, interp->cookie_stdout, " ");
4032 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4033 z = target_buffer_get_u8(target, &(target_buf[ x * 4 ]));
4034 Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
4036 for (; (x < 16) ; x += 1) {
4037 Jim_fprintf(interp, interp->cookie_stdout, " ");
4041 /* ascii-ify the bytes */
4042 for (x = 0 ; x < y ; x++) {
4043 if ((target_buf[x] >= 0x20) &&
4044 (target_buf[x] <= 0x7e)) {
4048 target_buf[x] = '.';
4053 target_buf[x] = ' ';
4058 /* print - with a newline */
4059 Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
4065 case TS_CMD_MEM2ARRAY:
4066 return target_mem2array(goi.interp, target, goi.argc, goi.argv);
4068 case TS_CMD_ARRAY2MEM:
4069 return target_array2mem(goi.interp, target, goi.argc, goi.argv);
4071 case TS_CMD_EXAMINE:
4073 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4076 if (!target->tap->enabled)
4077 goto err_tap_disabled;
4078 e = target->type->examine(target);
4079 if (e != ERROR_OK) {
4080 Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
4086 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4089 if (!target->tap->enabled)
4090 goto err_tap_disabled;
4091 if (!(target_was_examined(target))) {
4092 e = ERROR_TARGET_NOT_EXAMINED;
4094 e = target->type->poll(target);
4096 if (e != ERROR_OK) {
4097 Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4104 if (goi.argc != 2) {
4105 Jim_WrongNumArgs(interp, 2, argv,
4106 "([tT]|[fF]|assert|deassert) BOOL");
4109 e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4111 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4114 /* the halt or not param */
4115 e = Jim_GetOpt_Wide(&goi, &a);
4119 if (!target->tap->enabled)
4120 goto err_tap_disabled;
4121 if (!target->type->assert_reset
4122 || !target->type->deassert_reset) {
4123 Jim_SetResult_sprintf(interp,
4124 "No target-specific reset for %s",
4128 /* determine if we should halt or not. */
4129 target->reset_halt = !!a;
4130 /* When this happens - all workareas are invalid. */
4131 target_free_all_working_areas_restore(target, 0);
4134 if (n->value == NVP_ASSERT) {
4135 e = target->type->assert_reset(target);
4137 e = target->type->deassert_reset(target);
4139 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4142 Jim_WrongNumArgs(goi.interp, 0, argv, "halt [no parameters]");
4145 if (!target->tap->enabled)
4146 goto err_tap_disabled;
4147 e = target->type->halt(target);
4148 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4149 case TS_CMD_WAITSTATE:
4150 /* params: <name> statename timeoutmsecs */
4151 if (goi.argc != 2) {
4152 Jim_SetResult_sprintf(goi.interp, "%s STATENAME TIMEOUTMSECS", n->name);
4155 e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4157 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4160 e = Jim_GetOpt_Wide(&goi, &a);
4164 if (!target->tap->enabled)
4165 goto err_tap_disabled;
4166 e = target_wait_state(target, n->value, a);
4167 if (e != ERROR_OK) {
4168 Jim_SetResult_sprintf(goi.interp,
4169 "target: %s wait %s fails (%d) %s",
4172 e, target_strerror_safe(e));
4177 case TS_CMD_EVENTLIST:
4178 /* List for human, Events defined for this target.
4179 * scripts/programs should use 'name cget -event NAME'
4182 struct target_event_action *teap;
4183 teap = target->event_action;
4184 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4185 target->target_number,
4187 command_print(cmd_ctx, "%-25s | Body", "Event");
4188 command_print(cmd_ctx, "------------------------- | ----------------------------------------");
4190 command_print(cmd_ctx,
4192 Jim_Nvp_value2name_simple(nvp_target_event, teap->event)->name,
4193 Jim_GetString(teap->body, NULL));
4196 command_print(cmd_ctx, "***END***");
4199 case TS_CMD_CURSTATE:
4200 if (goi.argc != 0) {
4201 Jim_WrongNumArgs(goi.interp, 0, argv, "[no parameters]");
4204 Jim_SetResultString(goi.interp,
4205 target_state_name( target ),
4208 case TS_CMD_INVOKE_EVENT:
4209 if (goi.argc != 1) {
4210 Jim_SetResult_sprintf(goi.interp, "%s ?EVENTNAME?",n->name);
4213 e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4215 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4218 target_handle_event(target, n->value);
4224 Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4228 static int target_create(Jim_GetOptInfo *goi)
4236 struct target *target;
4237 struct command_context *cmd_ctx;
4239 cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4240 if (goi->argc < 3) {
4241 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4246 Jim_GetOpt_Obj(goi, &new_cmd);
4247 /* does this command exist? */
4248 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4250 cp = Jim_GetString(new_cmd, NULL);
4251 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4256 e = Jim_GetOpt_String(goi, &cp2, NULL);
4258 /* now does target type exist */
4259 for (x = 0 ; target_types[x] ; x++) {
4260 if (0 == strcmp(cp, target_types[x]->name)) {
4265 if (target_types[x] == NULL) {
4266 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4267 for (x = 0 ; target_types[x] ; x++) {
4268 if (target_types[x + 1]) {
4269 Jim_AppendStrings(goi->interp,
4270 Jim_GetResult(goi->interp),
4271 target_types[x]->name,
4274 Jim_AppendStrings(goi->interp,
4275 Jim_GetResult(goi->interp),
4277 target_types[x]->name,NULL);
4284 target = calloc(1,sizeof(struct target));
4285 /* set target number */
4286 target->target_number = new_target_number();
4288 /* allocate memory for each unique target type */
4289 target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4291 memcpy(target->type, target_types[x], sizeof(struct target_type));
4293 /* will be set by "-endian" */
4294 target->endianness = TARGET_ENDIAN_UNKNOWN;
4296 target->working_area = 0x0;
4297 target->working_area_size = 0x0;
4298 target->working_areas = NULL;
4299 target->backup_working_area = 0;
4301 target->state = TARGET_UNKNOWN;
4302 target->debug_reason = DBG_REASON_UNDEFINED;
4303 target->reg_cache = NULL;
4304 target->breakpoints = NULL;
4305 target->watchpoints = NULL;
4306 target->next = NULL;
4307 target->arch_info = NULL;
4309 target->display = 1;
4311 target->halt_issued = false;
4313 /* initialize trace information */
4314 target->trace_info = malloc(sizeof(struct trace));
4315 target->trace_info->num_trace_points = 0;
4316 target->trace_info->trace_points_size = 0;
4317 target->trace_info->trace_points = NULL;
4318 target->trace_info->trace_history_size = 0;
4319 target->trace_info->trace_history = NULL;
4320 target->trace_info->trace_history_pos = 0;
4321 target->trace_info->trace_history_overflowed = 0;
4323 target->dbgmsg = NULL;
4324 target->dbg_msg_enabled = 0;
4326 target->endianness = TARGET_ENDIAN_UNKNOWN;
4328 /* Do the rest as "configure" options */
4329 goi->isconfigure = 1;
4330 e = target_configure(goi, target);
4332 if (target->tap == NULL)
4334 Jim_SetResultString(interp, "-chain-position required when creating target", -1);
4344 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4345 /* default endian to little if not specified */
4346 target->endianness = TARGET_LITTLE_ENDIAN;
4349 /* incase variant is not set */
4350 if (!target->variant)
4351 target->variant = strdup("");
4353 /* create the target specific commands */
4354 if (target->type->register_commands) {
4355 (*(target->type->register_commands))(cmd_ctx);
4357 if (target->type->target_create) {
4358 (*(target->type->target_create))(target, goi->interp);
4361 /* append to end of list */
4363 struct target **tpp;
4364 tpp = &(all_targets);
4366 tpp = &((*tpp)->next);
4371 cp = Jim_GetString(new_cmd, NULL);
4372 target->cmd_name = strdup(cp);
4374 /* now - create the new target name command */
4375 e = Jim_CreateCommand(goi->interp,
4378 tcl_target_func, /* C function */
4379 target, /* private data */
4380 NULL); /* no del proc */
4385 static int jim_target(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4389 struct command_context *cmd_ctx;
4390 struct target *target;
4393 /* TG = target generic */
4401 const char *target_cmds[] = {
4402 "create", "types", "names", "current", "number",
4404 NULL /* terminate */
4407 LOG_DEBUG("Target command params:");
4408 LOG_DEBUG("%s", Jim_Debug_ArgvString(interp, argc, argv));
4410 cmd_ctx = Jim_GetAssocData(interp, "context");
4412 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
4414 if (goi.argc == 0) {
4415 Jim_WrongNumArgs(interp, 1, argv, "missing: command ...");
4419 /* Jim_GetOpt_Debug(&goi); */
4420 r = Jim_GetOpt_Enum(&goi, target_cmds, &x);
4427 Jim_Panic(goi.interp,"Why am I here?");
4429 case TG_CMD_CURRENT:
4430 if (goi.argc != 0) {
4431 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4434 Jim_SetResultString(goi.interp, get_current_target(cmd_ctx)->cmd_name, -1);
4437 if (goi.argc != 0) {
4438 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4441 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4442 for (x = 0 ; target_types[x] ; x++) {
4443 Jim_ListAppendElement(goi.interp,
4444 Jim_GetResult(goi.interp),
4445 Jim_NewStringObj(goi.interp, target_types[x]->name, -1));
4449 if (goi.argc != 0) {
4450 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4453 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4454 target = all_targets;
4456 Jim_ListAppendElement(goi.interp,
4457 Jim_GetResult(goi.interp),
4458 Jim_NewStringObj(goi.interp, target->cmd_name, -1));
4459 target = target->next;
4464 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "?name ... config options ...");
4467 return target_create(&goi);
4470 /* It's OK to remove this mechanism sometime after August 2010 or so */
4471 LOG_WARNING("don't use numbers as target identifiers; use names");
4472 if (goi.argc != 1) {
4473 Jim_SetResult_sprintf(goi.interp, "expected: target number ?NUMBER?");
4476 e = Jim_GetOpt_Wide(&goi, &w);
4480 for (x = 0, target = all_targets; target; target = target->next, x++) {
4481 if (target->target_number == w)
4484 if (target == NULL) {
4485 Jim_SetResult_sprintf(goi.interp,
4486 "Target: number %d does not exist", (int)(w));
4489 Jim_SetResultString(goi.interp, target->cmd_name, -1);
4492 if (goi.argc != 0) {
4493 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "<no parameters>");
4496 for (x = 0, target = all_targets; target; target = target->next, x++)
4498 Jim_SetResult(goi.interp, Jim_NewIntObj(goi.interp, x));
4514 static int fastload_num;
4515 static struct FastLoad *fastload;
4517 static void free_fastload(void)
4519 if (fastload != NULL)
4522 for (i = 0; i < fastload_num; i++)
4524 if (fastload[i].data)
4525 free(fastload[i].data);
4535 COMMAND_HANDLER(handle_fast_load_image_command)
4539 uint32_t image_size;
4540 uint32_t min_address = 0;
4541 uint32_t max_address = 0xffffffff;
4546 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_args,
4547 &image, &min_address, &max_address);
4548 if (ERROR_OK != retval)
4551 struct duration bench;
4552 duration_start(&bench);
4554 if (image_open(&image, args[0], (CMD_ARGC >= 3) ? args[2] : NULL) != ERROR_OK)
4561 fastload_num = image.num_sections;
4562 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4563 if (fastload == NULL)
4565 image_close(&image);
4568 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4569 for (i = 0; i < image.num_sections; i++)
4571 buffer = malloc(image.sections[i].size);
4574 command_print(cmd_ctx, "error allocating buffer for section (%d bytes)",
4575 (int)(image.sections[i].size));
4579 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4585 uint32_t offset = 0;
4586 uint32_t length = buf_cnt;
4589 /* DANGER!!! beware of unsigned comparision here!!! */
4591 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4592 (image.sections[i].base_address < max_address))
4594 if (image.sections[i].base_address < min_address)
4596 /* clip addresses below */
4597 offset += min_address-image.sections[i].base_address;
4601 if (image.sections[i].base_address + buf_cnt > max_address)
4603 length -= (image.sections[i].base_address + buf_cnt)-max_address;
4606 fastload[i].address = image.sections[i].base_address + offset;
4607 fastload[i].data = malloc(length);
4608 if (fastload[i].data == NULL)
4613 memcpy(fastload[i].data, buffer + offset, length);
4614 fastload[i].length = length;
4616 image_size += length;
4617 command_print(cmd_ctx, "%u bytes written at address 0x%8.8x",
4618 (unsigned int)length,
4619 ((unsigned int)(image.sections[i].base_address + offset)));
4625 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
4627 command_print(cmd_ctx, "Loaded %" PRIu32 " bytes "
4628 "in %fs (%0.3f kb/s)", image_size,
4629 duration_elapsed(&bench), duration_kbps(&bench, image_size));
4631 command_print(cmd_ctx,
4632 "WARNING: image has not been loaded to target!"
4633 "You can issue a 'fast_load' to finish loading.");
4636 image_close(&image);
4638 if (retval != ERROR_OK)
4646 COMMAND_HANDLER(handle_fast_load_command)
4649 return ERROR_COMMAND_SYNTAX_ERROR;
4650 if (fastload == NULL)
4652 LOG_ERROR("No image in memory");
4656 int ms = timeval_ms();
4658 int retval = ERROR_OK;
4659 for (i = 0; i < fastload_num;i++)
4661 struct target *target = get_current_target(cmd_ctx);
4662 command_print(cmd_ctx, "Write to 0x%08x, length 0x%08x",
4663 (unsigned int)(fastload[i].address),
4664 (unsigned int)(fastload[i].length));
4665 if (retval == ERROR_OK)
4667 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
4669 size += fastload[i].length;
4671 int after = timeval_ms();
4672 command_print(cmd_ctx, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
4676 static int jim_mcrmrc(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4678 struct command_context *context;
4679 struct target *target;
4682 context = Jim_GetAssocData(interp, "context");
4683 if (context == NULL) {
4684 LOG_ERROR("array2mem: no command context");
4687 target = get_current_target(context);
4688 if (target == NULL) {
4689 LOG_ERROR("array2mem: no current target");
4693 if ((argc < 6) || (argc > 7))
4707 e = Jim_GetLong(interp, argv[1], &l);
4713 e = Jim_GetLong(interp, argv[2], &l);
4719 e = Jim_GetLong(interp, argv[3], &l);
4725 e = Jim_GetLong(interp, argv[4], &l);
4731 e = Jim_GetLong(interp, argv[5], &l);
4741 e = Jim_GetLong(interp, argv[6], &l);
4747 retval = target_mcr(target, cpnum, op1, op2, CRn, CRm, value);
4748 if (retval != ERROR_OK)
4752 retval = target_mrc(target, cpnum, op1, op2, CRn, CRm, &value);
4753 if (retval != ERROR_OK)
4756 Jim_SetResult(interp, Jim_NewIntObj(interp, value));
4762 int target_register_commands(struct command_context *cmd_ctx)
4765 register_command(cmd_ctx, NULL, "targets",
4766 handle_targets_command, COMMAND_EXEC,
4767 "change current command line target (one parameter) "
4768 "or list targets (no parameters)");
4770 register_jim(cmd_ctx, "target", jim_target, "configure target");
4775 int target_register_user_commands(struct command_context *cmd_ctx)
4777 int retval = ERROR_OK;
4778 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
4781 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
4784 register_command(cmd_ctx, NULL, "profile",
4785 handle_profile_command, COMMAND_EXEC,
4786 "profiling samples the CPU PC");
4788 register_jim(cmd_ctx, "ocd_mem2array", jim_mem2array,
4789 "read memory and return as a TCL array for script processing "
4790 "<ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
4792 register_jim(cmd_ctx, "ocd_array2mem", jim_array2mem,
4793 "convert a TCL array to memory locations and write the values "
4794 "<ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
4796 register_command(cmd_ctx, NULL, "fast_load_image",
4797 handle_fast_load_image_command, COMMAND_ANY,
4798 "same args as load_image, image stored in memory "
4799 "- mainly for profiling purposes");
4801 register_command(cmd_ctx, NULL, "fast_load",
4802 handle_fast_load_command, COMMAND_ANY,
4803 "loads active fast load image to current target "
4804 "- mainly for profiling purposes");
4806 /** @todo don't register virt2phys() unless target supports it */
4807 register_command(cmd_ctx, NULL, "virt2phys",
4808 handle_virt2phys_command, COMMAND_ANY,
4809 "translate a virtual address into a physical address");
4811 register_command(cmd_ctx, NULL, "reg",
4812 handle_reg_command, COMMAND_EXEC,
4813 "display or set a register");
4815 register_command(cmd_ctx, NULL, "poll",
4816 handle_poll_command, COMMAND_EXEC,
4817 "poll target state");
4818 register_command(cmd_ctx, NULL, "wait_halt",
4819 handle_wait_halt_command, COMMAND_EXEC,
4820 "wait for target halt [time (s)]");
4821 register_command(cmd_ctx, NULL, "halt",
4822 handle_halt_command, COMMAND_EXEC,
4824 register_command(cmd_ctx, NULL, "resume",
4825 handle_resume_command, COMMAND_EXEC,
4826 "resume target [addr]");
4827 register_command(cmd_ctx, NULL, "reset",
4828 handle_reset_command, COMMAND_EXEC,
4829 "reset target [run | halt | init] - default is run");
4830 register_command(cmd_ctx, NULL, "soft_reset_halt",
4831 handle_soft_reset_halt_command, COMMAND_EXEC,
4832 "halt the target and do a soft reset");
4834 register_command(cmd_ctx, NULL, "step",
4835 handle_step_command, COMMAND_EXEC,
4836 "step one instruction from current PC or [addr]");
4838 register_command(cmd_ctx, NULL, "mdw",
4839 handle_md_command, COMMAND_EXEC,
4840 "display memory words [phys] <addr> [count]");
4841 register_command(cmd_ctx, NULL, "mdh",
4842 handle_md_command, COMMAND_EXEC,
4843 "display memory half-words [phys] <addr> [count]");
4844 register_command(cmd_ctx, NULL, "mdb",
4845 handle_md_command, COMMAND_EXEC,
4846 "display memory bytes [phys] <addr> [count]");
4848 register_command(cmd_ctx, NULL, "mww",
4849 handle_mw_command, COMMAND_EXEC,
4850 "write memory word [phys] <addr> <value> [count]");
4851 register_command(cmd_ctx, NULL, "mwh",
4852 handle_mw_command, COMMAND_EXEC,
4853 "write memory half-word [phys] <addr> <value> [count]");
4854 register_command(cmd_ctx, NULL, "mwb",
4855 handle_mw_command, COMMAND_EXEC,
4856 "write memory byte [phys] <addr> <value> [count]");
4858 register_command(cmd_ctx, NULL, "bp",
4859 handle_bp_command, COMMAND_EXEC,
4860 "list or set breakpoint [<address> <length> [hw]]");
4861 register_command(cmd_ctx, NULL, "rbp",
4862 handle_rbp_command, COMMAND_EXEC,
4863 "remove breakpoint <address>");
4865 register_command(cmd_ctx, NULL, "wp",
4866 handle_wp_command, COMMAND_EXEC,
4867 "list or set watchpoint "
4868 "[<address> <length> <r/w/a> [value] [mask]]");
4869 register_command(cmd_ctx, NULL, "rwp",
4870 handle_rwp_command, COMMAND_EXEC,
4871 "remove watchpoint <address>");
4873 register_command(cmd_ctx, NULL, "load_image",
4874 handle_load_image_command, COMMAND_EXEC,
4875 "load_image <file> <address> "
4876 "['bin'|'ihex'|'elf'|'s19'] [min_address] [max_length]");
4877 register_command(cmd_ctx, NULL, "dump_image",
4878 handle_dump_image_command, COMMAND_EXEC,
4879 "dump_image <file> <address> <size>");
4880 register_command(cmd_ctx, NULL, "verify_image",
4881 handle_verify_image_command, COMMAND_EXEC,
4882 "verify_image <file> [offset] [type]");
4883 register_command(cmd_ctx, NULL, "test_image",
4884 handle_test_image_command, COMMAND_EXEC,
4885 "test_image <file> [offset] [type]");